@osfactory/otel-hook 0.7.0 → 0.9.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.
package/dist/cli.js CHANGED
@@ -835,7 +835,9 @@ Delivery deduplication (at most once per callback, across process restarts):
835
835
  deduplicate only against --callback-id
836
836
 
837
837
  Exporter and runtime policy (never identity):
838
- --config-file <path> JSON configuration patch
838
+ --config-file <path> JSON configuration patch; "exporter.destinations"
839
+ sends to several OTLP endpoints in parallel, each
840
+ with its own spool (header values may be "env:NAME")
839
841
  --endpoint <url> OTLP HTTP/protobuf traces endpoint
840
842
  --protocol <p> http/protobuf | http/json | none
841
843
  --service-name <name> --service-namespace <ns>
@@ -876,7 +878,9 @@ Registration lifecycle (setup / diagnose / uninstall):
876
878
  documented path; required for a provider whose
877
879
  planner is verified but whose path is not
878
880
  --hook-command <cmd> command to register
879
- (default "otel-hook run --provider <id>")
881
+ (default "otel-hook run --provider <id>"); add
882
+ --config-file <path> to it to use a config file,
883
+ e.g. one with several export destinations
880
884
  --event <name> register only these events; repeatable
881
885
  --matcher <m> matcher for a newly created hook group
882
886
  --timeout-seconds <n> per-hook timeout written into the config
@@ -1154,6 +1158,35 @@ var errorInfoFromThrown = (thrown, input) => {
1154
1158
  });
1155
1159
  };
1156
1160
 
1161
+ // src/config/otlp-endpoint.ts
1162
+ var OTLP_ENDPOINT_VARIABLES = Object.freeze({
1163
+ generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
1164
+ traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
1165
+ logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
1166
+ });
1167
+ var OTLP_TRACES_PATH = "/v1/traces";
1168
+ var OTLP_LOGS_PATH = "/v1/logs";
1169
+ var withoutTrailingSlashes = (value) => {
1170
+ let end = value.length;
1171
+ while (end > 0 && value.charCodeAt(end - 1) === 47) {
1172
+ end -= 1;
1173
+ }
1174
+ return value.slice(0, end);
1175
+ };
1176
+ var otlpSignalEndpointFromBase = (base, signal) => {
1177
+ const trimmed = withoutTrailingSlashes(base);
1178
+ if (trimmed.endsWith(OTLP_TRACES_PATH)) {
1179
+ return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${OTLP_LOGS_PATH}`;
1180
+ }
1181
+ return `${trimmed}${signal === "traces" ? OTLP_TRACES_PATH : OTLP_LOGS_PATH}`;
1182
+ };
1183
+
1184
+ // src/config/header-value.ts
1185
+ var isUnsafeHeaderValue = (value) => [...value].some((char) => {
1186
+ const code = char.codePointAt(0) ?? 0;
1187
+ return code < 32 && code !== 9 || code === 127 || code > 255;
1188
+ });
1189
+
1157
1190
  // src/config/otlp-headers.ts
1158
1191
  var MAX_OTLP_HEADERS = 32;
1159
1192
  var OTLP_HEADER_VARIABLES = Object.freeze({
@@ -1162,10 +1195,6 @@ var OTLP_HEADER_VARIABLES = Object.freeze({
1162
1195
  logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
1163
1196
  });
1164
1197
  var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1165
- var isUnsafeHeaderValue = (value) => [...value].some((char) => {
1166
- const code = char.codePointAt(0) ?? 0;
1167
- return code < 32 && code !== 9 || code === 127 || code > 255;
1168
- });
1169
1198
  var decode = (raw) => {
1170
1199
  try {
1171
1200
  return decodeURIComponent(raw);
@@ -1278,7 +1307,13 @@ var describeOtlpHeaderNames = (...sources) => unionOtlpHeaderNames(...sources.ma
1278
1307
  // src/config/environment.ts
1279
1308
  var ENVIRONMENT_VARIABLES = Object.freeze({
1280
1309
  exporterEnabled: "OTEL_HOOK_ENABLED",
1310
+ /** Full traces URL; otel-hook's own variable, above the standard ones. */
1281
1311
  exporterEndpoint: "OTEL_HOOK_EXPORTER_ENDPOINT",
1312
+ /**
1313
+ * Standard base URL: `/v1/traces` and `/v1/logs` are appended per signal. A
1314
+ * value already ending in `/v1/traces` is the legacy full traces URL and is
1315
+ * used as-is (see `otlpSignalEndpointFromBase`).
1316
+ */
1282
1317
  otlpEndpoint: "OTEL_EXPORTER_OTLP_ENDPOINT",
1283
1318
  exporterProtocol: "OTEL_HOOK_EXPORTER_PROTOCOL",
1284
1319
  exporterTimeoutMillis: "OTEL_HOOK_EXPORTER_TIMEOUT_MS",
@@ -1352,7 +1387,10 @@ var parseEnvironmentConfig = (env) => {
1352
1387
  return trimmed === "" ? void 0 : trimmed;
1353
1388
  };
1354
1389
  const exporterEnabled = readBoolean(ENVIRONMENT_VARIABLES.exporterEnabled);
1355
- const endpoint = readString(ENVIRONMENT_VARIABLES.exporterEndpoint) ?? readString(ENVIRONMENT_VARIABLES.otlpEndpoint);
1390
+ const hookEndpoint = readString(ENVIRONMENT_VARIABLES.exporterEndpoint);
1391
+ const otlpTracesEndpoint = readString(OTLP_ENDPOINT_VARIABLES.traces);
1392
+ const otlpBaseEndpoint = readString(ENVIRONMENT_VARIABLES.otlpEndpoint);
1393
+ const endpoint = hookEndpoint ?? otlpTracesEndpoint ?? (otlpBaseEndpoint === void 0 ? void 0 : otlpSignalEndpointFromBase(otlpBaseEndpoint, "traces"));
1356
1394
  const timeoutMillis = readInteger(ENVIRONMENT_VARIABLES.exporterTimeoutMillis);
1357
1395
  const resourceRaw = readString(ENVIRONMENT_VARIABLES.resourceAttributes);
1358
1396
  const resource = resourceRaw === void 0 ? void 0 : parseResourceAttributesValue(resourceRaw);
@@ -1438,7 +1476,7 @@ var parseEnvironmentConfig = (env) => {
1438
1476
  const maxEventsPerInvocation = readInteger(ENVIRONMENT_VARIABLES.maxEventsPerInvocation);
1439
1477
  const logsEnabled = readBoolean(ENVIRONMENT_VARIABLES.logsEnabled);
1440
1478
  const logsIncludeContent = readBoolean(ENVIRONMENT_VARIABLES.logsIncludeContent);
1441
- const logsEndpoint = readString(ENVIRONMENT_VARIABLES.logsEndpoint) ?? readString(ENVIRONMENT_VARIABLES.otlpLogsEndpoint);
1479
+ const logsEndpoint = readString(ENVIRONMENT_VARIABLES.logsEndpoint) ?? readString(ENVIRONMENT_VARIABLES.otlpLogsEndpoint) ?? (hookEndpoint === void 0 && otlpTracesEndpoint !== void 0 && otlpBaseEndpoint !== void 0 ? otlpSignalEndpointFromBase(otlpBaseEndpoint, "logs") : void 0);
1442
1480
  const logs = {
1443
1481
  ...logsEnabled === void 0 ? {} : { enabled: logsEnabled },
1444
1482
  ...logsEndpoint === void 0 ? {} : { endpoint: logsEndpoint },
@@ -1484,40 +1522,237 @@ var parseEnvironmentConfig = (env) => {
1484
1522
  };
1485
1523
 
1486
1524
  // src/config/resolve.ts
1487
- import { z as z7 } from "zod";
1525
+ import { z as z8 } from "zod";
1488
1526
 
1489
- // src/config/schema.ts
1527
+ // src/config/destinations.ts
1490
1528
  import { z as z6 } from "zod";
1491
- var logsPolicySchema = z6.strictObject({
1492
- enabled: z6.boolean(),
1529
+ var DEFAULT_DESTINATION_NAME = "default";
1530
+ var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
1531
+ var MAX_EXPORT_DESTINATIONS = 16;
1532
+ var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
1533
+ var HEADER_ENV_REFERENCE_PREFIX = "env:";
1534
+ var HEADER_NAME_PATTERN2 = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
1535
+ var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
1536
+ var MAX_HEADER_VALUE_LENGTH = 8192;
1537
+ var exportSignalSchema = z6.enum(["traces", "logs"]);
1538
+ var headerValueSchema = z6.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1539
+ (value) => !isUnsafeHeaderValue(value),
1540
+ "header values may not contain line breaks, control characters, or characters beyond Latin-1"
1541
+ ).refine(
1542
+ (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
1543
+ "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
1544
+ );
1545
+ var endpointSchema = z6.string().url().max(2048);
1546
+ var exportDestinationSchema = z6.strictObject({
1547
+ /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
1548
+ name: z6.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
1549
+ /** Default true. A disabled destination is neither sent to nor drained. */
1550
+ enabled: z6.boolean().optional(),
1551
+ /**
1552
+ * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
1553
+ * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
1554
+ */
1555
+ endpoint: endpointSchema.optional(),
1556
+ /** Per-signal override of `endpoint` for traces. */
1557
+ tracesEndpoint: endpointSchema.optional(),
1558
+ /** Per-signal override of the derived logs URL. */
1559
+ logsEndpoint: endpointSchema.optional(),
1560
+ /** Defaults to `exporter.protocol`. */
1561
+ protocol: z6.enum(["http/protobuf", "http/json", "none"]).optional(),
1562
+ /**
1563
+ * Header name to value. A value of the form `env:NAME` is read from that
1564
+ * environment variable at send time, so a credential never has to be written
1565
+ * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
1566
+ */
1567
+ headers: z6.record(z6.string().regex(HEADER_NAME_PATTERN2, "not a valid header name"), headerValueSchema).refine(
1568
+ (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
1569
+ `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
1570
+ ).optional(),
1571
+ /**
1572
+ * Which signals this destination receives. Default: both. The logs signal is
1573
+ * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
1574
+ * second stream leaving the host.
1575
+ */
1576
+ signals: z6.array(exportSignalSchema).min(1).max(2).readonly().optional()
1577
+ }).refine(
1578
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
1579
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
1580
+ );
1581
+ var exportDestinationsSchema = z6.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
1582
+ const seen = /* @__PURE__ */ new Set();
1583
+ destinations.forEach((destination, index) => {
1584
+ if (destination.name === DEFAULT_DESTINATION_NAME) {
1585
+ context.addIssue({
1586
+ code: "custom",
1587
+ path: [index, "name"],
1588
+ message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
1589
+ });
1590
+ }
1591
+ if (seen.has(destination.name)) {
1592
+ context.addIssue({
1593
+ code: "custom",
1594
+ path: [index, "name"],
1595
+ message: `duplicate destination name "${destination.name}"`
1596
+ });
1597
+ }
1598
+ seen.add(destination.name);
1599
+ });
1600
+ });
1601
+ var spoolPolicySchema = z6.strictObject({
1602
+ /** Total bytes of queued batches. Default 16 MiB. */
1603
+ maxBytes: z6.number().int().min(1024).max(1073741824),
1604
+ /** A batch older than this is dropped instead of sent. Default 72 hours. */
1605
+ maxAgeMillis: z6.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
1606
+ /** Number of queued batches. Default 500. */
1607
+ maxBatches: z6.number().int().min(1).max(65536)
1608
+ });
1609
+ var DEFAULT_SPOOL_POLICY = Object.freeze({
1610
+ maxBytes: 16 * 1024 * 1024,
1611
+ maxAgeMillis: 72 * 60 * 60 * 1e3,
1612
+ maxBatches: 500
1613
+ });
1614
+ var effectiveSpoolPolicy = (exporter) => ({
1615
+ maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,
1616
+ maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
1617
+ maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
1618
+ });
1619
+ var legacyDestination = (exporter) => ({
1620
+ name: DEFAULT_DESTINATION_NAME,
1621
+ source: "exporter",
1622
+ protocol: exporter.protocol,
1623
+ ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
1624
+ ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
1625
+ signals: { traces: true, logs: exporter.logs.enabled },
1626
+ headers: {}
1627
+ });
1628
+ var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
1629
+ var resolveExportDestinations = (exporter) => {
1630
+ if (!hasConfiguredDestinations(exporter)) {
1631
+ return [legacyDestination(exporter)];
1632
+ }
1633
+ const resolved = [];
1634
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
1635
+ resolved.push(legacyDestination(exporter));
1636
+ }
1637
+ for (const destination of exporter.destinations ?? []) {
1638
+ if (destination.enabled === false) {
1639
+ continue;
1640
+ }
1641
+ const signals = destination.signals ?? exportSignalSchema.options;
1642
+ resolved.push({
1643
+ name: destination.name,
1644
+ source: "destinations",
1645
+ protocol: destination.protocol ?? exporter.protocol,
1646
+ ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
1647
+ ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
1648
+ ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
1649
+ signals: {
1650
+ traces: signals.includes("traces"),
1651
+ logs: exporter.logs.enabled && signals.includes("logs")
1652
+ },
1653
+ headers: { ...destination.headers ?? {} }
1654
+ });
1655
+ }
1656
+ return resolved;
1657
+ };
1658
+ var parseHeaderValueReference = (value) => value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ? { kind: "env", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) } : { kind: "literal" };
1659
+ var resolveDestinationHeaders = (headers, environment) => {
1660
+ const values = {};
1661
+ const missing = [];
1662
+ for (const [name, value] of Object.entries(headers)) {
1663
+ const reference = parseHeaderValueReference(value);
1664
+ if (reference.kind === "literal") {
1665
+ values[name] = value;
1666
+ continue;
1667
+ }
1668
+ const resolved = environment?.[reference.variable];
1669
+ if (resolved === void 0 || resolved === "") {
1670
+ missing.push(reference.variable);
1671
+ continue;
1672
+ }
1673
+ values[name] = resolved;
1674
+ }
1675
+ return { values, missingVariables: [...new Set(missing)].sort() };
1676
+ };
1677
+ var endpointOrigin = (endpoint) => {
1678
+ if (endpoint === void 0) {
1679
+ return void 0;
1680
+ }
1681
+ try {
1682
+ return new URL(endpoint).origin;
1683
+ } catch {
1684
+ return "<unparsable>";
1685
+ }
1686
+ };
1687
+ var describeExportDestinations = (exporter) => {
1688
+ const describe = (destination, enabled2) => {
1689
+ const tracesOrigin = endpointOrigin(destination.tracesEndpoint ?? destination.endpoint);
1690
+ const logsOrigin = endpointOrigin(
1691
+ destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
1692
+ );
1693
+ const variables = Object.values(destination.headers).map(parseHeaderValueReference).flatMap((reference) => reference.kind === "env" ? [reference.variable] : []);
1694
+ return {
1695
+ name: destination.name,
1696
+ enabled: enabled2,
1697
+ protocol: destination.protocol,
1698
+ signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),
1699
+ ...tracesOrigin === void 0 || !destination.signals.traces ? {} : { tracesEndpointOrigin: tracesOrigin },
1700
+ ...logsOrigin === void 0 || !destination.signals.logs ? {} : { logsEndpointOrigin: logsOrigin },
1701
+ headerNames: destination.source === "exporter" ? [...exporter.headerNames].sort() : Object.keys(destination.headers).sort(),
1702
+ headerVariables: [...new Set(variables)].sort()
1703
+ };
1704
+ };
1705
+ const enabled = resolveExportDestinations(exporter).map(
1706
+ (destination) => describe(destination, true)
1707
+ );
1708
+ const disabled = (exporter.destinations ?? []).filter((destination) => destination.enabled === false).map(
1709
+ (destination) => describe(
1710
+ {
1711
+ name: destination.name,
1712
+ source: "destinations",
1713
+ protocol: destination.protocol ?? exporter.protocol,
1714
+ ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
1715
+ signals: { traces: false, logs: false },
1716
+ headers: { ...destination.headers ?? {} }
1717
+ },
1718
+ false
1719
+ )
1720
+ );
1721
+ return [...enabled, ...disabled];
1722
+ };
1723
+
1724
+ // src/config/schema.ts
1725
+ import { z as z7 } from "zod";
1726
+ var logsPolicySchema = z7.strictObject({
1727
+ enabled: z7.boolean(),
1493
1728
  /**
1494
1729
  * Full URL for the logs signal.
1495
1730
  *
1496
1731
  * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
1497
1732
  * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
1498
1733
  */
1499
- endpoint: z6.string().url().max(2048).optional(),
1500
- includeContent: z6.boolean(),
1501
- maxBatchSize: z6.number().int().min(1).max(4096)
1734
+ endpoint: z7.string().url().max(2048).optional(),
1735
+ includeContent: z7.boolean(),
1736
+ maxBatchSize: z7.number().int().min(1).max(4096)
1502
1737
  });
1503
1738
  var DEFAULT_LOGS_POLICY = Object.freeze({
1504
1739
  enabled: false,
1505
1740
  includeContent: false,
1506
1741
  maxBatchSize: 128
1507
1742
  });
1508
- var exporterPolicySchema = z6.strictObject({
1509
- enabled: z6.boolean(),
1510
- protocol: z6.enum(["http/protobuf", "http/json", "none"]),
1511
- endpoint: z6.string().url().max(2048).optional(),
1743
+ var exporterPolicySchema = z7.strictObject({
1744
+ enabled: z7.boolean(),
1745
+ protocol: z7.enum(["http/protobuf", "http/json", "none"]),
1746
+ endpoint: z7.string().url().max(2048).optional(),
1512
1747
  /**
1513
1748
  * Header names only. Values are supplied separately at construction time and
1514
1749
  * are never part of a resolved-config snapshot, which is logged and exported.
1515
1750
  */
1516
- headerNames: z6.array(nonEmptyStringSchema).max(32).readonly(),
1517
- timeoutMillis: z6.number().int().min(1).max(6e5),
1518
- maxBatchSize: z6.number().int().min(1).max(4096),
1519
- maxQueueSize: z6.number().int().min(1).max(65536),
1520
- maxRetryAttempts: z6.number().int().min(0).max(10),
1751
+ headerNames: z7.array(nonEmptyStringSchema).max(32).readonly(),
1752
+ timeoutMillis: z7.number().int().min(1).max(6e5),
1753
+ maxBatchSize: z7.number().int().min(1).max(4096),
1754
+ maxQueueSize: z7.number().int().min(1).max(65536),
1755
+ maxRetryAttempts: z7.number().int().min(0).max(10),
1521
1756
  serviceName: nonEmptyStringSchema,
1522
1757
  serviceNamespace: nonEmptyStringSchema.optional(),
1523
1758
  /**
@@ -1534,32 +1769,52 @@ var exporterPolicySchema = z6.strictObject({
1534
1769
  * headers, timeout, protocol, service identity, and resource attributes above —
1535
1770
  * a second top-level section would invite two of each to drift apart.
1536
1771
  */
1537
- logs: logsPolicySchema
1772
+ logs: logsPolicySchema,
1773
+ /**
1774
+ * Additional OTLP destinations, each sent every batch in parallel.
1775
+ *
1776
+ * Absent (the default), the exporter has exactly one destination — the
1777
+ * single-endpoint settings above, named `default` — and behaves exactly as it
1778
+ * did before this list existed. See `destinations.ts`.
1779
+ *
1780
+ * Merged as one leaf: a higher layer that sets the list replaces it whole,
1781
+ * because "the union of two partial lists" has no answer an operator could
1782
+ * predict.
1783
+ */
1784
+ destinations: exportDestinationsSchema.optional(),
1785
+ /**
1786
+ * Per-destination retry spool bounds, each optional and merged per leaf; any
1787
+ * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
1788
+ */
1789
+ spool: spoolPolicySchema.partial().optional()
1538
1790
  });
1539
- var detectionPolicySchema = z6.strictObject({
1791
+ var detectionPolicySchema = z7.strictObject({
1540
1792
  /** Detections below this confidence resolve to the unknown provider. */
1541
1793
  minimumConfidence: detectionConfidenceSchema,
1542
1794
  /** When false, an ambiguous detection is an error rather than unknown. */
1543
- allowAmbiguousFallback: z6.boolean(),
1795
+ allowAmbiguousFallback: z7.boolean(),
1544
1796
  /** Optional allow-list of provider ids; empty means "any registered". */
1545
- allowedProviderIds: z6.array(nonEmptyStringSchema).max(32).readonly()
1797
+ allowedProviderIds: z7.array(nonEmptyStringSchema).max(32).readonly()
1546
1798
  });
1547
- var diagnosticsPolicySchema = z6.strictObject({
1548
- logLevel: z6.enum(["silent", "error", "warn", "info", "debug"]),
1799
+ var diagnosticsPolicySchema = z7.strictObject({
1800
+ logLevel: z7.enum(["silent", "error", "warn", "info", "debug"]),
1549
1801
  /** Emit `error.raised` events for contained failures. */
1550
- emitErrorEvents: z6.boolean()
1802
+ emitErrorEvents: z7.boolean()
1551
1803
  });
1552
- var otelHookConfigSchema = z6.strictObject({
1804
+ var otelHookConfigSchema = z7.strictObject({
1553
1805
  exporter: exporterPolicySchema,
1554
1806
  privacy: privacyPolicySchema,
1555
1807
  detection: detectionPolicySchema,
1556
1808
  diagnostics: diagnosticsPolicySchema
1557
1809
  });
1558
- var otelHookConfigPatchSchema = z6.strictObject({
1810
+ var otelHookConfigPatchSchema = z7.strictObject({
1559
1811
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
1560
1812
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
1561
1813
  // without also restating the endpoint and the batch size.
1562
- exporter: exporterPolicySchema.omit({ logs: true }).partial().extend({ logs: logsPolicySchema.partial().optional() }).optional(),
1814
+ exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
1815
+ logs: logsPolicySchema.partial().optional(),
1816
+ spool: spoolPolicySchema.partial().optional()
1817
+ }).optional(),
1563
1818
  privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
1564
1819
  detection: detectionPolicySchema.partial().optional(),
1565
1820
  diagnostics: diagnosticsPolicySchema.partial().optional()
@@ -1594,17 +1849,17 @@ var DEFAULT_CONFIG = Object.freeze({
1594
1849
 
1595
1850
  // src/config/resolve.ts
1596
1851
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
1597
- var configSourceSchema = z7.enum(CONFIG_SOURCE_PRECEDENCE);
1852
+ var configSourceSchema = z8.enum(CONFIG_SOURCE_PRECEDENCE);
1598
1853
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1599
- var mergeLeaf = (target, patch, source, provenance, path12) => {
1854
+ var mergeLeaf = (target, patch, source, provenance, path13) => {
1600
1855
  for (const [key, value] of Object.entries(patch)) {
1601
1856
  if (value === void 0) {
1602
1857
  continue;
1603
1858
  }
1604
- const childPath = path12 === "" ? key : `${path12}.${key}`;
1859
+ const childPath = path13 === "" ? key : `${path13}.${key}`;
1605
1860
  const existing = target[key];
1606
- if (isPlainObject(value) && isPlainObject(existing)) {
1607
- const child = { ...existing };
1861
+ if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
1862
+ const child = { ...existing ?? {} };
1608
1863
  mergeLeaf(child, value, source, provenance, childPath);
1609
1864
  target[key] = child;
1610
1865
  continue;
@@ -1615,14 +1870,14 @@ var mergeLeaf = (target, patch, source, provenance, path12) => {
1615
1870
  };
1616
1871
  var initialProvenance = (config) => {
1617
1872
  const provenance = {};
1618
- const walk = (value, path12) => {
1873
+ const walk = (value, path13) => {
1619
1874
  if (isPlainObject(value)) {
1620
1875
  for (const [key, child] of Object.entries(value)) {
1621
- walk(child, path12 === "" ? key : `${path12}.${key}`);
1876
+ walk(child, path13 === "" ? key : `${path13}.${key}`);
1622
1877
  }
1623
1878
  return;
1624
1879
  }
1625
- provenance[path12] = "defaults";
1880
+ provenance[path13] = "defaults";
1626
1881
  };
1627
1882
  walk(config, "");
1628
1883
  return provenance;
@@ -1676,10 +1931,27 @@ var resolveConfig = (layers = []) => {
1676
1931
  if (parsed.data.privacy.contentMode === "raw" && !parsed.data.privacy.allowRawContent) {
1677
1932
  notes.push("privacy.contentMode=raw will be downgraded to omit: allowRawContent is false");
1678
1933
  }
1679
- if (parsed.data.exporter.enabled && parsed.data.exporter.protocol !== "none" && parsed.data.exporter.endpoint === void 0) {
1934
+ const withDestinations = hasConfiguredDestinations(parsed.data.exporter);
1935
+ if (parsed.data.exporter.enabled && parsed.data.exporter.protocol !== "none" && parsed.data.exporter.endpoint === void 0 && !withDestinations) {
1680
1936
  notes.push("exporter.enabled is true but no endpoint is configured");
1681
1937
  }
1682
- if (parsed.data.exporter.logs.enabled && parsed.data.exporter.logs.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
1938
+ if (withDestinations) {
1939
+ const enabled = (parsed.data.exporter.destinations ?? []).filter(
1940
+ (destination) => destination.enabled !== false
1941
+ );
1942
+ if (enabled.length === 0 && parsed.data.exporter.endpoint === void 0) {
1943
+ notes.push("exporter.destinations is set but every destination is disabled");
1944
+ }
1945
+ if (!parsed.data.exporter.logs.enabled) {
1946
+ const askingForLogs = enabled.filter((destination) => destination.signals?.includes("logs") === true).map((destination) => destination.name);
1947
+ if (askingForLogs.length > 0) {
1948
+ notes.push(
1949
+ `destination(s) ${askingForLogs.join(", ")} list the logs signal but exporter.logs.enabled is false, so only traces are sent`
1950
+ );
1951
+ }
1952
+ }
1953
+ }
1954
+ if (!withDestinations && parsed.data.exporter.logs.enabled && parsed.data.exporter.logs.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
1683
1955
  notes.push(
1684
1956
  "exporter.logs.enabled is true but neither a logs endpoint nor a trace endpoint to derive one from is configured"
1685
1957
  );
@@ -1691,6 +1963,35 @@ var resolveConfig = (layers = []) => {
1691
1963
  }
1692
1964
  return { status: "ok", config: parsed.data, provenance, notes };
1693
1965
  };
1966
+ var describeDestinationAttributes = (config) => {
1967
+ const attributes = {};
1968
+ if (config.exporter.spool !== void 0 || hasConfiguredDestinations(config.exporter)) {
1969
+ const spool = effectiveSpoolPolicy(config.exporter);
1970
+ attributes["exporter.spool_max_bytes"] = spool.maxBytes;
1971
+ attributes["exporter.spool_max_age_millis"] = spool.maxAgeMillis;
1972
+ attributes["exporter.spool_max_batches"] = spool.maxBatches;
1973
+ }
1974
+ if (!hasConfiguredDestinations(config.exporter)) {
1975
+ return attributes;
1976
+ }
1977
+ const destinations = describeExportDestinations(config.exporter);
1978
+ attributes["exporter.destination_names"] = destinations.map((destination) => destination.name);
1979
+ for (const destination of destinations) {
1980
+ const prefix = `exporter.destination.${destination.name}`;
1981
+ attributes[`${prefix}.enabled`] = destination.enabled;
1982
+ attributes[`${prefix}.protocol`] = destination.protocol;
1983
+ attributes[`${prefix}.signals`] = [...destination.signals];
1984
+ if (destination.tracesEndpointOrigin !== void 0) {
1985
+ attributes[`${prefix}.traces_endpoint_origin`] = destination.tracesEndpointOrigin;
1986
+ }
1987
+ if (destination.logsEndpointOrigin !== void 0) {
1988
+ attributes[`${prefix}.logs_endpoint_origin`] = destination.logsEndpointOrigin;
1989
+ }
1990
+ attributes[`${prefix}.header_names`] = [...destination.headerNames];
1991
+ attributes[`${prefix}.header_variables`] = [...destination.headerVariables];
1992
+ }
1993
+ return attributes;
1994
+ };
1694
1995
  var describeResolvedConfig = (config) => {
1695
1996
  const originOf = (endpoint) => {
1696
1997
  if (endpoint === void 0) {
@@ -1702,12 +2003,12 @@ var describeResolvedConfig = (config) => {
1702
2003
  return "<unparsable>";
1703
2004
  }
1704
2005
  };
1705
- const endpointOrigin = originOf(config.exporter.endpoint);
2006
+ const endpointOrigin2 = originOf(config.exporter.endpoint);
1706
2007
  const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);
1707
2008
  return {
1708
2009
  "exporter.enabled": config.exporter.enabled,
1709
2010
  "exporter.protocol": config.exporter.protocol,
1710
- ...endpointOrigin === void 0 ? {} : { "exporter.endpoint_origin": endpointOrigin },
2011
+ ...endpointOrigin2 === void 0 ? {} : { "exporter.endpoint_origin": endpointOrigin2 },
1711
2012
  "exporter.logs_enabled": config.exporter.logs.enabled,
1712
2013
  "exporter.logs_include_content": config.exporter.logs.includeContent,
1713
2014
  "exporter.logs_max_batch_size": config.exporter.logs.maxBatchSize,
@@ -1719,6 +2020,7 @@ var describeResolvedConfig = (config) => {
1719
2020
  "exporter.resource_attribute_names": [
1720
2021
  ...describeResourceAttributeNames(config.exporter.resourceAttributes)
1721
2022
  ],
2023
+ ...describeDestinationAttributes(config),
1722
2024
  "exporter.timeout_millis": config.exporter.timeoutMillis,
1723
2025
  "exporter.max_batch_size": config.exporter.maxBatchSize,
1724
2026
  "exporter.service_name": config.exporter.serviceName,
@@ -1737,18 +2039,18 @@ var describeResolvedConfig = (config) => {
1737
2039
  };
1738
2040
 
1739
2041
  // src/runtime/ports.ts
1740
- import { z as z9 } from "zod";
2042
+ import { z as z10 } from "zod";
1741
2043
 
1742
2044
  // src/model/usage.ts
1743
- import { z as z8 } from "zod";
1744
- var usageTemporalitySchema = z8.enum(["delta", "cumulative"]);
1745
- var cacheCreationAccountingSchema = z8.enum([
2045
+ import { z as z9 } from "zod";
2046
+ var usageTemporalitySchema = z9.enum(["delta", "cumulative"]);
2047
+ var cacheCreationAccountingSchema = z9.enum([
1746
2048
  "included-in-input",
1747
2049
  "disjoint-from-input",
1748
2050
  "not-reported"
1749
2051
  ]);
1750
- var providerTotalAgreementSchema = z8.enum(["unreported", "agrees", "disagrees"]);
1751
- var usageReportSchema = z8.strictObject({
2052
+ var providerTotalAgreementSchema = z9.enum(["unreported", "agrees", "disagrees"]);
2053
+ var usageReportSchema = z9.strictObject({
1752
2054
  temporality: usageTemporalitySchema,
1753
2055
  /** Inclusive input tokens. */
1754
2056
  inputTokens: tokenCountSchema.optional(),
@@ -1765,7 +2067,7 @@ var usageReportSchema = z8.strictObject({
1765
2067
  /** Total exactly as the provider reported it, if it reported one. */
1766
2068
  providerTotalTokens: tokenCountSchema.optional()
1767
2069
  });
1768
- var canonicalUsageSchema = z8.strictObject({
2070
+ var canonicalUsageSchema = z9.strictObject({
1769
2071
  temporality: usageTemporalitySchema,
1770
2072
  inputTokens: tokenCountSchema,
1771
2073
  cachedInputTokens: tokenCountSchema,
@@ -1966,14 +2268,14 @@ var toReport = (usage) => ({
1966
2268
  });
1967
2269
 
1968
2270
  // src/runtime/ports.ts
1969
- var appliedDeliverySchema = z9.strictObject({
1970
- callbackId: z9.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
2271
+ var appliedDeliverySchema = z10.strictObject({
2272
+ callbackId: z10.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
1971
2273
  /** How many of that delivery's observations are folded in, counted from one. */
1972
- applications: z9.number().int().min(1).max(4096)
2274
+ applications: z10.number().int().min(1).max(4096)
1973
2275
  });
1974
- var stateValueSchema = z9.discriminatedUnion("kind", [
1975
- z9.strictObject({
1976
- kind: z9.literal("usage-cumulative"),
2276
+ var stateValueSchema = z10.discriminatedUnion("kind", [
2277
+ z10.strictObject({
2278
+ kind: z10.literal("usage-cumulative"),
1977
2279
  usage: canonicalUsageSchema,
1978
2280
  /**
1979
2281
  * Optional: absent on every record written before this field existed, which
@@ -1982,22 +2284,22 @@ var stateValueSchema = z9.discriminatedUnion("kind", [
1982
2284
  */
1983
2285
  appliedDelivery: appliedDeliverySchema.optional()
1984
2286
  }),
1985
- z9.strictObject({
1986
- kind: z9.literal("sequence"),
2287
+ z10.strictObject({
2288
+ kind: z10.literal("sequence"),
1987
2289
  next: sequenceNumberSchema
1988
2290
  }),
1989
- z9.strictObject({
1990
- kind: z9.literal("attributes"),
2291
+ z10.strictObject({
2292
+ kind: z10.literal("attributes"),
1991
2293
  attributes: attributesSchema
1992
2294
  })
1993
2295
  ]);
1994
- var stateRecordSchema = z9.strictObject({
2296
+ var stateRecordSchema = z10.strictObject({
1995
2297
  /** Incremented on each write; lets callers detect lost updates. */
1996
- revision: z9.number().int().min(0),
2298
+ revision: z10.number().int().min(0),
1997
2299
  updatedAt: epochMillisSchema,
1998
2300
  value: stateValueSchema
1999
2301
  });
2000
- var logLevelSchema = z9.enum(["silent", "error", "warn", "info", "debug"]);
2302
+ var logLevelSchema = z10.enum(["silent", "error", "warn", "info", "debug"]);
2001
2303
  var LOG_LEVEL_RANK = Object.freeze({
2002
2304
  silent: 0,
2003
2305
  error: 1,
@@ -2194,6 +2496,10 @@ var createCliLogger = (io, level) => createStderrLogger({
2194
2496
  });
2195
2497
  var readIdentityFile = readJsonFile;
2196
2498
 
2499
+ // src/cli/doctor.ts
2500
+ import { readdir as readdir3 } from "fs/promises";
2501
+ import * as path4 from "path";
2502
+
2197
2503
  // src/diagnostics/health.ts
2198
2504
  var createHealthTracker = (subsystem, options = {}) => {
2199
2505
  const unhealthyThreshold = options.unhealthyAfterConsecutiveFailures ?? 3;
@@ -2227,7 +2533,8 @@ var createHealthTracker = (subsystem, options = {}) => {
2227
2533
  consecutiveFailures,
2228
2534
  ...lastSuccessAt === void 0 ? {} : { lastSuccessAt },
2229
2535
  ...lastFailureAt === void 0 ? {} : { lastFailureAt },
2230
- ...lastErrorCode === void 0 ? {} : { lastErrorCode }
2536
+ ...lastErrorCode === void 0 ? {} : { lastErrorCode },
2537
+ ...options.destination === void 0 ? {} : { destination: options.destination }
2231
2538
  })
2232
2539
  };
2233
2540
  };
@@ -2237,15 +2544,15 @@ var summarizeHealth = (snapshots) => ({
2237
2544
  });
2238
2545
 
2239
2546
  // src/model/version.ts
2240
- import { z as z10 } from "zod";
2547
+ import { z as z11 } from "zod";
2241
2548
  var CANONICAL_SCHEMA_VERSION = 1;
2242
- var canonicalSchemaVersionSchema = z10.literal(CANONICAL_SCHEMA_VERSION);
2549
+ var canonicalSchemaVersionSchema = z11.literal(CANONICAL_SCHEMA_VERSION);
2243
2550
 
2244
2551
  // src/privacy/service.ts
2245
2552
  import { createHash } from "crypto";
2246
2553
 
2247
2554
  // src/model/extensions.ts
2248
- import { z as z11 } from "zod";
2555
+ import { z as z12 } from "zod";
2249
2556
  var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
2250
2557
  var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
2251
2558
  "otelhook",
@@ -2256,7 +2563,7 @@ var MAX_EXTENSION_ENTRIES = 64;
2256
2563
  var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
2257
2564
  var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
2258
2565
  var isValidExtensionKey = (key) => EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);
2259
- var extensionsSchema = z11.record(z11.string(), attributeValueSchema).check((ctx) => {
2566
+ var extensionsSchema = z12.record(z12.string(), attributeValueSchema).check((ctx) => {
2260
2567
  const keys = Object.keys(ctx.value);
2261
2568
  if (keys.length > MAX_EXTENSION_ENTRIES) {
2262
2569
  ctx.issues.push({
@@ -2506,11 +2813,11 @@ var createPrivacyService = (policyInput) => {
2506
2813
  };
2507
2814
  const flattenToAttributes = (value, prefix) => {
2508
2815
  const attributes = {};
2509
- const walk = (current, path12) => {
2816
+ const walk = (current, path13) => {
2510
2817
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
2511
2818
  const primitive = toAttributePrimitive(current);
2512
2819
  if (primitive !== void 0) {
2513
- attributes[path12] = primitive;
2820
+ attributes[path13] = primitive;
2514
2821
  }
2515
2822
  return;
2516
2823
  }
@@ -2529,16 +2836,16 @@ var createPrivacyService = (policyInput) => {
2529
2836
  primitives.push(entryPrimitive);
2530
2837
  }
2531
2838
  if (uniform) {
2532
- attributes[path12] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
2839
+ attributes[path13] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
2533
2840
  return;
2534
2841
  }
2535
2842
  for (const [index, entry] of current.entries()) {
2536
- walk(entry, `${path12}.${index}`);
2843
+ walk(entry, `${path13}.${index}`);
2537
2844
  }
2538
2845
  return;
2539
2846
  }
2540
2847
  for (const [key, entry] of Object.entries(current)) {
2541
- walk(entry, path12 === "" ? key : `${path12}.${key}`);
2848
+ walk(entry, path13 === "" ? key : `${path13}.${key}`);
2542
2849
  }
2543
2850
  };
2544
2851
  walk(value, prefix);
@@ -2631,15 +2938,15 @@ var createPrivacyService = (policyInput) => {
2631
2938
  };
2632
2939
 
2633
2940
  // src/model/identity.ts
2634
- import { z as z12 } from "zod";
2635
- var workspaceKeySourceSchema = z12.enum([
2941
+ import { z as z13 } from "zod";
2942
+ var workspaceKeySourceSchema = z13.enum([
2636
2943
  "git-remote",
2637
2944
  "git-root",
2638
2945
  "working-directory",
2639
2946
  "explicit",
2640
2947
  "unknown"
2641
2948
  ]);
2642
- var workspaceIdentitySchema = z12.strictObject({
2949
+ var workspaceIdentitySchema = z13.strictObject({
2643
2950
  workspaceId: workspaceIdSchema,
2644
2951
  keySource: workspaceKeySourceSchema,
2645
2952
  /** Repository name only; never an owner path or URL with credentials. */
@@ -2653,7 +2960,7 @@ var unknownWorkspaceIdentity = () => workspaceIdentitySchema.parse({
2653
2960
  workspaceId: UNKNOWN_WORKSPACE_ID,
2654
2961
  keySource: "unknown"
2655
2962
  });
2656
- var sourceProvenanceSchema = z12.strictObject({
2963
+ var sourceProvenanceSchema = z13.strictObject({
2657
2964
  providerId: resolvedProviderIdSchema,
2658
2965
  providerVersion: nonEmptyStringSchema.optional(),
2659
2966
  adapterId: nonEmptyStringSchema,
@@ -2664,7 +2971,7 @@ var sourceProvenanceSchema = z12.strictObject({
2664
2971
  transport: sourceTransportSchema
2665
2972
  }).readonly();
2666
2973
  var consumerAttributesSchema = attributesSchema.readonly();
2667
- var invocationIdentitySchema = z12.strictObject({
2974
+ var invocationIdentitySchema = z13.strictObject({
2668
2975
  invocationId: invocationIdSchema,
2669
2976
  sessionId: sessionIdSchema,
2670
2977
  /** Set when this invocation runs beneath another agent invocation. */
@@ -2678,7 +2985,7 @@ var invocationIdentitySchema = z12.strictObject({
2678
2985
  startedAt: epochMillisSchema,
2679
2986
  consumerAttributes: consumerAttributesSchema
2680
2987
  }).readonly();
2681
- var identityClaimFieldsSchema = z12.strictObject({
2988
+ var identityClaimFieldsSchema = z13.strictObject({
2682
2989
  invocationId: invocationIdSchema.optional(),
2683
2990
  sessionId: sessionIdSchema.optional(),
2684
2991
  parentInvocationId: invocationIdSchema.optional(),
@@ -2687,7 +2994,7 @@ var identityClaimFieldsSchema = z12.strictObject({
2687
2994
  workspace: workspaceIdentitySchema.optional(),
2688
2995
  startedAt: epochMillisSchema.optional()
2689
2996
  });
2690
- var identityClaimSchema = z12.strictObject({
2997
+ var identityClaimSchema = z13.strictObject({
2691
2998
  /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
2692
2999
  source: nonEmptyStringSchema,
2693
3000
  confidence: detectionConfidenceSchema,
@@ -2855,14 +3162,14 @@ var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
2855
3162
  };
2856
3163
 
2857
3164
  // src/providers/adapter.ts
2858
- import { z as z16 } from "zod";
3165
+ import { z as z17 } from "zod";
2859
3166
 
2860
3167
  // src/model/events.ts
2861
- import { z as z15 } from "zod";
3168
+ import { z as z16 } from "zod";
2862
3169
 
2863
3170
  // src/model/content.ts
2864
- import { z as z13 } from "zod";
2865
- var contentKindSchema = z13.enum([
3171
+ import { z as z14 } from "zod";
3172
+ var contentKindSchema = z14.enum([
2866
3173
  "prompt",
2867
3174
  "response",
2868
3175
  "reasoning",
@@ -2872,47 +3179,47 @@ var contentKindSchema = z13.enum([
2872
3179
  "system-instruction",
2873
3180
  "attachment"
2874
3181
  ]);
2875
- var contentRoleSchema = z13.enum(["user", "assistant", "system", "tool", "unknown"]);
2876
- var contentDisclosureSchema = z13.enum(["omitted", "masked", "redacted", "raw"]);
3182
+ var contentRoleSchema = z14.enum(["user", "assistant", "system", "tool", "unknown"]);
3183
+ var contentDisclosureSchema = z14.enum(["omitted", "masked", "redacted", "raw"]);
2877
3184
  var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
2878
- var contentFactSchema = z13.strictObject({
3185
+ var contentFactSchema = z14.strictObject({
2879
3186
  kind: contentKindSchema,
2880
3187
  role: contentRoleSchema.optional(),
2881
3188
  /** Unicode code point count of the original content. */
2882
- characterLength: z13.number().int().min(0),
3189
+ characterLength: z14.number().int().min(0),
2883
3190
  /** UTF-8 byte length of the original content. */
2884
- byteLength: z13.number().int().min(0),
3191
+ byteLength: z14.number().int().min(0),
2885
3192
  /** Stable salted digest of the original content. */
2886
- contentHash: z13.string().regex(CONTENT_HASH_PATTERN),
3193
+ contentHash: z14.string().regex(CONTENT_HASH_PATTERN),
2887
3194
  disclosure: contentDisclosureSchema,
2888
3195
  /** Disclosed text, bounded by the privacy policy. Absent when omitted. */
2889
- text: z13.string().optional(),
3196
+ text: z14.string().optional(),
2890
3197
  /** True when `text` was cut short by the configured string bound. */
2891
- truncated: z13.boolean(),
3198
+ truncated: z14.boolean(),
2892
3199
  /** Number of secret-looking spans replaced while producing `text`. */
2893
- secretsRedacted: z13.number().int().min(0),
3200
+ secretsRedacted: z14.number().int().min(0),
2894
3201
  /** Optional non-sensitive label, e.g. a MIME type or tool name. */
2895
3202
  label: nonEmptyStringSchema.optional()
2896
3203
  });
2897
- var contentFactsSchema = z13.array(contentFactSchema).max(64);
3204
+ var contentFactsSchema = z14.array(contentFactSchema).max(64);
2898
3205
  var isContentFactConsistent = (fact) => fact.disclosure === "omitted" ? fact.text === void 0 : fact.text !== void 0;
2899
3206
  var isUnavailableContentFact = (fact) => fact.disclosure === "omitted" && fact.text === void 0 && fact.characterLength === 0 && fact.byteLength === 0;
2900
3207
 
2901
3208
  // src/model/target.ts
2902
- import { z as z14 } from "zod";
2903
- var targetSourceSchema = z14.enum(["tool-path", "shell-cwd", "session-cwd"]);
3209
+ import { z as z15 } from "zod";
3210
+ var targetSourceSchema = z15.enum(["tool-path", "shell-cwd", "session-cwd"]);
2904
3211
  var MAX_TARGET_HINT_PATHS = 8;
2905
3212
  var MAX_TARGET_PATH_LENGTH = 4096;
2906
- var localPathSchema = z14.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
2907
- var targetHintSchema = z14.strictObject({
3213
+ var localPathSchema = z15.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
3214
+ var targetHintSchema = z15.strictObject({
2908
3215
  source: targetSourceSchema,
2909
- paths: z14.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
3216
+ paths: z15.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
2910
3217
  /** Absolute directory that relative `paths` resolve against. */
2911
3218
  baseDirectory: localPathSchema.optional()
2912
3219
  }).readonly();
2913
3220
  var sessionCwdHint = (cwd) => cwd === void 0 || cwd.length === 0 ? void 0 : { source: "session-cwd", paths: [cwd] };
2914
- var worktreeKindSchema = z14.enum(["main", "linked"]);
2915
- var workspaceTargetSchema = z14.strictObject({
3221
+ var worktreeKindSchema = z15.enum(["main", "linked"]);
3222
+ var workspaceTargetSchema = z15.strictObject({
2916
3223
  workspaceId: workspaceIdSchema,
2917
3224
  /** Branch checked out in that worktree; absent on a detached HEAD. */
2918
3225
  vcsBranchName: nonEmptyStringSchema.optional(),
@@ -2922,22 +3229,22 @@ var workspaceTargetSchema = z14.strictObject({
2922
3229
  worktreeKind: worktreeKindSchema.optional()
2923
3230
  }).readonly();
2924
3231
  var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
2925
- var subagentIdSchema = z14.string().regex(SUBAGENT_ID_PATTERN);
3232
+ var subagentIdSchema = z15.string().regex(SUBAGENT_ID_PATTERN);
2926
3233
 
2927
3234
  // src/model/events.ts
2928
- var modelDescriptorSchema = z15.strictObject({
3235
+ var modelDescriptorSchema = z16.strictObject({
2929
3236
  modelId: nonEmptyStringSchema,
2930
3237
  /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
2931
3238
  vendor: nonEmptyStringSchema.optional(),
2932
3239
  family: nonEmptyStringSchema.optional()
2933
3240
  });
2934
- var costFactsSchema = z15.strictObject({
3241
+ var costFactsSchema = z16.strictObject({
2935
3242
  /** ISO 4217 code. */
2936
- currency: z15.string().length(3),
2937
- amount: z15.number().min(0).finite(),
2938
- source: z15.enum(["provider-reported", "computed"])
3243
+ currency: z16.string().length(3),
3244
+ amount: z16.number().min(0).finite(),
3245
+ source: z16.enum(["provider-reported", "computed"])
2939
3246
  });
2940
- var canonicalEventTypeSchema = z15.enum([
3247
+ var canonicalEventTypeSchema = z16.enum([
2941
3248
  "session.start",
2942
3249
  "session.end",
2943
3250
  "prompt.submitted",
@@ -2951,7 +3258,7 @@ var canonicalEventTypeSchema = z15.enum([
2951
3258
  "error.raised"
2952
3259
  ]);
2953
3260
  var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
2954
- var outcomeSchema = z15.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
3261
+ var outcomeSchema = z16.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
2955
3262
  var baseEventFields = {
2956
3263
  schemaVersion: canonicalSchemaVersionSchema,
2957
3264
  eventId: eventIdSchema,
@@ -2970,10 +3277,10 @@ var baseEventFields = {
2970
3277
  subagentId: subagentIdSchema.optional(),
2971
3278
  extensions: extensionsSchema.default(emptyExtensions)
2972
3279
  };
2973
- var event = (shape) => z15.strictObject({ ...baseEventFields, ...shape });
3280
+ var event = (shape) => z16.strictObject({ ...baseEventFields, ...shape });
2974
3281
  var sessionStartEventSchema = event({
2975
- type: z15.literal("session.start"),
2976
- sessionKind: z15.enum(["interactive", "non-interactive", "unknown"]),
3282
+ type: z16.literal("session.start"),
3283
+ sessionKind: z16.enum(["interactive", "non-interactive", "unknown"]),
2977
3284
  agentName: nonEmptyStringSchema.optional(),
2978
3285
  agentVersion: nonEmptyStringSchema.optional(),
2979
3286
  model: modelDescriptorSchema.optional(),
@@ -2981,30 +3288,30 @@ var sessionStartEventSchema = event({
2981
3288
  target: workspaceTargetSchema.optional()
2982
3289
  });
2983
3290
  var sessionEndEventSchema = event({
2984
- type: z15.literal("session.end"),
2985
- reason: z15.enum(["completed", "aborted", "error", "timeout", "unknown"]),
3291
+ type: z16.literal("session.end"),
3292
+ reason: z16.enum(["completed", "aborted", "error", "timeout", "unknown"]),
2986
3293
  durationMillis: durationMillisSchema.optional(),
2987
3294
  /** Session totals, typically cumulative. */
2988
3295
  usage: canonicalUsageSchema.optional(),
2989
3296
  cost: costFactsSchema.optional()
2990
3297
  });
2991
3298
  var promptSubmittedEventSchema = event({
2992
- type: z15.literal("prompt.submitted"),
2993
- promptSource: z15.enum(["user", "automation", "resumed", "unknown"]),
3299
+ type: z16.literal("prompt.submitted"),
3300
+ promptSource: z16.enum(["user", "automation", "resumed", "unknown"]),
2994
3301
  content: contentFactSchema.optional(),
2995
- turnIndex: z15.number().int().min(0).optional(),
3302
+ turnIndex: z16.number().int().min(0).optional(),
2996
3303
  /** The git worktree the session runs in, resolved by the core (ADR 0008). */
2997
3304
  target: workspaceTargetSchema.optional()
2998
3305
  });
2999
3306
  var generationStartEventSchema = event({
3000
- type: z15.literal("generation.start"),
3307
+ type: z16.literal("generation.start"),
3001
3308
  generationId: nonEmptyStringSchema,
3002
3309
  model: modelDescriptorSchema,
3003
3310
  requestedMaxOutputTokens: tokenCountSchema.optional(),
3004
3311
  inputContent: contentFactsSchema.optional()
3005
3312
  });
3006
3313
  var generationEndEventSchema = event({
3007
- type: z15.literal("generation.end"),
3314
+ type: z16.literal("generation.end"),
3008
3315
  generationId: nonEmptyStringSchema,
3009
3316
  model: modelDescriptorSchema,
3010
3317
  outcome: outcomeSchema,
@@ -3014,7 +3321,7 @@ var generationEndEventSchema = event({
3014
3321
  cost: costFactsSchema.optional(),
3015
3322
  outputContent: contentFactsSchema.optional()
3016
3323
  });
3017
- var toolKindSchema = z15.enum([
3324
+ var toolKindSchema = z16.enum([
3018
3325
  "read",
3019
3326
  "write",
3020
3327
  "execute",
@@ -3025,7 +3332,7 @@ var toolKindSchema = z15.enum([
3025
3332
  "unknown"
3026
3333
  ]);
3027
3334
  var toolStartEventSchema = event({
3028
- type: z15.literal("tool.start"),
3335
+ type: z16.literal("tool.start"),
3029
3336
  toolCallId: nonEmptyStringSchema,
3030
3337
  toolName: nonEmptyStringSchema,
3031
3338
  toolKind: toolKindSchema,
@@ -3035,53 +3342,53 @@ var toolStartEventSchema = event({
3035
3342
  target: workspaceTargetSchema.optional()
3036
3343
  });
3037
3344
  var toolEndEventSchema = event({
3038
- type: z15.literal("tool.end"),
3345
+ type: z16.literal("tool.end"),
3039
3346
  toolCallId: nonEmptyStringSchema,
3040
3347
  toolName: nonEmptyStringSchema,
3041
3348
  outcome: outcomeSchema,
3042
3349
  durationMillis: durationMillisSchema.optional(),
3043
3350
  /** Present when the host asked for or recorded a permission decision. */
3044
- permissionDecision: z15.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
3351
+ permissionDecision: z16.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
3045
3352
  output: contentFactSchema.optional(),
3046
3353
  /** The git worktree this call targeted, resolved by the core (ADR 0008). */
3047
3354
  target: workspaceTargetSchema.optional()
3048
3355
  });
3049
3356
  var subagentStartEventSchema = event({
3050
- type: z15.literal("subagent.start"),
3357
+ type: z16.literal("subagent.start"),
3051
3358
  subagentInvocationId: invocationIdSchema,
3052
3359
  subagentType: nonEmptyStringSchema.optional(),
3053
3360
  /** 0 for the top-level agent; 1 for its direct children. */
3054
- delegationDepth: z15.number().int().min(0).max(64),
3361
+ delegationDepth: z16.number().int().min(0).max(64),
3055
3362
  model: modelDescriptorSchema.optional()
3056
3363
  });
3057
3364
  var subagentEndEventSchema = event({
3058
- type: z15.literal("subagent.end"),
3365
+ type: z16.literal("subagent.end"),
3059
3366
  subagentInvocationId: invocationIdSchema,
3060
3367
  outcome: outcomeSchema,
3061
3368
  durationMillis: durationMillisSchema.optional(),
3062
3369
  usage: canonicalUsageSchema.optional()
3063
3370
  });
3064
3371
  var compactionPerformedEventSchema = event({
3065
- type: z15.literal("compaction.performed"),
3066
- trigger: z15.enum(["automatic", "manual", "unknown"]),
3372
+ type: z16.literal("compaction.performed"),
3373
+ trigger: z16.enum(["automatic", "manual", "unknown"]),
3067
3374
  /** Provider-reported context size before and after compaction, if known. */
3068
3375
  contextTokensBefore: tokenCountSchema.optional(),
3069
3376
  contextTokensAfter: tokenCountSchema.optional(),
3070
- droppedMessageCount: z15.number().int().min(0).optional(),
3377
+ droppedMessageCount: z16.number().int().min(0).optional(),
3071
3378
  usage: canonicalUsageSchema.optional()
3072
3379
  });
3073
3380
  var errorRaisedEventSchema = event({
3074
- type: z15.literal("error.raised"),
3381
+ type: z16.literal("error.raised"),
3075
3382
  errorCode: otelHookErrorCodeSchema,
3076
3383
  severity: errorSeveritySchema,
3077
3384
  phase: errorPhaseSchema,
3078
- retryable: z15.boolean(),
3385
+ retryable: z16.boolean(),
3079
3386
  /** Error text is content: it is described, never embedded verbatim by default. */
3080
3387
  message: contentFactSchema.optional(),
3081
3388
  /** Non-sensitive, provider-agnostic short label. */
3082
3389
  detail: nonEmptyStringSchema.optional()
3083
3390
  });
3084
- var canonicalEventSchema = z15.discriminatedUnion("type", [
3391
+ var canonicalEventSchema = z16.discriminatedUnion("type", [
3085
3392
  sessionStartEventSchema,
3086
3393
  sessionEndEventSchema,
3087
3394
  promptSubmittedEventSchema,
@@ -3099,26 +3406,26 @@ var TARGETED = new Set(TARGETED_EVENT_TYPES);
3099
3406
  var isTargetedEvent = (event3) => TARGETED.has(event3.type);
3100
3407
 
3101
3408
  // src/providers/adapter.ts
3102
- var providerDetectionSchema = z16.strictObject({
3409
+ var providerDetectionSchema = z17.strictObject({
3103
3410
  providerId: resolvedProviderIdSchema,
3104
3411
  confidence: detectionConfidenceSchema,
3105
3412
  /**
3106
3413
  * Short, non-sensitive justifications, e.g. `"payload.hook_event_name present"`.
3107
3414
  * Reasons are exported in diagnostics, so they must not quote payload values.
3108
3415
  */
3109
- reasons: z16.array(z16.string().min(1).max(160)).max(8),
3416
+ reasons: z17.array(z17.string().min(1).max(160)).max(8),
3110
3417
  providerVersion: nonEmptyStringSchema.optional(),
3111
3418
  /** The provider's own name for this event, when the payload states one. */
3112
3419
  sourceEventName: nonEmptyStringSchema.optional()
3113
3420
  });
3114
- var deliveryIdentifierSupportSchema = z16.enum(["none", "partial", "all"]);
3421
+ var deliveryIdentifierSupportSchema = z17.enum(["none", "partial", "all"]);
3115
3422
  var DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
3116
- var deliveryComponentSchema = z16.string().regex(
3423
+ var deliveryComponentSchema = z17.string().regex(
3117
3424
  DELIVERY_COMPONENT_PATTERN,
3118
3425
  "delivery component must be identifier-shaped: no whitespace, no path separators"
3119
3426
  );
3120
3427
  var MAX_DELIVERY_COMPONENTS = 8;
3121
- var providerDeliveryClaimSchema = z16.strictObject({
3428
+ var providerDeliveryClaimSchema = z17.strictObject({
3122
3429
  /**
3123
3430
  * The provider's own session/conversation id. Scopes the callback identity, so
3124
3431
  * two sessions reusing one tool-call id never collide.
@@ -3130,26 +3437,26 @@ var providerDeliveryClaimSchema = z16.strictObject({
3130
3437
  * Identifier-shaped payload fields that, together with `sourceEventName`,
3131
3438
  * name this callback within the session exactly once.
3132
3439
  */
3133
- components: z16.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
3440
+ components: z17.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
3134
3441
  /**
3135
3442
  * Short, non-sensitive justifications, e.g. `"payload.tool_use_id names one
3136
3443
  * tool call"`. Evidence reaches diagnostics, so it must name fields, never
3137
3444
  * quote their values.
3138
3445
  */
3139
- evidence: z16.array(z16.string().min(1).max(160)).min(1).max(4).readonly()
3446
+ evidence: z17.array(z17.string().min(1).max(160)).min(1).max(4).readonly()
3140
3447
  });
3141
3448
  var DELIVERY_GAP_REASON_PATTERN = /^[^\n\r\t\\/]{1,240}$/;
3142
- var deliveryGapReasonSchema = z16.string().regex(
3449
+ var deliveryGapReasonSchema = z17.string().regex(
3143
3450
  DELIVERY_GAP_REASON_PATTERN,
3144
3451
  "delivery gap reason must be one line of prose: no path separators, no control characters"
3145
3452
  );
3146
3453
  var MAX_DELIVERY_GAPS = 48;
3147
- var providerDeliveryGapsSchema = z16.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
3454
+ var providerDeliveryGapsSchema = z17.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
3148
3455
  message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`
3149
3456
  });
3150
- var providerCapabilitiesSchema = z16.strictObject({
3457
+ var providerCapabilitiesSchema = z17.strictObject({
3151
3458
  /** Event types the adapter can produce. */
3152
- lifecycleEvents: z16.array(canonicalEventTypeSchema).max(32).readonly(),
3459
+ lifecycleEvents: z17.array(canonicalEventTypeSchema).max(32).readonly(),
3153
3460
  usageTemporality: usageTemporalitySchema,
3154
3461
  /**
3155
3462
  * Which accumulator series a `cumulative` report continues — that is, which
@@ -3168,32 +3475,32 @@ var providerCapabilitiesSchema = z16.strictObject({
3168
3475
  * Subagent snapshots keep their own series regardless: a delegated agent's
3169
3476
  * counter is not a point on the parent session's curve.
3170
3477
  */
3171
- cumulativeUsageSeries: z16.enum(["event-scope", "session-lifetime"]).optional(),
3172
- reportsCachedInput: z16.boolean(),
3173
- reportsCacheCreation: z16.boolean(),
3478
+ cumulativeUsageSeries: z17.enum(["event-scope", "session-lifetime"]).optional(),
3479
+ reportsCachedInput: z17.boolean(),
3480
+ reportsCacheCreation: z17.boolean(),
3174
3481
  cacheCreationAccounting: cacheCreationAccountingSchema,
3175
- reportsReasoningOutput: z16.boolean(),
3176
- reportsProviderTotal: z16.boolean(),
3177
- reportsCost: z16.boolean(),
3178
- emitsSubagentEvents: z16.boolean(),
3179
- emitsCompactionEvents: z16.boolean(),
3482
+ reportsReasoningOutput: z17.boolean(),
3483
+ reportsProviderTotal: z17.boolean(),
3484
+ reportsCost: z17.boolean(),
3485
+ emitsSubagentEvents: z17.boolean(),
3486
+ emitsCompactionEvents: z17.boolean(),
3180
3487
  /** True when the provider reads a structured response from stdout. */
3181
- requiresHookResponse: z16.boolean(),
3488
+ requiresHookResponse: z17.boolean(),
3182
3489
  /** How much of this provider's hook traffic is replay-identifiable. */
3183
3490
  deliveryIdentifier: deliveryIdentifierSupportSchema
3184
3491
  });
3185
- var providerHookResponseSchema = z16.strictObject({
3492
+ var providerHookResponseSchema = z17.strictObject({
3186
3493
  /**
3187
3494
  * Always 0. A telemetry hook that can fail the host agent is a liability, so
3188
3495
  * the type forbids expressing anything else (ADR 0004).
3189
3496
  */
3190
- exitCode: z16.literal(0),
3497
+ exitCode: z17.literal(0),
3191
3498
  /** Protocol response text. Omit to write nothing at all. */
3192
- stdout: z16.string().max(8192).optional(),
3499
+ stdout: z17.string().max(8192).optional(),
3193
3500
  /** Non-sensitive diagnostic text for stderr. */
3194
- stderr: z16.string().max(8192).optional(),
3501
+ stderr: z17.string().max(8192).optional(),
3195
3502
  /** Declares which of the two stdout contracts this response follows. */
3196
- contract: z16.enum(["silent", "provider-protocol"])
3503
+ contract: z17.enum(["silent", "provider-protocol"])
3197
3504
  });
3198
3505
  var SILENT_HOOK_RESPONSE = Object.freeze({
3199
3506
  exitCode: 0,
@@ -3306,7 +3613,7 @@ var createEventFactory = (input) => {
3306
3613
  };
3307
3614
 
3308
3615
  // src/providers/antigravity/payload.ts
3309
- import { z as z17 } from "zod";
3616
+ import { z as z18 } from "zod";
3310
3617
  var ANTIGRAVITY_HOOK_EVENT_NAMES = [
3311
3618
  "PreInvocation",
3312
3619
  "PostInvocation",
@@ -3314,48 +3621,48 @@ var ANTIGRAVITY_HOOK_EVENT_NAMES = [
3314
3621
  "PostToolUse",
3315
3622
  "Stop"
3316
3623
  ];
3317
- var hookEventNameSchema = z17.enum(ANTIGRAVITY_HOOK_EVENT_NAMES);
3318
- var antigravityWeakShapeSchema = z17.object({ hookEventName: hookEventNameSchema }).passthrough();
3624
+ var hookEventNameSchema = z18.enum(ANTIGRAVITY_HOOK_EVENT_NAMES);
3625
+ var antigravityWeakShapeSchema = z18.object({ hookEventName: hookEventNameSchema }).passthrough();
3319
3626
  var commonFields = {
3320
- conversationId: z17.string().min(1),
3321
- workspacePaths: z17.array(z17.string().min(1)).max(64),
3322
- invocationNum: z17.number().int().min(0),
3627
+ conversationId: z18.string().min(1),
3628
+ workspacePaths: z18.array(z18.string().min(1)).max(64),
3629
+ invocationNum: z18.number().int().min(0),
3323
3630
  /** Never disclosed: a real filesystem path. Accepted, never propagated. */
3324
- transcriptPath: z17.string().min(1).optional(),
3631
+ transcriptPath: z18.string().min(1).optional(),
3325
3632
  /** Never disclosed: a real filesystem path. Accepted, never propagated. */
3326
- artifactDirectoryPath: z17.string().min(1).optional()
3633
+ artifactDirectoryPath: z18.string().min(1).optional()
3327
3634
  };
3328
- var preInvocationPayloadSchema = z17.object({
3329
- hookEventName: z17.literal("PreInvocation"),
3635
+ var preInvocationPayloadSchema = z18.object({
3636
+ hookEventName: z18.literal("PreInvocation"),
3330
3637
  ...commonFields,
3331
- agentVersion: z17.string().min(1).optional()
3638
+ agentVersion: z18.string().min(1).optional()
3332
3639
  });
3333
- var postInvocationPayloadSchema = z17.object({
3334
- hookEventName: z17.literal("PostInvocation"),
3640
+ var postInvocationPayloadSchema = z18.object({
3641
+ hookEventName: z18.literal("PostInvocation"),
3335
3642
  ...commonFields,
3336
- agentVersion: z17.string().min(1).optional()
3643
+ agentVersion: z18.string().min(1).optional()
3337
3644
  });
3338
- var preToolUsePayloadSchema = z17.object({
3339
- hookEventName: z17.literal("PreToolUse"),
3645
+ var preToolUsePayloadSchema = z18.object({
3646
+ hookEventName: z18.literal("PreToolUse"),
3340
3647
  ...commonFields,
3341
- stepIdx: z17.number().int().min(0),
3342
- toolName: z17.string().min(1),
3343
- toolInput: z17.unknown().optional()
3648
+ stepIdx: z18.number().int().min(0),
3649
+ toolName: z18.string().min(1),
3650
+ toolInput: z18.unknown().optional()
3344
3651
  });
3345
- var postToolUsePayloadSchema = z17.object({
3346
- hookEventName: z17.literal("PostToolUse"),
3652
+ var postToolUsePayloadSchema = z18.object({
3653
+ hookEventName: z18.literal("PostToolUse"),
3347
3654
  ...commonFields,
3348
- stepIdx: z17.number().int().min(0),
3349
- toolName: z17.string().min(1),
3350
- toolResponse: z17.unknown().optional(),
3351
- isError: z17.boolean().optional()
3655
+ stepIdx: z18.number().int().min(0),
3656
+ toolName: z18.string().min(1),
3657
+ toolResponse: z18.unknown().optional(),
3658
+ isError: z18.boolean().optional()
3352
3659
  });
3353
- var stopPayloadSchema = z17.object({
3354
- hookEventName: z17.literal("Stop"),
3660
+ var stopPayloadSchema = z18.object({
3661
+ hookEventName: z18.literal("Stop"),
3355
3662
  ...commonFields,
3356
- fullyIdle: z17.boolean()
3663
+ fullyIdle: z18.boolean()
3357
3664
  });
3358
- var antigravityHookPayloadSchema = z17.discriminatedUnion("hookEventName", [
3665
+ var antigravityHookPayloadSchema = z18.discriminatedUnion("hookEventName", [
3359
3666
  preInvocationPayloadSchema,
3360
3667
  postInvocationPayloadSchema,
3361
3668
  preToolUsePayloadSchema,
@@ -3604,35 +3911,35 @@ var CLAUDE_CODE_CAPABILITIES = Object.freeze({
3604
3911
  });
3605
3912
 
3606
3913
  // src/providers/claude/schema.ts
3607
- import { z as z18 } from "zod";
3914
+ import { z as z19 } from "zod";
3608
3915
  var commonFields2 = {
3609
- session_id: z18.string().min(1),
3610
- transcript_path: z18.string().min(1).optional(),
3611
- cwd: z18.string().min(1).optional(),
3612
- permission_mode: z18.string().min(1).optional(),
3916
+ session_id: z19.string().min(1),
3917
+ transcript_path: z19.string().min(1).optional(),
3918
+ cwd: z19.string().min(1).optional(),
3919
+ permission_mode: z19.string().min(1).optional(),
3613
3920
  /** Correlates a hook firing with the user prompt that triggered it (Claude Code v2.1.196+). */
3614
- prompt_id: z18.string().min(1).optional(),
3921
+ prompt_id: z19.string().min(1).optional(),
3615
3922
  /** Present when the hook fired while running inside a subagent. */
3616
- agent_id: z18.string().min(1).optional(),
3617
- agent_type: z18.string().min(1).optional()
3618
- };
3619
- var claudeCacheCreationSchema = z18.object({
3620
- ephemeral_5m_input_tokens: z18.number().int().min(0).optional(),
3621
- ephemeral_1h_input_tokens: z18.number().int().min(0).optional()
3622
- });
3623
- var claudeUsageIterationSchema = z18.object({
3624
- input_tokens: z18.number().int().min(0).optional(),
3625
- output_tokens: z18.number().int().min(0).optional(),
3626
- cache_creation_input_tokens: z18.number().int().min(0).optional(),
3627
- cache_read_input_tokens: z18.number().int().min(0).optional()
3628
- });
3629
- var claudeUsageSchema = z18.object({
3630
- input_tokens: z18.number().int().min(0),
3631
- output_tokens: z18.number().int().min(0),
3632
- cache_creation_input_tokens: z18.number().int().min(0).optional(),
3633
- cache_read_input_tokens: z18.number().int().min(0).optional(),
3923
+ agent_id: z19.string().min(1).optional(),
3924
+ agent_type: z19.string().min(1).optional()
3925
+ };
3926
+ var claudeCacheCreationSchema = z19.object({
3927
+ ephemeral_5m_input_tokens: z19.number().int().min(0).optional(),
3928
+ ephemeral_1h_input_tokens: z19.number().int().min(0).optional()
3929
+ });
3930
+ var claudeUsageIterationSchema = z19.object({
3931
+ input_tokens: z19.number().int().min(0).optional(),
3932
+ output_tokens: z19.number().int().min(0).optional(),
3933
+ cache_creation_input_tokens: z19.number().int().min(0).optional(),
3934
+ cache_read_input_tokens: z19.number().int().min(0).optional()
3935
+ });
3936
+ var claudeUsageSchema = z19.object({
3937
+ input_tokens: z19.number().int().min(0),
3938
+ output_tokens: z19.number().int().min(0),
3939
+ cache_creation_input_tokens: z19.number().int().min(0).optional(),
3940
+ cache_read_input_tokens: z19.number().int().min(0).optional(),
3634
3941
  cache_creation: claudeCacheCreationSchema.optional(),
3635
- iterations: z18.array(claudeUsageIterationSchema).optional(),
3942
+ iterations: z19.array(claudeUsageIterationSchema).optional(),
3636
3943
  /**
3637
3944
  * Counters the canonical model has a home for but Claude Code never reports:
3638
3945
  * 0 of 4,999 real usage objects carried either (finding 5).
@@ -3641,112 +3948,112 @@ var claudeUsageSchema = z18.object({
3641
3948
  * that a harness attaching one gets told it was excluded, instead of watching
3642
3949
  * it vanish. See `CLAUDE_EXCLUDED_USAGE_COUNTERS`.
3643
3950
  */
3644
- total_tokens: z18.number().int().min(0).optional(),
3645
- reasoning_output_tokens: z18.number().int().min(0).optional()
3951
+ total_tokens: z19.number().int().min(0).optional(),
3952
+ reasoning_output_tokens: z19.number().int().min(0).optional()
3646
3953
  });
3647
- var sessionStartPayloadSchema = z18.object({
3954
+ var sessionStartPayloadSchema = z19.object({
3648
3955
  ...commonFields2,
3649
- hook_event_name: z18.literal("SessionStart"),
3956
+ hook_event_name: z19.literal("SessionStart"),
3650
3957
  /** Matcher values: startup | resume | clear | compact | fork. Forward-compatible: any string. */
3651
- source: z18.string().min(1).optional(),
3652
- model: z18.string().min(1).optional(),
3653
- session_title: z18.string().min(1).optional()
3958
+ source: z19.string().min(1).optional(),
3959
+ model: z19.string().min(1).optional(),
3960
+ session_title: z19.string().min(1).optional()
3654
3961
  });
3655
- var sessionEndPayloadSchema = z18.object({
3962
+ var sessionEndPayloadSchema = z19.object({
3656
3963
  ...commonFields2,
3657
- hook_event_name: z18.literal("SessionEnd"),
3964
+ hook_event_name: z19.literal("SessionEnd"),
3658
3965
  /** Current Claude Code field; values include clear, logout, prompt_input_exit, and other. */
3659
- reason: z18.string().min(1).optional(),
3966
+ reason: z19.string().min(1).optional(),
3660
3967
  /** Compatibility alias emitted by older wrappers and hook integrations. */
3661
- end_reason: z18.string().min(1).optional()
3968
+ end_reason: z19.string().min(1).optional()
3662
3969
  });
3663
- var userPromptSubmitPayloadSchema = z18.object({
3970
+ var userPromptSubmitPayloadSchema = z19.object({
3664
3971
  ...commonFields2,
3665
- hook_event_name: z18.literal("UserPromptSubmit"),
3666
- prompt: z18.string()
3972
+ hook_event_name: z19.literal("UserPromptSubmit"),
3973
+ prompt: z19.string()
3667
3974
  });
3668
- var preToolUsePayloadSchema2 = z18.object({
3975
+ var preToolUsePayloadSchema2 = z19.object({
3669
3976
  ...commonFields2,
3670
- hook_event_name: z18.literal("PreToolUse"),
3671
- tool_name: z18.string().min(1),
3672
- tool_input: z18.unknown(),
3673
- tool_use_id: z18.string().min(1)
3977
+ hook_event_name: z19.literal("PreToolUse"),
3978
+ tool_name: z19.string().min(1),
3979
+ tool_input: z19.unknown(),
3980
+ tool_use_id: z19.string().min(1)
3674
3981
  });
3675
- var postToolUsePayloadSchema2 = z18.object({
3982
+ var postToolUsePayloadSchema2 = z19.object({
3676
3983
  ...commonFields2,
3677
- hook_event_name: z18.literal("PostToolUse"),
3678
- tool_name: z18.string().min(1),
3679
- tool_input: z18.unknown().optional(),
3680
- tool_response: z18.unknown(),
3681
- tool_use_id: z18.string().min(1)
3984
+ hook_event_name: z19.literal("PostToolUse"),
3985
+ tool_name: z19.string().min(1),
3986
+ tool_input: z19.unknown().optional(),
3987
+ tool_response: z19.unknown(),
3988
+ tool_use_id: z19.string().min(1)
3682
3989
  });
3683
- var postToolUseFailurePayloadSchema = z18.object({
3990
+ var postToolUseFailurePayloadSchema = z19.object({
3684
3991
  ...commonFields2,
3685
- hook_event_name: z18.literal("PostToolUseFailure"),
3686
- tool_name: z18.string().min(1),
3687
- tool_input: z18.unknown().optional(),
3688
- tool_error: z18.unknown(),
3689
- tool_use_id: z18.string().min(1)
3992
+ hook_event_name: z19.literal("PostToolUseFailure"),
3993
+ tool_name: z19.string().min(1),
3994
+ tool_input: z19.unknown().optional(),
3995
+ tool_error: z19.unknown(),
3996
+ tool_use_id: z19.string().min(1)
3690
3997
  });
3691
- var permissionRequestPayloadSchema = z18.object({
3998
+ var permissionRequestPayloadSchema = z19.object({
3692
3999
  ...commonFields2,
3693
- hook_event_name: z18.literal("PermissionRequest"),
3694
- tool_name: z18.string().min(1),
3695
- tool_input: z18.unknown().optional(),
3696
- tool_use_id: z18.string().min(1)
4000
+ hook_event_name: z19.literal("PermissionRequest"),
4001
+ tool_name: z19.string().min(1),
4002
+ tool_input: z19.unknown().optional(),
4003
+ tool_use_id: z19.string().min(1)
3697
4004
  });
3698
- var subagentStartPayloadSchema = z18.object({
4005
+ var subagentStartPayloadSchema = z19.object({
3699
4006
  ...commonFields2,
3700
- hook_event_name: z18.literal("SubagentStart"),
3701
- agent_type: z18.string().min(1),
3702
- agent_id: z18.string().min(1)
4007
+ hook_event_name: z19.literal("SubagentStart"),
4008
+ agent_type: z19.string().min(1),
4009
+ agent_id: z19.string().min(1)
3703
4010
  });
3704
- var subagentStopPayloadSchema = z18.object({
4011
+ var subagentStopPayloadSchema = z19.object({
3705
4012
  ...commonFields2,
3706
- hook_event_name: z18.literal("SubagentStop"),
3707
- agent_type: z18.string().min(1),
3708
- agent_id: z18.string().min(1),
3709
- last_assistant_message: z18.string().optional(),
4013
+ hook_event_name: z19.literal("SubagentStop"),
4014
+ agent_type: z19.string().min(1),
4015
+ agent_id: z19.string().min(1),
4016
+ last_assistant_message: z19.string().optional(),
3710
4017
  /** True when this stop fired because a hook continued the subagent's turn. */
3711
- stop_hook_active: z18.boolean().optional(),
4018
+ stop_hook_active: z19.boolean().optional(),
3712
4019
  usage: claudeUsageSchema.optional()
3713
4020
  });
3714
- var preCompactPayloadSchema = z18.object({
4021
+ var preCompactPayloadSchema = z19.object({
3715
4022
  ...commonFields2,
3716
- hook_event_name: z18.literal("PreCompact"),
4023
+ hook_event_name: z19.literal("PreCompact"),
3717
4024
  /** Upstream values: manual | auto. Forward-compatible: any string. */
3718
- trigger: z18.string().min(1).optional(),
4025
+ trigger: z19.string().min(1).optional(),
3719
4026
  /** Compatibility alias emitted by older wrappers and hook integrations. */
3720
- compact_trigger: z18.string().min(1).optional(),
4027
+ compact_trigger: z19.string().min(1).optional(),
3721
4028
  /**
3722
4029
  * Harness-supplied, never upstream. Reported as an explicit exclusion rather
3723
4030
  * than carried across the process boundary: see `events.ts`.
3724
4031
  */
3725
- context_tokens_before: z18.number().int().min(0).optional(),
3726
- estimated_tokens_removed: z18.number().int().min(0).optional()
4032
+ context_tokens_before: z19.number().int().min(0).optional(),
4033
+ estimated_tokens_removed: z19.number().int().min(0).optional()
3727
4034
  });
3728
- var postCompactPayloadSchema = z18.object({
4035
+ var postCompactPayloadSchema = z19.object({
3729
4036
  ...commonFields2,
3730
- hook_event_name: z18.literal("PostCompact"),
3731
- trigger: z18.string().min(1).optional(),
3732
- compact_trigger: z18.string().min(1).optional(),
4037
+ hook_event_name: z19.literal("PostCompact"),
4038
+ trigger: z19.string().min(1).optional(),
4039
+ compact_trigger: z19.string().min(1).optional(),
3733
4040
  /** Harness-supplied, never upstream; accepted here because one callback carries both. */
3734
- context_tokens_before: z18.number().int().min(0).optional(),
3735
- context_tokens_after: z18.number().int().min(0).optional(),
3736
- dropped_message_count: z18.number().int().min(0).optional(),
4041
+ context_tokens_before: z19.number().int().min(0).optional(),
4042
+ context_tokens_after: z19.number().int().min(0).optional(),
4043
+ dropped_message_count: z19.number().int().min(0).optional(),
3737
4044
  usage: claudeUsageSchema.optional()
3738
4045
  });
3739
- var stopPayloadSchema2 = z18.object({
4046
+ var stopPayloadSchema2 = z19.object({
3740
4047
  ...commonFields2,
3741
- hook_event_name: z18.literal("Stop"),
4048
+ hook_event_name: z19.literal("Stop"),
3742
4049
  /**
3743
4050
  * Interactive Stop field (Claude Code ≥ 2.1.47). Print / `-p` / Agent SDK
3744
4051
  * result messages use `result` instead; `events.ts` reads both (and camelCase
3745
4052
  * `lastAssistantMessage`) through `extractClaudeAssistantText`.
3746
4053
  */
3747
- last_assistant_message: z18.string().optional(),
4054
+ last_assistant_message: z19.string().optional(),
3748
4055
  /** Print / `-p` JSON result field; accepted so a harness can attach it as-is. */
3749
- result: z18.string().optional(),
4056
+ result: z19.string().optional(),
3750
4057
  /**
3751
4058
  * True when this stop fired because a hook continued the turn.
3752
4059
  *
@@ -3754,22 +4061,22 @@ var stopPayloadSchema2 = z18.object({
3754
4061
  * stop from a continuation stop, which is what lets `delivery.ts` deduplicate
3755
4062
  * the former without suppressing the latter.
3756
4063
  */
3757
- stop_hook_active: z18.boolean().optional(),
4064
+ stop_hook_active: z19.boolean().optional(),
3758
4065
  usage: claudeUsageSchema.optional()
3759
4066
  });
3760
- var stopFailurePayloadSchema = z18.object({
4067
+ var stopFailurePayloadSchema = z19.object({
3761
4068
  ...commonFields2,
3762
- hook_event_name: z18.literal("StopFailure"),
4069
+ hook_event_name: z19.literal("StopFailure"),
3763
4070
  /**
3764
4071
  * Matcher values: rate_limit | overloaded | authentication_failed |
3765
4072
  * oauth_org_not_allowed | billing_error | invalid_request | model_not_found
3766
4073
  * | server_error | max_output_tokens | unknown.
3767
4074
  */
3768
- error_type: z18.string().min(1),
3769
- error_message: z18.string().optional(),
4075
+ error_type: z19.string().min(1),
4076
+ error_message: z19.string().optional(),
3770
4077
  usage: claudeUsageSchema.optional()
3771
4078
  });
3772
- var claudeHookPayloadSchema = z18.discriminatedUnion("hook_event_name", [
4079
+ var claudeHookPayloadSchema = z19.discriminatedUnion("hook_event_name", [
3773
4080
  sessionStartPayloadSchema,
3774
4081
  sessionEndPayloadSchema,
3775
4082
  userPromptSubmitPayloadSchema,
@@ -3799,15 +4106,15 @@ var CLAUDE_HOOK_EVENT_NAMES = [
3799
4106
  "Stop",
3800
4107
  "StopFailure"
3801
4108
  ];
3802
- var claudeIdentityFieldsSchema = z18.object({
3803
- session_id: z18.string().min(1),
3804
- hook_event_name: z18.string().min(1),
3805
- cwd: z18.string().min(1).optional(),
3806
- prompt_id: z18.string().min(1).optional(),
3807
- agent_id: z18.string().min(1).optional(),
3808
- tool_use_id: z18.string().min(1).optional(),
4109
+ var claudeIdentityFieldsSchema = z19.object({
4110
+ session_id: z19.string().min(1),
4111
+ hook_event_name: z19.string().min(1),
4112
+ cwd: z19.string().min(1).optional(),
4113
+ prompt_id: z19.string().min(1).optional(),
4114
+ agent_id: z19.string().min(1).optional(),
4115
+ tool_use_id: z19.string().min(1).optional(),
3809
4116
  /** Read by `delivery.ts` to tell a once-per-prompt stop from a continuation. */
3810
- stop_hook_active: z18.boolean().optional()
4117
+ stop_hook_active: z19.boolean().optional()
3811
4118
  });
3812
4119
 
3813
4120
  // src/providers/claude/usage.ts
@@ -4548,105 +4855,105 @@ var createClaudeCodeAdapter = (options = {}) => ({
4548
4855
  });
4549
4856
 
4550
4857
  // src/providers/codex/payload.ts
4551
- import { z as z19 } from "zod";
4552
- var permissionModeSchema = z19.enum([
4858
+ import { z as z20 } from "zod";
4859
+ var permissionModeSchema = z20.enum([
4553
4860
  "default",
4554
4861
  "acceptEdits",
4555
4862
  "plan",
4556
4863
  "dontAsk",
4557
4864
  "bypassPermissions"
4558
4865
  ]);
4559
- var codexUsageSchema = z19.object({
4560
- input_tokens: z19.number().int().min(0).optional(),
4561
- cached_input_tokens: z19.number().int().min(0).optional(),
4562
- output_tokens: z19.number().int().min(0).optional(),
4563
- reasoning_output_tokens: z19.number().int().min(0).optional(),
4564
- total_tokens: z19.number().int().min(0).optional()
4866
+ var codexUsageSchema = z20.object({
4867
+ input_tokens: z20.number().int().min(0).optional(),
4868
+ cached_input_tokens: z20.number().int().min(0).optional(),
4869
+ output_tokens: z20.number().int().min(0).optional(),
4870
+ reasoning_output_tokens: z20.number().int().min(0).optional(),
4871
+ total_tokens: z20.number().int().min(0).optional()
4565
4872
  });
4566
4873
  var baseFields = {
4567
- session_id: z19.string().min(1).max(256),
4568
- cwd: z19.string().min(1).max(4096).optional(),
4569
- model: z19.string().min(1).max(256).optional(),
4874
+ session_id: z20.string().min(1).max(256),
4875
+ cwd: z20.string().min(1).max(4096).optional(),
4876
+ model: z20.string().min(1).max(256).optional(),
4570
4877
  permission_mode: permissionModeSchema.optional(),
4571
- transcript_path: z19.string().min(1).max(4096).optional(),
4572
- codex_version: z19.string().min(1).max(64).optional(),
4878
+ transcript_path: z20.string().min(1).max(4096).optional(),
4879
+ codex_version: z20.string().min(1).max(64).optional(),
4573
4880
  /** Not part of the documented protocol; lets tests and replay stay deterministic. */
4574
- occurred_at: z19.number().int().min(0).optional()
4881
+ occurred_at: z20.number().int().min(0).optional()
4575
4882
  };
4576
- var codexSessionStartPayloadSchema = z19.object({
4883
+ var codexSessionStartPayloadSchema = z20.object({
4577
4884
  ...baseFields,
4578
- hook_event_name: z19.literal("SessionStart"),
4579
- source: z19.enum(["startup", "resume", "clear", "compact"]).optional()
4885
+ hook_event_name: z20.literal("SessionStart"),
4886
+ source: z20.enum(["startup", "resume", "clear", "compact"]).optional()
4580
4887
  });
4581
- var codexUserPromptSubmitPayloadSchema = z19.object({
4888
+ var codexUserPromptSubmitPayloadSchema = z20.object({
4582
4889
  ...baseFields,
4583
- hook_event_name: z19.literal("UserPromptSubmit"),
4584
- turn_id: z19.string().min(1).max(256).optional(),
4585
- prompt: z19.string().max(1e6).optional()
4890
+ hook_event_name: z20.literal("UserPromptSubmit"),
4891
+ turn_id: z20.string().min(1).max(256).optional(),
4892
+ prompt: z20.string().max(1e6).optional()
4586
4893
  });
4587
- var codexPreToolUsePayloadSchema = z19.object({
4894
+ var codexPreToolUsePayloadSchema = z20.object({
4588
4895
  ...baseFields,
4589
- hook_event_name: z19.literal("PreToolUse"),
4590
- turn_id: z19.string().min(1).max(256).optional(),
4591
- tool_name: z19.string().min(1).max(256),
4592
- tool_call_id: z19.string().min(1).max(256).optional(),
4593
- tool_input: z19.unknown().optional()
4896
+ hook_event_name: z20.literal("PreToolUse"),
4897
+ turn_id: z20.string().min(1).max(256).optional(),
4898
+ tool_name: z20.string().min(1).max(256),
4899
+ tool_call_id: z20.string().min(1).max(256).optional(),
4900
+ tool_input: z20.unknown().optional()
4594
4901
  });
4595
- var codexPermissionRequestPayloadSchema = z19.object({
4902
+ var codexPermissionRequestPayloadSchema = z20.object({
4596
4903
  ...baseFields,
4597
- hook_event_name: z19.literal("PermissionRequest"),
4598
- turn_id: z19.string().min(1).max(256).optional(),
4599
- tool_name: z19.string().min(1).max(256).optional(),
4600
- tool_call_id: z19.string().min(1).max(256).optional(),
4601
- tool_input: z19.unknown().optional()
4904
+ hook_event_name: z20.literal("PermissionRequest"),
4905
+ turn_id: z20.string().min(1).max(256).optional(),
4906
+ tool_name: z20.string().min(1).max(256).optional(),
4907
+ tool_call_id: z20.string().min(1).max(256).optional(),
4908
+ tool_input: z20.unknown().optional()
4602
4909
  });
4603
- var codexPostToolUsePayloadSchema = z19.object({
4910
+ var codexPostToolUsePayloadSchema = z20.object({
4604
4911
  ...baseFields,
4605
- hook_event_name: z19.literal("PostToolUse"),
4606
- turn_id: z19.string().min(1).max(256).optional(),
4607
- tool_name: z19.string().min(1).max(256),
4608
- tool_call_id: z19.string().min(1).max(256).optional(),
4609
- tool_input: z19.unknown().optional(),
4610
- tool_response: z19.unknown().optional(),
4611
- permission_decision: z19.enum(["allowed", "denied", "deferred"]).optional(),
4612
- duration_ms: z19.number().min(0).optional()
4912
+ hook_event_name: z20.literal("PostToolUse"),
4913
+ turn_id: z20.string().min(1).max(256).optional(),
4914
+ tool_name: z20.string().min(1).max(256),
4915
+ tool_call_id: z20.string().min(1).max(256).optional(),
4916
+ tool_input: z20.unknown().optional(),
4917
+ tool_response: z20.unknown().optional(),
4918
+ permission_decision: z20.enum(["allowed", "denied", "deferred"]).optional(),
4919
+ duration_ms: z20.number().min(0).optional()
4613
4920
  });
4614
- var codexPreCompactPayloadSchema = z19.object({
4921
+ var codexPreCompactPayloadSchema = z20.object({
4615
4922
  ...baseFields,
4616
- hook_event_name: z19.literal("PreCompact"),
4617
- trigger: z19.enum(["auto", "manual"]).optional(),
4618
- context_tokens_before: z19.number().int().min(0).optional()
4923
+ hook_event_name: z20.literal("PreCompact"),
4924
+ trigger: z20.enum(["auto", "manual"]).optional(),
4925
+ context_tokens_before: z20.number().int().min(0).optional()
4619
4926
  });
4620
- var codexPostCompactPayloadSchema = z19.object({
4927
+ var codexPostCompactPayloadSchema = z20.object({
4621
4928
  ...baseFields,
4622
- hook_event_name: z19.literal("PostCompact"),
4623
- trigger: z19.enum(["auto", "manual"]).optional(),
4624
- context_tokens_after: z19.number().int().min(0).optional(),
4625
- dropped_message_count: z19.number().int().min(0).optional(),
4929
+ hook_event_name: z20.literal("PostCompact"),
4930
+ trigger: z20.enum(["auto", "manual"]).optional(),
4931
+ context_tokens_after: z20.number().int().min(0).optional(),
4932
+ dropped_message_count: z20.number().int().min(0).optional(),
4626
4933
  usage: codexUsageSchema.optional()
4627
4934
  });
4628
- var codexSubagentStartPayloadSchema = z19.object({
4935
+ var codexSubagentStartPayloadSchema = z20.object({
4629
4936
  ...baseFields,
4630
- hook_event_name: z19.literal("SubagentStart"),
4631
- turn_id: z19.string().min(1).max(256).optional(),
4632
- subagent_id: z19.string().min(1).max(256),
4633
- subagent_type: z19.string().min(1).max(256).optional()
4937
+ hook_event_name: z20.literal("SubagentStart"),
4938
+ turn_id: z20.string().min(1).max(256).optional(),
4939
+ subagent_id: z20.string().min(1).max(256),
4940
+ subagent_type: z20.string().min(1).max(256).optional()
4634
4941
  });
4635
- var codexSubagentStopPayloadSchema = z19.object({
4942
+ var codexSubagentStopPayloadSchema = z20.object({
4636
4943
  ...baseFields,
4637
- hook_event_name: z19.literal("SubagentStop"),
4638
- turn_id: z19.string().min(1).max(256).optional(),
4639
- subagent_id: z19.string().min(1).max(256),
4640
- status: z19.enum(["completed", "failed", "cancelled"]).optional(),
4944
+ hook_event_name: z20.literal("SubagentStop"),
4945
+ turn_id: z20.string().min(1).max(256).optional(),
4946
+ subagent_id: z20.string().min(1).max(256),
4947
+ status: z20.enum(["completed", "failed", "cancelled"]).optional(),
4641
4948
  usage: codexUsageSchema.optional()
4642
4949
  });
4643
- var codexStopPayloadSchema = z19.object({
4950
+ var codexStopPayloadSchema = z20.object({
4644
4951
  ...baseFields,
4645
- hook_event_name: z19.literal("Stop"),
4646
- turn_id: z19.string().min(1).max(256).optional(),
4647
- stop_reason: z19.string().min(1).max(256).optional(),
4952
+ hook_event_name: z20.literal("Stop"),
4953
+ turn_id: z20.string().min(1).max(256).optional(),
4954
+ stop_reason: z20.string().min(1).max(256).optional(),
4648
4955
  usage: codexUsageSchema.optional(),
4649
- duration_ms: z19.number().min(0).optional()
4956
+ duration_ms: z20.number().min(0).optional()
4650
4957
  });
4651
4958
  var CODEX_HOOK_EVENT_NAMES = [
4652
4959
  "SessionStart",
@@ -4660,7 +4967,7 @@ var CODEX_HOOK_EVENT_NAMES = [
4660
4967
  "SubagentStop",
4661
4968
  "Stop"
4662
4969
  ];
4663
- var codexHookPayloadSchema = z19.discriminatedUnion("hook_event_name", [
4970
+ var codexHookPayloadSchema = z20.discriminatedUnion("hook_event_name", [
4664
4971
  codexSessionStartPayloadSchema,
4665
4972
  codexUserPromptSubmitPayloadSchema,
4666
4973
  codexPreToolUsePayloadSchema,
@@ -4672,9 +4979,9 @@ var codexHookPayloadSchema = z19.discriminatedUnion("hook_event_name", [
4672
4979
  codexSubagentStopPayloadSchema,
4673
4980
  codexStopPayloadSchema
4674
4981
  ]);
4675
- var codexHookEnvelopeSchema = z19.object({
4676
- session_id: z19.string().min(1),
4677
- hook_event_name: z19.enum(CODEX_HOOK_EVENT_NAMES)
4982
+ var codexHookEnvelopeSchema = z20.object({
4983
+ session_id: z20.string().min(1),
4984
+ hook_event_name: z20.enum(CODEX_HOOK_EVENT_NAMES)
4678
4985
  });
4679
4986
 
4680
4987
  // src/providers/codex/delivery.ts
@@ -5203,7 +5510,7 @@ var createCodexAdapter = () => ({
5203
5510
  });
5204
5511
 
5205
5512
  // src/providers/cursor/payload.ts
5206
- import { z as z20 } from "zod";
5513
+ import { z as z21 } from "zod";
5207
5514
  var CURSOR_PROVIDER_ID = "cursor";
5208
5515
  var CURSOR_HOOK_EVENT_NAMES = [
5209
5516
  "sessionStart",
@@ -5238,23 +5545,23 @@ var CURSOR_DECISION_EVENTS = Object.freeze({
5238
5545
  subagentStart: "permission",
5239
5546
  beforeSubmitPrompt: "continue"
5240
5547
  });
5241
- var modelParamSchema = z20.object({
5242
- id: z20.string(),
5243
- value: z20.string()
5548
+ var modelParamSchema = z21.object({
5549
+ id: z21.string(),
5550
+ value: z21.string()
5244
5551
  });
5245
- var attachmentSchema = z20.object({
5246
- type: z20.string().optional(),
5247
- file_path: z20.string().optional()
5552
+ var attachmentSchema = z21.object({
5553
+ type: z21.string().optional(),
5554
+ file_path: z21.string().optional()
5248
5555
  });
5249
- var fileEditSchema = z20.object({
5250
- old_string: z20.string().optional(),
5251
- new_string: z20.string().optional()
5556
+ var fileEditSchema = z21.object({
5557
+ old_string: z21.string().optional(),
5558
+ new_string: z21.string().optional()
5252
5559
  });
5253
5560
  var usageFields = {
5254
- input_tokens: z20.number().int().min(0).optional(),
5255
- output_tokens: z20.number().int().min(0).optional(),
5256
- cache_read_tokens: z20.number().int().min(0).optional(),
5257
- cache_write_tokens: z20.number().int().min(0).optional()
5561
+ input_tokens: z21.number().int().min(0).optional(),
5562
+ output_tokens: z21.number().int().min(0).optional(),
5563
+ cache_read_tokens: z21.number().int().min(0).optional(),
5564
+ cache_write_tokens: z21.number().int().min(0).optional()
5258
5565
  };
5259
5566
  var envelopeShape = {
5260
5567
  // Not `.min(1)`: see `cursorSessionId`. A payload naming neither
@@ -5262,136 +5569,136 @@ var envelopeShape = {
5262
5569
  // `recognizeCursorPayload`'s post-parse check — but rejecting it here would
5263
5570
  // fail the whole discriminated union on a field the adapter can source from
5264
5571
  // either name.
5265
- conversation_id: z20.string().optional(),
5266
- generation_id: z20.string().optional(),
5267
- session_id: z20.string().optional(),
5268
- model: z20.string().optional(),
5269
- model_id: z20.string().optional(),
5270
- model_params: z20.array(modelParamSchema).max(64).optional(),
5271
- cursor_version: z20.string().optional(),
5272
- workspace_roots: z20.array(z20.string()).max(64).optional(),
5273
- cwd: z20.string().optional(),
5572
+ conversation_id: z21.string().optional(),
5573
+ generation_id: z21.string().optional(),
5574
+ session_id: z21.string().optional(),
5575
+ model: z21.string().optional(),
5576
+ model_id: z21.string().optional(),
5577
+ model_params: z21.array(modelParamSchema).max(64).optional(),
5578
+ cursor_version: z21.string().optional(),
5579
+ workspace_roots: z21.array(z21.string()).max(64).optional(),
5580
+ cwd: z21.string().optional(),
5274
5581
  /** Never propagated. */
5275
- user_email: z20.string().nullish(),
5582
+ user_email: z21.string().nullish(),
5276
5583
  /** Never propagated. */
5277
- transcript_path: z20.string().nullish()
5584
+ transcript_path: z21.string().nullish()
5278
5585
  };
5279
- var event2 = (name, shape) => z20.object({ ...envelopeShape, hook_event_name: z20.literal(name), ...shape });
5586
+ var event2 = (name, shape) => z21.object({ ...envelopeShape, hook_event_name: z21.literal(name), ...shape });
5280
5587
  var sessionStartPayloadSchema2 = event2("sessionStart", {
5281
- is_background_agent: z20.boolean().optional(),
5282
- composer_mode: z20.string().optional()
5588
+ is_background_agent: z21.boolean().optional(),
5589
+ composer_mode: z21.string().optional()
5283
5590
  });
5284
5591
  var sessionEndPayloadSchema2 = event2("sessionEnd", {
5285
- reason: z20.string().optional(),
5286
- duration_ms: z20.number().min(0).optional(),
5287
- is_background_agent: z20.boolean().optional(),
5288
- final_status: z20.string().optional(),
5289
- error_message: z20.string().optional()
5592
+ reason: z21.string().optional(),
5593
+ duration_ms: z21.number().min(0).optional(),
5594
+ is_background_agent: z21.boolean().optional(),
5595
+ final_status: z21.string().optional(),
5596
+ error_message: z21.string().optional()
5290
5597
  });
5291
5598
  var beforeSubmitPromptPayloadSchema = event2("beforeSubmitPrompt", {
5292
- prompt: z20.string().optional(),
5293
- attachments: z20.array(attachmentSchema).max(256).optional(),
5294
- composer_mode: z20.string().optional()
5599
+ prompt: z21.string().optional(),
5600
+ attachments: z21.array(attachmentSchema).max(256).optional(),
5601
+ composer_mode: z21.string().optional()
5295
5602
  });
5296
5603
  var afterAgentResponsePayloadSchema = event2("afterAgentResponse", {
5297
- text: z20.string().optional(),
5604
+ text: z21.string().optional(),
5298
5605
  ...usageFields
5299
5606
  });
5300
5607
  var afterAgentThoughtPayloadSchema = event2("afterAgentThought", {
5301
- text: z20.string().optional(),
5302
- duration_ms: z20.number().min(0).optional()
5608
+ text: z21.string().optional(),
5609
+ duration_ms: z21.number().min(0).optional()
5303
5610
  });
5304
5611
  var preToolUsePayloadSchema3 = event2("preToolUse", {
5305
- tool_name: z20.string().min(1),
5306
- tool_input: z20.unknown().optional(),
5307
- tool_use_id: z20.string().optional(),
5308
- agent_message: z20.string().optional()
5612
+ tool_name: z21.string().min(1),
5613
+ tool_input: z21.unknown().optional(),
5614
+ tool_use_id: z21.string().optional(),
5615
+ agent_message: z21.string().optional()
5309
5616
  });
5310
5617
  var postToolUsePayloadSchema3 = event2("postToolUse", {
5311
- tool_name: z20.string().min(1),
5312
- tool_input: z20.unknown().optional(),
5313
- tool_output: z20.unknown().optional(),
5314
- tool_use_id: z20.string().optional(),
5315
- duration: z20.number().min(0).optional()
5618
+ tool_name: z21.string().min(1),
5619
+ tool_input: z21.unknown().optional(),
5620
+ tool_output: z21.unknown().optional(),
5621
+ tool_use_id: z21.string().optional(),
5622
+ duration: z21.number().min(0).optional()
5316
5623
  });
5317
5624
  var postToolUseFailurePayloadSchema2 = event2("postToolUseFailure", {
5318
- tool_name: z20.string().min(1),
5319
- tool_input: z20.unknown().optional(),
5320
- tool_use_id: z20.string().optional(),
5321
- error_message: z20.string().optional(),
5322
- failure_type: z20.string().optional(),
5323
- duration: z20.number().min(0).optional(),
5324
- is_interrupt: z20.boolean().optional()
5625
+ tool_name: z21.string().min(1),
5626
+ tool_input: z21.unknown().optional(),
5627
+ tool_use_id: z21.string().optional(),
5628
+ error_message: z21.string().optional(),
5629
+ failure_type: z21.string().optional(),
5630
+ duration: z21.number().min(0).optional(),
5631
+ is_interrupt: z21.boolean().optional()
5325
5632
  });
5326
5633
  var beforeShellExecutionPayloadSchema = event2("beforeShellExecution", {
5327
- command: z20.string(),
5328
- sandbox: z20.boolean().optional()
5634
+ command: z21.string(),
5635
+ sandbox: z21.boolean().optional()
5329
5636
  });
5330
5637
  var afterShellExecutionPayloadSchema = event2("afterShellExecution", {
5331
- command: z20.string(),
5332
- output: z20.string().optional(),
5333
- duration: z20.number().min(0).optional(),
5334
- sandbox: z20.boolean().optional()
5638
+ command: z21.string(),
5639
+ output: z21.string().optional(),
5640
+ duration: z21.number().min(0).optional(),
5641
+ sandbox: z21.boolean().optional()
5335
5642
  });
5336
5643
  var beforeMcpExecutionPayloadSchema = event2("beforeMCPExecution", {
5337
- tool_name: z20.string().min(1),
5338
- tool_input: z20.unknown().optional(),
5339
- url: z20.string().optional(),
5340
- command: z20.string().optional()
5644
+ tool_name: z21.string().min(1),
5645
+ tool_input: z21.unknown().optional(),
5646
+ url: z21.string().optional(),
5647
+ command: z21.string().optional()
5341
5648
  });
5342
5649
  var afterMcpExecutionPayloadSchema = event2("afterMCPExecution", {
5343
- tool_name: z20.string().min(1),
5344
- tool_input: z20.unknown().optional(),
5345
- result_json: z20.string().optional(),
5346
- duration: z20.number().min(0).optional()
5650
+ tool_name: z21.string().min(1),
5651
+ tool_input: z21.unknown().optional(),
5652
+ result_json: z21.string().optional(),
5653
+ duration: z21.number().min(0).optional()
5347
5654
  });
5348
5655
  var beforeReadFilePayloadSchema = event2("beforeReadFile", {
5349
- file_path: z20.string(),
5350
- content: z20.string().optional(),
5351
- attachments: z20.array(attachmentSchema).max(256).optional()
5656
+ file_path: z21.string(),
5657
+ content: z21.string().optional(),
5658
+ attachments: z21.array(attachmentSchema).max(256).optional()
5352
5659
  });
5353
5660
  var afterFileEditPayloadSchema = event2("afterFileEdit", {
5354
- file_path: z20.string(),
5355
- edits: z20.array(fileEditSchema).max(1024).optional()
5661
+ file_path: z21.string(),
5662
+ edits: z21.array(fileEditSchema).max(1024).optional()
5356
5663
  });
5357
5664
  var subagentStartPayloadSchema2 = event2("subagentStart", {
5358
- subagent_id: z20.string().optional(),
5359
- subagent_type: z20.string().optional(),
5360
- task: z20.string().optional(),
5361
- parent_conversation_id: z20.string().optional(),
5362
- tool_call_id: z20.string().optional(),
5363
- subagent_model: z20.string().optional(),
5364
- is_parallel_worker: z20.boolean().optional(),
5365
- git_branch: z20.string().optional()
5665
+ subagent_id: z21.string().optional(),
5666
+ subagent_type: z21.string().optional(),
5667
+ task: z21.string().optional(),
5668
+ parent_conversation_id: z21.string().optional(),
5669
+ tool_call_id: z21.string().optional(),
5670
+ subagent_model: z21.string().optional(),
5671
+ is_parallel_worker: z21.boolean().optional(),
5672
+ git_branch: z21.string().optional()
5366
5673
  });
5367
5674
  var subagentStopPayloadSchema2 = event2("subagentStop", {
5368
- subagent_type: z20.string().optional(),
5369
- status: z20.string().optional(),
5370
- task: z20.string().optional(),
5371
- description: z20.string().optional(),
5372
- summary: z20.string().optional(),
5373
- duration_ms: z20.number().min(0).optional(),
5374
- message_count: z20.number().int().min(0).optional(),
5375
- tool_call_count: z20.number().int().min(0).optional(),
5376
- loop_count: z20.number().int().min(0).optional(),
5377
- modified_files: z20.array(z20.string()).max(1024).optional(),
5378
- agent_transcript_path: z20.string().nullish()
5675
+ subagent_type: z21.string().optional(),
5676
+ status: z21.string().optional(),
5677
+ task: z21.string().optional(),
5678
+ description: z21.string().optional(),
5679
+ summary: z21.string().optional(),
5680
+ duration_ms: z21.number().min(0).optional(),
5681
+ message_count: z21.number().int().min(0).optional(),
5682
+ tool_call_count: z21.number().int().min(0).optional(),
5683
+ loop_count: z21.number().int().min(0).optional(),
5684
+ modified_files: z21.array(z21.string()).max(1024).optional(),
5685
+ agent_transcript_path: z21.string().nullish()
5379
5686
  });
5380
5687
  var preCompactPayloadSchema2 = event2("preCompact", {
5381
- trigger: z20.string().optional(),
5382
- context_usage_percent: z20.number().optional(),
5383
- context_tokens: z20.number().int().min(0).optional(),
5384
- context_window_size: z20.number().int().min(0).optional(),
5385
- message_count: z20.number().int().min(0).optional(),
5386
- messages_to_compact: z20.number().int().min(0).optional(),
5387
- is_first_compaction: z20.boolean().optional()
5688
+ trigger: z21.string().optional(),
5689
+ context_usage_percent: z21.number().optional(),
5690
+ context_tokens: z21.number().int().min(0).optional(),
5691
+ context_window_size: z21.number().int().min(0).optional(),
5692
+ message_count: z21.number().int().min(0).optional(),
5693
+ messages_to_compact: z21.number().int().min(0).optional(),
5694
+ is_first_compaction: z21.boolean().optional()
5388
5695
  });
5389
5696
  var stopPayloadSchema3 = event2("stop", {
5390
- status: z20.string().optional(),
5391
- loop_count: z20.number().int().min(0).optional(),
5697
+ status: z21.string().optional(),
5698
+ loop_count: z21.number().int().min(0).optional(),
5392
5699
  ...usageFields
5393
5700
  });
5394
- var cursorPayloadSchema = z20.discriminatedUnion("hook_event_name", [
5701
+ var cursorPayloadSchema = z21.discriminatedUnion("hook_event_name", [
5395
5702
  sessionStartPayloadSchema2,
5396
5703
  sessionEndPayloadSchema2,
5397
5704
  beforeSubmitPromptPayloadSchema,
@@ -6257,7 +6564,7 @@ var geminiCorrelationSeed = (input) => {
6257
6564
  };
6258
6565
 
6259
6566
  // src/providers/gemini/schema.ts
6260
- import { z as z21 } from "zod";
6567
+ import { z as z22 } from "zod";
6261
6568
  var GEMINI_HOOK_EVENT_NAMES = [
6262
6569
  "SessionStart",
6263
6570
  "SessionEnd",
@@ -6271,113 +6578,113 @@ var GEMINI_HOOK_EVENT_NAMES = [
6271
6578
  "PreCompress",
6272
6579
  "Notification"
6273
6580
  ];
6274
- var baseHookInputSchema = z21.object({
6275
- session_id: z21.string().min(1),
6276
- transcript_path: z21.string().optional(),
6277
- cwd: z21.string().optional(),
6278
- timestamp: z21.string().min(1).optional()
6279
- });
6280
- var llmMessageSchema = z21.object({
6281
- role: z21.enum(["user", "model", "system"]).optional(),
6282
- content: z21.union([z21.string(), z21.array(z21.unknown())]).optional()
6581
+ var baseHookInputSchema = z22.object({
6582
+ session_id: z22.string().min(1),
6583
+ transcript_path: z22.string().optional(),
6584
+ cwd: z22.string().optional(),
6585
+ timestamp: z22.string().min(1).optional()
6586
+ });
6587
+ var llmMessageSchema = z22.object({
6588
+ role: z22.enum(["user", "model", "system"]).optional(),
6589
+ content: z22.union([z22.string(), z22.array(z22.unknown())]).optional()
6283
6590
  }).loose();
6284
- var llmRequestConfigSchema = z21.object({
6285
- temperature: z21.number().optional(),
6286
- maxOutputTokens: z21.number().int().min(0).optional()
6591
+ var llmRequestConfigSchema = z22.object({
6592
+ temperature: z22.number().optional(),
6593
+ maxOutputTokens: z22.number().int().min(0).optional()
6287
6594
  }).loose();
6288
- var geminiLlmRequestSchema = z21.object({
6289
- model: z21.string().min(1).optional(),
6290
- messages: z21.array(llmMessageSchema).optional(),
6595
+ var geminiLlmRequestSchema = z22.object({
6596
+ model: z22.string().min(1).optional(),
6597
+ messages: z22.array(llmMessageSchema).optional(),
6291
6598
  config: llmRequestConfigSchema.optional(),
6292
- toolConfig: z21.unknown().optional()
6599
+ toolConfig: z22.unknown().optional()
6293
6600
  }).loose();
6294
- var geminiUsageMetadataSchema = z21.object({
6295
- promptTokenCount: z21.number().int().min(0).optional(),
6296
- cachedContentTokenCount: z21.number().int().min(0).optional(),
6297
- candidatesTokenCount: z21.number().int().min(0).optional(),
6298
- thoughtsTokenCount: z21.number().int().min(0).optional(),
6299
- totalTokenCount: z21.number().int().min(0).optional()
6601
+ var geminiUsageMetadataSchema = z22.object({
6602
+ promptTokenCount: z22.number().int().min(0).optional(),
6603
+ cachedContentTokenCount: z22.number().int().min(0).optional(),
6604
+ candidatesTokenCount: z22.number().int().min(0).optional(),
6605
+ thoughtsTokenCount: z22.number().int().min(0).optional(),
6606
+ totalTokenCount: z22.number().int().min(0).optional()
6300
6607
  }).loose();
6301
- var geminiCandidateSchema = z21.object({
6302
- content: z21.object({
6303
- role: z21.string().optional(),
6304
- parts: z21.array(z21.unknown()).optional()
6608
+ var geminiCandidateSchema = z22.object({
6609
+ content: z22.object({
6610
+ role: z22.string().optional(),
6611
+ parts: z22.array(z22.unknown()).optional()
6305
6612
  }).loose().optional(),
6306
- finishReason: z21.string().optional(),
6307
- index: z21.number().int().min(0).optional()
6613
+ finishReason: z22.string().optional(),
6614
+ index: z22.number().int().min(0).optional()
6308
6615
  }).loose();
6309
- var geminiLlmResponseSchema = z21.object({
6616
+ var geminiLlmResponseSchema = z22.object({
6310
6617
  /** Whole-response text, set by the translator from `getResponseText`. */
6311
- text: z21.string().optional(),
6312
- candidates: z21.array(geminiCandidateSchema).optional(),
6618
+ text: z22.string().optional(),
6619
+ candidates: z22.array(geminiCandidateSchema).optional(),
6313
6620
  usageMetadata: geminiUsageMetadataSchema.optional()
6314
6621
  }).loose();
6315
- var geminiMcpContextSchema = z21.object({
6316
- server_name: z21.string().optional(),
6317
- tool_name: z21.string().optional()
6622
+ var geminiMcpContextSchema = z22.object({
6623
+ server_name: z22.string().optional(),
6624
+ tool_name: z22.string().optional()
6318
6625
  }).loose();
6319
- var geminiToolResponseSchema = z21.object({
6320
- llmContent: z21.unknown().optional(),
6321
- returnDisplay: z21.unknown().optional(),
6322
- error: z21.unknown().optional()
6626
+ var geminiToolResponseSchema = z22.object({
6627
+ llmContent: z22.unknown().optional(),
6628
+ returnDisplay: z22.unknown().optional(),
6629
+ error: z22.unknown().optional()
6323
6630
  }).loose();
6324
6631
  var sessionStartInputSchema = baseHookInputSchema.extend({
6325
- hook_event_name: z21.literal("SessionStart"),
6326
- source: z21.enum(["startup", "resume", "clear"]).optional()
6632
+ hook_event_name: z22.literal("SessionStart"),
6633
+ source: z22.enum(["startup", "resume", "clear"]).optional()
6327
6634
  });
6328
6635
  var sessionEndInputSchema = baseHookInputSchema.extend({
6329
- hook_event_name: z21.literal("SessionEnd"),
6330
- reason: z21.enum(["exit", "clear", "logout", "prompt_input_exit", "other"]).optional()
6636
+ hook_event_name: z22.literal("SessionEnd"),
6637
+ reason: z22.enum(["exit", "clear", "logout", "prompt_input_exit", "other"]).optional()
6331
6638
  });
6332
6639
  var beforeAgentInputSchema = baseHookInputSchema.extend({
6333
- hook_event_name: z21.literal("BeforeAgent"),
6334
- prompt: z21.string().optional()
6640
+ hook_event_name: z22.literal("BeforeAgent"),
6641
+ prompt: z22.string().optional()
6335
6642
  });
6336
6643
  var afterAgentInputSchema = baseHookInputSchema.extend({
6337
- hook_event_name: z21.literal("AfterAgent"),
6338
- prompt: z21.string().optional(),
6339
- prompt_response: z21.string().optional(),
6340
- stop_hook_active: z21.boolean().optional()
6644
+ hook_event_name: z22.literal("AfterAgent"),
6645
+ prompt: z22.string().optional(),
6646
+ prompt_response: z22.string().optional(),
6647
+ stop_hook_active: z22.boolean().optional()
6341
6648
  });
6342
6649
  var beforeModelInputSchema = baseHookInputSchema.extend({
6343
- hook_event_name: z21.literal("BeforeModel"),
6650
+ hook_event_name: z22.literal("BeforeModel"),
6344
6651
  llm_request: geminiLlmRequestSchema
6345
6652
  });
6346
6653
  var afterModelInputSchema = baseHookInputSchema.extend({
6347
- hook_event_name: z21.literal("AfterModel"),
6654
+ hook_event_name: z22.literal("AfterModel"),
6348
6655
  llm_request: geminiLlmRequestSchema,
6349
6656
  llm_response: geminiLlmResponseSchema
6350
6657
  });
6351
6658
  var beforeToolSelectionInputSchema = baseHookInputSchema.extend({
6352
- hook_event_name: z21.literal("BeforeToolSelection"),
6659
+ hook_event_name: z22.literal("BeforeToolSelection"),
6353
6660
  llm_request: geminiLlmRequestSchema
6354
6661
  });
6355
6662
  var beforeToolInputSchema = baseHookInputSchema.extend({
6356
- hook_event_name: z21.literal("BeforeTool"),
6357
- tool_name: z21.string().min(1),
6358
- tool_input: z21.unknown().optional(),
6663
+ hook_event_name: z22.literal("BeforeTool"),
6664
+ tool_name: z22.string().min(1),
6665
+ tool_input: z22.unknown().optional(),
6359
6666
  mcp_context: geminiMcpContextSchema.optional(),
6360
- original_request_name: z21.string().min(1).optional()
6667
+ original_request_name: z22.string().min(1).optional()
6361
6668
  });
6362
6669
  var afterToolInputSchema = baseHookInputSchema.extend({
6363
- hook_event_name: z21.literal("AfterTool"),
6364
- tool_name: z21.string().min(1),
6365
- tool_input: z21.unknown().optional(),
6670
+ hook_event_name: z22.literal("AfterTool"),
6671
+ tool_name: z22.string().min(1),
6672
+ tool_input: z22.unknown().optional(),
6366
6673
  tool_response: geminiToolResponseSchema.optional(),
6367
6674
  mcp_context: geminiMcpContextSchema.optional(),
6368
- original_request_name: z21.string().min(1).optional()
6675
+ original_request_name: z22.string().min(1).optional()
6369
6676
  });
6370
6677
  var preCompressInputSchema = baseHookInputSchema.extend({
6371
- hook_event_name: z21.literal("PreCompress"),
6372
- trigger: z21.enum(["auto", "manual"]).optional()
6678
+ hook_event_name: z22.literal("PreCompress"),
6679
+ trigger: z22.enum(["auto", "manual"]).optional()
6373
6680
  });
6374
6681
  var notificationInputSchema = baseHookInputSchema.extend({
6375
- hook_event_name: z21.literal("Notification"),
6376
- notification_type: z21.string().optional(),
6377
- message: z21.string().optional(),
6378
- details: z21.unknown().optional()
6682
+ hook_event_name: z22.literal("Notification"),
6683
+ notification_type: z22.string().optional(),
6684
+ message: z22.string().optional(),
6685
+ details: z22.unknown().optional()
6379
6686
  });
6380
- var geminiHookInputSchema = z21.discriminatedUnion("hook_event_name", [
6687
+ var geminiHookInputSchema = z22.discriminatedUnion("hook_event_name", [
6381
6688
  sessionStartInputSchema,
6382
6689
  sessionEndInputSchema,
6383
6690
  beforeAgentInputSchema,
@@ -7414,8 +7721,64 @@ var createFilesystemStateStore = (options) => {
7414
7721
 
7415
7722
  // src/telemetry/spool-queue.ts
7416
7723
  import { randomBytes as randomBytes2 } from "crypto";
7417
- import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
7724
+ import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rename as rename2, stat, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
7418
7725
  import * as path3 from "path";
7726
+ var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
7727
+ total: 0,
7728
+ age: 0,
7729
+ size: 0,
7730
+ count: 0,
7731
+ rejected: 0
7732
+ });
7733
+ var SPOOL_DROPS_FILE = ".drops";
7734
+ var enqueuedAtOf = (fileName) => {
7735
+ const match = /^(\d{16})-/.exec(fileName);
7736
+ return match?.[1] === void 0 ? void 0 : Number(match[1]);
7737
+ };
7738
+ var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
7739
+ var readSpoolDropCounts = async (queueDir) => {
7740
+ try {
7741
+ const parsed = JSON.parse(await readFile3(path3.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
7742
+ if (typeof parsed !== "object" || parsed === null) {
7743
+ return EMPTY_SPOOL_DROP_COUNTS;
7744
+ }
7745
+ const record = parsed;
7746
+ const field = (name) => isCount(record[name]) ? record[name] : 0;
7747
+ return {
7748
+ total: field("total"),
7749
+ age: field("age"),
7750
+ size: field("size"),
7751
+ count: field("count"),
7752
+ rejected: field("rejected"),
7753
+ ...isCount(record.lastDroppedAt) ? { lastDroppedAt: record.lastDroppedAt } : {}
7754
+ };
7755
+ } catch {
7756
+ return EMPTY_SPOOL_DROP_COUNTS;
7757
+ }
7758
+ };
7759
+ var readSpoolQueueStats = async (queueDir) => {
7760
+ let entries;
7761
+ try {
7762
+ entries = await readdir2(queueDir);
7763
+ } catch {
7764
+ return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };
7765
+ }
7766
+ const files = entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
7767
+ let bytes = 0;
7768
+ for (const file of files) {
7769
+ try {
7770
+ bytes += (await stat(path3.join(queueDir, file))).size;
7771
+ } catch {
7772
+ }
7773
+ }
7774
+ const oldest = files[0] === void 0 ? void 0 : enqueuedAtOf(files[0]);
7775
+ return {
7776
+ batches: files.length,
7777
+ bytes,
7778
+ ...oldest === void 0 ? {} : { oldestEnqueuedAt: oldest },
7779
+ dropped: await readSpoolDropCounts(queueDir)
7780
+ };
7781
+ };
7419
7782
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
7420
7783
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
7421
7784
  var createSpoolQueue = (options) => {
@@ -7456,27 +7819,132 @@ var createSpoolQueue = (options) => {
7456
7819
  }
7457
7820
  return entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
7458
7821
  };
7822
+ const recordDrops = async (reason, dropped) => {
7823
+ if (dropped <= 0) {
7824
+ return;
7825
+ }
7826
+ try {
7827
+ const current = await readSpoolDropCounts(queueDir);
7828
+ const next = {
7829
+ ...current,
7830
+ total: current.total + dropped,
7831
+ [reason]: current[reason] + dropped,
7832
+ lastDroppedAt: options.clock.now()
7833
+ };
7834
+ const tmp = path3.join(queueDir, `.tmp-${randomBytes2(6).toString("hex")}.drops`);
7835
+ await writeFile2(tmp, JSON.stringify(next), "utf8");
7836
+ await rename2(tmp, path3.join(queueDir, SPOOL_DROPS_FILE));
7837
+ } catch {
7838
+ }
7839
+ options.logger?.warn("durable spool dropped batches", {
7840
+ "spool.queue": options.queueName,
7841
+ "spool.drop_reason": reason,
7842
+ "spool.dropped": dropped
7843
+ });
7844
+ };
7845
+ const listWithSizes = async () => {
7846
+ const names = await listSorted();
7847
+ const files = [];
7848
+ for (const name of names) {
7849
+ let bytes = 0;
7850
+ if (options.maxBytes !== void 0) {
7851
+ try {
7852
+ bytes = (await stat(path3.join(queueDir, name))).size;
7853
+ } catch {
7854
+ continue;
7855
+ }
7856
+ }
7857
+ const enqueuedAt = enqueuedAtOf(name);
7858
+ files.push({ name, bytes, ...enqueuedAt === void 0 ? {} : { enqueuedAt } });
7859
+ }
7860
+ return files;
7861
+ };
7862
+ const evict = async (files) => {
7863
+ let removed = 0;
7864
+ for (const file of files) {
7865
+ try {
7866
+ await unlink2(path3.join(queueDir, file.name));
7867
+ removed += 1;
7868
+ } catch {
7869
+ }
7870
+ }
7871
+ return removed;
7872
+ };
7873
+ const isExpired = (file, now) => options.maxAgeMillis !== void 0 && file.enqueuedAt !== void 0 && now - file.enqueuedAt > options.maxAgeMillis;
7459
7874
  const enqueue = async (batch) => {
7460
7875
  await ensureDirs();
7461
- const existing = await listSorted();
7462
- if (existing.length >= options.maxFiles) {
7876
+ const serialized = JSON.stringify(batch);
7877
+ const bytes = Buffer.byteLength(serialized, "utf8");
7878
+ const refuse = async (reason) => {
7463
7879
  options.logger?.warn("durable spool at capacity; batch dropped", {
7464
7880
  "spool.max_files": options.maxFiles,
7881
+ ...options.maxBytes === void 0 ? {} : { "spool.max_bytes": options.maxBytes },
7465
7882
  "spool.queue": options.queueName
7466
7883
  });
7884
+ await recordDrops(reason, 1);
7467
7885
  return { spooled: false, reason: "capacity-exceeded" };
7886
+ };
7887
+ if (options.maxBytes !== void 0 && bytes > options.maxBytes) {
7888
+ return refuse("size");
7889
+ }
7890
+ let queued = await listWithSizes();
7891
+ const now = options.clock.now();
7892
+ const expired = queued.filter((file) => isExpired(file, now));
7893
+ if (expired.length > 0) {
7894
+ await recordDrops("age", await evict(expired));
7895
+ queued = queued.filter((file) => !isExpired(file, now));
7896
+ }
7897
+ const overflow = options.overflow ?? "refuse-new";
7898
+ const totalBytes = () => queued.reduce((sum, file) => sum + file.bytes, 0);
7899
+ if (overflow === "refuse-new") {
7900
+ if (queued.length >= options.maxFiles) {
7901
+ return refuse("count");
7902
+ }
7903
+ if (options.maxBytes !== void 0 && totalBytes() + bytes > options.maxBytes) {
7904
+ return refuse("size");
7905
+ }
7906
+ } else {
7907
+ const overCount = Math.max(0, queued.length + 1 - options.maxFiles);
7908
+ if (overCount > 0) {
7909
+ await recordDrops("count", await evict(queued.slice(0, overCount)));
7910
+ queued = queued.slice(overCount);
7911
+ }
7912
+ if (options.maxBytes !== void 0) {
7913
+ let excess = totalBytes() + bytes - options.maxBytes;
7914
+ let cut = 0;
7915
+ while (excess > 0 && cut < queued.length) {
7916
+ excess -= queued[cut]?.bytes ?? 0;
7917
+ cut += 1;
7918
+ }
7919
+ if (cut > 0) {
7920
+ await recordDrops("size", await evict(queued.slice(0, cut)));
7921
+ queued = queued.slice(cut);
7922
+ }
7923
+ }
7468
7924
  }
7469
- const fileName = `${String(options.clock.now()).padStart(16, "0")}-${randomBytes2(6).toString("hex")}.json`;
7925
+ const fileName = `${String(now).padStart(16, "0")}-${randomBytes2(6).toString("hex")}.json`;
7470
7926
  const target = path3.join(queueDir, fileName);
7471
7927
  const tmp = path3.join(queueDir, `.tmp-${randomBytes2(6).toString("hex")}.json`);
7472
- await writeFile2(tmp, JSON.stringify(batch), "utf8");
7928
+ await writeFile2(tmp, serialized, "utf8");
7473
7929
  await rename2(tmp, target);
7474
7930
  return { spooled: true };
7475
7931
  };
7476
7932
  const drain = async (send, drainOptions) => {
7477
7933
  await ensureDirs();
7478
7934
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
7479
- const files = await listSorted();
7935
+ let files = await listSorted();
7936
+ if (options.maxAgeMillis !== void 0) {
7937
+ const now = options.clock.now();
7938
+ const expired = files.map((name) => {
7939
+ const enqueuedAt = enqueuedAtOf(name);
7940
+ return { name, bytes: 0, ...enqueuedAt === void 0 ? {} : { enqueuedAt } };
7941
+ }).filter((file) => isExpired(file, now));
7942
+ if (expired.length > 0) {
7943
+ await recordDrops("age", await evict(expired));
7944
+ const gone = new Set(expired.map((file) => file.name));
7945
+ files = files.filter((name) => !gone.has(name));
7946
+ }
7947
+ }
7480
7948
  let drained = 0;
7481
7949
  let failed = 0;
7482
7950
  let quarantined = 0;
@@ -7521,6 +7989,12 @@ var createSpoolQueue = (options) => {
7521
7989
  } catch {
7522
7990
  delivered = false;
7523
7991
  }
7992
+ if (delivered === "discard") {
7993
+ if (await unlink2(filePath).then(() => true, () => false)) {
7994
+ await recordDrops("rejected", 1);
7995
+ }
7996
+ continue;
7997
+ }
7524
7998
  if (delivered) {
7525
7999
  await unlink2(filePath).catch(() => void 0);
7526
8000
  drained += 1;
@@ -7538,7 +8012,8 @@ var createSpoolQueue = (options) => {
7538
8012
  size: async () => {
7539
8013
  await ensureDirs();
7540
8014
  return (await listSorted()).length;
7541
- }
8015
+ },
8016
+ stats: () => readSpoolQueueStats(queueDir)
7542
8017
  };
7543
8018
  };
7544
8019
 
@@ -7637,7 +8112,10 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
7637
8112
  clock: options.clock,
7638
8113
  ...options.logger === void 0 ? {} : { logger: options.logger },
7639
8114
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,
7640
- queueName: "spool-logs",
8115
+ queueName: options.queueName ?? "spool-logs",
8116
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
8117
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
8118
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
7641
8119
  validate: validateLogSpoolBatch
7642
8120
  });
7643
8121
 
@@ -7729,35 +8207,26 @@ var createFileDurableSpool = (options) => createSpoolQueue({
7729
8207
  clock: options.clock,
7730
8208
  ...options.logger === void 0 ? {} : { logger: options.logger },
7731
8209
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,
7732
- queueName: "spool",
8210
+ queueName: options.queueName ?? "spool",
8211
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
8212
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
8213
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
7733
8214
  validate: validateSpoolBatch
7734
8215
  });
7735
8216
 
7736
8217
  // src/telemetry/otlp-log-sink.ts
7737
8218
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
7738
-
7739
- // node_modules/@opentelemetry/core/build/esm/common/time.js
7740
- var NANOSECOND_DIGITS = 9;
7741
- var NANOSECOND_DIGITS_IN_MILLIS = 6;
7742
- var MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);
7743
- var SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);
7744
- function millisToHrTime(epochMillis) {
7745
- const epochSeconds = epochMillis / 1e3;
7746
- const seconds = Math.trunc(epochSeconds);
7747
- const nanos = Math.round(epochMillis % 1e3 * MILLISECONDS_TO_NANOSECONDS);
7748
- return [seconds, nanos];
7749
- }
7750
-
7751
- // node_modules/@opentelemetry/core/build/esm/ExportResult.js
7752
- var ExportResultCode;
7753
- (function(ExportResultCode2) {
7754
- ExportResultCode2[ExportResultCode2["SUCCESS"] = 0] = "SUCCESS";
7755
- ExportResultCode2[ExportResultCode2["FAILED"] = 1] = "FAILED";
7756
- })(ExportResultCode || (ExportResultCode = {}));
7757
-
7758
- // src/telemetry/otlp-log-sink.ts
8219
+ import { ExportResultCode } from "@opentelemetry/core";
8220
+ import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
7759
8221
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
7760
8222
 
8223
+ // src/telemetry/export-failure.ts
8224
+ var RETRYABLE_HTTP_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
8225
+ var isPermanentExportFailure = (result) => {
8226
+ const code = result.error?.code;
8227
+ return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
8228
+ };
8229
+
7761
8230
  // src/telemetry/exporter-resource.ts
7762
8231
  import { resourceFromAttributes } from "@opentelemetry/resources";
7763
8232
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
@@ -7794,8 +8263,8 @@ var replayResource = (attributes, policy) => {
7794
8263
  };
7795
8264
 
7796
8265
  // src/telemetry/log-records.ts
7797
- import { TraceFlags as TraceFlags2 } from "@opentelemetry/api";
7798
- import { SeverityNumber } from "@opentelemetry/api-logs";
8266
+ import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
8267
+ import { millisToHrTime as millisToHrTime2 } from "@opentelemetry/core";
7799
8268
  import {
7800
8269
  ATTR_ERROR_TYPE as ATTR_ERROR_TYPE2,
7801
8270
  ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME2,
@@ -7849,10 +8318,13 @@ var targetAttributes = (event3) => {
7849
8318
  };
7850
8319
  var usageTemporalityAttributes = (usage) => usage === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };
7851
8320
  var isPrimitiveAttribute = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean";
7852
- var passthroughHarAttributes = (resource) => {
8321
+ var PASSTHROUGH_RESOURCE_PREFIXES = Object.freeze(["har.", "factory.", "vcs."]);
8322
+ var LOCAL_ONLY_RESOURCE_PREFIX = "factory.local.";
8323
+ var isPassthroughKey = (key) => PASSTHROUGH_RESOURCE_PREFIXES.some((prefix) => key.startsWith(prefix)) && !key.startsWith(LOCAL_ONLY_RESOURCE_PREFIX) && key !== "factory.local";
8324
+ var passthroughResourceAttributes = (resource) => {
7853
8325
  const attributes = {};
7854
8326
  for (const [key, value] of Object.entries(resource.attributes)) {
7855
- if (key.startsWith("har.") && isPrimitiveAttribute(value)) {
8327
+ if (isPassthroughKey(key) && isPrimitiveAttribute(value)) {
7856
8328
  attributes[key] = value;
7857
8329
  }
7858
8330
  }
@@ -7886,7 +8358,7 @@ var exportIdentityAttributes = (event3, resource, ids) => {
7886
8358
  ...event3.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event3.provenance.providerVersion },
7887
8359
  [ATTR_OTELHOOK_WORKSPACE_ID]: event3.workspace.workspaceId,
7888
8360
  ...event3.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event3.subagentId },
7889
- ...passthroughHarAttributes(resource),
8361
+ ...passthroughResourceAttributes(resource),
7890
8362
  ...hexTraceAttributes(ids)
7891
8363
  };
7892
8364
  };
@@ -7894,6 +8366,7 @@ var exportIdentityAttributes = (event3, resource, ids) => {
7894
8366
  // src/telemetry/semconv.ts
7895
8367
  import { createHash as createHash3 } from "crypto";
7896
8368
  import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
8369
+ import { millisToHrTime } from "@opentelemetry/core";
7897
8370
  import {
7898
8371
  ATTR_ERROR_TYPE,
7899
8372
  ATTR_GEN_AI_OPERATION_NAME,
@@ -7910,7 +8383,7 @@ import {
7910
8383
  } from "@opentelemetry/semantic-conventions/incubating";
7911
8384
 
7912
8385
  // src/version.ts
7913
- var VERSION = "0.7.0";
8386
+ var VERSION = "0.9.0";
7914
8387
 
7915
8388
  // src/telemetry/semconv.ts
7916
8389
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -8057,12 +8530,12 @@ var pickTarget = (attributes) => {
8057
8530
  }
8058
8531
  return picked;
8059
8532
  };
8060
- var withoutTarget = (attributes) => {
8533
+ var withoutTarget = (attributes, resource) => {
8061
8534
  const rest = { ...attributes };
8062
8535
  for (const key of TARGET_KEYS) {
8063
8536
  delete rest[key];
8064
8537
  }
8065
- return rest;
8538
+ return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
8066
8539
  };
8067
8540
  var rankOf = (candidate) => {
8068
8541
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -8167,7 +8640,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8167
8640
  name = "session";
8168
8641
  kind = SpanKind.INTERNAL;
8169
8642
  attributes = {
8170
- ...withoutTarget(attributes),
8643
+ ...withoutTarget(attributes, resource),
8171
8644
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
8172
8645
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
8173
8646
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
@@ -8208,7 +8681,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8208
8681
  kind = SpanKind.CLIENT;
8209
8682
  attributes = {
8210
8683
  // Target keys are re-chosen below as one unit, never mixed across edges.
8211
- ...withoutTarget(attributes),
8684
+ ...withoutTarget(attributes, resource),
8212
8685
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
8213
8686
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
8214
8687
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
@@ -8694,14 +9167,14 @@ var contentAttributes = (fact, body) => ({
8694
9167
  });
8695
9168
  var buildRecord = (input) => {
8696
9169
  const severityNumber = severityFor(input.event);
8697
- const hrTime2 = millisToHrTime(input.event.occurredAt);
9170
+ const hrTime = millisToHrTime2(input.event.occurredAt);
8698
9171
  return {
8699
- hrTime: hrTime2,
9172
+ hrTime,
8700
9173
  // A hook observes an event that already happened, and this mapping is pure —
8701
9174
  // there is no clock here to read a real observation time from. Reporting the
8702
9175
  // occurrence time for both is the honest answer: it says "this is when it
8703
9176
  // happened" twice rather than inventing a second, wrong timestamp.
8704
- hrTimeObserved: hrTime2,
9177
+ hrTimeObserved: hrTime,
8705
9178
  spanContext: input.spanContext,
8706
9179
  severityNumber,
8707
9180
  severityText: SEVERITY_TEXT[severityNumber] ?? "INFO",
@@ -8791,15 +9264,6 @@ var canonicalEventsToLogRecords = (events, options) => {
8791
9264
  };
8792
9265
 
8793
9266
  // src/telemetry/otlp-log-sink.ts
8794
- var OTLP_TRACES_PATH = "/v1/traces";
8795
- var OTLP_LOGS_PATH = "/v1/logs";
8796
- var withoutTrailingSlashes = (value) => {
8797
- let end = value.length;
8798
- while (end > 0 && value.charCodeAt(end - 1) === 47) {
8799
- end -= 1;
8800
- }
8801
- return value.slice(0, end);
8802
- };
8803
9267
  var resolveLogsEndpoint = (exporter) => {
8804
9268
  if (exporter.logs.endpoint !== void 0) {
8805
9269
  return { endpoint: exporter.logs.endpoint, derived: false };
@@ -8853,8 +9317,8 @@ var deserializeRecord = (serialized, resource, scope) => {
8853
9317
  isRemote: false
8854
9318
  };
8855
9319
  return {
8856
- hrTime: millisToHrTime(serialized.timeMillis),
8857
- hrTimeObserved: millisToHrTime(serialized.observedTimeMillis),
9320
+ hrTime: millisToHrTime3(serialized.timeMillis),
9321
+ hrTimeObserved: millisToHrTime3(serialized.observedTimeMillis),
8858
9322
  ...spanContext === void 0 ? {} : { spanContext },
8859
9323
  severityNumber: serialized.severityNumber,
8860
9324
  ...serialized.severityText === void 0 ? {} : { severityText: serialized.severityText },
@@ -8876,8 +9340,11 @@ var chunk = (items, size) => {
8876
9340
  }
8877
9341
  return chunks;
8878
9342
  };
8879
- var createDisabledSink = () => {
8880
- const health = createHealthTracker("telemetry-log-sink");
9343
+ var createDisabledSink = (destination) => {
9344
+ const health = createHealthTracker(
9345
+ "telemetry-log-sink",
9346
+ destination === void 0 ? {} : { destination }
9347
+ );
8881
9348
  return {
8882
9349
  emit: (events) => {
8883
9350
  health.recordSuccess(events.length);
@@ -8916,19 +9383,24 @@ var DISABLED_DETAIL = Object.freeze({
8916
9383
  "no-endpoint": "otlp log sink disabled: no logs endpoint configured and none could be derived"
8917
9384
  });
8918
9385
  var createOtlpLogSink = (options) => {
9386
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
8919
9387
  const deliverability = describeLogsDeliverability(options.exporter);
8920
9388
  if (deliverability.status === "disabled") {
8921
9389
  if (deliverability.reason !== "logs-disabled") {
8922
9390
  options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {
8923
- "exporter.protocol": options.exporter.protocol
9391
+ "exporter.protocol": options.exporter.protocol,
9392
+ ...destinationFields
8924
9393
  });
8925
9394
  }
8926
- return createDisabledSink();
9395
+ return createDisabledSink(options.destination);
8927
9396
  }
8928
9397
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
8929
9398
  const resource = resourceFromExporterPolicy(options.exporter);
8930
9399
  const content = options.content ?? NO_LOG_CONTENT;
8931
- const health = createHealthTracker("telemetry-log-sink");
9400
+ const health = createHealthTracker(
9401
+ "telemetry-log-sink",
9402
+ options.destination === void 0 ? {} : { destination: options.destination }
9403
+ );
8932
9404
  const exporter = new OTLPLogExporter({
8933
9405
  url: deliverability.endpoint,
8934
9406
  headers: { ...options.headers },
@@ -8955,7 +9427,10 @@ var createOtlpLogSink = (options) => {
8955
9427
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
8956
9428
  );
8957
9429
  const result = await exportRecords(records);
8958
- return result.code === ExportResultCode.SUCCESS;
9430
+ if (result.code === ExportResultCode.SUCCESS) {
9431
+ return true;
9432
+ }
9433
+ return isPermanentExportFailure(result) ? "discard" : false;
8959
9434
  };
8960
9435
  const resolveCorrelations = async (events) => {
8961
9436
  if (options.correlate === void 0) {
@@ -9007,13 +9482,18 @@ var createOtlpLogSink = (options) => {
9007
9482
  continue;
9008
9483
  }
9009
9484
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
9010
- if (options.spool !== void 0) {
9485
+ const permanent = isPermanentExportFailure(result);
9486
+ if (options.spool !== void 0 && !permanent) {
9011
9487
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
9012
9488
  spooled: false,
9013
9489
  reason: "capacity-exceeded"
9014
9490
  }));
9015
9491
  if (spoolResult.spooled) {
9016
9492
  accepted += batch.length;
9493
+ options.logger?.warn("log record batch not delivered; spooled for the next invocation", {
9494
+ "export.batch_size": batch.length,
9495
+ ...destinationFields
9496
+ });
9017
9497
  continue;
9018
9498
  }
9019
9499
  }
@@ -9022,8 +9502,12 @@ var createOtlpLogSink = (options) => {
9022
9502
  createErrorInfo({
9023
9503
  code: "telemetry-export-failure",
9024
9504
  phase: "export",
9025
- detail: "collector rejected or was unreachable for a log record batch",
9026
- details: { "export.batch_size": batch.length, "export.signal": "logs" }
9505
+ detail: permanent ? "collector refused a log record batch with a non-retryable status" : "collector rejected or was unreachable for a log record batch",
9506
+ details: {
9507
+ "export.batch_size": batch.length,
9508
+ "export.signal": "logs",
9509
+ ...destinationFields
9510
+ }
9027
9511
  })
9028
9512
  );
9029
9513
  }
@@ -9069,6 +9553,7 @@ var createOtlpLogSink = (options) => {
9069
9553
  };
9070
9554
 
9071
9555
  // src/telemetry/otlp-sink.ts
9556
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
9072
9557
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
9073
9558
  var chunk2 = (items, size) => {
9074
9559
  if (size <= 0 || items.length <= size) {
@@ -9105,8 +9590,11 @@ var deserializeSpan = (serialized, resource, scope) => assembleReadableSpan({
9105
9590
  resource,
9106
9591
  instrumentationScope: scope
9107
9592
  });
9108
- var createDisabledSink2 = () => {
9109
- const health = createHealthTracker("telemetry-sink");
9593
+ var createDisabledSink2 = (destination) => {
9594
+ const health = createHealthTracker(
9595
+ "telemetry-sink",
9596
+ destination === void 0 ? {} : { destination }
9597
+ );
9110
9598
  return {
9111
9599
  emit: (events) => {
9112
9600
  health.recordSuccess(events.length);
@@ -9119,22 +9607,27 @@ var createDisabledSink2 = () => {
9119
9607
  };
9120
9608
  };
9121
9609
  var createOtlpTraceSink = (options) => {
9610
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
9122
9611
  if (!options.exporter.enabled || options.exporter.protocol === "none") {
9123
- return createDisabledSink2();
9612
+ return createDisabledSink2(options.destination);
9124
9613
  }
9125
9614
  if (options.exporter.endpoint === void 0) {
9126
- options.logger?.warn("otlp sink disabled: no endpoint configured", {});
9127
- return createDisabledSink2();
9615
+ options.logger?.warn("otlp sink disabled: no endpoint configured", destinationFields);
9616
+ return createDisabledSink2(options.destination);
9128
9617
  }
9129
9618
  if (options.exporter.protocol !== "http/protobuf") {
9130
9619
  options.logger?.warn("otlp sink: protocol not supported by this build, falling back to disabled", {
9131
- "exporter.protocol": options.exporter.protocol
9620
+ "exporter.protocol": options.exporter.protocol,
9621
+ ...destinationFields
9132
9622
  });
9133
- return createDisabledSink2();
9623
+ return createDisabledSink2(options.destination);
9134
9624
  }
9135
9625
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
9136
9626
  const resource = resourceFromExporterPolicy(options.exporter);
9137
- const health = createHealthTracker("telemetry-sink");
9627
+ const health = createHealthTracker(
9628
+ "telemetry-sink",
9629
+ options.destination === void 0 ? {} : { destination: options.destination }
9630
+ );
9138
9631
  const exporter = new OTLPTraceExporter({
9139
9632
  url: options.exporter.endpoint,
9140
9633
  headers: { ...options.headers },
@@ -9156,7 +9649,10 @@ var createOtlpTraceSink = (options) => {
9156
9649
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
9157
9650
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
9158
9651
  const result = await exportSpans(spans);
9159
- return result.code === ExportResultCode.SUCCESS;
9652
+ if (result.code === ExportResultCode2.SUCCESS) {
9653
+ return true;
9654
+ }
9655
+ return isPermanentExportFailure(result) ? "discard" : false;
9160
9656
  };
9161
9657
  const resolveCorrelations = async (events) => {
9162
9658
  if (options.correlate === void 0) {
@@ -9184,25 +9680,33 @@ var createOtlpTraceSink = (options) => {
9184
9680
  let accepted = 0;
9185
9681
  let rejected = 0;
9186
9682
  for (const batch of chunk2(spans, options.exporter.maxBatchSize)) {
9683
+ if (batch.length === 0) {
9684
+ continue;
9685
+ }
9187
9686
  let result;
9188
9687
  try {
9189
9688
  result = await exportSpans(batch);
9190
9689
  } catch (thrown) {
9191
- result = { code: ExportResultCode.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
9690
+ result = { code: ExportResultCode2.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
9192
9691
  }
9193
- if (result.code === ExportResultCode.SUCCESS) {
9692
+ if (result.code === ExportResultCode2.SUCCESS) {
9194
9693
  accepted += batch.length;
9195
9694
  health.recordSuccess(batch.length, options.clock.now());
9196
9695
  continue;
9197
9696
  }
9198
9697
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
9199
- if (options.spool !== void 0) {
9698
+ const permanent = isPermanentExportFailure(result);
9699
+ if (options.spool !== void 0 && !permanent) {
9200
9700
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
9201
9701
  spooled: false,
9202
9702
  reason: "capacity-exceeded"
9203
9703
  }));
9204
9704
  if (spoolResult.spooled) {
9205
9705
  accepted += batch.length;
9706
+ options.logger?.warn("span batch not delivered; spooled for the next invocation", {
9707
+ "export.batch_size": batch.length,
9708
+ ...destinationFields
9709
+ });
9206
9710
  continue;
9207
9711
  }
9208
9712
  }
@@ -9211,8 +9715,8 @@ var createOtlpTraceSink = (options) => {
9211
9715
  createErrorInfo({
9212
9716
  code: "telemetry-export-failure",
9213
9717
  phase: "export",
9214
- detail: "collector rejected or was unreachable for a span batch",
9215
- details: { "export.batch_size": batch.length }
9718
+ detail: permanent ? "collector refused a span batch with a non-retryable status" : "collector rejected or was unreachable for a span batch",
9719
+ details: { "export.batch_size": batch.length, ...destinationFields }
9216
9720
  })
9217
9721
  );
9218
9722
  }
@@ -9255,6 +9759,214 @@ var createOtlpTraceSink = (options) => {
9255
9759
  };
9256
9760
  };
9257
9761
 
9762
+ // src/telemetry/signal-fanout.ts
9763
+ var createSignalFanout = (options) => {
9764
+ const emit = async (events) => {
9765
+ const traces = await options.traces.emit(events);
9766
+ const logs = await options.logs.emit(events);
9767
+ const errors = [...traces.errors, ...logs.errors];
9768
+ return {
9769
+ accepted: traces.accepted + logs.accepted,
9770
+ rejected: traces.rejected + logs.rejected,
9771
+ errors
9772
+ };
9773
+ };
9774
+ const flush = async () => {
9775
+ await options.traces.flush().catch(() => void 0);
9776
+ await options.logs.flush().catch(() => void 0);
9777
+ };
9778
+ const shutdown = async () => {
9779
+ await options.traces.shutdown().catch(() => void 0);
9780
+ await options.logs.shutdown().catch(() => void 0);
9781
+ };
9782
+ return {
9783
+ emit,
9784
+ flush,
9785
+ shutdown,
9786
+ health: () => [
9787
+ options.traces.health(),
9788
+ options.logs.health()
9789
+ ]
9790
+ };
9791
+ };
9792
+ var shareCorrelationPerBatch = (correlate) => {
9793
+ let pending;
9794
+ return (events) => {
9795
+ if (pending?.events === events) {
9796
+ return pending.result;
9797
+ }
9798
+ const result = correlate(events);
9799
+ pending = { events, result };
9800
+ return result;
9801
+ };
9802
+ };
9803
+
9804
+ // src/telemetry/export-destinations.ts
9805
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs" } : { traces: `destinations/${destination}/spool`, logs: `destinations/${destination}/spool-logs` };
9806
+ var exporterPolicyForDestination = (exporter, destination) => {
9807
+ if (destination.source === "exporter") {
9808
+ return exporter;
9809
+ }
9810
+ const { destinations, endpoint, logs, ...shared } = exporter;
9811
+ void destinations;
9812
+ void endpoint;
9813
+ const tracesEndpoint = destination.tracesEndpoint ?? destination.endpoint;
9814
+ const derivedLogs = destination.logsEndpoint ?? (destination.endpoint === void 0 ? void 0 : (() => {
9815
+ const derived = resolveLogsEndpoint({
9816
+ ...exporter,
9817
+ endpoint: destination.endpoint,
9818
+ logs: { enabled: true, includeContent: false, maxBatchSize: logs.maxBatchSize }
9819
+ });
9820
+ return "endpoint" in derived ? derived.endpoint : void 0;
9821
+ })());
9822
+ return {
9823
+ ...shared,
9824
+ protocol: destination.protocol,
9825
+ ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
9826
+ headerNames: Object.keys(destination.headers).sort(),
9827
+ logs: {
9828
+ ...logs,
9829
+ enabled: destination.signals.logs,
9830
+ ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
9831
+ }
9832
+ };
9833
+ };
9834
+ var createOptedOutTraceSink = (destination) => {
9835
+ const health = createHealthTracker(
9836
+ "telemetry-sink",
9837
+ destination === void 0 ? {} : { destination }
9838
+ );
9839
+ return {
9840
+ emit: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
9841
+ flush: () => Promise.resolve(),
9842
+ shutdown: () => Promise.resolve(),
9843
+ health: () => health.snapshot(),
9844
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
9845
+ };
9846
+ };
9847
+ var createExportDestinationSinks = (options) => {
9848
+ const labelled = hasConfiguredDestinations(options.exporter);
9849
+ const spoolPolicy = effectiveSpoolPolicy(options.exporter);
9850
+ const destinations = [];
9851
+ const skipped = [];
9852
+ for (const destination of resolveExportDestinations(options.exporter)) {
9853
+ let headers;
9854
+ let logHeaders;
9855
+ if (destination.source === "exporter") {
9856
+ headers = options.defaultHeaders;
9857
+ logHeaders = options.defaultLogHeaders ?? options.defaultHeaders;
9858
+ } else {
9859
+ const resolved = resolveDestinationHeaders(destination.headers, options.headerEnvironment);
9860
+ if (resolved.missingVariables.length > 0) {
9861
+ options.logger?.warn("export destination skipped: a header references an unset environment variable", {
9862
+ "export.destination": destination.name,
9863
+ "config.variables": [...resolved.missingVariables]
9864
+ });
9865
+ skipped.push({
9866
+ name: destination.name,
9867
+ reason: "header-variable-missing",
9868
+ missingVariables: resolved.missingVariables
9869
+ });
9870
+ continue;
9871
+ }
9872
+ headers = resolved.values;
9873
+ logHeaders = resolved.values;
9874
+ }
9875
+ const label = labelled ? destination.name : void 0;
9876
+ const policy = exporterPolicyForDestination(options.exporter, destination);
9877
+ const queues = spoolQueueNamesFor(destination.name);
9878
+ const bounds = {
9879
+ maxSpoolFiles: spoolPolicy.maxBatches,
9880
+ maxBytes: spoolPolicy.maxBytes,
9881
+ maxAgeMillis: spoolPolicy.maxAgeMillis,
9882
+ overflow: "drop-oldest"
9883
+ };
9884
+ const shared = {
9885
+ providerId: options.providerId,
9886
+ installationId: options.installationId,
9887
+ clock: options.clock,
9888
+ ...options.logger === void 0 ? {} : { logger: options.logger }
9889
+ };
9890
+ const spool = options.spoolRootDir === void 0 || !destination.signals.traces ? void 0 : createFileDurableSpool({
9891
+ rootDir: options.spoolRootDir,
9892
+ ...shared,
9893
+ ...bounds,
9894
+ queueName: queues.traces
9895
+ });
9896
+ const logSpool = options.spoolRootDir === void 0 || !destination.signals.logs ? void 0 : createFileDurableLogSpool({
9897
+ rootDir: options.spoolRootDir,
9898
+ ...shared,
9899
+ ...bounds,
9900
+ queueName: queues.logs
9901
+ });
9902
+ const sinkShared = {
9903
+ exporter: policy,
9904
+ ...shared,
9905
+ ...options.correlate === void 0 ? {} : { correlate: options.correlate },
9906
+ ...label === void 0 ? {} : { destination: label }
9907
+ };
9908
+ const traces = destination.signals.traces ? createOtlpTraceSink({
9909
+ ...sinkShared,
9910
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
9911
+ ...spool === void 0 ? {} : { spool }
9912
+ }) : createOptedOutTraceSink(label);
9913
+ const logs = createOtlpLogSink({
9914
+ ...sinkShared,
9915
+ ...logHeaders === void 0 || Object.keys(logHeaders).length === 0 ? {} : { headers: logHeaders },
9916
+ ...logSpool === void 0 ? {} : { spool: logSpool },
9917
+ content: options.logContent
9918
+ });
9919
+ destinations.push({
9920
+ name: destination.name,
9921
+ traces,
9922
+ logs,
9923
+ ...spool === void 0 ? {} : { spool },
9924
+ ...logSpool === void 0 ? {} : { logSpool }
9925
+ });
9926
+ }
9927
+ return { destinations, skipped };
9928
+ };
9929
+ var createDestinationFanout = (destinations) => {
9930
+ const fanouts = destinations.map((destination) => ({
9931
+ name: destination.name,
9932
+ sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
9933
+ }));
9934
+ const only = fanouts.length === 1 ? fanouts[0] : void 0;
9935
+ if (only !== void 0) {
9936
+ return only.sink;
9937
+ }
9938
+ const emit = async (events) => {
9939
+ const results = await Promise.all(
9940
+ fanouts.map(
9941
+ (fanout) => fanout.sink.emit(events).catch(
9942
+ (thrown) => ({
9943
+ accepted: 0,
9944
+ rejected: events.length,
9945
+ errors: [errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })]
9946
+ })
9947
+ )
9948
+ )
9949
+ );
9950
+ const errors = results.flatMap((result) => result.errors);
9951
+ return {
9952
+ accepted: results.reduce((sum, result) => sum + result.accepted, 0),
9953
+ rejected: results.reduce((sum, result) => sum + result.rejected, 0),
9954
+ errors
9955
+ };
9956
+ };
9957
+ const settleAll = async (run) => {
9958
+ await Promise.all(fanouts.map((fanout) => run(fanout.sink).catch(() => void 0)));
9959
+ };
9960
+ return {
9961
+ emit,
9962
+ // Each destination drains its own spool in its flush; in parallel, so one
9963
+ // unreachable destination's drain cannot use up the others' flush window.
9964
+ flush: () => settleAll((sink) => sink.flush()),
9965
+ shutdown: () => settleAll((sink) => sink.shutdown()),
9966
+ health: () => fanouts.flatMap((fanout) => fanout.sink.health())
9967
+ };
9968
+ };
9969
+
9258
9970
  // src/cli/doctor.ts
9259
9971
  var DOCTOR_STATE_NAMESPACE = "doctor";
9260
9972
  var PROBE_KEY = "diagnostics:doctor-probe";
@@ -9325,6 +10037,12 @@ var collectDoctorReport = async (command, io) => {
9325
10037
  }
9326
10038
  }
9327
10039
  const traceHeaders = resolveCliExporterHeaders(command.policy, io).traces;
10040
+ const destinations = await describeDoctorDestinations(
10041
+ resolved.config.exporter,
10042
+ io.env,
10043
+ command.policy.spoolDisabled === true ? void 0 : { rootDir: stateRootDir, installationId }
10044
+ );
10045
+ const withDestinations = hasConfiguredDestinations(resolved.config.exporter);
9328
10046
  const sink = createOtlpTraceSink({
9329
10047
  exporter: resolved.config.exporter,
9330
10048
  ...Object.keys(traceHeaders).length === 0 ? {} : { headers: traceHeaders },
@@ -9333,11 +10051,13 @@ var collectDoctorReport = async (command, io) => {
9333
10051
  clock,
9334
10052
  logger
9335
10053
  });
9336
- const exporterConfigured = resolved.config.exporter.enabled && resolved.config.exporter.protocol === "http/protobuf" && resolved.config.exporter.endpoint !== void 0;
10054
+ const legacyConfigured = resolved.config.exporter.enabled && resolved.config.exporter.protocol === "http/protobuf" && resolved.config.exporter.endpoint !== void 0;
10055
+ const routable = destinations.filter((destination) => destination.enabled && destination.ok);
10056
+ const exporterConfigured = legacyConfigured || withDestinations && resolved.config.exporter.enabled && routable.length > 0;
9337
10057
  checks.push({
9338
10058
  name: "exporter",
9339
10059
  ok: exporterConfigured,
9340
- detail: exporterConfigured ? "OTLP HTTP/protobuf exporter is configured" : !resolved.config.exporter.enabled ? "exporter is disabled; events are accepted and discarded" : resolved.config.exporter.endpoint === void 0 ? "exporter is enabled but no endpoint is configured" : `protocol ${resolved.config.exporter.protocol} is not supported by this build`
10060
+ detail: exporterConfigured ? withDestinations ? `OTLP HTTP/protobuf export to ${String(routable.length)} destination(s): ${routable.map((destination) => destination.name).join(", ")}` : "OTLP HTTP/protobuf exporter is configured" : !resolved.config.exporter.enabled ? "exporter is disabled; events are accepted and discarded" : resolved.config.exporter.endpoint === void 0 && !withDestinations ? "exporter is enabled but no endpoint is configured" : withDestinations ? "exporter.destinations is set but no destination can be sent to" : `protocol ${resolved.config.exporter.protocol} is not supported by this build`
9341
10061
  });
9342
10062
  const logs = describeLogsDeliverability(resolved.config.exporter);
9343
10063
  checks.push({
@@ -9345,6 +10065,14 @@ var collectDoctorReport = async (command, io) => {
9345
10065
  ok: logs.status === "configured" || logs.reason === "logs-disabled",
9346
10066
  detail: logs.status === "configured" ? `OTLP HTTP/protobuf logs exporter is configured${logs.derivedEndpoint ? " (endpoint derived from the trace endpoint)" : ""}; content ${resolved.config.exporter.logs.includeContent ? "permitted" : "disabled"}` : logs.reason === "logs-disabled" ? "logs are disabled; only traces are exported" : logs.reason === "no-endpoint" ? "logs are enabled but no endpoint is configured and none could be derived" : `logs are enabled but unroutable: ${logs.reason}`
9347
10067
  });
10068
+ if (withDestinations) {
10069
+ const failing = destinations.filter((destination) => destination.enabled && !destination.ok);
10070
+ checks.push({
10071
+ name: "destinations",
10072
+ ok: failing.length === 0,
10073
+ detail: failing.length === 0 ? `${String(destinations.filter((destination) => destination.enabled).length)} enabled destination(s) resolve` : failing.map((destination) => `${destination.name}: ${destination.detail}`).join("; ")
10074
+ });
10075
+ }
9348
10076
  const health = summarizeHealth([sink.health()]);
9349
10077
  await sink.shutdown();
9350
10078
  checks.push({
@@ -9379,6 +10107,7 @@ var collectDoctorReport = async (command, io) => {
9379
10107
  ...spooledBatches === void 0 ? {} : { spooledBatches },
9380
10108
  ...spooledLogBatches === void 0 ? {} : { spooledLogBatches }
9381
10109
  },
10110
+ destinations,
9382
10111
  providers: providers.map((entry) => ({
9383
10112
  id: entry.id,
9384
10113
  version: entry.version,
@@ -9387,6 +10116,109 @@ var collectDoctorReport = async (command, io) => {
9387
10116
  }))
9388
10117
  };
9389
10118
  };
10119
+ var formatBytes = (bytes) => bytes < 1024 ? `${String(bytes)} B` : `${(bytes / 1024).toFixed(1)} KiB`;
10120
+ var describeDestinationLine = (destination) => {
10121
+ const parts = [];
10122
+ parts.push(destination.enabled ? destination.signals.join("+") || "no signals" : "disabled");
10123
+ if (destination.tracesEndpointOrigin !== void 0) {
10124
+ parts.push(`traces -> ${destination.tracesEndpointOrigin}`);
10125
+ }
10126
+ if (destination.logsEndpointOrigin !== void 0) {
10127
+ parts.push(`logs -> ${destination.logsEndpointOrigin}`);
10128
+ }
10129
+ if (destination.headerNames.length > 0) {
10130
+ parts.push(`headers ${destination.headerNames.join(", ")}`);
10131
+ }
10132
+ if (destination.missingVariables.length > 0) {
10133
+ parts.push(`MISSING ${destination.missingVariables.join(", ")}`);
10134
+ }
10135
+ for (const [signal, stats] of Object.entries(destination.spool ?? {})) {
10136
+ if (stats.batches > 0 || stats.dropped.total > 0) {
10137
+ const dropped = stats.dropped;
10138
+ parts.push(
10139
+ `${signal} spool ${String(stats.batches)} batch(es) ${formatBytes(stats.bytes)}, dropped ${String(
10140
+ dropped.total
10141
+ )} (age ${String(dropped.age)}, size ${String(dropped.size)}, count ${String(
10142
+ dropped.count
10143
+ )}, rejected ${String(dropped.rejected)})`
10144
+ );
10145
+ }
10146
+ }
10147
+ return `${destination.ok ? "ok " : "FAIL"} destination ${destination.name}: ${parts.join("; ")}`;
10148
+ };
10149
+ var sumSpoolStats = (all) => {
10150
+ const oldest = all.map((stats) => stats.oldestEnqueuedAt).filter((value) => value !== void 0);
10151
+ const lastDropped = all.map((stats) => stats.dropped.lastDroppedAt).filter((value) => value !== void 0);
10152
+ return {
10153
+ batches: all.reduce((sum, stats) => sum + stats.batches, 0),
10154
+ bytes: all.reduce((sum, stats) => sum + stats.bytes, 0),
10155
+ ...oldest.length === 0 ? {} : { oldestEnqueuedAt: Math.min(...oldest) },
10156
+ dropped: {
10157
+ total: all.reduce((sum, stats) => sum + stats.dropped.total, 0),
10158
+ age: all.reduce((sum, stats) => sum + stats.dropped.age, 0),
10159
+ size: all.reduce((sum, stats) => sum + stats.dropped.size, 0),
10160
+ count: all.reduce((sum, stats) => sum + stats.dropped.count, 0),
10161
+ rejected: all.reduce((sum, stats) => sum + stats.dropped.rejected, 0),
10162
+ ...lastDropped.length === 0 ? {} : { lastDroppedAt: Math.max(...lastDropped) }
10163
+ }
10164
+ };
10165
+ };
10166
+ var inspectQueue = async (spool, queueName) => {
10167
+ let namespaces;
10168
+ try {
10169
+ namespaces = await readdir3(spool.rootDir);
10170
+ } catch {
10171
+ namespaces = [];
10172
+ }
10173
+ const installation = sanitizeSegment(spool.installationId);
10174
+ const stats = await Promise.all(
10175
+ namespaces.map(
10176
+ (namespace) => readSpoolQueueStats(path4.join(spool.rootDir, namespace, installation, queueName))
10177
+ )
10178
+ );
10179
+ return stats.length === 0 ? { batches: 0, bytes: 0, dropped: EMPTY_SPOOL_DROP_COUNTS } : sumSpoolStats(stats);
10180
+ };
10181
+ var describeDoctorDestinations = async (exporter, environment, spool) => {
10182
+ const configured = new Map(
10183
+ (exporter.destinations ?? []).map((destination) => [destination.name, destination])
10184
+ );
10185
+ const resolvedNames = new Set(resolveExportDestinations(exporter).map((destination) => destination.name));
10186
+ const descriptions = describeExportDestinations(exporter);
10187
+ return Promise.all(
10188
+ descriptions.map(async (description) => {
10189
+ const headers = configured.get(description.name)?.headers ?? {};
10190
+ const missingVariables = resolveDestinationHeaders(headers, environment).missingVariables;
10191
+ const sends = description.signals.length > 0;
10192
+ const reachable = description.signals.includes("traces") && description.tracesEndpointOrigin !== void 0 || description.signals.includes("logs") && description.logsEndpointOrigin !== void 0;
10193
+ let detail = "resolves";
10194
+ let ok = true;
10195
+ if (!description.enabled) {
10196
+ detail = "disabled";
10197
+ } else if (missingVariables.length > 0) {
10198
+ ok = false;
10199
+ detail = `header variable(s) not set: ${missingVariables.join(", ")}; skipped until they are`;
10200
+ } else if (description.protocol !== "http/protobuf") {
10201
+ ok = description.protocol === "none";
10202
+ detail = description.protocol === "none" ? "protocol is none; nothing is sent" : `protocol ${description.protocol} is not supported by this build`;
10203
+ } else if (!sends || !reachable) {
10204
+ ok = false;
10205
+ detail = "no endpoint for any signal it receives";
10206
+ }
10207
+ const queues = spoolQueueNamesFor(description.name);
10208
+ const spoolStats = spool === void 0 || !resolvedNames.has(description.name) ? void 0 : {
10209
+ ...description.signals.includes("traces") ? { traces: await inspectQueue(spool, queues.traces) } : {},
10210
+ ...description.signals.includes("logs") ? { logs: await inspectQueue(spool, queues.logs) } : {}
10211
+ };
10212
+ return {
10213
+ ...description,
10214
+ missingVariables,
10215
+ ok,
10216
+ detail,
10217
+ ...spoolStats === void 0 ? {} : { spool: spoolStats }
10218
+ };
10219
+ })
10220
+ );
10221
+ };
9390
10222
  var runDoctorCommand = async (command, io) => {
9391
10223
  const report = await collectDoctorReport(command, io);
9392
10224
  if (command.json) {
@@ -9407,6 +10239,16 @@ var runDoctorCommand = async (command, io) => {
9407
10239
  if (report.state.spooledLogBatches !== void 0) {
9408
10240
  writeLine(io.stdout, `spooled log batches: ${String(report.state.spooledLogBatches)}`);
9409
10241
  }
10242
+ const listDestinations = report.config["exporter.destination_names"] !== void 0 || report.destinations.some(
10243
+ (destination) => Object.values(destination.spool ?? {}).some(
10244
+ (stats) => stats.dropped.total > 0
10245
+ )
10246
+ );
10247
+ if (listDestinations) {
10248
+ for (const destination of report.destinations) {
10249
+ writeLine(io.stdout, describeDestinationLine(destination));
10250
+ }
10251
+ }
9410
10252
  for (const note of report.configNotes) {
9411
10253
  writeLine(io.stdout, `note: ${note}`);
9412
10254
  }
@@ -10275,7 +11117,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
10275
11117
  );
10276
11118
 
10277
11119
  // src/install/scopes.ts
10278
- import * as path4 from "path";
11120
+ import * as path5 from "path";
10279
11121
  var REGISTRATION_SCOPES = Object.freeze([
10280
11122
  "global",
10281
11123
  "project"
@@ -10343,15 +11185,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
10343
11185
  var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
10344
11186
  (entry) => entry.providerId === providerId && entry.scope === scope
10345
11187
  );
10346
- var resolveInstallPath = (location, roots) => path4.resolve(
11188
+ var resolveInstallPath = (location, roots) => path5.resolve(
10347
11189
  location.scope === "global" ? roots.homeDir : roots.projectDir,
10348
11190
  ...location.segments
10349
11191
  );
10350
11192
 
10351
11193
  // src/install/document.ts
10352
11194
  import { randomBytes as randomBytes3 } from "crypto";
10353
- import { chmod, mkdir as mkdir3, open as open2, readFile as readFile4, rename as rename3, stat, unlink as unlink3 } from "fs/promises";
10354
- import * as path5 from "path";
11195
+ import { chmod, mkdir as mkdir3, open as open2, readFile as readFile4, rename as rename3, stat as stat2, unlink as unlink3 } from "fs/promises";
11196
+ import * as path6 from "path";
10355
11197
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
10356
11198
  indent: " ",
10357
11199
  eol: "\n",
@@ -10422,15 +11264,15 @@ var renameWithRetry = async (from, to) => {
10422
11264
  var NEW_DOCUMENT_MODE = 384;
10423
11265
  var TEMPORARY_DOCUMENT_MODE = 384;
10424
11266
  var writeDocumentAtomically = async (filePath, contents) => {
10425
- const directory = path5.dirname(filePath);
11267
+ const directory = path6.dirname(filePath);
10426
11268
  await mkdir3(directory, { recursive: true });
10427
- const temporary = path5.join(
11269
+ const temporary = path6.join(
10428
11270
  directory,
10429
- `.${path5.basename(filePath)}.${randomBytes3(6).toString("hex")}.tmp`
11271
+ `.${path6.basename(filePath)}.${randomBytes3(6).toString("hex")}.tmp`
10430
11272
  );
10431
11273
  let existingMode;
10432
11274
  try {
10433
- existingMode = (await stat(filePath)).mode & 4095;
11275
+ existingMode = (await stat2(filePath)).mode & 4095;
10434
11276
  } catch (thrown) {
10435
11277
  if (!isErrnoException3(thrown, "ENOENT")) {
10436
11278
  throw thrown;
@@ -10455,12 +11297,12 @@ var writeDocumentAtomically = async (filePath, contents) => {
10455
11297
 
10456
11298
  // src/install/file-lock.ts
10457
11299
  import { randomBytes as randomBytes4 } from "crypto";
10458
- import { mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat2, unlink as unlink4 } from "fs/promises";
10459
- import * as path6 from "path";
11300
+ import { mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat3, unlink as unlink4 } from "fs/promises";
11301
+ import * as path7 from "path";
10460
11302
  var FileLockTimeoutError = class extends Error {
10461
11303
  constructor(lockPath, timeoutMillis) {
10462
11304
  super(
10463
- `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path6.basename(lockPath)}`
11305
+ `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path7.basename(lockPath)}`
10464
11306
  );
10465
11307
  this.name = "FileLockTimeoutError";
10466
11308
  }
@@ -10520,7 +11362,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
10520
11362
  } catch {
10521
11363
  }
10522
11364
  try {
10523
- const stats = await stat2(lockPath);
11365
+ const stats = await stat3(lockPath);
10524
11366
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
10525
11367
  } catch (thrown) {
10526
11368
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -10532,7 +11374,7 @@ var withFileLock = async (filePath, options, fn) => {
10532
11374
  const pollIntervalMillis = options.pollIntervalMillis ?? 25;
10533
11375
  const lockPath = lockPathFor(filePath);
10534
11376
  const startedAt = options.clock.monotonicMillis();
10535
- await mkdir4(path6.dirname(filePath), { recursive: true });
11377
+ await mkdir4(path7.dirname(filePath), { recursive: true });
10536
11378
  for (; ; ) {
10537
11379
  const token = randomBytes4(16).toString("hex");
10538
11380
  let acquired = false;
@@ -10580,7 +11422,7 @@ var withFileLock = async (filePath, options, fn) => {
10580
11422
 
10581
11423
  // src/install/lifecycle.ts
10582
11424
  import { readFile as readFile6 } from "fs/promises";
10583
- import * as path7 from "path";
11425
+ import * as path8 from "path";
10584
11426
  var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
10585
11427
  var unsupportedOutcome = (providerId, scope, reason) => ({
10586
11428
  providerId,
@@ -10597,7 +11439,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
10597
11439
  var resolveTarget = (providerId, scope, request) => {
10598
11440
  if (request.configFile !== void 0) {
10599
11441
  return {
10600
- configPath: path7.resolve(request.configFile),
11442
+ configPath: path8.resolve(request.configFile),
10601
11443
  evidence: "path supplied by the caller with --settings-file"
10602
11444
  };
10603
11445
  }
@@ -10614,14 +11456,14 @@ var resolveTarget = (providerId, scope, request) => {
10614
11456
  };
10615
11457
  };
10616
11458
  var codexFeatureNote = async (configPath) => {
10617
- const tomlPath = path7.join(path7.dirname(configPath), "config.toml");
11459
+ const tomlPath = path8.join(path8.dirname(configPath), "config.toml");
10618
11460
  let raw;
10619
11461
  try {
10620
11462
  raw = await readFile6(tomlPath, "utf8");
10621
11463
  } catch {
10622
11464
  return void 0;
10623
11465
  }
10624
- return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path7.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
11466
+ return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path8.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
10625
11467
  };
10626
11468
  var readState = async (configPath) => {
10627
11469
  const read = await readJsonDocument(configPath);
@@ -10633,12 +11475,12 @@ var readState = async (configPath) => {
10633
11475
  case "unparseable":
10634
11476
  return {
10635
11477
  status: "blocked",
10636
- problem: `${path7.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
11478
+ problem: `${path8.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
10637
11479
  };
10638
11480
  case "unreadable":
10639
11481
  return {
10640
11482
  status: "failed",
10641
- problem: `${path7.basename(configPath)} could not be read (${read.detail})`
11483
+ problem: `${path8.basename(configPath)} could not be read (${read.detail})`
10642
11484
  };
10643
11485
  }
10644
11486
  };
@@ -10750,7 +11592,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
10750
11592
  missingEvents: [],
10751
11593
  notes,
10752
11594
  problems: planned.conflicts.map(
10753
- (conflict) => `${path7.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
11595
+ (conflict) => `${path8.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
10754
11596
  )
10755
11597
  };
10756
11598
  }
@@ -10761,7 +11603,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
10761
11603
  changed: false,
10762
11604
  registeredEvents: [],
10763
11605
  missingEvents: [],
10764
- notes: [...notes, `${path7.basename(configPath)} does not exist; nothing to remove`],
11606
+ notes: [...notes, `${path8.basename(configPath)} does not exist; nothing to remove`],
10765
11607
  problems: []
10766
11608
  };
10767
11609
  }
@@ -10804,7 +11646,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
10804
11646
  missingEvents: [],
10805
11647
  notes,
10806
11648
  problems: [
10807
- `could not write ${path7.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
11649
+ `could not write ${path8.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
10808
11650
  ]
10809
11651
  };
10810
11652
  }
@@ -10831,7 +11673,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
10831
11673
  missingEvents: [],
10832
11674
  notes,
10833
11675
  problems: [
10834
- thrown instanceof Error ? `${path7.basename(configPath)}: ${thrown.message}` : `${path7.basename(configPath)}: the configuration file could not be locked`
11676
+ thrown instanceof Error ? `${path8.basename(configPath)}: ${thrown.message}` : `${path8.basename(configPath)}: the configuration file could not be locked`
10835
11677
  ]
10836
11678
  };
10837
11679
  }
@@ -10927,9 +11769,9 @@ var runProvidersCommand = (command, io) => {
10927
11769
 
10928
11770
  // src/cli/registration.ts
10929
11771
  import * as os2 from "os";
10930
- import * as path8 from "path";
10931
- var resolveProjectDir = (command, io) => path8.resolve(command.projectDir ?? io.env.PWD ?? process.cwd());
10932
- var resolveHomeDir = (command, io) => path8.resolve(command.homeDir ?? io.homeDir ?? os2.homedir());
11772
+ import * as path9 from "path";
11773
+ var resolveProjectDir = (command, io) => path9.resolve(command.projectDir ?? io.env.PWD ?? process.cwd());
11774
+ var resolveHomeDir = (command, io) => path9.resolve(command.homeDir ?? io.homeDir ?? os2.homedir());
10933
11775
  var collectRegistrationReport = async (command, io) => runRegistrationLifecycle({
10934
11776
  action: command.name,
10935
11777
  // A bare `diagnose` sweeps the providers this tool can locate by itself.
@@ -11010,7 +11852,7 @@ var runRegistrationCommand = async (command, io) => {
11010
11852
  };
11011
11853
 
11012
11854
  // src/cli/run.ts
11013
- import * as path11 from "path";
11855
+ import * as path12 from "path";
11014
11856
 
11015
11857
  // src/lifecycle/dedup.ts
11016
11858
  import { randomBytes as randomBytes5 } from "crypto";
@@ -11747,7 +12589,7 @@ var createUsageAccumulator = (deps) => {
11747
12589
  };
11748
12590
 
11749
12591
  // src/runtime/hook.ts
11750
- import { z as z22 } from "zod";
12592
+ import { z as z23 } from "zod";
11751
12593
 
11752
12594
  // src/runtime/delivery.ts
11753
12595
  var PROVIDER_SCOPE_PREFIX = "provider-session";
@@ -11820,16 +12662,16 @@ var createDeterministicIdGenerator = (options = {}) => {
11820
12662
  };
11821
12663
 
11822
12664
  // src/runtime/target-resolution.ts
11823
- import * as path9 from "path";
12665
+ import * as path10 from "path";
11824
12666
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
11825
12667
  var absolutePathsOf = (hint) => {
11826
- const base = hint.baseDirectory !== void 0 && path9.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
12668
+ const base = hint.baseDirectory !== void 0 && path10.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
11827
12669
  const resolved = [];
11828
12670
  for (const candidate of hint.paths) {
11829
- if (path9.isAbsolute(candidate)) {
11830
- resolved.push(path9.resolve(candidate));
12671
+ if (path10.isAbsolute(candidate)) {
12672
+ resolved.push(path10.resolve(candidate));
11831
12673
  } else if (base !== void 0) {
11832
- resolved.push(path9.resolve(base, candidate));
12674
+ resolved.push(path10.resolve(base, candidate));
11833
12675
  } else {
11834
12676
  return void 0;
11835
12677
  }
@@ -11908,7 +12750,7 @@ var resolveEventTargets = async (input) => {
11908
12750
  };
11909
12751
 
11910
12752
  // src/runtime/hook.ts
11911
- var usageScopeSchema = z22.enum(["session", "generation", "subagent"]);
12753
+ var usageScopeSchema = z23.enum(["session", "generation", "subagent"]);
11912
12754
  var classifyDurability = (input) => {
11913
12755
  if (!input.attempted) {
11914
12756
  return "nothing-to-deliver";
@@ -12664,8 +13506,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
12664
13506
  };
12665
13507
 
12666
13508
  // src/runtime/git-worktree.ts
12667
- import { lstat, open as open4, stat as stat3 } from "fs/promises";
12668
- import * as path10 from "path";
13509
+ import { lstat, open as open4, stat as stat4 } from "fs/promises";
13510
+ import * as path11 from "path";
12669
13511
  var MAX_WORKTREE_WALK_DEPTH = 128;
12670
13512
  var MAX_GIT_FILE_BYTES = 4096;
12671
13513
  var MAX_CACHE_ENTRIES = 1024;
@@ -12697,7 +13539,7 @@ var parseHeadBranch = (head) => {
12697
13539
  return branch;
12698
13540
  };
12699
13541
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
12700
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path10.resolve(base, target);
13542
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path11.resolve(base, target);
12701
13543
  var parseGitDirFile = (content, worktreeRoot) => {
12702
13544
  const line = firstLine(content);
12703
13545
  return resolveGitPath(
@@ -12717,26 +13559,26 @@ var isMissing = async (filePath) => {
12717
13559
  };
12718
13560
  var isDirectory = async (directory) => {
12719
13561
  try {
12720
- return (await stat3(directory)).isDirectory();
13562
+ return (await stat4(directory)).isDirectory();
12721
13563
  } catch {
12722
13564
  return false;
12723
13565
  }
12724
13566
  };
12725
13567
  var repositoryOf = async (worktreeRoot, gitDir) => {
12726
- const commonDirFile = path10.join(gitDir, "commondir");
13568
+ const commonDirFile = path11.join(gitDir, "commondir");
12727
13569
  const content = await readBounded(commonDirFile);
12728
13570
  if (content === void 0) {
12729
13571
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
12730
13572
  }
12731
13573
  const commonDir = parseCommonDirFile(content, gitDir);
12732
- const mainRoot = commonDir !== void 0 && path10.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path10.dirname(commonDir) : void 0;
13574
+ const mainRoot = commonDir !== void 0 && path11.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path11.dirname(commonDir) : void 0;
12733
13575
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
12734
13576
  };
12735
13577
  var probeDirectory = async (directory) => {
12736
- const dotGit = path10.join(directory, ".git");
13578
+ const dotGit = path11.join(directory, ".git");
12737
13579
  let info;
12738
13580
  try {
12739
- info = await stat3(dotGit);
13581
+ info = await stat4(dotGit);
12740
13582
  } catch {
12741
13583
  return ABSENT;
12742
13584
  }
@@ -12750,7 +13592,7 @@ var probeDirectory = async (directory) => {
12750
13592
  if (gitDir === void 0) {
12751
13593
  return INVALID;
12752
13594
  }
12753
- const head = await readBounded(path10.join(gitDir, "HEAD"));
13595
+ const head = await readBounded(path11.join(gitDir, "HEAD"));
12754
13596
  if (head === void 0) {
12755
13597
  return INVALID;
12756
13598
  }
@@ -12780,10 +13622,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
12780
13622
  };
12781
13623
  const locate = async (absolutePath) => {
12782
13624
  try {
12783
- if (!path10.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
13625
+ if (!path11.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
12784
13626
  return void 0;
12785
13627
  }
12786
- let directory = path10.resolve(absolutePath);
13628
+ let directory = path11.resolve(absolutePath);
12787
13629
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
12788
13630
  const probe = await cachedProbe(directory);
12789
13631
  if (probe.kind === "worktree") {
@@ -12792,7 +13634,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
12792
13634
  if (probe.kind === "invalid") {
12793
13635
  return void 0;
12794
13636
  }
12795
- const parent = path10.dirname(directory);
13637
+ const parent = path11.dirname(directory);
12796
13638
  if (parent === directory) {
12797
13639
  return void 0;
12798
13640
  }
@@ -12806,48 +13648,6 @@ var createFilesystemWorktreeLocator = (options = {}) => {
12806
13648
  return { locate };
12807
13649
  };
12808
13650
 
12809
- // src/telemetry/signal-fanout.ts
12810
- var createSignalFanout = (options) => {
12811
- const emit = async (events) => {
12812
- const traces = await options.traces.emit(events);
12813
- const logs = await options.logs.emit(events);
12814
- const errors = [...traces.errors, ...logs.errors];
12815
- return {
12816
- accepted: traces.accepted + logs.accepted,
12817
- rejected: traces.rejected + logs.rejected,
12818
- errors
12819
- };
12820
- };
12821
- const flush = async () => {
12822
- await options.traces.flush().catch(() => void 0);
12823
- await options.logs.flush().catch(() => void 0);
12824
- };
12825
- const shutdown = async () => {
12826
- await options.traces.shutdown().catch(() => void 0);
12827
- await options.logs.shutdown().catch(() => void 0);
12828
- };
12829
- return {
12830
- emit,
12831
- flush,
12832
- shutdown,
12833
- health: () => [
12834
- options.traces.health(),
12835
- options.logs.health()
12836
- ]
12837
- };
12838
- };
12839
- var shareCorrelationPerBatch = (correlate) => {
12840
- let pending;
12841
- return (events) => {
12842
- if (pending?.events === events) {
12843
- return pending.result;
12844
- }
12845
- const result = correlate(events);
12846
- pending = { events, result };
12847
- return result;
12848
- };
12849
- };
12850
-
12851
13651
  // src/integration/hook-runtime.ts
12852
13652
  var DEFAULT_FLUSH_TIMEOUT_MILLIS = 2e3;
12853
13653
  var DEFAULT_STATE_LOCK_TIMEOUT_MILLIS = 1e3;
@@ -12910,46 +13710,23 @@ var createHookRuntime = (options) => {
12910
13710
  logger,
12911
13711
  lockTimeoutMillis: stateLockTimeoutMillis
12912
13712
  });
12913
- const spool = options.enableSpool === false ? void 0 : createFileDurableSpool({
12914
- rootDir: options.stateRootDir,
12915
- providerId: options.providerNamespace,
12916
- installationId: options.installationId,
12917
- clock,
12918
- logger
12919
- });
12920
- const logSpool = options.enableSpool === false || !options.config.exporter.logs.enabled ? void 0 : createFileDurableLogSpool({
12921
- rootDir: options.stateRootDir,
12922
- providerId: options.providerNamespace,
12923
- installationId: options.installationId,
12924
- clock,
12925
- logger
12926
- });
12927
13713
  const spanCorrelator = createSpanCorrelator({
12928
13714
  stateStore,
12929
13715
  clock,
12930
13716
  maxStartAgeMillis: lifecycleMaxAge
12931
13717
  });
12932
13718
  const correlate = shareCorrelationPerBatch((events) => spanCorrelator.correlateBatch(events));
12933
- const traceSink = createOtlpTraceSink({
13719
+ const exportDestinations = createExportDestinationSinks({
12934
13720
  exporter: options.config.exporter,
12935
- ...options.headers === void 0 ? {} : { headers: options.headers },
13721
+ ...options.headers === void 0 ? {} : { defaultHeaders: options.headers },
13722
+ ...options.logHeaders === void 0 ? {} : { defaultLogHeaders: options.logHeaders },
13723
+ ...options.headerEnvironment === void 0 ? {} : { headerEnvironment: options.headerEnvironment },
12936
13724
  providerId: options.providerNamespace,
12937
13725
  installationId: options.installationId,
12938
13726
  clock,
12939
13727
  logger,
12940
- ...spool === void 0 ? {} : { spool },
12941
- correlate
12942
- });
12943
- const logHeaders = options.logHeaders ?? options.headers;
12944
- const logSink = createOtlpLogSink({
12945
- exporter: options.config.exporter,
12946
- ...logHeaders === void 0 ? {} : { headers: logHeaders },
12947
- providerId: options.providerNamespace,
12948
- installationId: options.installationId,
12949
- clock,
12950
- logger,
12951
- ...logSpool === void 0 ? {} : { spool: logSpool },
12952
- content: {
13728
+ ...options.enableSpool === false ? {} : { spoolRootDir: options.stateRootDir },
13729
+ logContent: {
12953
13730
  includeContent: options.config.exporter.logs.includeContent,
12954
13731
  // The pre-existing verbatim-content opt-in, passed through rather than
12955
13732
  // re-derived: `raw` disclosure in a log body is governed by the same flag it
@@ -12958,7 +13735,22 @@ var createHookRuntime = (options) => {
12958
13735
  },
12959
13736
  correlate
12960
13737
  });
12961
- const sink = createSignalFanout({ traces: traceSink, logs: logSink });
13738
+ const primary = exportDestinations.destinations[0];
13739
+ const traceSink = primary?.traces ?? createOtlpTraceSink({
13740
+ exporter: { ...options.config.exporter, enabled: false },
13741
+ providerId: options.providerNamespace,
13742
+ installationId: options.installationId,
13743
+ clock
13744
+ });
13745
+ const logSink = primary?.logs ?? createOtlpLogSink({
13746
+ exporter: { ...options.config.exporter, logs: { ...options.config.exporter.logs, enabled: false } },
13747
+ providerId: options.providerNamespace,
13748
+ installationId: options.installationId,
13749
+ clock
13750
+ });
13751
+ const spool = primary?.spool;
13752
+ const logSpool = primary?.logSpool;
13753
+ const sink = createDestinationFanout(exportDestinations.destinations);
12962
13754
  const hookDeps = {
12963
13755
  stateStore,
12964
13756
  config: options.config,
@@ -13227,6 +14019,8 @@ var createHookRuntime = (options) => {
13227
14019
  logSink,
13228
14020
  ...spool === void 0 ? {} : { spool },
13229
14021
  ...logSpool === void 0 ? {} : { logSpool },
14022
+ destinations: exportDestinations.destinations,
14023
+ skippedDestinations: exportDestinations.skipped,
13230
14024
  privacy,
13231
14025
  deduplicator,
13232
14026
  usageAccumulator,
@@ -13528,13 +14322,13 @@ var runHookCommand = async (command, io) => {
13528
14322
  }
13529
14323
  const identityClaims = [];
13530
14324
  if (command.identity.identityFile !== void 0) {
13531
- const read = await readIdentityFile(path11.resolve(command.identity.identityFile));
14325
+ const read = await readIdentityFile(path12.resolve(command.identity.identityFile));
13532
14326
  if ("error" in read) {
13533
14327
  logDiagnostics(logger, [read.error]);
13534
14328
  } else {
13535
14329
  const fromFile = claimFromIdentityFile(
13536
14330
  read.value,
13537
- path11.basename(command.identity.identityFile)
14331
+ path12.basename(command.identity.identityFile)
13538
14332
  );
13539
14333
  logDiagnostics(logger, fromFile.errors);
13540
14334
  identityClaims.push(...fromFile.claims);
@@ -13554,6 +14348,9 @@ var runHookCommand = async (command, io) => {
13554
14348
  providerNamespace: selection.namespace,
13555
14349
  ...Object.keys(headers.traces).length === 0 ? {} : { headers: headers.traces },
13556
14350
  ...Object.keys(headers.logs).length === 0 ? {} : { logHeaders: headers.logs },
14351
+ // Only `env:` header references in `exporter.destinations` are resolved
14352
+ // against it; nothing else in the runtime reads the environment.
14353
+ headerEnvironment: io.env,
13557
14354
  clock,
13558
14355
  ids,
13559
14356
  logger,