@goodtiming/baton-sdk 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,16 +1,16 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-1.1.0";
2
+ var SDK_VERSION = "ts-1.2.0";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
6
6
 
7
7
  // src/uuid7.ts
8
- import { randomBytes } from "crypto";
8
+ import * as crypto from "crypto";
9
9
  var COUNTER_MAX = 4095;
10
10
  var lastMs = -1;
11
11
  var counter = 0;
12
12
  function uuid7() {
13
- const bytes = randomBytes(18);
13
+ const bytes = crypto.randomBytes(18);
14
14
  const seed = (bytes[16] << 8 | bytes[17]) & 2047;
15
15
  const now = Date.now();
16
16
  if (now > lastMs) {
@@ -132,7 +132,8 @@ var ClientObservedSchema = z.object({
132
132
  var CaptureObservedSchema = z.object({
133
133
  settings_version: z.number().int().min(1).optional(),
134
134
  audience: z.string().optional(),
135
- overlay: z.string().optional()
135
+ overlay: z.string().optional(),
136
+ candidate: z.string().optional()
136
137
  }).strict();
137
138
  var PrincipalWireSchema = z.object({
138
139
  id: z.string(),
@@ -389,13 +390,49 @@ function onWorkers() {
389
390
  return typeof globalThis.WebSocketPair === "function" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
390
391
  }
391
392
  var globalFetch = (input, init) => fetch(input, init);
393
+ function onProcess(event, listener) {
394
+ const target = typeof process !== "undefined" ? process : void 0;
395
+ if (typeof target?.on !== "function") return void 0;
396
+ try {
397
+ target.on(event, listener);
398
+ } catch {
399
+ return void 0;
400
+ }
401
+ return () => {
402
+ try {
403
+ target.off(event, listener);
404
+ } catch {
405
+ }
406
+ };
407
+ }
392
408
 
393
409
  // src/warn.ts
394
410
  function warn(message) {
395
411
  if (onWorkers()) {
396
412
  console.warn(message);
397
- } else if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
398
- process.emitWarning(message);
413
+ return;
414
+ }
415
+ try {
416
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") return process.emitWarning(message);
417
+ } catch {
418
+ }
419
+ stderrLine(message);
420
+ }
421
+ function stderrLine(message) {
422
+ stderrLines([message]);
423
+ }
424
+ function stderrLines(lines) {
425
+ try {
426
+ const stderr = typeof process !== "undefined" ? process.stderr : void 0;
427
+ if (typeof stderr?.write === "function") return void stderr.write(lines.map((line) => `${line}
428
+ `).join(""));
429
+ } catch {
430
+ }
431
+ for (const line of lines) {
432
+ try {
433
+ console.warn(line);
434
+ } catch {
435
+ }
399
436
  }
400
437
  }
401
438
  function printable(err) {
@@ -525,8 +562,8 @@ function identityScrub(value) {
525
562
  }
526
563
 
527
564
  // src/sinks.ts
528
- import { appendFileSync } from "fs";
529
- import { open } from "fs/promises";
565
+ import * as fs from "fs";
566
+ import * as fsp from "fs/promises";
530
567
 
531
568
  // src/_text.ts
532
569
  var WHITE_SPACE = /^\p{White_Space}$/u;
@@ -541,6 +578,11 @@ function stripEdges(value, space) {
541
578
  function stripWhiteSpace(value) {
542
579
  return stripEdges(value, WHITE_SPACE);
543
580
  }
581
+ function stripWhiteSpaceEnd(value) {
582
+ let end = value.length;
583
+ while (end > 0 && WHITE_SPACE.test(value[end - 1])) end--;
584
+ return value.slice(0, end);
585
+ }
544
586
  function isBlank(value) {
545
587
  return ALL_WHITE_SPACE.test(value);
546
588
  }
@@ -648,14 +690,9 @@ async function safeWrite(sink, event) {
648
690
  } catch (err) {
649
691
  if (isSinkClosed(err)) return droppedAfterClose(sink);
650
692
  PROCESS_DROPS.add("write_failed");
651
- process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}
652
- `);
693
+ stderrLine(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}`);
653
694
  }
654
695
  }
655
- function stderrLine(message) {
656
- process.stderr.write(`${message}
657
- `);
658
- }
659
696
  function isTimerMs(value) {
660
697
  return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
661
698
  }
@@ -695,11 +732,13 @@ var StdoutSink = class {
695
732
  stream;
696
733
  closed = false;
697
734
  constructor(options = {}) {
698
- this.stream = options.stream ?? process.stderr;
735
+ this.stream = options.stream;
699
736
  }
700
737
  async write(event) {
701
738
  if (this.closed) throw new SinkClosedError("StdoutSink is closed");
702
- this.stream.write(JSON.stringify(event) + "\n");
739
+ const line = JSON.stringify(event);
740
+ if (this.stream) this.stream.write(line + "\n");
741
+ else stderrLine(line);
703
742
  }
704
743
  async flush() {
705
744
  }
@@ -721,7 +760,7 @@ var FileSink = class {
721
760
  if (this.closed) throw new SinkClosedError("FileSink is closed");
722
761
  const line = JSON.stringify(event) + "\n";
723
762
  const written = this.last.then(async () => {
724
- this.file ??= await open(this.path, "a");
763
+ this.file ??= await fsp.open(this.path, "a");
725
764
  await this.file.appendFile(line);
726
765
  });
727
766
  this.last = written.catch(() => void 0);
@@ -778,30 +817,31 @@ var later = (run) => {
778
817
  else setTimeout(run, 0);
779
818
  };
780
819
  var withUnwrittenEvents = /* @__PURE__ */ new Set();
781
- var exitHooked = false;
820
+ var exitTriedOn = /* @__PURE__ */ new WeakSet();
782
821
  function hookExit() {
783
- if (exitHooked) return;
784
- exitHooked = true;
785
- try {
786
- process.on("exit", () => {
787
- try {
788
- let unsure = 0;
789
- for (const sink of withUnwrittenEvents) unsure += sink.handOffAtExit();
790
- if (unsure > 0) stderrLine(`baton: process exiting; ${unsure} event(s) may not have been written.`);
791
- } catch {
792
- }
793
- });
794
- } catch {
795
- }
822
+ const target = typeof process !== "undefined" ? process : void 0;
823
+ if (target === void 0 || exitTriedOn.has(target)) return;
824
+ exitTriedOn.add(target);
825
+ onProcess("exit", () => {
826
+ try {
827
+ let unsure = 0;
828
+ for (const sink of withUnwrittenEvents) unsure += sink.handOffAtExit();
829
+ if (unsure > 0) stderrLine(`baton: process exiting; ${unsure} event(s) may not have been written.`);
830
+ } catch {
831
+ }
832
+ });
796
833
  }
797
834
  function writeNow(sink, events) {
798
- const lines = events.map((event) => JSON.stringify(event) + "\n").join("");
835
+ const json = () => events.map((event) => JSON.stringify(event));
836
+ const lines = () => json().map((line) => line + "\n").join("");
799
837
  if (sink instanceof StdoutSink) {
800
838
  const stream = sink["stream"];
801
- if (stream !== process.stdout && stream !== process.stderr) return false;
802
- if (!sink["closed"]) stream.write(lines);
839
+ if (stream !== void 0 && stream !== process.stdout && stream !== process.stderr) return false;
840
+ if (sink["closed"]) return true;
841
+ if (stream === void 0) stderrLines(json());
842
+ else stream.write(lines());
803
843
  } else if (sink instanceof FileSink) {
804
- if (!sink["closed"]) appendFileSync(sink["path"], lines);
844
+ if (!sink["closed"]) fs.appendFileSync(sink["path"], lines());
805
845
  } else return false;
806
846
  return true;
807
847
  }
@@ -1059,6 +1099,8 @@ var HttpSink = class _HttpSink {
1059
1099
  /** Set for the life of the sink by a 404 or 405 on the batch path. */
1060
1100
  batchless = false;
1061
1101
  exitHooks = null;
1102
+ /** The `process` the exit hooks were last tried on, so a refusal is not retried per write. */
1103
+ exitHooksTriedOn;
1062
1104
  /** The least time between two of this sink's loss reports. */
1063
1105
  static reportIntervalMs = 6e4;
1064
1106
  /** Totals only grow, so their sum tells whether they changed. */
@@ -1156,11 +1198,8 @@ var HttpSink = class _HttpSink {
1156
1198
  warn(`baton: the sink closed with ${unsent} event(s) unsent.`);
1157
1199
  }
1158
1200
  this.warnUnloggedRefusals("the sink closed");
1159
- if (this.exitHooks) {
1160
- process.off("beforeExit", this.exitHooks.beforeExit);
1161
- process.off("exit", this.exitHooks.exit);
1162
- this.exitHooks = null;
1163
- }
1201
+ this.exitHooks?.off();
1202
+ this.exitHooks = null;
1164
1203
  }
1165
1204
  /** SPEC §11.2 rule 7: an explicit flush or close returns within `ms` and
1166
1205
  * never rejects. While an earlier wait's drain is still stuck, a flush
@@ -1254,7 +1293,9 @@ var HttpSink = class _HttpSink {
1254
1293
  * both hooks: a vendor needing that guarantee must call `aclose()` from
1255
1294
  * their own handler. */
1256
1295
  ensureExitHooksRegistered() {
1257
- if (this.exitHooks) return;
1296
+ const target = typeof process !== "undefined" ? process : void 0;
1297
+ if (this.exitHooks || target === void 0 || target === this.exitHooksTriedOn) return;
1298
+ this.exitHooksTriedOn = target;
1258
1299
  const beforeExit = () => {
1259
1300
  if (this.unsent === 0 || this.exitPassRan) {
1260
1301
  this.warnUnloggedRefusals("process exiting");
@@ -1272,9 +1313,14 @@ var HttpSink = class _HttpSink {
1272
1313
  } catch {
1273
1314
  }
1274
1315
  };
1275
- this.exitHooks = { beforeExit, exit };
1276
- process.on("beforeExit", beforeExit);
1277
- process.on("exit", exit);
1316
+ const offBeforeExit = onProcess("beforeExit", beforeExit);
1317
+ const offExit = onProcess("exit", exit);
1318
+ if (offBeforeExit === void 0 || offExit === void 0) {
1319
+ offBeforeExit?.();
1320
+ offExit?.();
1321
+ return;
1322
+ }
1323
+ this.exitHooks = { beforeExit, exit, off: () => (offBeforeExit(), offExit()) };
1278
1324
  }
1279
1325
  /** One attempt per batch, no retry, within `shutdownFlushTimeoutMs` in
1280
1326
  * total (SPEC §11.2); what is left is reported, not sent. */
@@ -1655,7 +1701,7 @@ var HttpSink = class _HttpSink {
1655
1701
  };
1656
1702
 
1657
1703
  // src/integrations/mcp/withBaton.ts
1658
- import { AsyncLocalStorage } from "async_hooks";
1704
+ import * as asyncHooks from "async_hooks";
1659
1705
 
1660
1706
  // src/integrations/mcp/annotation.ts
1661
1707
  import { z as z2 } from "zod";
@@ -1700,6 +1746,122 @@ function roundMetaCoordinates(meta) {
1700
1746
  return walk(meta, 0);
1701
1747
  }
1702
1748
 
1749
+ // src/integrations/mcp/overlays.ts
1750
+ var INSTRUCTION_PIECES = ["instructions.subagent", "instructions.report_pointer"];
1751
+ var AUDIENCE_PIECES = ["goal_param.description", "report_tool.description", "report_tool.refusal"];
1752
+ var TEXT_CHANGES = ["append", "replace"];
1753
+ var FLAG_CHANGES = ["remove", "required"];
1754
+ var warned = /* @__PURE__ */ new Set();
1755
+ var unreadable = /* @__PURE__ */ new Set();
1756
+ function warnSkipped(overlayId, index, reason) {
1757
+ const key = JSON.stringify([overlayId, index]);
1758
+ if (warned.has(key)) return;
1759
+ warned.add(key);
1760
+ warn(`baton: overlay ${JSON.stringify(overlayId)} action ${index} is skipped: ${reason}`);
1761
+ }
1762
+ var Overlay = class {
1763
+ constructor(id, actions) {
1764
+ this.id = id;
1765
+ this.actions = actions;
1766
+ this.hiddenTools = new Set(
1767
+ actions.filter((a) => a.tool !== void 0 && a.param === void 0 && a.change === "remove").map((a) => a.tool)
1768
+ );
1769
+ }
1770
+ id;
1771
+ actions;
1772
+ hiddenTools;
1773
+ pieceActions(piece) {
1774
+ return this.actions.filter((a) => a.piece === piece);
1775
+ }
1776
+ instructionAppends() {
1777
+ return this.actions.filter((a) => a.instructions && a.text !== void 0).map((a) => a.text);
1778
+ }
1779
+ };
1780
+ function changedText(text, actions) {
1781
+ let source = "default";
1782
+ for (const action of actions) {
1783
+ if (action.change === "replace") {
1784
+ text = action.text;
1785
+ source = "replaced";
1786
+ } else if (action.change === "append" && action.text !== void 0) {
1787
+ const kept = stripWhiteSpaceEnd(text ?? "");
1788
+ text = kept ? `${kept}
1789
+
1790
+ ${action.text}` : action.text;
1791
+ if (source === "default") source = "appended";
1792
+ }
1793
+ }
1794
+ return { text, source };
1795
+ }
1796
+ function overlaid(text, overlay, piece) {
1797
+ if (overlay === void 0) return text;
1798
+ return changedText(text, overlay.pieceActions(piece)).text ?? text;
1799
+ }
1800
+ function readOverlays(value) {
1801
+ return isRecord(value) ? value : {};
1802
+ }
1803
+ function overlayFor(overlays, overlayId, place) {
1804
+ if (overlayId === void 0 || overlayId === null) return void 0;
1805
+ let id;
1806
+ let body;
1807
+ if (typeof overlayId === "string") {
1808
+ id = overlayId;
1809
+ body = Object.hasOwn(overlays, id) ? overlays[id] : void 0;
1810
+ } else {
1811
+ id = JSON.stringify(overlayId);
1812
+ }
1813
+ const actions = isRecord(body) ? body.actions : void 0;
1814
+ if (!Array.isArray(actions)) {
1815
+ if (!unreadable.has(id)) {
1816
+ unreadable.add(id);
1817
+ warn(`baton: overlay ${JSON.stringify(id)} cannot be read; none is applied there`);
1818
+ }
1819
+ return void 0;
1820
+ }
1821
+ const kept = [];
1822
+ actions.forEach((raw, index) => {
1823
+ const read = readAction(index, raw, place);
1824
+ if (typeof read === "string") warnSkipped(id, index, read);
1825
+ else kept.push(read);
1826
+ });
1827
+ return new Overlay(id, kept);
1828
+ }
1829
+ function readAction(index, raw, place) {
1830
+ if (!isRecord(raw) || !isRecord(raw.target)) return "it has no target";
1831
+ const target = raw.target;
1832
+ const changes = [...TEXT_CHANGES, ...FLAG_CHANGES].filter((c) => Object.hasOwn(raw, c));
1833
+ if (changes.length !== 1 || Object.keys(raw).length !== 2) return "it needs exactly one change";
1834
+ const change = changes[0];
1835
+ const value = raw[change];
1836
+ if (TEXT_CHANGES.includes(change) && typeof value !== "string") return `'${change}' needs text`;
1837
+ if (FLAG_CHANGES.includes(change) && value !== true) return `'${change}' must be true`;
1838
+ const text = typeof value === "string" ? { text: value } : {};
1839
+ const keys = Object.keys(target).sort().join(",");
1840
+ if (keys === "tool" && typeof target.tool === "string") {
1841
+ if (change === "required") return "only a param can be required";
1842
+ return placed({ index, change, ...text, tool: target.tool }, place, "audience");
1843
+ }
1844
+ if (keys === "param,tool" && typeof target.tool === "string" && typeof target.param === "string") {
1845
+ return placed({ index, change, ...text, tool: target.tool, param: target.param }, place, "audience");
1846
+ }
1847
+ if (keys === "instructions" && target.instructions === true) {
1848
+ if (change !== "append") return "the instructions take only 'append'";
1849
+ return placed({ index, change, ...text, instructions: true }, place, "server");
1850
+ }
1851
+ if (keys === "agent_text" && typeof target.agent_text === "string") {
1852
+ const piece = target.agent_text;
1853
+ if (!TEXT_CHANGES.includes(change)) return "agent_text takes only 'append' or 'replace'";
1854
+ if (INSTRUCTION_PIECES.includes(piece)) return placed({ index, change, ...text, piece }, place, "server");
1855
+ if (AUDIENCE_PIECES.includes(piece)) return placed({ index, change, ...text, piece }, place, "audience");
1856
+ return `unknown agent_text ${JSON.stringify(piece)}`;
1857
+ }
1858
+ return "unknown target";
1859
+ }
1860
+ function placed(action, place, allowed) {
1861
+ if (place === allowed) return action;
1862
+ return `this target goes only in ${allowed === "server" ? "server_overlay" : "an audience's overlay"}`;
1863
+ }
1864
+
1703
1865
  // src/integrations/mcp/llmText.ts
1704
1866
  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.`;
1705
1867
  var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
@@ -1715,14 +1877,14 @@ Fields:
1715
1877
  - context: supplementary info not covered above. Common keys: plan, alternatives_considered, likely_cause, user_impact, error_class, downstream_blocked, confidence_in_intent. When no tool covers the request also missing_capability_field and requested_capability.`;
1716
1878
  var CLAUDE_CODE_TRUNCATION_CAP = 2087;
1717
1879
  var INSTRUCTIONS_LENGTH_CAP = 1500;
1718
- function renderServerInstructions(options) {
1880
+ function buildReportPointer(options) {
1719
1881
  return REPORT_POINTER_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
1720
1882
  }
1721
1883
  function fitsInstructionsCap(options) {
1722
- return renderServerInstructions(options).length <= INSTRUCTIONS_LENGTH_CAP;
1884
+ return buildReportPointer(options).length <= INSTRUCTIONS_LENGTH_CAP;
1723
1885
  }
1724
1886
  function buildServerInstructions(options) {
1725
- const rendered = renderServerInstructions(options);
1887
+ const rendered = buildReportPointer(options);
1726
1888
  if (rendered.length > INSTRUCTIONS_LENGTH_CAP) {
1727
1889
  throw new Error(
1728
1890
  `Rendered server instructions are ${rendered.length} chars, which exceeds the ${INSTRUCTIONS_LENGTH_CAP}-char safety cap (Claude Code truncates at ~${CLAUDE_CODE_TRUNCATION_CAP}). Shorten vendorDisplayName or annotationToolName.`
@@ -1734,7 +1896,8 @@ function buildAnnotationToolDescription(options) {
1734
1896
  return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
1735
1897
  }
1736
1898
  function buildRefusalText(options) {
1737
- return `${options.annotationToolName} is reactive-only on this server. Call it only AFTER a tool call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. What the user is trying to do is already recorded on each tool call, so no pre-call annotation is needed \u2014 nothing was lost. If a tool call really went wrong, or no tool covers the request, call this again and say what_happened. If neither is true, do NOT re-send: that would file a report for a call that did not go wrong.`;
1899
+ const text = `${options.annotationToolName} is reactive-only on this server. Call it only AFTER a tool call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. What the user is trying to do is already recorded on each tool call, so no pre-call annotation is needed \u2014 nothing was lost. If a tool call really went wrong, or no tool covers the request, call this again and say what_happened. If neither is true, do NOT re-send: that would file a report for a call that did not go wrong.`;
1900
+ return overlaid(text, options.overlay, "report_tool.refusal");
1738
1901
  }
1739
1902
  var USER_GOAL_PARAM_NAME = "user_goal";
1740
1903
  var EXPECTED_RESULT_PARAM_NAME = "expected_result";
@@ -1782,38 +1945,47 @@ var INTENT_PARAMS = Object.freeze([
1782
1945
  Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: "intent" })
1783
1946
  ]);
1784
1947
  var VENDOR_INSTRUCTIONS = /* @__PURE__ */ Symbol("batonVendorInstructions");
1785
- var escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1786
- var OURS_STARTS = [
1787
- new RegExp(
1788
- "^" + REPORT_POINTER_TEMPLATE("\0", "\0").split("\0").map(escapeRegExp).join(".+?")
1789
- ),
1790
- new RegExp("^" + escapeRegExp(INTENT_INSTRUCTIONS))
1791
- ];
1792
- function endsInOurs(current2, vendor) {
1793
- if (typeof current2 !== "string") return false;
1794
- const prefix = typeof vendor === "string" && !isBlank(vendor) ? `${vendor}
1948
+ var OURS = /* @__PURE__ */ Symbol("batonInstructions");
1949
+ var SUBAGENT = /* @__PURE__ */ Symbol("batonSubagentSentence");
1950
+ function joined(vendor, ours) {
1951
+ if (typeof vendor !== "string" || isBlank(vendor)) return ours;
1952
+ return ours ? `${vendor}
1795
1953
 
1796
- ` : "";
1797
- if (!current2.startsWith(prefix)) return false;
1798
- const rest = current2.slice(prefix.length);
1799
- return OURS_STARTS.some((start) => start.test(rest));
1954
+ ${ours}` : vendor;
1800
1955
  }
1801
- function withVendorInstructions(server, ours, warn3 = (message) => process.stderr.write(message)) {
1802
- const holder = server;
1956
+ function vendorText(holder) {
1803
1957
  const current2 = holder._instructions;
1804
- let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
1805
- if (!endsInOurs(current2, vendor)) {
1806
- vendor = current2;
1807
- holder[VENDOR_INSTRUCTIONS] = vendor;
1958
+ const written = holder[OURS];
1959
+ const vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
1960
+ return written !== void 0 && current2 === joined(vendor, written) ? vendor : current2;
1961
+ }
1962
+ function writeOurs(server, ours, subagent, write, warn3 = stderrLine) {
1963
+ const holder = server;
1964
+ const vendor = vendorText(holder);
1965
+ write(withVendorInstructions(server, ours, warn3));
1966
+ holder[VENDOR_INSTRUCTIONS] = vendor;
1967
+ holder[OURS] = ours;
1968
+ holder[SUBAGENT] = subagent && ours.endsWith(subagent) ? subagent : void 0;
1969
+ }
1970
+ function removeSubagentClause(server, write, warn3 = stderrLine) {
1971
+ const holder = server;
1972
+ const ours = holder[OURS];
1973
+ const subagent = holder[SUBAGENT];
1974
+ if (ours === void 0 || !subagent || holder._instructions !== joined(holder[VENDOR_INSTRUCTIONS], ours)) {
1975
+ return false;
1808
1976
  }
1809
- if (typeof vendor !== "string" || isBlank(vendor)) return ours;
1810
- const combined = `${vendor}
1811
-
1812
- ${ours}`;
1977
+ const kept = ours.slice(0, ours.length - subagent.length);
1978
+ writeOurs(server, kept.endsWith("\n\n") ? kept.slice(0, -2) : kept, null, write, warn3);
1979
+ return true;
1980
+ }
1981
+ function withVendorInstructions(server, ours, warn3 = stderrLine) {
1982
+ const vendor = vendorText(server);
1983
+ const combined = joined(vendor, ours);
1984
+ if (combined === ours) return ours;
1985
+ const vendorLength = vendor?.length ?? 0;
1813
1986
  if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
1814
1987
  warn3(
1815
- `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
1816
- `
1988
+ `baton: the server instructions are ${combined.length} chars (yours ${vendorLength}, Baton's ${ours.length}); Claude Code cuts them at ~${CLAUDE_CODE_TRUNCATION_CAP}, so the end of Baton's text is lost there`
1817
1989
  );
1818
1990
  }
1819
1991
  return combined;
@@ -1920,8 +2092,7 @@ async function emit(sink, build) {
1920
2092
  event = build();
1921
2093
  } catch (err) {
1922
2094
  PROCESS_DROPS.add("encode_failed");
1923
- process.stderr.write(`baton: event construction failed; event dropped: ${printable(err)}
1924
- `);
2095
+ stderrLine(`baton: event construction failed; event dropped: ${printable(err)}`);
1925
2096
  return;
1926
2097
  }
1927
2098
  await safeWrite(sink, event);
@@ -2072,135 +2243,571 @@ function identityWire(id, stated, displayName, onUnregisteredForm) {
2072
2243
  return wire;
2073
2244
  }
2074
2245
 
2075
- // src/integrations/mcp/mcpTypes.ts
2076
- function extraAuthInfo(extra) {
2077
- const found = extra.authInfo ?? extra.http?.authInfo;
2078
- return found !== null && typeof found === "object" ? found : null;
2079
- }
2080
- function extraMeta(extra) {
2081
- const direct = extra._meta;
2082
- if (direct) return direct;
2083
- const nested = extra.mcpReq?._meta;
2084
- return nested ?? null;
2085
- }
2086
- function extraEnvelope(extra) {
2087
- const envelope = extra.mcpReq?.envelope;
2088
- return envelope ?? null;
2246
+ // src/integrations/mcp/captureSettings.ts
2247
+ import * as crypto2 from "crypto";
2248
+
2249
+ // src/integrations/mcp/errorResult.ts
2250
+ var TOOL_ERROR_TYPE = "tool_error";
2251
+ var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
2252
+ var REFUSED = "refused";
2253
+ var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
2254
+ function requestSideFailureKind(entry, validation) {
2255
+ if (entry == null) return "unknown_tool";
2256
+ if (entry.enabled === false) return "tool_disabled";
2257
+ if (validation === "rejected") return "invalid_argument";
2258
+ if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
2259
+ return REFUSED;
2089
2260
  }
2090
- function observeTransport(extra) {
2261
+ var ERROR_BODY_MAX_CODE_POINTS = 2e3;
2262
+ function isErrorResult(value) {
2091
2263
  try {
2092
- const carrier = extra.http?.req ?? extra.requestInfo;
2093
- return carrier ? "http" : "no-http-request";
2264
+ if (typeof value !== "object" || value === null) return false;
2265
+ return Boolean(value.isError);
2094
2266
  } catch {
2095
- return "read-failed";
2267
+ return false;
2096
2268
  }
2097
2269
  }
2098
- function extraHeaders(extra) {
2099
- const fromV2 = extra.http?.req?.headers;
2100
- if (fromV2 && typeof fromV2.get === "function") return fromV2;
2101
- const fromV1 = extra.requestInfo?.headers;
2102
- if (fromV1 && typeof fromV1 === "object") {
2103
- const headers = new Headers();
2104
- for (const [name, value] of Object.entries(fromV1)) {
2105
- for (const item of Array.isArray(value) ? value : [value]) {
2106
- if (typeof item !== "string") continue;
2107
- try {
2108
- headers.append(name, item);
2109
- } catch {
2110
- }
2111
- }
2270
+ function errorText(value) {
2271
+ const parts = [];
2272
+ try {
2273
+ const content = value?.content;
2274
+ if (!Array.isArray(content)) return "";
2275
+ for (const part of content) {
2276
+ const text = part?.text;
2277
+ if (typeof text !== "string") continue;
2278
+ const trimmed = stripWhiteSpace(text);
2279
+ if (trimmed) parts.push(trimmed);
2112
2280
  }
2113
- return headers;
2281
+ } catch {
2282
+ return "";
2114
2283
  }
2115
- return null;
2284
+ return parts.join("\n");
2116
2285
  }
2117
- function isThenable(value) {
2118
- return typeof value?.then === "function";
2286
+ var RESULT_CAPTURE_MODES = ["full", "off"];
2287
+ var WITHHELD = "off";
2288
+ function endResultFields(mode, result, scrubber) {
2289
+ switch (mode) {
2290
+ case WITHHELD:
2291
+ return { result: null, result_capture: WITHHELD };
2292
+ case "full":
2293
+ return { result: scrubber(result) };
2294
+ }
2119
2295
  }
2120
-
2121
- // src/integrations/mcp/principalResolution.ts
2122
- function buildPrincipalResolutionContext(extra, toolName, args) {
2123
- return {
2124
- headers: extraHeaders(extra),
2125
- meta: extraMeta(extra),
2126
- toolName,
2127
- arguments: args,
2128
- authInfo: extraAuthInfo(extra)
2129
- };
2296
+ function returnedErrorFields(mode, result, errorBody2, scrubber) {
2297
+ return resultDerivedFields(mode, () => errorText(result), result, errorBody2, scrubber);
2130
2298
  }
2131
- var HOOK_TIMEOUT_MS = 5e3;
2132
- async function withinHookBudget(answer) {
2133
- if (!isThenable(answer)) return answer;
2134
- const first = await raceDeadline(answer, HOOK_TIMEOUT_MS);
2135
- if (first !== TIMED_OUT) return first;
2136
- warn(
2137
- `baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
2138
- );
2139
- return null;
2299
+ function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
2300
+ switch (mode) {
2301
+ case WITHHELD:
2302
+ return { error_body: "", result: null, result_capture: WITHHELD };
2303
+ case "full":
2304
+ return { error_body: errorBody2(text()), result: scrubber(result) };
2305
+ }
2140
2306
  }
2141
- var warned = /* @__PURE__ */ new Set();
2142
- function warnOnce(key, message) {
2143
- if (warned.has(key)) return;
2144
- warned.add(key);
2145
- warn(`baton: resolvePrincipal ${message}`);
2307
+ function requestSideErrorFields(text, errorBody2) {
2308
+ return { error_body: errorBody2(text), result: null };
2146
2309
  }
2147
- function callerEnvelope(caller) {
2148
- return {
2149
- principal: caller.principal,
2150
- organization: caller.organization,
2151
- labels: wireLabels(caller.labels),
2152
- capture: caller.settings?.capture ?? null
2153
- };
2310
+ function requestSideFailureFields(kind, mode, text, result, errorBody2, scrubber) {
2311
+ return kind === REFUSED ? resultDerivedFields(mode, text, result ?? null, errorBody2, scrubber) : requestSideErrorFields(text(), errorBody2);
2154
2312
  }
2155
- var settingsWarned = false;
2156
- async function resolveCaller(hook, call, settings, client = null) {
2157
- const caller = await resolveIdentity(hook, call);
2158
- if (settings === void 0) return caller;
2159
- try {
2160
- const callSettings = settings.forCaller({
2161
- labels: caller.labels,
2162
- clientName: client?.info?.name ?? null,
2163
- shareKey: caller.principal?.id ?? null
2164
- });
2165
- return callSettings === void 0 ? caller : { ...caller, settings: callSettings };
2166
- } catch {
2167
- if (!settingsWarned) {
2168
- settingsWarned = true;
2169
- warn("baton: applying capture settings failed; this request uses the config's values");
2170
- }
2171
- return caller;
2172
- }
2313
+ function errorTypeOf(err) {
2314
+ return err instanceof Error ? err.constructor.name : "Error";
2173
2315
  }
2174
- async function resolveIdentity(hook, call) {
2175
- if (hook === void 0) return NO_CALLER;
2316
+ function messageOf(err) {
2317
+ return err instanceof Error ? err.message : String(err);
2318
+ }
2319
+ function scrubbedErrorBody(scrubber, text) {
2320
+ return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
2321
+ }
2322
+
2323
+ // src/integrations/mcp/captureSettings.ts
2324
+ var SETTINGS_PATH = "/v0/settings";
2325
+ var TENANT_HEADER = "X-Baton-Tenant-Id";
2326
+ var SETTINGS_MODES = ["local", "console"];
2327
+ var DEFAULT_SETTINGS_REFRESH_MS = 6e4;
2328
+ var MIN_SETTINGS_REFRESH_MS = 15e3;
2329
+ var REQUEST_TIMEOUT_MS = 1e4;
2330
+ var CANDIDATE_ENV = "BATON_CANDIDATE";
2331
+ var CANDIDATE_HEADER = "baton-candidate";
2332
+ var CANDIDATES_HELD = 32;
2333
+ var CANDIDATE_READS_AT_ONCE = 4;
2334
+ var CANDIDATE_START_TIMEOUT_MS = 5e3;
2335
+ var CANDIDATE_ID = /^[A-Za-z0-9_-]{1,128}$/;
2336
+ function candidateId(value) {
2337
+ if (typeof value !== "string") return null;
2338
+ const id = stripWhiteSpace(value);
2339
+ return CANDIDATE_ID.test(id) ? id : null;
2340
+ }
2341
+ function headerCandidate(headers) {
2176
2342
  try {
2177
- const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
2178
- const result = await withinHookBudget(hook(context));
2179
- return callerFor(result, warnOnce);
2343
+ return candidateId(headers?.get(CANDIDATE_HEADER));
2180
2344
  } catch {
2181
- return NO_CALLER;
2345
+ return null;
2182
2346
  }
2183
2347
  }
2184
-
2185
- // src/integrations/mcp/zodCompat.ts
2186
- import * as z3rt from "zod/v3";
2187
- import * as z4mini from "zod/v4-mini";
2188
- import { zodToJsonSchema } from "zod-to-json-schema";
2189
- function isZ4Schema(s) {
2190
- const schema = s;
2191
- return !!schema?._zod;
2348
+ function envCandidate() {
2349
+ const value = typeof process !== "undefined" ? process.env?.[CANDIDATE_ENV] : void 0;
2350
+ if (!value) return null;
2351
+ const id = candidateId(value);
2352
+ if (id === null) warn(`baton: ${CANDIDATE_ENV} is not a change id; today's settings apply.`);
2353
+ return id;
2192
2354
  }
2193
- function objectFromShape(shape) {
2194
- const values = Object.values(shape);
2195
- if (values.length === 0) return z4mini.object({});
2196
- const allV4 = values.every(isZ4Schema);
2197
- const allV3 = values.every((s) => !isZ4Schema(s));
2198
- if (allV4) return z4mini.object(shape);
2199
- if (allV3) return z3rt.object(shape);
2200
- throw new Error("Mixed Zod versions detected in object shape.");
2355
+ function candidateNeedsConsole(settings) {
2356
+ if (settings !== "console" && envCandidate() !== null) {
2357
+ warn(
2358
+ `baton: ${CANDIDATE_ENV} is set, but this server's settings are not "console", so the change is not fetched; today's settings apply.`
2359
+ );
2360
+ }
2201
2361
  }
2202
- function getObjectShape(schema) {
2203
- if (!schema) return void 0;
2362
+ var MATCH_KEYS = /* @__PURE__ */ new Set(["label", "client", "share"]);
2363
+ var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
2364
+ var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
2365
+ var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
2366
+ function shareBucket(vendorId2, key) {
2367
+ const digest = crypto2.createHash("sha256").update(`${vendorId2}
2368
+ ${key}`, "utf-8").digest();
2369
+ return Number(digest.readBigUInt64BE(0) % 10000n);
2370
+ }
2371
+ function matchesEveryone(audience) {
2372
+ return audience.labels === null && audience.clients === null && audience.shareThreshold === null;
2373
+ }
2374
+ function matches(audience, caller, bucket) {
2375
+ if (audience.labels !== null && !caller.labels.some((label) => audience.labels.has(label))) return false;
2376
+ if (audience.clients !== null && (caller.clientName === null || !audience.clients.has(caller.clientName))) {
2377
+ return false;
2378
+ }
2379
+ if (audience.shareThreshold !== null && (bucket === null || bucket >= audience.shareThreshold)) return false;
2380
+ return true;
2381
+ }
2382
+ var SettingsDocument = class {
2383
+ constructor(version, audiences, serverOverlay, candidate) {
2384
+ this.version = version;
2385
+ this.audiences = audiences;
2386
+ this.serverOverlay = serverOverlay;
2387
+ const overlays = audiences.flatMap((a) => a.settings.overlay === void 0 ? [] : [a.settings.overlay]);
2388
+ this.hiddenSomewhere = new Set(overlays.flatMap((o) => [...o.hiddenTools]));
2389
+ this.audiencePieces = new Set(overlays.flatMap((o) => o.actions.flatMap((a) => a.piece === void 0 ? [] : [a.piece])));
2390
+ this.usesShare = audiences.some((a) => a.shareThreshold !== null);
2391
+ this.unmatched = { capture: { settings_version: version, ...candidate === void 0 ? {} : { candidate } } };
2392
+ this.reportsOnForAnyone = audiences.some((a) => a.settings.reportMode !== "off") || !audiences.some(matchesEveryone);
2393
+ }
2394
+ version;
2395
+ audiences;
2396
+ serverOverlay;
2397
+ usesShare;
2398
+ unmatched;
2399
+ /** Whether some caller can get reports, so the instructions point to the
2400
+ * tool. Read only where the code's value is "on": no tool exists otherwise. */
2401
+ reportsOnForAnyone;
2402
+ /** The tools some audience's overlay hides. */
2403
+ hiddenSomewhere;
2404
+ /** The pieces of Baton's text some audience's overlay changes. */
2405
+ audiencePieces;
2406
+ settingsFor(caller, vendorId2) {
2407
+ const bucket = caller.shareKey !== null && this.usesShare ? shareBucket(vendorId2, caller.shareKey) : null;
2408
+ return this.audiences.find((audience) => matches(audience, caller, bucket))?.settings ?? this.unmatched;
2409
+ }
2410
+ };
2411
+ function stringSet(value) {
2412
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) return null;
2413
+ return new Set(value);
2414
+ }
2415
+ function readAudience(version, id, match, capture, overlay, candidate) {
2416
+ if (!Object.keys(match).every((key) => MATCH_KEYS.has(key))) return null;
2417
+ let labels = null;
2418
+ let clients = null;
2419
+ let shareThreshold = null;
2420
+ if (Object.hasOwn(match, "label") && (labels = stringSet(match.label)) === null) return null;
2421
+ if (Object.hasOwn(match, "client") && (clients = stringSet(match.client)) === null) return null;
2422
+ if (Object.hasOwn(match, "share")) {
2423
+ const share = match.share;
2424
+ if (typeof share !== "number" || !(share > 0 && share <= 1)) return null;
2425
+ shareThreshold = Math.floor(share * 1e4 + 0.5);
2426
+ }
2427
+ const settings = {
2428
+ capture: {
2429
+ settings_version: version,
2430
+ audience: id,
2431
+ ...overlay === void 0 ? {} : { overlay: overlay.id },
2432
+ ...candidate === void 0 ? {} : { candidate }
2433
+ }
2434
+ };
2435
+ if (overlay !== void 0) settings.overlay = overlay;
2436
+ const { results, goal, reports } = capture;
2437
+ if (typeof results === "string" && RESULT_CAPTURE_MODE_SET.has(results)) {
2438
+ settings.resultCaptureMode = results;
2439
+ }
2440
+ if (typeof goal === "string" && INTENT_PARAM_MODES.has(goal)) settings.intentParamMode = goal;
2441
+ if (typeof reports === "string" && REPORT_MODES.has(reports)) settings.reportMode = reports;
2442
+ return { settings, labels, clients, shareThreshold };
2443
+ }
2444
+ function parseDocument(body, candidate) {
2445
+ let data;
2446
+ try {
2447
+ data = JSON.parse(body);
2448
+ } catch {
2449
+ return null;
2450
+ }
2451
+ if (!isRecord(data)) return null;
2452
+ const { version, audiences } = data;
2453
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 1) return null;
2454
+ if (!Array.isArray(audiences) || audiences.length === 0) return null;
2455
+ if (candidate !== void 0 && data.candidate !== candidate) return null;
2456
+ const overlays = readOverlays(data.overlays);
2457
+ const parsed = [];
2458
+ for (const audience of audiences) {
2459
+ if (!isRecord(audience)) return null;
2460
+ const { id, match, capture } = audience;
2461
+ if (typeof id !== "string" || !isRecord(match) || !isRecord(capture)) return null;
2462
+ const overlay = overlayFor(overlays, audience.overlay, "audience");
2463
+ const readable = readAudience(version, id, match, capture, overlay, candidate);
2464
+ if (readable !== null) parsed.push(readable);
2465
+ }
2466
+ return new SettingsDocument(version, parsed, overlayFor(overlays, data.server_overlay, "server"), candidate);
2467
+ }
2468
+ var SettingsFetcher = class {
2469
+ url;
2470
+ // `#`, not `private`, so logging a config shows no key: "logging the config shows no key".
2471
+ #headers;
2472
+ refreshMs;
2473
+ fetchImpl;
2474
+ etag = null;
2475
+ held = null;
2476
+ timer = null;
2477
+ reading = null;
2478
+ candidateReads = /* @__PURE__ */ new Set();
2479
+ warned = false;
2480
+ constructor(options) {
2481
+ this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
2482
+ this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
2483
+ this.refreshMs = options.refreshMs;
2484
+ this.fetchImpl = options.fetchImpl ?? globalFetch;
2485
+ }
2486
+ get document() {
2487
+ return this.held;
2488
+ }
2489
+ start() {
2490
+ if (this.timer !== null) return;
2491
+ this.timer = setInterval(() => void this.readOnce(), this.refreshMs);
2492
+ this.timer.unref?.();
2493
+ void this.readOnce();
2494
+ }
2495
+ stop() {
2496
+ if (this.timer !== null) clearInterval(this.timer);
2497
+ this.timer = null;
2498
+ this.reading?.abort();
2499
+ this.reading = null;
2500
+ for (const read of this.candidateReads) read.abort();
2501
+ }
2502
+ async fetchCandidate(candidate, timeoutMs) {
2503
+ const reading = new AbortController();
2504
+ const timeout = setTimeout(() => reading.abort(), timeoutMs);
2505
+ timeout.unref?.();
2506
+ this.candidateReads.add(reading);
2507
+ try {
2508
+ const url = `${this.url}&${new URLSearchParams({ candidate }).toString()}`;
2509
+ const response = await this.fetchImpl(url, {
2510
+ method: "GET",
2511
+ headers: this.#headers,
2512
+ redirect: "manual",
2513
+ signal: reading.signal
2514
+ });
2515
+ if (response.status !== 200) void response.body?.cancel().catch(() => void 0);
2516
+ if (response.status === 403) return { outcome: "refused" };
2517
+ if (response.status === 404) return { outcome: "unknown" };
2518
+ if (response.status === 200) {
2519
+ const document = parseDocument(await response.text(), candidate);
2520
+ if (document !== null) return { outcome: "loaded", document };
2521
+ }
2522
+ } catch {
2523
+ } finally {
2524
+ clearTimeout(timeout);
2525
+ this.candidateReads.delete(reading);
2526
+ }
2527
+ return { outcome: "failed" };
2528
+ }
2529
+ /** One request. Never rejects: a failure keeps what is held. */
2530
+ async readOnce() {
2531
+ if (this.reading !== null) return;
2532
+ const reading = new AbortController();
2533
+ this.reading = reading;
2534
+ const timeout = setTimeout(() => reading.abort(), REQUEST_TIMEOUT_MS);
2535
+ timeout.unref?.();
2536
+ try {
2537
+ await this.read(reading.signal);
2538
+ } catch {
2539
+ } finally {
2540
+ clearTimeout(timeout);
2541
+ if (this.reading === reading) this.reading = null;
2542
+ }
2543
+ }
2544
+ async read(signal) {
2545
+ const headers = this.etag === null ? this.#headers : { ...this.#headers, "If-None-Match": this.etag };
2546
+ const response = await this.fetchImpl(this.url, { method: "GET", headers, redirect: "manual", signal });
2547
+ if (response.status !== 200) {
2548
+ void response.body?.cancel().catch(() => void 0);
2549
+ }
2550
+ if (signal.aborted) return;
2551
+ if (response.status === 204) {
2552
+ this.held = null;
2553
+ this.etag = null;
2554
+ } else if (response.status === 200) {
2555
+ const document = parseDocument(await response.text());
2556
+ if (signal.aborted) return;
2557
+ if (document === null) {
2558
+ if (!this.warned) {
2559
+ this.warned = true;
2560
+ warn("baton: the collector sent capture settings this SDK cannot read");
2561
+ }
2562
+ return;
2563
+ }
2564
+ this.held = document;
2565
+ this.etag = response.headers.get("etag");
2566
+ }
2567
+ }
2568
+ };
2569
+ var PENDING = /* @__PURE__ */ Symbol("pending");
2570
+ var CaptureSettings = class {
2571
+ constructor(vendorId2, source, candidate = null, startTimeoutMs = CANDIDATE_START_TIMEOUT_MS) {
2572
+ this.vendorId = vendorId2;
2573
+ this.source = source;
2574
+ this.candidate = candidate;
2575
+ this.startTimeoutMs = startTimeoutMs;
2576
+ }
2577
+ vendorId;
2578
+ source;
2579
+ candidate;
2580
+ startTimeoutMs;
2581
+ processDocument = null;
2582
+ /** `BATON_CANDIDATE`'s read; requests wait for it. */
2583
+ ready = Promise.resolve();
2584
+ isReady = true;
2585
+ // id -> its document, `null` for an unknown id, `PENDING`, or the time a failed read may be tried again.
2586
+ held = /* @__PURE__ */ new Map();
2587
+ // A 403 is about the key, so it answers every id for this process.
2588
+ refused = false;
2589
+ stopped = false;
2590
+ retryAfterMs = REQUEST_TIMEOUT_MS;
2591
+ start() {
2592
+ const candidate = this.candidate;
2593
+ if (candidate !== null && this.processDocument === null) {
2594
+ const cannotLoad = (why) => warn(`baton: ${CANDIDATE_ENV}=${candidate} could not be loaded (${why}); today's settings apply.`);
2595
+ const fetched = this.source.fetchCandidate(candidate, this.startTimeoutMs);
2596
+ this.isReady = false;
2597
+ this.ready = raceDeadline(fetched, this.startTimeoutMs).then((read) => {
2598
+ this.isReady = true;
2599
+ if (this.stopped) return;
2600
+ if (read === TIMED_OUT) {
2601
+ cannotLoad("no answer");
2602
+ void fetched.then((late) => {
2603
+ if (!this.stopped && late.outcome === "refused") this.record(candidate, late);
2604
+ });
2605
+ return;
2606
+ }
2607
+ this.record(candidate, read);
2608
+ if (read.outcome === "loaded") this.processDocument = read.document;
2609
+ else if (read.outcome !== "refused") cannotLoad(read.outcome === "unknown" ? "unknown id" : "no answer");
2610
+ });
2611
+ }
2612
+ this.source.start();
2613
+ }
2614
+ stop() {
2615
+ this.stopped = true;
2616
+ this.source.stop();
2617
+ }
2618
+ /** The document for a request with no header of its own. */
2619
+ get document() {
2620
+ return this.processDocument ?? this.source.document;
2621
+ }
2622
+ /** `undefined` while no document is held, and the config's values apply. */
2623
+ forCaller(caller) {
2624
+ const document = caller.candidate == null ? this.document : this.headerDocument(caller.candidate) ?? this.source.document;
2625
+ return document?.settingsFor(caller, this.vendorId);
2626
+ }
2627
+ /** Whether `test` holds for some document a request could be served under now. */
2628
+ someDocument(test) {
2629
+ const today = this.document;
2630
+ if (today !== null && test(today)) return true;
2631
+ for (const held of this.held.values()) if (held instanceof SettingsDocument && test(held)) return true;
2632
+ return false;
2633
+ }
2634
+ /** The header's change if it is held. The first sight of an id starts its
2635
+ * read in the background, unless too many are already running. */
2636
+ headerDocument(candidate) {
2637
+ if (this.refused) return null;
2638
+ const held = this.held.get(candidate);
2639
+ if (held !== void 0 && !(typeof held === "number" && held <= Date.now())) {
2640
+ this.held.delete(candidate);
2641
+ this.held.set(candidate, held);
2642
+ return held instanceof SettingsDocument ? held : null;
2643
+ }
2644
+ if ([...this.held.values()].filter((v) => v === PENDING).length >= CANDIDATE_READS_AT_ONCE) return null;
2645
+ this.held.delete(candidate);
2646
+ this.held.set(candidate, PENDING);
2647
+ this.evict();
2648
+ void this.source.fetchCandidate(candidate, REQUEST_TIMEOUT_MS).then((read) => {
2649
+ if (!this.stopped) this.record(candidate, read);
2650
+ });
2651
+ return null;
2652
+ }
2653
+ record(candidate, read) {
2654
+ if (read.outcome === "refused") {
2655
+ if (!this.refused) {
2656
+ warn("baton: this server's key is not a test key, so test changes are not fetched; today's settings apply.");
2657
+ }
2658
+ this.held.delete(candidate);
2659
+ this.refused = true;
2660
+ } else if (read.outcome === "failed") {
2661
+ this.held.set(candidate, Date.now() + this.retryAfterMs);
2662
+ } else {
2663
+ this.held.set(candidate, read.outcome === "loaded" ? read.document : null);
2664
+ this.evict();
2665
+ }
2666
+ }
2667
+ evict() {
2668
+ for (const [key, value] of this.held) {
2669
+ if (this.held.size <= CANDIDATES_HELD) return;
2670
+ if (value !== PENDING) this.held.delete(key);
2671
+ }
2672
+ }
2673
+ };
2674
+ function overlayChanges(settings, piece) {
2675
+ return settings?.someDocument((d) => d.audiencePieces.has(piece)) ?? false;
2676
+ }
2677
+ function mayHide(settings, name) {
2678
+ return settings?.someDocument((d) => d.hiddenSomewhere.has(name)) ?? false;
2679
+ }
2680
+
2681
+ // src/integrations/mcp/mcpTypes.ts
2682
+ function extraAuthInfo(extra) {
2683
+ const found = extra.authInfo ?? extra.http?.authInfo;
2684
+ return found !== null && typeof found === "object" ? found : null;
2685
+ }
2686
+ function extraMeta(extra) {
2687
+ const direct = extra._meta;
2688
+ if (direct) return direct;
2689
+ const nested = extra.mcpReq?._meta;
2690
+ return nested ?? null;
2691
+ }
2692
+ function extraEnvelope(extra) {
2693
+ const envelope = extra.mcpReq?.envelope;
2694
+ return envelope ?? null;
2695
+ }
2696
+ function observeTransport(extra) {
2697
+ try {
2698
+ const carrier = extra.http?.req ?? extra.requestInfo;
2699
+ return carrier ? "http" : "no-http-request";
2700
+ } catch {
2701
+ return "read-failed";
2702
+ }
2703
+ }
2704
+ function extraHeaders(extra) {
2705
+ const fromV2 = extra.http?.req?.headers;
2706
+ if (fromV2 && typeof fromV2.get === "function") return fromV2;
2707
+ const fromV1 = extra.requestInfo?.headers;
2708
+ if (fromV1 && typeof fromV1 === "object") {
2709
+ const headers = new Headers();
2710
+ for (const [name, value] of Object.entries(fromV1)) {
2711
+ for (const item of Array.isArray(value) ? value : [value]) {
2712
+ if (typeof item !== "string") continue;
2713
+ try {
2714
+ headers.append(name, item);
2715
+ } catch {
2716
+ }
2717
+ }
2718
+ }
2719
+ return headers;
2720
+ }
2721
+ return null;
2722
+ }
2723
+ function isThenable(value) {
2724
+ return typeof value?.then === "function";
2725
+ }
2726
+
2727
+ // src/integrations/mcp/principalResolution.ts
2728
+ function buildPrincipalResolutionContext(extra, toolName, args) {
2729
+ return {
2730
+ headers: extraHeaders(extra),
2731
+ meta: extraMeta(extra),
2732
+ toolName,
2733
+ arguments: args,
2734
+ authInfo: extraAuthInfo(extra)
2735
+ };
2736
+ }
2737
+ var HOOK_TIMEOUT_MS = 5e3;
2738
+ async function withinHookBudget(answer) {
2739
+ if (!isThenable(answer)) return answer;
2740
+ const first = await raceDeadline(answer, HOOK_TIMEOUT_MS);
2741
+ if (first !== TIMED_OUT) return first;
2742
+ warn(
2743
+ `baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
2744
+ );
2745
+ return null;
2746
+ }
2747
+ var warned2 = /* @__PURE__ */ new Set();
2748
+ function warnOnce(key, message) {
2749
+ if (warned2.has(key)) return;
2750
+ warned2.add(key);
2751
+ warn(`baton: resolvePrincipal ${message}`);
2752
+ }
2753
+ function callerEnvelope(caller) {
2754
+ return {
2755
+ principal: caller.principal,
2756
+ organization: caller.organization,
2757
+ labels: wireLabels(caller.labels),
2758
+ capture: caller.settings?.capture ?? null
2759
+ };
2760
+ }
2761
+ var settingsWarned = false;
2762
+ async function resolveCaller(hook, call, settings, client = null) {
2763
+ const caller = await resolveIdentity(hook, call);
2764
+ if (settings === void 0) return caller;
2765
+ try {
2766
+ const callSettings = settings.forCaller({
2767
+ labels: caller.labels,
2768
+ clientName: client?.info?.name ?? null,
2769
+ shareKey: caller.principal?.id ?? null,
2770
+ candidate: headerCandidate(extraHeaders(call.extra))
2771
+ });
2772
+ return callSettings === void 0 ? caller : { ...caller, settings: callSettings };
2773
+ } catch {
2774
+ if (!settingsWarned) {
2775
+ settingsWarned = true;
2776
+ warn("baton: applying capture settings failed; this request uses the config's values");
2777
+ }
2778
+ return caller;
2779
+ }
2780
+ }
2781
+ async function resolveIdentity(hook, call) {
2782
+ if (hook === void 0) return NO_CALLER;
2783
+ try {
2784
+ const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
2785
+ const result = await withinHookBudget(hook(context));
2786
+ return callerFor(result, warnOnce);
2787
+ } catch {
2788
+ return NO_CALLER;
2789
+ }
2790
+ }
2791
+
2792
+ // src/integrations/mcp/zodCompat.ts
2793
+ import * as z3rt from "zod/v3";
2794
+ import * as z4mini from "zod/v4-mini";
2795
+ import { zodToJsonSchema } from "zod-to-json-schema";
2796
+ function isZ4Schema(s) {
2797
+ const schema = s;
2798
+ return !!schema?._zod;
2799
+ }
2800
+ function objectFromShape(shape) {
2801
+ const values = Object.values(shape);
2802
+ if (values.length === 0) return z4mini.object({});
2803
+ const allV4 = values.every(isZ4Schema);
2804
+ const allV3 = values.every((s) => !isZ4Schema(s));
2805
+ if (allV4) return z4mini.object(shape);
2806
+ if (allV3) return z3rt.object(shape);
2807
+ throw new Error("Mixed Zod versions detected in object shape.");
2808
+ }
2809
+ function getObjectShape(schema) {
2810
+ if (!schema) return void 0;
2204
2811
  let rawShape;
2205
2812
  if (isZ4Schema(schema)) {
2206
2813
  rawShape = schema._zod?.def?.shape;
@@ -2335,6 +2942,15 @@ function advertiseIntentParamsRequired(result, names, isInjected) {
2335
2942
  });
2336
2943
  return changed ? { ...result, tools: advertised } : result;
2337
2944
  }
2945
+ function withToolInputSchema(result, name, inputSchema2) {
2946
+ const tools = result?.tools;
2947
+ if (!Array.isArray(tools)) return result;
2948
+ const at = tools.findIndex((tool) => isRecord(tool) && tool.name === name);
2949
+ if (at === -1) return result;
2950
+ const served = [...tools];
2951
+ served[at] = { ...tools[at], inputSchema: inputSchema2 };
2952
+ return { ...result, tools: served };
2953
+ }
2338
2954
  function standardInputJsonSchema(schema) {
2339
2955
  try {
2340
2956
  const standard = schema?.["~standard"];
@@ -2353,17 +2969,16 @@ function toolInputJsonSchema(inputSchema2) {
2353
2969
  }
2354
2970
 
2355
2971
  // src/integrations/mcp/safeScrub.ts
2356
- var warned2 = /* @__PURE__ */ new Set();
2972
+ var warned3 = /* @__PURE__ */ new Set();
2357
2973
  function scrubOrNull(scrubber, value, field) {
2358
2974
  if (value === null) return null;
2359
2975
  try {
2360
2976
  return scrubber(value);
2361
2977
  } catch (err) {
2362
- if (!warned2.has(field)) {
2363
- warned2.add(field);
2364
- process.stderr.write(
2365
- `baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}
2366
- `
2978
+ if (!warned3.has(field)) {
2979
+ warned3.add(field);
2980
+ stderrLine(
2981
+ `baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}`
2367
2982
  );
2368
2983
  }
2369
2984
  return null;
@@ -2498,7 +3113,8 @@ var ANNOTATION_INPUT_SHAPE = {
2498
3113
  // not rejected by validation.
2499
3114
  tool_name: z2.string().nullable().optional(),
2500
3115
  suggested_improvement: z2.string().optional(),
2501
- context: z2.record(z2.string(), z2.unknown()).optional()
3116
+ // zod renders "any value" as `{}`, which some MCP clients refuse (reportToolSchema.test.ts).
3117
+ context: z2.record(z2.string(), z2.unknown()).meta({ additionalProperties: true }).optional()
2502
3118
  };
2503
3119
  function isReport(whatHappened) {
2504
3120
  return typeof whatHappened === "string" && !isBlank(whatHappened);
@@ -2530,33 +3146,21 @@ function buildAnnotationTool(server, options) {
2530
3146
  const description = buildAnnotationToolDescription({
2531
3147
  vendorDisplayName: options.vendorDisplayName
2532
3148
  });
2533
- const refusal = buildRefusalText({ annotationToolName: name });
3149
+ const refused = (overlay) => ({
3150
+ content: [
3151
+ {
3152
+ type: "text",
3153
+ text: JSON.stringify({ ok: false, error: buildRefusalText({ annotationToolName: name, overlay }) })
3154
+ }
3155
+ ]
3156
+ });
2534
3157
  return {
2535
3158
  name,
2536
3159
  description,
2537
3160
  handler: async (args, extra) => {
2538
3161
  const whatHappened = args.what_happened;
2539
- if (!isReport(whatHappened)) {
2540
- return {
2541
- content: [
2542
- {
2543
- type: "text",
2544
- text: JSON.stringify({
2545
- ok: false,
2546
- error: refusal
2547
- })
2548
- }
2549
- ]
2550
- };
2551
- }
3162
+ if (!isReport(whatHappened) && !overlayChanges(options.captureSettings, "report_tool.refusal")) return refused();
2552
3163
  const reportedTool = args.tool_name ?? null;
2553
- const meta = extraMeta(extra);
2554
- const scrubbedMeta = scrubOrNull(
2555
- options.scrubber,
2556
- meta ? roundMetaCoordinates(meta) : null,
2557
- "_meta"
2558
- );
2559
- const session = await resolveSessionId(options.fallbackSessionId, extra);
2560
3164
  const client = observeClient(extra, { server, scrubber: options.scrubber });
2561
3165
  const caller = await resolveCaller(
2562
3166
  options.resolvePrincipal,
@@ -2564,6 +3168,14 @@ function buildAnnotationTool(server, options) {
2564
3168
  options.captureSettings,
2565
3169
  client
2566
3170
  );
3171
+ if (!isReport(whatHappened)) return refused(caller.settings?.overlay);
3172
+ const meta = extraMeta(extra);
3173
+ const scrubbedMeta = scrubOrNull(
3174
+ options.scrubber,
3175
+ meta ? roundMetaCoordinates(meta) : null,
3176
+ "_meta"
3177
+ );
3178
+ const session = await resolveSessionId(options.fallbackSessionId, extra);
2567
3179
  await emit(
2568
3180
  options.sink,
2569
3181
  () => AnnotationEventSchema.parse({
@@ -2604,9 +3216,11 @@ var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
2604
3216
  var NOT_IN_A_KEY = /[\x00\t\n\r]/;
2605
3217
  var PUBLISHABLE_PREFIX = "baton_pk_";
2606
3218
  var SECRET_PREFIX = "baton_sk_";
2607
- var KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;
3219
+ var TEST_PREFIX = "baton_tk_";
3220
+ var KEY_PREFIXES = [PUBLISHABLE_PREFIX, SECRET_PREFIX, TEST_PREFIX];
3221
+ var KEY_RUN = /baton_(?:(?:pk|sk|tk)_[A-Za-z0-9_%-]{8,}|[A-Za-z0-9_%-]{43,})/g;
2608
3222
  function looksLikeAKey(value) {
2609
- return value.startsWith(PUBLISHABLE_PREFIX) || value.startsWith(SECRET_PREFIX);
3223
+ return KEY_PREFIXES.some((prefix) => value.startsWith(prefix));
2610
3224
  }
2611
3225
  function containsKey(value) {
2612
3226
  return sweep(value) !== value;
@@ -2676,385 +3290,123 @@ function selectDsn(explicit, supplied, door) {
2676
3290
  );
2677
3291
  return void 0;
2678
3292
  }
2679
- return ambient;
2680
- }
2681
- function parseDsn(raw) {
2682
- const dsn = typeof raw === "string" ? stripWhiteSpace(raw) : "";
2683
- if (dsn === "") fail("dsn must be a non-empty string");
2684
- if (looksLikeAKey(dsn)) {
2685
- fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
2686
- }
2687
- const safe = redact(dsn);
2688
- const parts = splitDsn(dsn);
2689
- if (parts === null || parts.scheme !== "https" && parts.scheme !== "http") {
2690
- fail(
2691
- `dsn ${safe} must start with https:// (or http:// for local development) \u2014 ${BARE_KEY_HINT}`
2692
- );
2693
- }
2694
- const { key, at, authority } = splitKeyFromAuthority(parts.netloc);
2695
- if (!at || !key) {
2696
- if (looksLikeAKey(parts.netloc)) {
2697
- fail(
2698
- `dsn ${safe} is a bare key with a scheme in front of it: ${BARE_KEY_HINT}. The full value also carries a host, your workspace and your server \u2014 https://baton_pk_...@host/ten_.../server`
2699
- );
2700
- }
2701
- const misplaced = parts.path.split("/").some((segment) => containsKey(segment));
2702
- const detail = misplaced ? "the key is in the PATH \u2014 it goes before an @" : "the value from /account has the key before an @";
2703
- fail(
2704
- `dsn ${safe} carries no key: ${detail}, as in https://baton_pk_...@host/ten_.../server`
2705
- );
2706
- }
2707
- if (NOT_IN_A_KEY.test(key)) {
2708
- fail(
2709
- `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.`
2710
- );
2711
- }
2712
- if (key.includes(":")) {
2713
- fail(
2714
- `dsn ${safe} has a ':' in its key \u2014 a DSN carries one credential and no password field`
2715
- );
2716
- }
2717
- if (!authority) {
2718
- fail(`dsn ${safe} has no host`);
2719
- }
2720
- if (containsKey(authority)) {
2721
- fail(
2722
- `dsn ${safe} has the KEY where the host belongs. The order is key, @, host \u2014 check whether the two are the wrong way round: https://baton_pk_...@host/ten_.../<server>`
2723
- );
2724
- }
2725
- if (NOT_IN_A_HOST.test(authority)) {
2726
- fail(
2727
- `dsn ${safe} has whitespace, a control character or a backslash inside its host. Those are silently REMOVED or reinterpreted when a URL is parsed, so the address dialled would not be the one you wrote \u2014 check for a line wrap or a stray space where the value was copied.`
2728
- );
2729
- }
2730
- let hostReason = null;
2731
- let parsedAuthority = null;
2732
- try {
2733
- parsedAuthority = new URL(`${parts.scheme}://${authority}`);
2734
- } catch (error) {
2735
- hostReason = error instanceof Error ? error.constructor.name : "Error";
2736
- }
2737
- if (parsedAuthority === null) {
2738
- fail(`dsn ${safe} is not a parseable URL (${hostReason ?? "Error"})`);
2739
- }
2740
- const segments = parts.path.split("/").filter((segment) => segment !== "");
2741
- const [workspace, server, ...extra] = segments;
2742
- if (workspace === void 0 || server === void 0 || extra.length > 0) {
2743
- fail(
2744
- `dsn ${safe} must carry exactly two path segments \u2014 the workspace and the server, as in /ten_.../<server>. A missing server is never defaulted: it is what the key is bound to.`
2745
- );
2746
- }
2747
- for (const [slot, segment] of [
2748
- ["workspace", workspace],
2749
- ["server", server]
2750
- ]) {
2751
- if (containsKey(segment)) {
2752
- fail(
2753
- `dsn ${safe} has a KEY in the ${slot} slot. The key goes before the @, and the path carries the workspace and the server: https://baton_pk_...@host/ten_.../<server>`
2754
- );
2755
- }
2756
- }
2757
- if (!WORKSPACE_PATTERN.test(workspace)) {
2758
- fail(
2759
- `dsn ${safe} has ${JSON.stringify(workspace)} where the workspace belongs \u2014 expected ten_ followed by 8 or 32 hex characters. If the two path segments are the right way round, this is not a Baton DSN.`
2760
- );
2761
- }
2762
- if (!VENDOR_ID_PATTERN.test(server)) {
2763
- fail(
2764
- `dsn ${safe} has ${JSON.stringify(server)} where the server belongs \u2014 it must match ${VENDOR_ID_PATTERN.source}, because this value becomes the annotation tool name prefix as well as the envelope's vendor_id.`
2765
- );
2766
- }
2767
- if (key.startsWith(SECRET_PREFIX)) {
2768
- warn(
2769
- `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.`
2770
- );
2771
- }
2772
- return sealKey({
2773
- origin: `${parts.scheme}://${authority}`,
2774
- tenantId: workspace,
2775
- vendorId: server,
2776
- key
2777
- });
2778
- }
2779
- function sealKey(dsn) {
2780
- const shown = {
2781
- origin: dsn.origin,
2782
- tenantId: dsn.tenantId,
2783
- vendorId: dsn.vendorId,
2784
- key: "<key>"
2785
- };
2786
- Object.defineProperty(dsn, "toJSON", {
2787
- value: () => shown,
2788
- enumerable: false
2789
- });
2790
- Object.defineProperty(dsn, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
2791
- value: () => shown,
2792
- enumerable: false
2793
- });
2794
- return dsn;
2795
- }
2796
-
2797
- // src/integrations/mcp/errorResult.ts
2798
- var TOOL_ERROR_TYPE = "tool_error";
2799
- var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
2800
- var REFUSED = "refused";
2801
- var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
2802
- function requestSideFailureKind(entry, validation) {
2803
- if (entry == null) return "unknown_tool";
2804
- if (entry.enabled === false) return "tool_disabled";
2805
- if (validation === "rejected") return "invalid_argument";
2806
- if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
2807
- return REFUSED;
2808
- }
2809
- var ERROR_BODY_MAX_CODE_POINTS = 2e3;
2810
- function isErrorResult(value) {
2811
- try {
2812
- if (typeof value !== "object" || value === null) return false;
2813
- return Boolean(value.isError);
2814
- } catch {
2815
- return false;
2816
- }
2817
- }
2818
- function errorText(value) {
2819
- const parts = [];
2820
- try {
2821
- const content = value?.content;
2822
- if (!Array.isArray(content)) return "";
2823
- for (const part of content) {
2824
- const text = part?.text;
2825
- if (typeof text !== "string") continue;
2826
- const trimmed = stripWhiteSpace(text);
2827
- if (trimmed) parts.push(trimmed);
2828
- }
2829
- } catch {
2830
- return "";
2831
- }
2832
- return parts.join("\n");
2833
- }
2834
- var RESULT_CAPTURE_MODES = ["full", "off"];
2835
- var WITHHELD = "off";
2836
- function endResultFields(mode, result, scrubber) {
2837
- switch (mode) {
2838
- case WITHHELD:
2839
- return { result: null, result_capture: WITHHELD };
2840
- case "full":
2841
- return { result: scrubber(result) };
2842
- }
2843
- }
2844
- function returnedErrorFields(mode, result, errorBody2, scrubber) {
2845
- return resultDerivedFields(mode, () => errorText(result), result, errorBody2, scrubber);
2846
- }
2847
- function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
2848
- switch (mode) {
2849
- case WITHHELD:
2850
- return { error_body: "", result: null, result_capture: WITHHELD };
2851
- case "full":
2852
- return { error_body: errorBody2(text()), result: scrubber(result) };
2853
- }
2854
- }
2855
- function requestSideErrorFields(text, errorBody2) {
2856
- return { error_body: errorBody2(text), result: null };
2857
- }
2858
- function requestSideFailureFields(kind, mode, text, result, errorBody2, scrubber) {
2859
- return kind === REFUSED ? resultDerivedFields(mode, text, result ?? null, errorBody2, scrubber) : requestSideErrorFields(text(), errorBody2);
2860
- }
2861
- function errorTypeOf(err) {
2862
- return err instanceof Error ? err.constructor.name : "Error";
2863
- }
2864
- function messageOf(err) {
2865
- return err instanceof Error ? err.message : String(err);
2866
- }
2867
- function scrubbedErrorBody(scrubber, text) {
2868
- return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
2869
- }
2870
-
2871
- // src/integrations/mcp/captureSettings.ts
2872
- import { createHash } from "crypto";
2873
- var SETTINGS_PATH = "/v0/settings";
2874
- var TENANT_HEADER = "X-Baton-Tenant-Id";
2875
- var SETTINGS_MODES = ["local", "console"];
2876
- var DEFAULT_SETTINGS_REFRESH_MS = 6e4;
2877
- var MIN_SETTINGS_REFRESH_MS = 15e3;
2878
- var REQUEST_TIMEOUT_MS = 1e4;
2879
- var MATCH_KEYS = /* @__PURE__ */ new Set(["label", "client", "share"]);
2880
- var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
2881
- var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
2882
- var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
2883
- function shareBucket(vendorId2, key) {
2884
- const digest = createHash("sha256").update(`${vendorId2}
2885
- ${key}`, "utf-8").digest();
2886
- return Number(digest.readBigUInt64BE(0) % 10000n);
2887
- }
2888
- function matchesEveryone(audience) {
2889
- return audience.labels === null && audience.clients === null && audience.shareThreshold === null;
2890
- }
2891
- function matches(audience, caller, bucket) {
2892
- if (audience.labels !== null && !caller.labels.some((label) => audience.labels.has(label))) return false;
2893
- if (audience.clients !== null && (caller.clientName === null || !audience.clients.has(caller.clientName))) {
2894
- return false;
2895
- }
2896
- if (audience.shareThreshold !== null && (bucket === null || bucket >= audience.shareThreshold)) return false;
2897
- return true;
2898
- }
2899
- var SettingsDocument = class {
2900
- constructor(version, audiences) {
2901
- this.version = version;
2902
- this.audiences = audiences;
2903
- this.usesShare = audiences.some((a) => a.shareThreshold !== null);
2904
- this.unmatched = { capture: { settings_version: version } };
2905
- this.reportsOnForAnyone = audiences.some((a) => a.settings.reportMode !== "off") || !audiences.some(matchesEveryone);
2906
- }
2907
- version;
2908
- audiences;
2909
- usesShare;
2910
- unmatched;
2911
- /** Whether some caller can get reports, so the instructions point to the
2912
- * tool. Read only where the code's value is "on": no tool exists otherwise. */
2913
- reportsOnForAnyone;
2914
- settingsFor(caller, vendorId2) {
2915
- const bucket = caller.shareKey !== null && this.usesShare ? shareBucket(vendorId2, caller.shareKey) : null;
2916
- return this.audiences.find((audience) => matches(audience, caller, bucket))?.settings ?? this.unmatched;
2917
- }
2918
- };
2919
- function stringSet(value) {
2920
- if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) return null;
2921
- return new Set(value);
2922
- }
2923
- function readAudience(version, id, match, capture) {
2924
- if (!Object.keys(match).every((key) => MATCH_KEYS.has(key))) return null;
2925
- let labels = null;
2926
- let clients = null;
2927
- let shareThreshold = null;
2928
- if (Object.hasOwn(match, "label") && (labels = stringSet(match.label)) === null) return null;
2929
- if (Object.hasOwn(match, "client") && (clients = stringSet(match.client)) === null) return null;
2930
- if (Object.hasOwn(match, "share")) {
2931
- const share = match.share;
2932
- if (typeof share !== "number" || !(share > 0 && share <= 1)) return null;
2933
- shareThreshold = Math.floor(share * 1e4 + 0.5);
2934
- }
2935
- const settings = { capture: { settings_version: version, audience: id } };
2936
- const { results, goal, reports } = capture;
2937
- if (typeof results === "string" && RESULT_CAPTURE_MODE_SET.has(results)) {
2938
- settings.resultCaptureMode = results;
2939
- }
2940
- if (typeof goal === "string" && INTENT_PARAM_MODES.has(goal)) settings.intentParamMode = goal;
2941
- if (typeof reports === "string" && REPORT_MODES.has(reports)) settings.reportMode = reports;
2942
- return { settings, labels, clients, shareThreshold };
3293
+ return ambient;
2943
3294
  }
2944
- function parseDocument(body) {
2945
- let data;
2946
- try {
2947
- data = JSON.parse(body);
2948
- } catch {
2949
- return null;
3295
+ function parseDsn(raw) {
3296
+ const dsn = typeof raw === "string" ? stripWhiteSpace(raw) : "";
3297
+ if (dsn === "") fail("dsn must be a non-empty string");
3298
+ if (looksLikeAKey(dsn)) {
3299
+ fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
2950
3300
  }
2951
- if (!isRecord(data)) return null;
2952
- const { version, audiences } = data;
2953
- if (typeof version !== "number" || !Number.isInteger(version) || version < 1) return null;
2954
- if (!Array.isArray(audiences) || audiences.length === 0) return null;
2955
- const parsed = [];
2956
- for (const audience of audiences) {
2957
- if (!isRecord(audience)) return null;
2958
- const { id, match, capture } = audience;
2959
- if (typeof id !== "string" || !isRecord(match) || !isRecord(capture)) return null;
2960
- const readable = readAudience(version, id, match, capture);
2961
- if (readable !== null) parsed.push(readable);
3301
+ const safe = redact(dsn);
3302
+ const parts = splitDsn(dsn);
3303
+ if (parts === null || parts.scheme !== "https" && parts.scheme !== "http") {
3304
+ fail(
3305
+ `dsn ${safe} must start with https:// (or http:// for local development) \u2014 ${BARE_KEY_HINT}`
3306
+ );
2962
3307
  }
2963
- return new SettingsDocument(version, parsed);
2964
- }
2965
- var SettingsFetcher = class {
2966
- url;
2967
- // `#`, not `private`, so logging a config shows no key: "logging the config shows no key".
2968
- #headers;
2969
- refreshMs;
2970
- fetchImpl;
2971
- etag = null;
2972
- held = null;
2973
- timer = null;
2974
- reading = null;
2975
- warned = false;
2976
- constructor(options) {
2977
- this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
2978
- this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
2979
- this.refreshMs = options.refreshMs;
2980
- this.fetchImpl = options.fetchImpl ?? globalFetch;
3308
+ const { key, at, authority } = splitKeyFromAuthority(parts.netloc);
3309
+ if (!at || !key) {
3310
+ if (looksLikeAKey(parts.netloc)) {
3311
+ fail(
3312
+ `dsn ${safe} is a bare key with a scheme in front of it: ${BARE_KEY_HINT}. The full value also carries a host, your workspace and your server \u2014 https://baton_pk_...@host/ten_.../server`
3313
+ );
3314
+ }
3315
+ const misplaced = parts.path.split("/").some((segment) => containsKey(segment));
3316
+ const detail = misplaced ? "the key is in the PATH \u2014 it goes before an @" : "the value from /account has the key before an @";
3317
+ fail(
3318
+ `dsn ${safe} carries no key: ${detail}, as in https://baton_pk_...@host/ten_.../server`
3319
+ );
2981
3320
  }
2982
- get document() {
2983
- return this.held;
3321
+ if (NOT_IN_A_KEY.test(key)) {
3322
+ fail(
3323
+ `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.`
3324
+ );
2984
3325
  }
2985
- start() {
2986
- if (this.timer !== null) return;
2987
- this.timer = setInterval(() => void this.readOnce(), this.refreshMs);
2988
- this.timer.unref?.();
2989
- void this.readOnce();
3326
+ if (key.includes(":")) {
3327
+ fail(
3328
+ `dsn ${safe} has a ':' in its key \u2014 a DSN carries one credential and no password field`
3329
+ );
2990
3330
  }
2991
- stop() {
2992
- if (this.timer !== null) clearInterval(this.timer);
2993
- this.timer = null;
2994
- this.reading?.abort();
2995
- this.reading = null;
3331
+ if (!authority) {
3332
+ fail(`dsn ${safe} has no host`);
2996
3333
  }
2997
- /** One request. Never rejects: a failure keeps what is held. */
2998
- async readOnce() {
2999
- if (this.reading !== null) return;
3000
- const reading = new AbortController();
3001
- this.reading = reading;
3002
- const timeout = setTimeout(() => reading.abort(), REQUEST_TIMEOUT_MS);
3003
- timeout.unref?.();
3004
- try {
3005
- await this.read(reading.signal);
3006
- } catch {
3007
- } finally {
3008
- clearTimeout(timeout);
3009
- if (this.reading === reading) this.reading = null;
3010
- }
3334
+ if (containsKey(authority)) {
3335
+ fail(
3336
+ `dsn ${safe} has the KEY where the host belongs. The order is key, @, host \u2014 check whether the two are the wrong way round: https://baton_pk_...@host/ten_.../<server>`
3337
+ );
3011
3338
  }
3012
- async read(signal) {
3013
- const headers = this.etag === null ? this.#headers : { ...this.#headers, "If-None-Match": this.etag };
3014
- const response = await this.fetchImpl(this.url, { method: "GET", headers, redirect: "manual", signal });
3015
- if (response.status !== 200) {
3016
- void response.body?.cancel().catch(() => void 0);
3017
- }
3018
- if (signal.aborted) return;
3019
- if (response.status === 204) {
3020
- this.held = null;
3021
- this.etag = null;
3022
- } else if (response.status === 200) {
3023
- const document = parseDocument(await response.text());
3024
- if (signal.aborted) return;
3025
- if (document === null) {
3026
- if (!this.warned) {
3027
- this.warned = true;
3028
- warn("baton: the collector sent capture settings this SDK cannot read");
3029
- }
3030
- return;
3031
- }
3032
- this.held = document;
3033
- this.etag = response.headers.get("etag");
3034
- }
3339
+ if (NOT_IN_A_HOST.test(authority)) {
3340
+ fail(
3341
+ `dsn ${safe} has whitespace, a control character or a backslash inside its host. Those are silently REMOVED or reinterpreted when a URL is parsed, so the address dialled would not be the one you wrote \u2014 check for a line wrap or a stray space where the value was copied.`
3342
+ );
3035
3343
  }
3036
- };
3037
- var CaptureSettings = class {
3038
- constructor(vendorId2, source) {
3039
- this.vendorId = vendorId2;
3040
- this.source = source;
3344
+ let hostReason = null;
3345
+ let parsedAuthority = null;
3346
+ try {
3347
+ parsedAuthority = new URL(`${parts.scheme}://${authority}`);
3348
+ } catch (error) {
3349
+ hostReason = error instanceof Error ? error.constructor.name : "Error";
3041
3350
  }
3042
- vendorId;
3043
- source;
3044
- start() {
3045
- this.source.start();
3351
+ if (parsedAuthority === null) {
3352
+ fail(`dsn ${safe} is not a parseable URL (${hostReason ?? "Error"})`);
3046
3353
  }
3047
- stop() {
3048
- this.source.stop();
3354
+ const segments = parts.path.split("/").filter((segment) => segment !== "");
3355
+ const [workspace, server, ...extra] = segments;
3356
+ if (workspace === void 0 || server === void 0 || extra.length > 0) {
3357
+ fail(
3358
+ `dsn ${safe} must carry exactly two path segments \u2014 the workspace and the server, as in /ten_.../<server>. A missing server is never defaulted: it is what the key is bound to.`
3359
+ );
3049
3360
  }
3050
- get document() {
3051
- return this.source.document;
3361
+ for (const [slot, segment] of [
3362
+ ["workspace", workspace],
3363
+ ["server", server]
3364
+ ]) {
3365
+ if (containsKey(segment)) {
3366
+ fail(
3367
+ `dsn ${safe} has a KEY in the ${slot} slot. The key goes before the @, and the path carries the workspace and the server: https://baton_pk_...@host/ten_.../<server>`
3368
+ );
3369
+ }
3052
3370
  }
3053
- /** `undefined` while no document is held, and the config's values apply. */
3054
- forCaller(caller) {
3055
- return this.document?.settingsFor(caller, this.vendorId);
3371
+ if (!WORKSPACE_PATTERN.test(workspace)) {
3372
+ fail(
3373
+ `dsn ${safe} has ${JSON.stringify(workspace)} where the workspace belongs \u2014 expected ten_ followed by 8 or 32 hex characters. If the two path segments are the right way round, this is not a Baton DSN.`
3374
+ );
3056
3375
  }
3057
- };
3376
+ if (!VENDOR_ID_PATTERN.test(server)) {
3377
+ fail(
3378
+ `dsn ${safe} has ${JSON.stringify(server)} where the server belongs \u2014 it must match ${VENDOR_ID_PATTERN.source}, because this value becomes the annotation tool name prefix as well as the envelope's vendor_id.`
3379
+ );
3380
+ }
3381
+ if (key.startsWith(SECRET_PREFIX)) {
3382
+ warn(
3383
+ `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.`
3384
+ );
3385
+ }
3386
+ return sealKey({
3387
+ origin: `${parts.scheme}://${authority}`,
3388
+ tenantId: workspace,
3389
+ vendorId: server,
3390
+ key
3391
+ });
3392
+ }
3393
+ function sealKey(dsn) {
3394
+ const shown = {
3395
+ origin: dsn.origin,
3396
+ tenantId: dsn.tenantId,
3397
+ vendorId: dsn.vendorId,
3398
+ key: "<key>"
3399
+ };
3400
+ Object.defineProperty(dsn, "toJSON", {
3401
+ value: () => shown,
3402
+ enumerable: false
3403
+ });
3404
+ Object.defineProperty(dsn, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
3405
+ value: () => shown,
3406
+ enumerable: false
3407
+ });
3408
+ return dsn;
3409
+ }
3058
3410
 
3059
3411
  // src/integrations/mcp/config.ts
3060
3412
  function resolveTenantId(explicit, vendorId2) {
@@ -3150,7 +3502,8 @@ function resolveBatonConfig(supplied) {
3150
3502
  tenantId: dsn.tenantId,
3151
3503
  vendorId: dsn.vendorId,
3152
3504
  refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
3153
- })
3505
+ }),
3506
+ envCandidate()
3154
3507
  )
3155
3508
  } : {}
3156
3509
  };
@@ -3323,53 +3676,148 @@ var BatonHandle = class {
3323
3676
  };
3324
3677
 
3325
3678
  // src/integrations/mcp/perCaller.ts
3679
+ var UNREAD = /* @__PURE__ */ Symbol("unread");
3326
3680
  var PerCallerSurface = class {
3327
3681
  constructor(options) {
3328
3682
  this.options = options;
3329
3683
  }
3330
3684
  options;
3331
- pointerOn = true;
3685
+ document = UNREAD;
3686
+ served = null;
3687
+ serverOverlay;
3332
3688
  /** Called at install and on every request; writes only when the report
3333
- * pointer should change. */
3689
+ * pointer or the server overlay should change. */
3334
3690
  followSettings() {
3335
- if (this.options.annotationToolName === "") return;
3336
3691
  try {
3337
3692
  const document = this.options.settings.document;
3338
- const pointerOn = document === null || document.reportsOnForAnyone;
3339
- if (pointerOn === this.pointerOn) return;
3340
- this.options.writeInstructions(pointerOn ? this.options.instructions : INTENT_INSTRUCTIONS);
3341
- this.pointerOn = pointerOn;
3693
+ if (document === this.document) return;
3694
+ const overlay = document?.serverOverlay;
3695
+ const pointer = this.options.pointer();
3696
+ const pointerOn = pointer !== void 0 && (document === null || document.reportsOnForAnyone);
3697
+ const served = JSON.stringify([pointerOn, overlay?.id ?? null]);
3698
+ if (served !== this.served) {
3699
+ const { ours, subagent } = batonParagraphs(pointerOn ? pointer : void 0, overlay, this.options.subagentLine());
3700
+ this.options.writeInstructions(ours, subagent);
3701
+ this.served = served;
3702
+ this.serverOverlay = overlay;
3703
+ }
3704
+ this.document = document;
3342
3705
  } catch (err) {
3343
- process.stderr.write(`baton: could not update the server instructions for new settings: ${printable(err)}
3344
- `);
3706
+ stderrLine(`baton: could not update the server instructions for new settings: ${printable(err)}`);
3345
3707
  }
3346
3708
  }
3347
- /** `result` with the caller's goal and reports settings; as served on any failure. */
3709
+ /** `followSettings` after the report pointer changed outside the settings. */
3710
+ refresh() {
3711
+ this.document = UNREAD;
3712
+ this.served = null;
3713
+ this.followSettings();
3714
+ }
3715
+ /** `result` with the caller's goal, reports and overlay; as served on any failure. */
3348
3716
  toolsFor(result, caller) {
3349
3717
  const settings = caller.settings;
3350
3718
  if (settings === void 0) return result;
3351
3719
  const { intentParamMode, annotationToolName, injectsGoal } = this.options;
3352
3720
  const goal = settings.intentParamMode ?? intentParamMode;
3353
3721
  const hideReports = annotationToolName !== "" && settings.reportMode === "off";
3354
- if (goal === intentParamMode && !hideReports) return result;
3722
+ const overlay = settings.overlay;
3723
+ if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
3355
3724
  try {
3356
3725
  const tools = result?.tools;
3357
3726
  if (!Array.isArray(tools)) return result;
3358
3727
  const served = [];
3728
+ const injected = [];
3359
3729
  for (const tool of tools) {
3360
3730
  const name = tool?.name;
3361
3731
  if (hideReports && name === annotationToolName) continue;
3362
- const rewrite = goal !== intentParamMode && typeof name === "string" && injectsGoal(name);
3363
- served.push(rewrite ? withGoalMode(tool, goal) : tool);
3732
+ const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
3733
+ served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
3734
+ injected.push(ours);
3364
3735
  }
3365
- return { ...result, tools: served };
3736
+ const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
3737
+ return { ...result, tools: rewritten };
3366
3738
  } catch (err) {
3367
- process.stderr.write(`baton: could not apply capture settings to the tool list: ${printable(err)}
3368
- `);
3739
+ stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
3369
3740
  return result;
3370
3741
  }
3371
3742
  }
3372
3743
  };
3744
+ function batonParagraphs(pointer, overlay, subagentLine) {
3745
+ const parts = overlay?.instructionAppends() ?? [];
3746
+ if (pointer !== void 0) parts.push(overlaid(pointer, overlay, "instructions.report_pointer"));
3747
+ if (subagentLine) parts.push(overlaid(INTENT_INSTRUCTIONS, overlay, "instructions.subagent"));
3748
+ const kept = parts.map(stripWhiteSpaceEnd);
3749
+ return { ours: kept.filter((part) => part).join("\n\n"), subagent: subagentLine && kept.at(-1) || null };
3750
+ }
3751
+ function withOverlay(tools, injected, overlay, reportTool2) {
3752
+ const position = /* @__PURE__ */ new Map();
3753
+ tools.forEach((tool, i) => position.set(tool?.name, i));
3754
+ const hidden = /* @__PURE__ */ new Set();
3755
+ for (const action of overlay.actions) {
3756
+ if (action.tool === void 0) continue;
3757
+ const i = position.get(action.tool);
3758
+ if (i === void 0) {
3759
+ warnSkipped(overlay.id, action.index, `no tool is named ${JSON.stringify(action.tool)}`);
3760
+ } else if (action.tool === reportTool2) {
3761
+ warnSkipped(overlay.id, action.index, "the report tool takes agent_text targets only");
3762
+ } else if (action.param === void 0 && action.change === "remove") {
3763
+ hidden.add(i);
3764
+ } else if (action.param === void 0) {
3765
+ tools[i] = withDescription(tools[i], [action]);
3766
+ } else {
3767
+ const reason = paramChange(tools, i, action, injected[i]);
3768
+ if (reason !== void 0) warnSkipped(overlay.id, action.index, reason);
3769
+ }
3770
+ }
3771
+ const goalActions = overlay.pieceActions("goal_param.description");
3772
+ if (goalActions.length > 0) {
3773
+ injected.forEach((ours, i) => {
3774
+ if (ours) describeParam(tools, i, USER_GOAL_PARAM_NAME, goalActions);
3775
+ });
3776
+ }
3777
+ const reportActions = overlay.pieceActions("report_tool.description");
3778
+ const reportAt = reportTool2 === void 0 ? void 0 : position.get(reportTool2);
3779
+ if (reportActions.length > 0 && reportAt !== void 0) {
3780
+ tools[reportAt] = withDescription(tools[reportAt], reportActions);
3781
+ }
3782
+ return tools.filter((_, i) => !hidden.has(i));
3783
+ }
3784
+ function withDescription(tool, actions) {
3785
+ const description = typeof tool.description === "string" ? tool.description : void 0;
3786
+ return { ...tool, description: changedText(description, actions).text };
3787
+ }
3788
+ function paramChange(tools, i, action, injected) {
3789
+ const param = action.param;
3790
+ const tool = tools[i];
3791
+ const schema = tool.inputSchema;
3792
+ const properties = isRecord(schema) && isRecord(schema.properties) ? schema.properties : void 0;
3793
+ if (properties === void 0 || !Object.hasOwn(properties, param)) {
3794
+ return `${JSON.stringify(action.tool)} has no param ${JSON.stringify(param)}`;
3795
+ }
3796
+ if (injected && param === USER_GOAL_PARAM_NAME) return "Baton's user_goal takes the goal_param.description target";
3797
+ const required = Array.isArray(schema.required) ? schema.required : [];
3798
+ if (action.change === "remove") {
3799
+ if (required.includes(param)) return `${JSON.stringify(action.tool)} requires ${JSON.stringify(param)}`;
3800
+ const kept = Object.fromEntries(Object.entries(properties).filter(([name]) => name !== param));
3801
+ tools[i] = { ...tool, inputSchema: { ...schema, properties: kept } };
3802
+ } else if (action.change === "required") {
3803
+ if (!required.includes(param)) tools[i] = { ...tool, inputSchema: { ...schema, required: [...required, param] } };
3804
+ } else {
3805
+ describeParam(tools, i, param, [action]);
3806
+ }
3807
+ return void 0;
3808
+ }
3809
+ function describeParam(tools, i, param, actions) {
3810
+ const tool = tools[i];
3811
+ const schema = tool.inputSchema;
3812
+ const properties = schema.properties;
3813
+ const described = isRecord(properties[param]) ? properties[param] : {};
3814
+ const current2 = typeof described.description === "string" ? described.description : void 0;
3815
+ const description = changedText(current2, actions).text;
3816
+ tools[i] = {
3817
+ ...tool,
3818
+ inputSchema: { ...schema, properties: { ...properties, [param]: { ...described, description } } }
3819
+ };
3820
+ }
3373
3821
  function withGoalMode(tool, goal) {
3374
3822
  const entry = tool;
3375
3823
  const schema = entry.inputSchema;
@@ -3424,10 +3872,10 @@ var ServerCounter = class extends SessionCounter {
3424
3872
  };
3425
3873
 
3426
3874
  // src/integrations/mcp/surface.ts
3427
- import { createHash as createHash2 } from "crypto";
3875
+ import * as crypto3 from "crypto";
3428
3876
  function surfaceHash(surface) {
3429
3877
  const canonical = canonicalJson(surface);
3430
- const digest = createHash2("sha256").update(canonical, "utf-8").digest("hex");
3878
+ const digest = crypto3.createHash("sha256").update(canonical, "utf-8").digest("hex");
3431
3879
  return `sha256:${digest}`;
3432
3880
  }
3433
3881
  function canonicalJson(value) {
@@ -3459,13 +3907,20 @@ function assembleSurface(serverMeta, tools) {
3459
3907
  var SENT_SURFACES_CAP = 256;
3460
3908
  var SentSurfaces = class {
3461
3909
  hashes = /* @__PURE__ */ new Set();
3462
- wasSent(digest) {
3463
- if (!this.hashes.has(digest)) return false;
3910
+ serverOverlay = null;
3911
+ /** `serverOverlay` is not in `surface_hash`, and a snapshot is sent again
3912
+ * whenever it changes (SPEC §11.4.2). */
3913
+ wasSent(digest, serverOverlay = null) {
3914
+ if (serverOverlay !== this.serverOverlay || !this.hashes.has(digest)) return false;
3464
3915
  this.hashes.delete(digest);
3465
3916
  this.hashes.add(digest);
3466
3917
  return true;
3467
3918
  }
3468
- mark(digest) {
3919
+ mark(digest, serverOverlay = null) {
3920
+ if (serverOverlay !== this.serverOverlay) {
3921
+ this.hashes.clear();
3922
+ this.serverOverlay = serverOverlay;
3923
+ }
3469
3924
  this.hashes.add(digest);
3470
3925
  if (this.hashes.size > SENT_SURFACES_CAP) {
3471
3926
  this.hashes.delete(this.hashes.values().next().value);
@@ -3489,7 +3944,7 @@ var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
3489
3944
  var wired = /* @__PURE__ */ new WeakSet();
3490
3945
  var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
3491
3946
  var INTENT_PARAM_NAMES = [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES];
3492
- var callSlots = new AsyncLocalStorage();
3947
+ var callSlots = new asyncHooks.AsyncLocalStorage();
3493
3948
  var SurfaceState = class {
3494
3949
  constructor(serverMeta, sentSurfaces) {
3495
3950
  this.serverMeta = serverMeta;
@@ -3503,6 +3958,7 @@ var SurfaceState = class {
3503
3958
  * injected schema as if it were vendor-true. */
3504
3959
  rawTools = /* @__PURE__ */ new Map();
3505
3960
  dirty = false;
3961
+ servedOverlayId = null;
3506
3962
  /** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
3507
3963
  * which picks the spelling THIS SDK major puts on the wire. */
3508
3964
  noteTool(name, inputSchemaJson, description) {
@@ -3554,7 +4010,7 @@ async function resolveEnvelopeParts(ctx, extra) {
3554
4010
  const session = await resolveSessionId(ctx.fallbackSessionId, extra);
3555
4011
  return { ...session, scrubbedMeta };
3556
4012
  }
3557
- async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn") {
4013
+ async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn", resolved) {
3558
4014
  await maybeEmitSurfaceSnapshot(ctx);
3559
4015
  const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
3560
4016
  const dispositions = ctx.paramRegistry.get(toolName);
@@ -3564,12 +4020,7 @@ async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn
3564
4020
  (name) => dispositions === void 0 || dispositions[name] === "native" || unlisted === "leave" || unlisted === "goalOnly" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
3565
4021
  );
3566
4022
  const client = observeClient(extra, ctx);
3567
- const caller = await resolveCaller(
3568
- ctx.resolvePrincipal,
3569
- { extra, toolName, arguments: params },
3570
- ctx.captureSettings,
3571
- client
3572
- );
4023
+ const caller = resolved ?? await resolveCaller(ctx.resolvePrincipal, { extra, toolName, arguments: params }, ctx.captureSettings, client);
3573
4024
  const resultCaptureMode = caller.settings?.resultCaptureMode ?? ctx.configResultCaptureMode;
3574
4025
  const common = {
3575
4026
  tenant_id: ctx.tenantId,
@@ -3607,16 +4058,24 @@ async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn
3607
4058
  );
3608
4059
  return { common, session, resultCaptureMode };
3609
4060
  }
3610
- function batonWrap(nameRef, original, ctx, unlisted = "warn") {
4061
+ function batonWrap(nameRef, original, ctx, unlisted = "warn", resolved) {
3611
4062
  return async (...callArgs) => {
3612
4063
  const toolName = nameRef.current;
3613
4064
  const slot = callSlots.getStore();
3614
4065
  if (slot) slot.innerFired = true;
3615
4066
  const extra = callArgs[callArgs.length - 1];
3616
4067
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
3617
- const stripped = slot?.strippedFor === toolName ? slot.stripped : {};
4068
+ const ours = slot?.strippedFor === toolName ? slot : void 0;
3618
4069
  if (slot) slot.strippedFor = null;
3619
- const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped, unlisted);
4070
+ const { common, session, resultCaptureMode } = await openCall(
4071
+ ctx,
4072
+ toolName,
4073
+ extra,
4074
+ params,
4075
+ ours?.stripped ?? {},
4076
+ unlisted,
4077
+ ours?.caller ?? resolved
4078
+ );
3620
4079
  const terminate = async (build, replacement) => {
3621
4080
  if (!slot) {
3622
4081
  if (build !== null) await emit(ctx.sink, build);
@@ -3780,9 +4239,8 @@ function extractGoalParam(args, paramName, toolName, dispositions, unlisted) {
3780
4239
  if (disposition === "native") return null;
3781
4240
  if (disposition === void 0 && unlisted === "leave") return null;
3782
4241
  if (disposition === void 0 && unlisted === "warn") {
3783
- process.stderr.write(
3784
- `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
3785
- `
4242
+ stderrLine(
4243
+ `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)`
3786
4244
  );
3787
4245
  }
3788
4246
  return popText(args, paramName);
@@ -3808,6 +4266,11 @@ function stripIntentParams(params, ctx) {
3808
4266
  return stripped;
3809
4267
  }
3810
4268
  async function maybeEmitSurfaceSnapshot(ctx) {
4269
+ const overlayId = ctx.perCaller?.serverOverlay?.id ?? null;
4270
+ if (overlayId !== ctx.surfaceState.servedOverlayId) {
4271
+ ctx.surfaceState.servedOverlayId = overlayId;
4272
+ ctx.surfaceState.dirty = true;
4273
+ }
3811
4274
  if (!ctx.surfaceState.dirty) return;
3812
4275
  ctx.surfaceState.dirty = false;
3813
4276
  let snapshot;
@@ -3816,13 +4279,12 @@ async function maybeEmitSurfaceSnapshot(ctx) {
3816
4279
  snapshot = ctx.surfaceState.buildSnapshot();
3817
4280
  digest = surfaceHash(snapshot);
3818
4281
  } catch (err) {
3819
- process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
3820
- `);
4282
+ stderrLine(`baton: surface snapshot capture failed: ${String(err)}`);
3821
4283
  return;
3822
4284
  }
3823
4285
  const sent = ctx.surfaceState.sentSurfaces;
3824
- if (sent.wasSent(digest)) return;
3825
- sent.mark(digest);
4286
+ if (sent.wasSent(digest, overlayId)) return;
4287
+ sent.mark(digest, overlayId);
3826
4288
  const seam = buildSeamAugmentations({
3827
4289
  injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
3828
4290
  intentParamNames: [USER_GOAL_PARAM_NAME],
@@ -3830,6 +4292,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
3830
4292
  requiredParamNames: requiredParamNames(ctx.intentParamMode),
3831
4293
  instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions())
3832
4294
  });
4295
+ if (ctx.captureSettings !== void 0) seam.server_overlay = overlayId;
3833
4296
  await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
3834
4297
  }
3835
4298
  function declaredIntentParams(vendorSchema) {
@@ -3885,16 +4348,16 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
3885
4348
  return registered;
3886
4349
  };
3887
4350
  }
3888
- function installToolsListSeam(lowLevel, ctx) {
4351
+ function installToolsListSeam(lowLevel, ctx, listsOwnReportTool) {
3889
4352
  const names = [...requiredParamNames(ctx.intentParamMode), TOOL_NAME_PARAM_NAME];
3890
4353
  const isInjected = (toolName, paramName) => toolName === ctx.annotationToolName ? paramName === TOOL_NAME_PARAM_NAME : ctx.paramRegistry.get(toolName)?.[paramName] === "injected";
3891
4354
  const advertise = (result) => {
3892
4355
  try {
3893
- return advertiseIntentParamsRequired(result, names, isInjected);
4356
+ const served = listsOwnReportTool || ctx.annotationToolName === "" ? result : withToolInputSchema(result, ctx.annotationToolName, annotationInputJsonSchema(lowLevelMajor(lowLevel)));
4357
+ return advertiseIntentParamsRequired(served, names, isInjected);
3894
4358
  } catch (err) {
3895
- process.stderr.write(
3896
- `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}
3897
- `
4359
+ stderrLine(
4360
+ `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}`
3898
4361
  );
3899
4362
  return result;
3900
4363
  }
@@ -3907,6 +4370,7 @@ function installToolsListSeam(lowLevel, ctx) {
3907
4370
  var LOW_LEVEL_LIST_SEAM = /* @__PURE__ */ Symbol("batonLowLevelListSeam");
3908
4371
  var LOW_LEVEL_CALL_SEAM = /* @__PURE__ */ Symbol("batonLowLevelCallSeam");
3909
4372
  var LOW_LEVEL_HANDSHAKE_SEAM = /* @__PURE__ */ Symbol("batonLowLevelHandshakeSeam");
4373
+ var SETTINGS_SEAM = /* @__PURE__ */ Symbol("batonSettingsSeam");
3910
4374
  function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce2, reportToolTaken) {
3911
4375
  let reportTool2 = annotationTool;
3912
4376
  const listedReportTool = reportTool2 && {
@@ -3918,14 +4382,12 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
3918
4382
  known.unread.add(name);
3919
4383
  warnOnce2(
3920
4384
  `tool-unread:${name}`,
3921
- `baton: could not read tool ${JSON.stringify(name)}; its calls keep user_goal until Baton can read it: ${printable(err)}
3922
- `
4385
+ `baton: could not read tool ${JSON.stringify(name)}; its calls keep user_goal until Baton can read it: ${printable(err)}`
3923
4386
  );
3924
4387
  };
3925
4388
  const skipNote = (name, err) => {
3926
4389
  if (known.unread.has(name)) return;
3927
- warnOnce2(`tool-unnoted:${name}`, `baton: could not note tool ${JSON.stringify(name)}; Baton adds no user_goal to it: ${printable(err)}
3928
- `);
4390
+ warnOnce2(`tool-unnoted:${name}`, `baton: could not note tool ${JSON.stringify(name)}; Baton adds no user_goal to it: ${printable(err)}`);
3929
4391
  };
3930
4392
  const keepGoalIfDeclared = (tools) => {
3931
4393
  for (const { name, inputSchema: inputSchema2 } of tools) {
@@ -3945,8 +4407,7 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
3945
4407
  if (surface && reportTool2 !== void 0 && tools.some((tool) => tool.name === reportTool2?.name)) {
3946
4408
  warnOnce2(
3947
4409
  "report-tool-name-taken",
3948
- `baton: the server lists its own tool ${JSON.stringify(reportTool2.name)}, so Baton's report tool is not added; set annotationToolName to another name
3949
- `
4410
+ `baton: the server lists its own tool ${JSON.stringify(reportTool2.name)}, so Baton's report tool is not added; set annotationToolName to another name`
3950
4411
  );
3951
4412
  reportTool2 = void 0;
3952
4413
  ctx.annotationToolName = "";
@@ -3977,8 +4438,7 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
3977
4438
  } catch (err) {
3978
4439
  warnOnce2(
3979
4440
  "tools-unread",
3980
- `baton: could not read the tools option; Baton learns the tools from tools/list: ${printable(err)}
3981
- `
4441
+ `baton: could not read the tools option; Baton learns the tools from tools/list: ${printable(err)}`
3982
4442
  );
3983
4443
  }
3984
4444
  }
@@ -3997,8 +4457,7 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
3997
4457
  const firstPage = args[0]?.params?.cursor === void 0;
3998
4458
  return servedToolList(result, listed, ctx, firstPage && reportTool2 ? listedReportTool : void 0);
3999
4459
  } catch (err) {
4000
- process.stderr.write(`baton: tools/list capture failed; serving the vendor's own result: ${printable(err)}
4001
- `);
4460
+ stderrLine(`baton: tools/list capture failed; serving the vendor's own result: ${printable(err)}`);
4002
4461
  return result;
4003
4462
  }
4004
4463
  });
@@ -4010,28 +4469,36 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
4010
4469
  installRequestSeam(lowLevel, "server/discover", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);
4011
4470
  installRequestSeam(lowLevel, TOOLS_CALL_METHOD, LOW_LEVEL_CALL_SEAM, (handler) => async (...args) => {
4012
4471
  catchUp();
4013
- ctx.perCaller?.followSettings();
4014
4472
  const request = args[0];
4015
4473
  const name = request?.params?.name;
4016
4474
  if (typeof name !== "string") return handler(...args);
4017
4475
  if (name === reportTool2?.name) return callAnnotationTool(reportTool2, request?.params?.arguments, args[1]);
4018
4476
  const injected = ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected";
4019
4477
  const unlisted = injected ? "warn" : known.keepsGoal.has(name) || known.unread.has(name) ? "leave" : "goalOnly";
4478
+ const strip = (args2) => injected ? stripIntentParams({ name, arguments: args2 }, ctx) : { [USER_GOAL_PARAM_NAME]: extractGoalParam(args2, USER_GOAL_PARAM_NAME, name, ctx.paramRegistry.get(name), unlisted) };
4479
+ let slot;
4480
+ if (mayHide(ctx.captureSettings, name)) {
4481
+ const hookArgs = isRecord(request?.params?.arguments) ? { ...request.params.arguments } : {};
4482
+ const checked = { innerFired: false, flushTerminal: null, stripped: strip(hookArgs), strippedFor: name, validation: "unseen", unlisted };
4483
+ if (await hiddenFrom(checked, name, hookArgs, args[1], ctx)) {
4484
+ if (request?.params !== void 0 && isRecord(request.params.arguments)) request.params.arguments = hookArgs;
4485
+ return answerHidden(lowLevel, name, (outcome) => settleCall(checked, outcome, args, () => void 0, ctx, "tool_hidden"));
4486
+ }
4487
+ slot = checked;
4488
+ }
4020
4489
  const params = request?.params?.arguments;
4021
4490
  const toolArgs = isRecord(params) ? params : {};
4022
4491
  if (unlisted === "goalOnly" && USER_GOAL_PARAM_NAME in toolArgs && !known.served.has(name) && !known.givenTools.some((tool) => tool.name === name)) {
4023
4492
  warnOnce2(
4024
4493
  "user-goal-unlisted",
4025
- `baton: ${JSON.stringify(name)} is not in any tool list this process has read, so Baton took user_goal off it without knowing whether the tool declares its own; pass your tools as the tools option
4026
- `
4494
+ `baton: ${JSON.stringify(name)} is not in any tool list this process has read, so Baton took user_goal off it without knowing whether the tool declares its own; pass your tools as the tools option`
4027
4495
  );
4028
4496
  }
4029
4497
  if (request?.params?.task !== void 0) {
4030
- if (injected) stripIntentParams(request.params, ctx);
4031
- else extractGoalParam(toolArgs, USER_GOAL_PARAM_NAME, name, ctx.paramRegistry.get(name), unlisted);
4498
+ strip(toolArgs);
4032
4499
  return handler(...args);
4033
4500
  }
4034
- return batonWrap({ current: name }, () => handler(...args), ctx, unlisted)(toolArgs, args[1]);
4501
+ return batonWrap({ current: name }, () => handler(...args), ctx, unlisted, slot?.caller)(toolArgs, args[1]);
4035
4502
  });
4036
4503
  }
4037
4504
  function lowLevelMajor(lowLevel) {
@@ -4159,8 +4626,7 @@ async function openLifecycleCall(ctx, spec, requestParams, extra) {
4159
4626
  }
4160
4627
  };
4161
4628
  } catch (err) {
4162
- process.stderr.write(`baton: ${spec.method} capture failed: ${String(err)}
4163
- `);
4629
+ stderrLine(`baton: ${spec.method} capture failed: ${String(err)}`);
4164
4630
  return null;
4165
4631
  }
4166
4632
  }
@@ -4280,7 +4746,6 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
4280
4746
  TOOLS_CALL_METHOD,
4281
4747
  TOOLS_CALL_SEAM,
4282
4748
  (handler) => async (...args) => {
4283
- ctx.perCaller?.followSettings();
4284
4749
  const request = args[0];
4285
4750
  const name = request?.params?.name;
4286
4751
  const slot = {
@@ -4290,6 +4755,10 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
4290
4755
  strippedFor: typeof name === "string" ? name : null,
4291
4756
  validation: "unseen"
4292
4757
  };
4758
+ const toolArgs = request?.params?.arguments;
4759
+ if (typeof name === "string" && toolEntry(name) != null && await hiddenFrom(slot, name, isRecord(toolArgs) ? toolArgs : {}, args[1], ctx)) {
4760
+ return answerHidden(lowLevel, name, (outcome2) => settleCall(slot, outcome2, args, toolEntry, ctx, "tool_hidden"));
4761
+ }
4293
4762
  let outcome = CLEAN_OUTCOME;
4294
4763
  try {
4295
4764
  const result = await callSlots.run(slot, () => handler(...args));
@@ -4304,6 +4773,34 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
4304
4773
  }
4305
4774
  );
4306
4775
  }
4776
+ async function hiddenFrom(slot, name, params, extra, ctx) {
4777
+ try {
4778
+ if (name === ctx.annotationToolName || !mayHide(ctx.captureSettings, name)) return false;
4779
+ slot.caller = await resolveCaller(
4780
+ ctx.resolvePrincipal,
4781
+ { extra, toolName: name, arguments: params },
4782
+ ctx.captureSettings,
4783
+ observeClient(extra, ctx)
4784
+ );
4785
+ return slot.caller.settings?.overlay?.hiddenTools.has(name) ?? false;
4786
+ } catch (err) {
4787
+ stderrLine(`baton: could not check whether the tool is hidden; it is served: ${printable(err)}`);
4788
+ return false;
4789
+ }
4790
+ }
4791
+ async function answerHidden(lowLevel, name, settle) {
4792
+ if (lowLevelMajor(lowLevel) === 1) {
4793
+ const result = { content: [{ type: "text", text: `MCP error -32602: Tool ${name} not found` }], isError: true };
4794
+ await settle({ failed: true, raised: false, result });
4795
+ return result;
4796
+ }
4797
+ const err = new ProtocolError(`Tool ${name} not found`);
4798
+ await settle({ failed: true, raised: true, err });
4799
+ throw err;
4800
+ }
4801
+ var ProtocolError = class extends Error {
4802
+ code = -32602;
4803
+ };
4307
4804
  var VALIDATION_PROBE = /* @__PURE__ */ Symbol("baton.validationProbe");
4308
4805
  function installValidationProbe(server) {
4309
4806
  const target = server;
@@ -4323,7 +4820,7 @@ function installValidationProbe(server) {
4323
4820
  Object.assign(probe, { [VALIDATION_PROBE]: true });
4324
4821
  target.validateToolInput = probe;
4325
4822
  }
4326
- async function settleCall(slot, outcome, args, toolEntry, ctx) {
4823
+ async function settleCall(slot, outcome, args, toolEntry, ctx, kind) {
4327
4824
  try {
4328
4825
  if (slot.flushTerminal !== null) {
4329
4826
  const flush = slot.flushTerminal;
@@ -4333,14 +4830,13 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
4333
4830
  }
4334
4831
  if (slot.innerFired) return;
4335
4832
  if (!outcome.failed) return;
4336
- await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
4833
+ await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx, kind);
4337
4834
  } catch (err) {
4338
4835
  PROCESS_DROPS.add("encode_failed");
4339
- process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
4340
- `);
4836
+ stderrLine(`baton: settling a tool call failed; events dropped: ${String(err)}`);
4341
4837
  }
4342
4838
  }
4343
- async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
4839
+ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx, kind) {
4344
4840
  const request = args[0];
4345
4841
  const toolName = request?.params?.name;
4346
4842
  if (typeof toolName !== "string") return;
@@ -4354,9 +4850,10 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
4354
4850
  args[1],
4355
4851
  params,
4356
4852
  slot.stripped,
4357
- entry != null ? "warn" : "quiet"
4853
+ slot.unlisted ?? (entry != null ? "warn" : "quiet"),
4854
+ slot.caller
4358
4855
  );
4359
- const failureKind = requestSideFailureKind(entry, slot.validation);
4856
+ const failureKind = kind ?? requestSideFailureKind(entry, slot.validation);
4360
4857
  const text = () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result);
4361
4858
  await emit(
4362
4859
  ctx.sink,
@@ -4550,7 +5047,7 @@ function newBatonState(config) {
4550
5047
  lowLevelTools: { given: config.tools, givenTools: [], served: /* @__PURE__ */ new Map(), keepsGoal: /* @__PURE__ */ new Set(), unread: /* @__PURE__ */ new Set() }
4551
5048
  };
4552
5049
  }
4553
- function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber, lowLevelTools }, unconfigured) {
5050
+ function install(server, supplied, resolved, { sentSurfaces, warned: warned4, counter: sharedCounter, scrubber, lowLevelTools }, unconfigured) {
4554
5051
  const shape = serverShapeOf(server);
4555
5052
  const internals = server;
4556
5053
  const lowLevel = shape === "mcpServer" ? internals.server : server;
@@ -4563,6 +5060,11 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4563
5060
  const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
4564
5061
  const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
4565
5062
  if (unconfigured) return inertHandle(new DisabledSink(), "baton-unconfigured");
5063
+ if (shape === "mcpServer" && reports && internals._registeredTools?.[annotationToolName]) {
5064
+ throw new Error(
5065
+ `Tool ${annotationToolName} is already registered, so Baton cannot add its report tool. If it is your tool, set annotationToolName to another name; if Baton is already on this server, call withBaton once.`
5066
+ );
5067
+ }
4566
5068
  const given = config.sink ?? new StdoutSink();
4567
5069
  const sink = offTheCall(given);
4568
5070
  const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
@@ -4598,23 +5100,19 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4598
5100
  if (memo && typeof memo === "object") delete memo[name];
4599
5101
  };
4600
5102
  const warnOnce2 = (key, message) => {
4601
- if (warned3.has(key)) return;
4602
- warned3.add(key);
4603
- process.stderr.write(message);
5103
+ if (warned4.has(key)) return;
5104
+ warned4.add(key);
5105
+ stderrLine(message);
5106
+ };
5107
+ const warnLength = (message) => warnOnce2("instructions-length", message);
5108
+ const setInstructions = (text) => {
5109
+ lowLevel._instructions = text;
4604
5110
  };
4605
5111
  const dropSubagentClause = (name) => {
4606
- const current2 = lowLevel._instructions;
4607
- if (current2 === INTENT_INSTRUCTIONS) {
4608
- lowLevel._instructions = "";
4609
- } else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
4610
- lowLevel._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
4611
- } else {
4612
- return;
4613
- }
5112
+ if (!removeSubagentClause(lowLevel, setInstructions, warnLength)) return;
4614
5113
  warnOnce2(
4615
5114
  "native-user-goal",
4616
- `baton: tool ${JSON.stringify(name)} declares its own user_goal, so the subagent sentence was removed from the server instructions; a session that already started keeps it
4617
- `
5115
+ `baton: tool ${JSON.stringify(name)} declares its own user_goal, so the subagent sentence was removed from the server instructions; a session that already started keeps it`
4618
5116
  );
4619
5117
  };
4620
5118
  const isV2Server = typeof internals.toolInputSchemaJson === "function";
@@ -4658,12 +5156,8 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4658
5156
  surfaceState,
4659
5157
  emitSurface
4660
5158
  };
4661
- const writeInstructions = (text) => {
4662
- lowLevel._instructions = withVendorInstructions(
4663
- lowLevel,
4664
- text,
4665
- (message) => warnOnce2("instructions-length", message)
4666
- );
5159
+ const writeInstructions = (text, subagent = INTENT_INSTRUCTIONS) => {
5160
+ writeOurs(lowLevel, text, subagent, setInstructions, warnLength);
4667
5161
  };
4668
5162
  writeInstructions(ours);
4669
5163
  const rewriteInstructions = (text) => {
@@ -4679,8 +5173,9 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4679
5173
  get annotationToolName() {
4680
5174
  return ctx.annotationToolName;
4681
5175
  },
4682
- instructions: ours,
4683
- writeInstructions: rewriteInstructions,
5176
+ pointer: () => reports && ctx.annotationToolName ? buildReportPointer({ vendorDisplayName: reports.vendorDisplayName, annotationToolName: ctx.annotationToolName }) : void 0,
5177
+ writeInstructions,
5178
+ subagentLine: () => ![...ctx.paramRegistry.values()].some((d) => d[USER_GOAL_PARAM_NAME] === "native"),
4684
5179
  injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
4685
5180
  });
4686
5181
  ctx.perCaller.followSettings();
@@ -4708,10 +5203,10 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4708
5203
  annotationOptions && buildAnnotationTool(server, annotationOptions),
4709
5204
  lowLevelTools,
4710
5205
  warnOnce2,
4711
- () => rewriteInstructions(INTENT_INSTRUCTIONS)
5206
+ () => ctx.perCaller ? ctx.perCaller.refresh() : rewriteInstructions(INTENT_INSTRUCTIONS)
4712
5207
  );
4713
5208
  }
4714
- installToolsListSeam(lowLevel, ctx);
5209
+ installToolsListSeam(lowLevel, ctx, shape === "lowLevel");
4715
5210
  if (shape === "mcpServer") installToolsCallSeam(
4716
5211
  lowLevel,
4717
5212
  // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
@@ -4728,6 +5223,17 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4728
5223
  ctx
4729
5224
  );
4730
5225
  installLifecycleSeams(lowLevel, ctx);
5226
+ const settings = config.captureSettings;
5227
+ if (settings !== void 0) {
5228
+ const waitFirst = (handler) => async (...args) => {
5229
+ if (!settings.isReady) await settings.ready;
5230
+ ctx.perCaller?.followSettings();
5231
+ return handler(...args);
5232
+ };
5233
+ for (const method of ["initialize", "server/discover", TOOLS_LIST_METHOD, TOOLS_CALL_METHOD]) {
5234
+ installRequestSeam(lowLevel, method, SETTINGS_SEAM, waitFirst);
5235
+ }
5236
+ }
4731
5237
  const handle = (name) => new BatonHandle({
4732
5238
  sink: given,
4733
5239
  queue: sink,
@@ -4757,11 +5263,11 @@ function reportsFor(config) {
4757
5263
  }
4758
5264
  function warnAboutSettings(config) {
4759
5265
  if (config.reportMode !== "on" && config.annotationToolName !== void 0) {
4760
- process.stderr.write(
4761
- `baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered
4762
- `
5266
+ stderrLine(
5267
+ `baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered`
4763
5268
  );
4764
5269
  }
5270
+ candidateNeedsConsole(config.settings);
4765
5271
  if (config.resultCaptureMode === WITHHELD) {
4766
5272
  warn(
4767
5273
  'baton: resultCaptureMode "off" does not withhold the message of a failed tool list, resource or prompt request. tool_list_error, resource_list_error, resource_read_error, prompt_list_error and prompt_get_error carry that message, which can include text your handler or middleware threw. Throw a message that does not quote what your code fetched.'
@@ -4801,7 +5307,7 @@ function principalFromOAuthEmail(context) {
4801
5307
  }
4802
5308
 
4803
5309
  // src/library/session.ts
4804
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
5310
+ import * as asyncHooks2 from "async_hooks";
4805
5311
  var TRANSPORT_LIBRARY = "library";
4806
5312
  var TURN_ID_META_KEY = "baton/turn_id";
4807
5313
  function sessionEnvelope(session) {
@@ -4817,8 +5323,7 @@ function sessionEnvelope(session) {
4817
5323
  };
4818
5324
  }
4819
5325
  function warn2(message) {
4820
- process.stderr.write(`baton: ${message}
4821
- `);
5326
+ stderrLine(`baton: ${message}`);
4822
5327
  }
4823
5328
  function vendorId(name, value) {
4824
5329
  const cleaned = typeof value === "string" ? stripWhiteSpace(value) : "";
@@ -4855,7 +5360,7 @@ function newSession(values, scrubber, disabled) {
4855
5360
  runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
4856
5361
  };
4857
5362
  }
4858
- var current = new AsyncLocalStorage2();
5363
+ var current = new asyncHooks2.AsyncLocalStorage();
4859
5364
  function runInSession(owner, session, fn) {
4860
5365
  return current.run({ owner, session }, fn);
4861
5366
  }
@@ -4870,8 +5375,7 @@ function serveTools(tools, options) {
4870
5375
  try {
4871
5376
  served = tools.map(servedEntry);
4872
5377
  } catch (err) {
4873
- process.stderr.write(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}
4874
- `);
5378
+ stderrLine(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}`);
4875
5379
  return { served: tools, surface: null };
4876
5380
  }
4877
5381
  try {
@@ -4890,8 +5394,7 @@ function serveTools(tools, options) {
4890
5394
  );
4891
5395
  return { served, surface: { surface, digest: surfaceHash(surface) } };
4892
5396
  } catch (err) {
4893
- process.stderr.write(`baton: surface snapshot capture failed: ${printable(err)}
4894
- `);
5397
+ stderrLine(`baton: surface snapshot capture failed: ${printable(err)}`);
4895
5398
  return { served, surface: null };
4896
5399
  }
4897
5400
  }
@@ -5055,8 +5558,7 @@ var Core = class {
5055
5558
  });
5056
5559
  } catch (err) {
5057
5560
  PROCESS_DROPS.add("encode_failed");
5058
- process.stderr.write(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}
5059
- `);
5561
+ stderrLine(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}`);
5060
5562
  return Promise.resolve();
5061
5563
  }
5062
5564
  return safeWrite(this.sink, event);
@@ -5114,7 +5616,7 @@ var Trace = class _Trace {
5114
5616
  observed(result, failure) {
5115
5617
  if ((this.#result !== UNSET || this.#error !== null) && !this.#observedWarned) {
5116
5618
  this.#observedWarned = true;
5117
- process.stderr.write("baton: Trace.observed() called more than once; the last call wins.\n");
5619
+ stderrLine("baton: Trace.observed() called more than once; the last call wins.");
5118
5620
  }
5119
5621
  this.#result = UNSET;
5120
5622
  this.#error = null;
@@ -5134,8 +5636,7 @@ var Trace = class _Trace {
5134
5636
  try {
5135
5637
  this.#result = this.#core.scrubber(result);
5136
5638
  } catch (err) {
5137
- process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}
5138
- `);
5639
+ stderrLine(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}`);
5139
5640
  this.#result = SCRUB_FAILED;
5140
5641
  }
5141
5642
  }
@@ -5281,8 +5782,7 @@ var Client = class {
5281
5782
  try {
5282
5783
  block = newSession(options, this.#core.scrubber, this.#core.disabled);
5283
5784
  } catch (err) {
5284
- process.stderr.write(`baton: session values could not be read; using a minted session: ${printable(err)}
5285
- `);
5785
+ stderrLine(`baton: session values could not be read; using a minted session: ${printable(err)}`);
5286
5786
  block = newSession({}, this.#core.scrubber, this.#core.disabled);
5287
5787
  }
5288
5788
  return runInSession(this, block, fn);