@goodtiming/baton-sdk 0.6.1 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -34,13 +34,18 @@ __export(index_exports, {
34
34
  AnnotationPayloadSchema: () => AnnotationPayloadSchema,
35
35
  BatonHandle: () => BatonHandle,
36
36
  Client: () => Client,
37
+ ClientReportEventSchema: () => ClientReportEventSchema,
38
+ ClientReportPayloadSchema: () => ClientReportPayloadSchema,
37
39
  DEFAULT_CONSENT_TOKEN: () => DEFAULT_CONSENT_TOKEN,
38
40
  DEPTH_LIMIT: () => DEPTH_LIMIT,
41
+ DEPTH_MARKER: () => DEPTH_MARKER,
39
42
  EventSchema: () => EventSchema,
40
43
  EventTypeSchema: () => EventTypeSchema,
44
+ FileSink: () => FileSink,
41
45
  HttpSink: () => HttpSink,
42
46
  INTENT_INSTRUCTIONS: () => INTENT_INSTRUCTIONS,
43
47
  INTENT_PARAMS: () => INTENT_PARAMS,
48
+ MultiSink: () => MultiSink,
44
49
  PRINCIPAL_FORM_HASHED: () => PRINCIPAL_FORM_HASHED,
45
50
  PRINCIPAL_FORM_RAW: () => PRINCIPAL_FORM_RAW,
46
51
  PRINCIPAL_SOURCE_ASSERTED: () => PRINCIPAL_SOURCE_ASSERTED,
@@ -97,7 +102,7 @@ __export(index_exports, {
97
102
  module.exports = __toCommonJS(index_exports);
98
103
 
99
104
  // src/version.ts
100
- var SDK_VERSION = "ts-0.6.1";
105
+ var SDK_VERSION = "ts-0.6.2";
101
106
 
102
107
  // src/events.ts
103
108
  var import_zod = require("zod");
@@ -218,6 +223,10 @@ var SurfaceSnapshotPayloadSchema = import_zod.z.object({
218
223
  tools: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
219
224
  seam_augmentations: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).default({})
220
225
  }).strict();
226
+ var ClientReportPayloadSchema = import_zod.z.object({
227
+ instance_id: import_zod.z.uuid(),
228
+ dropped: import_zod.z.record(import_zod.z.string(), import_zod.z.number().int().nonnegative())
229
+ }).strict();
221
230
  var DEFAULT_CONSENT_TOKEN = "customer-consented";
222
231
  var ClientObservedSchema = import_zod.z.object({
223
232
  info: import_zod.z.object({ name: import_zod.z.string().optional(), version: import_zod.z.string().optional() }).strict().optional(),
@@ -255,6 +264,7 @@ var EventTypeSchema = import_zod.z.enum([
255
264
  "tool_call_error",
256
265
  "annotation",
257
266
  "surface_snapshot",
267
+ "client_report",
258
268
  // The RESOURCE and PROMPT lifecycles (SPEC §11.4.4). Twelve types whose
259
269
  // shapes were set by `baton-proxy`, which has been emitting all of them in
260
270
  // production — see the payload schemas below.
@@ -364,6 +374,11 @@ var SurfaceSnapshotEventSchema = import_zod.z.object({
364
374
  event_type: import_zod.z.literal("surface_snapshot").default("surface_snapshot"),
365
375
  payload: SurfaceSnapshotPayloadSchema
366
376
  }).strict();
377
+ var ClientReportEventSchema = import_zod.z.object({
378
+ ...envelopeShape,
379
+ event_type: import_zod.z.literal("client_report").default("client_report"),
380
+ payload: ClientReportPayloadSchema
381
+ }).strict();
367
382
  var ResourceListStartEventSchema = import_zod.z.object({
368
383
  ...envelopeShape,
369
384
  event_type: import_zod.z.literal("resource_list_start").default("resource_list_start"),
@@ -445,6 +460,7 @@ var EventSchema = import_zod.z.discriminatedUnion("event_type", [
445
460
  ToolCallErrorEventSchema,
446
461
  AnnotationEventSchema,
447
462
  SurfaceSnapshotEventSchema,
463
+ ClientReportEventSchema,
448
464
  ResourceListStartEventSchema,
449
465
  ResourceListEndEventSchema,
450
466
  ResourceListErrorEventSchema,
@@ -462,8 +478,33 @@ var EventSchema = import_zod.z.discriminatedUnion("event_type", [
462
478
  ToolListErrorEventSchema
463
479
  ]);
464
480
 
481
+ // src/warn.ts
482
+ function warn(message) {
483
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
484
+ process.emitWarning(message);
485
+ }
486
+ }
487
+ function printable(err) {
488
+ try {
489
+ return String(err);
490
+ } catch {
491
+ return "(an error that cannot be printed)";
492
+ }
493
+ }
494
+
495
+ // src/_object.ts
496
+ function isPlainObject(value) {
497
+ if (typeof value !== "object" || value === null) return false;
498
+ const proto = Object.getPrototypeOf(value);
499
+ return proto === Object.prototype || proto === null;
500
+ }
501
+ function isRecord(value) {
502
+ return typeof value === "object" && value !== null && !Array.isArray(value);
503
+ }
504
+
465
505
  // src/scrub.ts
466
506
  var DEPTH_LIMIT = 10;
507
+ var DEPTH_MARKER = "[REDACTED:depth-limit]";
467
508
  var REDACT_FIELD_NAMES = /* @__PURE__ */ new Set([
468
509
  "email",
469
510
  "phone",
@@ -474,16 +515,21 @@ var REDACT_FIELD_NAMES = /* @__PURE__ */ new Set([
474
515
  "password",
475
516
  "user_name"
476
517
  ]);
518
+ var WS_CHARS = String.raw` \t\n\r\f\u00a0`;
519
+ var PHONE_SEP = String.raw`[${WS_CHARS}\-.]`;
477
520
  var PATTERNS = [
478
521
  ["jwt", /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g],
479
- ["bearer", /\bBearer\s+[A-Za-z0-9_\-.+/=]{16,}/gi],
522
+ ["bearer", new RegExp(String.raw`\bBearer[${WS_CHARS}]+[A-Za-z0-9_\-.+/=]{16,}`, "gi")],
480
523
  ["sk_key", /\bsk-[A-Za-z0-9_-]{20,}\b/g],
481
524
  ["aws_key", /\bAKIA[0-9A-Z]{16}\b/g],
482
525
  ["email", /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g],
483
526
  // Phone: optional `+1`, optional area-code parens, separators
484
- // `-` / `.` / space, 10 digits. Conservative — won't catch every
527
+ // `-`, `.` or `WS_CHARS`, 10 digits. Conservative — won't catch every
485
528
  // international format, but won't trip on every 10-digit identifier.
486
- ["phone", /\b(?:\+?1[\s\-.]?)?\(?\d{3}\)?[\s\-.]?\d{3}[\s\-.]?\d{4}\b/g]
529
+ [
530
+ "phone",
531
+ new RegExp(String.raw`\b(?:\+?1${PHONE_SEP}?)?\(?\d{3}\)?${PHONE_SEP}?\d{3}${PHONE_SEP}?\d{4}\b`, "g")
532
+ ]
487
533
  ];
488
534
  var CC_CANDIDATE = /\b\d{13,19}\b/g;
489
535
  function luhnValid(digits) {
@@ -498,13 +544,9 @@ function luhnValid(digits) {
498
544
  }
499
545
  return total % 10 === 0;
500
546
  }
501
- function isPlainObject(value) {
502
- if (typeof value !== "object" || value === null) return false;
503
- const proto = Object.getPrototypeOf(value);
504
- return proto === Object.prototype || proto === null;
505
- }
506
547
  var Scrubber = class {
507
548
  counts = /* @__PURE__ */ new Map();
549
+ warnedDepth = false;
508
550
  /** Bound so `new Scrubber().scrub` can be passed as a bare function
509
551
  * reference — the closest TS gets to Python's `__call__`. */
510
552
  scrub = (value) => this.walk(value, 0, null);
@@ -515,8 +557,20 @@ var Scrubber = class {
515
557
  bump(category) {
516
558
  this.counts.set(category, this.count(category) + 1);
517
559
  }
560
+ pastTheDepthLimit() {
561
+ this.bump("depth_limit");
562
+ if (!this.warnedDepth) {
563
+ this.warnedDepth = true;
564
+ warn(
565
+ `baton: a payload nests deeper than ${DEPTH_LIMIT} levels; containers past that depth are sent as ${JSON.stringify(DEPTH_MARKER)}`
566
+ );
567
+ }
568
+ return DEPTH_MARKER;
569
+ }
518
570
  walk(value, depth, forceField) {
519
- if (depth >= DEPTH_LIMIT) return value;
571
+ if (depth >= DEPTH_LIMIT && (isPlainObject(value) || Array.isArray(value))) {
572
+ return this.pastTheDepthLimit();
573
+ }
520
574
  if (isPlainObject(value)) {
521
575
  const out = {};
522
576
  for (const [k, v] of Object.entries(value)) {
@@ -557,14 +611,155 @@ function identityScrub(value) {
557
611
  }
558
612
 
559
613
  // src/sinks.ts
614
+ var import_node_fs = require("fs");
615
+
616
+ // src/_text.ts
617
+ var WHITE_SPACE = /^\p{White_Space}$/u;
618
+ var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
619
+ function stripEdges(value, space) {
620
+ let start = 0;
621
+ let end = value.length;
622
+ while (start < end && space.test(value[start])) start++;
623
+ while (end > start && space.test(value[end - 1])) end--;
624
+ return value.slice(start, end);
625
+ }
626
+ function stripWhiteSpace(value) {
627
+ return stripEdges(value, WHITE_SPACE);
628
+ }
629
+ function isBlank(value) {
630
+ return ALL_WHITE_SPACE.test(value);
631
+ }
632
+ function exceedsCodePoints(value, max) {
633
+ if (value.length <= max) return false;
634
+ if (value.length > 2 * max) return true;
635
+ return [...value].length > max;
636
+ }
637
+ function capCodePoints(value, max) {
638
+ if (value.length <= max) return value;
639
+ return [...value].slice(0, max).join("");
640
+ }
641
+ function escapeForLog(value) {
642
+ return value.replace(/[\\\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (c) => `\\u{${c.codePointAt(0).toString(16)}}`);
643
+ }
644
+
645
+ // src/deadline.ts
646
+ var TIMED_OUT = /* @__PURE__ */ Symbol("timedOut");
647
+ var MAX_TIMER_MS = 2 ** 31 - 1;
648
+ async function raceDeadline(work, ms) {
649
+ let timer;
650
+ const deadline = new Promise((resolve) => {
651
+ timer = setTimeout(() => resolve(TIMED_OUT), Math.min(ms, MAX_TIMER_MS));
652
+ timer.unref?.();
653
+ });
654
+ try {
655
+ return await Promise.race([work, deadline]);
656
+ } finally {
657
+ clearTimeout(timer);
658
+ }
659
+ }
660
+ var SHUTDOWN_FLUSH_TIMEOUT_MS = 3e3;
661
+
662
+ // src/drops.ts
663
+ var RECOVERY_LOG_MS = 6e4;
664
+ var DropCounts = class {
665
+ #instanceId = uuid7();
666
+ #total = /* @__PURE__ */ new Map();
667
+ #sinceDelivery = /* @__PURE__ */ new Map();
668
+ #lastRecoveryLog = -RECOVERY_LOG_MS;
669
+ add(reason, n = 1) {
670
+ if (n <= 0) return;
671
+ this.#total.set(reason, (this.#total.get(reason) ?? 0) + n);
672
+ this.#sinceDelivery.set(reason, (this.#sinceDelivery.get(reason) ?? 0) + n);
673
+ }
674
+ total() {
675
+ return Object.fromEntries(this.#total);
676
+ }
677
+ /** Called on each delivery: names what was lost before it, the other half of
678
+ * a drop's own warning, which says only that loss started. */
679
+ logRecovery() {
680
+ if (this.#sinceDelivery.size === 0) return;
681
+ const now = performance.now();
682
+ if (now - this.#lastRecoveryLog < RECOVERY_LOG_MS) return;
683
+ const lost = [...this.#sinceDelivery].sort(([a], [b]) => a.localeCompare(b));
684
+ this.#sinceDelivery.clear();
685
+ this.#lastRecoveryLog = now;
686
+ const total = lost.reduce((sum, [, n]) => sum + n, 0);
687
+ warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(", ")}.`);
688
+ }
689
+ /** For tests: the counts are one per process. */
690
+ /** Names this process in its loss reports (SPEC §11.4.7). */
691
+ get instanceId() {
692
+ return this.#instanceId;
693
+ }
694
+ clear() {
695
+ this.#instanceId = uuid7();
696
+ this.#total.clear();
697
+ this.#sinceDelivery.clear();
698
+ this.#lastRecoveryLog = -RECOVERY_LOG_MS;
699
+ }
700
+ };
701
+ var PROCESS_DROPS = new DropCounts();
702
+
703
+ // src/sequence.ts
704
+ var lastSequence = 0;
705
+ function nextClockSequence() {
706
+ const nowMicros = Math.floor((performance.timeOrigin + performance.now()) * 1e3);
707
+ lastSequence = Math.max(lastSequence + 1, nowMicros);
708
+ return lastSequence;
709
+ }
710
+
711
+ // src/sinks.ts
712
+ var REFUSAL_BODY_MAX_LEN = 500;
713
+ var REFUSAL_LOG_MS = 6e4;
560
714
  async function safeWrite(sink, event) {
561
715
  try {
562
716
  await sink.write(event);
563
717
  } catch (err) {
564
- process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${String(err)}
718
+ PROCESS_DROPS.add("write_failed");
719
+ process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}
565
720
  `);
566
721
  }
567
722
  }
723
+ function stderrLine(message) {
724
+ process.stderr.write(`${message}
725
+ `);
726
+ }
727
+ function isTimerMs(value) {
728
+ return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
729
+ }
730
+ function shutdownFlushTimeoutOption(given) {
731
+ 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;
736
+ }
737
+ function shutdownBudgetMs(sink) {
738
+ try {
739
+ if (sink instanceof MultiSink) return Math.max(...sink["sinks"].map(shutdownBudgetMs));
740
+ const budget = sink instanceof HttpSink ? sink["shutdownFlushTimeoutMs"] : void 0;
741
+ if (isTimerMs(budget)) return budget;
742
+ } catch {
743
+ }
744
+ return SHUTDOWN_FLUSH_TIMEOUT_MS;
745
+ }
746
+ function callWithin(sink, method, ms) {
747
+ if (sink[method] === HttpSink.prototype[method]) return sink[`${method}Within`](ms);
748
+ if (sink[method] === MultiSink.prototype[method]) return sink[`${method}Within`](ms);
749
+ return sink[method]();
750
+ }
751
+ async function boundedSinkCall(sink, method, work = () => sink[method]()) {
752
+ const what = `${method}()`;
753
+ const budget = shutdownBudgetMs(sink);
754
+ const ms = budget + 250;
755
+ const settled = Promise.resolve().then(() => work(budget)).then(
756
+ () => void 0,
757
+ (err) => warn(`baton: ${what} failed: ${printable(err)}`)
758
+ );
759
+ if (await raceDeadline(settled, ms) === TIMED_OUT) {
760
+ warn(`baton: ${what} took over ${String(ms)} ms and was left unfinished.`);
761
+ }
762
+ }
568
763
  var StdoutSink = class {
569
764
  stream;
570
765
  closed = false;
@@ -581,6 +776,57 @@ var StdoutSink = class {
581
776
  this.closed = true;
582
777
  }
583
778
  };
779
+ var FileSink = class {
780
+ constructor(path) {
781
+ this.path = path;
782
+ }
783
+ path;
784
+ fd = null;
785
+ closed = false;
786
+ async write(event) {
787
+ if (this.closed) throw new Error("FileSink is closed");
788
+ this.fd ??= (0, import_node_fs.openSync)(this.path, "a");
789
+ (0, import_node_fs.writeSync)(this.fd, JSON.stringify(event) + "\n");
790
+ }
791
+ async flush() {
792
+ }
793
+ async aclose() {
794
+ if (this.closed) return;
795
+ this.closed = true;
796
+ if (this.fd !== null) {
797
+ (0, import_node_fs.closeSync)(this.fd);
798
+ this.fd = null;
799
+ }
800
+ }
801
+ };
802
+ var MultiSink = class {
803
+ sinks;
804
+ constructor(sinks) {
805
+ if (sinks.length === 0) throw new Error("MultiSink requires at least one sink");
806
+ this.sinks = [...sinks];
807
+ }
808
+ write(event) {
809
+ return this.fanOut((sink) => sink.write(event));
810
+ }
811
+ flush() {
812
+ return this.flushWithin(Infinity);
813
+ }
814
+ aclose() {
815
+ return this.acloseWithin(Infinity);
816
+ }
817
+ flushWithin(ms) {
818
+ return this.fanOut((sink) => callWithin(sink, "flush", ms));
819
+ }
820
+ acloseWithin(ms) {
821
+ return this.fanOut((sink) => callWithin(sink, "aclose", ms));
822
+ }
823
+ async fanOut(op) {
824
+ 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");
828
+ }
829
+ };
584
830
  var CircuitBreaker = class {
585
831
  constructor(threshold, resetMs) {
586
832
  this.threshold = threshold;
@@ -610,19 +856,43 @@ var HttpSink = class _HttpSink {
610
856
  apiKey;
611
857
  buffer = [];
612
858
  bufferSize;
859
+ requestTimeoutMs;
860
+ shutdownFlushTimeoutMs;
861
+ /** Set when an exit pass ends; cleared once a normal drain empties the
862
+ * buffer, which means the process went on. */
863
+ exitPassRan = false;
864
+ /** Whether the exit pass warned about every event now buffered. */
865
+ unsentWarned = false;
613
866
  maxRetries;
614
867
  backoffBaseMs;
615
868
  backoffMaxMs;
616
869
  circuit;
617
870
  fetchImpl;
618
871
  overflowWarned = false;
619
- closed = false;
872
+ /** Per status, so a new kind of refusal, such as a 401 after a 422, still warns. */
873
+ refusals = /* @__PURE__ */ new Map();
874
+ /** Aborted once `aclose()` returns: nothing Baton started may keep the
875
+ * process alive after the vendor closed it. */
876
+ closing = new AbortController();
877
+ /** The drain chain's tail when a flush() or aclose() gave up waiting, until it settles. */
878
+ stalledDrain = null;
879
+ skipWarnedFor = null;
880
+ closeOnce;
620
881
  drainChain = Promise.resolve();
621
- beforeExitHandler = null;
882
+ exitHooks = null;
883
+ /** The least time between two of this sink's loss reports. */
884
+ static reportIntervalMs = 6e4;
885
+ /** Totals only grow, so their sum tells whether they changed. */
886
+ reportedSum = 0;
887
+ lastReportAt = -Infinity;
888
+ reportsStopped = false;
889
+ reportInFlight = null;
622
890
  constructor(url, options) {
623
891
  this.url = url.replace(/\/+$/, "");
624
892
  this.apiKey = options.apiKey;
625
893
  this.bufferSize = options.bufferSize ?? 1e3;
894
+ this.requestTimeoutMs = options.requestTimeoutMs ?? 1e3;
895
+ this.shutdownFlushTimeoutMs = shutdownFlushTimeoutOption(options.shutdownFlushTimeoutMs);
626
896
  this.maxRetries = options.maxRetries ?? 3;
627
897
  this.backoffBaseMs = options.backoffBaseMs ?? 100;
628
898
  this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
@@ -638,9 +908,7 @@ var HttpSink = class _HttpSink {
638
908
  * ⚠ **A sink built from a DSN holds a key the vendor never typed**, and it
639
909
  * hangs off `BatonHandle.sink` and off the resolved config, so
640
910
  * `console.log(handle.sink)` or a structured logger serialising either one
641
- * wrote a publishable key into the vendor's logs. Found by the S2 test that
642
- * asserts the DSN's own string does not survive resolution: it does not, and
643
- * the key was one field further down. Same treatment as the parsed DSN —
911
+ * would write a publishable key into the vendor's logs. Same treatment as the parsed DSN —
644
912
  * `toJSON` for serialisers, the inspect symbol for `console.log`, and
645
913
  * `Symbol.for` rather than importing `node:util`, since this package runs on
646
914
  * runtimes that have no such module.
@@ -651,29 +919,84 @@ var HttpSink = class _HttpSink {
651
919
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
652
920
  return this.toJSON();
653
921
  }
922
+ get closed() {
923
+ return this.closing.signal.aborted;
924
+ }
654
925
  async write(event) {
655
926
  if (this.closed) throw new Error("HttpSink is closed");
656
927
  this.enqueue(event);
928
+ this.unsentWarned = false;
657
929
  void this.scheduleDrain();
658
- this.ensureBeforeExitRegistered();
930
+ this.ensureExitHooksRegistered();
659
931
  }
660
- async flush() {
661
- if (this.closed) return;
662
- await this.scheduleDrain();
932
+ flush() {
933
+ return this.flushWithin(Infinity);
663
934
  }
664
- async aclose() {
935
+ /** A second call waits for the first (SPEC §11.2 rule 7). */
936
+ aclose() {
937
+ return this.acloseWithin(Infinity);
938
+ }
939
+ async flushWithin(ms) {
665
940
  if (this.closed) return;
666
- await this.flush();
667
- this.closed = true;
668
- if (this.beforeExitHandler) {
669
- process.off("beforeExit", this.beforeExitHandler);
670
- this.beforeExitHandler = null;
941
+ await this.drainWithinBudget("flush()", Math.min(ms, this.shutdownFlushTimeoutMs));
942
+ }
943
+ acloseWithin(ms) {
944
+ this.closeOnce ??= this.close(Math.min(ms, this.shutdownFlushTimeoutMs));
945
+ return this.closeOnce;
946
+ }
947
+ async close(ms) {
948
+ this.stopReports();
949
+ await this.drainWithinBudget("aclose()", ms);
950
+ 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.`);
954
+ }
955
+ this.warnUnloggedRefusals("the sink closed");
956
+ if (this.exitHooks) {
957
+ process.off("beforeExit", this.exitHooks.beforeExit);
958
+ process.off("exit", this.exitHooks.exit);
959
+ this.exitHooks = null;
671
960
  }
672
961
  }
962
+ /** SPEC §11.2 rule 7: an explicit flush or close returns within `ms` and
963
+ * never rejects. While an earlier wait's drain is still stuck, a flush
964
+ * returns at once, without queuing a pass, and a close gives it `ms`. The
965
+ * drain is not cancelled here, so after `flush()` it goes on sending;
966
+ * `aclose()` stops it. */
967
+ async drainWithinBudget(what, ms) {
968
+ if (this.stalledDrain) {
969
+ if (what === "aclose()") {
970
+ await raceDeadline(this.stalledDrain, ms);
971
+ return;
972
+ }
973
+ if (this.skipWarnedFor !== this.stalledDrain) {
974
+ this.skipWarnedFor = this.stalledDrain;
975
+ warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.buffer.length} event(s) wait to be sent.`);
976
+ }
977
+ return;
978
+ }
979
+ const settled = this.scheduleDrain().catch(() => void 0);
980
+ if (await raceDeadline(settled, ms) !== TIMED_OUT) return;
981
+ if (ms < this.shutdownFlushTimeoutMs) return;
982
+ const stalled = this.drainChain.catch(() => void 0);
983
+ this.stalledDrain = stalled;
984
+ void stalled.then(() => {
985
+ if (this.stalledDrain === stalled) this.stalledDrain = null;
986
+ });
987
+ if (what === "flush()") {
988
+ warn(`baton: flush() took over ${ms} ms; it goes on in the background.`);
989
+ }
990
+ }
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();
994
+ }
673
995
  enqueue(event) {
674
996
  if (this.buffer.length >= this.bufferSize) {
997
+ PROCESS_DROPS.add("buffer_full");
675
998
  if (!this.overflowWarned) {
676
- process.emitWarning(
999
+ warn(
677
1000
  `Baton HTTP sink buffer full (${this.bufferSize}); oldest events dropped. Further overflows will be silent.`
678
1001
  );
679
1002
  this.overflowWarned = true;
@@ -695,18 +1018,58 @@ var HttpSink = class _HttpSink {
695
1018
  return this.drainChain;
696
1019
  }
697
1020
  /** Best-effort flush when the process is about to exit without an
698
- * explicit `aclose()`. Node re-runs `beforeExit` if new async work is
699
- * scheduled during it, so an in-flight flush here can complete normally —
700
- * unlike Python's synchronous `atexit`, no separate sync-client fallback
701
- * is needed. Real residual gap, not fixable in-process: SIGKILL, or
702
- * SIGTERM with no installed handler, skip `beforeExit` entirely. A vendor
703
- * needing that guarantee must call `aclose()` from their own handler. */
704
- ensureBeforeExitRegistered() {
705
- if (this.beforeExitHandler) return;
706
- this.beforeExitHandler = () => {
707
- void this.flush();
1021
+ * explicit `aclose()`. SIGKILL, or SIGTERM with no installed handler, skip
1022
+ * both hooks: a vendor needing that guarantee must call `aclose()` from
1023
+ * their own handler. */
1024
+ ensureExitHooksRegistered() {
1025
+ if (this.exitHooks) return;
1026
+ const beforeExit = () => {
1027
+ if (this.buffer.length === 0 || this.exitPassRan) {
1028
+ this.warnUnloggedRefusals("process exiting");
1029
+ return;
1030
+ }
1031
+ this.drainChain = this.drainChain.then(
1032
+ () => this.exitPass(),
1033
+ () => this.exitPass()
1034
+ );
708
1035
  };
709
- process.on("beforeExit", this.beforeExitHandler);
1036
+ const exit = () => {
1037
+ try {
1038
+ if (this.buffer.length > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
1039
+ this.warnUnloggedRefusals("process exiting", stderrLine);
1040
+ } catch {
1041
+ }
1042
+ };
1043
+ this.exitHooks = { beforeExit, exit };
1044
+ process.on("beforeExit", beforeExit);
1045
+ process.on("exit", exit);
1046
+ }
1047
+ /** One attempt per event, no retry, within `shutdownFlushTimeoutMs` in
1048
+ * total (SPEC §11.2); what is left is reported, not sent. */
1049
+ async exitPass() {
1050
+ 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);
1065
+ }
1066
+ this.exitPassRan = true;
1067
+ this.unsentWarned = true;
1068
+ if (this.buffer.length > 0) warn(this.unsentAtExit());
1069
+ this.warnUnloggedRefusals("process exiting");
1070
+ }
1071
+ unsentAtExit() {
1072
+ return `baton: process exiting with ${this.buffer.length} unsent event(s).`;
710
1073
  }
711
1074
  events_url() {
712
1075
  return `${this.url}/v0/events`;
@@ -719,38 +1082,197 @@ var HttpSink = class _HttpSink {
719
1082
  if (status >= 400 && status < 500 && status !== 429) return "permanent_failure";
720
1083
  return "transient_failure";
721
1084
  }
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
1088
+ * 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
+ );
1094
+ 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.` : "")
1096
+ );
1097
+ }
1098
+ warnUnloggedRefusals(when, emit2 = warn) {
1099
+ let total = 0;
1100
+ for (const seen of this.refusals.values()) {
1101
+ total += seen.unlogged;
1102
+ seen.unlogged = 0;
1103
+ }
1104
+ if (total > 0) emit2(`baton: ${when}; ${total} more event(s) refused since the last such warning.`);
1105
+ }
1106
+ /** How many refusals with `status` went unlogged before this one, or `null`
1107
+ * when this one goes unlogged too. */
1108
+ refusalToLog(status) {
1109
+ const now = performance.now();
1110
+ const seen = this.refusals.get(status);
1111
+ if (seen !== void 0 && now - seen.loggedAt < REFUSAL_LOG_MS) {
1112
+ seen.unlogged++;
1113
+ return null;
1114
+ }
1115
+ this.refusals.set(status, { loggedAt: now, unlogged: 0 });
1116
+ return seen?.unlogged ?? 0;
1117
+ }
1118
+ /** Enough of the body for `REFUSAL_BODY_MAX_LEN` code points; the rest is
1119
+ * cancelled unread, so a large error page does not hold the drain. */
1120
+ static async readHead(response) {
1121
+ const reader = response.body?.getReader();
1122
+ if (reader === void 0) return "";
1123
+ const decoder = new TextDecoder();
1124
+ let text = "";
1125
+ try {
1126
+ while (text.length < REFUSAL_BODY_MAX_LEN * 2) {
1127
+ const { done, value } = await reader.read();
1128
+ if (done) return text + decoder.decode();
1129
+ text += decoder.decode(value, { stream: true });
1130
+ }
1131
+ return text;
1132
+ } finally {
1133
+ void reader.cancel().catch(() => {
1134
+ });
1135
+ }
1136
+ }
722
1137
  async drainLocked() {
723
1138
  while (this.buffer.length > 0) {
724
- if (!this.circuit.canRequest()) return;
1139
+ if (!this.circuit.canRequest() || this.closing.signal.aborted) return;
725
1140
  const event = this.buffer[0];
726
1141
  const outcome = await this.sendWithRetry(event);
727
1142
  if (outcome === "success" || outcome === "permanent_failure") {
728
- this.buffer.shift();
1143
+ this.dequeue(event);
729
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);
730
1151
  } else {
731
1152
  this.circuit.recordFailure();
732
1153
  return;
733
1154
  }
734
1155
  }
1156
+ this.exitPassRan = false;
1157
+ }
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. */
1161
+ maybeReport({ tenant_id, vendor_id, consent_token }) {
1162
+ const now = performance.now();
1163
+ if (this.reportsStopped || this.reportInFlight !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
1164
+ return;
1165
+ }
1166
+ const totals = PROCESS_DROPS.total();
1167
+ const sum = Object.values(totals).reduce((a, b) => a + b, 0);
1168
+ if (sum === this.reportedSum) return;
1169
+ 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
+ });
1176
+ }
1177
+ stopReports() {
1178
+ this.reportsStopped = true;
1179
+ this.reportInFlight?.abort();
1180
+ }
1181
+ async sendReport(envelope, totals, sum, abort) {
1182
+ const timer = setTimeout(() => abort.abort(), this.requestTimeoutMs);
1183
+ try {
1184
+ const report = ClientReportEventSchema.parse({
1185
+ ...envelope,
1186
+ session_id: PROCESS_DROPS.instanceId,
1187
+ sequence_number: nextClockSequence(),
1188
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1189
+ payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals }
1190
+ });
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;
1200
+ } catch {
1201
+ } finally {
1202
+ clearTimeout(timer);
1203
+ }
735
1204
  }
736
1205
  async sendWithRetry(event) {
737
- const url = this.events_url();
738
- const headers = this.authHeaders();
739
- const body = JSON.stringify(event);
1206
+ const body = this.encode(event);
1207
+ if (body === null) return "unencodable";
740
1208
  for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
741
- try {
742
- const response = await this.fetchImpl(url, { method: "POST", headers, body });
743
- const outcome = _HttpSink.classifyStatus(response.status);
744
- if (outcome !== "transient_failure") return outcome;
745
- } catch {
746
- }
1209
+ const outcome = await this.postOnce(body, this.requestTimeoutMs);
1210
+ if (outcome !== "transient_failure") return outcome;
747
1211
  if (attempt < this.maxRetries) {
748
1212
  const backoff = Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs);
749
- await new Promise((resolve) => setTimeout(resolve, backoff));
1213
+ await this.sleepUnlessClosed(backoff);
1214
+ if (this.closing.signal.aborted) return "transient_failure";
750
1215
  }
751
1216
  }
752
1217
  return "transient_failure";
753
1218
  }
1219
+ /** `null`, with a warning, for an event `JSON.stringify` rejects. */
1220
+ encode(event) {
1221
+ try {
1222
+ return JSON.stringify(event);
1223
+ } catch (err) {
1224
+ PROCESS_DROPS.add("encode_failed");
1225
+ warn(
1226
+ `baton: a ${event.event_type} event could not be encoded and has been dropped (${err?.name ?? "Error"}) \u2014 the event is gone; the events after it are still sent.`
1227
+ );
1228
+ return null;
1229
+ }
1230
+ }
1231
+ sleepUnlessClosed(ms) {
1232
+ if (this.closed) return Promise.resolve();
1233
+ return new Promise((resolve) => {
1234
+ const done = () => {
1235
+ clearTimeout(timer);
1236
+ this.closing.signal.removeEventListener("abort", done);
1237
+ resolve();
1238
+ };
1239
+ const timer = setTimeout(done, ms);
1240
+ this.closing.signal.addEventListener("abort", done);
1241
+ });
1242
+ }
1243
+ /** Aborted by the timeout or by `aclose()`. Built by hand: `AbortSignal.any`
1244
+ * 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) {
1247
+ const request = new AbortController();
1248
+ const abort = () => request.abort();
1249
+ const timer = setTimeout(abort, timeoutMs);
1250
+ this.closing.signal.addEventListener("abort", abort);
1251
+ try {
1252
+ const response = await this.fetchImpl(this.events_url(), {
1253
+ method: "POST",
1254
+ headers: this.authHeaders(),
1255
+ body,
1256
+ signal: request.signal
1257
+ });
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;
1265
+ }
1266
+ }
1267
+ void response.body?.cancel().catch(() => void 0);
1268
+ return outcome;
1269
+ } catch {
1270
+ return "transient_failure";
1271
+ } finally {
1272
+ clearTimeout(timer);
1273
+ this.closing.signal.removeEventListener("abort", abort);
1274
+ }
1275
+ }
754
1276
  };
755
1277
 
756
1278
  // src/integrations/mcp/withBaton.ts
@@ -762,11 +1284,6 @@ var import_zod2 = require("zod");
762
1284
  // src/metaCoordinates.ts
763
1285
  var COORD_FIELD_NAMES = /* @__PURE__ */ new Set(["latitude", "longitude"]);
764
1286
  var DECIMAL_STRING = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
765
- function isPlainObject2(value) {
766
- if (typeof value !== "object" || value === null) return false;
767
- const proto = Object.getPrototypeOf(value);
768
- return proto === Object.prototype || proto === null;
769
- }
770
1287
  function toOneDecimal(value) {
771
1288
  const magnitude = Math.abs(value);
772
1289
  if (Number.isInteger(magnitude * 4) && !Number.isInteger(magnitude * 2)) {
@@ -787,7 +1304,7 @@ function roundCoordinate(value) {
787
1304
  }
788
1305
  function walk(value, depth) {
789
1306
  if (depth >= DEPTH_LIMIT) return value;
790
- if (isPlainObject2(value)) {
1307
+ if (isPlainObject(value)) {
791
1308
  const out = {};
792
1309
  for (const [k, v] of Object.entries(value)) {
793
1310
  const rounded = COORD_FIELD_NAMES.has(k.toLowerCase()) && depth + 1 < DEPTH_LIMIT ? roundCoordinate(v) : void 0;
@@ -804,126 +1321,6 @@ function roundMetaCoordinates(meta) {
804
1321
  return walk(meta, 0);
805
1322
  }
806
1323
 
807
- // src/_text.ts
808
- function exceedsCodePoints(value, max) {
809
- if (value.length <= max) return false;
810
- if (value.length > 2 * max) return true;
811
- return [...value].length > max;
812
- }
813
- function capCodePoints(value, max) {
814
- if (value.length <= max) return value;
815
- return [...value].slice(0, max).join("");
816
- }
817
-
818
- // src/identity.ts
819
- var PRINCIPAL_SOURCE_ASSERTED = "asserted";
820
- var PRINCIPAL_FORM_HASHED = "hashed";
821
- var PRINCIPAL_FORM_RAW = "raw";
822
- var PRINCIPAL_ID_MAX_LEN = 128;
823
- var DISPLAY_NAME_MAX_LEN = 128;
824
- var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
825
- function wireDisplayName(value) {
826
- if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
827
- if (LONE_SURROGATE.test(value) || value.includes("\0") || ALL_WHITE_SPACE.test(value)) return null;
828
- return value;
829
- }
830
- var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
831
- var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
832
- var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
833
- var LONE_SURROGATE = /\p{Surrogate}/u;
834
- function pythonStrip(value) {
835
- return value.replace(PYTHON_STRIP, "");
836
- }
837
- function usableId(id) {
838
- if (typeof id !== "string") return false;
839
- if (LONE_SURROGATE.test(id)) return false;
840
- if (id.includes("\0")) return false;
841
- return pythonStrip(id) !== "";
842
- }
843
- function readIdentity(result, idKey) {
844
- if (result === null || typeof result !== "object") return null;
845
- const candidate = result;
846
- const id = candidate[idKey];
847
- if (!usableId(id)) return null;
848
- const displayName = typeof candidate.displayName === "string" ? candidate.displayName : void 0;
849
- return { id, form: candidate.form, displayName };
850
- }
851
- var NO_CALLER = Object.freeze({ principal: null, organization: null });
852
- function callerFor(result, warn4) {
853
- try {
854
- return readCaller(result, warn4);
855
- } catch {
856
- warn4("unreadable", "could not be read \u2014 sending neither principal nor organization.");
857
- return NO_CALLER;
858
- }
859
- }
860
- function readCaller(result, warn4) {
861
- if (result === void 0 || result === null) return NO_CALLER;
862
- if (typeof result !== "object") {
863
- warn4("not-object", `got a ${typeof result}, not an object \u2014 sending neither principal nor organization.`);
864
- return NO_CALLER;
865
- }
866
- if (!("principalId" in result) && !("organization" in result)) {
867
- if ("organizationId" in result) {
868
- return { principal: null, organization: identityFor(result, "organization", warn4) };
869
- }
870
- if (typeof result.userId === "string") {
871
- warn4(
872
- "user-id",
873
- "returned { userId }, which was renamed to { principalId } in 0.3.5, so the principal is dropped from every event until it returns the new key."
874
- );
875
- } else {
876
- warn4("no-id", "got an object with neither principalId nor organizationId \u2014 sending neither.");
877
- }
878
- return NO_CALLER;
879
- }
880
- if ("organizationId" in result) {
881
- warn4("flat-organization-id", "got principalId and organizationId side by side; put the company in `organization`.");
882
- }
883
- const nested = result.organization;
884
- return {
885
- principal: identityFor(result, "principal", warn4),
886
- organization: nested == null ? null : identityFor(nested, "organization", warn4)
887
- };
888
- }
889
- function identityFor(value, member, warn4) {
890
- const idKey = member === "principal" ? "principalId" : "organizationId";
891
- const identity = readIdentity(value, idKey);
892
- if (identity === null) {
893
- warn4(`${member}:id`, `${member} has no usable ${idKey} \u2014 sending no ${member}.`);
894
- return null;
895
- }
896
- return identityWire(
897
- identity.id,
898
- identity.form,
899
- identity.displayName,
900
- (form) => warn4(`${member}:form`, `${member} form ${describeForm(form)} is not registered \u2014 sending "raw".`)
901
- );
902
- }
903
- function describeForm(form) {
904
- return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
905
- }
906
- function identityWire(id, stated, displayName, onUnregisteredForm) {
907
- let form = PRINCIPAL_FORM_RAW;
908
- if (stated !== void 0) {
909
- if (PRINCIPAL_FORMS.has(stated)) {
910
- form = stated;
911
- } else {
912
- onUnregisteredForm?.(stated);
913
- }
914
- }
915
- const wire = {
916
- // `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
917
- // an astral id cut at the boundary would ship a lone surrogate.
918
- id: capCodePoints(id, PRINCIPAL_ID_MAX_LEN),
919
- source: PRINCIPAL_SOURCE_ASSERTED,
920
- form
921
- };
922
- const name = wireDisplayName(displayName);
923
- if (name !== null) wire.display_name = name;
924
- return wire;
925
- }
926
-
927
1324
  // src/integrations/mcp/llmText.ts
928
1325
  var REPORT_POINTER_TEMPLATE = (vendorDisplayName, annotationToolName) => `Use \`${annotationToolName}\` to report a ${vendorDisplayName} tool call that went wrong, or a request no tool covers; its description says when and how.`;
929
1326
  var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
@@ -995,14 +1392,14 @@ var OURS_STARTS = [
995
1392
  ];
996
1393
  function endsInOurs(current2, vendor) {
997
1394
  if (typeof current2 !== "string") return false;
998
- const prefix = typeof vendor === "string" && vendor.trim() ? `${vendor}
1395
+ const prefix = typeof vendor === "string" && !isBlank(vendor) ? `${vendor}
999
1396
 
1000
1397
  ` : "";
1001
1398
  if (!current2.startsWith(prefix)) return false;
1002
1399
  const rest = current2.slice(prefix.length);
1003
1400
  return OURS_STARTS.some((start) => start.test(rest));
1004
1401
  }
1005
- function withVendorInstructions(server, ours, warn4 = (message) => process.stderr.write(message)) {
1402
+ function withVendorInstructions(server, ours, warn3 = (message) => process.stderr.write(message)) {
1006
1403
  const holder = server;
1007
1404
  const current2 = holder._instructions;
1008
1405
  let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
@@ -1010,12 +1407,12 @@ function withVendorInstructions(server, ours, warn4 = (message) => process.stder
1010
1407
  vendor = current2;
1011
1408
  holder[VENDOR_INSTRUCTIONS] = vendor;
1012
1409
  }
1013
- if (typeof vendor !== "string" || !vendor.trim()) return ours;
1410
+ if (typeof vendor !== "string" || isBlank(vendor)) return ours;
1014
1411
  const combined = `${vendor}
1015
1412
 
1016
1413
  ${ours}`;
1017
1414
  if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
1018
- warn4(
1415
+ warn3(
1019
1416
  `baton: the server instructions are ${combined.length} chars (yours ${vendor.length}, Baton's ${ours.length}); Claude Code cuts them at ~${CLAUDE_CODE_TRUNCATION_CAP}, so the end of Baton's text is lost there
1020
1417
  `
1021
1418
  );
@@ -1029,17 +1426,17 @@ var SUFFIX = "_annotate";
1029
1426
  var SLUG_CAP = 30;
1030
1427
  var PLACEHOLDER_LITERALS = /* @__PURE__ */ new Set(["fastmcp", "mcp-server"]);
1031
1428
  var RANDOM_SUFFIX = /-[0-9a-f]{4}$/;
1429
+ var SEPARATORS = "\\x1c-\\x1f";
1430
+ var PYTHON_SPACE = new RegExp(`^[\\p{White_Space}${SEPARATORS}]$`, "u");
1431
+ function pythonStrip(value) {
1432
+ return stripEdges(value, PYTHON_SPACE);
1433
+ }
1032
1434
  function isLibraryPlaceholder(serverName, className) {
1033
1435
  const stripped = pythonStrip(serverName);
1034
1436
  if (PLACEHOLDER_LITERALS.has(stripped.toLowerCase())) return true;
1035
1437
  const stem = stripped.replace(RANDOM_SUFFIX, "");
1036
1438
  return stem !== stripped && stem === className;
1037
1439
  }
1038
- function warn(message) {
1039
- if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
1040
- process.emitWarning(message);
1041
- }
1042
- }
1043
1440
  function usableServerName(read) {
1044
1441
  let name;
1045
1442
  let className;
@@ -1113,13 +1510,117 @@ async function emit(sink, build) {
1113
1510
  try {
1114
1511
  event = build();
1115
1512
  } catch (err) {
1116
- process.stderr.write(`baton: event construction failed; event dropped: ${String(err)}
1513
+ PROCESS_DROPS.add("encode_failed");
1514
+ process.stderr.write(`baton: event construction failed; event dropped: ${printable(err)}
1117
1515
  `);
1118
1516
  return;
1119
1517
  }
1120
1518
  await safeWrite(sink, event);
1121
1519
  }
1122
1520
 
1521
+ // src/identity.ts
1522
+ var PRINCIPAL_SOURCE_ASSERTED = "asserted";
1523
+ var PRINCIPAL_FORM_HASHED = "hashed";
1524
+ var PRINCIPAL_FORM_RAW = "raw";
1525
+ var PRINCIPAL_ID_MAX_LEN = 128;
1526
+ var DISPLAY_NAME_MAX_LEN = 128;
1527
+ function wireDisplayName(value) {
1528
+ if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
1529
+ if (LONE_SURROGATE.test(value) || value.includes("\0") || isBlank(value)) return null;
1530
+ return value;
1531
+ }
1532
+ var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
1533
+ var LONE_SURROGATE = /\p{Surrogate}/u;
1534
+ function usableId(id) {
1535
+ if (typeof id !== "string") return false;
1536
+ if (LONE_SURROGATE.test(id)) return false;
1537
+ if (id.includes("\0")) return false;
1538
+ return !isBlank(id);
1539
+ }
1540
+ function readIdentity(result, idKey) {
1541
+ if (result === null || typeof result !== "object") return null;
1542
+ const candidate = result;
1543
+ const id = candidate[idKey];
1544
+ if (!usableId(id)) return null;
1545
+ const displayName = typeof candidate.displayName === "string" ? candidate.displayName : void 0;
1546
+ return { id, form: candidate.form, displayName };
1547
+ }
1548
+ var NO_CALLER = Object.freeze({ principal: null, organization: null });
1549
+ function callerFor(result, warn3) {
1550
+ try {
1551
+ return readCaller(result, warn3);
1552
+ } catch {
1553
+ warn3("unreadable", "could not be read \u2014 sending neither principal nor organization.");
1554
+ return NO_CALLER;
1555
+ }
1556
+ }
1557
+ function readCaller(result, warn3) {
1558
+ if (result === void 0 || result === null) return NO_CALLER;
1559
+ if (typeof result !== "object") {
1560
+ warn3("not-object", `got a ${typeof result}, not an object \u2014 sending neither principal nor organization.`);
1561
+ return NO_CALLER;
1562
+ }
1563
+ if (!("principalId" in result) && !("organization" in result)) {
1564
+ if ("organizationId" in result) {
1565
+ return { principal: null, organization: identityFor(result, "organization", warn3) };
1566
+ }
1567
+ if (typeof result.userId === "string") {
1568
+ warn3(
1569
+ "user-id",
1570
+ "returned { userId }, which was renamed to { principalId } in 0.3.5, so the principal is dropped from every event until it returns the new key."
1571
+ );
1572
+ } else {
1573
+ warn3("no-id", "got an object with neither principalId nor organizationId \u2014 sending neither.");
1574
+ }
1575
+ return NO_CALLER;
1576
+ }
1577
+ if ("organizationId" in result) {
1578
+ warn3("flat-organization-id", "got principalId and organizationId side by side; put the company in `organization`.");
1579
+ }
1580
+ const nested = result.organization;
1581
+ return {
1582
+ principal: identityFor(result, "principal", warn3),
1583
+ organization: nested == null ? null : identityFor(nested, "organization", warn3)
1584
+ };
1585
+ }
1586
+ function identityFor(value, member, warn3) {
1587
+ const idKey = member === "principal" ? "principalId" : "organizationId";
1588
+ const identity = readIdentity(value, idKey);
1589
+ if (identity === null) {
1590
+ warn3(`${member}:id`, `${member} has no usable ${idKey} \u2014 sending no ${member}.`);
1591
+ return null;
1592
+ }
1593
+ return identityWire(
1594
+ identity.id,
1595
+ identity.form,
1596
+ identity.displayName,
1597
+ (form) => warn3(`${member}:form`, `${member} form ${describeForm(form)} is not registered \u2014 sending "raw".`)
1598
+ );
1599
+ }
1600
+ function describeForm(form) {
1601
+ return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
1602
+ }
1603
+ function identityWire(id, stated, displayName, onUnregisteredForm) {
1604
+ let form = PRINCIPAL_FORM_RAW;
1605
+ if (stated !== void 0) {
1606
+ if (PRINCIPAL_FORMS.has(stated)) {
1607
+ form = stated;
1608
+ } else {
1609
+ onUnregisteredForm?.(stated);
1610
+ }
1611
+ }
1612
+ const wire = {
1613
+ // `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
1614
+ // an astral id cut at the boundary would ship a lone surrogate.
1615
+ id: capCodePoints(id, PRINCIPAL_ID_MAX_LEN),
1616
+ source: PRINCIPAL_SOURCE_ASSERTED,
1617
+ form
1618
+ };
1619
+ const name = wireDisplayName(displayName);
1620
+ if (name !== null) wire.display_name = name;
1621
+ return wire;
1622
+ }
1623
+
1123
1624
  // src/integrations/mcp/mcpTypes.ts
1124
1625
  function extraAuthInfo(extra) {
1125
1626
  const found = extra.authInfo ?? extra.http?.authInfo;
@@ -1177,24 +1678,14 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
1177
1678
  };
1178
1679
  }
1179
1680
  var HOOK_TIMEOUT_MS = 5e3;
1180
- var TIMED_OUT = /* @__PURE__ */ Symbol("hookTimedOut");
1181
1681
  async function withinHookBudget(answer) {
1182
1682
  if (!isThenable(answer)) return answer;
1183
- let timer;
1184
- const deadline = new Promise((resolve) => {
1185
- timer = setTimeout(() => resolve(TIMED_OUT), HOOK_TIMEOUT_MS);
1186
- timer.unref?.();
1187
- });
1188
- try {
1189
- const first = await Promise.race([answer, deadline]);
1190
- if (first !== TIMED_OUT) return first;
1191
- warn(
1192
- `baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
1193
- );
1194
- return null;
1195
- } finally {
1196
- clearTimeout(timer);
1197
- }
1683
+ const first = await raceDeadline(answer, HOOK_TIMEOUT_MS);
1684
+ if (first !== TIMED_OUT) return first;
1685
+ warn(
1686
+ `baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
1687
+ );
1688
+ return null;
1198
1689
  }
1199
1690
  var warned = /* @__PURE__ */ new Set();
1200
1691
  function warnOnce(key, message) {
@@ -1223,7 +1714,7 @@ function scrubOrNull(scrubber, value, field) {
1223
1714
  if (!warned2.has(field)) {
1224
1715
  warned2.add(field);
1225
1716
  process.stderr.write(
1226
- `baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${String(err)}
1717
+ `baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}
1227
1718
  `
1228
1719
  );
1229
1720
  }
@@ -1322,9 +1813,9 @@ function registeredHeaders(input) {
1322
1813
  }
1323
1814
  return out;
1324
1815
  }
1325
- function clientObservedFrom(clientInfo, headers, scrubber) {
1816
+ function clientObservedFrom(clientInfo, headers, scrubber, meta) {
1326
1817
  return assemble(
1327
- orNothing(() => cleanInfo(declared(clientInfo), scrubber)),
1818
+ orNothing(() => cleanInfo(declared(meta?.[CLIENT_INFO_META_KEY]) ?? declared(clientInfo), scrubber)),
1328
1819
  orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
1329
1820
  );
1330
1821
  }
@@ -1332,16 +1823,19 @@ function clientObservedFrom(clientInfo, headers, scrubber) {
1332
1823
  // src/integrations/mcp/sessionResolution.ts
1333
1824
  async function resolveSessionId(fallbackSessionId, extra) {
1334
1825
  if (typeof extra.sessionId === "string" && extra.sessionId) {
1335
- return { sessionId: extra.sessionId, origin: "observed" };
1826
+ return { sessionId: extra.sessionId, origin: "observed", perCall: false };
1336
1827
  }
1337
1828
  const fromHeader = sessionIdFromHeader(extra);
1338
- if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed" };
1339
- return { sessionId: fallbackSessionId, origin: "minted" };
1829
+ if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed", perCall: false };
1830
+ if (observeTransport(extra) === "http") {
1831
+ return { sessionId: `sdk-${uuid7()}`, origin: "minted", perCall: true };
1832
+ }
1833
+ return { sessionId: fallbackSessionId, origin: "minted", perCall: false };
1340
1834
  }
1341
1835
  function sessionIdFromHeader(extra) {
1342
1836
  try {
1343
- const value = extraHeaders(extra)?.get("mcp-session-id")?.trim();
1344
- return value ? value : null;
1837
+ const value = extraHeaders(extra)?.get("mcp-session-id");
1838
+ return value ? stripWhiteSpace(value) || null : null;
1345
1839
  } catch {
1346
1840
  return null;
1347
1841
  }
@@ -1350,7 +1844,7 @@ function sessionIdFromHeader(extra) {
1350
1844
  // src/integrations/mcp/annotation.ts
1351
1845
  var TOOL_NAME_PARAM_NAME = "tool_name";
1352
1846
  function isReport(whatHappened) {
1353
- return typeof whatHappened === "string" && whatHappened.trim() !== "";
1847
+ return typeof whatHappened === "string" && !isBlank(whatHappened);
1354
1848
  }
1355
1849
  function registerAnnotationTool(server, options) {
1356
1850
  const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
@@ -1393,7 +1887,7 @@ function registerAnnotationTool(server, options) {
1393
1887
  meta ? roundMetaCoordinates(meta) : null,
1394
1888
  "_meta"
1395
1889
  );
1396
- const { sessionId, origin } = await resolveSessionId(options.fallbackSessionId, extra);
1890
+ const session = await resolveSessionId(options.fallbackSessionId, extra);
1397
1891
  const caller = await resolveCaller(
1398
1892
  options.resolvePrincipal,
1399
1893
  { extra, toolName: name, arguments: args }
@@ -1403,14 +1897,14 @@ function registerAnnotationTool(server, options) {
1403
1897
  () => AnnotationEventSchema.parse({
1404
1898
  tenant_id: options.tenantId,
1405
1899
  vendor_id: options.vendorId,
1406
- session_id: sessionId,
1407
- sequence_number: options.counter.next(sessionId),
1900
+ session_id: session.sessionId,
1901
+ sequence_number: options.counter.nextFor(session),
1408
1902
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1409
1903
  consent_token: options.consentToken,
1410
1904
  principal: caller.principal,
1411
1905
  organization: caller.organization,
1412
1906
  transport_observed: observeTransport(extra),
1413
- session_id_origin: origin,
1907
+ session_id_origin: session.origin,
1414
1908
  client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
1415
1909
  runtime_meta: scrubbedMeta,
1416
1910
  payload: {
@@ -1437,7 +1931,7 @@ function registerAnnotationTool(server, options) {
1437
1931
  var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
1438
1932
  var WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;
1439
1933
  var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
1440
- var NOT_IN_A_KEY = /[\x00\n\r]/;
1934
+ var NOT_IN_A_KEY = /[\x00\t\n\r]/;
1441
1935
  var PUBLISHABLE_PREFIX = "baton_pk_";
1442
1936
  var SECRET_PREFIX = "baton_sk_";
1443
1937
  var KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;
@@ -1448,11 +1942,6 @@ function containsKey(value) {
1448
1942
  return sweep(value) !== value;
1449
1943
  }
1450
1944
  var BARE_KEY_HINT = "this looks like a bare key, not a DSN \u2014 copy the full value from /account, which starts with https:// and ends with your server's name";
1451
- function warn2(message) {
1452
- if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
1453
- process.emitWarning(message);
1454
- }
1455
- }
1456
1945
  function splitDsn(raw) {
1457
1946
  const schemeEnd = raw.indexOf("://");
1458
1947
  if (schemeEnd === -1) return null;
@@ -1512,7 +2001,7 @@ function selectDsn(explicit, supplied, door) {
1512
2001
  const ambient = dsnFromEnvironment();
1513
2002
  if (ambient === void 0) return void 0;
1514
2003
  if (conflicts.length > 0) {
1515
- warn2(
2004
+ warn(
1516
2005
  `baton: BATON_DSN is set, but this ${door} supplies ${conflicts.join(", ")} directly, so BATON_DSN is being IGNORED and these events are NOT going to the collector it names. Remove the explicit value to use it, or unset BATON_DSN if it was meant for a different server.`
1517
2006
  );
1518
2007
  return void 0;
@@ -1520,10 +2009,8 @@ function selectDsn(explicit, supplied, door) {
1520
2009
  return ambient;
1521
2010
  }
1522
2011
  function parseDsn(raw) {
1523
- if (typeof raw !== "string" || raw.trim() === "") {
1524
- fail("dsn must be a non-empty string");
1525
- }
1526
- const dsn = raw.trim();
2012
+ const dsn = typeof raw === "string" ? stripWhiteSpace(raw) : "";
2013
+ if (dsn === "") fail("dsn must be a non-empty string");
1527
2014
  if (looksLikeAKey(dsn)) {
1528
2015
  fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
1529
2016
  }
@@ -1549,7 +2036,7 @@ function parseDsn(raw) {
1549
2036
  }
1550
2037
  if (NOT_IN_A_KEY.test(key)) {
1551
2038
  fail(
1552
- `dsn ${safe} has a line break or a null inside its key \u2014 those can never be sent in an Authorization header, so this DSN could not have worked. Check for a line wrap where the value was copied.`
2039
+ `dsn ${safe} has a tab, a line break or a null inside its key \u2014 no key from /account contains one, so this DSN could not have worked. Check for a line wrap where the value was copied.`
1553
2040
  );
1554
2041
  }
1555
2042
  if (key.includes(":")) {
@@ -1608,7 +2095,7 @@ function parseDsn(raw) {
1608
2095
  );
1609
2096
  }
1610
2097
  if (key.startsWith(SECRET_PREFIX)) {
1611
- warn2(
2098
+ warn(
1612
2099
  `baton: this DSN carries a ${SECRET_PREFIX} key (a workspace SECRET) where a ${PUBLISHABLE_PREFIX} key belongs. It will work. But if this server ships to anyone else, that key reads and writes everything the workspace holds \u2014 mint a publishable key at /account instead.`
1613
2100
  );
1614
2101
  }
@@ -1647,7 +2134,7 @@ function requestSideFailureKind(entry, validation) {
1647
2134
  if (entry.enabled === false) return "tool_disabled";
1648
2135
  if (validation === "rejected") return "invalid_argument";
1649
2136
  if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
1650
- return validation === "unprobed" ? "invalid_argument" : REFUSED;
2137
+ return REFUSED;
1651
2138
  }
1652
2139
  var ERROR_BODY_MAX_CODE_POINTS = 2e3;
1653
2140
  function isErrorResult(value) {
@@ -1666,7 +2153,7 @@ function errorText(value) {
1666
2153
  for (const part of content) {
1667
2154
  const text = part?.text;
1668
2155
  if (typeof text !== "string") continue;
1669
- const trimmed = text.trim();
2156
+ const trimmed = stripWhiteSpace(text);
1670
2157
  if (trimmed) parts.push(trimmed);
1671
2158
  }
1672
2159
  } catch {
@@ -1846,7 +2333,7 @@ var SWITCH = "BATON_DISABLED";
1846
2333
  var OFF_VALUES = /* @__PURE__ */ new Set(["", "0", "false", "no", "off"]);
1847
2334
  function captureDisabled() {
1848
2335
  const value = typeof process !== "undefined" ? process.env?.[SWITCH] : void 0;
1849
- if (value !== void 0 && !OFF_VALUES.has(value.trim().toLowerCase())) {
2336
+ if (value !== void 0 && !OFF_VALUES.has(stripWhiteSpace(value).toLowerCase())) {
1850
2337
  return SWITCH;
1851
2338
  }
1852
2339
  return null;
@@ -1877,9 +2364,9 @@ var DisabledSink = class {
1877
2364
  var BatonHandle = class {
1878
2365
  sink;
1879
2366
  vendorId;
1880
- /** Process-lifetime fallback session id — the value events fall back to
1881
- * when no real per-call session id resolves. Not every event necessarily
1882
- * carries this id; see `withBaton`'s session-resolution order. */
2367
+ /** The install's own session id: what stdio and in-memory calls, and the
2368
+ * surface snapshot, carry when no session id resolves. A call over HTTP
2369
+ * with no session to read gets a per-request id instead (SPEC §3.4 rung 5). */
1883
2370
  sessionId;
1884
2371
  /** The resolved annotation tool name: `BatonConfig.annotationToolName` if
1885
2372
  * set, else derived from the server's own name (`{slug}_annotate`), else
@@ -1891,19 +2378,25 @@ var BatonHandle = class {
1891
2378
  this.sessionId = options.sessionId;
1892
2379
  this.annotationToolName = options.annotationToolName;
1893
2380
  }
1894
- /** Flush any pending events held by the sink. */
2381
+ /** Flush any pending events held by the sink. Never rejects; returns within
2382
+ * the shutdown budget (SPEC §11.2 rule 7). */
1895
2383
  async flush() {
1896
- await this.sink.flush();
2384
+ await boundedSinkCall(this.sink, "flush");
1897
2385
  }
1898
- /** Flush and release sink resources. Subsequent writes reject. */
2386
+ /** Flush and release sink resources, on the same terms as `flush()`. */
1899
2387
  async aclose() {
1900
- await this.sink.aclose();
2388
+ await boundedSinkCall(this.sink, "aclose");
1901
2389
  }
1902
2390
  };
1903
2391
 
1904
2392
  // src/integrations/mcp/sessionCounter.ts
1905
2393
  var SessionCounter = class {
1906
2394
  counters = /* @__PURE__ */ new Map();
2395
+ /** A per-call session is numbered by the clock: a counter would keep an
2396
+ * entry for every request the process serves. */
2397
+ nextFor(session) {
2398
+ return session.perCall ? nextClockSequence() : this.next(session.sessionId);
2399
+ }
1907
2400
  next(sessionId) {
1908
2401
  const current2 = this.counters.get(sessionId) ?? 0;
1909
2402
  const next = current2 + 1;
@@ -1990,6 +2483,7 @@ function toJsonSchemaCompat(schema, opts) {
1990
2483
  // src/integrations/mcp/schemaCompat.ts
1991
2484
  var import_zod3 = require("zod");
1992
2485
  var import_v3 = require("zod/v3");
2486
+ var DEFAULT_INTENT_PARAM_MODE = "required";
1993
2487
  var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
1994
2488
  function injectGoalParams(inputSchema, intentParamMode) {
1995
2489
  const objSchema = normalizeObjectSchema(inputSchema);
@@ -2068,9 +2562,9 @@ function surfaceHash(surface) {
2068
2562
  }
2069
2563
  function canonicalJson(value) {
2070
2564
  if (value === null || typeof value !== "object") return JSON.stringify(value);
2071
- if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
2565
+ if (Array.isArray(value)) return `[${value.map((v) => v === void 0 ? "null" : canonicalJson(v)).join(",")}]`;
2072
2566
  const record = value;
2073
- const keys = Object.keys(record).sort();
2567
+ const keys = Object.keys(record).filter((k) => record[k] !== void 0).sort();
2074
2568
  return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(record[k])}`).join(",")}}`;
2075
2569
  }
2076
2570
  function buildServerMeta(lowlevelServer) {
@@ -2092,6 +2586,25 @@ function assembleSurface(serverMeta, tools) {
2092
2586
  tools
2093
2587
  };
2094
2588
  }
2589
+ var SENT_SURFACES_CAP = 256;
2590
+ var SentSurfaces = class {
2591
+ hashes = /* @__PURE__ */ new Set();
2592
+ wasSent(digest) {
2593
+ if (!this.hashes.has(digest)) return false;
2594
+ this.hashes.delete(digest);
2595
+ this.hashes.add(digest);
2596
+ return true;
2597
+ }
2598
+ mark(digest) {
2599
+ this.hashes.add(digest);
2600
+ if (this.hashes.size > SENT_SURFACES_CAP) {
2601
+ this.hashes.delete(this.hashes.values().next().value);
2602
+ }
2603
+ }
2604
+ unmark(digest) {
2605
+ this.hashes.delete(digest);
2606
+ }
2607
+ };
2095
2608
  function buildSeamAugmentations(options) {
2096
2609
  return {
2097
2610
  injected_tools: [...options.injectedToolNames].sort(),
@@ -2110,12 +2623,12 @@ var wired = /* @__PURE__ */ new WeakSet();
2110
2623
  var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
2111
2624
  var callSlots = new import_node_async_hooks.AsyncLocalStorage();
2112
2625
  var SurfaceState = class {
2113
- constructor(serverMeta, emittedHashes) {
2626
+ constructor(serverMeta, sentSurfaces) {
2114
2627
  this.serverMeta = serverMeta;
2115
- this.emittedHashes = emittedHashes;
2628
+ this.sentSurfaces = sentSurfaces;
2116
2629
  }
2117
2630
  serverMeta;
2118
- emittedHashes;
2631
+ sentSurfaces;
2119
2632
  /** Every tool this install has seen, keyed by its CURRENT name. `disabled`
2120
2633
  * is tracked alongside rather than pruned, so re-enabling costs nothing and
2121
2634
  * — crucially — never needs a re-capture, which would re-read Baton's own
@@ -2172,7 +2685,7 @@ async function resolveEnvelopeParts(ctx, extra) {
2172
2685
  }
2173
2686
  async function openCall(ctx, toolName, extra, params, retired, registered = true) {
2174
2687
  await maybeEmitSurfaceSnapshot(ctx);
2175
- const { sessionId, origin, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
2688
+ const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
2176
2689
  const dispositions = ctx.paramRegistry.get(toolName);
2177
2690
  const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
2178
2691
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
@@ -2186,7 +2699,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
2186
2699
  const common = {
2187
2700
  tenant_id: ctx.tenantId,
2188
2701
  vendor_id: ctx.vendorId,
2189
- session_id: sessionId,
2702
+ session_id: session.sessionId,
2190
2703
  consent_token: ctx.consentToken,
2191
2704
  // Every `...common` site is an event of this call, so `call_id` rides in
2192
2705
  // it. `surface_snapshot` is deliberately not among them: it describes the
@@ -2195,7 +2708,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
2195
2708
  principal: caller.principal,
2196
2709
  organization: caller.organization,
2197
2710
  transport_observed: observeTransport(extra),
2198
- session_id_origin: origin,
2711
+ session_id_origin: session.origin,
2199
2712
  client_observed: observeClient(extra, ctx),
2200
2713
  runtime_meta: scrubbedMeta,
2201
2714
  call_id: uuid7()
@@ -2204,7 +2717,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
2204
2717
  ctx.sink,
2205
2718
  () => ToolCallStartEventSchema.parse({
2206
2719
  ...common,
2207
- sequence_number: ctx.counter.next(sessionId),
2720
+ sequence_number: ctx.counter.nextFor(session),
2208
2721
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2209
2722
  payload: {
2210
2723
  tool_name: toolName,
@@ -2217,7 +2730,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
2217
2730
  }
2218
2731
  })
2219
2732
  );
2220
- return { common, sessionId };
2733
+ return { common, session };
2221
2734
  }
2222
2735
  function batonWrap(nameRef, original, ctx) {
2223
2736
  return async (...callArgs) => {
@@ -2228,7 +2741,7 @@ function batonWrap(nameRef, original, ctx) {
2228
2741
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
2229
2742
  const retired = slot?.retired ?? {};
2230
2743
  if (slot) slot.retired = {};
2231
- const { common, sessionId } = await openCall(ctx, toolName, extra, params, retired);
2744
+ const { common, session } = await openCall(ctx, toolName, extra, params, retired);
2232
2745
  const terminate = async (build, replacement) => {
2233
2746
  if (!slot) {
2234
2747
  await emit(ctx.sink, build);
@@ -2254,18 +2767,20 @@ function batonWrap(nameRef, original, ctx) {
2254
2767
  await parkFailure(
2255
2768
  () => ToolCallErrorEventSchema.parse({
2256
2769
  ...common,
2257
- sequence_number: ctx.counter.next(sessionId),
2770
+ sequence_number: ctx.counter.nextFor(session),
2258
2771
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2259
2772
  payload: {
2260
2773
  tool_name: toolName,
2261
2774
  error_type: errorTypeOf(err),
2262
- // ⚠ KEPT under `resultCaptureMode: "off"`, and that is the rule's
2263
- // shape rather than an exception to it: the rule is keyed on
2264
- // PROVENANCE, and a thrown error's message is the vendor's own
2265
- // code speaking about a call that returned nothing (SPEC
2266
- // §11.4.3(1)). A switch written as "drop `error_body`" would
2267
- // delete the highest-value diagnostic the product has.
2268
- error_body: errorBody(ctx, messageOf(err)),
2775
+ // SPEC §11.4.3(1): the MCP SDK has no tool-error class to mark a
2776
+ // raised message public, so under "off" every one is withheld.
2777
+ ...resultDerivedFields(
2778
+ ctx.resultCaptureMode,
2779
+ () => messageOf(err),
2780
+ null,
2781
+ (text) => errorBody(ctx, text),
2782
+ ctx.scrubber
2783
+ ),
2269
2784
  duration_ms: durationMs2,
2270
2785
  // Explicit, though the field is `.optional()` and this is its
2271
2786
  // absent value. The schema is deliberately not an emitter (see
@@ -2289,7 +2804,7 @@ function batonWrap(nameRef, original, ctx) {
2289
2804
  await parkFailure(
2290
2805
  () => ToolCallErrorEventSchema.parse({
2291
2806
  ...common,
2292
- sequence_number: ctx.counter.next(sessionId),
2807
+ sequence_number: ctx.counter.nextFor(session),
2293
2808
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2294
2809
  payload: {
2295
2810
  tool_name: toolName,
@@ -2319,7 +2834,7 @@ function batonWrap(nameRef, original, ctx) {
2319
2834
  await parkSuccess(
2320
2835
  () => ToolCallEndEventSchema.parse({
2321
2836
  ...common,
2322
- sequence_number: ctx.counter.next(sessionId),
2837
+ sequence_number: ctx.counter.nextFor(session),
2323
2838
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2324
2839
  payload: {
2325
2840
  tool_name: toolName,
@@ -2335,7 +2850,7 @@ function batonWrap(nameRef, original, ctx) {
2335
2850
  // CALLER saw fail, which is a success the product invented.
2336
2851
  (outcome) => ToolCallErrorEventSchema.parse({
2337
2852
  ...common,
2338
- sequence_number: ctx.counter.next(sessionId),
2853
+ sequence_number: ctx.counter.nextFor(session),
2339
2854
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2340
2855
  payload: {
2341
2856
  tool_name: toolName,
@@ -2402,7 +2917,7 @@ function popText(args, paramName) {
2402
2917
  if (!(paramName in args)) return null;
2403
2918
  const raw = args[paramName];
2404
2919
  delete args[paramName];
2405
- return typeof raw === "string" && raw.trim() ? raw : null;
2920
+ return typeof raw === "string" && !isBlank(raw) ? raw : null;
2406
2921
  }
2407
2922
  function stripRetiredParams(params, ctx) {
2408
2923
  const toolName = params?.name;
@@ -2418,7 +2933,6 @@ function stripRetiredParams(params, ctx) {
2418
2933
  }
2419
2934
  return retired;
2420
2935
  }
2421
- var MAX_REMEMBERED_SURFACES = 1024;
2422
2936
  async function maybeEmitSurfaceSnapshot(ctx) {
2423
2937
  if (!ctx.surfaceState.dirty) return;
2424
2938
  ctx.surfaceState.dirty = false;
@@ -2432,10 +2946,9 @@ async function maybeEmitSurfaceSnapshot(ctx) {
2432
2946
  `);
2433
2947
  return;
2434
2948
  }
2435
- const emitted = ctx.surfaceState.emittedHashes;
2436
- if (emitted.has(digest)) return;
2437
- if (emitted.size >= MAX_REMEMBERED_SURFACES) emitted.clear();
2438
- emitted.add(digest);
2949
+ const sent = ctx.surfaceState.sentSurfaces;
2950
+ if (sent.wasSent(digest)) return;
2951
+ sent.mark(digest);
2439
2952
  const seam = buildSeamAugmentations({
2440
2953
  injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
2441
2954
  intentParamNames: [USER_GOAL_PARAM_NAME],
@@ -2448,7 +2961,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
2448
2961
  } catch (err) {
2449
2962
  process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
2450
2963
  `);
2451
- emitted.delete(digest);
2964
+ sent.unmark(digest);
2452
2965
  ctx.surfaceState.dirty = true;
2453
2966
  }
2454
2967
  }
@@ -2543,7 +3056,7 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
2543
3056
  ctx.sink,
2544
3057
  () => schema.parse({
2545
3058
  ...opened.common,
2546
- sequence_number: ctx.counter.next(opened.sessionId),
3059
+ sequence_number: ctx.counter.nextFor(opened.session),
2547
3060
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2548
3061
  payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload })
2549
3062
  })
@@ -2575,26 +3088,26 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
2575
3088
  }
2576
3089
  async function openLifecycleCall(ctx, spec, requestParams, extra) {
2577
3090
  try {
2578
- const parts = await resolveEnvelopeParts(ctx, extra);
3091
+ const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
2579
3092
  const caller = await resolveCaller(ctx.resolvePrincipal, {
2580
3093
  extra,
2581
3094
  toolName: null,
2582
3095
  arguments: {}
2583
3096
  });
2584
3097
  return {
2585
- sessionId: parts.sessionId,
3098
+ session,
2586
3099
  subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
2587
3100
  common: {
2588
3101
  tenant_id: ctx.tenantId,
2589
3102
  vendor_id: ctx.vendorId,
2590
- session_id: parts.sessionId,
3103
+ session_id: session.sessionId,
2591
3104
  consent_token: ctx.consentToken,
2592
3105
  principal: caller.principal,
2593
3106
  organization: caller.organization,
2594
3107
  transport_observed: observeTransport(extra),
2595
- session_id_origin: parts.origin,
3108
+ session_id_origin: session.origin,
2596
3109
  client_observed: observeClient(extra, ctx),
2597
- runtime_meta: parts.scrubbedMeta
3110
+ runtime_meta: scrubbedMeta
2598
3111
  }
2599
3112
  };
2600
3113
  } catch (err) {
@@ -2723,7 +3236,7 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
2723
3236
  innerFired: false,
2724
3237
  flushTerminal: null,
2725
3238
  retired: stripRetiredParams(request?.params, ctx),
2726
- validation: ctx.validationProbeLive() ? "unseen" : "unprobed"
3239
+ validation: "unseen"
2727
3240
  };
2728
3241
  let outcome = CLEAN_OUTCOME;
2729
3242
  try {
@@ -2743,8 +3256,7 @@ var VALIDATION_PROBE = /* @__PURE__ */ Symbol("baton.validationProbe");
2743
3256
  function installValidationProbe(server) {
2744
3257
  const target = server;
2745
3258
  const original = target.validateToolInput;
2746
- if (typeof original !== "function") return () => false;
2747
- if (original[VALIDATION_PROBE]) return () => target.validateToolInput === original;
3259
+ if (typeof original !== "function" || original[VALIDATION_PROBE]) return;
2748
3260
  const probe = async function(...args) {
2749
3261
  const slot = callSlots.getStore();
2750
3262
  try {
@@ -2758,7 +3270,6 @@ function installValidationProbe(server) {
2758
3270
  };
2759
3271
  Object.assign(probe, { [VALIDATION_PROBE]: true });
2760
3272
  target.validateToolInput = probe;
2761
- return () => target.validateToolInput === probe;
2762
3273
  }
2763
3274
  async function settleCall(slot, outcome, args, toolEntry, ctx) {
2764
3275
  try {
@@ -2772,6 +3283,7 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
2772
3283
  if (!outcome.failed) return;
2773
3284
  await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
2774
3285
  } catch (err) {
3286
+ PROCESS_DROPS.add("encode_failed");
2775
3287
  process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
2776
3288
  `);
2777
3289
  }
@@ -2784,7 +3296,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
2784
3296
  const entry = toolEntry(toolName);
2785
3297
  if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
2786
3298
  const params = { ...request?.params?.arguments ?? {} };
2787
- const { common, sessionId } = await openCall(
3299
+ const { common, session } = await openCall(
2788
3300
  ctx,
2789
3301
  toolName,
2790
3302
  args[1],
@@ -2798,7 +3310,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
2798
3310
  ctx.sink,
2799
3311
  () => ToolCallErrorEventSchema.parse({
2800
3312
  ...common,
2801
- sequence_number: ctx.counter.next(sessionId),
3313
+ sequence_number: ctx.counter.nextFor(session),
2802
3314
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2803
3315
  payload: {
2804
3316
  tool_name: toolName,
@@ -2914,15 +3426,19 @@ function withBaton(server, supplied = {}) {
2914
3426
  }
2915
3427
  const resolved = resolveBatonConfig(supplied);
2916
3428
  warnUnusedReportSettings(resolved);
2917
- return install(server, supplied, resolved, /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set());
3429
+ return install(server, supplied, resolved, new SentSurfaces(), /* @__PURE__ */ new Set());
2918
3430
  }
2919
3431
  function createBaton(supplied = {}) {
2920
3432
  const disabledBy = captureDisabled();
2921
3433
  if (disabledBy !== null) {
2922
3434
  logDisabled(disabledBy, "createBaton");
2923
3435
  const unused = supplied.sink ?? new DisabledSink();
2924
- return { wrap: () => {
2925
- }, flush: () => unused.flush(), aclose: () => unused.aclose() };
3436
+ return {
3437
+ wrap: () => {
3438
+ },
3439
+ flush: () => boundedSinkCall(unused, "flush"),
3440
+ aclose: () => boundedSinkCall(unused, "aclose")
3441
+ };
2926
3442
  }
2927
3443
  const resolved = resolveBatonConfig(supplied);
2928
3444
  warnUnusedReportSettings(resolved);
@@ -2933,17 +3449,17 @@ function createBaton(supplied = {}) {
2933
3449
  sink,
2934
3450
  tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
2935
3451
  };
2936
- const emittedSurfaceHashes = /* @__PURE__ */ new Set();
3452
+ const sentSurfaces = new SentSurfaces();
2937
3453
  const warned3 = /* @__PURE__ */ new Set();
2938
3454
  return {
2939
3455
  wrap: (server) => {
2940
- install(server, supplied, config, emittedSurfaceHashes, warned3);
3456
+ install(server, supplied, config, sentSurfaces, warned3);
2941
3457
  },
2942
- flush: () => sink.flush(),
2943
- aclose: () => sink.aclose()
3458
+ flush: () => boundedSinkCall(sink, "flush"),
3459
+ aclose: () => boundedSinkCall(sink, "aclose")
2944
3460
  };
2945
3461
  }
2946
- function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
3462
+ function install(server, supplied, resolved, sentSurfaces, warned3) {
2947
3463
  const internals = server;
2948
3464
  const serverName = usableServerName(() => ({
2949
3465
  name: internals.server._serverInfo?.name,
@@ -2953,13 +3469,13 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
2953
3469
  const sink = config.sink ?? new StdoutSink();
2954
3470
  const reports = reportsFor(config);
2955
3471
  const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
2956
- const intentParamMode = config.intentParamMode ?? "required";
3472
+ const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
2957
3473
  const counter2 = new SessionCounter();
2958
3474
  const fallbackSessionId = `sdk-${uuid7()}`;
2959
3475
  const tenantId = resolveTenantId(config.tenantId, config.vendorId);
2960
3476
  const scrubber = config.scrubber ?? new Scrubber().scrub;
2961
3477
  const serverMeta = buildServerMeta(server.server);
2962
- const surfaceState = new SurfaceState(serverMeta, emittedSurfaceHashes);
3478
+ const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
2963
3479
  const emitSurface = async (sessionId, digest, snapshot) => {
2964
3480
  const event = SurfaceSnapshotEventSchema.parse({
2965
3481
  tenant_id: tenantId,
@@ -3025,6 +3541,7 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
3025
3541
  return { type: "object", properties: {} };
3026
3542
  }
3027
3543
  };
3544
+ installValidationProbe(server);
3028
3545
  const ctx = {
3029
3546
  sink,
3030
3547
  counter: counter2,
@@ -3037,7 +3554,6 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
3037
3554
  annotationToolName,
3038
3555
  intentParamMode,
3039
3556
  resultCaptureMode: config.resultCaptureMode ?? "full",
3040
- validationProbeLive: installValidationProbe(server),
3041
3557
  paramRegistry: /* @__PURE__ */ new Map(),
3042
3558
  resolvePrincipal: config.resolvePrincipal,
3043
3559
  vendorToolJsonSchema,
@@ -3128,7 +3644,7 @@ function claimsOf(context) {
3128
3644
  }
3129
3645
  function stringClaim(claims, name) {
3130
3646
  const value = claims[name];
3131
- return typeof value === "string" && pythonStrip(value) !== "" ? value : null;
3647
+ return typeof value === "string" && !isBlank(value) ? value : null;
3132
3648
  }
3133
3649
  function principalFromOAuthSub(context) {
3134
3650
  const claims = claimsOf(context);
@@ -3160,33 +3676,46 @@ function sessionEnvelope(session) {
3160
3676
  principal: session.principal,
3161
3677
  organization: session.organization,
3162
3678
  client_observed: session.clientObserved,
3163
- runtime_meta: session.turnId !== null ? { [TURN_ID_META_KEY]: session.turnId } : null
3679
+ runtime_meta: session.runtimeMeta
3164
3680
  };
3165
3681
  }
3166
- function warn3(message) {
3682
+ function warn2(message) {
3167
3683
  process.stderr.write(`baton: ${message}
3168
3684
  `);
3169
3685
  }
3170
3686
  function vendorId(name, value) {
3171
- const cleaned = typeof value === "string" ? pythonStrip(value) : "";
3687
+ const cleaned = typeof value === "string" ? stripWhiteSpace(value) : "";
3172
3688
  if (cleaned !== "") return cleaned;
3173
3689
  if (value !== void 0 && value !== null) {
3174
- warn3(`${name} is not a non-blank string \u2014 ignoring it.`);
3690
+ warn2(`${name} is not a non-blank string \u2014 ignoring it.`);
3175
3691
  }
3176
3692
  return null;
3177
3693
  }
3178
3694
  function blank(sessionId, origin) {
3179
- return { sessionId, origin, ...NO_CALLER, clientObserved: null, turnId: null };
3695
+ return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };
3696
+ }
3697
+ function requestMeta(meta) {
3698
+ if (isRecord(meta)) return meta;
3699
+ if (meta !== void 0 && meta !== null) warn2("meta is not an object \u2014 ignoring it.");
3700
+ return null;
3701
+ }
3702
+ function runtimeMeta(meta, turnId, scrubber) {
3703
+ const clientKeys = Object.fromEntries(Object.entries(meta ?? {}).filter(([key]) => key !== TURN_ID_META_KEY));
3704
+ const cleaned = Object.keys(clientKeys).length > 0 ? scrubOrNull(scrubber, roundMetaCoordinates(clientKeys), "_meta") : null;
3705
+ const out = isRecord(cleaned) ? { ...cleaned } : {};
3706
+ if (turnId !== null) out[TURN_ID_META_KEY] = turnId;
3707
+ return Object.keys(out).length > 0 ? out : null;
3180
3708
  }
3181
3709
  function newSession(values, scrubber, disabled) {
3182
3710
  const id = vendorId("sessionId", values.sessionId);
3183
3711
  const base = id !== null ? blank(id, "observed") : blank(uuid7(), "minted");
3184
3712
  if (disabled) return base;
3713
+ const meta = requestMeta(values.meta);
3185
3714
  return {
3186
3715
  ...base,
3187
- ...callerFor(values.principal, (_key, message) => warn3(`principal ${message}`)),
3188
- clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber),
3189
- turnId: vendorId("turnId", values.turnId)
3716
+ ...callerFor(values.principal, (_key, message) => warn2(`principal ${message}`)),
3717
+ clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber, meta),
3718
+ runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
3190
3719
  };
3191
3720
  }
3192
3721
  var current = new import_node_async_hooks2.AsyncLocalStorage();
@@ -3197,11 +3726,71 @@ function sessionForCall(owner) {
3197
3726
  const entry = current.getStore();
3198
3727
  return entry !== void 0 && entry.owner === owner ? entry.session : blank(uuid7(), "minted");
3199
3728
  }
3200
- var lastSequence = 0;
3201
- function nextSequence() {
3202
- const nowMicros = Math.floor((performance.timeOrigin + performance.now()) * 1e3);
3203
- lastSequence = Math.max(lastSequence + 1, nowMicros);
3204
- return lastSequence;
3729
+
3730
+ // src/library/surface.ts
3731
+ function serveTools(tools, options) {
3732
+ let served;
3733
+ try {
3734
+ served = tools.map(servedEntry);
3735
+ } catch (err) {
3736
+ process.stderr.write(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}
3737
+ `);
3738
+ return { served: tools, surface: null };
3739
+ }
3740
+ try {
3741
+ const nameOf = (tool) => isRecord(tool) ? String(tool.name) : "";
3742
+ const ordered = [...tools].sort((a, b) => {
3743
+ const [x, y] = [nameOf(a), nameOf(b)];
3744
+ return x < y ? -1 : x > y ? 1 : 0;
3745
+ });
3746
+ const meta = {
3747
+ server_info: options.serverInfo ?? null,
3748
+ capabilities: options.capabilities ?? null,
3749
+ instructions: options.instructions ?? null
3750
+ };
3751
+ const surface = JSON.parse(
3752
+ JSON.stringify(assembleSurface(meta, ordered))
3753
+ );
3754
+ return { served, surface: { surface, digest: surfaceHash(surface) } };
3755
+ } catch (err) {
3756
+ process.stderr.write(`baton: surface snapshot capture failed: ${printable(err)}
3757
+ `);
3758
+ return { served, surface: null };
3759
+ }
3760
+ }
3761
+ function snapshotPayload({ surface, digest }) {
3762
+ return {
3763
+ surface_hash: digest,
3764
+ ...surface,
3765
+ seam_augmentations: buildSeamAugmentations({
3766
+ injectedToolNames: [],
3767
+ intentParamNames: [USER_GOAL_PARAM_NAME],
3768
+ intentParamMode: DEFAULT_INTENT_PARAM_MODE,
3769
+ requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),
3770
+ instructionsSuffix: null
3771
+ })
3772
+ };
3773
+ }
3774
+ function servedEntry(tool) {
3775
+ if (!isRecord(tool)) return tool;
3776
+ const entry = { ...tool };
3777
+ if (isRecord(entry.inputSchema)) {
3778
+ const schema = { ...entry.inputSchema };
3779
+ if (isRecord(schema.properties)) schema.properties = { ...schema.properties };
3780
+ injectGoalParam(schema);
3781
+ entry.inputSchema = schema;
3782
+ }
3783
+ return entry;
3784
+ }
3785
+ function injectGoalParam(schema) {
3786
+ if (schema.properties === void 0) schema.properties = {};
3787
+ if (!isRecord(schema.properties) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return;
3788
+ schema.properties[USER_GOAL_PARAM_NAME] = {
3789
+ type: "string",
3790
+ description: buildUserGoalParamDescription({ intentParamMode: DEFAULT_INTENT_PARAM_MODE })
3791
+ };
3792
+ const required = Array.isArray(schema.required) ? schema.required : [];
3793
+ if (!required.includes(USER_GOAL_PARAM_NAME)) schema.required = [...required, USER_GOAL_PARAM_NAME];
3205
3794
  }
3206
3795
 
3207
3796
  // src/library/client.ts
@@ -3264,7 +3853,7 @@ function resolveClientOptions(options) {
3264
3853
  resultCaptureMode
3265
3854
  };
3266
3855
  }
3267
- var hasText2 = (value) => typeof value === "string" && pythonStrip(value) !== "";
3856
+ var hasText2 = (value) => typeof value === "string" && !isBlank(value);
3268
3857
  function describeError(err) {
3269
3858
  let type = "Error";
3270
3859
  let body = "";
@@ -3278,19 +3867,18 @@ function describeError(err) {
3278
3867
  }
3279
3868
  return [type, body];
3280
3869
  }
3281
- function isPlainObject3(value) {
3282
- if (typeof value !== "object" || value === null) return false;
3283
- const proto = Object.getPrototypeOf(value);
3284
- return proto === Object.prototype || proto === null;
3285
- }
3286
3870
  function paramsOf(args) {
3287
- if (args.length === 1 && isPlainObject3(args[0])) return args[0];
3871
+ if (args.length === 1 && isPlainObject(args[0])) return args[0];
3288
3872
  return args.length === 0 ? {} : { args };
3289
3873
  }
3290
3874
  var Core = class {
3291
3875
  closed = false;
3292
3876
  pending = /* @__PURE__ */ new Set();
3293
3877
  closedWarned = false;
3878
+ // A snapshot describes the server, so it takes no block's session,
3879
+ // principal or client: SPEC §11.5.1's join must not count it.
3880
+ surfaceSessionId = uuid7();
3881
+ sentSurfaces = new SentSurfaces();
3294
3882
  sink;
3295
3883
  vendorId;
3296
3884
  tenantId;
@@ -3323,6 +3911,7 @@ var Core = class {
3323
3911
  live() {
3324
3912
  if (this.disabled) return false;
3325
3913
  if (!this.closed) return true;
3914
+ PROCESS_DROPS.add("after_close");
3326
3915
  if (!this.closedWarned) {
3327
3916
  this.closedWarned = true;
3328
3917
  process.stderr.write("baton: Client is closed; further events are dropped.\n");
@@ -3331,19 +3920,69 @@ var Core = class {
3331
3920
  }
3332
3921
  /** Never rejects. Tracked so `flush()` can wait for it. */
3333
3922
  emit(build) {
3334
- const write = emit(this.sink, build).finally(() => this.pending.delete(write));
3335
- this.pending.add(write);
3336
- return write;
3923
+ return this.track(emit(this.sink, build));
3924
+ }
3925
+ track(work) {
3926
+ const tracked = work.finally(() => this.pending.delete(tracked));
3927
+ this.pending.add(tracked);
3928
+ return tracked;
3929
+ }
3930
+ /** Sends `surface` unless this client already has. Never rejects; a failed
3931
+ * write unmarks it, so the next `listTools` tries again. A surface that does
3932
+ * not fit the schema stays marked: it would fail the same way every time. */
3933
+ sendSurface(surface) {
3934
+ if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();
3935
+ this.sentSurfaces.mark(surface.digest);
3936
+ let event;
3937
+ try {
3938
+ event = SurfaceSnapshotEventSchema.parse({
3939
+ tenant_id: this.tenantId,
3940
+ vendor_id: this.vendorId,
3941
+ session_id: this.surfaceSessionId,
3942
+ session_id_origin: "minted",
3943
+ sequence_number: nextClockSequence(),
3944
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
3945
+ consent_token: this.consentToken,
3946
+ payload: snapshotPayload(surface)
3947
+ });
3948
+ } catch (err) {
3949
+ PROCESS_DROPS.add("encode_failed");
3950
+ process.stderr.write(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}
3951
+ `);
3952
+ return Promise.resolve();
3953
+ }
3954
+ return this.track(
3955
+ (async () => {
3956
+ try {
3957
+ await this.sink.write(event);
3958
+ } catch (err) {
3959
+ process.stderr.write(`baton: surface snapshot not sent; will retry: ${printable(err)}
3960
+ `);
3961
+ this.sentSurfaces.unmark(surface.digest);
3962
+ }
3963
+ })()
3964
+ );
3337
3965
  }
3338
- async settle() {
3339
- while (this.pending.size > 0) await Promise.all([...this.pending]);
3966
+ /** Waits up to `ms` for pending events to reach the sink; with `untilEmpty`,
3967
+ * also for ones emitted while it waits. A write still pending when time runs
3968
+ * out is not waited on again, so one stuck write costs one wait. */
3969
+ async settleWithin(ms, untilEmpty) {
3970
+ const deadline = performance.now() + ms;
3971
+ do {
3972
+ const waiting = [...this.pending];
3973
+ if (await raceDeadline(Promise.allSettled(waiting), deadline - performance.now()) === TIMED_OUT) {
3974
+ const left = waiting.filter((write) => this.pending.delete(write));
3975
+ if (untilEmpty) PROCESS_DROPS.add("unsent_at_close", left.length);
3976
+ return;
3977
+ }
3978
+ } while (untilEmpty && this.pending.size > 0);
3340
3979
  }
3341
3980
  scrub(value, field) {
3342
3981
  return scrubOrNull(this.scrubber, value, field);
3343
3982
  }
3344
3983
  annotate(session, consentToken, options) {
3345
3984
  if (!this.live()) return Promise.resolve();
3346
- const sequence = nextSequence();
3985
+ const sequence = nextClockSequence();
3347
3986
  const text = (value) => value === void 0 ? null : this.scrubber(value);
3348
3987
  return this.emit(
3349
3988
  () => AnnotationEventSchema.parse({
@@ -3411,7 +4050,7 @@ var Trace = class _Trace {
3411
4050
  try {
3412
4051
  this.#result = this.#core.scrubber(result);
3413
4052
  } catch (err) {
3414
- process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${String(err)}
4053
+ process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}
3415
4054
  `);
3416
4055
  this.#result = SCRUB_FAILED;
3417
4056
  }
@@ -3431,7 +4070,7 @@ var Trace = class _Trace {
3431
4070
  #start() {
3432
4071
  this.#startedAt = performance.now();
3433
4072
  if (!this.#core.live()) return;
3434
- const sequence = nextSequence();
4073
+ const sequence = nextClockSequence();
3435
4074
  const o = this.#options;
3436
4075
  const params = o.params === void 0 ? {} : this.#core.scrub(o.params, "params") ?? {};
3437
4076
  const textOf = (value, field) => {
@@ -3460,7 +4099,7 @@ var Trace = class _Trace {
3460
4099
  const durationMs = this.#durationMs();
3461
4100
  if (!this.#core.live()) return;
3462
4101
  if (this.#result === UNSET && this.#error === null) this.observed(value);
3463
- const sequence = nextSequence();
4102
+ const sequence = nextClockSequence();
3464
4103
  const error = this.#error;
3465
4104
  if (error !== null) {
3466
4105
  this.#emitError(sequence, error.type, error.body, durationMs);
@@ -3482,7 +4121,7 @@ var Trace = class _Trace {
3482
4121
  #fail(err) {
3483
4122
  const durationMs = this.#durationMs();
3484
4123
  if (!this.#core.live()) return;
3485
- this.#emitError(nextSequence(), ...describeError(err), durationMs);
4124
+ this.#emitError(nextClockSequence(), ...describeError(err), durationMs);
3486
4125
  }
3487
4126
  #emitError(sequence, type, body, durationMs) {
3488
4127
  void this.#core.emit(
@@ -3558,7 +4197,7 @@ var Client = class {
3558
4197
  try {
3559
4198
  block = newSession(options, this.#core.scrubber, this.#core.disabled);
3560
4199
  } catch (err) {
3561
- process.stderr.write(`baton: session values could not be read; using a minted session: ${String(err)}
4200
+ process.stderr.write(`baton: session values could not be read; using a minted session: ${printable(err)}
3562
4201
  `);
3563
4202
  block = newSession({}, this.#core.scrubber, this.#core.disabled);
3564
4203
  }
@@ -3588,30 +4227,41 @@ var Client = class {
3588
4227
  const given = options ?? {};
3589
4228
  return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);
3590
4229
  }
3591
- /** Wait until every event so far has reached the sink and the sink has flushed. */
4230
+ /** `tools`, the vendor's own `tools/list` entries, with `user_goal` added
4231
+ * to each `inputSchema` as `withBaton` adds it, and a `surface_snapshot`
4232
+ * of `tools` as passed, sent once per distinct surface. For a vendor
4233
+ * serving MCP itself (SPEC §5.6).
4234
+ *
4235
+ * Pass the tools before anything of Baton's is added, so the snapshot
4236
+ * describes the vendor's own surface. `options` holds the vendor's own
4237
+ * `initialize` values. The input is not changed. Never rejects over the
4238
+ * tool list: one it cannot read is returned as it came. Does not wait for
4239
+ * the snapshot to be sent; `flush()` does. */
4240
+ async listTools(tools, options = {}) {
4241
+ if (this.#core.disabled) return tools;
4242
+ const { served, surface } = serveTools(tools, options);
4243
+ if (surface !== null) void this.#core.sendSurface(surface);
4244
+ return served;
4245
+ }
4246
+ /** Wait for events so far to reach the sink, then flush it. Never rejects;
4247
+ * returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
3592
4248
  async flush() {
3593
- await this.#core.settle();
3594
- try {
3595
- await this.#core.sink.flush();
3596
- } catch (err) {
3597
- process.stderr.write(`baton: sink.flush failed: ${String(err)}
3598
- `);
3599
- }
4249
+ await this.#settleThen("flush");
3600
4250
  }
3601
4251
  /** Flush, then close the sink. Later events are dropped. */
3602
4252
  aclose() {
3603
- this.#closing ??= this.#close();
4253
+ this.#closing ??= this.#settleThen("aclose");
3604
4254
  return this.#closing;
3605
4255
  }
3606
- async #close() {
3607
- await this.#core.settle();
3608
- this.#core.closed = true;
3609
- try {
3610
- await this.#core.sink.aclose();
3611
- } catch (err) {
3612
- process.stderr.write(`baton: sink.aclose failed: ${String(err)}
3613
- `);
3614
- }
4256
+ /** One budget: events in flight get until its end to reach the sink, then
4257
+ * the sink gets the time left. */
4258
+ async #settleThen(method) {
4259
+ await boundedSinkCall(this.#core.sink, method, async (budgetMs) => {
4260
+ const deadline = performance.now() + budgetMs;
4261
+ await this.#core.settleWithin(budgetMs, method === "aclose");
4262
+ if (method === "aclose") this.#core.closed = true;
4263
+ await callWithin(this.#core.sink, method, Math.max(0, deadline - performance.now()));
4264
+ });
3615
4265
  }
3616
4266
  };
3617
4267
  // Annotate the CommonJS export names for ESM import in node:
@@ -3620,13 +4270,18 @@ var Client = class {
3620
4270
  AnnotationPayloadSchema,
3621
4271
  BatonHandle,
3622
4272
  Client,
4273
+ ClientReportEventSchema,
4274
+ ClientReportPayloadSchema,
3623
4275
  DEFAULT_CONSENT_TOKEN,
3624
4276
  DEPTH_LIMIT,
4277
+ DEPTH_MARKER,
3625
4278
  EventSchema,
3626
4279
  EventTypeSchema,
4280
+ FileSink,
3627
4281
  HttpSink,
3628
4282
  INTENT_INSTRUCTIONS,
3629
4283
  INTENT_PARAMS,
4284
+ MultiSink,
3630
4285
  PRINCIPAL_FORM_HASHED,
3631
4286
  PRINCIPAL_FORM_RAW,
3632
4287
  PRINCIPAL_SOURCE_ASSERTED,