@goodtiming/baton-sdk 0.6.3 → 0.6.5

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/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-0.6.3";
2
+ var SDK_VERSION = "ts-0.6.5";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
@@ -580,7 +580,7 @@ var DropCounts = class {
580
580
  const lost = [...this.#sinceDelivery].sort(([a], [b]) => a.localeCompare(b));
581
581
  this.#sinceDelivery.clear();
582
582
  this.#lastRecoveryLog = now;
583
- const total = lost.reduce((sum, [, n]) => sum + n, 0);
583
+ const total = lost.reduce((sum2, [, n]) => sum2 + n, 0);
584
584
  warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(", ")}.`);
585
585
  }
586
586
  /** For tests: the counts are one per process. */
@@ -638,12 +638,10 @@ function stderrLine(message) {
638
638
  function isTimerMs(value) {
639
639
  return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
640
640
  }
641
- function shutdownFlushTimeoutOption(given) {
641
+ function timerMsOption(given, name, fallback) {
642
642
  if (isTimerMs(given)) return given;
643
- if (given !== void 0) {
644
- warn(`baton: shutdownFlushTimeoutMs must be from 0 to ${MAX_TIMER_MS} ms; using ${SHUTDOWN_FLUSH_TIMEOUT_MS}.`);
645
- }
646
- return SHUTDOWN_FLUSH_TIMEOUT_MS;
643
+ if (given !== void 0) warn(`baton: ${name} must be from 0 to ${MAX_TIMER_MS} ms; using ${fallback}.`);
644
+ return fallback;
647
645
  }
648
646
  function shutdownBudgetMs(sink) {
649
647
  try {
@@ -740,6 +738,31 @@ var MultiSink = class {
740
738
  throw new AggregateError(errors, "MultiSink fan-out failures");
741
739
  }
742
740
  };
741
+ var BATCH_OPEN = '{"events":[';
742
+ var BATCH_CLOSE = "]}";
743
+ var BATCH_FRAME_BYTES = (BATCH_OPEN + BATCH_CLOSE).length;
744
+ var BATCH_MAX_EVENTS = 100;
745
+ var BATCH_MAX_BYTES = 1048576;
746
+ var FLUSH_INTERVAL_MS = 5e3;
747
+ var RETRY_AFTER_MIN_S = 1;
748
+ var RETRY_AFTER_MAX_S = 60;
749
+ var utf8 = new TextEncoder();
750
+ function utf8Bytes(text) {
751
+ return typeof Buffer === "undefined" ? utf8.encode(text).length : Buffer.byteLength(text, "utf8");
752
+ }
753
+ function sum(values) {
754
+ let total = 0;
755
+ for (const value of values) total += value;
756
+ return total;
757
+ }
758
+ function retryAfterMs(header) {
759
+ const value = header?.trim() ?? "";
760
+ if (!/^\d+$/.test(value)) return null;
761
+ return Math.min(Math.max(Number(value), RETRY_AFTER_MIN_S), RETRY_AFTER_MAX_S) * 1e3;
762
+ }
763
+ function sameBatch(a, b) {
764
+ return a.tenant_id === b.tenant_id && a.vendor_id === b.vendor_id;
765
+ }
743
766
  var CircuitBreaker = class {
744
767
  constructor(threshold, resetMs) {
745
768
  this.threshold = threshold;
@@ -750,8 +773,11 @@ var CircuitBreaker = class {
750
773
  failures = 0;
751
774
  openedAt = null;
752
775
  canRequest() {
753
- if (this.openedAt === null) return true;
754
- return Date.now() - this.openedAt >= this.resetMs;
776
+ return this.msUntilRequest() === 0;
777
+ }
778
+ msUntilRequest() {
779
+ if (this.openedAt === null) return 0;
780
+ return Math.max(this.openedAt + this.resetMs - Date.now(), 0);
755
781
  }
756
782
  recordSuccess() {
757
783
  this.failures = 0;
@@ -767,12 +793,17 @@ var CircuitBreaker = class {
767
793
  var HttpSink = class _HttpSink {
768
794
  url;
769
795
  apiKey;
796
+ /** Waiting events only: a batch being sent is out of it, so the bound
797
+ * never pushes out an event in flight (SPEC §11.2 rule 4). */
770
798
  buffer = [];
799
+ bufferedBytes = 0;
800
+ sendingEvents = 0;
771
801
  bufferSize;
772
802
  requestTimeoutMs;
773
803
  shutdownFlushTimeoutMs;
774
- /** Set when an exit pass ends; cleared once a normal drain empties the
775
- * buffer, which means the process went on. */
804
+ flushIntervalMs;
805
+ /** Set when an exit pass ends; cleared once a normal drain sends
806
+ * everything, which means the process went on. */
776
807
  exitPassRan = false;
777
808
  /** Whether the exit pass warned about every event now buffered. */
778
809
  unsentWarned = false;
@@ -782,7 +813,8 @@ var HttpSink = class _HttpSink {
782
813
  circuit;
783
814
  fetchImpl;
784
815
  overflowWarned = false;
785
- /** Per status, so a new kind of refusal, such as a 401 after a 422, still warns. */
816
+ /** Per status or refusal code, so a new kind of refusal, such as a 401
817
+ * after a 422, still warns. */
786
818
  refusals = /* @__PURE__ */ new Map();
787
819
  /** Aborted once `aclose()` returns: nothing Baton started may keep the
788
820
  * process alive after the vendor closed it. */
@@ -792,6 +824,16 @@ var HttpSink = class _HttpSink {
792
824
  skipWarnedFor = null;
793
825
  closeOnce;
794
826
  drainChain = Promise.resolve();
827
+ queuedDrain = null;
828
+ /** Whether the queued pass sends everything waiting, not only what is due. */
829
+ forceNext = false;
830
+ flushTimer = null;
831
+ /** Set by a failed batch: only the timer, a flush or a close tries again. */
832
+ waitForTimer = false;
833
+ /** Nothing is sent before this `Date.now()`, from a 429's `Retry-After`. */
834
+ retryAt = 0;
835
+ /** Set for the life of the sink by a 404 or 405 on the batch path. */
836
+ batchless = false;
795
837
  exitHooks = null;
796
838
  /** The least time between two of this sink's loss reports. */
797
839
  static reportIntervalMs = 6e4;
@@ -799,13 +841,21 @@ var HttpSink = class _HttpSink {
799
841
  reportedSum = 0;
800
842
  lastReportAt = -Infinity;
801
843
  reportsStopped = false;
802
- reportInFlight = null;
844
+ /** The envelope of a report due to ride the next batch, and when it was set up.
845
+ * `built` is the report once taken: a kept batch resends it unchanged (SPEC §11.4.7). */
846
+ pendingReport = null;
847
+ reportSetAt = 0;
803
848
  constructor(url, options) {
804
849
  this.url = url.replace(/\/+$/, "");
805
850
  this.apiKey = options.apiKey;
806
851
  this.bufferSize = options.bufferSize ?? 1e3;
807
852
  this.requestTimeoutMs = options.requestTimeoutMs ?? 1e3;
808
- this.shutdownFlushTimeoutMs = shutdownFlushTimeoutOption(options.shutdownFlushTimeoutMs);
853
+ this.shutdownFlushTimeoutMs = timerMsOption(
854
+ options.shutdownFlushTimeoutMs,
855
+ "shutdownFlushTimeoutMs",
856
+ SHUTDOWN_FLUSH_TIMEOUT_MS
857
+ );
858
+ this.flushIntervalMs = timerMsOption(options.flushIntervalMs, "flushIntervalMs", FLUSH_INTERVAL_MS);
809
859
  this.maxRetries = options.maxRetries ?? 3;
810
860
  this.backoffBaseMs = options.backoffBaseMs ?? 100;
811
861
  this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
@@ -835,11 +885,24 @@ var HttpSink = class _HttpSink {
835
885
  get closed() {
836
886
  return this.closing.signal.aborted;
837
887
  }
888
+ get unsent() {
889
+ return this.buffer.length + this.sendingEvents;
890
+ }
891
+ /** Encodes at once, not when the batch is cut, because the byte cap
892
+ * decides when a batch goes. */
838
893
  async write(event) {
839
894
  if (this.closed) throw new SinkClosedError("HttpSink is closed");
840
- this.enqueue(event);
895
+ const json = this.encode(event);
896
+ if (json === null) return;
897
+ const bytes = utf8Bytes(json);
898
+ if (BATCH_FRAME_BYTES + bytes > BATCH_MAX_BYTES) {
899
+ this.refuse(1, { kind: "over 1 MiB", detail: `${bytes} bytes` }, false);
900
+ return;
901
+ }
902
+ this.enqueue({ event, json, bytes, writtenAt: Date.now() });
841
903
  this.unsentWarned = false;
842
- void this.scheduleDrain();
904
+ if (this.batchIsFull() && !this.waitForTimer) void this.scheduleDrain(false);
905
+ else this.armTimer(this.buffer[0].writtenAt + this.flushIntervalMs - Date.now());
843
906
  this.ensureExitHooksRegistered();
844
907
  }
845
908
  flush() {
@@ -861,9 +924,11 @@ var HttpSink = class _HttpSink {
861
924
  this.stopReports();
862
925
  await this.drainWithinBudget("aclose()", ms);
863
926
  this.closing.abort();
864
- if (this.buffer.length > 0) {
865
- PROCESS_DROPS.add("unsent_at_close", this.buffer.length);
866
- warn(`baton: the sink closed with ${this.buffer.length} event(s) unsent.`);
927
+ this.clearTimer();
928
+ const unsent = this.unsent;
929
+ if (unsent > 0) {
930
+ PROCESS_DROPS.add("unsent_at_close", unsent);
931
+ warn(`baton: the sink closed with ${unsent} event(s) unsent.`);
867
932
  }
868
933
  this.warnUnloggedRefusals("the sink closed");
869
934
  if (this.exitHooks) {
@@ -885,11 +950,11 @@ var HttpSink = class _HttpSink {
885
950
  }
886
951
  if (this.skipWarnedFor !== this.stalledDrain) {
887
952
  this.skipWarnedFor = this.stalledDrain;
888
- warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.buffer.length} event(s) wait to be sent.`);
953
+ warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.unsent} event(s) wait to be sent.`);
889
954
  }
890
955
  return;
891
956
  }
892
- const settled = this.scheduleDrain().catch(() => void 0);
957
+ const settled = this.scheduleDrain(true).catch(() => void 0);
893
958
  if (await raceDeadline(settled, ms) !== TIMED_OUT) return;
894
959
  if (ms < this.shutdownFlushTimeoutMs) return;
895
960
  const stalled = this.drainChain.catch(() => void 0);
@@ -901,12 +966,13 @@ var HttpSink = class _HttpSink {
901
966
  warn(`baton: flush() took over ${ms} ms; it goes on in the background.`);
902
967
  }
903
968
  }
904
- /** A full buffer may already have pushed `event` out while it was being sent. */
905
- dequeue(event) {
906
- if (this.buffer[0] === event) this.buffer.shift();
969
+ enqueue(waiting) {
970
+ this.buffer.push(waiting);
971
+ this.bufferedBytes += waiting.bytes;
972
+ this.dropOverflow();
907
973
  }
908
- enqueue(event) {
909
- if (this.buffer.length >= this.bufferSize) {
974
+ dropOverflow() {
975
+ while (this.buffer.length > this.bufferSize) {
910
976
  PROCESS_DROPS.add("buffer_full");
911
977
  if (!this.overflowWarned) {
912
978
  warn(
@@ -914,21 +980,49 @@ var HttpSink = class _HttpSink {
914
980
  );
915
981
  this.overflowWarned = true;
916
982
  }
917
- this.buffer.shift();
983
+ this.bufferedBytes -= this.buffer.shift().bytes;
918
984
  }
919
- this.buffer.push(event);
920
- }
921
- /** Serializes every call to `drainLocked` — from `write()`'s background
922
- * drain and from explicit `flush()` alike — onto one promise chain, so
923
- * concurrent tool calls (the normal case once the MCP interceptor is
924
- * wired up) can never run two drains at once racing on `buffer[0]`/
925
- * `shift()`. Mirrors Python's `asyncio.Lock` around `_drain_locked`. */
926
- scheduleDrain() {
927
- this.drainChain = this.drainChain.then(
928
- () => this.drainLocked(),
929
- () => this.drainLocked()
985
+ }
986
+ batchIsFull() {
987
+ return this.buffer.length >= BATCH_MAX_EVENTS || BATCH_FRAME_BYTES + this.bufferedBytes + this.buffer.length - 1 > BATCH_MAX_BYTES;
988
+ }
989
+ /** The timer must not keep the vendor's process alive: the exit hooks send
990
+ * what is left. */
991
+ armTimer(delayMs) {
992
+ if (this.flushTimer !== null || this.closed) return;
993
+ const timer = setTimeout(
994
+ () => {
995
+ this.flushTimer = null;
996
+ this.waitForTimer = false;
997
+ void this.scheduleDrain(false);
998
+ },
999
+ Math.min(Math.max(delayMs, 0), MAX_TIMER_MS)
930
1000
  );
931
- return this.drainChain;
1001
+ timer.unref?.();
1002
+ this.flushTimer = timer;
1003
+ }
1004
+ clearTimer() {
1005
+ if (this.flushTimer === null) return;
1006
+ clearTimeout(this.flushTimer);
1007
+ this.flushTimer = null;
1008
+ }
1009
+ /** Runs `drainLocked` after the pass under way, one pass at a time, so two
1010
+ * never send at once or race on the buffer. A pass not yet started is
1011
+ * shared by every caller: one per write would grow without bound while a
1012
+ * slow collector holds a pass. */
1013
+ scheduleDrain(force) {
1014
+ this.forceNext ||= force;
1015
+ if (this.queuedDrain) return this.queuedDrain;
1016
+ const run = () => {
1017
+ this.queuedDrain = null;
1018
+ const forced = this.forceNext;
1019
+ this.forceNext = false;
1020
+ return this.drainLocked(forced);
1021
+ };
1022
+ this.queuedDrain = this.drainChain.then(run, run);
1023
+ this.queuedDrain.catch(() => void 0);
1024
+ this.drainChain = this.queuedDrain;
1025
+ return this.queuedDrain;
932
1026
  }
933
1027
  /** Best-effort flush when the process is about to exit without an
934
1028
  * explicit `aclose()`. SIGKILL, or SIGTERM with no installed handler, skip
@@ -937,18 +1031,18 @@ var HttpSink = class _HttpSink {
937
1031
  ensureExitHooksRegistered() {
938
1032
  if (this.exitHooks) return;
939
1033
  const beforeExit = () => {
940
- if (this.buffer.length === 0 || this.exitPassRan) {
1034
+ if (this.unsent === 0 || this.exitPassRan) {
941
1035
  this.warnUnloggedRefusals("process exiting");
942
1036
  return;
943
1037
  }
944
1038
  this.drainChain = this.drainChain.then(
945
1039
  () => this.exitPass(),
946
1040
  () => this.exitPass()
947
- );
1041
+ ).catch(() => void 0);
948
1042
  };
949
1043
  const exit = () => {
950
1044
  try {
951
- if (this.buffer.length > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
1045
+ if (this.unsent > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
952
1046
  this.warnUnloggedRefusals("process exiting", stderrLine);
953
1047
  } catch {
954
1048
  }
@@ -957,35 +1051,22 @@ var HttpSink = class _HttpSink {
957
1051
  process.on("beforeExit", beforeExit);
958
1052
  process.on("exit", exit);
959
1053
  }
960
- /** One attempt per event, no retry, within `shutdownFlushTimeoutMs` in
1054
+ /** One attempt per batch, no retry, within `shutdownFlushTimeoutMs` in
961
1055
  * total (SPEC §11.2); what is left is reported, not sent. */
962
1056
  async exitPass() {
963
1057
  const deadline = Date.now() + this.shutdownFlushTimeoutMs;
964
- while (this.buffer.length > 0 && this.circuit.canRequest()) {
965
- const timeLeft = deadline - Date.now();
966
- if (timeLeft <= 0) break;
967
- const event = this.buffer[0];
968
- const body = this.encode(event);
969
- if (body !== null) {
970
- const outcome = await this.postOnce(body, Math.min(this.requestTimeoutMs, timeLeft));
971
- if (outcome === "transient_failure") {
972
- this.circuit.recordFailure();
973
- break;
974
- }
975
- this.circuit.recordSuccess();
976
- }
977
- this.dequeue(event);
1058
+ while (this.circuit.canRequest() && Date.now() >= this.retryAt && Date.now() < deadline) {
1059
+ const batch = this.takeBatch(false);
1060
+ if (batch === null) break;
1061
+ if (!this.putBack(await this.sendBatch(batch, 0, deadline), batch)) break;
978
1062
  }
979
1063
  this.exitPassRan = true;
980
1064
  this.unsentWarned = true;
981
- if (this.buffer.length > 0) warn(this.unsentAtExit());
1065
+ if (this.unsent > 0) warn(this.unsentAtExit());
982
1066
  this.warnUnloggedRefusals("process exiting");
983
1067
  }
984
1068
  unsentAtExit() {
985
- return `baton: process exiting with ${this.buffer.length} unsent event(s).`;
986
- }
987
- events_url() {
988
- return `${this.url}/v0/events`;
1069
+ return `baton: process exiting with ${this.unsent} unsent event(s).`;
989
1070
  }
990
1071
  authHeaders() {
991
1072
  return { Authorization: `Bearer ${this.apiKey}`, "Content-Type": "application/json" };
@@ -995,17 +1076,19 @@ var HttpSink = class _HttpSink {
995
1076
  if (status >= 400 && status < 500 && status !== 429) return "permanent_failure";
996
1077
  return "transient_failure";
997
1078
  }
998
- /** A refused event is otherwise dropped silently, which looks the same from
999
- * the vendor's process as an accepted one. The collector's own message is
1000
- * logged because it names the field at fault; it is capped and escaped
1079
+ /** Counts `n` refused events and logs them, at most once a minute per
1080
+ * kind. A refused event is otherwise dropped silently, which looks the same
1081
+ * from the vendor's process as an accepted one. The collector's own message
1082
+ * is logged because it names the field at fault; it is capped and escaped
1001
1083
  * because it is a remote server's text landing in the vendor's log. */
1002
- static async logRefusal(response, unlogged) {
1003
- const detail = await _HttpSink.readHead(response).then(
1004
- (text) => escapeForLog(capCodePoints(text, REFUSAL_BODY_MAX_LEN)),
1005
- () => "<unreadable>"
1006
- );
1084
+ refuse(n, { kind, detail }, byCollector = true) {
1085
+ if (n === 0) return;
1086
+ PROCESS_DROPS.add("refused", n);
1087
+ const unlogged = this.refusalToLog(kind, n);
1088
+ if (unlogged === null) return;
1089
+ const what = n === 1 ? "an event and it has" : `${n} events and they have`;
1007
1090
  warn(
1008
- `baton: collector REFUSED an event and it has been dropped (HTTP ${response.status}): ${detail} \u2014 the event is gone; nothing retries a 4xx.` + (unlogged > 0 ? ` ${unlogged} more refused since the last such warning.` : "")
1091
+ `baton: ${byCollector ? "collector REFUSED" : "REFUSED, unsent,"} ${what} been dropped (${kind}): ${escapeForLog(capCodePoints(detail, REFUSAL_BODY_MAX_LEN))} \u2014 the event is gone; nothing retries a refusal.` + (unlogged > 0 ? ` ${unlogged} more refused since the last such warning.` : "")
1009
1092
  );
1010
1093
  }
1011
1094
  warnUnloggedRefusals(when, emit2 = warn) {
@@ -1016,16 +1099,16 @@ var HttpSink = class _HttpSink {
1016
1099
  }
1017
1100
  if (total > 0) emit2(`baton: ${when}; ${total} more event(s) refused since the last such warning.`);
1018
1101
  }
1019
- /** How many refusals with `status` went unlogged before this one, or `null`
1020
- * when this one goes unlogged too. */
1021
- refusalToLog(status) {
1102
+ /** How many refusals of `kind` went unlogged before these `n`, or `null`
1103
+ * when these go unlogged too. */
1104
+ refusalToLog(kind, n) {
1022
1105
  const now = performance.now();
1023
- const seen = this.refusals.get(status);
1106
+ const seen = this.refusals.get(kind);
1024
1107
  if (seen !== void 0 && now - seen.loggedAt < REFUSAL_LOG_MS) {
1025
- seen.unlogged++;
1108
+ seen.unlogged += n;
1026
1109
  return null;
1027
1110
  }
1028
- this.refusals.set(status, { loggedAt: now, unlogged: 0 });
1111
+ this.refusals.set(kind, { loggedAt: now, unlogged: 0 });
1029
1112
  return seen?.unlogged ?? 0;
1030
1113
  }
1031
1114
  /** Enough of the body for `REFUSAL_BODY_MAX_LEN` code points; the rest is
@@ -1047,87 +1130,208 @@ var HttpSink = class _HttpSink {
1047
1130
  });
1048
1131
  }
1049
1132
  }
1050
- async drainLocked() {
1051
- while (this.buffer.length > 0) {
1052
- if (!this.circuit.canRequest() || this.closing.signal.aborted) return;
1053
- const event = this.buffer[0];
1054
- const outcome = await this.sendWithRetry(event);
1055
- if (outcome === "success" || outcome === "permanent_failure") {
1056
- this.dequeue(event);
1057
- this.circuit.recordSuccess();
1058
- if (outcome === "success") {
1059
- PROCESS_DROPS.logRecovery();
1060
- this.maybeReport(event);
1061
- }
1062
- } else if (outcome === "unencodable") {
1063
- this.dequeue(event);
1064
- } else {
1065
- this.circuit.recordFailure();
1066
- return;
1133
+ /** Sends what is due, one batch at a time; `force` (a flush or close) sends
1134
+ * everything waiting. A report set up before the pass rides along; one set
1135
+ * up by this pass's own delivery waits for the next batch. */
1136
+ async drainLocked(force) {
1137
+ let failed = false;
1138
+ let reportDue = this.pendingReport !== null;
1139
+ while (!this.closed) {
1140
+ if (!this.isDue(force, reportDue)) break;
1141
+ if (!this.circuit.canRequest() || Date.now() < this.retryAt) {
1142
+ failed = true;
1143
+ break;
1144
+ }
1145
+ const batch = this.takeBatch(reportDue);
1146
+ if (batch === null) break;
1147
+ if (batch.some((w) => w.reportSum !== void 0)) reportDue = false;
1148
+ if (!this.putBack(await this.sendBatch(batch, this.maxRetries, Infinity), batch)) {
1149
+ failed = true;
1150
+ break;
1067
1151
  }
1068
1152
  }
1069
- this.exitPassRan = false;
1153
+ if (!failed && this.unsent === 0) this.exitPassRan = false;
1154
+ this.waitForTimer = failed;
1155
+ this.clearTimer();
1156
+ if (failed) {
1157
+ const waits = [this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest()];
1158
+ if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(Math.max(...waits));
1159
+ return;
1160
+ }
1161
+ const next = Math.min(this.buffer[0]?.writtenAt ?? Infinity, this.reportRidesHead() ? this.reportSetAt : Infinity);
1162
+ if (next !== Infinity) this.armTimer(next + this.flushIntervalMs - Date.now());
1163
+ }
1164
+ /** A due report makes the next batch due only when it can ride it; the
1165
+ * timer is armed the same way, so a pass that sends nothing never re-arms
1166
+ * it at a time already past. */
1167
+ isDue(force, reportDue) {
1168
+ const now = Date.now();
1169
+ if (reportDue && this.reportRidesHead() && (force || this.reportSetAt + this.flushIntervalMs <= now)) return true;
1170
+ return this.buffer.length > 0 && (force || this.batchIsFull() || this.buffer[0].writtenAt + this.flushIntervalMs <= now);
1171
+ }
1172
+ /** A pending report can go in the next batch: alone, or with the head event's tenant and vendor. */
1173
+ reportRidesHead() {
1174
+ const head = this.buffer[0];
1175
+ return this.pendingReport !== null && (head === void 0 || sameBatch(this.pendingReport, head.event));
1176
+ }
1177
+ /** Takes the head of the buffer that fits one batch: one tenant and vendor
1178
+ * (SPEC §2.5), at most 100 events and 1 MiB. A due report with the head
1179
+ * event's tenant and vendor takes one of those places, and goes alone when
1180
+ * the head event fits only without it. A report that cannot ride the head
1181
+ * waits for a batch it can ride. Without a batch endpoint the same events
1182
+ * go one per request. */
1183
+ takeBatch(withReport) {
1184
+ const batch = [];
1185
+ let bytes = BATCH_FRAME_BYTES - 1;
1186
+ let eventBytes = 0;
1187
+ const report = withReport && this.reportRidesHead() ? this.pendingReport.built ?? this.buildReport() : null;
1188
+ const maxEvents = BATCH_MAX_EVENTS - (report ? 1 : 0);
1189
+ const maxBytes = BATCH_MAX_BYTES - (report ? 1 + report.bytes : 0);
1190
+ const fits = (w) => bytes + 1 + w.bytes <= maxBytes && (batch.length === 0 || batch.length < maxEvents && sameBatch(w.event, batch[0].event));
1191
+ for (const waiting of this.buffer) {
1192
+ if (!fits(waiting)) break;
1193
+ batch.push(waiting);
1194
+ bytes += 1 + waiting.bytes;
1195
+ eventBytes += waiting.bytes;
1196
+ }
1197
+ this.buffer.splice(0, batch.length);
1198
+ this.bufferedBytes -= eventBytes;
1199
+ this.sendingEvents = batch.length;
1200
+ if (report !== null) batch.push(report);
1201
+ return batch.length > 0 ? batch : null;
1202
+ }
1203
+ /** Puts what a failure `kept` of the batch `taken` back at the head of the
1204
+ * buffer, and keeps its report unless `taken` had no events; `true` when
1205
+ * nothing was kept. */
1206
+ putBack(kept, taken) {
1207
+ this.sendingEvents = 0;
1208
+ if (this.closed) return kept.length === 0;
1209
+ const events = [];
1210
+ for (const waiting of kept) {
1211
+ if (waiting.reportSum !== void 0) {
1212
+ if (taken.every((w) => w.reportSum !== void 0) || this.batchless) this.pendingReport = null;
1213
+ continue;
1214
+ }
1215
+ events.push(waiting);
1216
+ this.bufferedBytes += waiting.bytes;
1217
+ }
1218
+ this.buffer.unshift(...events);
1219
+ this.dropOverflow();
1220
+ return kept.length === 0;
1070
1221
  }
1071
- /** Starts a report of this process's loss totals (SPEC §11.4.7) beside the
1072
- * drain and outside the buffer, so it never delays an event and is never
1073
- * counted as one. */
1222
+ /** After a delivery, sets up a report of this process's loss totals (SPEC
1223
+ * §11.4.7) to ride the next batch. It stays outside the buffer, so it never
1224
+ * pushes an event out and is never counted as one. */
1074
1225
  maybeReport({ tenant_id, vendor_id, consent_token }) {
1075
1226
  const now = performance.now();
1076
- if (this.reportsStopped || this.reportInFlight !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
1227
+ if (this.reportsStopped || this.pendingReport !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
1077
1228
  return;
1078
1229
  }
1079
- const totals = PROCESS_DROPS.total();
1080
- const sum = Object.values(totals).reduce((a, b) => a + b, 0);
1081
- if (sum === this.reportedSum) return;
1230
+ if (sum(Object.values(PROCESS_DROPS.total())) === this.reportedSum) return;
1082
1231
  this.lastReportAt = now;
1083
- const abort = new AbortController();
1084
- this.reportInFlight = abort;
1085
- const envelope = { tenant_id, vendor_id, consent_token };
1086
- void this.sendReport(envelope, totals, sum, abort).finally(() => {
1087
- this.reportInFlight = null;
1088
- });
1232
+ this.reportSetAt = Date.now();
1233
+ this.pendingReport = { tenant_id, vendor_id, consent_token };
1089
1234
  }
1090
1235
  stopReports() {
1091
1236
  this.reportsStopped = true;
1092
- this.reportInFlight?.abort();
1237
+ this.pendingReport = null;
1093
1238
  }
1094
- async sendReport(envelope, totals, sum, abort) {
1095
- const timer = setTimeout(() => abort.abort(), this.requestTimeoutMs);
1239
+ buildReport() {
1240
+ if (this.pendingReport === null) return null;
1241
+ const { tenant_id, vendor_id, consent_token } = this.pendingReport;
1242
+ const totals = PROCESS_DROPS.total();
1096
1243
  try {
1097
1244
  const report = ClientReportEventSchema.parse({
1098
- ...envelope,
1245
+ tenant_id,
1246
+ vendor_id,
1247
+ consent_token,
1099
1248
  session_id: PROCESS_DROPS.instanceId,
1100
1249
  sequence_number: nextClockSequence(),
1101
1250
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1102
1251
  payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals }
1103
1252
  });
1104
- const response = await this.fetchImpl(this.events_url(), {
1105
- method: "POST",
1106
- headers: this.authHeaders(),
1107
- body: JSON.stringify(report),
1108
- signal: abort.signal
1109
- });
1110
- void response.body?.cancel().catch(() => void 0);
1111
- if (response.status === 400 || response.status === 422) this.reportsStopped = true;
1112
- else if (_HttpSink.classifyStatus(response.status) === "success") this.reportedSum = sum;
1253
+ const json = JSON.stringify(report);
1254
+ this.pendingReport.built = { event: report, json, bytes: utf8Bytes(json), writtenAt: Date.now(), reportSum: sum(Object.values(totals)) };
1255
+ return this.pendingReport.built;
1113
1256
  } catch {
1114
- } finally {
1115
- clearTimeout(timer);
1257
+ this.pendingReport = null;
1258
+ return null;
1116
1259
  }
1117
1260
  }
1118
- async sendWithRetry(event) {
1119
- const body = this.encode(event);
1120
- if (body === null) return "unencodable";
1121
- for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
1122
- const outcome = await this.postOnce(body, this.requestTimeoutMs);
1123
- if (outcome !== "transient_failure") return outcome;
1124
- if (attempt < this.maxRetries) {
1125
- const backoff = Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs);
1126
- await this.sleepUnlessClosed(backoff);
1127
- if (this.closing.signal.aborted) return "transient_failure";
1261
+ /** Sends one batch, splitting it on 413, until every event in it is
1262
+ * delivered or refused. Returns what a failure kept, to go back in the
1263
+ * buffer. */
1264
+ async sendBatch(batch, retries, deadline) {
1265
+ if (this.batchless && batch.length > 1) return this.sendEachAlone(batch, retries, deadline);
1266
+ const batchless = this.batchless;
1267
+ const body = batchless ? batch[0].json : BATCH_OPEN + batch.map((w) => w.json).join(",") + BATCH_CLOSE;
1268
+ for (let attempt = 0; ; attempt++) {
1269
+ const timeLeft = deadline - Date.now();
1270
+ if (timeLeft <= 0) return batch;
1271
+ const answer = await this.post(body, batch.length, batchless, Math.min(this.requestTimeoutMs, timeLeft));
1272
+ if (answer.kind === "no_batch_endpoint") {
1273
+ this.batchless = true;
1274
+ warn("baton: the collector has no batch endpoint; sending one event per request.");
1275
+ return this.sendEachAlone(batch, retries, deadline);
1276
+ }
1277
+ if (answer.kind === "too_large") {
1278
+ const half = Math.floor(batch.length / 2);
1279
+ const kept = await this.sendBatch(batch.slice(0, half), retries, deadline);
1280
+ if (kept.length > 0) return [...kept, ...batch.slice(half)];
1281
+ return this.sendBatch(batch.slice(half), retries, deadline);
1128
1282
  }
1283
+ if (answer.kind === "transient") {
1284
+ if (answer.retryAfterMs !== null) {
1285
+ this.retryAt = Date.now() + answer.retryAfterMs;
1286
+ return batch;
1287
+ }
1288
+ if (attempt < retries && !this.closed) {
1289
+ await this.sleepUnlessClosed(Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs));
1290
+ if (!this.closed) continue;
1291
+ }
1292
+ this.circuit.recordFailure();
1293
+ return batch;
1294
+ }
1295
+ this.circuit.recordSuccess();
1296
+ this.settle(batch, answer, batchless);
1297
+ return [];
1298
+ }
1299
+ }
1300
+ async sendEachAlone(batch, retries, deadline) {
1301
+ for (const [i, waiting] of batch.entries()) {
1302
+ if (this.closed) return batch.slice(i);
1303
+ const kept = await this.sendBatch([waiting], retries, deadline);
1304
+ if (kept.length > 0) return [...kept, ...batch.slice(i + 1)];
1305
+ }
1306
+ return [];
1307
+ }
1308
+ /** `alone` is one event per request (SPEC §2.5), so a whole refusal there is that event's own. */
1309
+ settle(batch, answer, alone) {
1310
+ if (this.closed) return;
1311
+ let lastDelivered = null;
1312
+ const refused = /* @__PURE__ */ new Map();
1313
+ for (const waiting of batch) {
1314
+ if (waiting.reportSum === void 0) this.sendingEvents -= 1;
1315
+ const refusal = answer.kind === "refused" ? answer.refusal : answer.refused.get(waiting.event.event_id);
1316
+ if (waiting.reportSum !== void 0) {
1317
+ this.pendingReport = null;
1318
+ if (refusal === void 0) this.reportedSum = waiting.reportSum;
1319
+ else if (answer.kind === "answered" ? refusal.kind === "payload_malformed" : alone && (answer.status === 400 || answer.status === 422)) {
1320
+ this.reportsStopped = true;
1321
+ }
1322
+ } else if (refusal === void 0) {
1323
+ lastDelivered = waiting.event;
1324
+ } else {
1325
+ const seen = refused.get(refusal.kind);
1326
+ if (seen) seen.n += 1;
1327
+ else refused.set(refusal.kind, { first: refusal, n: 1 });
1328
+ }
1329
+ }
1330
+ for (const { first, n } of refused.values()) this.refuse(n, first);
1331
+ if (lastDelivered !== null) {
1332
+ PROCESS_DROPS.logRecovery();
1333
+ this.maybeReport(lastDelivered);
1129
1334
  }
1130
- return "transient_failure";
1131
1335
  }
1132
1336
  /** `null`, with a warning, for an event `JSON.stringify` rejects. */
1133
1337
  encode(event) {
@@ -1155,37 +1359,73 @@ var HttpSink = class _HttpSink {
1155
1359
  }
1156
1360
  /** Aborted by the timeout or by `aclose()`. Built by hand: `AbortSignal.any`
1157
1361
  * is missing before Node 20.3, and on some later versions it keeps every
1158
- * combined signal alive as long as the long-lived `closing` signal. */
1159
- async postOnce(body, timeoutMs) {
1362
+ * combined signal alive as long as the long-lived `closing` signal. Any body
1363
+ * read is under the same signal, so a stalled body cannot hold the drain. */
1364
+ async post(body, size, batchless, timeoutMs) {
1365
+ if (this.closed) return { kind: "transient", retryAfterMs: null };
1160
1366
  const request = new AbortController();
1161
1367
  const abort = () => request.abort();
1162
1368
  const timer = setTimeout(abort, timeoutMs);
1163
1369
  this.closing.signal.addEventListener("abort", abort);
1164
1370
  try {
1165
- const response = await this.fetchImpl(this.events_url(), {
1371
+ const response = await this.fetchImpl(batchless ? `${this.url}/v0/events` : `${this.url}/v0/events/batch`, {
1166
1372
  method: "POST",
1167
1373
  headers: this.authHeaders(),
1168
1374
  body,
1169
- signal: request.signal
1375
+ signal: request.signal,
1376
+ // SPEC §2.5: a redirect is a failure, not followed.
1377
+ redirect: "manual"
1170
1378
  });
1171
- const outcome = _HttpSink.classifyStatus(response.status);
1172
- if (outcome === "permanent_failure") {
1173
- PROCESS_DROPS.add("refused");
1174
- const unlogged = this.refusalToLog(response.status);
1175
- if (unlogged !== null) {
1176
- await _HttpSink.logRefusal(response, unlogged);
1177
- return outcome;
1379
+ const { status } = response;
1380
+ const outcome = _HttpSink.classifyStatus(status);
1381
+ if (outcome === "success") {
1382
+ if (batchless) {
1383
+ void response.body?.cancel().catch(() => void 0);
1384
+ return { kind: "answered", refused: /* @__PURE__ */ new Map() };
1178
1385
  }
1386
+ return { kind: "answered", refused: _HttpSink.refusedIn(await response.text()) };
1179
1387
  }
1180
- void response.body?.cancel().catch(() => void 0);
1181
- return outcome;
1388
+ const other = _HttpSink.otherAnswer(response, size, batchless);
1389
+ if (other !== null) {
1390
+ void response.body?.cancel().catch(() => void 0);
1391
+ return other;
1392
+ }
1393
+ const detail = await _HttpSink.readHead(response).catch(() => "<unreadable>");
1394
+ return { kind: "refused", status, refusal: { kind: `HTTP ${status}`, detail } };
1182
1395
  } catch {
1183
- return "transient_failure";
1396
+ return { kind: "transient", retryAfterMs: null };
1184
1397
  } finally {
1185
1398
  clearTimeout(timer);
1186
1399
  this.closing.signal.removeEventListener("abort", abort);
1187
1400
  }
1188
1401
  }
1402
+ /** Every answer but a 2xx and a refusal of the whole batch. */
1403
+ static otherAnswer(response, size, batchless) {
1404
+ const { status } = response;
1405
+ if (status === 413 && size > 1) return { kind: "too_large" };
1406
+ if ((status === 404 || status === 405) && !batchless) return { kind: "no_batch_endpoint" };
1407
+ if (status === 429) return { kind: "transient", retryAfterMs: retryAfterMs(response.headers.get("Retry-After")) };
1408
+ if (_HttpSink.classifyStatus(status) === "transient_failure") return { kind: "transient", retryAfterMs: null };
1409
+ return null;
1410
+ }
1411
+ /** The refused results by `event_id` (SPEC §2.5). An event with no readable
1412
+ * result was delivered. */
1413
+ static refusedIn(text) {
1414
+ const refused = /* @__PURE__ */ new Map();
1415
+ let results;
1416
+ try {
1417
+ results = JSON.parse(text)?.results;
1418
+ } catch {
1419
+ return refused;
1420
+ }
1421
+ if (!Array.isArray(results)) return refused;
1422
+ const str = (value) => typeof value === "string" ? value : "";
1423
+ for (const result of results) {
1424
+ if (result?.status !== "refused" || typeof result.event_id !== "string") continue;
1425
+ refused.set(result.event_id, { kind: str(result.error?.code) || "no code", detail: str(result.error?.message) });
1426
+ }
1427
+ return refused;
1428
+ }
1189
1429
  };
1190
1430
 
1191
1431
  // src/integrations/mcp/withBaton.ts
@@ -2121,6 +2361,18 @@ function resolveTenantId(explicit, vendorId2) {
2121
2361
  if (fromEnv2) return fromEnv2;
2122
2362
  return vendorId2;
2123
2363
  }
2364
+ var STAND_IN_VENDOR_ID = "unset";
2365
+ function resolveInstallConfig(config) {
2366
+ const unconfigured = !config.dsn && dsnFromEnvironment() === void 0 && !config.vendorId && !config.tenantId && config.sink === void 0;
2367
+ const resolved = resolveBatonConfig(
2368
+ unconfigured ? {
2369
+ ...config,
2370
+ vendorId: STAND_IN_VENDOR_ID,
2371
+ vendorDisplayName: config.vendorDisplayName ?? STAND_IN_VENDOR_ID
2372
+ } : config
2373
+ );
2374
+ return { resolved, unconfigured };
2375
+ }
2124
2376
  function resolveBatonConfig(config) {
2125
2377
  const dsnString = selectDsn(
2126
2378
  config.dsn,
@@ -2166,7 +2418,7 @@ function resolveBatonConfig(config) {
2166
2418
  validateBatonConfig(identity);
2167
2419
  return {
2168
2420
  ...identity,
2169
- // The origin is scheme + authority; `HttpSink` appends `/v0/events`
2421
+ // The origin is scheme + authority; `HttpSink` appends `/v0/events/batch`
2170
2422
  // itself, exactly as it does for an explicitly-constructed sink.
2171
2423
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
2172
2424
  };
@@ -2252,11 +2504,12 @@ function captureDisabled() {
2252
2504
  return null;
2253
2505
  }
2254
2506
  function logDisabled(switchName, surface) {
2255
- if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
2256
- process.emitWarning(
2257
- `baton: ${switchName} is set, so capture is OFF \u2014 ${surface} installed nothing and will emit no events. Unset it to re-enable.`
2258
- );
2259
- }
2507
+ warn(
2508
+ `baton: ${switchName} is set, so capture is OFF \u2014 ${surface} installed nothing and will emit no events. Unset it to re-enable.`
2509
+ );
2510
+ }
2511
+ function logUnconfigured(surface) {
2512
+ warn(`baton: no DSN (dsn or BATON_DSN), so ${surface} installed nothing and records nothing`);
2260
2513
  }
2261
2514
  var DisabledSink = class {
2262
2515
  // The parameter is omitted rather than named-and-ignored: a narrower
@@ -2335,6 +2588,19 @@ var SessionCounter = class {
2335
2588
  return next;
2336
2589
  }
2337
2590
  };
2591
+ var ServerCounter = class extends SessionCounter {
2592
+ constructor(shared, ownSessionId) {
2593
+ super();
2594
+ this.shared = shared;
2595
+ this.ownSessionId = ownSessionId;
2596
+ }
2597
+ shared;
2598
+ ownSessionId;
2599
+ ownSequence = 0;
2600
+ next(sessionId) {
2601
+ return sessionId === this.ownSessionId ? ++this.ownSequence : this.shared.next(sessionId);
2602
+ }
2603
+ };
2338
2604
 
2339
2605
  // src/integrations/mcp/zodCompat.ts
2340
2606
  import * as z3rt from "zod/v3";
@@ -2552,6 +2818,7 @@ function buildSeamAugmentations(options) {
2552
2818
  var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
2553
2819
  var wired = /* @__PURE__ */ new WeakSet();
2554
2820
  var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
2821
+ var INTENT_PARAM_NAMES = [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES];
2555
2822
  var callSlots = new AsyncLocalStorage();
2556
2823
  var SurfaceState = class {
2557
2824
  constructor(serverMeta, sentSurfaces) {
@@ -2614,14 +2881,14 @@ async function resolveEnvelopeParts(ctx, extra) {
2614
2881
  const session = await resolveSessionId(ctx.fallbackSessionId, extra);
2615
2882
  return { ...session, scrubbedMeta };
2616
2883
  }
2617
- async function openCall(ctx, toolName, extra, params, retired, registered = true) {
2884
+ async function openCall(ctx, toolName, extra, params, stripped, registered = true) {
2618
2885
  await maybeEmitSurfaceSnapshot(ctx);
2619
2886
  const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
2620
2887
  const dispositions = ctx.paramRegistry.get(toolName);
2621
- const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
2888
+ const rawIntent = stripped[USER_GOAL_PARAM_NAME] ?? extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
2622
2889
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
2623
2890
  const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
2624
- (name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, retired[name] ?? popText(params, name), name)
2891
+ (name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
2625
2892
  );
2626
2893
  const caller = await resolveCaller(
2627
2894
  ctx.resolvePrincipal,
@@ -2671,9 +2938,9 @@ function batonWrap(nameRef, original, ctx) {
2671
2938
  if (slot) slot.innerFired = true;
2672
2939
  const extra = callArgs[callArgs.length - 1];
2673
2940
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
2674
- const retired = slot?.retired ?? {};
2675
- if (slot) slot.retired = {};
2676
- const { common, session } = await openCall(ctx, toolName, extra, params, retired);
2941
+ const stripped = slot?.strippedFor === toolName ? slot.stripped : {};
2942
+ if (slot) slot.strippedFor = null;
2943
+ const { common, session } = await openCall(ctx, toolName, extra, params, stripped);
2677
2944
  const terminate = async (build, replacement) => {
2678
2945
  if (!slot) {
2679
2946
  if (build !== null) await emit(ctx.sink, build);
@@ -2849,19 +3116,19 @@ function popText(args, paramName) {
2849
3116
  delete args[paramName];
2850
3117
  return typeof raw === "string" && !isBlank(raw) ? raw : null;
2851
3118
  }
2852
- function stripRetiredParams(params, ctx) {
3119
+ function stripIntentParams(params, ctx) {
2853
3120
  const toolName = params?.name;
2854
3121
  const args = params?.arguments;
2855
3122
  if (typeof toolName !== "string") return {};
2856
3123
  if (toolName === ctx.annotationToolName) return {};
2857
3124
  if (typeof args !== "object" || args === null || Array.isArray(args)) return {};
2858
3125
  const dispositions = ctx.paramRegistry.get(toolName);
2859
- const retired = {};
2860
- for (const name of RETIRED_PARAM_NAMES) {
3126
+ const stripped = {};
3127
+ for (const name of INTENT_PARAM_NAMES) {
2861
3128
  if (dispositions === void 0 || dispositions[name] === "native" || !(name in args)) continue;
2862
- retired[name] = popText(args, name);
3129
+ stripped[name] = popText(args, name);
2863
3130
  }
2864
- return retired;
3131
+ return stripped;
2865
3132
  }
2866
3133
  async function maybeEmitSurfaceSnapshot(ctx) {
2867
3134
  if (!ctx.surfaceState.dirty) return;
@@ -2897,7 +3164,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
2897
3164
  }
2898
3165
  function declaredIntentParams(vendorSchema) {
2899
3166
  const declared2 = {};
2900
- for (const name of [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES]) {
3167
+ for (const name of INTENT_PARAM_NAMES) {
2901
3168
  if (declaresParam(vendorSchema, name)) declared2[name] = "native";
2902
3169
  }
2903
3170
  return declared2;
@@ -3163,10 +3430,12 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
3163
3430
  TOOLS_CALL_SEAM,
3164
3431
  (handler) => async (...args) => {
3165
3432
  const request = args[0];
3433
+ const name = request?.params?.name;
3166
3434
  const slot = {
3167
3435
  innerFired: false,
3168
3436
  flushTerminal: null,
3169
- retired: stripRetiredParams(request?.params, ctx),
3437
+ stripped: stripIntentParams(request?.params, ctx),
3438
+ strippedFor: typeof name === "string" ? name : null,
3170
3439
  validation: "unseen"
3171
3440
  };
3172
3441
  let outcome = CLEAN_OUTCOME;
@@ -3232,7 +3501,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
3232
3501
  toolName,
3233
3502
  args[1],
3234
3503
  params,
3235
- slot.retired,
3504
+ slot.stripped,
3236
3505
  entry != null
3237
3506
  );
3238
3507
  const failureKind = requestSideFailureKind(entry, slot.validation);
@@ -3341,23 +3610,13 @@ function withBaton(server, supplied = {}) {
3341
3610
  const disabledBy = captureDisabled();
3342
3611
  if (disabledBy !== null) {
3343
3612
  logDisabled(disabledBy, "withBaton");
3344
- return new BatonHandle({
3345
- // A sink the VENDOR constructed is held rather than dropped, so their
3346
- // `handle.aclose()` still releases it — we took ownership of that object
3347
- // the moment they passed it, and the switch does not undo that. Nothing
3348
- // writes to it: nothing is wrapped.
3349
- sink: supplied.sink ?? new DisabledSink(),
3350
- // Empty, and a constant, because when the switch is on nothing was
3351
- // resolved: inventing a session id would put a real identifier on a
3352
- // handle whose whole meaning is that no events exist under it.
3353
- vendorId: "",
3354
- sessionId: "baton-disabled",
3355
- annotationToolName: ""
3356
- });
3613
+ return inertHandle(supplied.sink ?? new DisabledSink(), "baton-disabled");
3357
3614
  }
3358
- const resolved = resolveBatonConfig(supplied);
3359
- warnUnusedReportSettings(resolved);
3360
- return install(server, supplied, resolved, new SentSurfaces(), /* @__PURE__ */ new Set());
3615
+ const { resolved, unconfigured } = resolveInstallConfig(supplied);
3616
+ if (!unconfigured) warnUnusedReportSettings(resolved);
3617
+ const handle = install(server, supplied, resolved, newBatonState(resolved), unconfigured);
3618
+ if (unconfigured) logUnconfigured("withBaton");
3619
+ return handle;
3361
3620
  }
3362
3621
  function createBaton(supplied = {}) {
3363
3622
  const disabledBy = captureDisabled();
@@ -3371,40 +3630,61 @@ function createBaton(supplied = {}) {
3371
3630
  aclose: () => boundedSinkCall(unused, "aclose")
3372
3631
  };
3373
3632
  }
3374
- const resolved = resolveBatonConfig(supplied);
3375
- warnUnusedReportSettings(resolved);
3633
+ const { resolved, unconfigured } = resolveInstallConfig(supplied);
3376
3634
  if (resolved.reportMode === "on") deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
3377
- const sink = resolved.sink ?? new StdoutSink();
3635
+ if (unconfigured) logUnconfigured("createBaton");
3636
+ else warnUnusedReportSettings(resolved);
3637
+ const sink = unconfigured ? new DisabledSink() : resolved.sink ?? new StdoutSink();
3378
3638
  const config = {
3379
3639
  ...resolved,
3380
3640
  sink,
3381
3641
  tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
3382
3642
  };
3383
- const sentSurfaces = new SentSurfaces();
3384
- const warned3 = /* @__PURE__ */ new Set();
3643
+ const state = newBatonState(resolved);
3385
3644
  return {
3386
3645
  wrap: (server) => {
3387
- install(server, supplied, config, sentSurfaces, warned3);
3646
+ install(server, supplied, config, state, unconfigured);
3388
3647
  },
3389
3648
  flush: () => boundedSinkCall(sink, "flush"),
3390
3649
  aclose: () => boundedSinkCall(sink, "aclose")
3391
3650
  };
3392
3651
  }
3393
- function install(server, supplied, resolved, sentSurfaces, warned3) {
3652
+ function inertHandle(sink, sessionId) {
3653
+ return new BatonHandle({ sink, sessionId, vendorId: "", annotationToolName: "" });
3654
+ }
3655
+ function requireHighLevelServer(server) {
3656
+ const candidate = server;
3657
+ if (typeof candidate?.registerTool !== "function" || typeof candidate.server !== "object" || candidate.server === null) {
3658
+ throw new TypeError(
3659
+ "Baton needs a high-level McpServer (from @modelcontextprotocol/sdk/server/mcp.js or @modelcontextprotocol/server); the low-level Server is not supported."
3660
+ );
3661
+ }
3662
+ }
3663
+ function newBatonState(config) {
3664
+ return {
3665
+ sentSurfaces: new SentSurfaces(),
3666
+ warned: /* @__PURE__ */ new Set(),
3667
+ counter: new SessionCounter(),
3668
+ scrubber: config.scrubber ?? new Scrubber().scrub
3669
+ };
3670
+ }
3671
+ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber }, unconfigured) {
3672
+ requireHighLevelServer(server);
3394
3673
  const internals = server;
3395
3674
  const serverName = usableServerName(() => ({
3396
3675
  name: internals.server._serverInfo?.name,
3397
3676
  className: internals.constructor.name
3398
3677
  }));
3399
3678
  const config = resolved.reportMode === "on" ? withServerDisplayName(resolved, supplied, serverName) : resolved;
3400
- const sink = config.sink ?? new StdoutSink();
3401
3679
  const reports = reportsFor(config);
3402
3680
  const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
3681
+ const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
3682
+ if (unconfigured) return inertHandle(new DisabledSink(), "baton-unconfigured");
3683
+ const sink = config.sink ?? new StdoutSink();
3403
3684
  const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
3404
- const counter2 = new SessionCounter();
3405
3685
  const fallbackSessionId = `sdk-${uuid7()}`;
3686
+ const counter2 = new ServerCounter(sharedCounter, fallbackSessionId);
3406
3687
  const tenantId = resolveTenantId(config.tenantId, config.vendorId);
3407
- const scrubber = config.scrubber ?? new Scrubber().scrub;
3408
3688
  const serverMeta = buildServerMeta(server.server);
3409
3689
  const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
3410
3690
  const emitSurface = async (sessionId, digest, snapshot) => {
@@ -3499,7 +3779,6 @@ function install(server, supplied, resolved, sentSurfaces, warned3) {
3499
3779
  surfaceState,
3500
3780
  emitSurface
3501
3781
  };
3502
- const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
3503
3782
  internals.server._instructions = withVendorInstructions(
3504
3783
  internals.server,
3505
3784
  ours,