@goodtiming/baton-sdk 1.1.0 → 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.1.0";
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) {
@@ -389,13 +389,49 @@ function onWorkers() {
389
389
  return typeof globalThis.WebSocketPair === "function" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
390
390
  }
391
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
+ }
392
407
 
393
408
  // src/warn.ts
394
409
  function warn(message) {
395
410
  if (onWorkers()) {
396
411
  console.warn(message);
397
- } else if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
398
- process.emitWarning(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
+ }
399
435
  }
400
436
  }
401
437
  function printable(err) {
@@ -525,8 +561,8 @@ function identityScrub(value) {
525
561
  }
526
562
 
527
563
  // src/sinks.ts
528
- import { appendFileSync } from "fs";
529
- import { open } from "fs/promises";
564
+ import * as fs from "fs";
565
+ import * as fsp from "fs/promises";
530
566
 
531
567
  // src/_text.ts
532
568
  var WHITE_SPACE = /^\p{White_Space}$/u;
@@ -648,14 +684,9 @@ async function safeWrite(sink, event) {
648
684
  } catch (err) {
649
685
  if (isSinkClosed(err)) return droppedAfterClose(sink);
650
686
  PROCESS_DROPS.add("write_failed");
651
- process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}
652
- `);
687
+ stderrLine(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}`);
653
688
  }
654
689
  }
655
- function stderrLine(message) {
656
- process.stderr.write(`${message}
657
- `);
658
- }
659
690
  function isTimerMs(value) {
660
691
  return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
661
692
  }
@@ -695,11 +726,13 @@ var StdoutSink = class {
695
726
  stream;
696
727
  closed = false;
697
728
  constructor(options = {}) {
698
- this.stream = options.stream ?? process.stderr;
729
+ this.stream = options.stream;
699
730
  }
700
731
  async write(event) {
701
732
  if (this.closed) throw new SinkClosedError("StdoutSink is closed");
702
- 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);
703
736
  }
704
737
  async flush() {
705
738
  }
@@ -721,7 +754,7 @@ var FileSink = class {
721
754
  if (this.closed) throw new SinkClosedError("FileSink is closed");
722
755
  const line = JSON.stringify(event) + "\n";
723
756
  const written = this.last.then(async () => {
724
- this.file ??= await open(this.path, "a");
757
+ this.file ??= await fsp.open(this.path, "a");
725
758
  await this.file.appendFile(line);
726
759
  });
727
760
  this.last = written.catch(() => void 0);
@@ -778,30 +811,31 @@ var later = (run) => {
778
811
  else setTimeout(run, 0);
779
812
  };
780
813
  var withUnwrittenEvents = /* @__PURE__ */ new Set();
781
- var exitHooked = false;
814
+ var exitTriedOn = /* @__PURE__ */ new WeakSet();
782
815
  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
- }
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
+ });
796
827
  }
797
828
  function writeNow(sink, events) {
798
- 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("");
799
831
  if (sink instanceof StdoutSink) {
800
832
  const stream = sink["stream"];
801
- if (stream !== process.stdout && stream !== process.stderr) return false;
802
- 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());
803
837
  } else if (sink instanceof FileSink) {
804
- if (!sink["closed"]) appendFileSync(sink["path"], lines);
838
+ if (!sink["closed"]) fs.appendFileSync(sink["path"], lines());
805
839
  } else return false;
806
840
  return true;
807
841
  }
@@ -1059,6 +1093,8 @@ var HttpSink = class _HttpSink {
1059
1093
  /** Set for the life of the sink by a 404 or 405 on the batch path. */
1060
1094
  batchless = false;
1061
1095
  exitHooks = null;
1096
+ /** The `process` the exit hooks were last tried on, so a refusal is not retried per write. */
1097
+ exitHooksTriedOn;
1062
1098
  /** The least time between two of this sink's loss reports. */
1063
1099
  static reportIntervalMs = 6e4;
1064
1100
  /** Totals only grow, so their sum tells whether they changed. */
@@ -1156,11 +1192,8 @@ var HttpSink = class _HttpSink {
1156
1192
  warn(`baton: the sink closed with ${unsent} event(s) unsent.`);
1157
1193
  }
1158
1194
  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
- }
1195
+ this.exitHooks?.off();
1196
+ this.exitHooks = null;
1164
1197
  }
1165
1198
  /** SPEC §11.2 rule 7: an explicit flush or close returns within `ms` and
1166
1199
  * never rejects. While an earlier wait's drain is still stuck, a flush
@@ -1254,7 +1287,9 @@ var HttpSink = class _HttpSink {
1254
1287
  * both hooks: a vendor needing that guarantee must call `aclose()` from
1255
1288
  * their own handler. */
1256
1289
  ensureExitHooksRegistered() {
1257
- 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;
1258
1293
  const beforeExit = () => {
1259
1294
  if (this.unsent === 0 || this.exitPassRan) {
1260
1295
  this.warnUnloggedRefusals("process exiting");
@@ -1272,9 +1307,14 @@ var HttpSink = class _HttpSink {
1272
1307
  } catch {
1273
1308
  }
1274
1309
  };
1275
- this.exitHooks = { beforeExit, exit };
1276
- process.on("beforeExit", beforeExit);
1277
- 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()) };
1278
1318
  }
1279
1319
  /** One attempt per batch, no retry, within `shutdownFlushTimeoutMs` in
1280
1320
  * total (SPEC §11.2); what is left is reported, not sent. */
@@ -1655,7 +1695,7 @@ var HttpSink = class _HttpSink {
1655
1695
  };
1656
1696
 
1657
1697
  // src/integrations/mcp/withBaton.ts
1658
- import { AsyncLocalStorage } from "async_hooks";
1698
+ import * as asyncHooks from "async_hooks";
1659
1699
 
1660
1700
  // src/integrations/mcp/annotation.ts
1661
1701
  import { z as z2 } from "zod";
@@ -1798,7 +1838,7 @@ function endsInOurs(current2, vendor) {
1798
1838
  const rest = current2.slice(prefix.length);
1799
1839
  return OURS_STARTS.some((start) => start.test(rest));
1800
1840
  }
1801
- function withVendorInstructions(server, ours, warn3 = (message) => process.stderr.write(message)) {
1841
+ function withVendorInstructions(server, ours, warn3 = stderrLine) {
1802
1842
  const holder = server;
1803
1843
  const current2 = holder._instructions;
1804
1844
  let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
@@ -1812,8 +1852,7 @@ function withVendorInstructions(server, ours, warn3 = (message) => process.stder
1812
1852
  ${ours}`;
1813
1853
  if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
1814
1854
  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
- `
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`
1817
1856
  );
1818
1857
  }
1819
1858
  return combined;
@@ -1920,8 +1959,7 @@ async function emit(sink, build) {
1920
1959
  event = build();
1921
1960
  } catch (err) {
1922
1961
  PROCESS_DROPS.add("encode_failed");
1923
- process.stderr.write(`baton: event construction failed; event dropped: ${printable(err)}
1924
- `);
1962
+ stderrLine(`baton: event construction failed; event dropped: ${printable(err)}`);
1925
1963
  return;
1926
1964
  }
1927
1965
  await safeWrite(sink, event);
@@ -2335,6 +2373,15 @@ function advertiseIntentParamsRequired(result, names, isInjected) {
2335
2373
  });
2336
2374
  return changed ? { ...result, tools: advertised } : result;
2337
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
+ }
2338
2385
  function standardInputJsonSchema(schema) {
2339
2386
  try {
2340
2387
  const standard = schema?.["~standard"];
@@ -2361,9 +2408,8 @@ function scrubOrNull(scrubber, value, field) {
2361
2408
  } catch (err) {
2362
2409
  if (!warned2.has(field)) {
2363
2410
  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
- `
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)}`
2367
2413
  );
2368
2414
  }
2369
2415
  return null;
@@ -2498,7 +2544,8 @@ var ANNOTATION_INPUT_SHAPE = {
2498
2544
  // not rejected by validation.
2499
2545
  tool_name: z2.string().nullable().optional(),
2500
2546
  suggested_improvement: z2.string().optional(),
2501
- 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()
2502
2549
  };
2503
2550
  function isReport(whatHappened) {
2504
2551
  return typeof whatHappened === "string" && !isBlank(whatHappened);
@@ -2869,7 +2916,7 @@ function scrubbedErrorBody(scrubber, text) {
2869
2916
  }
2870
2917
 
2871
2918
  // src/integrations/mcp/captureSettings.ts
2872
- import { createHash } from "crypto";
2919
+ import * as crypto2 from "crypto";
2873
2920
  var SETTINGS_PATH = "/v0/settings";
2874
2921
  var TENANT_HEADER = "X-Baton-Tenant-Id";
2875
2922
  var SETTINGS_MODES = ["local", "console"];
@@ -2881,7 +2928,7 @@ var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
2881
2928
  var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
2882
2929
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
2883
2930
  function shareBucket(vendorId2, key) {
2884
- const digest = createHash("sha256").update(`${vendorId2}
2931
+ const digest = crypto2.createHash("sha256").update(`${vendorId2}
2885
2932
  ${key}`, "utf-8").digest();
2886
2933
  return Number(digest.readBigUInt64BE(0) % 10000n);
2887
2934
  }
@@ -3340,8 +3387,7 @@ var PerCallerSurface = class {
3340
3387
  this.options.writeInstructions(pointerOn ? this.options.instructions : INTENT_INSTRUCTIONS);
3341
3388
  this.pointerOn = pointerOn;
3342
3389
  } catch (err) {
3343
- process.stderr.write(`baton: could not update the server instructions for new settings: ${printable(err)}
3344
- `);
3390
+ stderrLine(`baton: could not update the server instructions for new settings: ${printable(err)}`);
3345
3391
  }
3346
3392
  }
3347
3393
  /** `result` with the caller's goal and reports settings; as served on any failure. */
@@ -3364,8 +3410,7 @@ var PerCallerSurface = class {
3364
3410
  }
3365
3411
  return { ...result, tools: served };
3366
3412
  } catch (err) {
3367
- process.stderr.write(`baton: could not apply capture settings to the tool list: ${printable(err)}
3368
- `);
3413
+ stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
3369
3414
  return result;
3370
3415
  }
3371
3416
  }
@@ -3424,10 +3469,10 @@ var ServerCounter = class extends SessionCounter {
3424
3469
  };
3425
3470
 
3426
3471
  // src/integrations/mcp/surface.ts
3427
- import { createHash as createHash2 } from "crypto";
3472
+ import * as crypto3 from "crypto";
3428
3473
  function surfaceHash(surface) {
3429
3474
  const canonical = canonicalJson(surface);
3430
- const digest = createHash2("sha256").update(canonical, "utf-8").digest("hex");
3475
+ const digest = crypto3.createHash("sha256").update(canonical, "utf-8").digest("hex");
3431
3476
  return `sha256:${digest}`;
3432
3477
  }
3433
3478
  function canonicalJson(value) {
@@ -3489,7 +3534,7 @@ var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
3489
3534
  var wired = /* @__PURE__ */ new WeakSet();
3490
3535
  var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
3491
3536
  var INTENT_PARAM_NAMES = [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES];
3492
- var callSlots = new AsyncLocalStorage();
3537
+ var callSlots = new asyncHooks.AsyncLocalStorage();
3493
3538
  var SurfaceState = class {
3494
3539
  constructor(serverMeta, sentSurfaces) {
3495
3540
  this.serverMeta = serverMeta;
@@ -3780,9 +3825,8 @@ function extractGoalParam(args, paramName, toolName, dispositions, unlisted) {
3780
3825
  if (disposition === "native") return null;
3781
3826
  if (disposition === void 0 && unlisted === "leave") return null;
3782
3827
  if (disposition === void 0 && unlisted === "warn") {
3783
- process.stderr.write(
3784
- `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
3785
- `
3828
+ stderrLine(
3829
+ `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)`
3786
3830
  );
3787
3831
  }
3788
3832
  return popText(args, paramName);
@@ -3816,8 +3860,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
3816
3860
  snapshot = ctx.surfaceState.buildSnapshot();
3817
3861
  digest = surfaceHash(snapshot);
3818
3862
  } catch (err) {
3819
- process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
3820
- `);
3863
+ stderrLine(`baton: surface snapshot capture failed: ${String(err)}`);
3821
3864
  return;
3822
3865
  }
3823
3866
  const sent = ctx.surfaceState.sentSurfaces;
@@ -3885,16 +3928,16 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
3885
3928
  return registered;
3886
3929
  };
3887
3930
  }
3888
- function installToolsListSeam(lowLevel, ctx) {
3931
+ function installToolsListSeam(lowLevel, ctx, listsOwnReportTool) {
3889
3932
  const names = [...requiredParamNames(ctx.intentParamMode), TOOL_NAME_PARAM_NAME];
3890
3933
  const isInjected = (toolName, paramName) => toolName === ctx.annotationToolName ? paramName === TOOL_NAME_PARAM_NAME : ctx.paramRegistry.get(toolName)?.[paramName] === "injected";
3891
3934
  const advertise = (result) => {
3892
3935
  try {
3893
- 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);
3894
3938
  } catch (err) {
3895
- process.stderr.write(
3896
- `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}
3897
- `
3939
+ stderrLine(
3940
+ `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}`
3898
3941
  );
3899
3942
  return result;
3900
3943
  }
@@ -3918,14 +3961,12 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
3918
3961
  known.unread.add(name);
3919
3962
  warnOnce2(
3920
3963
  `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
- `
3964
+ `baton: could not read tool ${JSON.stringify(name)}; its calls keep user_goal until Baton can read it: ${printable(err)}`
3923
3965
  );
3924
3966
  };
3925
3967
  const skipNote = (name, err) => {
3926
3968
  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
- `);
3969
+ warnOnce2(`tool-unnoted:${name}`, `baton: could not note tool ${JSON.stringify(name)}; Baton adds no user_goal to it: ${printable(err)}`);
3929
3970
  };
3930
3971
  const keepGoalIfDeclared = (tools) => {
3931
3972
  for (const { name, inputSchema: inputSchema2 } of tools) {
@@ -3945,8 +3986,7 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
3945
3986
  if (surface && reportTool2 !== void 0 && tools.some((tool) => tool.name === reportTool2?.name)) {
3946
3987
  warnOnce2(
3947
3988
  "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
- `
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`
3950
3990
  );
3951
3991
  reportTool2 = void 0;
3952
3992
  ctx.annotationToolName = "";
@@ -3977,8 +4017,7 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
3977
4017
  } catch (err) {
3978
4018
  warnOnce2(
3979
4019
  "tools-unread",
3980
- `baton: could not read the tools option; Baton learns the tools from tools/list: ${printable(err)}
3981
- `
4020
+ `baton: could not read the tools option; Baton learns the tools from tools/list: ${printable(err)}`
3982
4021
  );
3983
4022
  }
3984
4023
  }
@@ -3997,8 +4036,7 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
3997
4036
  const firstPage = args[0]?.params?.cursor === void 0;
3998
4037
  return servedToolList(result, listed, ctx, firstPage && reportTool2 ? listedReportTool : void 0);
3999
4038
  } catch (err) {
4000
- process.stderr.write(`baton: tools/list capture failed; serving the vendor's own result: ${printable(err)}
4001
- `);
4039
+ stderrLine(`baton: tools/list capture failed; serving the vendor's own result: ${printable(err)}`);
4002
4040
  return result;
4003
4041
  }
4004
4042
  });
@@ -4022,8 +4060,7 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
4022
4060
  if (unlisted === "goalOnly" && USER_GOAL_PARAM_NAME in toolArgs && !known.served.has(name) && !known.givenTools.some((tool) => tool.name === name)) {
4023
4061
  warnOnce2(
4024
4062
  "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
- `
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`
4027
4064
  );
4028
4065
  }
4029
4066
  if (request?.params?.task !== void 0) {
@@ -4159,8 +4196,7 @@ async function openLifecycleCall(ctx, spec, requestParams, extra) {
4159
4196
  }
4160
4197
  };
4161
4198
  } catch (err) {
4162
- process.stderr.write(`baton: ${spec.method} capture failed: ${String(err)}
4163
- `);
4199
+ stderrLine(`baton: ${spec.method} capture failed: ${String(err)}`);
4164
4200
  return null;
4165
4201
  }
4166
4202
  }
@@ -4336,8 +4372,7 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
4336
4372
  await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
4337
4373
  } catch (err) {
4338
4374
  PROCESS_DROPS.add("encode_failed");
4339
- process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
4340
- `);
4375
+ stderrLine(`baton: settling a tool call failed; events dropped: ${String(err)}`);
4341
4376
  }
4342
4377
  }
4343
4378
  async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
@@ -4563,6 +4598,11 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4563
4598
  const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
4564
4599
  const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
4565
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
+ }
4566
4606
  const given = config.sink ?? new StdoutSink();
4567
4607
  const sink = offTheCall(given);
4568
4608
  const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
@@ -4600,7 +4640,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4600
4640
  const warnOnce2 = (key, message) => {
4601
4641
  if (warned3.has(key)) return;
4602
4642
  warned3.add(key);
4603
- process.stderr.write(message);
4643
+ stderrLine(message);
4604
4644
  };
4605
4645
  const dropSubagentClause = (name) => {
4606
4646
  const current2 = lowLevel._instructions;
@@ -4613,8 +4653,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4613
4653
  }
4614
4654
  warnOnce2(
4615
4655
  "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
- `
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`
4618
4657
  );
4619
4658
  };
4620
4659
  const isV2Server = typeof internals.toolInputSchemaJson === "function";
@@ -4711,7 +4750,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4711
4750
  () => rewriteInstructions(INTENT_INSTRUCTIONS)
4712
4751
  );
4713
4752
  }
4714
- installToolsListSeam(lowLevel, ctx);
4753
+ installToolsListSeam(lowLevel, ctx, shape === "lowLevel");
4715
4754
  if (shape === "mcpServer") installToolsCallSeam(
4716
4755
  lowLevel,
4717
4756
  // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
@@ -4757,9 +4796,8 @@ function reportsFor(config) {
4757
4796
  }
4758
4797
  function warnAboutSettings(config) {
4759
4798
  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
- `
4799
+ stderrLine(
4800
+ `baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered`
4763
4801
  );
4764
4802
  }
4765
4803
  if (config.resultCaptureMode === WITHHELD) {
@@ -4801,7 +4839,7 @@ function principalFromOAuthEmail(context) {
4801
4839
  }
4802
4840
 
4803
4841
  // src/library/session.ts
4804
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
4842
+ import * as asyncHooks2 from "async_hooks";
4805
4843
  var TRANSPORT_LIBRARY = "library";
4806
4844
  var TURN_ID_META_KEY = "baton/turn_id";
4807
4845
  function sessionEnvelope(session) {
@@ -4817,8 +4855,7 @@ function sessionEnvelope(session) {
4817
4855
  };
4818
4856
  }
4819
4857
  function warn2(message) {
4820
- process.stderr.write(`baton: ${message}
4821
- `);
4858
+ stderrLine(`baton: ${message}`);
4822
4859
  }
4823
4860
  function vendorId(name, value) {
4824
4861
  const cleaned = typeof value === "string" ? stripWhiteSpace(value) : "";
@@ -4855,7 +4892,7 @@ function newSession(values, scrubber, disabled) {
4855
4892
  runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
4856
4893
  };
4857
4894
  }
4858
- var current = new AsyncLocalStorage2();
4895
+ var current = new asyncHooks2.AsyncLocalStorage();
4859
4896
  function runInSession(owner, session, fn) {
4860
4897
  return current.run({ owner, session }, fn);
4861
4898
  }
@@ -4870,8 +4907,7 @@ function serveTools(tools, options) {
4870
4907
  try {
4871
4908
  served = tools.map(servedEntry);
4872
4909
  } catch (err) {
4873
- process.stderr.write(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}
4874
- `);
4910
+ stderrLine(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}`);
4875
4911
  return { served: tools, surface: null };
4876
4912
  }
4877
4913
  try {
@@ -4890,8 +4926,7 @@ function serveTools(tools, options) {
4890
4926
  );
4891
4927
  return { served, surface: { surface, digest: surfaceHash(surface) } };
4892
4928
  } catch (err) {
4893
- process.stderr.write(`baton: surface snapshot capture failed: ${printable(err)}
4894
- `);
4929
+ stderrLine(`baton: surface snapshot capture failed: ${printable(err)}`);
4895
4930
  return { served, surface: null };
4896
4931
  }
4897
4932
  }
@@ -5055,8 +5090,7 @@ var Core = class {
5055
5090
  });
5056
5091
  } catch (err) {
5057
5092
  PROCESS_DROPS.add("encode_failed");
5058
- process.stderr.write(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}
5059
- `);
5093
+ stderrLine(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}`);
5060
5094
  return Promise.resolve();
5061
5095
  }
5062
5096
  return safeWrite(this.sink, event);
@@ -5114,7 +5148,7 @@ var Trace = class _Trace {
5114
5148
  observed(result, failure) {
5115
5149
  if ((this.#result !== UNSET || this.#error !== null) && !this.#observedWarned) {
5116
5150
  this.#observedWarned = true;
5117
- 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.");
5118
5152
  }
5119
5153
  this.#result = UNSET;
5120
5154
  this.#error = null;
@@ -5134,8 +5168,7 @@ var Trace = class _Trace {
5134
5168
  try {
5135
5169
  this.#result = this.#core.scrubber(result);
5136
5170
  } catch (err) {
5137
- process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}
5138
- `);
5171
+ stderrLine(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}`);
5139
5172
  this.#result = SCRUB_FAILED;
5140
5173
  }
5141
5174
  }
@@ -5281,8 +5314,7 @@ var Client = class {
5281
5314
  try {
5282
5315
  block = newSession(options, this.#core.scrubber, this.#core.disabled);
5283
5316
  } catch (err) {
5284
- process.stderr.write(`baton: session values could not be read; using a minted session: ${printable(err)}
5285
- `);
5317
+ stderrLine(`baton: session values could not be read; using a minted session: ${printable(err)}`);
5286
5318
  block = newSession({}, this.#core.scrubber, this.#core.disabled);
5287
5319
  }
5288
5320
  return runInSession(this, block, fn);