@goodtiming/baton-sdk 1.0.1 → 1.1.1

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.0.1";
2
+ var SDK_VERSION = "ts-1.1.1";
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) {
@@ -384,10 +384,54 @@ var EventSchema = z.discriminatedUnion("event_type", [
384
384
  ToolListErrorEventSchema
385
385
  ]);
386
386
 
387
+ // src/runtime.ts
388
+ function onWorkers() {
389
+ return typeof globalThis.WebSocketPair === "function" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
390
+ }
391
+ var globalFetch = (input, init) => fetch(input, init);
392
+ function onProcess(event, listener) {
393
+ const target = typeof process !== "undefined" ? process : void 0;
394
+ if (typeof target?.on !== "function") return void 0;
395
+ try {
396
+ target.on(event, listener);
397
+ } catch {
398
+ return void 0;
399
+ }
400
+ return () => {
401
+ try {
402
+ target.off(event, listener);
403
+ } catch {
404
+ }
405
+ };
406
+ }
407
+
387
408
  // src/warn.ts
388
409
  function warn(message) {
389
- if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
390
- process.emitWarning(message);
410
+ if (onWorkers()) {
411
+ console.warn(message);
412
+ return;
413
+ }
414
+ try {
415
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") return process.emitWarning(message);
416
+ } catch {
417
+ }
418
+ stderrLine(message);
419
+ }
420
+ function stderrLine(message) {
421
+ stderrLines([message]);
422
+ }
423
+ function stderrLines(lines) {
424
+ try {
425
+ const stderr = typeof process !== "undefined" ? process.stderr : void 0;
426
+ if (typeof stderr?.write === "function") return void stderr.write(lines.map((line) => `${line}
427
+ `).join(""));
428
+ } catch {
429
+ }
430
+ for (const line of lines) {
431
+ try {
432
+ console.warn(line);
433
+ } catch {
434
+ }
391
435
  }
392
436
  }
393
437
  function printable(err) {
@@ -517,8 +561,8 @@ function identityScrub(value) {
517
561
  }
518
562
 
519
563
  // src/sinks.ts
520
- import { appendFileSync } from "fs";
521
- import { open } from "fs/promises";
564
+ import * as fs from "fs";
565
+ import * as fsp from "fs/promises";
522
566
 
523
567
  // src/_text.ts
524
568
  var WHITE_SPACE = /^\p{White_Space}$/u;
@@ -569,7 +613,8 @@ var SHUTDOWN_FLUSH_TIMEOUT_MS = 3e3;
569
613
  // src/drops.ts
570
614
  var RECOVERY_LOG_MS = 6e4;
571
615
  var DropCounts = class {
572
- #instanceId = uuid7();
616
+ // Made on first use: a Worker refuses random values while its modules load.
617
+ #instanceId;
573
618
  #total = /* @__PURE__ */ new Map();
574
619
  #sinceDelivery = /* @__PURE__ */ new Map();
575
620
  #lastRecoveryLog = -RECOVERY_LOG_MS;
@@ -593,13 +638,13 @@ var DropCounts = class {
593
638
  const total = lost.reduce((sum2, [, n]) => sum2 + n, 0);
594
639
  warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(", ")}.`);
595
640
  }
596
- /** For tests: the counts are one per process. */
597
641
  /** Names this process in its loss reports (SPEC §11.4.7). */
598
642
  get instanceId() {
599
- return this.#instanceId;
643
+ return this.#instanceId ??= uuid7();
600
644
  }
645
+ /** For tests: the counts are one per process. */
601
646
  clear() {
602
- this.#instanceId = uuid7();
647
+ this.#instanceId = void 0;
603
648
  this.#total.clear();
604
649
  this.#sinceDelivery.clear();
605
650
  this.#lastRecoveryLog = -RECOVERY_LOG_MS;
@@ -639,14 +684,9 @@ async function safeWrite(sink, event) {
639
684
  } catch (err) {
640
685
  if (isSinkClosed(err)) return droppedAfterClose(sink);
641
686
  PROCESS_DROPS.add("write_failed");
642
- process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}
643
- `);
687
+ stderrLine(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}`);
644
688
  }
645
689
  }
646
- function stderrLine(message) {
647
- process.stderr.write(`${message}
648
- `);
649
- }
650
690
  function isTimerMs(value) {
651
691
  return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
652
692
  }
@@ -686,11 +726,13 @@ var StdoutSink = class {
686
726
  stream;
687
727
  closed = false;
688
728
  constructor(options = {}) {
689
- this.stream = options.stream ?? process.stderr;
729
+ this.stream = options.stream;
690
730
  }
691
731
  async write(event) {
692
732
  if (this.closed) throw new SinkClosedError("StdoutSink is closed");
693
- this.stream.write(JSON.stringify(event) + "\n");
733
+ const line = JSON.stringify(event);
734
+ if (this.stream) this.stream.write(line + "\n");
735
+ else stderrLine(line);
694
736
  }
695
737
  async flush() {
696
738
  }
@@ -712,7 +754,7 @@ var FileSink = class {
712
754
  if (this.closed) throw new SinkClosedError("FileSink is closed");
713
755
  const line = JSON.stringify(event) + "\n";
714
756
  const written = this.last.then(async () => {
715
- this.file ??= await open(this.path, "a");
757
+ this.file ??= await fsp.open(this.path, "a");
716
758
  await this.file.appendFile(line);
717
759
  });
718
760
  this.last = written.catch(() => void 0);
@@ -769,30 +811,31 @@ var later = (run) => {
769
811
  else setTimeout(run, 0);
770
812
  };
771
813
  var withUnwrittenEvents = /* @__PURE__ */ new Set();
772
- var exitHooked = false;
814
+ var exitTriedOn = /* @__PURE__ */ new WeakSet();
773
815
  function hookExit() {
774
- if (exitHooked) return;
775
- exitHooked = true;
776
- try {
777
- process.on("exit", () => {
778
- try {
779
- let unsure = 0;
780
- for (const sink of withUnwrittenEvents) unsure += sink.handOffAtExit();
781
- if (unsure > 0) stderrLine(`baton: process exiting; ${unsure} event(s) may not have been written.`);
782
- } catch {
783
- }
784
- });
785
- } catch {
786
- }
816
+ const target = typeof process !== "undefined" ? process : void 0;
817
+ if (target === void 0 || exitTriedOn.has(target)) return;
818
+ exitTriedOn.add(target);
819
+ onProcess("exit", () => {
820
+ try {
821
+ let unsure = 0;
822
+ for (const sink of withUnwrittenEvents) unsure += sink.handOffAtExit();
823
+ if (unsure > 0) stderrLine(`baton: process exiting; ${unsure} event(s) may not have been written.`);
824
+ } catch {
825
+ }
826
+ });
787
827
  }
788
828
  function writeNow(sink, events) {
789
- const lines = events.map((event) => JSON.stringify(event) + "\n").join("");
829
+ const json = () => events.map((event) => JSON.stringify(event));
830
+ const lines = () => json().map((line) => line + "\n").join("");
790
831
  if (sink instanceof StdoutSink) {
791
832
  const stream = sink["stream"];
792
- if (stream !== process.stdout && stream !== process.stderr) return false;
793
- if (!sink["closed"]) stream.write(lines);
833
+ if (stream !== void 0 && stream !== process.stdout && stream !== process.stderr) return false;
834
+ if (sink["closed"]) return true;
835
+ if (stream === void 0) stderrLines(json());
836
+ else stream.write(lines());
794
837
  } else if (sink instanceof FileSink) {
795
- if (!sink["closed"]) appendFileSync(sink["path"], lines);
838
+ if (!sink["closed"]) fs.appendFileSync(sink["path"], lines());
796
839
  } else return false;
797
840
  return true;
798
841
  }
@@ -1039,13 +1082,19 @@ var HttpSink = class _HttpSink {
1039
1082
  /** Whether the queued pass sends everything waiting, not only what is due. */
1040
1083
  forceNext = false;
1041
1084
  flushTimer = null;
1042
- /** Set by a failed batch: only the timer, a flush or a close tries again. */
1085
+ /** Set by a failed batch: only the timer, a flush, a close or, at
1086
+ * `flushIntervalMs` 0, a write after `retryFrom` tries again. */
1043
1087
  waitForTimer = false;
1088
+ /** When a failed batch may be tried again. At `flushIntervalMs` 0 the
1089
+ * first write from then retries, as a Worker may drop the timer. */
1090
+ retryFrom = 0;
1044
1091
  /** Nothing is sent before this `Date.now()`, from a 429's `Retry-After`. */
1045
1092
  retryAt = 0;
1046
1093
  /** Set for the life of the sink by a 404 or 405 on the batch path. */
1047
1094
  batchless = false;
1048
1095
  exitHooks = null;
1096
+ /** The `process` the exit hooks were last tried on, so a refusal is not retried per write. */
1097
+ exitHooksTriedOn;
1049
1098
  /** The least time between two of this sink's loss reports. */
1050
1099
  static reportIntervalMs = 6e4;
1051
1100
  /** Totals only grow, so their sum tells whether they changed. */
@@ -1066,7 +1115,7 @@ var HttpSink = class _HttpSink {
1066
1115
  "shutdownFlushTimeoutMs",
1067
1116
  SHUTDOWN_FLUSH_TIMEOUT_MS
1068
1117
  );
1069
- this.flushIntervalMs = timerMsOption(options.flushIntervalMs, "flushIntervalMs", FLUSH_INTERVAL_MS);
1118
+ this.flushIntervalMs = timerMsOption(options.flushIntervalMs, "flushIntervalMs", onWorkers() ? 0 : FLUSH_INTERVAL_MS);
1070
1119
  this.maxRetries = options.maxRetries ?? 3;
1071
1120
  this.backoffBaseMs = options.backoffBaseMs ?? 100;
1072
1121
  this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
@@ -1074,7 +1123,7 @@ var HttpSink = class _HttpSink {
1074
1123
  options.circuitBreakerThreshold ?? 5,
1075
1124
  options.circuitBreakerResetMs ?? 3e4
1076
1125
  );
1077
- this.fetchImpl = options.fetchImpl ?? fetch;
1126
+ this.fetchImpl = options.fetchImpl ?? globalFetch;
1078
1127
  }
1079
1128
  /**
1080
1129
  * What this sink shows when something prints it — never the bearer.
@@ -1112,8 +1161,9 @@ var HttpSink = class _HttpSink {
1112
1161
  }
1113
1162
  this.enqueue({ event, json, bytes, writtenAt: Date.now() });
1114
1163
  this.unsentWarned = false;
1115
- if (this.batchIsFull() && !this.waitForTimer) void this.scheduleDrain(false);
1116
- else this.armTimer(this.buffer[0].writtenAt + this.flushIntervalMs - Date.now());
1164
+ const held = this.waitForTimer && !(this.flushIntervalMs === 0 && Date.now() >= this.retryFrom);
1165
+ if (!held && (this.flushIntervalMs === 0 || this.batchIsFull())) void this.scheduleDrain(false);
1166
+ else this.armTimer(Math.max(this.buffer[0].writtenAt + this.flushIntervalMs, held ? this.retryFrom : 0) - Date.now());
1117
1167
  this.ensureExitHooksRegistered();
1118
1168
  }
1119
1169
  flush() {
@@ -1142,11 +1192,8 @@ var HttpSink = class _HttpSink {
1142
1192
  warn(`baton: the sink closed with ${unsent} event(s) unsent.`);
1143
1193
  }
1144
1194
  this.warnUnloggedRefusals("the sink closed");
1145
- if (this.exitHooks) {
1146
- process.off("beforeExit", this.exitHooks.beforeExit);
1147
- process.off("exit", this.exitHooks.exit);
1148
- this.exitHooks = null;
1149
- }
1195
+ this.exitHooks?.off();
1196
+ this.exitHooks = null;
1150
1197
  }
1151
1198
  /** SPEC §11.2 rule 7: an explicit flush or close returns within `ms` and
1152
1199
  * never rejects. While an earlier wait's drain is still stuck, a flush
@@ -1240,7 +1287,9 @@ var HttpSink = class _HttpSink {
1240
1287
  * both hooks: a vendor needing that guarantee must call `aclose()` from
1241
1288
  * their own handler. */
1242
1289
  ensureExitHooksRegistered() {
1243
- if (this.exitHooks) return;
1290
+ const target = typeof process !== "undefined" ? process : void 0;
1291
+ if (this.exitHooks || target === void 0 || target === this.exitHooksTriedOn) return;
1292
+ this.exitHooksTriedOn = target;
1244
1293
  const beforeExit = () => {
1245
1294
  if (this.unsent === 0 || this.exitPassRan) {
1246
1295
  this.warnUnloggedRefusals("process exiting");
@@ -1258,9 +1307,14 @@ var HttpSink = class _HttpSink {
1258
1307
  } catch {
1259
1308
  }
1260
1309
  };
1261
- this.exitHooks = { beforeExit, exit };
1262
- process.on("beforeExit", beforeExit);
1263
- process.on("exit", exit);
1310
+ const offBeforeExit = onProcess("beforeExit", beforeExit);
1311
+ const offExit = onProcess("exit", exit);
1312
+ if (offBeforeExit === void 0 || offExit === void 0) {
1313
+ offBeforeExit?.();
1314
+ offExit?.();
1315
+ return;
1316
+ }
1317
+ this.exitHooks = { beforeExit, exit, off: () => (offBeforeExit(), offExit()) };
1264
1318
  }
1265
1319
  /** One attempt per batch, no retry, within `shutdownFlushTimeoutMs` in
1266
1320
  * total (SPEC §11.2); what is left is reported, not sent. */
@@ -1365,8 +1419,9 @@ var HttpSink = class _HttpSink {
1365
1419
  this.waitForTimer = failed;
1366
1420
  this.clearTimer();
1367
1421
  if (failed) {
1368
- const waits = [this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest()];
1369
- if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(Math.max(...waits));
1422
+ const wait = Math.max(this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest());
1423
+ this.retryFrom = Date.now() + wait;
1424
+ if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(wait);
1370
1425
  return;
1371
1426
  }
1372
1427
  const next = Math.min(this.buffer[0]?.writtenAt ?? Infinity, this.reportRidesHead() ? this.reportSetAt : Infinity);
@@ -1640,7 +1695,7 @@ var HttpSink = class _HttpSink {
1640
1695
  };
1641
1696
 
1642
1697
  // src/integrations/mcp/withBaton.ts
1643
- import { AsyncLocalStorage } from "async_hooks";
1698
+ import * as asyncHooks from "async_hooks";
1644
1699
 
1645
1700
  // src/integrations/mcp/annotation.ts
1646
1701
  import { z as z2 } from "zod";
@@ -1742,6 +1797,23 @@ function declaresParam(schema, name) {
1742
1797
  const props = schema?.properties;
1743
1798
  return typeof props === "object" && props !== null && name in props;
1744
1799
  }
1800
+ var NOT_ACCEPTED = /* @__PURE__ */ new Set(["not", "const", "enum", "default", "examples"]);
1801
+ var NAMED_SCHEMAS = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
1802
+ function mayDeclareParam(schema, name) {
1803
+ const seen = /* @__PURE__ */ new Set();
1804
+ const walk2 = (node) => {
1805
+ if (typeof node !== "object" || node === null || seen.has(node)) return false;
1806
+ seen.add(node);
1807
+ const { required, $ref } = node;
1808
+ if (declaresParam(node, name) || Array.isArray(required) && required.includes(name)) return true;
1809
+ if (typeof $ref === "string" && !$ref.startsWith("#")) return true;
1810
+ return Object.entries(node).some(([key, child]) => {
1811
+ if (NAMED_SCHEMAS.has(key) && typeof child === "object" && child !== null) return Object.values(child).some(walk2);
1812
+ return !NOT_ACCEPTED.has(key) && walk2(child);
1813
+ });
1814
+ };
1815
+ return walk2(schema);
1816
+ }
1745
1817
  function instructionsSuffixServed(annotationToolName, served) {
1746
1818
  if (annotationToolName) return true;
1747
1819
  return typeof served === "string" && served.includes(INTENT_INSTRUCTIONS);
@@ -1766,7 +1838,7 @@ function endsInOurs(current2, vendor) {
1766
1838
  const rest = current2.slice(prefix.length);
1767
1839
  return OURS_STARTS.some((start) => start.test(rest));
1768
1840
  }
1769
- function withVendorInstructions(server, ours, warn3 = (message) => process.stderr.write(message)) {
1841
+ function withVendorInstructions(server, ours, warn3 = stderrLine) {
1770
1842
  const holder = server;
1771
1843
  const current2 = holder._instructions;
1772
1844
  let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
@@ -1780,8 +1852,7 @@ function withVendorInstructions(server, ours, warn3 = (message) => process.stder
1780
1852
  ${ours}`;
1781
1853
  if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
1782
1854
  warn3(
1783
- `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
1784
- `
1855
+ `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`
1785
1856
  );
1786
1857
  }
1787
1858
  return combined;
@@ -1888,8 +1959,7 @@ async function emit(sink, build) {
1888
1959
  event = build();
1889
1960
  } catch (err) {
1890
1961
  PROCESS_DROPS.add("encode_failed");
1891
- process.stderr.write(`baton: event construction failed; event dropped: ${printable(err)}
1892
- `);
1962
+ stderrLine(`baton: event construction failed; event dropped: ${printable(err)}`);
1893
1963
  return;
1894
1964
  }
1895
1965
  await safeWrite(sink, event);
@@ -2150,6 +2220,185 @@ async function resolveIdentity(hook, call) {
2150
2220
  }
2151
2221
  }
2152
2222
 
2223
+ // src/integrations/mcp/zodCompat.ts
2224
+ import * as z3rt from "zod/v3";
2225
+ import * as z4mini from "zod/v4-mini";
2226
+ import { zodToJsonSchema } from "zod-to-json-schema";
2227
+ function isZ4Schema(s) {
2228
+ const schema = s;
2229
+ return !!schema?._zod;
2230
+ }
2231
+ function objectFromShape(shape) {
2232
+ const values = Object.values(shape);
2233
+ if (values.length === 0) return z4mini.object({});
2234
+ const allV4 = values.every(isZ4Schema);
2235
+ const allV3 = values.every((s) => !isZ4Schema(s));
2236
+ if (allV4) return z4mini.object(shape);
2237
+ if (allV3) return z3rt.object(shape);
2238
+ throw new Error("Mixed Zod versions detected in object shape.");
2239
+ }
2240
+ function getObjectShape(schema) {
2241
+ if (!schema) return void 0;
2242
+ let rawShape;
2243
+ if (isZ4Schema(schema)) {
2244
+ rawShape = schema._zod?.def?.shape;
2245
+ } else {
2246
+ rawShape = schema.shape;
2247
+ }
2248
+ if (!rawShape) return void 0;
2249
+ if (typeof rawShape === "function") {
2250
+ try {
2251
+ return rawShape();
2252
+ } catch {
2253
+ return void 0;
2254
+ }
2255
+ }
2256
+ return rawShape;
2257
+ }
2258
+ function normalizeObjectSchema(schema) {
2259
+ if (!schema) return void 0;
2260
+ if (typeof schema === "object") {
2261
+ const asAny = schema;
2262
+ if (!asAny._def && !asAny._zod) {
2263
+ const values = Object.values(schema);
2264
+ if (values.length > 0 && values.every(
2265
+ (v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function")
2266
+ )) {
2267
+ return objectFromShape(schema);
2268
+ }
2269
+ }
2270
+ }
2271
+ if (isZ4Schema(schema)) {
2272
+ const def = schema._zod?.def;
2273
+ if (def && (def.type === "object" || def.shape !== void 0)) return schema;
2274
+ } else {
2275
+ if (schema.shape !== void 0) return schema;
2276
+ }
2277
+ return void 0;
2278
+ }
2279
+ function mapMiniTarget(t) {
2280
+ if (!t) return "draft-7";
2281
+ if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
2282
+ if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
2283
+ return "draft-7";
2284
+ }
2285
+ function toJsonSchemaCompat(schema, opts) {
2286
+ if (isZ4Schema(schema)) {
2287
+ return z4mini.toJSONSchema(schema, {
2288
+ target: mapMiniTarget(opts?.target),
2289
+ io: opts?.pipeStrategy ?? "input"
2290
+ });
2291
+ }
2292
+ return zodToJsonSchema(schema, {
2293
+ strictUnions: opts?.strictUnions ?? true,
2294
+ pipeStrategy: opts?.pipeStrategy ?? "input"
2295
+ });
2296
+ }
2297
+
2298
+ // src/integrations/mcp/schemaCompat.ts
2299
+ import { z as zV4 } from "zod";
2300
+ import { z as zV3 } from "zod/v3";
2301
+ var DEFAULT_INTENT_PARAM_MODE = "required";
2302
+ var ROOT_COMBINERS = ["$ref", "oneOf", "anyOf", "allOf"];
2303
+ function takesUserGoalJson(schema) {
2304
+ const properties = schema.properties ?? {};
2305
+ return isRecord(properties) && !ROOT_COMBINERS.some((key) => key in schema);
2306
+ }
2307
+ function withUserGoalJson(schema, intentParamMode, listRequired) {
2308
+ if (!takesUserGoalJson(schema) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return schema;
2309
+ const properties = schema.properties ?? {};
2310
+ const goal = { type: "string", description: buildUserGoalParamDescription({ intentParamMode }) };
2311
+ const served = { ...schema, properties: { ...properties, [USER_GOAL_PARAM_NAME]: goal } };
2312
+ const required = Array.isArray(schema.required) ? schema.required : [];
2313
+ if (listRequired && !required.includes(USER_GOAL_PARAM_NAME)) served.required = [...required, USER_GOAL_PARAM_NAME];
2314
+ return served;
2315
+ }
2316
+ var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
2317
+ function injectGoalParams(inputSchema2, intentParamMode) {
2318
+ const objSchema = normalizeObjectSchema(inputSchema2);
2319
+ if (!objSchema) return { schema: inputSchema2, dispositions: {} };
2320
+ const existingShape = getObjectShape(objSchema) ?? {};
2321
+ const values = Object.values(existingShape);
2322
+ const useV4 = values.length === 0 || isZ4Schema(values[0]);
2323
+ const zodImpl = useV4 ? zV4 : zV3;
2324
+ const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
2325
+ if (Object.keys(toInject).length === 0)
2326
+ return { schema: inputSchema2, dispositions };
2327
+ const mergedShape = { ...existingShape, ...toInject };
2328
+ const newSchema = objectFromShape(mergedShape);
2329
+ return { schema: newSchema, dispositions };
2330
+ }
2331
+ function buildIntentFields(existingShape, zodImpl, intentParamMode) {
2332
+ const dispositions = {};
2333
+ const toInject = {};
2334
+ for (const name of RETIRED_PARAM_NAMES) {
2335
+ if (name in existingShape) dispositions[name] = "native";
2336
+ }
2337
+ if (USER_GOAL_PARAM_NAME in existingShape) {
2338
+ dispositions[USER_GOAL_PARAM_NAME] = "native";
2339
+ } else {
2340
+ dispositions[USER_GOAL_PARAM_NAME] = "injected";
2341
+ toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
2342
+ }
2343
+ return { dispositions, toInject };
2344
+ }
2345
+ function injectGoalParamsV2(inputSchema2, intentParamMode) {
2346
+ const candidate = inputSchema2;
2347
+ const shape = candidate?.shape;
2348
+ if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
2349
+ return { schema: inputSchema2, dispositions: {} };
2350
+ }
2351
+ const { dispositions, toInject } = buildIntentFields(shape, zV4, intentParamMode);
2352
+ if (Object.keys(toInject).length === 0)
2353
+ return { schema: inputSchema2, dispositions };
2354
+ return { schema: candidate.extend(toInject), dispositions };
2355
+ }
2356
+ function advertiseIntentParamsRequired(result, names, isInjected) {
2357
+ const tools = result?.tools;
2358
+ if (!Array.isArray(tools)) return result;
2359
+ let changed = false;
2360
+ const advertised = tools.map((tool) => {
2361
+ const entry = tool;
2362
+ const toolName = entry?.name;
2363
+ if (typeof toolName !== "string") return tool;
2364
+ const schema = entry?.inputSchema;
2365
+ if (!schema || typeof schema !== "object") return tool;
2366
+ const declared2 = schema.required ?? [];
2367
+ if (!Array.isArray(declared2)) return tool;
2368
+ const required = declared2;
2369
+ const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
2370
+ if (missing.length === 0) return tool;
2371
+ changed = true;
2372
+ return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
2373
+ });
2374
+ return changed ? { ...result, tools: advertised } : result;
2375
+ }
2376
+ function withToolInputSchema(result, name, inputSchema2) {
2377
+ const tools = result?.tools;
2378
+ if (!Array.isArray(tools)) return result;
2379
+ const at = tools.findIndex((tool) => isRecord(tool) && tool.name === name);
2380
+ if (at === -1) return result;
2381
+ const served = [...tools];
2382
+ served[at] = { ...tools[at], inputSchema: inputSchema2 };
2383
+ return { ...result, tools: served };
2384
+ }
2385
+ function standardInputJsonSchema(schema) {
2386
+ try {
2387
+ const standard = schema?.["~standard"];
2388
+ return standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
2389
+ } catch {
2390
+ return void 0;
2391
+ }
2392
+ }
2393
+ function toolInputJsonSchema(inputSchema2) {
2394
+ const objSchema = normalizeObjectSchema(inputSchema2);
2395
+ if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
2396
+ return toJsonSchemaCompat(objSchema, {
2397
+ strictUnions: true,
2398
+ pipeStrategy: "input"
2399
+ });
2400
+ }
2401
+
2153
2402
  // src/integrations/mcp/safeScrub.ts
2154
2403
  var warned2 = /* @__PURE__ */ new Set();
2155
2404
  function scrubOrNull(scrubber, value, field) {
@@ -2159,9 +2408,8 @@ function scrubOrNull(scrubber, value, field) {
2159
2408
  } catch (err) {
2160
2409
  if (!warned2.has(field)) {
2161
2410
  warned2.add(field);
2162
- process.stderr.write(
2163
- `baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}
2164
- `
2411
+ stderrLine(
2412
+ `baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}`
2165
2413
  );
2166
2414
  }
2167
2415
  return null;
@@ -2296,24 +2544,44 @@ var ANNOTATION_INPUT_SHAPE = {
2296
2544
  // not rejected by validation.
2297
2545
  tool_name: z2.string().nullable().optional(),
2298
2546
  suggested_improvement: z2.string().optional(),
2299
- context: z2.record(z2.string(), z2.unknown()).optional()
2547
+ // zod renders "any value" as `{}`, which some MCP clients refuse (reportToolSchema.test.ts).
2548
+ context: z2.record(z2.string(), z2.unknown()).meta({ additionalProperties: true }).optional()
2300
2549
  };
2301
2550
  function isReport(whatHappened) {
2302
2551
  return typeof whatHappened === "string" && !isBlank(whatHappened);
2303
2552
  }
2304
2553
  function registerAnnotationTool(server, options) {
2554
+ const tool = buildAnnotationTool(server, options);
2555
+ server.registerTool(
2556
+ tool.name,
2557
+ { description: tool.description, inputSchema: ANNOTATION_INPUT_SHAPE },
2558
+ tool.handler
2559
+ );
2560
+ return tool.name;
2561
+ }
2562
+ var ANNOTATION_ARGS = z2.object(ANNOTATION_INPUT_SHAPE);
2563
+ function annotationInputJsonSchema(major) {
2564
+ return annotationJsonSchemas[major] ??= (major === 2 ? standardInputJsonSchema(ANNOTATION_ARGS) : void 0) ?? toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
2565
+ }
2566
+ var annotationJsonSchemas = {};
2567
+ function callAnnotationTool(tool, args, extra) {
2568
+ const parsed = ANNOTATION_ARGS.safeParse(args ?? {});
2569
+ if (parsed.success) return tool.handler(parsed.data, extra);
2570
+ return Promise.resolve({
2571
+ content: [{ type: "text", text: `Invalid arguments for tool ${tool.name}: ${parsed.error.message}` }],
2572
+ isError: true
2573
+ });
2574
+ }
2575
+ function buildAnnotationTool(server, options) {
2305
2576
  const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
2306
2577
  const description = buildAnnotationToolDescription({
2307
2578
  vendorDisplayName: options.vendorDisplayName
2308
2579
  });
2309
2580
  const refusal = buildRefusalText({ annotationToolName: name });
2310
- server.registerTool(
2581
+ return {
2311
2582
  name,
2312
- {
2313
- description,
2314
- inputSchema: ANNOTATION_INPUT_SHAPE
2315
- },
2316
- async (args, extra) => {
2583
+ description,
2584
+ handler: async (args, extra) => {
2317
2585
  const whatHappened = args.what_happened;
2318
2586
  if (!isReport(whatHappened)) {
2319
2587
  return {
@@ -2373,8 +2641,7 @@ function registerAnnotationTool(server, options) {
2373
2641
  );
2374
2642
  return { content: [{ type: "text", text: JSON.stringify({ ok: true }) }] };
2375
2643
  }
2376
- );
2377
- return name;
2644
+ };
2378
2645
  }
2379
2646
 
2380
2647
  // src/dsn.ts
@@ -2649,7 +2916,7 @@ function scrubbedErrorBody(scrubber, text) {
2649
2916
  }
2650
2917
 
2651
2918
  // src/integrations/mcp/captureSettings.ts
2652
- import { createHash } from "crypto";
2919
+ import * as crypto2 from "crypto";
2653
2920
  var SETTINGS_PATH = "/v0/settings";
2654
2921
  var TENANT_HEADER = "X-Baton-Tenant-Id";
2655
2922
  var SETTINGS_MODES = ["local", "console"];
@@ -2661,7 +2928,7 @@ var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
2661
2928
  var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
2662
2929
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
2663
2930
  function shareBucket(vendorId2, key) {
2664
- const digest = createHash("sha256").update(`${vendorId2}
2931
+ const digest = crypto2.createHash("sha256").update(`${vendorId2}
2665
2932
  ${key}`, "utf-8").digest();
2666
2933
  return Number(digest.readBigUInt64BE(0) % 10000n);
2667
2934
  }
@@ -2757,7 +3024,7 @@ var SettingsFetcher = class {
2757
3024
  this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
2758
3025
  this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
2759
3026
  this.refreshMs = options.refreshMs;
2760
- this.fetchImpl = options.fetchImpl ?? fetch;
3027
+ this.fetchImpl = options.fetchImpl ?? globalFetch;
2761
3028
  }
2762
3029
  get document() {
2763
3030
  return this.held;
@@ -2855,19 +3122,31 @@ function resolveInstallConfig(config) {
2855
3122
  );
2856
3123
  return { resolved, unconfigured };
2857
3124
  }
2858
- function resolveBatonConfig(config) {
3125
+ var consoleOffWarned = false;
3126
+ function withoutConsoleOnWorkers(config) {
3127
+ if (config.settings !== "console" || !onWorkers()) return config;
3128
+ if (!consoleOffWarned) {
3129
+ consoleOffWarned = true;
3130
+ warn(`baton: settings: "console" is not supported on Cloudflare Workers yet; the Console's settings are not read and this config's capture values apply.`);
3131
+ }
3132
+ const rest = { ...config, reportMode: config.reportMode ?? "on" };
3133
+ delete rest.settings;
3134
+ return rest;
3135
+ }
3136
+ function resolveBatonConfig(supplied) {
2859
3137
  const dsnString = selectDsn(
2860
- config.dsn,
3138
+ supplied.dsn,
2861
3139
  {
2862
3140
  // Truthiness per field, mirroring Python's `bool()` / `is not None`
2863
3141
  // split: an empty `vendorId` is an unset one, while an explicitly
2864
3142
  // supplied `tenantId` or `sink` is a conflict whatever it holds.
2865
- vendorId: Boolean(config.vendorId),
2866
- tenantId: config.tenantId !== void 0,
2867
- sink: config.sink !== void 0
3143
+ vendorId: Boolean(supplied.vendorId),
3144
+ tenantId: supplied.tenantId !== void 0,
3145
+ sink: supplied.sink !== void 0
2868
3146
  },
2869
3147
  "BatonConfig"
2870
3148
  );
3149
+ const config = dsnString === void 0 ? supplied : withoutConsoleOnWorkers(supplied);
2871
3150
  if (dsnString === void 0) {
2872
3151
  const defaulted = {
2873
3152
  ...config,
@@ -3002,6 +3281,9 @@ function validateBatonConfig(config) {
3002
3281
  if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
3003
3282
  throw new Error("BatonConfig.resolvePrincipal must be a function.");
3004
3283
  }
3284
+ if (config.tools !== void 0 && !Array.isArray(config.tools) && typeof config.tools !== "function") {
3285
+ throw new Error("BatonConfig.tools must be an array of tools or a function that returns one.");
3286
+ }
3005
3287
  }
3006
3288
 
3007
3289
  // src/optout.ts
@@ -3105,8 +3387,7 @@ var PerCallerSurface = class {
3105
3387
  this.options.writeInstructions(pointerOn ? this.options.instructions : INTENT_INSTRUCTIONS);
3106
3388
  this.pointerOn = pointerOn;
3107
3389
  } catch (err) {
3108
- process.stderr.write(`baton: could not update the server instructions for new settings: ${printable(err)}
3109
- `);
3390
+ stderrLine(`baton: could not update the server instructions for new settings: ${printable(err)}`);
3110
3391
  }
3111
3392
  }
3112
3393
  /** `result` with the caller's goal and reports settings; as served on any failure. */
@@ -3129,8 +3410,7 @@ var PerCallerSurface = class {
3129
3410
  }
3130
3411
  return { ...result, tools: served };
3131
3412
  } catch (err) {
3132
- process.stderr.write(`baton: could not apply capture settings to the tool list: ${printable(err)}
3133
- `);
3413
+ stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
3134
3414
  return result;
3135
3415
  }
3136
3416
  }
@@ -3188,159 +3468,11 @@ var ServerCounter = class extends SessionCounter {
3188
3468
  }
3189
3469
  };
3190
3470
 
3191
- // src/integrations/mcp/zodCompat.ts
3192
- import * as z3rt from "zod/v3";
3193
- import * as z4mini from "zod/v4-mini";
3194
- import { zodToJsonSchema } from "zod-to-json-schema";
3195
- function isZ4Schema(s) {
3196
- const schema = s;
3197
- return !!schema?._zod;
3198
- }
3199
- function objectFromShape(shape) {
3200
- const values = Object.values(shape);
3201
- if (values.length === 0) return z4mini.object({});
3202
- const allV4 = values.every(isZ4Schema);
3203
- const allV3 = values.every((s) => !isZ4Schema(s));
3204
- if (allV4) return z4mini.object(shape);
3205
- if (allV3) return z3rt.object(shape);
3206
- throw new Error("Mixed Zod versions detected in object shape.");
3207
- }
3208
- function getObjectShape(schema) {
3209
- if (!schema) return void 0;
3210
- let rawShape;
3211
- if (isZ4Schema(schema)) {
3212
- rawShape = schema._zod?.def?.shape;
3213
- } else {
3214
- rawShape = schema.shape;
3215
- }
3216
- if (!rawShape) return void 0;
3217
- if (typeof rawShape === "function") {
3218
- try {
3219
- return rawShape();
3220
- } catch {
3221
- return void 0;
3222
- }
3223
- }
3224
- return rawShape;
3225
- }
3226
- function normalizeObjectSchema(schema) {
3227
- if (!schema) return void 0;
3228
- if (typeof schema === "object") {
3229
- const asAny = schema;
3230
- if (!asAny._def && !asAny._zod) {
3231
- const values = Object.values(schema);
3232
- if (values.length > 0 && values.every(
3233
- (v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function")
3234
- )) {
3235
- return objectFromShape(schema);
3236
- }
3237
- }
3238
- }
3239
- if (isZ4Schema(schema)) {
3240
- const def = schema._zod?.def;
3241
- if (def && (def.type === "object" || def.shape !== void 0)) return schema;
3242
- } else {
3243
- if (schema.shape !== void 0) return schema;
3244
- }
3245
- return void 0;
3246
- }
3247
- function mapMiniTarget(t) {
3248
- if (!t) return "draft-7";
3249
- if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
3250
- if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
3251
- return "draft-7";
3252
- }
3253
- function toJsonSchemaCompat(schema, opts) {
3254
- if (isZ4Schema(schema)) {
3255
- return z4mini.toJSONSchema(schema, {
3256
- target: mapMiniTarget(opts?.target),
3257
- io: opts?.pipeStrategy ?? "input"
3258
- });
3259
- }
3260
- return zodToJsonSchema(schema, {
3261
- strictUnions: opts?.strictUnions ?? true,
3262
- pipeStrategy: opts?.pipeStrategy ?? "input"
3263
- });
3264
- }
3265
-
3266
- // src/integrations/mcp/schemaCompat.ts
3267
- import { z as zV4 } from "zod";
3268
- import { z as zV3 } from "zod/v3";
3269
- var DEFAULT_INTENT_PARAM_MODE = "required";
3270
- var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
3271
- function injectGoalParams(inputSchema2, intentParamMode) {
3272
- const objSchema = normalizeObjectSchema(inputSchema2);
3273
- if (!objSchema) return { schema: inputSchema2, dispositions: {} };
3274
- const existingShape = getObjectShape(objSchema) ?? {};
3275
- const values = Object.values(existingShape);
3276
- const useV4 = values.length === 0 || isZ4Schema(values[0]);
3277
- const zodImpl = useV4 ? zV4 : zV3;
3278
- const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
3279
- if (Object.keys(toInject).length === 0)
3280
- return { schema: inputSchema2, dispositions };
3281
- const mergedShape = { ...existingShape, ...toInject };
3282
- const newSchema = objectFromShape(mergedShape);
3283
- return { schema: newSchema, dispositions };
3284
- }
3285
- function buildIntentFields(existingShape, zodImpl, intentParamMode) {
3286
- const dispositions = {};
3287
- const toInject = {};
3288
- for (const name of RETIRED_PARAM_NAMES) {
3289
- if (name in existingShape) dispositions[name] = "native";
3290
- }
3291
- if (USER_GOAL_PARAM_NAME in existingShape) {
3292
- dispositions[USER_GOAL_PARAM_NAME] = "native";
3293
- } else {
3294
- dispositions[USER_GOAL_PARAM_NAME] = "injected";
3295
- toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
3296
- }
3297
- return { dispositions, toInject };
3298
- }
3299
- function injectGoalParamsV2(inputSchema2, intentParamMode) {
3300
- const candidate = inputSchema2;
3301
- const shape = candidate?.shape;
3302
- if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
3303
- return { schema: inputSchema2, dispositions: {} };
3304
- }
3305
- const { dispositions, toInject } = buildIntentFields(shape, zV4, intentParamMode);
3306
- if (Object.keys(toInject).length === 0)
3307
- return { schema: inputSchema2, dispositions };
3308
- return { schema: candidate.extend(toInject), dispositions };
3309
- }
3310
- function advertiseIntentParamsRequired(result, names, isInjected) {
3311
- const tools = result?.tools;
3312
- if (!Array.isArray(tools)) return result;
3313
- let changed = false;
3314
- const advertised = tools.map((tool) => {
3315
- const entry = tool;
3316
- const toolName = entry?.name;
3317
- if (typeof toolName !== "string") return tool;
3318
- const schema = entry?.inputSchema;
3319
- if (!schema || typeof schema !== "object") return tool;
3320
- const declared2 = schema.required ?? [];
3321
- if (!Array.isArray(declared2)) return tool;
3322
- const required = declared2;
3323
- const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
3324
- if (missing.length === 0) return tool;
3325
- changed = true;
3326
- return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
3327
- });
3328
- return changed ? { ...result, tools: advertised } : result;
3329
- }
3330
- function toolInputJsonSchema(inputSchema2) {
3331
- const objSchema = normalizeObjectSchema(inputSchema2);
3332
- if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
3333
- return toJsonSchemaCompat(objSchema, {
3334
- strictUnions: true,
3335
- pipeStrategy: "input"
3336
- });
3337
- }
3338
-
3339
3471
  // src/integrations/mcp/surface.ts
3340
- import { createHash as createHash2 } from "crypto";
3472
+ import * as crypto3 from "crypto";
3341
3473
  function surfaceHash(surface) {
3342
3474
  const canonical = canonicalJson(surface);
3343
- const digest = createHash2("sha256").update(canonical, "utf-8").digest("hex");
3475
+ const digest = crypto3.createHash("sha256").update(canonical, "utf-8").digest("hex");
3344
3476
  return `sha256:${digest}`;
3345
3477
  }
3346
3478
  function canonicalJson(value) {
@@ -3402,7 +3534,7 @@ var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
3402
3534
  var wired = /* @__PURE__ */ new WeakSet();
3403
3535
  var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
3404
3536
  var INTENT_PARAM_NAMES = [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES];
3405
- var callSlots = new AsyncLocalStorage();
3537
+ var callSlots = new asyncHooks.AsyncLocalStorage();
3406
3538
  var SurfaceState = class {
3407
3539
  constructor(serverMeta, sentSurfaces) {
3408
3540
  this.serverMeta = serverMeta;
@@ -3419,10 +3551,13 @@ var SurfaceState = class {
3419
3551
  /** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
3420
3552
  * which picks the spelling THIS SDK major puts on the wire. */
3421
3553
  noteTool(name, inputSchemaJson, description) {
3422
- this.rawTools.set(name, {
3423
- disabled: this.rawTools.get(name)?.disabled ?? false,
3424
- tool: { name, description: description ?? null, inputSchema: inputSchemaJson }
3425
- });
3554
+ const before = this.rawTools.get(name);
3555
+ const tool = { name, description: description ?? null, inputSchema: inputSchemaJson };
3556
+ if (before !== void 0 && before.tool.description === tool.description) {
3557
+ const same = before.tool.inputSchema === inputSchemaJson || JSON.stringify(before.tool.inputSchema) === JSON.stringify(inputSchemaJson);
3558
+ if (same) return;
3559
+ }
3560
+ this.rawTools.set(name, { disabled: before?.disabled ?? false, tool });
3426
3561
  this.dirty = true;
3427
3562
  }
3428
3563
  pruneTool(name) {
@@ -3464,14 +3599,14 @@ async function resolveEnvelopeParts(ctx, extra) {
3464
3599
  const session = await resolveSessionId(ctx.fallbackSessionId, extra);
3465
3600
  return { ...session, scrubbedMeta };
3466
3601
  }
3467
- async function openCall(ctx, toolName, extra, params, stripped, registered = true) {
3602
+ async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn") {
3468
3603
  await maybeEmitSurfaceSnapshot(ctx);
3469
3604
  const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
3470
3605
  const dispositions = ctx.paramRegistry.get(toolName);
3471
- const rawIntent = stripped[USER_GOAL_PARAM_NAME] ?? extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
3606
+ const rawIntent = stripped[USER_GOAL_PARAM_NAME] ?? extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, unlisted);
3472
3607
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
3473
3608
  const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
3474
- (name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
3609
+ (name) => dispositions === void 0 || dispositions[name] === "native" || unlisted === "leave" || unlisted === "goalOnly" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
3475
3610
  );
3476
3611
  const client = observeClient(extra, ctx);
3477
3612
  const caller = await resolveCaller(
@@ -3517,7 +3652,7 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
3517
3652
  );
3518
3653
  return { common, session, resultCaptureMode };
3519
3654
  }
3520
- function batonWrap(nameRef, original, ctx) {
3655
+ function batonWrap(nameRef, original, ctx, unlisted = "warn") {
3521
3656
  return async (...callArgs) => {
3522
3657
  const toolName = nameRef.current;
3523
3658
  const slot = callSlots.getStore();
@@ -3526,7 +3661,7 @@ function batonWrap(nameRef, original, ctx) {
3526
3661
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
3527
3662
  const stripped = slot?.strippedFor === toolName ? slot.stripped : {};
3528
3663
  if (slot) slot.strippedFor = null;
3529
- const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped);
3664
+ const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped, unlisted);
3530
3665
  const terminate = async (build, replacement) => {
3531
3666
  if (!slot) {
3532
3667
  if (build !== null) await emit(ctx.sink, build);
@@ -3684,14 +3819,14 @@ function batonWrap(nameRef, original, ctx) {
3684
3819
  return result;
3685
3820
  };
3686
3821
  }
3687
- function extractGoalParam(args, paramName, toolName, dispositions, registered) {
3822
+ function extractGoalParam(args, paramName, toolName, dispositions, unlisted) {
3688
3823
  if (!(paramName in args)) return null;
3689
3824
  const disposition = dispositions ? dispositions[paramName] : void 0;
3690
3825
  if (disposition === "native") return null;
3691
- if (disposition === void 0 && registered) {
3692
- process.stderr.write(
3693
- `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
3694
- `
3826
+ if (disposition === void 0 && unlisted === "leave") return null;
3827
+ if (disposition === void 0 && unlisted === "warn") {
3828
+ stderrLine(
3829
+ `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)`
3695
3830
  );
3696
3831
  }
3697
3832
  return popText(args, paramName);
@@ -3725,8 +3860,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
3725
3860
  snapshot = ctx.surfaceState.buildSnapshot();
3726
3861
  digest = surfaceHash(snapshot);
3727
3862
  } catch (err) {
3728
- process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
3729
- `);
3863
+ stderrLine(`baton: surface snapshot capture failed: ${String(err)}`);
3730
3864
  return;
3731
3865
  }
3732
3866
  const sent = ctx.surfaceState.sentSurfaces;
@@ -3794,16 +3928,16 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
3794
3928
  return registered;
3795
3929
  };
3796
3930
  }
3797
- function installToolsListSeam(lowLevel, ctx) {
3931
+ function installToolsListSeam(lowLevel, ctx, listsOwnReportTool) {
3798
3932
  const names = [...requiredParamNames(ctx.intentParamMode), TOOL_NAME_PARAM_NAME];
3799
3933
  const isInjected = (toolName, paramName) => toolName === ctx.annotationToolName ? paramName === TOOL_NAME_PARAM_NAME : ctx.paramRegistry.get(toolName)?.[paramName] === "injected";
3800
3934
  const advertise = (result) => {
3801
3935
  try {
3802
- return advertiseIntentParamsRequired(result, names, isInjected);
3936
+ const served = listsOwnReportTool || ctx.annotationToolName === "" ? result : withToolInputSchema(result, ctx.annotationToolName, annotationInputJsonSchema(lowLevelMajor(lowLevel)));
3937
+ return advertiseIntentParamsRequired(served, names, isInjected);
3803
3938
  } catch (err) {
3804
- process.stderr.write(
3805
- `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}
3806
- `
3939
+ stderrLine(
3940
+ `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}`
3807
3941
  );
3808
3942
  return result;
3809
3943
  }
@@ -3813,6 +3947,177 @@ function installToolsListSeam(lowLevel, ctx) {
3813
3947
  return isThenable(out) ? out.then(advertise) : advertise(out);
3814
3948
  });
3815
3949
  }
3950
+ var LOW_LEVEL_LIST_SEAM = /* @__PURE__ */ Symbol("batonLowLevelListSeam");
3951
+ var LOW_LEVEL_CALL_SEAM = /* @__PURE__ */ Symbol("batonLowLevelCallSeam");
3952
+ var LOW_LEVEL_HANDSHAKE_SEAM = /* @__PURE__ */ Symbol("batonLowLevelHandshakeSeam");
3953
+ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce2, reportToolTaken) {
3954
+ let reportTool2 = annotationTool;
3955
+ const listedReportTool = reportTool2 && {
3956
+ name: reportTool2.name,
3957
+ description: reportTool2.description,
3958
+ inputSchema: annotationInputJsonSchema(lowLevelMajor(lowLevel))
3959
+ };
3960
+ const skipTool = (name, err) => {
3961
+ known.unread.add(name);
3962
+ warnOnce2(
3963
+ `tool-unread:${name}`,
3964
+ `baton: could not read tool ${JSON.stringify(name)}; its calls keep user_goal until Baton can read it: ${printable(err)}`
3965
+ );
3966
+ };
3967
+ const skipNote = (name, err) => {
3968
+ if (known.unread.has(name)) return;
3969
+ warnOnce2(`tool-unnoted:${name}`, `baton: could not note tool ${JSON.stringify(name)}; Baton adds no user_goal to it: ${printable(err)}`);
3970
+ };
3971
+ const keepGoalIfDeclared = (tools) => {
3972
+ for (const { name, inputSchema: inputSchema2 } of tools) {
3973
+ try {
3974
+ const checked = known.served.get(name)?.inputSchema === inputSchema2 && !known.unread.has(name);
3975
+ if (!known.keepsGoal.has(name) && !checked) {
3976
+ const declares = isRecord(inputSchema2) && takesUserGoalJson(inputSchema2) ? declaresParam : mayDeclareParam;
3977
+ if (declares(inputSchema2, USER_GOAL_PARAM_NAME)) known.keepsGoal.add(name);
3978
+ }
3979
+ known.unread.delete(name);
3980
+ } catch (err) {
3981
+ skipTool(name, err);
3982
+ }
3983
+ }
3984
+ };
3985
+ const read = (tools, { surface }) => {
3986
+ if (surface && reportTool2 !== void 0 && tools.some((tool) => tool.name === reportTool2?.name)) {
3987
+ warnOnce2(
3988
+ "report-tool-name-taken",
3989
+ `baton: the server lists its own tool ${JSON.stringify(reportTool2.name)}, so Baton's report tool is not added; set annotationToolName to another name`
3990
+ );
3991
+ reportTool2 = void 0;
3992
+ ctx.annotationToolName = "";
3993
+ reportToolTaken();
3994
+ }
3995
+ readToolList(tools, ctx, surface, skipNote);
3996
+ };
3997
+ const learn = (tools) => {
3998
+ keepGoalIfDeclared(tools);
3999
+ for (const tool of tools) {
4000
+ const held = known.served.get(tool.name);
4001
+ const ownGoal = (info) => declaresParam(info?.inputSchema, USER_GOAL_PARAM_NAME);
4002
+ if (held === void 0 || !ownGoal(held) || ownGoal(tool)) known.served.set(tool.name, tool);
4003
+ }
4004
+ };
4005
+ let caughtUp = false;
4006
+ const catchUp = () => {
4007
+ if (caughtUp) return;
4008
+ caughtUp = true;
4009
+ if (known.given !== void 0) {
4010
+ const given = known.given;
4011
+ known.given = void 0;
4012
+ try {
4013
+ const tools = typeof given === "function" ? given() : given;
4014
+ if (!Array.isArray(tools)) throw new Error("it is not an array of tools");
4015
+ known.givenTools = toolInfos(tools, skipTool);
4016
+ keepGoalIfDeclared(known.givenTools);
4017
+ } catch (err) {
4018
+ warnOnce2(
4019
+ "tools-unread",
4020
+ `baton: could not read the tools option; Baton learns the tools from tools/list: ${printable(err)}`
4021
+ );
4022
+ }
4023
+ }
4024
+ read(known.givenTools, { surface: true });
4025
+ read([...known.served.values()], { surface: false });
4026
+ };
4027
+ installRequestSeam(lowLevel, TOOLS_LIST_METHOD, LOW_LEVEL_LIST_SEAM, (handler) => async (...args) => {
4028
+ catchUp();
4029
+ const result = await handler(...args);
4030
+ try {
4031
+ const listed = listedTools(result);
4032
+ if (listed === null) return result;
4033
+ const tools = toolInfos(listed, skipTool);
4034
+ learn(tools);
4035
+ read(tools, { surface: true });
4036
+ const firstPage = args[0]?.params?.cursor === void 0;
4037
+ return servedToolList(result, listed, ctx, firstPage && reportTool2 ? listedReportTool : void 0);
4038
+ } catch (err) {
4039
+ stderrLine(`baton: tools/list capture failed; serving the vendor's own result: ${printable(err)}`);
4040
+ return result;
4041
+ }
4042
+ });
4043
+ const readFirst = (handler) => (...args) => {
4044
+ catchUp();
4045
+ return handler(...args);
4046
+ };
4047
+ installRequestSeam(lowLevel, "initialize", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);
4048
+ installRequestSeam(lowLevel, "server/discover", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);
4049
+ installRequestSeam(lowLevel, TOOLS_CALL_METHOD, LOW_LEVEL_CALL_SEAM, (handler) => async (...args) => {
4050
+ catchUp();
4051
+ ctx.perCaller?.followSettings();
4052
+ const request = args[0];
4053
+ const name = request?.params?.name;
4054
+ if (typeof name !== "string") return handler(...args);
4055
+ if (name === reportTool2?.name) return callAnnotationTool(reportTool2, request?.params?.arguments, args[1]);
4056
+ const injected = ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected";
4057
+ const unlisted = injected ? "warn" : known.keepsGoal.has(name) || known.unread.has(name) ? "leave" : "goalOnly";
4058
+ const params = request?.params?.arguments;
4059
+ const toolArgs = isRecord(params) ? params : {};
4060
+ if (unlisted === "goalOnly" && USER_GOAL_PARAM_NAME in toolArgs && !known.served.has(name) && !known.givenTools.some((tool) => tool.name === name)) {
4061
+ warnOnce2(
4062
+ "user-goal-unlisted",
4063
+ `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`
4064
+ );
4065
+ }
4066
+ if (request?.params?.task !== void 0) {
4067
+ if (injected) stripIntentParams(request.params, ctx);
4068
+ else extractGoalParam(toolArgs, USER_GOAL_PARAM_NAME, name, ctx.paramRegistry.get(name), unlisted);
4069
+ return handler(...args);
4070
+ }
4071
+ return batonWrap({ current: name }, () => handler(...args), ctx, unlisted)(toolArgs, args[1]);
4072
+ });
4073
+ }
4074
+ function lowLevelMajor(lowLevel) {
4075
+ return typeof lowLevel._wrapHandler === "function" ? 2 : 1;
4076
+ }
4077
+ function listedTools(result) {
4078
+ return isRecord(result) && Array.isArray(result.tools) ? result.tools : null;
4079
+ }
4080
+ function toolInfos(tools, skip) {
4081
+ const infos = [];
4082
+ for (const tool of tools) {
4083
+ let name;
4084
+ try {
4085
+ name = isRecord(tool) ? tool.name : void 0;
4086
+ if (typeof name !== "string") continue;
4087
+ infos.push({ name, description: tool.description, inputSchema: tool.inputSchema });
4088
+ } catch (err) {
4089
+ if (typeof name === "string") skip(name, err);
4090
+ }
4091
+ }
4092
+ return infos;
4093
+ }
4094
+ function readToolList(tools, ctx, surface, skip) {
4095
+ for (const { name, inputSchema: inputSchema2, description } of tools) {
4096
+ try {
4097
+ const schema = isRecord(inputSchema2) ? inputSchema2 : null;
4098
+ if (surface) {
4099
+ ctx.surfaceState.noteTool(name, schema ?? EMPTY_OBJECT_JSON_SCHEMA, typeof description === "string" ? description : void 0);
4100
+ }
4101
+ const dispositions = declaredIntentParams(schema);
4102
+ if (dispositions[USER_GOAL_PARAM_NAME] === "native") ctx.dropSubagentClause(name);
4103
+ else if (schema !== null && takesUserGoalJson(schema)) dispositions[USER_GOAL_PARAM_NAME] = "injected";
4104
+ if (Object.keys(dispositions).length > 0) ctx.paramRegistry.set(name, dispositions);
4105
+ else ctx.paramRegistry.delete(name);
4106
+ } catch (err) {
4107
+ ctx.paramRegistry.delete(name);
4108
+ skip(name, err);
4109
+ }
4110
+ }
4111
+ }
4112
+ function servedToolList(result, listed, ctx, reportTool2) {
4113
+ const tools = listed.map((tool) => {
4114
+ if (!isRecord(tool) || typeof tool.name !== "string") return tool;
4115
+ if (ctx.paramRegistry.get(tool.name)?.[USER_GOAL_PARAM_NAME] !== "injected") return tool;
4116
+ return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, ctx.intentParamMode, false) };
4117
+ });
4118
+ if (reportTool2 !== void 0) tools.push(reportTool2);
4119
+ return { ...result, tools };
4120
+ }
3816
4121
  var LIFECYCLE_SEAMS = {
3817
4122
  resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
3818
4123
  resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
@@ -3891,8 +4196,7 @@ async function openLifecycleCall(ctx, spec, requestParams, extra) {
3891
4196
  }
3892
4197
  };
3893
4198
  } catch (err) {
3894
- process.stderr.write(`baton: ${spec.method} capture failed: ${String(err)}
3895
- `);
4199
+ stderrLine(`baton: ${spec.method} capture failed: ${String(err)}`);
3896
4200
  return null;
3897
4201
  }
3898
4202
  }
@@ -4068,8 +4372,7 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
4068
4372
  await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
4069
4373
  } catch (err) {
4070
4374
  PROCESS_DROPS.add("encode_failed");
4071
- process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
4072
- `);
4375
+ stderrLine(`baton: settling a tool call failed; events dropped: ${String(err)}`);
4073
4376
  }
4074
4377
  }
4075
4378
  async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
@@ -4086,7 +4389,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
4086
4389
  args[1],
4087
4390
  params,
4088
4391
  slot.stripped,
4089
- entry != null
4392
+ entry != null ? "warn" : "quiet"
4090
4393
  );
4091
4394
  const failureKind = requestSideFailureKind(entry, slot.validation);
4092
4395
  const text = () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result);
@@ -4260,27 +4563,34 @@ function createBaton(supplied = {}) {
4260
4563
  function inertHandle(sink, sessionId) {
4261
4564
  return new BatonHandle({ sink, sessionId, vendorId: "", annotationToolName: "" });
4262
4565
  }
4263
- function requireHighLevelServer(server) {
4566
+ function serverShapeOf(server) {
4264
4567
  const candidate = server;
4265
- if (typeof candidate?.registerTool !== "function" || typeof candidate.server !== "object" || candidate.server === null) {
4266
- throw new TypeError(
4267
- "Baton needs a high-level McpServer (from @modelcontextprotocol/sdk/server/mcp.js or @modelcontextprotocol/server); the low-level Server is not supported."
4268
- );
4568
+ if (typeof candidate?.registerTool === "function" && typeof candidate.server === "object" && candidate.server !== null) {
4569
+ return "mcpServer";
4269
4570
  }
4571
+ const isServer = typeof candidate?._serverInfo === "object" && candidate._serverInfo !== null;
4572
+ if (typeof candidate?.setRequestHandler === "function" && candidate._requestHandlers instanceof Map && isServer) {
4573
+ return "lowLevel";
4574
+ }
4575
+ throw new TypeError(
4576
+ "Baton needs an McpServer or a low-level Server, from @modelcontextprotocol/sdk or @modelcontextprotocol/server."
4577
+ );
4270
4578
  }
4271
4579
  function newBatonState(config) {
4272
4580
  return {
4273
4581
  sentSurfaces: new SentSurfaces(),
4274
4582
  warned: /* @__PURE__ */ new Set(),
4275
4583
  counter: new SessionCounter(),
4276
- scrubber: config.scrubber ?? new Scrubber().scrub
4584
+ scrubber: config.scrubber ?? new Scrubber().scrub,
4585
+ lowLevelTools: { given: config.tools, givenTools: [], served: /* @__PURE__ */ new Map(), keepsGoal: /* @__PURE__ */ new Set(), unread: /* @__PURE__ */ new Set() }
4277
4586
  };
4278
4587
  }
4279
- function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber }, unconfigured) {
4280
- requireHighLevelServer(server);
4588
+ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber, lowLevelTools }, unconfigured) {
4589
+ const shape = serverShapeOf(server);
4281
4590
  const internals = server;
4591
+ const lowLevel = shape === "mcpServer" ? internals.server : server;
4282
4592
  const serverName = usableServerName(() => ({
4283
- name: internals.server._serverInfo?.name,
4593
+ name: lowLevel._serverInfo?.name,
4284
4594
  className: internals.constructor.name
4285
4595
  }));
4286
4596
  const config = resolved.reportMode === "on" ? withServerDisplayName(resolved, supplied, serverName) : resolved;
@@ -4288,13 +4598,18 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4288
4598
  const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
4289
4599
  const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
4290
4600
  if (unconfigured) return inertHandle(new DisabledSink(), "baton-unconfigured");
4601
+ if (shape === "mcpServer" && reports && internals._registeredTools?.[annotationToolName]) {
4602
+ throw new Error(
4603
+ `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.`
4604
+ );
4605
+ }
4291
4606
  const given = config.sink ?? new StdoutSink();
4292
4607
  const sink = offTheCall(given);
4293
4608
  const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
4294
4609
  const fallbackSessionId = `sdk-${uuid7()}`;
4295
4610
  const counter2 = new ServerCounter(sharedCounter, fallbackSessionId);
4296
4611
  const tenantId = resolveTenantId(config.tenantId, config.vendorId);
4297
- const serverMeta = buildServerMeta(server.server);
4612
+ const serverMeta = buildServerMeta(lowLevel);
4298
4613
  const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
4299
4614
  const emitSurface = async (sessionId, digest, snapshot) => {
4300
4615
  await emit(
@@ -4325,42 +4640,37 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4325
4640
  const warnOnce2 = (key, message) => {
4326
4641
  if (warned3.has(key)) return;
4327
4642
  warned3.add(key);
4328
- process.stderr.write(message);
4643
+ stderrLine(message);
4329
4644
  };
4330
4645
  const dropSubagentClause = (name) => {
4331
- const current2 = internals.server._instructions;
4646
+ const current2 = lowLevel._instructions;
4332
4647
  if (current2 === INTENT_INSTRUCTIONS) {
4333
- internals.server._instructions = "";
4648
+ lowLevel._instructions = "";
4334
4649
  } else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
4335
- internals.server._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
4650
+ lowLevel._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
4336
4651
  } else {
4337
4652
  return;
4338
4653
  }
4339
4654
  warnOnce2(
4340
4655
  "native-user-goal",
4341
- `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
4342
- `
4656
+ `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`
4343
4657
  );
4344
4658
  };
4345
4659
  const isV2Server = typeof internals.toolInputSchemaJson === "function";
4346
4660
  const vendorToolJsonSchema = (name, inputSchema2) => {
4347
4661
  if (isV2Server) {
4348
4662
  try {
4349
- const json = internals.toolInputSchemaJson(name);
4350
- if (json) return json;
4351
- } catch {
4352
- }
4353
- try {
4354
- const standard = inputSchema2?.["~standard"];
4355
- const json = standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
4356
- if (json) return json;
4663
+ const json2 = internals.toolInputSchemaJson(name);
4664
+ if (json2) return json2;
4357
4665
  } catch {
4358
4666
  }
4667
+ const json = standardInputJsonSchema(inputSchema2);
4668
+ if (json) return json;
4359
4669
  }
4360
4670
  try {
4361
4671
  return toolInputJsonSchema(inputSchema2);
4362
4672
  } catch {
4363
- return { type: "object", properties: {} };
4673
+ return EMPTY_OBJECT_JSON_SCHEMA;
4364
4674
  }
4365
4675
  };
4366
4676
  installValidationProbe(server);
@@ -4383,51 +4693,38 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4383
4693
  vendorToolJsonSchema,
4384
4694
  bustSchemaMemo,
4385
4695
  dropSubagentClause,
4386
- servedInstructions: () => internals.server._instructions,
4696
+ servedInstructions: () => lowLevel._instructions,
4387
4697
  surfaceState,
4388
4698
  emitSurface
4389
4699
  };
4390
4700
  const writeInstructions = (text) => {
4391
- internals.server._instructions = withVendorInstructions(
4392
- internals.server,
4701
+ lowLevel._instructions = withVendorInstructions(
4702
+ lowLevel,
4393
4703
  text,
4394
4704
  (message) => warnOnce2("instructions-length", message)
4395
4705
  );
4396
4706
  };
4397
4707
  writeInstructions(ours);
4708
+ const rewriteInstructions = (text) => {
4709
+ writeInstructions(text);
4710
+ const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === "native");
4711
+ if (native !== void 0) dropSubagentClause(native[0]);
4712
+ };
4398
4713
  if (config.captureSettings !== void 0) {
4399
4714
  ctx.perCaller = new PerCallerSurface({
4400
4715
  settings: config.captureSettings,
4401
4716
  intentParamMode,
4402
- annotationToolName,
4403
- instructions: ours,
4404
- writeInstructions: (text) => {
4405
- writeInstructions(text);
4406
- const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === "native");
4407
- if (native !== void 0) dropSubagentClause(native[0]);
4717
+ // Read, not copied: a low-level Server's own tool can take the name.
4718
+ get annotationToolName() {
4719
+ return ctx.annotationToolName;
4408
4720
  },
4721
+ instructions: ours,
4722
+ writeInstructions: rewriteInstructions,
4409
4723
  injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
4410
4724
  });
4411
4725
  ctx.perCaller.followSettings();
4412
4726
  }
4413
- installToolsListSeam(internals.server, ctx);
4414
- installToolsCallSeam(
4415
- internals.server,
4416
- // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
4417
- // object, so `registry["constructor"]` answers `Object` and
4418
- // `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
4419
- // so the "a tool we did not wrap" guard would decline to report, and a
4420
- // caller-visible `Tool constructor disabled` would reach the client with
4421
- // this seam silent. An agent hallucinating a prototype-shaped tool name is
4422
- // exactly the kind of failure the seam exists to make visible.
4423
- (name) => {
4424
- const registry = internals._registeredTools;
4425
- return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
4426
- },
4427
- ctx
4428
- );
4429
- installLifecycleSeams(internals.server, ctx);
4430
- const resolvedAnnotationToolName = !reports ? "" : registerAnnotationTool(server, {
4727
+ const annotationOptions = !reports ? void 0 : {
4431
4728
  sink,
4432
4729
  counter: ctx.counter,
4433
4730
  tenantId: ctx.tenantId,
@@ -4442,7 +4739,43 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4442
4739
  // raw override and letting the registration re-derive would register
4443
4740
  // `srv-..._annotate` while the instructions name the server-derived one.
4444
4741
  annotationToolName
4742
+ };
4743
+ if (shape === "lowLevel") {
4744
+ installLowLevelToolSeams(
4745
+ lowLevel,
4746
+ ctx,
4747
+ annotationOptions && buildAnnotationTool(server, annotationOptions),
4748
+ lowLevelTools,
4749
+ warnOnce2,
4750
+ () => rewriteInstructions(INTENT_INSTRUCTIONS)
4751
+ );
4752
+ }
4753
+ installToolsListSeam(lowLevel, ctx, shape === "lowLevel");
4754
+ if (shape === "mcpServer") installToolsCallSeam(
4755
+ lowLevel,
4756
+ // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
4757
+ // object, so `registry["constructor"]` answers `Object` and
4758
+ // `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
4759
+ // so the "a tool we did not wrap" guard would decline to report, and a
4760
+ // caller-visible `Tool constructor disabled` would reach the client with
4761
+ // this seam silent. An agent hallucinating a prototype-shaped tool name is
4762
+ // exactly the kind of failure the seam exists to make visible.
4763
+ (name) => {
4764
+ const registry = internals._registeredTools;
4765
+ return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
4766
+ },
4767
+ ctx
4768
+ );
4769
+ installLifecycleSeams(lowLevel, ctx);
4770
+ const handle = (name) => new BatonHandle({
4771
+ sink: given,
4772
+ queue: sink,
4773
+ vendorId: config.vendorId,
4774
+ sessionId: fallbackSessionId,
4775
+ annotationToolName: name
4445
4776
  });
4777
+ if (shape === "lowLevel") return handle(annotationToolName);
4778
+ const resolvedAnnotationToolName = annotationOptions ? registerAnnotationTool(server, annotationOptions) : "";
4446
4779
  const existing = internals._registeredTools;
4447
4780
  if (existing) {
4448
4781
  for (const [name, entry] of Object.entries(existing)) {
@@ -4455,13 +4788,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4455
4788
  wireEntry(String(args[0]), registered, ctx);
4456
4789
  return registered;
4457
4790
  };
4458
- return new BatonHandle({
4459
- sink: given,
4460
- queue: sink,
4461
- vendorId: config.vendorId,
4462
- sessionId: fallbackSessionId,
4463
- annotationToolName: resolvedAnnotationToolName
4464
- });
4791
+ return handle(resolvedAnnotationToolName);
4465
4792
  }
4466
4793
  function reportsFor(config) {
4467
4794
  if (config.reportMode !== "on") return void 0;
@@ -4469,9 +4796,8 @@ function reportsFor(config) {
4469
4796
  }
4470
4797
  function warnAboutSettings(config) {
4471
4798
  if (config.reportMode !== "on" && config.annotationToolName !== void 0) {
4472
- process.stderr.write(
4473
- `baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered
4474
- `
4799
+ stderrLine(
4800
+ `baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered`
4475
4801
  );
4476
4802
  }
4477
4803
  if (config.resultCaptureMode === WITHHELD) {
@@ -4513,7 +4839,7 @@ function principalFromOAuthEmail(context) {
4513
4839
  }
4514
4840
 
4515
4841
  // src/library/session.ts
4516
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
4842
+ import * as asyncHooks2 from "async_hooks";
4517
4843
  var TRANSPORT_LIBRARY = "library";
4518
4844
  var TURN_ID_META_KEY = "baton/turn_id";
4519
4845
  function sessionEnvelope(session) {
@@ -4529,8 +4855,7 @@ function sessionEnvelope(session) {
4529
4855
  };
4530
4856
  }
4531
4857
  function warn2(message) {
4532
- process.stderr.write(`baton: ${message}
4533
- `);
4858
+ stderrLine(`baton: ${message}`);
4534
4859
  }
4535
4860
  function vendorId(name, value) {
4536
4861
  const cleaned = typeof value === "string" ? stripWhiteSpace(value) : "";
@@ -4567,7 +4892,7 @@ function newSession(values, scrubber, disabled) {
4567
4892
  runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
4568
4893
  };
4569
4894
  }
4570
- var current = new AsyncLocalStorage2();
4895
+ var current = new asyncHooks2.AsyncLocalStorage();
4571
4896
  function runInSession(owner, session, fn) {
4572
4897
  return current.run({ owner, session }, fn);
4573
4898
  }
@@ -4582,8 +4907,7 @@ function serveTools(tools, options) {
4582
4907
  try {
4583
4908
  served = tools.map(servedEntry);
4584
4909
  } catch (err) {
4585
- process.stderr.write(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}
4586
- `);
4910
+ stderrLine(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}`);
4587
4911
  return { served: tools, surface: null };
4588
4912
  }
4589
4913
  try {
@@ -4602,8 +4926,7 @@ function serveTools(tools, options) {
4602
4926
  );
4603
4927
  return { served, surface: { surface, digest: surfaceHash(surface) } };
4604
4928
  } catch (err) {
4605
- process.stderr.write(`baton: surface snapshot capture failed: ${printable(err)}
4606
- `);
4929
+ stderrLine(`baton: surface snapshot capture failed: ${printable(err)}`);
4607
4930
  return { served, surface: null };
4608
4931
  }
4609
4932
  }
@@ -4621,25 +4944,8 @@ function snapshotPayload({ surface, digest }) {
4621
4944
  };
4622
4945
  }
4623
4946
  function servedEntry(tool) {
4624
- if (!isRecord(tool)) return tool;
4625
- const entry = { ...tool };
4626
- if (isRecord(entry.inputSchema)) {
4627
- const schema = { ...entry.inputSchema };
4628
- if (isRecord(schema.properties)) schema.properties = { ...schema.properties };
4629
- injectGoalParam(schema);
4630
- entry.inputSchema = schema;
4631
- }
4632
- return entry;
4633
- }
4634
- function injectGoalParam(schema) {
4635
- if (schema.properties === void 0) schema.properties = {};
4636
- if (!isRecord(schema.properties) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return;
4637
- schema.properties[USER_GOAL_PARAM_NAME] = {
4638
- type: "string",
4639
- description: buildUserGoalParamDescription({ intentParamMode: DEFAULT_INTENT_PARAM_MODE })
4640
- };
4641
- const required = Array.isArray(schema.required) ? schema.required : [];
4642
- if (!required.includes(USER_GOAL_PARAM_NAME)) schema.required = [...required, USER_GOAL_PARAM_NAME];
4947
+ if (!isRecord(tool) || !isRecord(tool.inputSchema)) return tool;
4948
+ return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, DEFAULT_INTENT_PARAM_MODE, true) };
4643
4949
  }
4644
4950
 
4645
4951
  // src/library/client.ts
@@ -4784,8 +5090,7 @@ var Core = class {
4784
5090
  });
4785
5091
  } catch (err) {
4786
5092
  PROCESS_DROPS.add("encode_failed");
4787
- process.stderr.write(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}
4788
- `);
5093
+ stderrLine(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}`);
4789
5094
  return Promise.resolve();
4790
5095
  }
4791
5096
  return safeWrite(this.sink, event);
@@ -4843,7 +5148,7 @@ var Trace = class _Trace {
4843
5148
  observed(result, failure) {
4844
5149
  if ((this.#result !== UNSET || this.#error !== null) && !this.#observedWarned) {
4845
5150
  this.#observedWarned = true;
4846
- process.stderr.write("baton: Trace.observed() called more than once; the last call wins.\n");
5151
+ stderrLine("baton: Trace.observed() called more than once; the last call wins.");
4847
5152
  }
4848
5153
  this.#result = UNSET;
4849
5154
  this.#error = null;
@@ -4863,8 +5168,7 @@ var Trace = class _Trace {
4863
5168
  try {
4864
5169
  this.#result = this.#core.scrubber(result);
4865
5170
  } catch (err) {
4866
- process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}
4867
- `);
5171
+ stderrLine(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}`);
4868
5172
  this.#result = SCRUB_FAILED;
4869
5173
  }
4870
5174
  }
@@ -5010,8 +5314,7 @@ var Client = class {
5010
5314
  try {
5011
5315
  block = newSession(options, this.#core.scrubber, this.#core.disabled);
5012
5316
  } catch (err) {
5013
- process.stderr.write(`baton: session values could not be read; using a minted session: ${printable(err)}
5014
- `);
5317
+ stderrLine(`baton: session values could not be read; using a minted session: ${printable(err)}`);
5015
5318
  block = newSession({}, this.#core.scrubber, this.#core.disabled);
5016
5319
  }
5017
5320
  return runInSession(this, block, fn);