@goodtiming/baton-sdk 0.6.2 → 0.6.4

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.cjs CHANGED
@@ -76,6 +76,7 @@ __export(index_exports, {
76
76
  ResourceReadStartPayloadSchema: () => ResourceReadStartPayloadSchema,
77
77
  SDK_VERSION: () => SDK_VERSION,
78
78
  Scrubber: () => Scrubber,
79
+ SinkClosedError: () => SinkClosedError,
79
80
  StdoutSink: () => StdoutSink,
80
81
  SurfaceSnapshotEventSchema: () => SurfaceSnapshotEventSchema,
81
82
  SurfaceSnapshotPayloadSchema: () => SurfaceSnapshotPayloadSchema,
@@ -102,7 +103,7 @@ __export(index_exports, {
102
103
  module.exports = __toCommonJS(index_exports);
103
104
 
104
105
  // src/version.ts
105
- var SDK_VERSION = "ts-0.6.2";
106
+ var SDK_VERSION = "ts-0.6.4";
106
107
 
107
108
  // src/events.ts
108
109
  var import_zod = require("zod");
@@ -683,7 +684,7 @@ var DropCounts = class {
683
684
  const lost = [...this.#sinceDelivery].sort(([a], [b]) => a.localeCompare(b));
684
685
  this.#sinceDelivery.clear();
685
686
  this.#lastRecoveryLog = now;
686
- const total = lost.reduce((sum, [, n]) => sum + n, 0);
687
+ const total = lost.reduce((sum2, [, n]) => sum2 + n, 0);
687
688
  warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(", ")}.`);
688
689
  }
689
690
  /** For tests: the counts are one per process. */
@@ -711,10 +712,24 @@ function nextClockSequence() {
711
712
  // src/sinks.ts
712
713
  var REFUSAL_BODY_MAX_LEN = 500;
713
714
  var REFUSAL_LOG_MS = 6e4;
715
+ var SinkClosedError = class extends Error {
716
+ name = "SinkClosedError";
717
+ };
718
+ function isSinkClosed(err) {
719
+ return err instanceof Error && err.name === "SinkClosedError";
720
+ }
721
+ var warnedClosed = /* @__PURE__ */ new WeakSet();
722
+ function droppedAfterClose(sink) {
723
+ PROCESS_DROPS.add("after_close");
724
+ if (warnedClosed.has(sink)) return;
725
+ warnedClosed.add(sink);
726
+ warn("baton: the sink is closed; further events are dropped.");
727
+ }
714
728
  async function safeWrite(sink, event) {
715
729
  try {
716
730
  await sink.write(event);
717
731
  } catch (err) {
732
+ if (isSinkClosed(err)) return droppedAfterClose(sink);
718
733
  PROCESS_DROPS.add("write_failed");
719
734
  process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}
720
735
  `);
@@ -727,12 +742,10 @@ function stderrLine(message) {
727
742
  function isTimerMs(value) {
728
743
  return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
729
744
  }
730
- function shutdownFlushTimeoutOption(given) {
745
+ function timerMsOption(given, name, fallback) {
731
746
  if (isTimerMs(given)) return given;
732
- if (given !== void 0) {
733
- warn(`baton: shutdownFlushTimeoutMs must be from 0 to ${MAX_TIMER_MS} ms; using ${SHUTDOWN_FLUSH_TIMEOUT_MS}.`);
734
- }
735
- return SHUTDOWN_FLUSH_TIMEOUT_MS;
747
+ if (given !== void 0) warn(`baton: ${name} must be from 0 to ${MAX_TIMER_MS} ms; using ${fallback}.`);
748
+ return fallback;
736
749
  }
737
750
  function shutdownBudgetMs(sink) {
738
751
  try {
@@ -767,7 +780,7 @@ var StdoutSink = class {
767
780
  this.stream = options.stream ?? process.stderr;
768
781
  }
769
782
  async write(event) {
770
- if (this.closed) throw new Error("StdoutSink is closed");
783
+ if (this.closed) throw new SinkClosedError("StdoutSink is closed");
771
784
  this.stream.write(JSON.stringify(event) + "\n");
772
785
  }
773
786
  async flush() {
@@ -784,7 +797,7 @@ var FileSink = class {
784
797
  fd = null;
785
798
  closed = false;
786
799
  async write(event) {
787
- if (this.closed) throw new Error("FileSink is closed");
800
+ if (this.closed) throw new SinkClosedError("FileSink is closed");
788
801
  this.fd ??= (0, import_node_fs.openSync)(this.path, "a");
789
802
  (0, import_node_fs.writeSync)(this.fd, JSON.stringify(event) + "\n");
790
803
  }
@@ -822,11 +835,38 @@ var MultiSink = class {
822
835
  }
823
836
  async fanOut(op) {
824
837
  const results = await Promise.allSettled(this.sinks.map(async (sink) => op(sink)));
825
- const errors = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
826
- if (errors.length === 1) throw errors[0];
827
- if (errors.length > 1) throw new AggregateError(errors, "MultiSink fan-out failures");
838
+ let errors = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
839
+ if (errors.length < results.length) errors = errors.filter((e) => !isSinkClosed(e));
840
+ if (errors.length === 0) return;
841
+ if (errors.length === 1 || errors.every(isSinkClosed)) throw errors[0];
842
+ throw new AggregateError(errors, "MultiSink fan-out failures");
828
843
  }
829
844
  };
845
+ var BATCH_OPEN = '{"events":[';
846
+ var BATCH_CLOSE = "]}";
847
+ var BATCH_FRAME_BYTES = (BATCH_OPEN + BATCH_CLOSE).length;
848
+ var BATCH_MAX_EVENTS = 100;
849
+ var BATCH_MAX_BYTES = 1048576;
850
+ var FLUSH_INTERVAL_MS = 5e3;
851
+ var RETRY_AFTER_MIN_S = 1;
852
+ var RETRY_AFTER_MAX_S = 60;
853
+ var utf8 = new TextEncoder();
854
+ function utf8Bytes(text) {
855
+ return typeof Buffer === "undefined" ? utf8.encode(text).length : Buffer.byteLength(text, "utf8");
856
+ }
857
+ function sum(values) {
858
+ let total = 0;
859
+ for (const value of values) total += value;
860
+ return total;
861
+ }
862
+ function retryAfterMs(header) {
863
+ const value = header?.trim() ?? "";
864
+ if (!/^\d+$/.test(value)) return null;
865
+ return Math.min(Math.max(Number(value), RETRY_AFTER_MIN_S), RETRY_AFTER_MAX_S) * 1e3;
866
+ }
867
+ function sameBatch(a, b) {
868
+ return a.tenant_id === b.tenant_id && a.vendor_id === b.vendor_id;
869
+ }
830
870
  var CircuitBreaker = class {
831
871
  constructor(threshold, resetMs) {
832
872
  this.threshold = threshold;
@@ -837,8 +877,11 @@ var CircuitBreaker = class {
837
877
  failures = 0;
838
878
  openedAt = null;
839
879
  canRequest() {
840
- if (this.openedAt === null) return true;
841
- return Date.now() - this.openedAt >= this.resetMs;
880
+ return this.msUntilRequest() === 0;
881
+ }
882
+ msUntilRequest() {
883
+ if (this.openedAt === null) return 0;
884
+ return Math.max(this.openedAt + this.resetMs - Date.now(), 0);
842
885
  }
843
886
  recordSuccess() {
844
887
  this.failures = 0;
@@ -854,12 +897,17 @@ var CircuitBreaker = class {
854
897
  var HttpSink = class _HttpSink {
855
898
  url;
856
899
  apiKey;
900
+ /** Waiting events only: a batch being sent is out of it, so the bound
901
+ * never pushes out an event in flight (SPEC §11.2 rule 4). */
857
902
  buffer = [];
903
+ bufferedBytes = 0;
904
+ sendingEvents = 0;
858
905
  bufferSize;
859
906
  requestTimeoutMs;
860
907
  shutdownFlushTimeoutMs;
861
- /** Set when an exit pass ends; cleared once a normal drain empties the
862
- * buffer, which means the process went on. */
908
+ flushIntervalMs;
909
+ /** Set when an exit pass ends; cleared once a normal drain sends
910
+ * everything, which means the process went on. */
863
911
  exitPassRan = false;
864
912
  /** Whether the exit pass warned about every event now buffered. */
865
913
  unsentWarned = false;
@@ -869,7 +917,8 @@ var HttpSink = class _HttpSink {
869
917
  circuit;
870
918
  fetchImpl;
871
919
  overflowWarned = false;
872
- /** Per status, so a new kind of refusal, such as a 401 after a 422, still warns. */
920
+ /** Per status or refusal code, so a new kind of refusal, such as a 401
921
+ * after a 422, still warns. */
873
922
  refusals = /* @__PURE__ */ new Map();
874
923
  /** Aborted once `aclose()` returns: nothing Baton started may keep the
875
924
  * process alive after the vendor closed it. */
@@ -879,6 +928,16 @@ var HttpSink = class _HttpSink {
879
928
  skipWarnedFor = null;
880
929
  closeOnce;
881
930
  drainChain = Promise.resolve();
931
+ queuedDrain = null;
932
+ /** Whether the queued pass sends everything waiting, not only what is due. */
933
+ forceNext = false;
934
+ flushTimer = null;
935
+ /** Set by a failed batch: only the timer, a flush or a close tries again. */
936
+ waitForTimer = false;
937
+ /** Nothing is sent before this `Date.now()`, from a 429's `Retry-After`. */
938
+ retryAt = 0;
939
+ /** Set for the life of the sink by a 404 or 405 on the batch path. */
940
+ batchless = false;
882
941
  exitHooks = null;
883
942
  /** The least time between two of this sink's loss reports. */
884
943
  static reportIntervalMs = 6e4;
@@ -886,13 +945,20 @@ var HttpSink = class _HttpSink {
886
945
  reportedSum = 0;
887
946
  lastReportAt = -Infinity;
888
947
  reportsStopped = false;
889
- reportInFlight = null;
948
+ /** The envelope of a report due to ride the next batch, and when it was set up. */
949
+ pendingReport = null;
950
+ reportSetAt = 0;
890
951
  constructor(url, options) {
891
952
  this.url = url.replace(/\/+$/, "");
892
953
  this.apiKey = options.apiKey;
893
954
  this.bufferSize = options.bufferSize ?? 1e3;
894
955
  this.requestTimeoutMs = options.requestTimeoutMs ?? 1e3;
895
- this.shutdownFlushTimeoutMs = shutdownFlushTimeoutOption(options.shutdownFlushTimeoutMs);
956
+ this.shutdownFlushTimeoutMs = timerMsOption(
957
+ options.shutdownFlushTimeoutMs,
958
+ "shutdownFlushTimeoutMs",
959
+ SHUTDOWN_FLUSH_TIMEOUT_MS
960
+ );
961
+ this.flushIntervalMs = timerMsOption(options.flushIntervalMs, "flushIntervalMs", FLUSH_INTERVAL_MS);
896
962
  this.maxRetries = options.maxRetries ?? 3;
897
963
  this.backoffBaseMs = options.backoffBaseMs ?? 100;
898
964
  this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
@@ -922,11 +988,24 @@ var HttpSink = class _HttpSink {
922
988
  get closed() {
923
989
  return this.closing.signal.aborted;
924
990
  }
991
+ get unsent() {
992
+ return this.buffer.length + this.sendingEvents;
993
+ }
994
+ /** Encodes at once, not when the batch is cut, because the byte cap
995
+ * decides when a batch goes. */
925
996
  async write(event) {
926
- if (this.closed) throw new Error("HttpSink is closed");
927
- this.enqueue(event);
997
+ if (this.closed) throw new SinkClosedError("HttpSink is closed");
998
+ const json = this.encode(event);
999
+ if (json === null) return;
1000
+ const bytes = utf8Bytes(json);
1001
+ if (BATCH_FRAME_BYTES + bytes > BATCH_MAX_BYTES) {
1002
+ this.refuse(1, { kind: "over 1 MiB", detail: `${bytes} bytes` }, false);
1003
+ return;
1004
+ }
1005
+ this.enqueue({ event, json, bytes, writtenAt: Date.now() });
928
1006
  this.unsentWarned = false;
929
- void this.scheduleDrain();
1007
+ if (this.batchIsFull() && !this.waitForTimer) void this.scheduleDrain(false);
1008
+ else this.armTimer(this.buffer[0].writtenAt + this.flushIntervalMs - Date.now());
930
1009
  this.ensureExitHooksRegistered();
931
1010
  }
932
1011
  flush() {
@@ -948,9 +1027,11 @@ var HttpSink = class _HttpSink {
948
1027
  this.stopReports();
949
1028
  await this.drainWithinBudget("aclose()", ms);
950
1029
  this.closing.abort();
951
- if (this.buffer.length > 0) {
952
- PROCESS_DROPS.add("unsent_at_close", this.buffer.length);
953
- warn(`baton: the sink closed with ${this.buffer.length} event(s) unsent.`);
1030
+ this.clearTimer();
1031
+ const unsent = this.unsent;
1032
+ if (unsent > 0) {
1033
+ PROCESS_DROPS.add("unsent_at_close", unsent);
1034
+ warn(`baton: the sink closed with ${unsent} event(s) unsent.`);
954
1035
  }
955
1036
  this.warnUnloggedRefusals("the sink closed");
956
1037
  if (this.exitHooks) {
@@ -972,11 +1053,11 @@ var HttpSink = class _HttpSink {
972
1053
  }
973
1054
  if (this.skipWarnedFor !== this.stalledDrain) {
974
1055
  this.skipWarnedFor = this.stalledDrain;
975
- warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.buffer.length} event(s) wait to be sent.`);
1056
+ warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.unsent} event(s) wait to be sent.`);
976
1057
  }
977
1058
  return;
978
1059
  }
979
- const settled = this.scheduleDrain().catch(() => void 0);
1060
+ const settled = this.scheduleDrain(true).catch(() => void 0);
980
1061
  if (await raceDeadline(settled, ms) !== TIMED_OUT) return;
981
1062
  if (ms < this.shutdownFlushTimeoutMs) return;
982
1063
  const stalled = this.drainChain.catch(() => void 0);
@@ -988,12 +1069,13 @@ var HttpSink = class _HttpSink {
988
1069
  warn(`baton: flush() took over ${ms} ms; it goes on in the background.`);
989
1070
  }
990
1071
  }
991
- /** A full buffer may already have pushed `event` out while it was being sent. */
992
- dequeue(event) {
993
- if (this.buffer[0] === event) this.buffer.shift();
1072
+ enqueue(waiting) {
1073
+ this.buffer.push(waiting);
1074
+ this.bufferedBytes += waiting.bytes;
1075
+ this.dropOverflow();
994
1076
  }
995
- enqueue(event) {
996
- if (this.buffer.length >= this.bufferSize) {
1077
+ dropOverflow() {
1078
+ while (this.buffer.length > this.bufferSize) {
997
1079
  PROCESS_DROPS.add("buffer_full");
998
1080
  if (!this.overflowWarned) {
999
1081
  warn(
@@ -1001,21 +1083,49 @@ var HttpSink = class _HttpSink {
1001
1083
  );
1002
1084
  this.overflowWarned = true;
1003
1085
  }
1004
- this.buffer.shift();
1086
+ this.bufferedBytes -= this.buffer.shift().bytes;
1005
1087
  }
1006
- this.buffer.push(event);
1007
- }
1008
- /** Serializes every call to `drainLocked` — from `write()`'s background
1009
- * drain and from explicit `flush()` alike — onto one promise chain, so
1010
- * concurrent tool calls (the normal case once the MCP interceptor is
1011
- * wired up) can never run two drains at once racing on `buffer[0]`/
1012
- * `shift()`. Mirrors Python's `asyncio.Lock` around `_drain_locked`. */
1013
- scheduleDrain() {
1014
- this.drainChain = this.drainChain.then(
1015
- () => this.drainLocked(),
1016
- () => this.drainLocked()
1088
+ }
1089
+ batchIsFull() {
1090
+ return this.buffer.length >= BATCH_MAX_EVENTS || BATCH_FRAME_BYTES + this.bufferedBytes + this.buffer.length - 1 > BATCH_MAX_BYTES;
1091
+ }
1092
+ /** The timer must not keep the vendor's process alive: the exit hooks send
1093
+ * what is left. */
1094
+ armTimer(delayMs) {
1095
+ if (this.flushTimer !== null || this.closed) return;
1096
+ const timer = setTimeout(
1097
+ () => {
1098
+ this.flushTimer = null;
1099
+ this.waitForTimer = false;
1100
+ void this.scheduleDrain(false);
1101
+ },
1102
+ Math.min(Math.max(delayMs, 0), MAX_TIMER_MS)
1017
1103
  );
1018
- return this.drainChain;
1104
+ timer.unref?.();
1105
+ this.flushTimer = timer;
1106
+ }
1107
+ clearTimer() {
1108
+ if (this.flushTimer === null) return;
1109
+ clearTimeout(this.flushTimer);
1110
+ this.flushTimer = null;
1111
+ }
1112
+ /** Runs `drainLocked` after the pass under way, one pass at a time, so two
1113
+ * never send at once or race on the buffer. A pass not yet started is
1114
+ * shared by every caller: one per write would grow without bound while a
1115
+ * slow collector holds a pass. */
1116
+ scheduleDrain(force) {
1117
+ this.forceNext ||= force;
1118
+ if (this.queuedDrain) return this.queuedDrain;
1119
+ const run = () => {
1120
+ this.queuedDrain = null;
1121
+ const forced = this.forceNext;
1122
+ this.forceNext = false;
1123
+ return this.drainLocked(forced);
1124
+ };
1125
+ this.queuedDrain = this.drainChain.then(run, run);
1126
+ this.queuedDrain.catch(() => void 0);
1127
+ this.drainChain = this.queuedDrain;
1128
+ return this.queuedDrain;
1019
1129
  }
1020
1130
  /** Best-effort flush when the process is about to exit without an
1021
1131
  * explicit `aclose()`. SIGKILL, or SIGTERM with no installed handler, skip
@@ -1024,18 +1134,18 @@ var HttpSink = class _HttpSink {
1024
1134
  ensureExitHooksRegistered() {
1025
1135
  if (this.exitHooks) return;
1026
1136
  const beforeExit = () => {
1027
- if (this.buffer.length === 0 || this.exitPassRan) {
1137
+ if (this.unsent === 0 || this.exitPassRan) {
1028
1138
  this.warnUnloggedRefusals("process exiting");
1029
1139
  return;
1030
1140
  }
1031
1141
  this.drainChain = this.drainChain.then(
1032
1142
  () => this.exitPass(),
1033
1143
  () => this.exitPass()
1034
- );
1144
+ ).catch(() => void 0);
1035
1145
  };
1036
1146
  const exit = () => {
1037
1147
  try {
1038
- if (this.buffer.length > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
1148
+ if (this.unsent > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
1039
1149
  this.warnUnloggedRefusals("process exiting", stderrLine);
1040
1150
  } catch {
1041
1151
  }
@@ -1044,35 +1154,22 @@ var HttpSink = class _HttpSink {
1044
1154
  process.on("beforeExit", beforeExit);
1045
1155
  process.on("exit", exit);
1046
1156
  }
1047
- /** One attempt per event, no retry, within `shutdownFlushTimeoutMs` in
1157
+ /** One attempt per batch, no retry, within `shutdownFlushTimeoutMs` in
1048
1158
  * total (SPEC §11.2); what is left is reported, not sent. */
1049
1159
  async exitPass() {
1050
1160
  const deadline = Date.now() + this.shutdownFlushTimeoutMs;
1051
- while (this.buffer.length > 0 && this.circuit.canRequest()) {
1052
- const timeLeft = deadline - Date.now();
1053
- if (timeLeft <= 0) break;
1054
- const event = this.buffer[0];
1055
- const body = this.encode(event);
1056
- if (body !== null) {
1057
- const outcome = await this.postOnce(body, Math.min(this.requestTimeoutMs, timeLeft));
1058
- if (outcome === "transient_failure") {
1059
- this.circuit.recordFailure();
1060
- break;
1061
- }
1062
- this.circuit.recordSuccess();
1063
- }
1064
- this.dequeue(event);
1161
+ while (this.circuit.canRequest() && Date.now() >= this.retryAt && Date.now() < deadline) {
1162
+ const batch = this.takeBatch(false);
1163
+ if (batch === null) break;
1164
+ if (!this.putBack(await this.sendBatch(batch, 0, deadline))) break;
1065
1165
  }
1066
1166
  this.exitPassRan = true;
1067
1167
  this.unsentWarned = true;
1068
- if (this.buffer.length > 0) warn(this.unsentAtExit());
1168
+ if (this.unsent > 0) warn(this.unsentAtExit());
1069
1169
  this.warnUnloggedRefusals("process exiting");
1070
1170
  }
1071
1171
  unsentAtExit() {
1072
- return `baton: process exiting with ${this.buffer.length} unsent event(s).`;
1073
- }
1074
- events_url() {
1075
- return `${this.url}/v0/events`;
1172
+ return `baton: process exiting with ${this.unsent} unsent event(s).`;
1076
1173
  }
1077
1174
  authHeaders() {
1078
1175
  return { Authorization: `Bearer ${this.apiKey}`, "Content-Type": "application/json" };
@@ -1082,17 +1179,19 @@ var HttpSink = class _HttpSink {
1082
1179
  if (status >= 400 && status < 500 && status !== 429) return "permanent_failure";
1083
1180
  return "transient_failure";
1084
1181
  }
1085
- /** A refused event is otherwise dropped silently, which looks the same from
1086
- * the vendor's process as an accepted one. The collector's own message is
1087
- * logged because it names the field at fault; it is capped and escaped
1182
+ /** Counts `n` refused events and logs them, at most once a minute per
1183
+ * kind. A refused event is otherwise dropped silently, which looks the same
1184
+ * from the vendor's process as an accepted one. The collector's own message
1185
+ * is logged because it names the field at fault; it is capped and escaped
1088
1186
  * because it is a remote server's text landing in the vendor's log. */
1089
- static async logRefusal(response, unlogged) {
1090
- const detail = await _HttpSink.readHead(response).then(
1091
- (text) => escapeForLog(capCodePoints(text, REFUSAL_BODY_MAX_LEN)),
1092
- () => "<unreadable>"
1093
- );
1187
+ refuse(n, { kind, detail }, byCollector = true) {
1188
+ if (n === 0) return;
1189
+ PROCESS_DROPS.add("refused", n);
1190
+ const unlogged = this.refusalToLog(kind, n);
1191
+ if (unlogged === null) return;
1192
+ const what = n === 1 ? "an event and it has" : `${n} events and they have`;
1094
1193
  warn(
1095
- `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.` : "")
1194
+ `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.` : "")
1096
1195
  );
1097
1196
  }
1098
1197
  warnUnloggedRefusals(when, emit2 = warn) {
@@ -1103,16 +1202,16 @@ var HttpSink = class _HttpSink {
1103
1202
  }
1104
1203
  if (total > 0) emit2(`baton: ${when}; ${total} more event(s) refused since the last such warning.`);
1105
1204
  }
1106
- /** How many refusals with `status` went unlogged before this one, or `null`
1107
- * when this one goes unlogged too. */
1108
- refusalToLog(status) {
1205
+ /** How many refusals of `kind` went unlogged before these `n`, or `null`
1206
+ * when these go unlogged too. */
1207
+ refusalToLog(kind, n) {
1109
1208
  const now = performance.now();
1110
- const seen = this.refusals.get(status);
1209
+ const seen = this.refusals.get(kind);
1111
1210
  if (seen !== void 0 && now - seen.loggedAt < REFUSAL_LOG_MS) {
1112
- seen.unlogged++;
1211
+ seen.unlogged += n;
1113
1212
  return null;
1114
1213
  }
1115
- this.refusals.set(status, { loggedAt: now, unlogged: 0 });
1214
+ this.refusals.set(kind, { loggedAt: now, unlogged: 0 });
1116
1215
  return seen?.unlogged ?? 0;
1117
1216
  }
1118
1217
  /** Enough of the body for `REFUSAL_BODY_MAX_LEN` code points; the rest is
@@ -1134,87 +1233,205 @@ var HttpSink = class _HttpSink {
1134
1233
  });
1135
1234
  }
1136
1235
  }
1137
- async drainLocked() {
1138
- while (this.buffer.length > 0) {
1139
- if (!this.circuit.canRequest() || this.closing.signal.aborted) return;
1140
- const event = this.buffer[0];
1141
- const outcome = await this.sendWithRetry(event);
1142
- if (outcome === "success" || outcome === "permanent_failure") {
1143
- this.dequeue(event);
1144
- this.circuit.recordSuccess();
1145
- if (outcome === "success") {
1146
- PROCESS_DROPS.logRecovery();
1147
- this.maybeReport(event);
1148
- }
1149
- } else if (outcome === "unencodable") {
1150
- this.dequeue(event);
1151
- } else {
1152
- this.circuit.recordFailure();
1153
- return;
1236
+ /** Sends what is due, one batch at a time; `force` (a flush or close) sends
1237
+ * everything waiting. A report set up before the pass rides along; one set
1238
+ * up by this pass's own delivery waits for the next batch. */
1239
+ async drainLocked(force) {
1240
+ let failed = false;
1241
+ let reportDue = this.pendingReport !== null;
1242
+ while (!this.closed) {
1243
+ if (!this.isDue(force, reportDue)) break;
1244
+ if (!this.circuit.canRequest() || Date.now() < this.retryAt) {
1245
+ failed = true;
1246
+ break;
1247
+ }
1248
+ const batch = this.takeBatch(reportDue);
1249
+ if (batch === null) break;
1250
+ if (batch.some((w) => w.reportSum !== void 0)) reportDue = false;
1251
+ if (!this.putBack(await this.sendBatch(batch, this.maxRetries, Infinity))) {
1252
+ failed = true;
1253
+ break;
1254
+ }
1255
+ }
1256
+ if (!failed && this.unsent === 0) this.exitPassRan = false;
1257
+ this.waitForTimer = failed;
1258
+ this.clearTimer();
1259
+ if (failed) {
1260
+ const waits = [this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest()];
1261
+ if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(Math.max(...waits));
1262
+ return;
1263
+ }
1264
+ const next = Math.min(this.buffer[0]?.writtenAt ?? Infinity, this.reportRidesHead() ? this.reportSetAt : Infinity);
1265
+ if (next !== Infinity) this.armTimer(next + this.flushIntervalMs - Date.now());
1266
+ }
1267
+ /** A due report makes the next batch due only when it can ride it; the
1268
+ * timer is armed the same way, so a pass that sends nothing never re-arms
1269
+ * it at a time already past. */
1270
+ isDue(force, reportDue) {
1271
+ const now = Date.now();
1272
+ if (reportDue && this.reportRidesHead() && (force || this.reportSetAt + this.flushIntervalMs <= now)) return true;
1273
+ return this.buffer.length > 0 && (force || this.batchIsFull() || this.buffer[0].writtenAt + this.flushIntervalMs <= now);
1274
+ }
1275
+ /** A pending report can go in the next batch: alone, or with the head event's tenant and vendor. */
1276
+ reportRidesHead() {
1277
+ const head = this.buffer[0];
1278
+ return this.pendingReport !== null && (head === void 0 || sameBatch(this.pendingReport, head.event));
1279
+ }
1280
+ /** Takes the head of the buffer that fits one batch: one tenant and vendor
1281
+ * (SPEC §2.5), at most 100 events and 1 MiB. A due report with the head
1282
+ * event's tenant and vendor takes one of those places; otherwise it is not
1283
+ * built, and waits for a batch it can ride. Without a batch endpoint the same events go one
1284
+ * per request. */
1285
+ takeBatch(withReport) {
1286
+ const batch = [];
1287
+ let bytes = BATCH_FRAME_BYTES - 1;
1288
+ let eventBytes = 0;
1289
+ const fits = (w, maxEvents2 = BATCH_MAX_EVENTS, maxBytes2 = BATCH_MAX_BYTES) => batch.length === 0 || batch.length < maxEvents2 && sameBatch(w.event, batch[0].event) && bytes + 1 + w.bytes <= maxBytes2;
1290
+ const report = withReport && this.reportRidesHead() ? this.buildReport() : null;
1291
+ const maxEvents = BATCH_MAX_EVENTS - (report ? 1 : 0);
1292
+ const maxBytes = BATCH_MAX_BYTES - (report ? 1 + report.bytes : 0);
1293
+ for (const waiting of this.buffer) {
1294
+ if (!fits(waiting, maxEvents, maxBytes)) break;
1295
+ batch.push(waiting);
1296
+ bytes += 1 + waiting.bytes;
1297
+ eventBytes += waiting.bytes;
1298
+ }
1299
+ this.buffer.splice(0, batch.length);
1300
+ this.bufferedBytes -= eventBytes;
1301
+ this.sendingEvents = batch.length;
1302
+ if (report !== null && fits(report)) {
1303
+ report.alone = batch.length === 0;
1304
+ batch.push(report);
1305
+ }
1306
+ return batch.length > 0 ? batch : null;
1307
+ }
1308
+ /** Puts a kept batch's events back at the head of the buffer; `true` when
1309
+ * there were none. */
1310
+ putBack(kept) {
1311
+ this.sendingEvents = 0;
1312
+ if (this.closed) return kept.length === 0;
1313
+ const events = [];
1314
+ for (const waiting of kept) {
1315
+ if (waiting.reportSum !== void 0) {
1316
+ if (waiting.alone || this.batchless) this.pendingReport = null;
1317
+ continue;
1154
1318
  }
1319
+ events.push(waiting);
1320
+ this.bufferedBytes += waiting.bytes;
1155
1321
  }
1156
- this.exitPassRan = false;
1322
+ this.buffer.unshift(...events);
1323
+ this.dropOverflow();
1324
+ return kept.length === 0;
1157
1325
  }
1158
- /** Starts a report of this process's loss totals (SPEC §11.4.7) beside the
1159
- * drain and outside the buffer, so it never delays an event and is never
1160
- * counted as one. */
1326
+ /** After a delivery, sets up a report of this process's loss totals (SPEC
1327
+ * §11.4.7) to ride the next batch. It stays outside the buffer, so it never
1328
+ * pushes an event out and is never counted as one. */
1161
1329
  maybeReport({ tenant_id, vendor_id, consent_token }) {
1162
1330
  const now = performance.now();
1163
- if (this.reportsStopped || this.reportInFlight !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
1331
+ if (this.reportsStopped || this.pendingReport !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
1164
1332
  return;
1165
1333
  }
1166
- const totals = PROCESS_DROPS.total();
1167
- const sum = Object.values(totals).reduce((a, b) => a + b, 0);
1168
- if (sum === this.reportedSum) return;
1334
+ if (sum(Object.values(PROCESS_DROPS.total())) === this.reportedSum) return;
1169
1335
  this.lastReportAt = now;
1170
- const abort = new AbortController();
1171
- this.reportInFlight = abort;
1172
- const envelope = { tenant_id, vendor_id, consent_token };
1173
- void this.sendReport(envelope, totals, sum, abort).finally(() => {
1174
- this.reportInFlight = null;
1175
- });
1336
+ this.reportSetAt = Date.now();
1337
+ this.pendingReport = { tenant_id, vendor_id, consent_token };
1176
1338
  }
1177
1339
  stopReports() {
1178
1340
  this.reportsStopped = true;
1179
- this.reportInFlight?.abort();
1341
+ this.pendingReport = null;
1180
1342
  }
1181
- async sendReport(envelope, totals, sum, abort) {
1182
- const timer = setTimeout(() => abort.abort(), this.requestTimeoutMs);
1343
+ buildReport() {
1344
+ if (this.pendingReport === null) return null;
1345
+ const totals = PROCESS_DROPS.total();
1183
1346
  try {
1184
1347
  const report = ClientReportEventSchema.parse({
1185
- ...envelope,
1348
+ ...this.pendingReport,
1186
1349
  session_id: PROCESS_DROPS.instanceId,
1187
1350
  sequence_number: nextClockSequence(),
1188
1351
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1189
1352
  payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals }
1190
1353
  });
1191
- const response = await this.fetchImpl(this.events_url(), {
1192
- method: "POST",
1193
- headers: this.authHeaders(),
1194
- body: JSON.stringify(report),
1195
- signal: abort.signal
1196
- });
1197
- void response.body?.cancel().catch(() => void 0);
1198
- if (response.status === 400 || response.status === 422) this.reportsStopped = true;
1199
- else if (_HttpSink.classifyStatus(response.status) === "success") this.reportedSum = sum;
1354
+ const json = JSON.stringify(report);
1355
+ return { event: report, json, bytes: utf8Bytes(json), writtenAt: Date.now(), reportSum: sum(Object.values(totals)) };
1200
1356
  } catch {
1201
- } finally {
1202
- clearTimeout(timer);
1357
+ this.pendingReport = null;
1358
+ return null;
1203
1359
  }
1204
1360
  }
1205
- async sendWithRetry(event) {
1206
- const body = this.encode(event);
1207
- if (body === null) return "unencodable";
1208
- for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
1209
- const outcome = await this.postOnce(body, this.requestTimeoutMs);
1210
- if (outcome !== "transient_failure") return outcome;
1211
- if (attempt < this.maxRetries) {
1212
- const backoff = Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs);
1213
- await this.sleepUnlessClosed(backoff);
1214
- if (this.closing.signal.aborted) return "transient_failure";
1361
+ /** Sends one batch, splitting it on 413, until every event in it is
1362
+ * delivered or refused. Returns what a failure kept, to go back in the
1363
+ * buffer. */
1364
+ async sendBatch(batch, retries, deadline) {
1365
+ if (this.batchless && batch.length > 1) return this.sendEachAlone(batch, retries, deadline);
1366
+ const batchless = this.batchless;
1367
+ const body = batchless ? batch[0].json : BATCH_OPEN + batch.map((w) => w.json).join(",") + BATCH_CLOSE;
1368
+ for (let attempt = 0; ; attempt++) {
1369
+ const timeLeft = deadline - Date.now();
1370
+ if (timeLeft <= 0) return batch;
1371
+ const answer = await this.post(body, batch.length, batchless, Math.min(this.requestTimeoutMs, timeLeft));
1372
+ if (answer.kind === "no_batch_endpoint") {
1373
+ this.batchless = true;
1374
+ warn("baton: the collector has no batch endpoint; sending one event per request.");
1375
+ return this.sendEachAlone(batch, retries, deadline);
1215
1376
  }
1377
+ if (answer.kind === "too_large") {
1378
+ const half = Math.floor(batch.length / 2);
1379
+ const kept = await this.sendBatch(batch.slice(0, half), retries, deadline);
1380
+ if (kept.length > 0) return [...kept, ...batch.slice(half)];
1381
+ return this.sendBatch(batch.slice(half), retries, deadline);
1382
+ }
1383
+ if (answer.kind === "transient") {
1384
+ if (answer.retryAfterMs !== null) {
1385
+ this.retryAt = Date.now() + answer.retryAfterMs;
1386
+ return batch;
1387
+ }
1388
+ if (attempt < retries && !this.closed) {
1389
+ await this.sleepUnlessClosed(Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs));
1390
+ if (!this.closed) continue;
1391
+ }
1392
+ this.circuit.recordFailure();
1393
+ return batch;
1394
+ }
1395
+ this.circuit.recordSuccess();
1396
+ this.settle(batch, answer, batchless);
1397
+ return [];
1398
+ }
1399
+ }
1400
+ async sendEachAlone(batch, retries, deadline) {
1401
+ for (const [i, waiting] of batch.entries()) {
1402
+ if (this.closed) return batch.slice(i);
1403
+ const kept = await this.sendBatch([waiting], retries, deadline);
1404
+ if (kept.length > 0) return [...kept, ...batch.slice(i + 1)];
1405
+ }
1406
+ return [];
1407
+ }
1408
+ /** `alone` is one event per request (SPEC §2.5), so a whole refusal there is that event's own. */
1409
+ settle(batch, answer, alone) {
1410
+ if (this.closed) return;
1411
+ let lastDelivered = null;
1412
+ const refused = /* @__PURE__ */ new Map();
1413
+ for (const waiting of batch) {
1414
+ if (waiting.reportSum === void 0) this.sendingEvents -= 1;
1415
+ const refusal = answer.kind === "refused" ? answer.refusal : answer.refused.get(waiting.event.event_id);
1416
+ if (waiting.reportSum !== void 0) {
1417
+ this.pendingReport = null;
1418
+ if (refusal === void 0) this.reportedSum = waiting.reportSum;
1419
+ else if (answer.kind === "answered" ? refusal.kind === "payload_malformed" : alone && (answer.status === 400 || answer.status === 422)) {
1420
+ this.reportsStopped = true;
1421
+ }
1422
+ } else if (refusal === void 0) {
1423
+ lastDelivered = waiting.event;
1424
+ } else {
1425
+ const seen = refused.get(refusal.kind);
1426
+ if (seen) seen.n += 1;
1427
+ else refused.set(refusal.kind, { first: refusal, n: 1 });
1428
+ }
1429
+ }
1430
+ for (const { first, n } of refused.values()) this.refuse(n, first);
1431
+ if (lastDelivered !== null) {
1432
+ PROCESS_DROPS.logRecovery();
1433
+ this.maybeReport(lastDelivered);
1216
1434
  }
1217
- return "transient_failure";
1218
1435
  }
1219
1436
  /** `null`, with a warning, for an event `JSON.stringify` rejects. */
1220
1437
  encode(event) {
@@ -1242,37 +1459,73 @@ var HttpSink = class _HttpSink {
1242
1459
  }
1243
1460
  /** Aborted by the timeout or by `aclose()`. Built by hand: `AbortSignal.any`
1244
1461
  * is missing before Node 20.3, and on some later versions it keeps every
1245
- * combined signal alive as long as the long-lived `closing` signal. */
1246
- async postOnce(body, timeoutMs) {
1462
+ * combined signal alive as long as the long-lived `closing` signal. Any body
1463
+ * read is under the same signal, so a stalled body cannot hold the drain. */
1464
+ async post(body, size, batchless, timeoutMs) {
1465
+ if (this.closed) return { kind: "transient", retryAfterMs: null };
1247
1466
  const request = new AbortController();
1248
1467
  const abort = () => request.abort();
1249
1468
  const timer = setTimeout(abort, timeoutMs);
1250
1469
  this.closing.signal.addEventListener("abort", abort);
1251
1470
  try {
1252
- const response = await this.fetchImpl(this.events_url(), {
1471
+ const response = await this.fetchImpl(batchless ? `${this.url}/v0/events` : `${this.url}/v0/events/batch`, {
1253
1472
  method: "POST",
1254
1473
  headers: this.authHeaders(),
1255
1474
  body,
1256
- signal: request.signal
1475
+ signal: request.signal,
1476
+ // SPEC §2.5: a redirect is a failure, not followed.
1477
+ redirect: "manual"
1257
1478
  });
1258
- const outcome = _HttpSink.classifyStatus(response.status);
1259
- if (outcome === "permanent_failure") {
1260
- PROCESS_DROPS.add("refused");
1261
- const unlogged = this.refusalToLog(response.status);
1262
- if (unlogged !== null) {
1263
- await _HttpSink.logRefusal(response, unlogged);
1264
- return outcome;
1479
+ const { status } = response;
1480
+ const outcome = _HttpSink.classifyStatus(status);
1481
+ if (outcome === "success") {
1482
+ if (batchless) {
1483
+ void response.body?.cancel().catch(() => void 0);
1484
+ return { kind: "answered", refused: /* @__PURE__ */ new Map() };
1265
1485
  }
1486
+ return { kind: "answered", refused: _HttpSink.refusedIn(await response.text()) };
1487
+ }
1488
+ const other = _HttpSink.otherAnswer(response, size, batchless);
1489
+ if (other !== null) {
1490
+ void response.body?.cancel().catch(() => void 0);
1491
+ return other;
1266
1492
  }
1267
- void response.body?.cancel().catch(() => void 0);
1268
- return outcome;
1493
+ const detail = await _HttpSink.readHead(response).catch(() => "<unreadable>");
1494
+ return { kind: "refused", status, refusal: { kind: `HTTP ${status}`, detail } };
1269
1495
  } catch {
1270
- return "transient_failure";
1496
+ return { kind: "transient", retryAfterMs: null };
1271
1497
  } finally {
1272
1498
  clearTimeout(timer);
1273
1499
  this.closing.signal.removeEventListener("abort", abort);
1274
1500
  }
1275
1501
  }
1502
+ /** Every answer but a 2xx and a refusal of the whole batch. */
1503
+ static otherAnswer(response, size, batchless) {
1504
+ const { status } = response;
1505
+ if (status === 413 && size > 1) return { kind: "too_large" };
1506
+ if ((status === 404 || status === 405) && !batchless) return { kind: "no_batch_endpoint" };
1507
+ if (status === 429) return { kind: "transient", retryAfterMs: retryAfterMs(response.headers.get("Retry-After")) };
1508
+ if (_HttpSink.classifyStatus(status) === "transient_failure") return { kind: "transient", retryAfterMs: null };
1509
+ return null;
1510
+ }
1511
+ /** The refused results by `event_id` (SPEC §2.5). An event with no readable
1512
+ * result was delivered. */
1513
+ static refusedIn(text) {
1514
+ const refused = /* @__PURE__ */ new Map();
1515
+ let results;
1516
+ try {
1517
+ results = JSON.parse(text)?.results;
1518
+ } catch {
1519
+ return refused;
1520
+ }
1521
+ if (!Array.isArray(results)) return refused;
1522
+ const str = (value) => typeof value === "string" ? value : "";
1523
+ for (const result of results) {
1524
+ if (result?.status !== "refused" || typeof result.event_id !== "string") continue;
1525
+ refused.set(result.event_id, { kind: str(result.error?.code) || "no code", detail: str(result.error?.message) });
1526
+ }
1527
+ return refused;
1528
+ }
1276
1529
  };
1277
1530
 
1278
1531
  // src/integrations/mcp/withBaton.ts
@@ -2253,7 +2506,7 @@ function resolveBatonConfig(config) {
2253
2506
  validateBatonConfig(identity);
2254
2507
  return {
2255
2508
  ...identity,
2256
- // The origin is scheme + authority; `HttpSink` appends `/v0/events`
2509
+ // The origin is scheme + authority; `HttpSink` appends `/v0/events/batch`
2257
2510
  // itself, exactly as it does for an explicitly-constructed sink.
2258
2511
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
2259
2512
  };
@@ -2360,6 +2613,24 @@ var DisabledSink = class {
2360
2613
  }
2361
2614
  };
2362
2615
 
2616
+ // src/integrations/mcp/inputRequired.ts
2617
+ function isInputRequired(result) {
2618
+ try {
2619
+ return isRecord(result) && result.resultType === "input_required";
2620
+ } catch {
2621
+ return false;
2622
+ }
2623
+ }
2624
+ function resumesPausedCall(extra) {
2625
+ try {
2626
+ const req = extra?.mcpReq;
2627
+ if (req === void 0) return false;
2628
+ return req.inputResponses !== void 0 || req.requestState?.() !== void 0;
2629
+ } catch {
2630
+ return false;
2631
+ }
2632
+ }
2633
+
2363
2634
  // src/integrations/mcp/handle.ts
2364
2635
  var BatonHandle = class {
2365
2636
  sink;
@@ -2713,6 +2984,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
2713
2984
  runtime_meta: scrubbedMeta,
2714
2985
  call_id: uuid7()
2715
2986
  };
2987
+ if (resumesPausedCall(extra)) return { common, session };
2716
2988
  await emit(
2717
2989
  ctx.sink,
2718
2990
  () => ToolCallStartEventSchema.parse({
@@ -2744,20 +3016,19 @@ function batonWrap(nameRef, original, ctx) {
2744
3016
  const { common, session } = await openCall(ctx, toolName, extra, params, retired);
2745
3017
  const terminate = async (build, replacement) => {
2746
3018
  if (!slot) {
2747
- await emit(ctx.sink, build);
3019
+ if (build !== null) await emit(ctx.sink, build);
2748
3020
  return;
2749
3021
  }
2750
3022
  const earlier = slot.flushTerminal;
2751
3023
  if (earlier !== null) await earlier(CLEAN_OUTCOME);
2752
3024
  slot.flushTerminal = async (outcome) => {
2753
- await emit(
2754
- ctx.sink,
2755
- () => replacement !== null && outcome.failed ? replacement(outcome) : build()
2756
- );
3025
+ if (replacement !== null && outcome.failed) await emit(ctx.sink, () => replacement(outcome));
3026
+ else if (build !== null) await emit(ctx.sink, build);
2757
3027
  };
2758
3028
  };
2759
3029
  const parkFailure = (build) => terminate(build, null);
2760
3030
  const parkSuccess = (build, replacement) => terminate(build, replacement);
3031
+ const parkPause = (replacement) => terminate(null, replacement);
2761
3032
  const startedAt = performance.now();
2762
3033
  let result;
2763
3034
  try {
@@ -2800,6 +3071,59 @@ function batonWrap(nameRef, original, ctx) {
2800
3071
  throw err;
2801
3072
  }
2802
3073
  const durationMs = Math.round(performance.now() - startedAt);
3074
+ const failedAbove = (outcome, failureKind) => ToolCallErrorEventSchema.parse({
3075
+ ...common,
3076
+ sequence_number: ctx.counter.nextFor(session),
3077
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
3078
+ payload: {
3079
+ tool_name: toolName,
3080
+ // The lane the OUTER came back on, not this one's: on 2.x the
3081
+ // conversion failure is converted to a returned `isError` inside
3082
+ // `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
3083
+ // right there. A pause the SDK rejects on 2026-07-28 raises, so
3084
+ // both lanes are reachable.
3085
+ error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
3086
+ // ⚠ The INNER's measurement — the vendor's handler duration —
3087
+ // not the outer's. Every other leg means the same thing by this
3088
+ // member, and widening it here for one failure kind would make
3089
+ // `duration_ms` mean two things in one column.
3090
+ duration_ms: durationMs,
3091
+ // Omitted, not null, when undetermined: SPEC §11.4.3 says MUST OMIT.
3092
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind },
3093
+ // ⚠ **WITHHELD under `"off"`, unlike the three request-side
3094
+ // kinds.** The message quotes the value the tool returned
3095
+ // ("`'not-an-int'` is not of type `integer`"), so it is
3096
+ // result-derived by provenance and goes — which leaves
3097
+ // `failure_kind` as the ONLY surviving signal for an
3098
+ // `output_schema_mismatch` under `"off"`, and is the measurement
3099
+ // that justified putting the member on the wire at all.
3100
+ //
3101
+ // ⚠ `result` is what the CLIENT received — the SDK's own error
3102
+ // envelope — not the vendor's rejected return value. §11.4.3
3103
+ // asks for the envelope that holds the flag and the reason, and
3104
+ // this package's own invariant is that it agrees with the
3105
+ // caller. Recording the rejected output TOO would need a member
3106
+ // nothing on the wire has; the loss is deliberate and worth
3107
+ // knowing when debugging one of these.
3108
+ ...resultDerivedFields(
3109
+ ctx.resultCaptureMode,
3110
+ () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
3111
+ // ⚠ `null` on the `raised` lane, never `undefined`, and the
3112
+ // union is what forces the branch rather than a comment: the
3113
+ // scrubber would answer `undefined` and DROP the key, where the
3114
+ // sibling raise lane a few lines up declares `result: null`
3115
+ // explicitly, for the reason `ToolCallErrorPayloadSchema`
3116
+ // records. One shape for "no result object existed", not two.
3117
+ outcome.raised ? null : outcome.result ?? null,
3118
+ (text) => errorBody(ctx, text),
3119
+ ctx.scrubber
3120
+ )
3121
+ }
3122
+ });
3123
+ if (isInputRequired(result)) {
3124
+ await parkPause(failedAbove);
3125
+ return result;
3126
+ }
2803
3127
  if (isErrorResult(result)) {
2804
3128
  await parkFailure(
2805
3129
  () => ToolCallErrorEventSchema.parse({
@@ -2842,61 +3166,7 @@ function batonWrap(nameRef, original, ctx) {
2842
3166
  ...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber)
2843
3167
  }
2844
3168
  }),
2845
- // The handler returned something this sensor reads as a success, and
2846
- // then the outer seam saw the call fail anyway — so what failed is the
2847
- // producer's own conversion of the output (SPEC §11.4.3's
2848
- // `output_schema_mismatch`). Correcting this is the whole point of the
2849
- // second seam: without it this is a `tool_call_end` for a call the
2850
- // CALLER saw fail, which is a success the product invented.
2851
- (outcome) => ToolCallErrorEventSchema.parse({
2852
- ...common,
2853
- sequence_number: ctx.counter.nextFor(session),
2854
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2855
- payload: {
2856
- tool_name: toolName,
2857
- // The lane the OUTER came back on, not this one's: on 2.x the
2858
- // conversion failure is converted to a returned `isError` inside
2859
- // `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
2860
- // right there. A throw out of the handler is unreachable on
2861
- // either major today for this lane; spelled anyway, because the
2862
- // alternative is a crash on the day it stops being.
2863
- error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
2864
- // ⚠ The INNER's measurement — the vendor's handler duration —
2865
- // not the outer's. Every other leg means the same thing by this
2866
- // member, and widening it here for one failure kind would make
2867
- // `duration_ms` mean two things in one column.
2868
- duration_ms: durationMs,
2869
- failure_kind: OUTPUT_SCHEMA_MISMATCH,
2870
- // ⚠ **WITHHELD under `"off"`, unlike the three request-side
2871
- // kinds.** The message quotes the value the tool returned
2872
- // ("`'not-an-int'` is not of type `integer`"), so it is
2873
- // result-derived by provenance and goes — which leaves
2874
- // `failure_kind` as the ONLY surviving signal for this failure
2875
- // under `"off"`, and is the measurement that justified putting
2876
- // the member on the wire at all.
2877
- //
2878
- // ⚠ `result` is what the CLIENT received — the SDK's own error
2879
- // envelope — not the vendor's rejected return value. §11.4.3
2880
- // asks for the envelope that holds the flag and the reason, and
2881
- // this package's own invariant is that it agrees with the
2882
- // caller. Recording the rejected output TOO would need a member
2883
- // nothing on the wire has; the loss is deliberate and worth
2884
- // knowing when debugging one of these.
2885
- ...resultDerivedFields(
2886
- ctx.resultCaptureMode,
2887
- () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
2888
- // ⚠ `null` on the `raised` lane, never `undefined`, and the
2889
- // union is what forces the branch rather than a comment: the
2890
- // scrubber would answer `undefined` and DROP the key, where the
2891
- // sibling raise lane a few lines up declares `result: null`
2892
- // explicitly, for the reason `ToolCallErrorPayloadSchema`
2893
- // records. One shape for "no result object existed", not two.
2894
- outcome.raised ? null : outcome.result ?? null,
2895
- (text) => errorBody(ctx, text),
2896
- ctx.scrubber
2897
- )
2898
- }
2899
- })
3169
+ (outcome) => failedAbove(outcome, OUTPUT_SCHEMA_MISMATCH)
2900
3170
  );
2901
3171
  return result;
2902
3172
  };
@@ -3062,11 +3332,12 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
3062
3332
  })
3063
3333
  );
3064
3334
  };
3065
- await fire(spec.schemas.start, spec.startParams(requestParams));
3335
+ if (!resumesPausedCall(extra)) await fire(spec.schemas.start, spec.startParams(requestParams));
3066
3336
  const startedAt = performance.now();
3067
3337
  const elapsed = () => Math.round(performance.now() - startedAt);
3068
3338
  try {
3069
3339
  const result = await handler(...args);
3340
+ if (isInputRequired(result)) return result;
3070
3341
  await fire(spec.schemas.end, {
3071
3342
  ...spec.countKey === void 0 ? {} : { count: countOf(result, spec.countKey) },
3072
3343
  duration_ms: elapsed()
@@ -3494,7 +3765,12 @@ function install(server, supplied, resolved, sentSurfaces, warned3) {
3494
3765
  seam_augmentations: snapshot.seam_augmentations
3495
3766
  }
3496
3767
  });
3497
- await sink.write(event);
3768
+ try {
3769
+ await sink.write(event);
3770
+ } catch (err) {
3771
+ if (isSinkClosed(err)) return droppedAfterClose(sink);
3772
+ throw err;
3773
+ }
3498
3774
  };
3499
3775
  const bustSchemaMemo = (name) => {
3500
3776
  const memo = internals._toolInputSchemaJson;
@@ -3956,6 +4232,7 @@ var Core = class {
3956
4232
  try {
3957
4233
  await this.sink.write(event);
3958
4234
  } catch (err) {
4235
+ if (isSinkClosed(err)) return droppedAfterClose(this.sink);
3959
4236
  process.stderr.write(`baton: surface snapshot not sent; will retry: ${printable(err)}
3960
4237
  `);
3961
4238
  this.sentSurfaces.unmark(surface.digest);
@@ -4312,6 +4589,7 @@ var Client = class {
4312
4589
  ResourceReadStartPayloadSchema,
4313
4590
  SDK_VERSION,
4314
4591
  Scrubber,
4592
+ SinkClosedError,
4315
4593
  StdoutSink,
4316
4594
  SurfaceSnapshotEventSchema,
4317
4595
  SurfaceSnapshotPayloadSchema,