@goodtiming/baton-sdk 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/index.cjs +1194 -694
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +67 -7
- package/dist/index.d.ts +67 -7
- package/dist/index.js +1194 -694
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.cjs
CHANGED
|
@@ -53,18 +53,18 @@ __export(index_exports, {
|
|
|
53
53
|
module.exports = __toCommonJS(index_exports);
|
|
54
54
|
|
|
55
55
|
// src/version.ts
|
|
56
|
-
var SDK_VERSION = "ts-1.
|
|
56
|
+
var SDK_VERSION = "ts-1.2.0";
|
|
57
57
|
|
|
58
58
|
// src/events.ts
|
|
59
59
|
var import_zod = require("zod");
|
|
60
60
|
|
|
61
61
|
// src/uuid7.ts
|
|
62
|
-
var
|
|
62
|
+
var crypto = __toESM(require("crypto"), 1);
|
|
63
63
|
var COUNTER_MAX = 4095;
|
|
64
64
|
var lastMs = -1;
|
|
65
65
|
var counter = 0;
|
|
66
66
|
function uuid7() {
|
|
67
|
-
const bytes =
|
|
67
|
+
const bytes = crypto.randomBytes(18);
|
|
68
68
|
const seed = (bytes[16] << 8 | bytes[17]) & 2047;
|
|
69
69
|
const now = Date.now();
|
|
70
70
|
if (now > lastMs) {
|
|
@@ -186,7 +186,8 @@ var ClientObservedSchema = import_zod.z.object({
|
|
|
186
186
|
var CaptureObservedSchema = import_zod.z.object({
|
|
187
187
|
settings_version: import_zod.z.number().int().min(1).optional(),
|
|
188
188
|
audience: import_zod.z.string().optional(),
|
|
189
|
-
overlay: import_zod.z.string().optional()
|
|
189
|
+
overlay: import_zod.z.string().optional(),
|
|
190
|
+
candidate: import_zod.z.string().optional()
|
|
190
191
|
}).strict();
|
|
191
192
|
var PrincipalWireSchema = import_zod.z.object({
|
|
192
193
|
id: import_zod.z.string(),
|
|
@@ -443,13 +444,49 @@ function onWorkers() {
|
|
|
443
444
|
return typeof globalThis.WebSocketPair === "function" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
|
|
444
445
|
}
|
|
445
446
|
var globalFetch = (input, init) => fetch(input, init);
|
|
447
|
+
function onProcess(event, listener) {
|
|
448
|
+
const target = typeof process !== "undefined" ? process : void 0;
|
|
449
|
+
if (typeof target?.on !== "function") return void 0;
|
|
450
|
+
try {
|
|
451
|
+
target.on(event, listener);
|
|
452
|
+
} catch {
|
|
453
|
+
return void 0;
|
|
454
|
+
}
|
|
455
|
+
return () => {
|
|
456
|
+
try {
|
|
457
|
+
target.off(event, listener);
|
|
458
|
+
} catch {
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
}
|
|
446
462
|
|
|
447
463
|
// src/warn.ts
|
|
448
464
|
function warn(message) {
|
|
449
465
|
if (onWorkers()) {
|
|
450
466
|
console.warn(message);
|
|
451
|
-
|
|
452
|
-
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
try {
|
|
470
|
+
if (typeof process !== "undefined" && typeof process.emitWarning === "function") return process.emitWarning(message);
|
|
471
|
+
} catch {
|
|
472
|
+
}
|
|
473
|
+
stderrLine(message);
|
|
474
|
+
}
|
|
475
|
+
function stderrLine(message) {
|
|
476
|
+
stderrLines([message]);
|
|
477
|
+
}
|
|
478
|
+
function stderrLines(lines) {
|
|
479
|
+
try {
|
|
480
|
+
const stderr = typeof process !== "undefined" ? process.stderr : void 0;
|
|
481
|
+
if (typeof stderr?.write === "function") return void stderr.write(lines.map((line) => `${line}
|
|
482
|
+
`).join(""));
|
|
483
|
+
} catch {
|
|
484
|
+
}
|
|
485
|
+
for (const line of lines) {
|
|
486
|
+
try {
|
|
487
|
+
console.warn(line);
|
|
488
|
+
} catch {
|
|
489
|
+
}
|
|
453
490
|
}
|
|
454
491
|
}
|
|
455
492
|
function printable(err) {
|
|
@@ -579,8 +616,8 @@ function identityScrub(value) {
|
|
|
579
616
|
}
|
|
580
617
|
|
|
581
618
|
// src/sinks.ts
|
|
582
|
-
var
|
|
583
|
-
var
|
|
619
|
+
var fs = __toESM(require("fs"), 1);
|
|
620
|
+
var fsp = __toESM(require("fs/promises"), 1);
|
|
584
621
|
|
|
585
622
|
// src/_text.ts
|
|
586
623
|
var WHITE_SPACE = /^\p{White_Space}$/u;
|
|
@@ -595,6 +632,11 @@ function stripEdges(value, space) {
|
|
|
595
632
|
function stripWhiteSpace(value) {
|
|
596
633
|
return stripEdges(value, WHITE_SPACE);
|
|
597
634
|
}
|
|
635
|
+
function stripWhiteSpaceEnd(value) {
|
|
636
|
+
let end = value.length;
|
|
637
|
+
while (end > 0 && WHITE_SPACE.test(value[end - 1])) end--;
|
|
638
|
+
return value.slice(0, end);
|
|
639
|
+
}
|
|
598
640
|
function isBlank(value) {
|
|
599
641
|
return ALL_WHITE_SPACE.test(value);
|
|
600
642
|
}
|
|
@@ -702,14 +744,9 @@ async function safeWrite(sink, event) {
|
|
|
702
744
|
} catch (err) {
|
|
703
745
|
if (isSinkClosed(err)) return droppedAfterClose(sink);
|
|
704
746
|
PROCESS_DROPS.add("write_failed");
|
|
705
|
-
|
|
706
|
-
`);
|
|
747
|
+
stderrLine(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}`);
|
|
707
748
|
}
|
|
708
749
|
}
|
|
709
|
-
function stderrLine(message) {
|
|
710
|
-
process.stderr.write(`${message}
|
|
711
|
-
`);
|
|
712
|
-
}
|
|
713
750
|
function isTimerMs(value) {
|
|
714
751
|
return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
|
|
715
752
|
}
|
|
@@ -749,11 +786,13 @@ var StdoutSink = class {
|
|
|
749
786
|
stream;
|
|
750
787
|
closed = false;
|
|
751
788
|
constructor(options = {}) {
|
|
752
|
-
this.stream = options.stream
|
|
789
|
+
this.stream = options.stream;
|
|
753
790
|
}
|
|
754
791
|
async write(event) {
|
|
755
792
|
if (this.closed) throw new SinkClosedError("StdoutSink is closed");
|
|
756
|
-
|
|
793
|
+
const line = JSON.stringify(event);
|
|
794
|
+
if (this.stream) this.stream.write(line + "\n");
|
|
795
|
+
else stderrLine(line);
|
|
757
796
|
}
|
|
758
797
|
async flush() {
|
|
759
798
|
}
|
|
@@ -775,7 +814,7 @@ var FileSink = class {
|
|
|
775
814
|
if (this.closed) throw new SinkClosedError("FileSink is closed");
|
|
776
815
|
const line = JSON.stringify(event) + "\n";
|
|
777
816
|
const written = this.last.then(async () => {
|
|
778
|
-
this.file ??= await
|
|
817
|
+
this.file ??= await fsp.open(this.path, "a");
|
|
779
818
|
await this.file.appendFile(line);
|
|
780
819
|
});
|
|
781
820
|
this.last = written.catch(() => void 0);
|
|
@@ -832,30 +871,31 @@ var later = (run) => {
|
|
|
832
871
|
else setTimeout(run, 0);
|
|
833
872
|
};
|
|
834
873
|
var withUnwrittenEvents = /* @__PURE__ */ new Set();
|
|
835
|
-
var
|
|
874
|
+
var exitTriedOn = /* @__PURE__ */ new WeakSet();
|
|
836
875
|
function hookExit() {
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
} catch {
|
|
849
|
-
}
|
|
876
|
+
const target = typeof process !== "undefined" ? process : void 0;
|
|
877
|
+
if (target === void 0 || exitTriedOn.has(target)) return;
|
|
878
|
+
exitTriedOn.add(target);
|
|
879
|
+
onProcess("exit", () => {
|
|
880
|
+
try {
|
|
881
|
+
let unsure = 0;
|
|
882
|
+
for (const sink of withUnwrittenEvents) unsure += sink.handOffAtExit();
|
|
883
|
+
if (unsure > 0) stderrLine(`baton: process exiting; ${unsure} event(s) may not have been written.`);
|
|
884
|
+
} catch {
|
|
885
|
+
}
|
|
886
|
+
});
|
|
850
887
|
}
|
|
851
888
|
function writeNow(sink, events) {
|
|
852
|
-
const
|
|
889
|
+
const json = () => events.map((event) => JSON.stringify(event));
|
|
890
|
+
const lines = () => json().map((line) => line + "\n").join("");
|
|
853
891
|
if (sink instanceof StdoutSink) {
|
|
854
892
|
const stream = sink["stream"];
|
|
855
|
-
if (stream !== process.stdout && stream !== process.stderr) return false;
|
|
856
|
-
if (
|
|
893
|
+
if (stream !== void 0 && stream !== process.stdout && stream !== process.stderr) return false;
|
|
894
|
+
if (sink["closed"]) return true;
|
|
895
|
+
if (stream === void 0) stderrLines(json());
|
|
896
|
+
else stream.write(lines());
|
|
857
897
|
} else if (sink instanceof FileSink) {
|
|
858
|
-
if (!sink["closed"])
|
|
898
|
+
if (!sink["closed"]) fs.appendFileSync(sink["path"], lines());
|
|
859
899
|
} else return false;
|
|
860
900
|
return true;
|
|
861
901
|
}
|
|
@@ -1113,6 +1153,8 @@ var HttpSink = class _HttpSink {
|
|
|
1113
1153
|
/** Set for the life of the sink by a 404 or 405 on the batch path. */
|
|
1114
1154
|
batchless = false;
|
|
1115
1155
|
exitHooks = null;
|
|
1156
|
+
/** The `process` the exit hooks were last tried on, so a refusal is not retried per write. */
|
|
1157
|
+
exitHooksTriedOn;
|
|
1116
1158
|
/** The least time between two of this sink's loss reports. */
|
|
1117
1159
|
static reportIntervalMs = 6e4;
|
|
1118
1160
|
/** Totals only grow, so their sum tells whether they changed. */
|
|
@@ -1210,11 +1252,8 @@ var HttpSink = class _HttpSink {
|
|
|
1210
1252
|
warn(`baton: the sink closed with ${unsent} event(s) unsent.`);
|
|
1211
1253
|
}
|
|
1212
1254
|
this.warnUnloggedRefusals("the sink closed");
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
process.off("exit", this.exitHooks.exit);
|
|
1216
|
-
this.exitHooks = null;
|
|
1217
|
-
}
|
|
1255
|
+
this.exitHooks?.off();
|
|
1256
|
+
this.exitHooks = null;
|
|
1218
1257
|
}
|
|
1219
1258
|
/** SPEC §11.2 rule 7: an explicit flush or close returns within `ms` and
|
|
1220
1259
|
* never rejects. While an earlier wait's drain is still stuck, a flush
|
|
@@ -1308,7 +1347,9 @@ var HttpSink = class _HttpSink {
|
|
|
1308
1347
|
* both hooks: a vendor needing that guarantee must call `aclose()` from
|
|
1309
1348
|
* their own handler. */
|
|
1310
1349
|
ensureExitHooksRegistered() {
|
|
1311
|
-
|
|
1350
|
+
const target = typeof process !== "undefined" ? process : void 0;
|
|
1351
|
+
if (this.exitHooks || target === void 0 || target === this.exitHooksTriedOn) return;
|
|
1352
|
+
this.exitHooksTriedOn = target;
|
|
1312
1353
|
const beforeExit = () => {
|
|
1313
1354
|
if (this.unsent === 0 || this.exitPassRan) {
|
|
1314
1355
|
this.warnUnloggedRefusals("process exiting");
|
|
@@ -1326,9 +1367,14 @@ var HttpSink = class _HttpSink {
|
|
|
1326
1367
|
} catch {
|
|
1327
1368
|
}
|
|
1328
1369
|
};
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1370
|
+
const offBeforeExit = onProcess("beforeExit", beforeExit);
|
|
1371
|
+
const offExit = onProcess("exit", exit);
|
|
1372
|
+
if (offBeforeExit === void 0 || offExit === void 0) {
|
|
1373
|
+
offBeforeExit?.();
|
|
1374
|
+
offExit?.();
|
|
1375
|
+
return;
|
|
1376
|
+
}
|
|
1377
|
+
this.exitHooks = { beforeExit, exit, off: () => (offBeforeExit(), offExit()) };
|
|
1332
1378
|
}
|
|
1333
1379
|
/** One attempt per batch, no retry, within `shutdownFlushTimeoutMs` in
|
|
1334
1380
|
* total (SPEC §11.2); what is left is reported, not sent. */
|
|
@@ -1709,7 +1755,7 @@ var HttpSink = class _HttpSink {
|
|
|
1709
1755
|
};
|
|
1710
1756
|
|
|
1711
1757
|
// src/integrations/mcp/withBaton.ts
|
|
1712
|
-
var
|
|
1758
|
+
var asyncHooks = __toESM(require("async_hooks"), 1);
|
|
1713
1759
|
|
|
1714
1760
|
// src/integrations/mcp/annotation.ts
|
|
1715
1761
|
var import_zod3 = require("zod");
|
|
@@ -1754,6 +1800,122 @@ function roundMetaCoordinates(meta) {
|
|
|
1754
1800
|
return walk(meta, 0);
|
|
1755
1801
|
}
|
|
1756
1802
|
|
|
1803
|
+
// src/integrations/mcp/overlays.ts
|
|
1804
|
+
var INSTRUCTION_PIECES = ["instructions.subagent", "instructions.report_pointer"];
|
|
1805
|
+
var AUDIENCE_PIECES = ["goal_param.description", "report_tool.description", "report_tool.refusal"];
|
|
1806
|
+
var TEXT_CHANGES = ["append", "replace"];
|
|
1807
|
+
var FLAG_CHANGES = ["remove", "required"];
|
|
1808
|
+
var warned = /* @__PURE__ */ new Set();
|
|
1809
|
+
var unreadable = /* @__PURE__ */ new Set();
|
|
1810
|
+
function warnSkipped(overlayId, index, reason) {
|
|
1811
|
+
const key = JSON.stringify([overlayId, index]);
|
|
1812
|
+
if (warned.has(key)) return;
|
|
1813
|
+
warned.add(key);
|
|
1814
|
+
warn(`baton: overlay ${JSON.stringify(overlayId)} action ${index} is skipped: ${reason}`);
|
|
1815
|
+
}
|
|
1816
|
+
var Overlay = class {
|
|
1817
|
+
constructor(id, actions) {
|
|
1818
|
+
this.id = id;
|
|
1819
|
+
this.actions = actions;
|
|
1820
|
+
this.hiddenTools = new Set(
|
|
1821
|
+
actions.filter((a) => a.tool !== void 0 && a.param === void 0 && a.change === "remove").map((a) => a.tool)
|
|
1822
|
+
);
|
|
1823
|
+
}
|
|
1824
|
+
id;
|
|
1825
|
+
actions;
|
|
1826
|
+
hiddenTools;
|
|
1827
|
+
pieceActions(piece) {
|
|
1828
|
+
return this.actions.filter((a) => a.piece === piece);
|
|
1829
|
+
}
|
|
1830
|
+
instructionAppends() {
|
|
1831
|
+
return this.actions.filter((a) => a.instructions && a.text !== void 0).map((a) => a.text);
|
|
1832
|
+
}
|
|
1833
|
+
};
|
|
1834
|
+
function changedText(text, actions) {
|
|
1835
|
+
let source = "default";
|
|
1836
|
+
for (const action of actions) {
|
|
1837
|
+
if (action.change === "replace") {
|
|
1838
|
+
text = action.text;
|
|
1839
|
+
source = "replaced";
|
|
1840
|
+
} else if (action.change === "append" && action.text !== void 0) {
|
|
1841
|
+
const kept = stripWhiteSpaceEnd(text ?? "");
|
|
1842
|
+
text = kept ? `${kept}
|
|
1843
|
+
|
|
1844
|
+
${action.text}` : action.text;
|
|
1845
|
+
if (source === "default") source = "appended";
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
return { text, source };
|
|
1849
|
+
}
|
|
1850
|
+
function overlaid(text, overlay, piece) {
|
|
1851
|
+
if (overlay === void 0) return text;
|
|
1852
|
+
return changedText(text, overlay.pieceActions(piece)).text ?? text;
|
|
1853
|
+
}
|
|
1854
|
+
function readOverlays(value) {
|
|
1855
|
+
return isRecord(value) ? value : {};
|
|
1856
|
+
}
|
|
1857
|
+
function overlayFor(overlays, overlayId, place) {
|
|
1858
|
+
if (overlayId === void 0 || overlayId === null) return void 0;
|
|
1859
|
+
let id;
|
|
1860
|
+
let body;
|
|
1861
|
+
if (typeof overlayId === "string") {
|
|
1862
|
+
id = overlayId;
|
|
1863
|
+
body = Object.hasOwn(overlays, id) ? overlays[id] : void 0;
|
|
1864
|
+
} else {
|
|
1865
|
+
id = JSON.stringify(overlayId);
|
|
1866
|
+
}
|
|
1867
|
+
const actions = isRecord(body) ? body.actions : void 0;
|
|
1868
|
+
if (!Array.isArray(actions)) {
|
|
1869
|
+
if (!unreadable.has(id)) {
|
|
1870
|
+
unreadable.add(id);
|
|
1871
|
+
warn(`baton: overlay ${JSON.stringify(id)} cannot be read; none is applied there`);
|
|
1872
|
+
}
|
|
1873
|
+
return void 0;
|
|
1874
|
+
}
|
|
1875
|
+
const kept = [];
|
|
1876
|
+
actions.forEach((raw, index) => {
|
|
1877
|
+
const read = readAction(index, raw, place);
|
|
1878
|
+
if (typeof read === "string") warnSkipped(id, index, read);
|
|
1879
|
+
else kept.push(read);
|
|
1880
|
+
});
|
|
1881
|
+
return new Overlay(id, kept);
|
|
1882
|
+
}
|
|
1883
|
+
function readAction(index, raw, place) {
|
|
1884
|
+
if (!isRecord(raw) || !isRecord(raw.target)) return "it has no target";
|
|
1885
|
+
const target = raw.target;
|
|
1886
|
+
const changes = [...TEXT_CHANGES, ...FLAG_CHANGES].filter((c) => Object.hasOwn(raw, c));
|
|
1887
|
+
if (changes.length !== 1 || Object.keys(raw).length !== 2) return "it needs exactly one change";
|
|
1888
|
+
const change = changes[0];
|
|
1889
|
+
const value = raw[change];
|
|
1890
|
+
if (TEXT_CHANGES.includes(change) && typeof value !== "string") return `'${change}' needs text`;
|
|
1891
|
+
if (FLAG_CHANGES.includes(change) && value !== true) return `'${change}' must be true`;
|
|
1892
|
+
const text = typeof value === "string" ? { text: value } : {};
|
|
1893
|
+
const keys = Object.keys(target).sort().join(",");
|
|
1894
|
+
if (keys === "tool" && typeof target.tool === "string") {
|
|
1895
|
+
if (change === "required") return "only a param can be required";
|
|
1896
|
+
return placed({ index, change, ...text, tool: target.tool }, place, "audience");
|
|
1897
|
+
}
|
|
1898
|
+
if (keys === "param,tool" && typeof target.tool === "string" && typeof target.param === "string") {
|
|
1899
|
+
return placed({ index, change, ...text, tool: target.tool, param: target.param }, place, "audience");
|
|
1900
|
+
}
|
|
1901
|
+
if (keys === "instructions" && target.instructions === true) {
|
|
1902
|
+
if (change !== "append") return "the instructions take only 'append'";
|
|
1903
|
+
return placed({ index, change, ...text, instructions: true }, place, "server");
|
|
1904
|
+
}
|
|
1905
|
+
if (keys === "agent_text" && typeof target.agent_text === "string") {
|
|
1906
|
+
const piece = target.agent_text;
|
|
1907
|
+
if (!TEXT_CHANGES.includes(change)) return "agent_text takes only 'append' or 'replace'";
|
|
1908
|
+
if (INSTRUCTION_PIECES.includes(piece)) return placed({ index, change, ...text, piece }, place, "server");
|
|
1909
|
+
if (AUDIENCE_PIECES.includes(piece)) return placed({ index, change, ...text, piece }, place, "audience");
|
|
1910
|
+
return `unknown agent_text ${JSON.stringify(piece)}`;
|
|
1911
|
+
}
|
|
1912
|
+
return "unknown target";
|
|
1913
|
+
}
|
|
1914
|
+
function placed(action, place, allowed) {
|
|
1915
|
+
if (place === allowed) return action;
|
|
1916
|
+
return `this target goes only in ${allowed === "server" ? "server_overlay" : "an audience's overlay"}`;
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1757
1919
|
// src/integrations/mcp/llmText.ts
|
|
1758
1920
|
var REPORT_POINTER_TEMPLATE = (vendorDisplayName, annotationToolName) => `Use \`${annotationToolName}\` to report a ${vendorDisplayName} tool call that went wrong, or a request no tool covers; its description says when and how.`;
|
|
1759
1921
|
var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
|
|
@@ -1769,14 +1931,14 @@ Fields:
|
|
|
1769
1931
|
- context: supplementary info not covered above. Common keys: plan, alternatives_considered, likely_cause, user_impact, error_class, downstream_blocked, confidence_in_intent. When no tool covers the request also missing_capability_field and requested_capability.`;
|
|
1770
1932
|
var CLAUDE_CODE_TRUNCATION_CAP = 2087;
|
|
1771
1933
|
var INSTRUCTIONS_LENGTH_CAP = 1500;
|
|
1772
|
-
function
|
|
1934
|
+
function buildReportPointer(options) {
|
|
1773
1935
|
return REPORT_POINTER_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
|
|
1774
1936
|
}
|
|
1775
1937
|
function fitsInstructionsCap(options) {
|
|
1776
|
-
return
|
|
1938
|
+
return buildReportPointer(options).length <= INSTRUCTIONS_LENGTH_CAP;
|
|
1777
1939
|
}
|
|
1778
1940
|
function buildServerInstructions(options) {
|
|
1779
|
-
const rendered =
|
|
1941
|
+
const rendered = buildReportPointer(options);
|
|
1780
1942
|
if (rendered.length > INSTRUCTIONS_LENGTH_CAP) {
|
|
1781
1943
|
throw new Error(
|
|
1782
1944
|
`Rendered server instructions are ${rendered.length} chars, which exceeds the ${INSTRUCTIONS_LENGTH_CAP}-char safety cap (Claude Code truncates at ~${CLAUDE_CODE_TRUNCATION_CAP}). Shorten vendorDisplayName or annotationToolName.`
|
|
@@ -1788,7 +1950,8 @@ function buildAnnotationToolDescription(options) {
|
|
|
1788
1950
|
return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
|
|
1789
1951
|
}
|
|
1790
1952
|
function buildRefusalText(options) {
|
|
1791
|
-
|
|
1953
|
+
const text = `${options.annotationToolName} is reactive-only on this server. Call it only AFTER a tool call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. What the user is trying to do is already recorded on each tool call, so no pre-call annotation is needed \u2014 nothing was lost. If a tool call really went wrong, or no tool covers the request, call this again and say what_happened. If neither is true, do NOT re-send: that would file a report for a call that did not go wrong.`;
|
|
1954
|
+
return overlaid(text, options.overlay, "report_tool.refusal");
|
|
1792
1955
|
}
|
|
1793
1956
|
var USER_GOAL_PARAM_NAME = "user_goal";
|
|
1794
1957
|
var EXPECTED_RESULT_PARAM_NAME = "expected_result";
|
|
@@ -1836,38 +1999,47 @@ var INTENT_PARAMS = Object.freeze([
|
|
|
1836
1999
|
Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: "intent" })
|
|
1837
2000
|
]);
|
|
1838
2001
|
var VENDOR_INSTRUCTIONS = /* @__PURE__ */ Symbol("batonVendorInstructions");
|
|
1839
|
-
var
|
|
1840
|
-
var
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
new RegExp("^" + escapeRegExp(INTENT_INSTRUCTIONS))
|
|
1845
|
-
];
|
|
1846
|
-
function endsInOurs(current2, vendor) {
|
|
1847
|
-
if (typeof current2 !== "string") return false;
|
|
1848
|
-
const prefix = typeof vendor === "string" && !isBlank(vendor) ? `${vendor}
|
|
2002
|
+
var OURS = /* @__PURE__ */ Symbol("batonInstructions");
|
|
2003
|
+
var SUBAGENT = /* @__PURE__ */ Symbol("batonSubagentSentence");
|
|
2004
|
+
function joined(vendor, ours) {
|
|
2005
|
+
if (typeof vendor !== "string" || isBlank(vendor)) return ours;
|
|
2006
|
+
return ours ? `${vendor}
|
|
1849
2007
|
|
|
1850
|
-
` :
|
|
1851
|
-
if (!current2.startsWith(prefix)) return false;
|
|
1852
|
-
const rest = current2.slice(prefix.length);
|
|
1853
|
-
return OURS_STARTS.some((start) => start.test(rest));
|
|
2008
|
+
${ours}` : vendor;
|
|
1854
2009
|
}
|
|
1855
|
-
function
|
|
1856
|
-
const holder = server;
|
|
2010
|
+
function vendorText(holder) {
|
|
1857
2011
|
const current2 = holder._instructions;
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
2012
|
+
const written = holder[OURS];
|
|
2013
|
+
const vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
|
|
2014
|
+
return written !== void 0 && current2 === joined(vendor, written) ? vendor : current2;
|
|
2015
|
+
}
|
|
2016
|
+
function writeOurs(server, ours, subagent, write, warn3 = stderrLine) {
|
|
2017
|
+
const holder = server;
|
|
2018
|
+
const vendor = vendorText(holder);
|
|
2019
|
+
write(withVendorInstructions(server, ours, warn3));
|
|
2020
|
+
holder[VENDOR_INSTRUCTIONS] = vendor;
|
|
2021
|
+
holder[OURS] = ours;
|
|
2022
|
+
holder[SUBAGENT] = subagent && ours.endsWith(subagent) ? subagent : void 0;
|
|
2023
|
+
}
|
|
2024
|
+
function removeSubagentClause(server, write, warn3 = stderrLine) {
|
|
2025
|
+
const holder = server;
|
|
2026
|
+
const ours = holder[OURS];
|
|
2027
|
+
const subagent = holder[SUBAGENT];
|
|
2028
|
+
if (ours === void 0 || !subagent || holder._instructions !== joined(holder[VENDOR_INSTRUCTIONS], ours)) {
|
|
2029
|
+
return false;
|
|
1862
2030
|
}
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
2031
|
+
const kept = ours.slice(0, ours.length - subagent.length);
|
|
2032
|
+
writeOurs(server, kept.endsWith("\n\n") ? kept.slice(0, -2) : kept, null, write, warn3);
|
|
2033
|
+
return true;
|
|
2034
|
+
}
|
|
2035
|
+
function withVendorInstructions(server, ours, warn3 = stderrLine) {
|
|
2036
|
+
const vendor = vendorText(server);
|
|
2037
|
+
const combined = joined(vendor, ours);
|
|
2038
|
+
if (combined === ours) return ours;
|
|
2039
|
+
const vendorLength = vendor?.length ?? 0;
|
|
1867
2040
|
if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
|
|
1868
2041
|
warn3(
|
|
1869
|
-
`baton: the server instructions are ${combined.length} chars (yours ${
|
|
1870
|
-
`
|
|
2042
|
+
`baton: the server instructions are ${combined.length} chars (yours ${vendorLength}, Baton's ${ours.length}); Claude Code cuts them at ~${CLAUDE_CODE_TRUNCATION_CAP}, so the end of Baton's text is lost there`
|
|
1871
2043
|
);
|
|
1872
2044
|
}
|
|
1873
2045
|
return combined;
|
|
@@ -1974,8 +2146,7 @@ async function emit(sink, build) {
|
|
|
1974
2146
|
event = build();
|
|
1975
2147
|
} catch (err) {
|
|
1976
2148
|
PROCESS_DROPS.add("encode_failed");
|
|
1977
|
-
|
|
1978
|
-
`);
|
|
2149
|
+
stderrLine(`baton: event construction failed; event dropped: ${printable(err)}`);
|
|
1979
2150
|
return;
|
|
1980
2151
|
}
|
|
1981
2152
|
await safeWrite(sink, event);
|
|
@@ -2126,135 +2297,571 @@ function identityWire(id, stated, displayName, onUnregisteredForm) {
|
|
|
2126
2297
|
return wire;
|
|
2127
2298
|
}
|
|
2128
2299
|
|
|
2129
|
-
// src/integrations/mcp/
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
return
|
|
2300
|
+
// src/integrations/mcp/captureSettings.ts
|
|
2301
|
+
var crypto2 = __toESM(require("crypto"), 1);
|
|
2302
|
+
|
|
2303
|
+
// src/integrations/mcp/errorResult.ts
|
|
2304
|
+
var TOOL_ERROR_TYPE = "tool_error";
|
|
2305
|
+
var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
|
|
2306
|
+
var REFUSED = "refused";
|
|
2307
|
+
var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
|
|
2308
|
+
function requestSideFailureKind(entry, validation) {
|
|
2309
|
+
if (entry == null) return "unknown_tool";
|
|
2310
|
+
if (entry.enabled === false) return "tool_disabled";
|
|
2311
|
+
if (validation === "rejected") return "invalid_argument";
|
|
2312
|
+
if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
|
|
2313
|
+
return REFUSED;
|
|
2143
2314
|
}
|
|
2144
|
-
|
|
2315
|
+
var ERROR_BODY_MAX_CODE_POINTS = 2e3;
|
|
2316
|
+
function isErrorResult(value) {
|
|
2145
2317
|
try {
|
|
2146
|
-
|
|
2147
|
-
return
|
|
2318
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2319
|
+
return Boolean(value.isError);
|
|
2148
2320
|
} catch {
|
|
2149
|
-
return
|
|
2321
|
+
return false;
|
|
2150
2322
|
}
|
|
2151
2323
|
}
|
|
2152
|
-
function
|
|
2153
|
-
const
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
const
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
headers.append(name, item);
|
|
2163
|
-
} catch {
|
|
2164
|
-
}
|
|
2165
|
-
}
|
|
2324
|
+
function errorText(value) {
|
|
2325
|
+
const parts = [];
|
|
2326
|
+
try {
|
|
2327
|
+
const content = value?.content;
|
|
2328
|
+
if (!Array.isArray(content)) return "";
|
|
2329
|
+
for (const part of content) {
|
|
2330
|
+
const text = part?.text;
|
|
2331
|
+
if (typeof text !== "string") continue;
|
|
2332
|
+
const trimmed = stripWhiteSpace(text);
|
|
2333
|
+
if (trimmed) parts.push(trimmed);
|
|
2166
2334
|
}
|
|
2167
|
-
|
|
2335
|
+
} catch {
|
|
2336
|
+
return "";
|
|
2168
2337
|
}
|
|
2169
|
-
return
|
|
2338
|
+
return parts.join("\n");
|
|
2170
2339
|
}
|
|
2171
|
-
|
|
2172
|
-
|
|
2340
|
+
var RESULT_CAPTURE_MODES = ["full", "off"];
|
|
2341
|
+
var WITHHELD = "off";
|
|
2342
|
+
function endResultFields(mode, result, scrubber) {
|
|
2343
|
+
switch (mode) {
|
|
2344
|
+
case WITHHELD:
|
|
2345
|
+
return { result: null, result_capture: WITHHELD };
|
|
2346
|
+
case "full":
|
|
2347
|
+
return { result: scrubber(result) };
|
|
2348
|
+
}
|
|
2173
2349
|
}
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
function buildPrincipalResolutionContext(extra, toolName, args) {
|
|
2177
|
-
return {
|
|
2178
|
-
headers: extraHeaders(extra),
|
|
2179
|
-
meta: extraMeta(extra),
|
|
2180
|
-
toolName,
|
|
2181
|
-
arguments: args,
|
|
2182
|
-
authInfo: extraAuthInfo(extra)
|
|
2183
|
-
};
|
|
2350
|
+
function returnedErrorFields(mode, result, errorBody2, scrubber) {
|
|
2351
|
+
return resultDerivedFields(mode, () => errorText(result), result, errorBody2, scrubber);
|
|
2184
2352
|
}
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
);
|
|
2193
|
-
return null;
|
|
2353
|
+
function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
|
|
2354
|
+
switch (mode) {
|
|
2355
|
+
case WITHHELD:
|
|
2356
|
+
return { error_body: "", result: null, result_capture: WITHHELD };
|
|
2357
|
+
case "full":
|
|
2358
|
+
return { error_body: errorBody2(text()), result: scrubber(result) };
|
|
2359
|
+
}
|
|
2194
2360
|
}
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
if (warned.has(key)) return;
|
|
2198
|
-
warned.add(key);
|
|
2199
|
-
warn(`baton: resolvePrincipal ${message}`);
|
|
2361
|
+
function requestSideErrorFields(text, errorBody2) {
|
|
2362
|
+
return { error_body: errorBody2(text), result: null };
|
|
2200
2363
|
}
|
|
2201
|
-
function
|
|
2202
|
-
return
|
|
2203
|
-
principal: caller.principal,
|
|
2204
|
-
organization: caller.organization,
|
|
2205
|
-
labels: wireLabels(caller.labels),
|
|
2206
|
-
capture: caller.settings?.capture ?? null
|
|
2207
|
-
};
|
|
2364
|
+
function requestSideFailureFields(kind, mode, text, result, errorBody2, scrubber) {
|
|
2365
|
+
return kind === REFUSED ? resultDerivedFields(mode, text, result ?? null, errorBody2, scrubber) : requestSideErrorFields(text(), errorBody2);
|
|
2208
2366
|
}
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
const caller = await resolveIdentity(hook, call);
|
|
2212
|
-
if (settings === void 0) return caller;
|
|
2213
|
-
try {
|
|
2214
|
-
const callSettings = settings.forCaller({
|
|
2215
|
-
labels: caller.labels,
|
|
2216
|
-
clientName: client?.info?.name ?? null,
|
|
2217
|
-
shareKey: caller.principal?.id ?? null
|
|
2218
|
-
});
|
|
2219
|
-
return callSettings === void 0 ? caller : { ...caller, settings: callSettings };
|
|
2220
|
-
} catch {
|
|
2221
|
-
if (!settingsWarned) {
|
|
2222
|
-
settingsWarned = true;
|
|
2223
|
-
warn("baton: applying capture settings failed; this request uses the config's values");
|
|
2224
|
-
}
|
|
2225
|
-
return caller;
|
|
2226
|
-
}
|
|
2367
|
+
function errorTypeOf(err) {
|
|
2368
|
+
return err instanceof Error ? err.constructor.name : "Error";
|
|
2227
2369
|
}
|
|
2228
|
-
|
|
2229
|
-
|
|
2370
|
+
function messageOf(err) {
|
|
2371
|
+
return err instanceof Error ? err.message : String(err);
|
|
2372
|
+
}
|
|
2373
|
+
function scrubbedErrorBody(scrubber, text) {
|
|
2374
|
+
return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
|
|
2375
|
+
}
|
|
2376
|
+
|
|
2377
|
+
// src/integrations/mcp/captureSettings.ts
|
|
2378
|
+
var SETTINGS_PATH = "/v0/settings";
|
|
2379
|
+
var TENANT_HEADER = "X-Baton-Tenant-Id";
|
|
2380
|
+
var SETTINGS_MODES = ["local", "console"];
|
|
2381
|
+
var DEFAULT_SETTINGS_REFRESH_MS = 6e4;
|
|
2382
|
+
var MIN_SETTINGS_REFRESH_MS = 15e3;
|
|
2383
|
+
var REQUEST_TIMEOUT_MS = 1e4;
|
|
2384
|
+
var CANDIDATE_ENV = "BATON_CANDIDATE";
|
|
2385
|
+
var CANDIDATE_HEADER = "baton-candidate";
|
|
2386
|
+
var CANDIDATES_HELD = 32;
|
|
2387
|
+
var CANDIDATE_READS_AT_ONCE = 4;
|
|
2388
|
+
var CANDIDATE_START_TIMEOUT_MS = 5e3;
|
|
2389
|
+
var CANDIDATE_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
2390
|
+
function candidateId(value) {
|
|
2391
|
+
if (typeof value !== "string") return null;
|
|
2392
|
+
const id = stripWhiteSpace(value);
|
|
2393
|
+
return CANDIDATE_ID.test(id) ? id : null;
|
|
2394
|
+
}
|
|
2395
|
+
function headerCandidate(headers) {
|
|
2230
2396
|
try {
|
|
2231
|
-
|
|
2232
|
-
const result = await withinHookBudget(hook(context));
|
|
2233
|
-
return callerFor(result, warnOnce);
|
|
2397
|
+
return candidateId(headers?.get(CANDIDATE_HEADER));
|
|
2234
2398
|
} catch {
|
|
2235
|
-
return
|
|
2399
|
+
return null;
|
|
2236
2400
|
}
|
|
2237
2401
|
}
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
const schema = s;
|
|
2245
|
-
return !!schema?._zod;
|
|
2402
|
+
function envCandidate() {
|
|
2403
|
+
const value = typeof process !== "undefined" ? process.env?.[CANDIDATE_ENV] : void 0;
|
|
2404
|
+
if (!value) return null;
|
|
2405
|
+
const id = candidateId(value);
|
|
2406
|
+
if (id === null) warn(`baton: ${CANDIDATE_ENV} is not a change id; today's settings apply.`);
|
|
2407
|
+
return id;
|
|
2246
2408
|
}
|
|
2247
|
-
function
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
if (allV3) return z3rt.object(shape);
|
|
2254
|
-
throw new Error("Mixed Zod versions detected in object shape.");
|
|
2409
|
+
function candidateNeedsConsole(settings) {
|
|
2410
|
+
if (settings !== "console" && envCandidate() !== null) {
|
|
2411
|
+
warn(
|
|
2412
|
+
`baton: ${CANDIDATE_ENV} is set, but this server's settings are not "console", so the change is not fetched; today's settings apply.`
|
|
2413
|
+
);
|
|
2414
|
+
}
|
|
2255
2415
|
}
|
|
2256
|
-
|
|
2257
|
-
|
|
2416
|
+
var MATCH_KEYS = /* @__PURE__ */ new Set(["label", "client", "share"]);
|
|
2417
|
+
var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
|
|
2418
|
+
var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
|
|
2419
|
+
var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
|
|
2420
|
+
function shareBucket(vendorId2, key) {
|
|
2421
|
+
const digest = crypto2.createHash("sha256").update(`${vendorId2}
|
|
2422
|
+
${key}`, "utf-8").digest();
|
|
2423
|
+
return Number(digest.readBigUInt64BE(0) % 10000n);
|
|
2424
|
+
}
|
|
2425
|
+
function matchesEveryone(audience) {
|
|
2426
|
+
return audience.labels === null && audience.clients === null && audience.shareThreshold === null;
|
|
2427
|
+
}
|
|
2428
|
+
function matches(audience, caller, bucket) {
|
|
2429
|
+
if (audience.labels !== null && !caller.labels.some((label) => audience.labels.has(label))) return false;
|
|
2430
|
+
if (audience.clients !== null && (caller.clientName === null || !audience.clients.has(caller.clientName))) {
|
|
2431
|
+
return false;
|
|
2432
|
+
}
|
|
2433
|
+
if (audience.shareThreshold !== null && (bucket === null || bucket >= audience.shareThreshold)) return false;
|
|
2434
|
+
return true;
|
|
2435
|
+
}
|
|
2436
|
+
var SettingsDocument = class {
|
|
2437
|
+
constructor(version, audiences, serverOverlay, candidate) {
|
|
2438
|
+
this.version = version;
|
|
2439
|
+
this.audiences = audiences;
|
|
2440
|
+
this.serverOverlay = serverOverlay;
|
|
2441
|
+
const overlays = audiences.flatMap((a) => a.settings.overlay === void 0 ? [] : [a.settings.overlay]);
|
|
2442
|
+
this.hiddenSomewhere = new Set(overlays.flatMap((o) => [...o.hiddenTools]));
|
|
2443
|
+
this.audiencePieces = new Set(overlays.flatMap((o) => o.actions.flatMap((a) => a.piece === void 0 ? [] : [a.piece])));
|
|
2444
|
+
this.usesShare = audiences.some((a) => a.shareThreshold !== null);
|
|
2445
|
+
this.unmatched = { capture: { settings_version: version, ...candidate === void 0 ? {} : { candidate } } };
|
|
2446
|
+
this.reportsOnForAnyone = audiences.some((a) => a.settings.reportMode !== "off") || !audiences.some(matchesEveryone);
|
|
2447
|
+
}
|
|
2448
|
+
version;
|
|
2449
|
+
audiences;
|
|
2450
|
+
serverOverlay;
|
|
2451
|
+
usesShare;
|
|
2452
|
+
unmatched;
|
|
2453
|
+
/** Whether some caller can get reports, so the instructions point to the
|
|
2454
|
+
* tool. Read only where the code's value is "on": no tool exists otherwise. */
|
|
2455
|
+
reportsOnForAnyone;
|
|
2456
|
+
/** The tools some audience's overlay hides. */
|
|
2457
|
+
hiddenSomewhere;
|
|
2458
|
+
/** The pieces of Baton's text some audience's overlay changes. */
|
|
2459
|
+
audiencePieces;
|
|
2460
|
+
settingsFor(caller, vendorId2) {
|
|
2461
|
+
const bucket = caller.shareKey !== null && this.usesShare ? shareBucket(vendorId2, caller.shareKey) : null;
|
|
2462
|
+
return this.audiences.find((audience) => matches(audience, caller, bucket))?.settings ?? this.unmatched;
|
|
2463
|
+
}
|
|
2464
|
+
};
|
|
2465
|
+
function stringSet(value) {
|
|
2466
|
+
if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) return null;
|
|
2467
|
+
return new Set(value);
|
|
2468
|
+
}
|
|
2469
|
+
function readAudience(version, id, match, capture, overlay, candidate) {
|
|
2470
|
+
if (!Object.keys(match).every((key) => MATCH_KEYS.has(key))) return null;
|
|
2471
|
+
let labels = null;
|
|
2472
|
+
let clients = null;
|
|
2473
|
+
let shareThreshold = null;
|
|
2474
|
+
if (Object.hasOwn(match, "label") && (labels = stringSet(match.label)) === null) return null;
|
|
2475
|
+
if (Object.hasOwn(match, "client") && (clients = stringSet(match.client)) === null) return null;
|
|
2476
|
+
if (Object.hasOwn(match, "share")) {
|
|
2477
|
+
const share = match.share;
|
|
2478
|
+
if (typeof share !== "number" || !(share > 0 && share <= 1)) return null;
|
|
2479
|
+
shareThreshold = Math.floor(share * 1e4 + 0.5);
|
|
2480
|
+
}
|
|
2481
|
+
const settings = {
|
|
2482
|
+
capture: {
|
|
2483
|
+
settings_version: version,
|
|
2484
|
+
audience: id,
|
|
2485
|
+
...overlay === void 0 ? {} : { overlay: overlay.id },
|
|
2486
|
+
...candidate === void 0 ? {} : { candidate }
|
|
2487
|
+
}
|
|
2488
|
+
};
|
|
2489
|
+
if (overlay !== void 0) settings.overlay = overlay;
|
|
2490
|
+
const { results, goal, reports } = capture;
|
|
2491
|
+
if (typeof results === "string" && RESULT_CAPTURE_MODE_SET.has(results)) {
|
|
2492
|
+
settings.resultCaptureMode = results;
|
|
2493
|
+
}
|
|
2494
|
+
if (typeof goal === "string" && INTENT_PARAM_MODES.has(goal)) settings.intentParamMode = goal;
|
|
2495
|
+
if (typeof reports === "string" && REPORT_MODES.has(reports)) settings.reportMode = reports;
|
|
2496
|
+
return { settings, labels, clients, shareThreshold };
|
|
2497
|
+
}
|
|
2498
|
+
function parseDocument(body, candidate) {
|
|
2499
|
+
let data;
|
|
2500
|
+
try {
|
|
2501
|
+
data = JSON.parse(body);
|
|
2502
|
+
} catch {
|
|
2503
|
+
return null;
|
|
2504
|
+
}
|
|
2505
|
+
if (!isRecord(data)) return null;
|
|
2506
|
+
const { version, audiences } = data;
|
|
2507
|
+
if (typeof version !== "number" || !Number.isInteger(version) || version < 1) return null;
|
|
2508
|
+
if (!Array.isArray(audiences) || audiences.length === 0) return null;
|
|
2509
|
+
if (candidate !== void 0 && data.candidate !== candidate) return null;
|
|
2510
|
+
const overlays = readOverlays(data.overlays);
|
|
2511
|
+
const parsed = [];
|
|
2512
|
+
for (const audience of audiences) {
|
|
2513
|
+
if (!isRecord(audience)) return null;
|
|
2514
|
+
const { id, match, capture } = audience;
|
|
2515
|
+
if (typeof id !== "string" || !isRecord(match) || !isRecord(capture)) return null;
|
|
2516
|
+
const overlay = overlayFor(overlays, audience.overlay, "audience");
|
|
2517
|
+
const readable = readAudience(version, id, match, capture, overlay, candidate);
|
|
2518
|
+
if (readable !== null) parsed.push(readable);
|
|
2519
|
+
}
|
|
2520
|
+
return new SettingsDocument(version, parsed, overlayFor(overlays, data.server_overlay, "server"), candidate);
|
|
2521
|
+
}
|
|
2522
|
+
var SettingsFetcher = class {
|
|
2523
|
+
url;
|
|
2524
|
+
// `#`, not `private`, so logging a config shows no key: "logging the config shows no key".
|
|
2525
|
+
#headers;
|
|
2526
|
+
refreshMs;
|
|
2527
|
+
fetchImpl;
|
|
2528
|
+
etag = null;
|
|
2529
|
+
held = null;
|
|
2530
|
+
timer = null;
|
|
2531
|
+
reading = null;
|
|
2532
|
+
candidateReads = /* @__PURE__ */ new Set();
|
|
2533
|
+
warned = false;
|
|
2534
|
+
constructor(options) {
|
|
2535
|
+
this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
|
|
2536
|
+
this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
|
|
2537
|
+
this.refreshMs = options.refreshMs;
|
|
2538
|
+
this.fetchImpl = options.fetchImpl ?? globalFetch;
|
|
2539
|
+
}
|
|
2540
|
+
get document() {
|
|
2541
|
+
return this.held;
|
|
2542
|
+
}
|
|
2543
|
+
start() {
|
|
2544
|
+
if (this.timer !== null) return;
|
|
2545
|
+
this.timer = setInterval(() => void this.readOnce(), this.refreshMs);
|
|
2546
|
+
this.timer.unref?.();
|
|
2547
|
+
void this.readOnce();
|
|
2548
|
+
}
|
|
2549
|
+
stop() {
|
|
2550
|
+
if (this.timer !== null) clearInterval(this.timer);
|
|
2551
|
+
this.timer = null;
|
|
2552
|
+
this.reading?.abort();
|
|
2553
|
+
this.reading = null;
|
|
2554
|
+
for (const read of this.candidateReads) read.abort();
|
|
2555
|
+
}
|
|
2556
|
+
async fetchCandidate(candidate, timeoutMs) {
|
|
2557
|
+
const reading = new AbortController();
|
|
2558
|
+
const timeout = setTimeout(() => reading.abort(), timeoutMs);
|
|
2559
|
+
timeout.unref?.();
|
|
2560
|
+
this.candidateReads.add(reading);
|
|
2561
|
+
try {
|
|
2562
|
+
const url = `${this.url}&${new URLSearchParams({ candidate }).toString()}`;
|
|
2563
|
+
const response = await this.fetchImpl(url, {
|
|
2564
|
+
method: "GET",
|
|
2565
|
+
headers: this.#headers,
|
|
2566
|
+
redirect: "manual",
|
|
2567
|
+
signal: reading.signal
|
|
2568
|
+
});
|
|
2569
|
+
if (response.status !== 200) void response.body?.cancel().catch(() => void 0);
|
|
2570
|
+
if (response.status === 403) return { outcome: "refused" };
|
|
2571
|
+
if (response.status === 404) return { outcome: "unknown" };
|
|
2572
|
+
if (response.status === 200) {
|
|
2573
|
+
const document = parseDocument(await response.text(), candidate);
|
|
2574
|
+
if (document !== null) return { outcome: "loaded", document };
|
|
2575
|
+
}
|
|
2576
|
+
} catch {
|
|
2577
|
+
} finally {
|
|
2578
|
+
clearTimeout(timeout);
|
|
2579
|
+
this.candidateReads.delete(reading);
|
|
2580
|
+
}
|
|
2581
|
+
return { outcome: "failed" };
|
|
2582
|
+
}
|
|
2583
|
+
/** One request. Never rejects: a failure keeps what is held. */
|
|
2584
|
+
async readOnce() {
|
|
2585
|
+
if (this.reading !== null) return;
|
|
2586
|
+
const reading = new AbortController();
|
|
2587
|
+
this.reading = reading;
|
|
2588
|
+
const timeout = setTimeout(() => reading.abort(), REQUEST_TIMEOUT_MS);
|
|
2589
|
+
timeout.unref?.();
|
|
2590
|
+
try {
|
|
2591
|
+
await this.read(reading.signal);
|
|
2592
|
+
} catch {
|
|
2593
|
+
} finally {
|
|
2594
|
+
clearTimeout(timeout);
|
|
2595
|
+
if (this.reading === reading) this.reading = null;
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
2598
|
+
async read(signal) {
|
|
2599
|
+
const headers = this.etag === null ? this.#headers : { ...this.#headers, "If-None-Match": this.etag };
|
|
2600
|
+
const response = await this.fetchImpl(this.url, { method: "GET", headers, redirect: "manual", signal });
|
|
2601
|
+
if (response.status !== 200) {
|
|
2602
|
+
void response.body?.cancel().catch(() => void 0);
|
|
2603
|
+
}
|
|
2604
|
+
if (signal.aborted) return;
|
|
2605
|
+
if (response.status === 204) {
|
|
2606
|
+
this.held = null;
|
|
2607
|
+
this.etag = null;
|
|
2608
|
+
} else if (response.status === 200) {
|
|
2609
|
+
const document = parseDocument(await response.text());
|
|
2610
|
+
if (signal.aborted) return;
|
|
2611
|
+
if (document === null) {
|
|
2612
|
+
if (!this.warned) {
|
|
2613
|
+
this.warned = true;
|
|
2614
|
+
warn("baton: the collector sent capture settings this SDK cannot read");
|
|
2615
|
+
}
|
|
2616
|
+
return;
|
|
2617
|
+
}
|
|
2618
|
+
this.held = document;
|
|
2619
|
+
this.etag = response.headers.get("etag");
|
|
2620
|
+
}
|
|
2621
|
+
}
|
|
2622
|
+
};
|
|
2623
|
+
var PENDING = /* @__PURE__ */ Symbol("pending");
|
|
2624
|
+
var CaptureSettings = class {
|
|
2625
|
+
constructor(vendorId2, source, candidate = null, startTimeoutMs = CANDIDATE_START_TIMEOUT_MS) {
|
|
2626
|
+
this.vendorId = vendorId2;
|
|
2627
|
+
this.source = source;
|
|
2628
|
+
this.candidate = candidate;
|
|
2629
|
+
this.startTimeoutMs = startTimeoutMs;
|
|
2630
|
+
}
|
|
2631
|
+
vendorId;
|
|
2632
|
+
source;
|
|
2633
|
+
candidate;
|
|
2634
|
+
startTimeoutMs;
|
|
2635
|
+
processDocument = null;
|
|
2636
|
+
/** `BATON_CANDIDATE`'s read; requests wait for it. */
|
|
2637
|
+
ready = Promise.resolve();
|
|
2638
|
+
isReady = true;
|
|
2639
|
+
// id -> its document, `null` for an unknown id, `PENDING`, or the time a failed read may be tried again.
|
|
2640
|
+
held = /* @__PURE__ */ new Map();
|
|
2641
|
+
// A 403 is about the key, so it answers every id for this process.
|
|
2642
|
+
refused = false;
|
|
2643
|
+
stopped = false;
|
|
2644
|
+
retryAfterMs = REQUEST_TIMEOUT_MS;
|
|
2645
|
+
start() {
|
|
2646
|
+
const candidate = this.candidate;
|
|
2647
|
+
if (candidate !== null && this.processDocument === null) {
|
|
2648
|
+
const cannotLoad = (why) => warn(`baton: ${CANDIDATE_ENV}=${candidate} could not be loaded (${why}); today's settings apply.`);
|
|
2649
|
+
const fetched = this.source.fetchCandidate(candidate, this.startTimeoutMs);
|
|
2650
|
+
this.isReady = false;
|
|
2651
|
+
this.ready = raceDeadline(fetched, this.startTimeoutMs).then((read) => {
|
|
2652
|
+
this.isReady = true;
|
|
2653
|
+
if (this.stopped) return;
|
|
2654
|
+
if (read === TIMED_OUT) {
|
|
2655
|
+
cannotLoad("no answer");
|
|
2656
|
+
void fetched.then((late) => {
|
|
2657
|
+
if (!this.stopped && late.outcome === "refused") this.record(candidate, late);
|
|
2658
|
+
});
|
|
2659
|
+
return;
|
|
2660
|
+
}
|
|
2661
|
+
this.record(candidate, read);
|
|
2662
|
+
if (read.outcome === "loaded") this.processDocument = read.document;
|
|
2663
|
+
else if (read.outcome !== "refused") cannotLoad(read.outcome === "unknown" ? "unknown id" : "no answer");
|
|
2664
|
+
});
|
|
2665
|
+
}
|
|
2666
|
+
this.source.start();
|
|
2667
|
+
}
|
|
2668
|
+
stop() {
|
|
2669
|
+
this.stopped = true;
|
|
2670
|
+
this.source.stop();
|
|
2671
|
+
}
|
|
2672
|
+
/** The document for a request with no header of its own. */
|
|
2673
|
+
get document() {
|
|
2674
|
+
return this.processDocument ?? this.source.document;
|
|
2675
|
+
}
|
|
2676
|
+
/** `undefined` while no document is held, and the config's values apply. */
|
|
2677
|
+
forCaller(caller) {
|
|
2678
|
+
const document = caller.candidate == null ? this.document : this.headerDocument(caller.candidate) ?? this.source.document;
|
|
2679
|
+
return document?.settingsFor(caller, this.vendorId);
|
|
2680
|
+
}
|
|
2681
|
+
/** Whether `test` holds for some document a request could be served under now. */
|
|
2682
|
+
someDocument(test) {
|
|
2683
|
+
const today = this.document;
|
|
2684
|
+
if (today !== null && test(today)) return true;
|
|
2685
|
+
for (const held of this.held.values()) if (held instanceof SettingsDocument && test(held)) return true;
|
|
2686
|
+
return false;
|
|
2687
|
+
}
|
|
2688
|
+
/** The header's change if it is held. The first sight of an id starts its
|
|
2689
|
+
* read in the background, unless too many are already running. */
|
|
2690
|
+
headerDocument(candidate) {
|
|
2691
|
+
if (this.refused) return null;
|
|
2692
|
+
const held = this.held.get(candidate);
|
|
2693
|
+
if (held !== void 0 && !(typeof held === "number" && held <= Date.now())) {
|
|
2694
|
+
this.held.delete(candidate);
|
|
2695
|
+
this.held.set(candidate, held);
|
|
2696
|
+
return held instanceof SettingsDocument ? held : null;
|
|
2697
|
+
}
|
|
2698
|
+
if ([...this.held.values()].filter((v) => v === PENDING).length >= CANDIDATE_READS_AT_ONCE) return null;
|
|
2699
|
+
this.held.delete(candidate);
|
|
2700
|
+
this.held.set(candidate, PENDING);
|
|
2701
|
+
this.evict();
|
|
2702
|
+
void this.source.fetchCandidate(candidate, REQUEST_TIMEOUT_MS).then((read) => {
|
|
2703
|
+
if (!this.stopped) this.record(candidate, read);
|
|
2704
|
+
});
|
|
2705
|
+
return null;
|
|
2706
|
+
}
|
|
2707
|
+
record(candidate, read) {
|
|
2708
|
+
if (read.outcome === "refused") {
|
|
2709
|
+
if (!this.refused) {
|
|
2710
|
+
warn("baton: this server's key is not a test key, so test changes are not fetched; today's settings apply.");
|
|
2711
|
+
}
|
|
2712
|
+
this.held.delete(candidate);
|
|
2713
|
+
this.refused = true;
|
|
2714
|
+
} else if (read.outcome === "failed") {
|
|
2715
|
+
this.held.set(candidate, Date.now() + this.retryAfterMs);
|
|
2716
|
+
} else {
|
|
2717
|
+
this.held.set(candidate, read.outcome === "loaded" ? read.document : null);
|
|
2718
|
+
this.evict();
|
|
2719
|
+
}
|
|
2720
|
+
}
|
|
2721
|
+
evict() {
|
|
2722
|
+
for (const [key, value] of this.held) {
|
|
2723
|
+
if (this.held.size <= CANDIDATES_HELD) return;
|
|
2724
|
+
if (value !== PENDING) this.held.delete(key);
|
|
2725
|
+
}
|
|
2726
|
+
}
|
|
2727
|
+
};
|
|
2728
|
+
function overlayChanges(settings, piece) {
|
|
2729
|
+
return settings?.someDocument((d) => d.audiencePieces.has(piece)) ?? false;
|
|
2730
|
+
}
|
|
2731
|
+
function mayHide(settings, name) {
|
|
2732
|
+
return settings?.someDocument((d) => d.hiddenSomewhere.has(name)) ?? false;
|
|
2733
|
+
}
|
|
2734
|
+
|
|
2735
|
+
// src/integrations/mcp/mcpTypes.ts
|
|
2736
|
+
function extraAuthInfo(extra) {
|
|
2737
|
+
const found = extra.authInfo ?? extra.http?.authInfo;
|
|
2738
|
+
return found !== null && typeof found === "object" ? found : null;
|
|
2739
|
+
}
|
|
2740
|
+
function extraMeta(extra) {
|
|
2741
|
+
const direct = extra._meta;
|
|
2742
|
+
if (direct) return direct;
|
|
2743
|
+
const nested = extra.mcpReq?._meta;
|
|
2744
|
+
return nested ?? null;
|
|
2745
|
+
}
|
|
2746
|
+
function extraEnvelope(extra) {
|
|
2747
|
+
const envelope = extra.mcpReq?.envelope;
|
|
2748
|
+
return envelope ?? null;
|
|
2749
|
+
}
|
|
2750
|
+
function observeTransport(extra) {
|
|
2751
|
+
try {
|
|
2752
|
+
const carrier = extra.http?.req ?? extra.requestInfo;
|
|
2753
|
+
return carrier ? "http" : "no-http-request";
|
|
2754
|
+
} catch {
|
|
2755
|
+
return "read-failed";
|
|
2756
|
+
}
|
|
2757
|
+
}
|
|
2758
|
+
function extraHeaders(extra) {
|
|
2759
|
+
const fromV2 = extra.http?.req?.headers;
|
|
2760
|
+
if (fromV2 && typeof fromV2.get === "function") return fromV2;
|
|
2761
|
+
const fromV1 = extra.requestInfo?.headers;
|
|
2762
|
+
if (fromV1 && typeof fromV1 === "object") {
|
|
2763
|
+
const headers = new Headers();
|
|
2764
|
+
for (const [name, value] of Object.entries(fromV1)) {
|
|
2765
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
2766
|
+
if (typeof item !== "string") continue;
|
|
2767
|
+
try {
|
|
2768
|
+
headers.append(name, item);
|
|
2769
|
+
} catch {
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
}
|
|
2773
|
+
return headers;
|
|
2774
|
+
}
|
|
2775
|
+
return null;
|
|
2776
|
+
}
|
|
2777
|
+
function isThenable(value) {
|
|
2778
|
+
return typeof value?.then === "function";
|
|
2779
|
+
}
|
|
2780
|
+
|
|
2781
|
+
// src/integrations/mcp/principalResolution.ts
|
|
2782
|
+
function buildPrincipalResolutionContext(extra, toolName, args) {
|
|
2783
|
+
return {
|
|
2784
|
+
headers: extraHeaders(extra),
|
|
2785
|
+
meta: extraMeta(extra),
|
|
2786
|
+
toolName,
|
|
2787
|
+
arguments: args,
|
|
2788
|
+
authInfo: extraAuthInfo(extra)
|
|
2789
|
+
};
|
|
2790
|
+
}
|
|
2791
|
+
var HOOK_TIMEOUT_MS = 5e3;
|
|
2792
|
+
async function withinHookBudget(answer) {
|
|
2793
|
+
if (!isThenable(answer)) return answer;
|
|
2794
|
+
const first = await raceDeadline(answer, HOOK_TIMEOUT_MS);
|
|
2795
|
+
if (first !== TIMED_OUT) return first;
|
|
2796
|
+
warn(
|
|
2797
|
+
`baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
|
|
2798
|
+
);
|
|
2799
|
+
return null;
|
|
2800
|
+
}
|
|
2801
|
+
var warned2 = /* @__PURE__ */ new Set();
|
|
2802
|
+
function warnOnce(key, message) {
|
|
2803
|
+
if (warned2.has(key)) return;
|
|
2804
|
+
warned2.add(key);
|
|
2805
|
+
warn(`baton: resolvePrincipal ${message}`);
|
|
2806
|
+
}
|
|
2807
|
+
function callerEnvelope(caller) {
|
|
2808
|
+
return {
|
|
2809
|
+
principal: caller.principal,
|
|
2810
|
+
organization: caller.organization,
|
|
2811
|
+
labels: wireLabels(caller.labels),
|
|
2812
|
+
capture: caller.settings?.capture ?? null
|
|
2813
|
+
};
|
|
2814
|
+
}
|
|
2815
|
+
var settingsWarned = false;
|
|
2816
|
+
async function resolveCaller(hook, call, settings, client = null) {
|
|
2817
|
+
const caller = await resolveIdentity(hook, call);
|
|
2818
|
+
if (settings === void 0) return caller;
|
|
2819
|
+
try {
|
|
2820
|
+
const callSettings = settings.forCaller({
|
|
2821
|
+
labels: caller.labels,
|
|
2822
|
+
clientName: client?.info?.name ?? null,
|
|
2823
|
+
shareKey: caller.principal?.id ?? null,
|
|
2824
|
+
candidate: headerCandidate(extraHeaders(call.extra))
|
|
2825
|
+
});
|
|
2826
|
+
return callSettings === void 0 ? caller : { ...caller, settings: callSettings };
|
|
2827
|
+
} catch {
|
|
2828
|
+
if (!settingsWarned) {
|
|
2829
|
+
settingsWarned = true;
|
|
2830
|
+
warn("baton: applying capture settings failed; this request uses the config's values");
|
|
2831
|
+
}
|
|
2832
|
+
return caller;
|
|
2833
|
+
}
|
|
2834
|
+
}
|
|
2835
|
+
async function resolveIdentity(hook, call) {
|
|
2836
|
+
if (hook === void 0) return NO_CALLER;
|
|
2837
|
+
try {
|
|
2838
|
+
const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
|
|
2839
|
+
const result = await withinHookBudget(hook(context));
|
|
2840
|
+
return callerFor(result, warnOnce);
|
|
2841
|
+
} catch {
|
|
2842
|
+
return NO_CALLER;
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
|
|
2846
|
+
// src/integrations/mcp/zodCompat.ts
|
|
2847
|
+
var z3rt = __toESM(require("zod/v3"), 1);
|
|
2848
|
+
var z4mini = __toESM(require("zod/v4-mini"), 1);
|
|
2849
|
+
var import_zod_to_json_schema = require("zod-to-json-schema");
|
|
2850
|
+
function isZ4Schema(s) {
|
|
2851
|
+
const schema = s;
|
|
2852
|
+
return !!schema?._zod;
|
|
2853
|
+
}
|
|
2854
|
+
function objectFromShape(shape) {
|
|
2855
|
+
const values = Object.values(shape);
|
|
2856
|
+
if (values.length === 0) return z4mini.object({});
|
|
2857
|
+
const allV4 = values.every(isZ4Schema);
|
|
2858
|
+
const allV3 = values.every((s) => !isZ4Schema(s));
|
|
2859
|
+
if (allV4) return z4mini.object(shape);
|
|
2860
|
+
if (allV3) return z3rt.object(shape);
|
|
2861
|
+
throw new Error("Mixed Zod versions detected in object shape.");
|
|
2862
|
+
}
|
|
2863
|
+
function getObjectShape(schema) {
|
|
2864
|
+
if (!schema) return void 0;
|
|
2258
2865
|
let rawShape;
|
|
2259
2866
|
if (isZ4Schema(schema)) {
|
|
2260
2867
|
rawShape = schema._zod?.def?.shape;
|
|
@@ -2389,6 +2996,15 @@ function advertiseIntentParamsRequired(result, names, isInjected) {
|
|
|
2389
2996
|
});
|
|
2390
2997
|
return changed ? { ...result, tools: advertised } : result;
|
|
2391
2998
|
}
|
|
2999
|
+
function withToolInputSchema(result, name, inputSchema2) {
|
|
3000
|
+
const tools = result?.tools;
|
|
3001
|
+
if (!Array.isArray(tools)) return result;
|
|
3002
|
+
const at = tools.findIndex((tool) => isRecord(tool) && tool.name === name);
|
|
3003
|
+
if (at === -1) return result;
|
|
3004
|
+
const served = [...tools];
|
|
3005
|
+
served[at] = { ...tools[at], inputSchema: inputSchema2 };
|
|
3006
|
+
return { ...result, tools: served };
|
|
3007
|
+
}
|
|
2392
3008
|
function standardInputJsonSchema(schema) {
|
|
2393
3009
|
try {
|
|
2394
3010
|
const standard = schema?.["~standard"];
|
|
@@ -2407,17 +3023,16 @@ function toolInputJsonSchema(inputSchema2) {
|
|
|
2407
3023
|
}
|
|
2408
3024
|
|
|
2409
3025
|
// src/integrations/mcp/safeScrub.ts
|
|
2410
|
-
var
|
|
3026
|
+
var warned3 = /* @__PURE__ */ new Set();
|
|
2411
3027
|
function scrubOrNull(scrubber, value, field) {
|
|
2412
3028
|
if (value === null) return null;
|
|
2413
3029
|
try {
|
|
2414
3030
|
return scrubber(value);
|
|
2415
3031
|
} catch (err) {
|
|
2416
|
-
if (!
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}
|
|
2420
|
-
`
|
|
3032
|
+
if (!warned3.has(field)) {
|
|
3033
|
+
warned3.add(field);
|
|
3034
|
+
stderrLine(
|
|
3035
|
+
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}`
|
|
2421
3036
|
);
|
|
2422
3037
|
}
|
|
2423
3038
|
return null;
|
|
@@ -2552,7 +3167,8 @@ var ANNOTATION_INPUT_SHAPE = {
|
|
|
2552
3167
|
// not rejected by validation.
|
|
2553
3168
|
tool_name: import_zod3.z.string().nullable().optional(),
|
|
2554
3169
|
suggested_improvement: import_zod3.z.string().optional(),
|
|
2555
|
-
|
|
3170
|
+
// zod renders "any value" as `{}`, which some MCP clients refuse (reportToolSchema.test.ts).
|
|
3171
|
+
context: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).meta({ additionalProperties: true }).optional()
|
|
2556
3172
|
};
|
|
2557
3173
|
function isReport(whatHappened) {
|
|
2558
3174
|
return typeof whatHappened === "string" && !isBlank(whatHappened);
|
|
@@ -2584,33 +3200,21 @@ function buildAnnotationTool(server, options) {
|
|
|
2584
3200
|
const description = buildAnnotationToolDescription({
|
|
2585
3201
|
vendorDisplayName: options.vendorDisplayName
|
|
2586
3202
|
});
|
|
2587
|
-
const
|
|
3203
|
+
const refused = (overlay) => ({
|
|
3204
|
+
content: [
|
|
3205
|
+
{
|
|
3206
|
+
type: "text",
|
|
3207
|
+
text: JSON.stringify({ ok: false, error: buildRefusalText({ annotationToolName: name, overlay }) })
|
|
3208
|
+
}
|
|
3209
|
+
]
|
|
3210
|
+
});
|
|
2588
3211
|
return {
|
|
2589
3212
|
name,
|
|
2590
3213
|
description,
|
|
2591
3214
|
handler: async (args, extra) => {
|
|
2592
3215
|
const whatHappened = args.what_happened;
|
|
2593
|
-
if (!isReport(whatHappened))
|
|
2594
|
-
return {
|
|
2595
|
-
content: [
|
|
2596
|
-
{
|
|
2597
|
-
type: "text",
|
|
2598
|
-
text: JSON.stringify({
|
|
2599
|
-
ok: false,
|
|
2600
|
-
error: refusal
|
|
2601
|
-
})
|
|
2602
|
-
}
|
|
2603
|
-
]
|
|
2604
|
-
};
|
|
2605
|
-
}
|
|
3216
|
+
if (!isReport(whatHappened) && !overlayChanges(options.captureSettings, "report_tool.refusal")) return refused();
|
|
2606
3217
|
const reportedTool = args.tool_name ?? null;
|
|
2607
|
-
const meta = extraMeta(extra);
|
|
2608
|
-
const scrubbedMeta = scrubOrNull(
|
|
2609
|
-
options.scrubber,
|
|
2610
|
-
meta ? roundMetaCoordinates(meta) : null,
|
|
2611
|
-
"_meta"
|
|
2612
|
-
);
|
|
2613
|
-
const session = await resolveSessionId(options.fallbackSessionId, extra);
|
|
2614
3218
|
const client = observeClient(extra, { server, scrubber: options.scrubber });
|
|
2615
3219
|
const caller = await resolveCaller(
|
|
2616
3220
|
options.resolvePrincipal,
|
|
@@ -2618,6 +3222,14 @@ function buildAnnotationTool(server, options) {
|
|
|
2618
3222
|
options.captureSettings,
|
|
2619
3223
|
client
|
|
2620
3224
|
);
|
|
3225
|
+
if (!isReport(whatHappened)) return refused(caller.settings?.overlay);
|
|
3226
|
+
const meta = extraMeta(extra);
|
|
3227
|
+
const scrubbedMeta = scrubOrNull(
|
|
3228
|
+
options.scrubber,
|
|
3229
|
+
meta ? roundMetaCoordinates(meta) : null,
|
|
3230
|
+
"_meta"
|
|
3231
|
+
);
|
|
3232
|
+
const session = await resolveSessionId(options.fallbackSessionId, extra);
|
|
2621
3233
|
await emit(
|
|
2622
3234
|
options.sink,
|
|
2623
3235
|
() => AnnotationEventSchema.parse({
|
|
@@ -2658,9 +3270,11 @@ var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
|
|
|
2658
3270
|
var NOT_IN_A_KEY = /[\x00\t\n\r]/;
|
|
2659
3271
|
var PUBLISHABLE_PREFIX = "baton_pk_";
|
|
2660
3272
|
var SECRET_PREFIX = "baton_sk_";
|
|
2661
|
-
var
|
|
3273
|
+
var TEST_PREFIX = "baton_tk_";
|
|
3274
|
+
var KEY_PREFIXES = [PUBLISHABLE_PREFIX, SECRET_PREFIX, TEST_PREFIX];
|
|
3275
|
+
var KEY_RUN = /baton_(?:(?:pk|sk|tk)_[A-Za-z0-9_%-]{8,}|[A-Za-z0-9_%-]{43,})/g;
|
|
2662
3276
|
function looksLikeAKey(value) {
|
|
2663
|
-
return
|
|
3277
|
+
return KEY_PREFIXES.some((prefix) => value.startsWith(prefix));
|
|
2664
3278
|
}
|
|
2665
3279
|
function containsKey(value) {
|
|
2666
3280
|
return sweep(value) !== value;
|
|
@@ -2730,385 +3344,123 @@ function selectDsn(explicit, supplied, door) {
|
|
|
2730
3344
|
);
|
|
2731
3345
|
return void 0;
|
|
2732
3346
|
}
|
|
2733
|
-
return ambient;
|
|
2734
|
-
}
|
|
2735
|
-
function parseDsn(raw) {
|
|
2736
|
-
const dsn = typeof raw === "string" ? stripWhiteSpace(raw) : "";
|
|
2737
|
-
if (dsn === "") fail("dsn must be a non-empty string");
|
|
2738
|
-
if (looksLikeAKey(dsn)) {
|
|
2739
|
-
fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
|
|
2740
|
-
}
|
|
2741
|
-
const safe = redact(dsn);
|
|
2742
|
-
const parts = splitDsn(dsn);
|
|
2743
|
-
if (parts === null || parts.scheme !== "https" && parts.scheme !== "http") {
|
|
2744
|
-
fail(
|
|
2745
|
-
`dsn ${safe} must start with https:// (or http:// for local development) \u2014 ${BARE_KEY_HINT}`
|
|
2746
|
-
);
|
|
2747
|
-
}
|
|
2748
|
-
const { key, at, authority } = splitKeyFromAuthority(parts.netloc);
|
|
2749
|
-
if (!at || !key) {
|
|
2750
|
-
if (looksLikeAKey(parts.netloc)) {
|
|
2751
|
-
fail(
|
|
2752
|
-
`dsn ${safe} is a bare key with a scheme in front of it: ${BARE_KEY_HINT}. The full value also carries a host, your workspace and your server \u2014 https://baton_pk_...@host/ten_.../server`
|
|
2753
|
-
);
|
|
2754
|
-
}
|
|
2755
|
-
const misplaced = parts.path.split("/").some((segment) => containsKey(segment));
|
|
2756
|
-
const detail = misplaced ? "the key is in the PATH \u2014 it goes before an @" : "the value from /account has the key before an @";
|
|
2757
|
-
fail(
|
|
2758
|
-
`dsn ${safe} carries no key: ${detail}, as in https://baton_pk_...@host/ten_.../server`
|
|
2759
|
-
);
|
|
2760
|
-
}
|
|
2761
|
-
if (NOT_IN_A_KEY.test(key)) {
|
|
2762
|
-
fail(
|
|
2763
|
-
`dsn ${safe} has a tab, a line break or a null inside its key \u2014 no key from /account contains one, so this DSN could not have worked. Check for a line wrap where the value was copied.`
|
|
2764
|
-
);
|
|
2765
|
-
}
|
|
2766
|
-
if (key.includes(":")) {
|
|
2767
|
-
fail(
|
|
2768
|
-
`dsn ${safe} has a ':' in its key \u2014 a DSN carries one credential and no password field`
|
|
2769
|
-
);
|
|
2770
|
-
}
|
|
2771
|
-
if (!authority) {
|
|
2772
|
-
fail(`dsn ${safe} has no host`);
|
|
2773
|
-
}
|
|
2774
|
-
if (containsKey(authority)) {
|
|
2775
|
-
fail(
|
|
2776
|
-
`dsn ${safe} has the KEY where the host belongs. The order is key, @, host \u2014 check whether the two are the wrong way round: https://baton_pk_...@host/ten_.../<server>`
|
|
2777
|
-
);
|
|
2778
|
-
}
|
|
2779
|
-
if (NOT_IN_A_HOST.test(authority)) {
|
|
2780
|
-
fail(
|
|
2781
|
-
`dsn ${safe} has whitespace, a control character or a backslash inside its host. Those are silently REMOVED or reinterpreted when a URL is parsed, so the address dialled would not be the one you wrote \u2014 check for a line wrap or a stray space where the value was copied.`
|
|
2782
|
-
);
|
|
2783
|
-
}
|
|
2784
|
-
let hostReason = null;
|
|
2785
|
-
let parsedAuthority = null;
|
|
2786
|
-
try {
|
|
2787
|
-
parsedAuthority = new URL(`${parts.scheme}://${authority}`);
|
|
2788
|
-
} catch (error) {
|
|
2789
|
-
hostReason = error instanceof Error ? error.constructor.name : "Error";
|
|
2790
|
-
}
|
|
2791
|
-
if (parsedAuthority === null) {
|
|
2792
|
-
fail(`dsn ${safe} is not a parseable URL (${hostReason ?? "Error"})`);
|
|
2793
|
-
}
|
|
2794
|
-
const segments = parts.path.split("/").filter((segment) => segment !== "");
|
|
2795
|
-
const [workspace, server, ...extra] = segments;
|
|
2796
|
-
if (workspace === void 0 || server === void 0 || extra.length > 0) {
|
|
2797
|
-
fail(
|
|
2798
|
-
`dsn ${safe} must carry exactly two path segments \u2014 the workspace and the server, as in /ten_.../<server>. A missing server is never defaulted: it is what the key is bound to.`
|
|
2799
|
-
);
|
|
2800
|
-
}
|
|
2801
|
-
for (const [slot, segment] of [
|
|
2802
|
-
["workspace", workspace],
|
|
2803
|
-
["server", server]
|
|
2804
|
-
]) {
|
|
2805
|
-
if (containsKey(segment)) {
|
|
2806
|
-
fail(
|
|
2807
|
-
`dsn ${safe} has a KEY in the ${slot} slot. The key goes before the @, and the path carries the workspace and the server: https://baton_pk_...@host/ten_.../<server>`
|
|
2808
|
-
);
|
|
2809
|
-
}
|
|
2810
|
-
}
|
|
2811
|
-
if (!WORKSPACE_PATTERN.test(workspace)) {
|
|
2812
|
-
fail(
|
|
2813
|
-
`dsn ${safe} has ${JSON.stringify(workspace)} where the workspace belongs \u2014 expected ten_ followed by 8 or 32 hex characters. If the two path segments are the right way round, this is not a Baton DSN.`
|
|
2814
|
-
);
|
|
2815
|
-
}
|
|
2816
|
-
if (!VENDOR_ID_PATTERN.test(server)) {
|
|
2817
|
-
fail(
|
|
2818
|
-
`dsn ${safe} has ${JSON.stringify(server)} where the server belongs \u2014 it must match ${VENDOR_ID_PATTERN.source}, because this value becomes the annotation tool name prefix as well as the envelope's vendor_id.`
|
|
2819
|
-
);
|
|
2820
|
-
}
|
|
2821
|
-
if (key.startsWith(SECRET_PREFIX)) {
|
|
2822
|
-
warn(
|
|
2823
|
-
`baton: this DSN carries a ${SECRET_PREFIX} key (a workspace SECRET) where a ${PUBLISHABLE_PREFIX} key belongs. It will work. But if this server ships to anyone else, that key reads and writes everything the workspace holds \u2014 mint a publishable key at /account instead.`
|
|
2824
|
-
);
|
|
2825
|
-
}
|
|
2826
|
-
return sealKey({
|
|
2827
|
-
origin: `${parts.scheme}://${authority}`,
|
|
2828
|
-
tenantId: workspace,
|
|
2829
|
-
vendorId: server,
|
|
2830
|
-
key
|
|
2831
|
-
});
|
|
2832
|
-
}
|
|
2833
|
-
function sealKey(dsn) {
|
|
2834
|
-
const shown = {
|
|
2835
|
-
origin: dsn.origin,
|
|
2836
|
-
tenantId: dsn.tenantId,
|
|
2837
|
-
vendorId: dsn.vendorId,
|
|
2838
|
-
key: "<key>"
|
|
2839
|
-
};
|
|
2840
|
-
Object.defineProperty(dsn, "toJSON", {
|
|
2841
|
-
value: () => shown,
|
|
2842
|
-
enumerable: false
|
|
2843
|
-
});
|
|
2844
|
-
Object.defineProperty(dsn, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
|
|
2845
|
-
value: () => shown,
|
|
2846
|
-
enumerable: false
|
|
2847
|
-
});
|
|
2848
|
-
return dsn;
|
|
2849
|
-
}
|
|
2850
|
-
|
|
2851
|
-
// src/integrations/mcp/errorResult.ts
|
|
2852
|
-
var TOOL_ERROR_TYPE = "tool_error";
|
|
2853
|
-
var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
|
|
2854
|
-
var REFUSED = "refused";
|
|
2855
|
-
var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
|
|
2856
|
-
function requestSideFailureKind(entry, validation) {
|
|
2857
|
-
if (entry == null) return "unknown_tool";
|
|
2858
|
-
if (entry.enabled === false) return "tool_disabled";
|
|
2859
|
-
if (validation === "rejected") return "invalid_argument";
|
|
2860
|
-
if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
|
|
2861
|
-
return REFUSED;
|
|
2862
|
-
}
|
|
2863
|
-
var ERROR_BODY_MAX_CODE_POINTS = 2e3;
|
|
2864
|
-
function isErrorResult(value) {
|
|
2865
|
-
try {
|
|
2866
|
-
if (typeof value !== "object" || value === null) return false;
|
|
2867
|
-
return Boolean(value.isError);
|
|
2868
|
-
} catch {
|
|
2869
|
-
return false;
|
|
2870
|
-
}
|
|
2871
|
-
}
|
|
2872
|
-
function errorText(value) {
|
|
2873
|
-
const parts = [];
|
|
2874
|
-
try {
|
|
2875
|
-
const content = value?.content;
|
|
2876
|
-
if (!Array.isArray(content)) return "";
|
|
2877
|
-
for (const part of content) {
|
|
2878
|
-
const text = part?.text;
|
|
2879
|
-
if (typeof text !== "string") continue;
|
|
2880
|
-
const trimmed = stripWhiteSpace(text);
|
|
2881
|
-
if (trimmed) parts.push(trimmed);
|
|
2882
|
-
}
|
|
2883
|
-
} catch {
|
|
2884
|
-
return "";
|
|
2885
|
-
}
|
|
2886
|
-
return parts.join("\n");
|
|
2887
|
-
}
|
|
2888
|
-
var RESULT_CAPTURE_MODES = ["full", "off"];
|
|
2889
|
-
var WITHHELD = "off";
|
|
2890
|
-
function endResultFields(mode, result, scrubber) {
|
|
2891
|
-
switch (mode) {
|
|
2892
|
-
case WITHHELD:
|
|
2893
|
-
return { result: null, result_capture: WITHHELD };
|
|
2894
|
-
case "full":
|
|
2895
|
-
return { result: scrubber(result) };
|
|
2896
|
-
}
|
|
2897
|
-
}
|
|
2898
|
-
function returnedErrorFields(mode, result, errorBody2, scrubber) {
|
|
2899
|
-
return resultDerivedFields(mode, () => errorText(result), result, errorBody2, scrubber);
|
|
2900
|
-
}
|
|
2901
|
-
function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
|
|
2902
|
-
switch (mode) {
|
|
2903
|
-
case WITHHELD:
|
|
2904
|
-
return { error_body: "", result: null, result_capture: WITHHELD };
|
|
2905
|
-
case "full":
|
|
2906
|
-
return { error_body: errorBody2(text()), result: scrubber(result) };
|
|
2907
|
-
}
|
|
2908
|
-
}
|
|
2909
|
-
function requestSideErrorFields(text, errorBody2) {
|
|
2910
|
-
return { error_body: errorBody2(text), result: null };
|
|
2911
|
-
}
|
|
2912
|
-
function requestSideFailureFields(kind, mode, text, result, errorBody2, scrubber) {
|
|
2913
|
-
return kind === REFUSED ? resultDerivedFields(mode, text, result ?? null, errorBody2, scrubber) : requestSideErrorFields(text(), errorBody2);
|
|
2914
|
-
}
|
|
2915
|
-
function errorTypeOf(err) {
|
|
2916
|
-
return err instanceof Error ? err.constructor.name : "Error";
|
|
2917
|
-
}
|
|
2918
|
-
function messageOf(err) {
|
|
2919
|
-
return err instanceof Error ? err.message : String(err);
|
|
2920
|
-
}
|
|
2921
|
-
function scrubbedErrorBody(scrubber, text) {
|
|
2922
|
-
return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
|
|
2923
|
-
}
|
|
2924
|
-
|
|
2925
|
-
// src/integrations/mcp/captureSettings.ts
|
|
2926
|
-
var import_node_crypto2 = require("crypto");
|
|
2927
|
-
var SETTINGS_PATH = "/v0/settings";
|
|
2928
|
-
var TENANT_HEADER = "X-Baton-Tenant-Id";
|
|
2929
|
-
var SETTINGS_MODES = ["local", "console"];
|
|
2930
|
-
var DEFAULT_SETTINGS_REFRESH_MS = 6e4;
|
|
2931
|
-
var MIN_SETTINGS_REFRESH_MS = 15e3;
|
|
2932
|
-
var REQUEST_TIMEOUT_MS = 1e4;
|
|
2933
|
-
var MATCH_KEYS = /* @__PURE__ */ new Set(["label", "client", "share"]);
|
|
2934
|
-
var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
|
|
2935
|
-
var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
|
|
2936
|
-
var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
|
|
2937
|
-
function shareBucket(vendorId2, key) {
|
|
2938
|
-
const digest = (0, import_node_crypto2.createHash)("sha256").update(`${vendorId2}
|
|
2939
|
-
${key}`, "utf-8").digest();
|
|
2940
|
-
return Number(digest.readBigUInt64BE(0) % 10000n);
|
|
2941
|
-
}
|
|
2942
|
-
function matchesEveryone(audience) {
|
|
2943
|
-
return audience.labels === null && audience.clients === null && audience.shareThreshold === null;
|
|
2944
|
-
}
|
|
2945
|
-
function matches(audience, caller, bucket) {
|
|
2946
|
-
if (audience.labels !== null && !caller.labels.some((label) => audience.labels.has(label))) return false;
|
|
2947
|
-
if (audience.clients !== null && (caller.clientName === null || !audience.clients.has(caller.clientName))) {
|
|
2948
|
-
return false;
|
|
2949
|
-
}
|
|
2950
|
-
if (audience.shareThreshold !== null && (bucket === null || bucket >= audience.shareThreshold)) return false;
|
|
2951
|
-
return true;
|
|
2952
|
-
}
|
|
2953
|
-
var SettingsDocument = class {
|
|
2954
|
-
constructor(version, audiences) {
|
|
2955
|
-
this.version = version;
|
|
2956
|
-
this.audiences = audiences;
|
|
2957
|
-
this.usesShare = audiences.some((a) => a.shareThreshold !== null);
|
|
2958
|
-
this.unmatched = { capture: { settings_version: version } };
|
|
2959
|
-
this.reportsOnForAnyone = audiences.some((a) => a.settings.reportMode !== "off") || !audiences.some(matchesEveryone);
|
|
2960
|
-
}
|
|
2961
|
-
version;
|
|
2962
|
-
audiences;
|
|
2963
|
-
usesShare;
|
|
2964
|
-
unmatched;
|
|
2965
|
-
/** Whether some caller can get reports, so the instructions point to the
|
|
2966
|
-
* tool. Read only where the code's value is "on": no tool exists otherwise. */
|
|
2967
|
-
reportsOnForAnyone;
|
|
2968
|
-
settingsFor(caller, vendorId2) {
|
|
2969
|
-
const bucket = caller.shareKey !== null && this.usesShare ? shareBucket(vendorId2, caller.shareKey) : null;
|
|
2970
|
-
return this.audiences.find((audience) => matches(audience, caller, bucket))?.settings ?? this.unmatched;
|
|
2971
|
-
}
|
|
2972
|
-
};
|
|
2973
|
-
function stringSet(value) {
|
|
2974
|
-
if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) return null;
|
|
2975
|
-
return new Set(value);
|
|
2976
|
-
}
|
|
2977
|
-
function readAudience(version, id, match, capture) {
|
|
2978
|
-
if (!Object.keys(match).every((key) => MATCH_KEYS.has(key))) return null;
|
|
2979
|
-
let labels = null;
|
|
2980
|
-
let clients = null;
|
|
2981
|
-
let shareThreshold = null;
|
|
2982
|
-
if (Object.hasOwn(match, "label") && (labels = stringSet(match.label)) === null) return null;
|
|
2983
|
-
if (Object.hasOwn(match, "client") && (clients = stringSet(match.client)) === null) return null;
|
|
2984
|
-
if (Object.hasOwn(match, "share")) {
|
|
2985
|
-
const share = match.share;
|
|
2986
|
-
if (typeof share !== "number" || !(share > 0 && share <= 1)) return null;
|
|
2987
|
-
shareThreshold = Math.floor(share * 1e4 + 0.5);
|
|
2988
|
-
}
|
|
2989
|
-
const settings = { capture: { settings_version: version, audience: id } };
|
|
2990
|
-
const { results, goal, reports } = capture;
|
|
2991
|
-
if (typeof results === "string" && RESULT_CAPTURE_MODE_SET.has(results)) {
|
|
2992
|
-
settings.resultCaptureMode = results;
|
|
2993
|
-
}
|
|
2994
|
-
if (typeof goal === "string" && INTENT_PARAM_MODES.has(goal)) settings.intentParamMode = goal;
|
|
2995
|
-
if (typeof reports === "string" && REPORT_MODES.has(reports)) settings.reportMode = reports;
|
|
2996
|
-
return { settings, labels, clients, shareThreshold };
|
|
3347
|
+
return ambient;
|
|
2997
3348
|
}
|
|
2998
|
-
function
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
return null;
|
|
3349
|
+
function parseDsn(raw) {
|
|
3350
|
+
const dsn = typeof raw === "string" ? stripWhiteSpace(raw) : "";
|
|
3351
|
+
if (dsn === "") fail("dsn must be a non-empty string");
|
|
3352
|
+
if (looksLikeAKey(dsn)) {
|
|
3353
|
+
fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
|
|
3004
3354
|
}
|
|
3005
|
-
|
|
3006
|
-
const
|
|
3007
|
-
if (
|
|
3008
|
-
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
if (!isRecord(audience)) return null;
|
|
3012
|
-
const { id, match, capture } = audience;
|
|
3013
|
-
if (typeof id !== "string" || !isRecord(match) || !isRecord(capture)) return null;
|
|
3014
|
-
const readable = readAudience(version, id, match, capture);
|
|
3015
|
-
if (readable !== null) parsed.push(readable);
|
|
3355
|
+
const safe = redact(dsn);
|
|
3356
|
+
const parts = splitDsn(dsn);
|
|
3357
|
+
if (parts === null || parts.scheme !== "https" && parts.scheme !== "http") {
|
|
3358
|
+
fail(
|
|
3359
|
+
`dsn ${safe} must start with https:// (or http:// for local development) \u2014 ${BARE_KEY_HINT}`
|
|
3360
|
+
);
|
|
3016
3361
|
}
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
warned = false;
|
|
3030
|
-
constructor(options) {
|
|
3031
|
-
this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
|
|
3032
|
-
this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
|
|
3033
|
-
this.refreshMs = options.refreshMs;
|
|
3034
|
-
this.fetchImpl = options.fetchImpl ?? globalFetch;
|
|
3362
|
+
const { key, at, authority } = splitKeyFromAuthority(parts.netloc);
|
|
3363
|
+
if (!at || !key) {
|
|
3364
|
+
if (looksLikeAKey(parts.netloc)) {
|
|
3365
|
+
fail(
|
|
3366
|
+
`dsn ${safe} is a bare key with a scheme in front of it: ${BARE_KEY_HINT}. The full value also carries a host, your workspace and your server \u2014 https://baton_pk_...@host/ten_.../server`
|
|
3367
|
+
);
|
|
3368
|
+
}
|
|
3369
|
+
const misplaced = parts.path.split("/").some((segment) => containsKey(segment));
|
|
3370
|
+
const detail = misplaced ? "the key is in the PATH \u2014 it goes before an @" : "the value from /account has the key before an @";
|
|
3371
|
+
fail(
|
|
3372
|
+
`dsn ${safe} carries no key: ${detail}, as in https://baton_pk_...@host/ten_.../server`
|
|
3373
|
+
);
|
|
3035
3374
|
}
|
|
3036
|
-
|
|
3037
|
-
|
|
3375
|
+
if (NOT_IN_A_KEY.test(key)) {
|
|
3376
|
+
fail(
|
|
3377
|
+
`dsn ${safe} has a tab, a line break or a null inside its key \u2014 no key from /account contains one, so this DSN could not have worked. Check for a line wrap where the value was copied.`
|
|
3378
|
+
);
|
|
3038
3379
|
}
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
void this.readOnce();
|
|
3380
|
+
if (key.includes(":")) {
|
|
3381
|
+
fail(
|
|
3382
|
+
`dsn ${safe} has a ':' in its key \u2014 a DSN carries one credential and no password field`
|
|
3383
|
+
);
|
|
3044
3384
|
}
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
this.timer = null;
|
|
3048
|
-
this.reading?.abort();
|
|
3049
|
-
this.reading = null;
|
|
3385
|
+
if (!authority) {
|
|
3386
|
+
fail(`dsn ${safe} has no host`);
|
|
3050
3387
|
}
|
|
3051
|
-
|
|
3052
|
-
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
this.reading = reading;
|
|
3056
|
-
const timeout = setTimeout(() => reading.abort(), REQUEST_TIMEOUT_MS);
|
|
3057
|
-
timeout.unref?.();
|
|
3058
|
-
try {
|
|
3059
|
-
await this.read(reading.signal);
|
|
3060
|
-
} catch {
|
|
3061
|
-
} finally {
|
|
3062
|
-
clearTimeout(timeout);
|
|
3063
|
-
if (this.reading === reading) this.reading = null;
|
|
3064
|
-
}
|
|
3388
|
+
if (containsKey(authority)) {
|
|
3389
|
+
fail(
|
|
3390
|
+
`dsn ${safe} has the KEY where the host belongs. The order is key, @, host \u2014 check whether the two are the wrong way round: https://baton_pk_...@host/ten_.../<server>`
|
|
3391
|
+
);
|
|
3065
3392
|
}
|
|
3066
|
-
|
|
3067
|
-
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
void response.body?.cancel().catch(() => void 0);
|
|
3071
|
-
}
|
|
3072
|
-
if (signal.aborted) return;
|
|
3073
|
-
if (response.status === 204) {
|
|
3074
|
-
this.held = null;
|
|
3075
|
-
this.etag = null;
|
|
3076
|
-
} else if (response.status === 200) {
|
|
3077
|
-
const document = parseDocument(await response.text());
|
|
3078
|
-
if (signal.aborted) return;
|
|
3079
|
-
if (document === null) {
|
|
3080
|
-
if (!this.warned) {
|
|
3081
|
-
this.warned = true;
|
|
3082
|
-
warn("baton: the collector sent capture settings this SDK cannot read");
|
|
3083
|
-
}
|
|
3084
|
-
return;
|
|
3085
|
-
}
|
|
3086
|
-
this.held = document;
|
|
3087
|
-
this.etag = response.headers.get("etag");
|
|
3088
|
-
}
|
|
3393
|
+
if (NOT_IN_A_HOST.test(authority)) {
|
|
3394
|
+
fail(
|
|
3395
|
+
`dsn ${safe} has whitespace, a control character or a backslash inside its host. Those are silently REMOVED or reinterpreted when a URL is parsed, so the address dialled would not be the one you wrote \u2014 check for a line wrap or a stray space where the value was copied.`
|
|
3396
|
+
);
|
|
3089
3397
|
}
|
|
3090
|
-
|
|
3091
|
-
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
|
|
3398
|
+
let hostReason = null;
|
|
3399
|
+
let parsedAuthority = null;
|
|
3400
|
+
try {
|
|
3401
|
+
parsedAuthority = new URL(`${parts.scheme}://${authority}`);
|
|
3402
|
+
} catch (error) {
|
|
3403
|
+
hostReason = error instanceof Error ? error.constructor.name : "Error";
|
|
3095
3404
|
}
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
start() {
|
|
3099
|
-
this.source.start();
|
|
3405
|
+
if (parsedAuthority === null) {
|
|
3406
|
+
fail(`dsn ${safe} is not a parseable URL (${hostReason ?? "Error"})`);
|
|
3100
3407
|
}
|
|
3101
|
-
|
|
3102
|
-
|
|
3408
|
+
const segments = parts.path.split("/").filter((segment) => segment !== "");
|
|
3409
|
+
const [workspace, server, ...extra] = segments;
|
|
3410
|
+
if (workspace === void 0 || server === void 0 || extra.length > 0) {
|
|
3411
|
+
fail(
|
|
3412
|
+
`dsn ${safe} must carry exactly two path segments \u2014 the workspace and the server, as in /ten_.../<server>. A missing server is never defaulted: it is what the key is bound to.`
|
|
3413
|
+
);
|
|
3103
3414
|
}
|
|
3104
|
-
|
|
3105
|
-
|
|
3415
|
+
for (const [slot, segment] of [
|
|
3416
|
+
["workspace", workspace],
|
|
3417
|
+
["server", server]
|
|
3418
|
+
]) {
|
|
3419
|
+
if (containsKey(segment)) {
|
|
3420
|
+
fail(
|
|
3421
|
+
`dsn ${safe} has a KEY in the ${slot} slot. The key goes before the @, and the path carries the workspace and the server: https://baton_pk_...@host/ten_.../<server>`
|
|
3422
|
+
);
|
|
3423
|
+
}
|
|
3106
3424
|
}
|
|
3107
|
-
|
|
3108
|
-
|
|
3109
|
-
|
|
3425
|
+
if (!WORKSPACE_PATTERN.test(workspace)) {
|
|
3426
|
+
fail(
|
|
3427
|
+
`dsn ${safe} has ${JSON.stringify(workspace)} where the workspace belongs \u2014 expected ten_ followed by 8 or 32 hex characters. If the two path segments are the right way round, this is not a Baton DSN.`
|
|
3428
|
+
);
|
|
3110
3429
|
}
|
|
3111
|
-
|
|
3430
|
+
if (!VENDOR_ID_PATTERN.test(server)) {
|
|
3431
|
+
fail(
|
|
3432
|
+
`dsn ${safe} has ${JSON.stringify(server)} where the server belongs \u2014 it must match ${VENDOR_ID_PATTERN.source}, because this value becomes the annotation tool name prefix as well as the envelope's vendor_id.`
|
|
3433
|
+
);
|
|
3434
|
+
}
|
|
3435
|
+
if (key.startsWith(SECRET_PREFIX)) {
|
|
3436
|
+
warn(
|
|
3437
|
+
`baton: this DSN carries a ${SECRET_PREFIX} key (a workspace SECRET) where a ${PUBLISHABLE_PREFIX} key belongs. It will work. But if this server ships to anyone else, that key reads and writes everything the workspace holds \u2014 mint a publishable key at /account instead.`
|
|
3438
|
+
);
|
|
3439
|
+
}
|
|
3440
|
+
return sealKey({
|
|
3441
|
+
origin: `${parts.scheme}://${authority}`,
|
|
3442
|
+
tenantId: workspace,
|
|
3443
|
+
vendorId: server,
|
|
3444
|
+
key
|
|
3445
|
+
});
|
|
3446
|
+
}
|
|
3447
|
+
function sealKey(dsn) {
|
|
3448
|
+
const shown = {
|
|
3449
|
+
origin: dsn.origin,
|
|
3450
|
+
tenantId: dsn.tenantId,
|
|
3451
|
+
vendorId: dsn.vendorId,
|
|
3452
|
+
key: "<key>"
|
|
3453
|
+
};
|
|
3454
|
+
Object.defineProperty(dsn, "toJSON", {
|
|
3455
|
+
value: () => shown,
|
|
3456
|
+
enumerable: false
|
|
3457
|
+
});
|
|
3458
|
+
Object.defineProperty(dsn, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
|
|
3459
|
+
value: () => shown,
|
|
3460
|
+
enumerable: false
|
|
3461
|
+
});
|
|
3462
|
+
return dsn;
|
|
3463
|
+
}
|
|
3112
3464
|
|
|
3113
3465
|
// src/integrations/mcp/config.ts
|
|
3114
3466
|
function resolveTenantId(explicit, vendorId2) {
|
|
@@ -3204,7 +3556,8 @@ function resolveBatonConfig(supplied) {
|
|
|
3204
3556
|
tenantId: dsn.tenantId,
|
|
3205
3557
|
vendorId: dsn.vendorId,
|
|
3206
3558
|
refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
|
|
3207
|
-
})
|
|
3559
|
+
}),
|
|
3560
|
+
envCandidate()
|
|
3208
3561
|
)
|
|
3209
3562
|
} : {}
|
|
3210
3563
|
};
|
|
@@ -3377,53 +3730,148 @@ var BatonHandle = class {
|
|
|
3377
3730
|
};
|
|
3378
3731
|
|
|
3379
3732
|
// src/integrations/mcp/perCaller.ts
|
|
3733
|
+
var UNREAD = /* @__PURE__ */ Symbol("unread");
|
|
3380
3734
|
var PerCallerSurface = class {
|
|
3381
3735
|
constructor(options) {
|
|
3382
3736
|
this.options = options;
|
|
3383
3737
|
}
|
|
3384
3738
|
options;
|
|
3385
|
-
|
|
3739
|
+
document = UNREAD;
|
|
3740
|
+
served = null;
|
|
3741
|
+
serverOverlay;
|
|
3386
3742
|
/** Called at install and on every request; writes only when the report
|
|
3387
|
-
* pointer should change. */
|
|
3743
|
+
* pointer or the server overlay should change. */
|
|
3388
3744
|
followSettings() {
|
|
3389
|
-
if (this.options.annotationToolName === "") return;
|
|
3390
3745
|
try {
|
|
3391
3746
|
const document = this.options.settings.document;
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
|
|
3747
|
+
if (document === this.document) return;
|
|
3748
|
+
const overlay = document?.serverOverlay;
|
|
3749
|
+
const pointer = this.options.pointer();
|
|
3750
|
+
const pointerOn = pointer !== void 0 && (document === null || document.reportsOnForAnyone);
|
|
3751
|
+
const served = JSON.stringify([pointerOn, overlay?.id ?? null]);
|
|
3752
|
+
if (served !== this.served) {
|
|
3753
|
+
const { ours, subagent } = batonParagraphs(pointerOn ? pointer : void 0, overlay, this.options.subagentLine());
|
|
3754
|
+
this.options.writeInstructions(ours, subagent);
|
|
3755
|
+
this.served = served;
|
|
3756
|
+
this.serverOverlay = overlay;
|
|
3757
|
+
}
|
|
3758
|
+
this.document = document;
|
|
3396
3759
|
} catch (err) {
|
|
3397
|
-
|
|
3398
|
-
`);
|
|
3760
|
+
stderrLine(`baton: could not update the server instructions for new settings: ${printable(err)}`);
|
|
3399
3761
|
}
|
|
3400
3762
|
}
|
|
3401
|
-
/** `
|
|
3763
|
+
/** `followSettings` after the report pointer changed outside the settings. */
|
|
3764
|
+
refresh() {
|
|
3765
|
+
this.document = UNREAD;
|
|
3766
|
+
this.served = null;
|
|
3767
|
+
this.followSettings();
|
|
3768
|
+
}
|
|
3769
|
+
/** `result` with the caller's goal, reports and overlay; as served on any failure. */
|
|
3402
3770
|
toolsFor(result, caller) {
|
|
3403
3771
|
const settings = caller.settings;
|
|
3404
3772
|
if (settings === void 0) return result;
|
|
3405
3773
|
const { intentParamMode, annotationToolName, injectsGoal } = this.options;
|
|
3406
3774
|
const goal = settings.intentParamMode ?? intentParamMode;
|
|
3407
3775
|
const hideReports = annotationToolName !== "" && settings.reportMode === "off";
|
|
3408
|
-
|
|
3776
|
+
const overlay = settings.overlay;
|
|
3777
|
+
if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
|
|
3409
3778
|
try {
|
|
3410
3779
|
const tools = result?.tools;
|
|
3411
3780
|
if (!Array.isArray(tools)) return result;
|
|
3412
3781
|
const served = [];
|
|
3782
|
+
const injected = [];
|
|
3413
3783
|
for (const tool of tools) {
|
|
3414
3784
|
const name = tool?.name;
|
|
3415
3785
|
if (hideReports && name === annotationToolName) continue;
|
|
3416
|
-
const
|
|
3417
|
-
served.push(
|
|
3786
|
+
const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
|
|
3787
|
+
served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
|
|
3788
|
+
injected.push(ours);
|
|
3418
3789
|
}
|
|
3419
|
-
|
|
3790
|
+
const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
|
|
3791
|
+
return { ...result, tools: rewritten };
|
|
3420
3792
|
} catch (err) {
|
|
3421
|
-
|
|
3422
|
-
`);
|
|
3793
|
+
stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
|
|
3423
3794
|
return result;
|
|
3424
3795
|
}
|
|
3425
3796
|
}
|
|
3426
3797
|
};
|
|
3798
|
+
function batonParagraphs(pointer, overlay, subagentLine) {
|
|
3799
|
+
const parts = overlay?.instructionAppends() ?? [];
|
|
3800
|
+
if (pointer !== void 0) parts.push(overlaid(pointer, overlay, "instructions.report_pointer"));
|
|
3801
|
+
if (subagentLine) parts.push(overlaid(INTENT_INSTRUCTIONS, overlay, "instructions.subagent"));
|
|
3802
|
+
const kept = parts.map(stripWhiteSpaceEnd);
|
|
3803
|
+
return { ours: kept.filter((part) => part).join("\n\n"), subagent: subagentLine && kept.at(-1) || null };
|
|
3804
|
+
}
|
|
3805
|
+
function withOverlay(tools, injected, overlay, reportTool2) {
|
|
3806
|
+
const position = /* @__PURE__ */ new Map();
|
|
3807
|
+
tools.forEach((tool, i) => position.set(tool?.name, i));
|
|
3808
|
+
const hidden = /* @__PURE__ */ new Set();
|
|
3809
|
+
for (const action of overlay.actions) {
|
|
3810
|
+
if (action.tool === void 0) continue;
|
|
3811
|
+
const i = position.get(action.tool);
|
|
3812
|
+
if (i === void 0) {
|
|
3813
|
+
warnSkipped(overlay.id, action.index, `no tool is named ${JSON.stringify(action.tool)}`);
|
|
3814
|
+
} else if (action.tool === reportTool2) {
|
|
3815
|
+
warnSkipped(overlay.id, action.index, "the report tool takes agent_text targets only");
|
|
3816
|
+
} else if (action.param === void 0 && action.change === "remove") {
|
|
3817
|
+
hidden.add(i);
|
|
3818
|
+
} else if (action.param === void 0) {
|
|
3819
|
+
tools[i] = withDescription(tools[i], [action]);
|
|
3820
|
+
} else {
|
|
3821
|
+
const reason = paramChange(tools, i, action, injected[i]);
|
|
3822
|
+
if (reason !== void 0) warnSkipped(overlay.id, action.index, reason);
|
|
3823
|
+
}
|
|
3824
|
+
}
|
|
3825
|
+
const goalActions = overlay.pieceActions("goal_param.description");
|
|
3826
|
+
if (goalActions.length > 0) {
|
|
3827
|
+
injected.forEach((ours, i) => {
|
|
3828
|
+
if (ours) describeParam(tools, i, USER_GOAL_PARAM_NAME, goalActions);
|
|
3829
|
+
});
|
|
3830
|
+
}
|
|
3831
|
+
const reportActions = overlay.pieceActions("report_tool.description");
|
|
3832
|
+
const reportAt = reportTool2 === void 0 ? void 0 : position.get(reportTool2);
|
|
3833
|
+
if (reportActions.length > 0 && reportAt !== void 0) {
|
|
3834
|
+
tools[reportAt] = withDescription(tools[reportAt], reportActions);
|
|
3835
|
+
}
|
|
3836
|
+
return tools.filter((_, i) => !hidden.has(i));
|
|
3837
|
+
}
|
|
3838
|
+
function withDescription(tool, actions) {
|
|
3839
|
+
const description = typeof tool.description === "string" ? tool.description : void 0;
|
|
3840
|
+
return { ...tool, description: changedText(description, actions).text };
|
|
3841
|
+
}
|
|
3842
|
+
function paramChange(tools, i, action, injected) {
|
|
3843
|
+
const param = action.param;
|
|
3844
|
+
const tool = tools[i];
|
|
3845
|
+
const schema = tool.inputSchema;
|
|
3846
|
+
const properties = isRecord(schema) && isRecord(schema.properties) ? schema.properties : void 0;
|
|
3847
|
+
if (properties === void 0 || !Object.hasOwn(properties, param)) {
|
|
3848
|
+
return `${JSON.stringify(action.tool)} has no param ${JSON.stringify(param)}`;
|
|
3849
|
+
}
|
|
3850
|
+
if (injected && param === USER_GOAL_PARAM_NAME) return "Baton's user_goal takes the goal_param.description target";
|
|
3851
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
3852
|
+
if (action.change === "remove") {
|
|
3853
|
+
if (required.includes(param)) return `${JSON.stringify(action.tool)} requires ${JSON.stringify(param)}`;
|
|
3854
|
+
const kept = Object.fromEntries(Object.entries(properties).filter(([name]) => name !== param));
|
|
3855
|
+
tools[i] = { ...tool, inputSchema: { ...schema, properties: kept } };
|
|
3856
|
+
} else if (action.change === "required") {
|
|
3857
|
+
if (!required.includes(param)) tools[i] = { ...tool, inputSchema: { ...schema, required: [...required, param] } };
|
|
3858
|
+
} else {
|
|
3859
|
+
describeParam(tools, i, param, [action]);
|
|
3860
|
+
}
|
|
3861
|
+
return void 0;
|
|
3862
|
+
}
|
|
3863
|
+
function describeParam(tools, i, param, actions) {
|
|
3864
|
+
const tool = tools[i];
|
|
3865
|
+
const schema = tool.inputSchema;
|
|
3866
|
+
const properties = schema.properties;
|
|
3867
|
+
const described = isRecord(properties[param]) ? properties[param] : {};
|
|
3868
|
+
const current2 = typeof described.description === "string" ? described.description : void 0;
|
|
3869
|
+
const description = changedText(current2, actions).text;
|
|
3870
|
+
tools[i] = {
|
|
3871
|
+
...tool,
|
|
3872
|
+
inputSchema: { ...schema, properties: { ...properties, [param]: { ...described, description } } }
|
|
3873
|
+
};
|
|
3874
|
+
}
|
|
3427
3875
|
function withGoalMode(tool, goal) {
|
|
3428
3876
|
const entry = tool;
|
|
3429
3877
|
const schema = entry.inputSchema;
|
|
@@ -3478,10 +3926,10 @@ var ServerCounter = class extends SessionCounter {
|
|
|
3478
3926
|
};
|
|
3479
3927
|
|
|
3480
3928
|
// src/integrations/mcp/surface.ts
|
|
3481
|
-
var
|
|
3929
|
+
var crypto3 = __toESM(require("crypto"), 1);
|
|
3482
3930
|
function surfaceHash(surface) {
|
|
3483
3931
|
const canonical = canonicalJson(surface);
|
|
3484
|
-
const digest =
|
|
3932
|
+
const digest = crypto3.createHash("sha256").update(canonical, "utf-8").digest("hex");
|
|
3485
3933
|
return `sha256:${digest}`;
|
|
3486
3934
|
}
|
|
3487
3935
|
function canonicalJson(value) {
|
|
@@ -3513,13 +3961,20 @@ function assembleSurface(serverMeta, tools) {
|
|
|
3513
3961
|
var SENT_SURFACES_CAP = 256;
|
|
3514
3962
|
var SentSurfaces = class {
|
|
3515
3963
|
hashes = /* @__PURE__ */ new Set();
|
|
3516
|
-
|
|
3517
|
-
|
|
3964
|
+
serverOverlay = null;
|
|
3965
|
+
/** `serverOverlay` is not in `surface_hash`, and a snapshot is sent again
|
|
3966
|
+
* whenever it changes (SPEC §11.4.2). */
|
|
3967
|
+
wasSent(digest, serverOverlay = null) {
|
|
3968
|
+
if (serverOverlay !== this.serverOverlay || !this.hashes.has(digest)) return false;
|
|
3518
3969
|
this.hashes.delete(digest);
|
|
3519
3970
|
this.hashes.add(digest);
|
|
3520
3971
|
return true;
|
|
3521
3972
|
}
|
|
3522
|
-
mark(digest) {
|
|
3973
|
+
mark(digest, serverOverlay = null) {
|
|
3974
|
+
if (serverOverlay !== this.serverOverlay) {
|
|
3975
|
+
this.hashes.clear();
|
|
3976
|
+
this.serverOverlay = serverOverlay;
|
|
3977
|
+
}
|
|
3523
3978
|
this.hashes.add(digest);
|
|
3524
3979
|
if (this.hashes.size > SENT_SURFACES_CAP) {
|
|
3525
3980
|
this.hashes.delete(this.hashes.values().next().value);
|
|
@@ -3543,7 +3998,7 @@ var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
|
|
|
3543
3998
|
var wired = /* @__PURE__ */ new WeakSet();
|
|
3544
3999
|
var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
|
|
3545
4000
|
var INTENT_PARAM_NAMES = [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES];
|
|
3546
|
-
var callSlots = new
|
|
4001
|
+
var callSlots = new asyncHooks.AsyncLocalStorage();
|
|
3547
4002
|
var SurfaceState = class {
|
|
3548
4003
|
constructor(serverMeta, sentSurfaces) {
|
|
3549
4004
|
this.serverMeta = serverMeta;
|
|
@@ -3557,6 +4012,7 @@ var SurfaceState = class {
|
|
|
3557
4012
|
* injected schema as if it were vendor-true. */
|
|
3558
4013
|
rawTools = /* @__PURE__ */ new Map();
|
|
3559
4014
|
dirty = false;
|
|
4015
|
+
servedOverlayId = null;
|
|
3560
4016
|
/** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
|
|
3561
4017
|
* which picks the spelling THIS SDK major puts on the wire. */
|
|
3562
4018
|
noteTool(name, inputSchemaJson, description) {
|
|
@@ -3608,7 +4064,7 @@ async function resolveEnvelopeParts(ctx, extra) {
|
|
|
3608
4064
|
const session = await resolveSessionId(ctx.fallbackSessionId, extra);
|
|
3609
4065
|
return { ...session, scrubbedMeta };
|
|
3610
4066
|
}
|
|
3611
|
-
async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn") {
|
|
4067
|
+
async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn", resolved) {
|
|
3612
4068
|
await maybeEmitSurfaceSnapshot(ctx);
|
|
3613
4069
|
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
3614
4070
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
@@ -3618,12 +4074,7 @@ async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn
|
|
|
3618
4074
|
(name) => dispositions === void 0 || dispositions[name] === "native" || unlisted === "leave" || unlisted === "goalOnly" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
|
|
3619
4075
|
);
|
|
3620
4076
|
const client = observeClient(extra, ctx);
|
|
3621
|
-
const caller = await resolveCaller(
|
|
3622
|
-
ctx.resolvePrincipal,
|
|
3623
|
-
{ extra, toolName, arguments: params },
|
|
3624
|
-
ctx.captureSettings,
|
|
3625
|
-
client
|
|
3626
|
-
);
|
|
4077
|
+
const caller = resolved ?? await resolveCaller(ctx.resolvePrincipal, { extra, toolName, arguments: params }, ctx.captureSettings, client);
|
|
3627
4078
|
const resultCaptureMode = caller.settings?.resultCaptureMode ?? ctx.configResultCaptureMode;
|
|
3628
4079
|
const common = {
|
|
3629
4080
|
tenant_id: ctx.tenantId,
|
|
@@ -3661,16 +4112,24 @@ async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn
|
|
|
3661
4112
|
);
|
|
3662
4113
|
return { common, session, resultCaptureMode };
|
|
3663
4114
|
}
|
|
3664
|
-
function batonWrap(nameRef, original, ctx, unlisted = "warn") {
|
|
4115
|
+
function batonWrap(nameRef, original, ctx, unlisted = "warn", resolved) {
|
|
3665
4116
|
return async (...callArgs) => {
|
|
3666
4117
|
const toolName = nameRef.current;
|
|
3667
4118
|
const slot = callSlots.getStore();
|
|
3668
4119
|
if (slot) slot.innerFired = true;
|
|
3669
4120
|
const extra = callArgs[callArgs.length - 1];
|
|
3670
4121
|
const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
|
|
3671
|
-
const
|
|
4122
|
+
const ours = slot?.strippedFor === toolName ? slot : void 0;
|
|
3672
4123
|
if (slot) slot.strippedFor = null;
|
|
3673
|
-
const { common, session, resultCaptureMode } = await openCall(
|
|
4124
|
+
const { common, session, resultCaptureMode } = await openCall(
|
|
4125
|
+
ctx,
|
|
4126
|
+
toolName,
|
|
4127
|
+
extra,
|
|
4128
|
+
params,
|
|
4129
|
+
ours?.stripped ?? {},
|
|
4130
|
+
unlisted,
|
|
4131
|
+
ours?.caller ?? resolved
|
|
4132
|
+
);
|
|
3674
4133
|
const terminate = async (build, replacement) => {
|
|
3675
4134
|
if (!slot) {
|
|
3676
4135
|
if (build !== null) await emit(ctx.sink, build);
|
|
@@ -3834,9 +4293,8 @@ function extractGoalParam(args, paramName, toolName, dispositions, unlisted) {
|
|
|
3834
4293
|
if (disposition === "native") return null;
|
|
3835
4294
|
if (disposition === void 0 && unlisted === "leave") return null;
|
|
3836
4295
|
if (disposition === void 0 && unlisted === "warn") {
|
|
3837
|
-
|
|
3838
|
-
`baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
|
|
3839
|
-
`
|
|
4296
|
+
stderrLine(
|
|
4297
|
+
`baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)`
|
|
3840
4298
|
);
|
|
3841
4299
|
}
|
|
3842
4300
|
return popText(args, paramName);
|
|
@@ -3862,6 +4320,11 @@ function stripIntentParams(params, ctx) {
|
|
|
3862
4320
|
return stripped;
|
|
3863
4321
|
}
|
|
3864
4322
|
async function maybeEmitSurfaceSnapshot(ctx) {
|
|
4323
|
+
const overlayId = ctx.perCaller?.serverOverlay?.id ?? null;
|
|
4324
|
+
if (overlayId !== ctx.surfaceState.servedOverlayId) {
|
|
4325
|
+
ctx.surfaceState.servedOverlayId = overlayId;
|
|
4326
|
+
ctx.surfaceState.dirty = true;
|
|
4327
|
+
}
|
|
3865
4328
|
if (!ctx.surfaceState.dirty) return;
|
|
3866
4329
|
ctx.surfaceState.dirty = false;
|
|
3867
4330
|
let snapshot;
|
|
@@ -3870,13 +4333,12 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
3870
4333
|
snapshot = ctx.surfaceState.buildSnapshot();
|
|
3871
4334
|
digest = surfaceHash(snapshot);
|
|
3872
4335
|
} catch (err) {
|
|
3873
|
-
|
|
3874
|
-
`);
|
|
4336
|
+
stderrLine(`baton: surface snapshot capture failed: ${String(err)}`);
|
|
3875
4337
|
return;
|
|
3876
4338
|
}
|
|
3877
4339
|
const sent = ctx.surfaceState.sentSurfaces;
|
|
3878
|
-
if (sent.wasSent(digest)) return;
|
|
3879
|
-
sent.mark(digest);
|
|
4340
|
+
if (sent.wasSent(digest, overlayId)) return;
|
|
4341
|
+
sent.mark(digest, overlayId);
|
|
3880
4342
|
const seam = buildSeamAugmentations({
|
|
3881
4343
|
injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
|
|
3882
4344
|
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
@@ -3884,6 +4346,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
3884
4346
|
requiredParamNames: requiredParamNames(ctx.intentParamMode),
|
|
3885
4347
|
instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions())
|
|
3886
4348
|
});
|
|
4349
|
+
if (ctx.captureSettings !== void 0) seam.server_overlay = overlayId;
|
|
3887
4350
|
await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
|
|
3888
4351
|
}
|
|
3889
4352
|
function declaredIntentParams(vendorSchema) {
|
|
@@ -3939,16 +4402,16 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
|
|
|
3939
4402
|
return registered;
|
|
3940
4403
|
};
|
|
3941
4404
|
}
|
|
3942
|
-
function installToolsListSeam(lowLevel, ctx) {
|
|
4405
|
+
function installToolsListSeam(lowLevel, ctx, listsOwnReportTool) {
|
|
3943
4406
|
const names = [...requiredParamNames(ctx.intentParamMode), TOOL_NAME_PARAM_NAME];
|
|
3944
4407
|
const isInjected = (toolName, paramName) => toolName === ctx.annotationToolName ? paramName === TOOL_NAME_PARAM_NAME : ctx.paramRegistry.get(toolName)?.[paramName] === "injected";
|
|
3945
4408
|
const advertise = (result) => {
|
|
3946
4409
|
try {
|
|
3947
|
-
|
|
4410
|
+
const served = listsOwnReportTool || ctx.annotationToolName === "" ? result : withToolInputSchema(result, ctx.annotationToolName, annotationInputJsonSchema(lowLevelMajor(lowLevel)));
|
|
4411
|
+
return advertiseIntentParamsRequired(served, names, isInjected);
|
|
3948
4412
|
} catch (err) {
|
|
3949
|
-
|
|
3950
|
-
`baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}
|
|
3951
|
-
`
|
|
4413
|
+
stderrLine(
|
|
4414
|
+
`baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}`
|
|
3952
4415
|
);
|
|
3953
4416
|
return result;
|
|
3954
4417
|
}
|
|
@@ -3961,6 +4424,7 @@ function installToolsListSeam(lowLevel, ctx) {
|
|
|
3961
4424
|
var LOW_LEVEL_LIST_SEAM = /* @__PURE__ */ Symbol("batonLowLevelListSeam");
|
|
3962
4425
|
var LOW_LEVEL_CALL_SEAM = /* @__PURE__ */ Symbol("batonLowLevelCallSeam");
|
|
3963
4426
|
var LOW_LEVEL_HANDSHAKE_SEAM = /* @__PURE__ */ Symbol("batonLowLevelHandshakeSeam");
|
|
4427
|
+
var SETTINGS_SEAM = /* @__PURE__ */ Symbol("batonSettingsSeam");
|
|
3964
4428
|
function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce2, reportToolTaken) {
|
|
3965
4429
|
let reportTool2 = annotationTool;
|
|
3966
4430
|
const listedReportTool = reportTool2 && {
|
|
@@ -3972,14 +4436,12 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
|
|
|
3972
4436
|
known.unread.add(name);
|
|
3973
4437
|
warnOnce2(
|
|
3974
4438
|
`tool-unread:${name}`,
|
|
3975
|
-
`baton: could not read tool ${JSON.stringify(name)}; its calls keep user_goal until Baton can read it: ${printable(err)}
|
|
3976
|
-
`
|
|
4439
|
+
`baton: could not read tool ${JSON.stringify(name)}; its calls keep user_goal until Baton can read it: ${printable(err)}`
|
|
3977
4440
|
);
|
|
3978
4441
|
};
|
|
3979
4442
|
const skipNote = (name, err) => {
|
|
3980
4443
|
if (known.unread.has(name)) return;
|
|
3981
|
-
warnOnce2(`tool-unnoted:${name}`, `baton: could not note tool ${JSON.stringify(name)}; Baton adds no user_goal to it: ${printable(err)}
|
|
3982
|
-
`);
|
|
4444
|
+
warnOnce2(`tool-unnoted:${name}`, `baton: could not note tool ${JSON.stringify(name)}; Baton adds no user_goal to it: ${printable(err)}`);
|
|
3983
4445
|
};
|
|
3984
4446
|
const keepGoalIfDeclared = (tools) => {
|
|
3985
4447
|
for (const { name, inputSchema: inputSchema2 } of tools) {
|
|
@@ -3999,8 +4461,7 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
|
|
|
3999
4461
|
if (surface && reportTool2 !== void 0 && tools.some((tool) => tool.name === reportTool2?.name)) {
|
|
4000
4462
|
warnOnce2(
|
|
4001
4463
|
"report-tool-name-taken",
|
|
4002
|
-
`baton: the server lists its own tool ${JSON.stringify(reportTool2.name)}, so Baton's report tool is not added; set annotationToolName to another name
|
|
4003
|
-
`
|
|
4464
|
+
`baton: the server lists its own tool ${JSON.stringify(reportTool2.name)}, so Baton's report tool is not added; set annotationToolName to another name`
|
|
4004
4465
|
);
|
|
4005
4466
|
reportTool2 = void 0;
|
|
4006
4467
|
ctx.annotationToolName = "";
|
|
@@ -4031,8 +4492,7 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
|
|
|
4031
4492
|
} catch (err) {
|
|
4032
4493
|
warnOnce2(
|
|
4033
4494
|
"tools-unread",
|
|
4034
|
-
`baton: could not read the tools option; Baton learns the tools from tools/list: ${printable(err)}
|
|
4035
|
-
`
|
|
4495
|
+
`baton: could not read the tools option; Baton learns the tools from tools/list: ${printable(err)}`
|
|
4036
4496
|
);
|
|
4037
4497
|
}
|
|
4038
4498
|
}
|
|
@@ -4051,8 +4511,7 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
|
|
|
4051
4511
|
const firstPage = args[0]?.params?.cursor === void 0;
|
|
4052
4512
|
return servedToolList(result, listed, ctx, firstPage && reportTool2 ? listedReportTool : void 0);
|
|
4053
4513
|
} catch (err) {
|
|
4054
|
-
|
|
4055
|
-
`);
|
|
4514
|
+
stderrLine(`baton: tools/list capture failed; serving the vendor's own result: ${printable(err)}`);
|
|
4056
4515
|
return result;
|
|
4057
4516
|
}
|
|
4058
4517
|
});
|
|
@@ -4064,28 +4523,36 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
|
|
|
4064
4523
|
installRequestSeam(lowLevel, "server/discover", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);
|
|
4065
4524
|
installRequestSeam(lowLevel, TOOLS_CALL_METHOD, LOW_LEVEL_CALL_SEAM, (handler) => async (...args) => {
|
|
4066
4525
|
catchUp();
|
|
4067
|
-
ctx.perCaller?.followSettings();
|
|
4068
4526
|
const request = args[0];
|
|
4069
4527
|
const name = request?.params?.name;
|
|
4070
4528
|
if (typeof name !== "string") return handler(...args);
|
|
4071
4529
|
if (name === reportTool2?.name) return callAnnotationTool(reportTool2, request?.params?.arguments, args[1]);
|
|
4072
4530
|
const injected = ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected";
|
|
4073
4531
|
const unlisted = injected ? "warn" : known.keepsGoal.has(name) || known.unread.has(name) ? "leave" : "goalOnly";
|
|
4532
|
+
const strip = (args2) => injected ? stripIntentParams({ name, arguments: args2 }, ctx) : { [USER_GOAL_PARAM_NAME]: extractGoalParam(args2, USER_GOAL_PARAM_NAME, name, ctx.paramRegistry.get(name), unlisted) };
|
|
4533
|
+
let slot;
|
|
4534
|
+
if (mayHide(ctx.captureSettings, name)) {
|
|
4535
|
+
const hookArgs = isRecord(request?.params?.arguments) ? { ...request.params.arguments } : {};
|
|
4536
|
+
const checked = { innerFired: false, flushTerminal: null, stripped: strip(hookArgs), strippedFor: name, validation: "unseen", unlisted };
|
|
4537
|
+
if (await hiddenFrom(checked, name, hookArgs, args[1], ctx)) {
|
|
4538
|
+
if (request?.params !== void 0 && isRecord(request.params.arguments)) request.params.arguments = hookArgs;
|
|
4539
|
+
return answerHidden(lowLevel, name, (outcome) => settleCall(checked, outcome, args, () => void 0, ctx, "tool_hidden"));
|
|
4540
|
+
}
|
|
4541
|
+
slot = checked;
|
|
4542
|
+
}
|
|
4074
4543
|
const params = request?.params?.arguments;
|
|
4075
4544
|
const toolArgs = isRecord(params) ? params : {};
|
|
4076
4545
|
if (unlisted === "goalOnly" && USER_GOAL_PARAM_NAME in toolArgs && !known.served.has(name) && !known.givenTools.some((tool) => tool.name === name)) {
|
|
4077
4546
|
warnOnce2(
|
|
4078
4547
|
"user-goal-unlisted",
|
|
4079
|
-
`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
|
|
4080
|
-
`
|
|
4548
|
+
`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`
|
|
4081
4549
|
);
|
|
4082
4550
|
}
|
|
4083
4551
|
if (request?.params?.task !== void 0) {
|
|
4084
|
-
|
|
4085
|
-
else extractGoalParam(toolArgs, USER_GOAL_PARAM_NAME, name, ctx.paramRegistry.get(name), unlisted);
|
|
4552
|
+
strip(toolArgs);
|
|
4086
4553
|
return handler(...args);
|
|
4087
4554
|
}
|
|
4088
|
-
return batonWrap({ current: name }, () => handler(...args), ctx, unlisted)(toolArgs, args[1]);
|
|
4555
|
+
return batonWrap({ current: name }, () => handler(...args), ctx, unlisted, slot?.caller)(toolArgs, args[1]);
|
|
4089
4556
|
});
|
|
4090
4557
|
}
|
|
4091
4558
|
function lowLevelMajor(lowLevel) {
|
|
@@ -4213,8 +4680,7 @@ async function openLifecycleCall(ctx, spec, requestParams, extra) {
|
|
|
4213
4680
|
}
|
|
4214
4681
|
};
|
|
4215
4682
|
} catch (err) {
|
|
4216
|
-
|
|
4217
|
-
`);
|
|
4683
|
+
stderrLine(`baton: ${spec.method} capture failed: ${String(err)}`);
|
|
4218
4684
|
return null;
|
|
4219
4685
|
}
|
|
4220
4686
|
}
|
|
@@ -4334,7 +4800,6 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
4334
4800
|
TOOLS_CALL_METHOD,
|
|
4335
4801
|
TOOLS_CALL_SEAM,
|
|
4336
4802
|
(handler) => async (...args) => {
|
|
4337
|
-
ctx.perCaller?.followSettings();
|
|
4338
4803
|
const request = args[0];
|
|
4339
4804
|
const name = request?.params?.name;
|
|
4340
4805
|
const slot = {
|
|
@@ -4344,6 +4809,10 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
4344
4809
|
strippedFor: typeof name === "string" ? name : null,
|
|
4345
4810
|
validation: "unseen"
|
|
4346
4811
|
};
|
|
4812
|
+
const toolArgs = request?.params?.arguments;
|
|
4813
|
+
if (typeof name === "string" && toolEntry(name) != null && await hiddenFrom(slot, name, isRecord(toolArgs) ? toolArgs : {}, args[1], ctx)) {
|
|
4814
|
+
return answerHidden(lowLevel, name, (outcome2) => settleCall(slot, outcome2, args, toolEntry, ctx, "tool_hidden"));
|
|
4815
|
+
}
|
|
4347
4816
|
let outcome = CLEAN_OUTCOME;
|
|
4348
4817
|
try {
|
|
4349
4818
|
const result = await callSlots.run(slot, () => handler(...args));
|
|
@@ -4358,6 +4827,34 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
4358
4827
|
}
|
|
4359
4828
|
);
|
|
4360
4829
|
}
|
|
4830
|
+
async function hiddenFrom(slot, name, params, extra, ctx) {
|
|
4831
|
+
try {
|
|
4832
|
+
if (name === ctx.annotationToolName || !mayHide(ctx.captureSettings, name)) return false;
|
|
4833
|
+
slot.caller = await resolveCaller(
|
|
4834
|
+
ctx.resolvePrincipal,
|
|
4835
|
+
{ extra, toolName: name, arguments: params },
|
|
4836
|
+
ctx.captureSettings,
|
|
4837
|
+
observeClient(extra, ctx)
|
|
4838
|
+
);
|
|
4839
|
+
return slot.caller.settings?.overlay?.hiddenTools.has(name) ?? false;
|
|
4840
|
+
} catch (err) {
|
|
4841
|
+
stderrLine(`baton: could not check whether the tool is hidden; it is served: ${printable(err)}`);
|
|
4842
|
+
return false;
|
|
4843
|
+
}
|
|
4844
|
+
}
|
|
4845
|
+
async function answerHidden(lowLevel, name, settle) {
|
|
4846
|
+
if (lowLevelMajor(lowLevel) === 1) {
|
|
4847
|
+
const result = { content: [{ type: "text", text: `MCP error -32602: Tool ${name} not found` }], isError: true };
|
|
4848
|
+
await settle({ failed: true, raised: false, result });
|
|
4849
|
+
return result;
|
|
4850
|
+
}
|
|
4851
|
+
const err = new ProtocolError(`Tool ${name} not found`);
|
|
4852
|
+
await settle({ failed: true, raised: true, err });
|
|
4853
|
+
throw err;
|
|
4854
|
+
}
|
|
4855
|
+
var ProtocolError = class extends Error {
|
|
4856
|
+
code = -32602;
|
|
4857
|
+
};
|
|
4361
4858
|
var VALIDATION_PROBE = /* @__PURE__ */ Symbol("baton.validationProbe");
|
|
4362
4859
|
function installValidationProbe(server) {
|
|
4363
4860
|
const target = server;
|
|
@@ -4377,7 +4874,7 @@ function installValidationProbe(server) {
|
|
|
4377
4874
|
Object.assign(probe, { [VALIDATION_PROBE]: true });
|
|
4378
4875
|
target.validateToolInput = probe;
|
|
4379
4876
|
}
|
|
4380
|
-
async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
4877
|
+
async function settleCall(slot, outcome, args, toolEntry, ctx, kind) {
|
|
4381
4878
|
try {
|
|
4382
4879
|
if (slot.flushTerminal !== null) {
|
|
4383
4880
|
const flush = slot.flushTerminal;
|
|
@@ -4387,14 +4884,13 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
|
4387
4884
|
}
|
|
4388
4885
|
if (slot.innerFired) return;
|
|
4389
4886
|
if (!outcome.failed) return;
|
|
4390
|
-
await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
|
|
4887
|
+
await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx, kind);
|
|
4391
4888
|
} catch (err) {
|
|
4392
4889
|
PROCESS_DROPS.add("encode_failed");
|
|
4393
|
-
|
|
4394
|
-
`);
|
|
4890
|
+
stderrLine(`baton: settling a tool call failed; events dropped: ${String(err)}`);
|
|
4395
4891
|
}
|
|
4396
4892
|
}
|
|
4397
|
-
async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
4893
|
+
async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx, kind) {
|
|
4398
4894
|
const request = args[0];
|
|
4399
4895
|
const toolName = request?.params?.name;
|
|
4400
4896
|
if (typeof toolName !== "string") return;
|
|
@@ -4408,9 +4904,10 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
|
4408
4904
|
args[1],
|
|
4409
4905
|
params,
|
|
4410
4906
|
slot.stripped,
|
|
4411
|
-
entry != null ? "warn" : "quiet"
|
|
4907
|
+
slot.unlisted ?? (entry != null ? "warn" : "quiet"),
|
|
4908
|
+
slot.caller
|
|
4412
4909
|
);
|
|
4413
|
-
const failureKind = requestSideFailureKind(entry, slot.validation);
|
|
4910
|
+
const failureKind = kind ?? requestSideFailureKind(entry, slot.validation);
|
|
4414
4911
|
const text = () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result);
|
|
4415
4912
|
await emit(
|
|
4416
4913
|
ctx.sink,
|
|
@@ -4604,7 +5101,7 @@ function newBatonState(config) {
|
|
|
4604
5101
|
lowLevelTools: { given: config.tools, givenTools: [], served: /* @__PURE__ */ new Map(), keepsGoal: /* @__PURE__ */ new Set(), unread: /* @__PURE__ */ new Set() }
|
|
4605
5102
|
};
|
|
4606
5103
|
}
|
|
4607
|
-
function install(server, supplied, resolved, { sentSurfaces, warned:
|
|
5104
|
+
function install(server, supplied, resolved, { sentSurfaces, warned: warned4, counter: sharedCounter, scrubber, lowLevelTools }, unconfigured) {
|
|
4608
5105
|
const shape = serverShapeOf(server);
|
|
4609
5106
|
const internals = server;
|
|
4610
5107
|
const lowLevel = shape === "mcpServer" ? internals.server : server;
|
|
@@ -4617,6 +5114,11 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4617
5114
|
const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
|
|
4618
5115
|
const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
|
|
4619
5116
|
if (unconfigured) return inertHandle(new DisabledSink(), "baton-unconfigured");
|
|
5117
|
+
if (shape === "mcpServer" && reports && internals._registeredTools?.[annotationToolName]) {
|
|
5118
|
+
throw new Error(
|
|
5119
|
+
`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.`
|
|
5120
|
+
);
|
|
5121
|
+
}
|
|
4620
5122
|
const given = config.sink ?? new StdoutSink();
|
|
4621
5123
|
const sink = offTheCall(given);
|
|
4622
5124
|
const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
|
|
@@ -4652,23 +5154,19 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4652
5154
|
if (memo && typeof memo === "object") delete memo[name];
|
|
4653
5155
|
};
|
|
4654
5156
|
const warnOnce2 = (key, message) => {
|
|
4655
|
-
if (
|
|
4656
|
-
|
|
4657
|
-
|
|
5157
|
+
if (warned4.has(key)) return;
|
|
5158
|
+
warned4.add(key);
|
|
5159
|
+
stderrLine(message);
|
|
5160
|
+
};
|
|
5161
|
+
const warnLength = (message) => warnOnce2("instructions-length", message);
|
|
5162
|
+
const setInstructions = (text) => {
|
|
5163
|
+
lowLevel._instructions = text;
|
|
4658
5164
|
};
|
|
4659
5165
|
const dropSubagentClause = (name) => {
|
|
4660
|
-
|
|
4661
|
-
if (current2 === INTENT_INSTRUCTIONS) {
|
|
4662
|
-
lowLevel._instructions = "";
|
|
4663
|
-
} else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
|
|
4664
|
-
lowLevel._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
|
|
4665
|
-
} else {
|
|
4666
|
-
return;
|
|
4667
|
-
}
|
|
5166
|
+
if (!removeSubagentClause(lowLevel, setInstructions, warnLength)) return;
|
|
4668
5167
|
warnOnce2(
|
|
4669
5168
|
"native-user-goal",
|
|
4670
|
-
`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
|
|
4671
|
-
`
|
|
5169
|
+
`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`
|
|
4672
5170
|
);
|
|
4673
5171
|
};
|
|
4674
5172
|
const isV2Server = typeof internals.toolInputSchemaJson === "function";
|
|
@@ -4712,12 +5210,8 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4712
5210
|
surfaceState,
|
|
4713
5211
|
emitSurface
|
|
4714
5212
|
};
|
|
4715
|
-
const writeInstructions = (text) => {
|
|
4716
|
-
lowLevel
|
|
4717
|
-
lowLevel,
|
|
4718
|
-
text,
|
|
4719
|
-
(message) => warnOnce2("instructions-length", message)
|
|
4720
|
-
);
|
|
5213
|
+
const writeInstructions = (text, subagent = INTENT_INSTRUCTIONS) => {
|
|
5214
|
+
writeOurs(lowLevel, text, subagent, setInstructions, warnLength);
|
|
4721
5215
|
};
|
|
4722
5216
|
writeInstructions(ours);
|
|
4723
5217
|
const rewriteInstructions = (text) => {
|
|
@@ -4733,8 +5227,9 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4733
5227
|
get annotationToolName() {
|
|
4734
5228
|
return ctx.annotationToolName;
|
|
4735
5229
|
},
|
|
4736
|
-
|
|
4737
|
-
writeInstructions
|
|
5230
|
+
pointer: () => reports && ctx.annotationToolName ? buildReportPointer({ vendorDisplayName: reports.vendorDisplayName, annotationToolName: ctx.annotationToolName }) : void 0,
|
|
5231
|
+
writeInstructions,
|
|
5232
|
+
subagentLine: () => ![...ctx.paramRegistry.values()].some((d) => d[USER_GOAL_PARAM_NAME] === "native"),
|
|
4738
5233
|
injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
|
|
4739
5234
|
});
|
|
4740
5235
|
ctx.perCaller.followSettings();
|
|
@@ -4762,10 +5257,10 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4762
5257
|
annotationOptions && buildAnnotationTool(server, annotationOptions),
|
|
4763
5258
|
lowLevelTools,
|
|
4764
5259
|
warnOnce2,
|
|
4765
|
-
() => rewriteInstructions(INTENT_INSTRUCTIONS)
|
|
5260
|
+
() => ctx.perCaller ? ctx.perCaller.refresh() : rewriteInstructions(INTENT_INSTRUCTIONS)
|
|
4766
5261
|
);
|
|
4767
5262
|
}
|
|
4768
|
-
installToolsListSeam(lowLevel, ctx);
|
|
5263
|
+
installToolsListSeam(lowLevel, ctx, shape === "lowLevel");
|
|
4769
5264
|
if (shape === "mcpServer") installToolsCallSeam(
|
|
4770
5265
|
lowLevel,
|
|
4771
5266
|
// ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
|
|
@@ -4782,6 +5277,17 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4782
5277
|
ctx
|
|
4783
5278
|
);
|
|
4784
5279
|
installLifecycleSeams(lowLevel, ctx);
|
|
5280
|
+
const settings = config.captureSettings;
|
|
5281
|
+
if (settings !== void 0) {
|
|
5282
|
+
const waitFirst = (handler) => async (...args) => {
|
|
5283
|
+
if (!settings.isReady) await settings.ready;
|
|
5284
|
+
ctx.perCaller?.followSettings();
|
|
5285
|
+
return handler(...args);
|
|
5286
|
+
};
|
|
5287
|
+
for (const method of ["initialize", "server/discover", TOOLS_LIST_METHOD, TOOLS_CALL_METHOD]) {
|
|
5288
|
+
installRequestSeam(lowLevel, method, SETTINGS_SEAM, waitFirst);
|
|
5289
|
+
}
|
|
5290
|
+
}
|
|
4785
5291
|
const handle = (name) => new BatonHandle({
|
|
4786
5292
|
sink: given,
|
|
4787
5293
|
queue: sink,
|
|
@@ -4811,11 +5317,11 @@ function reportsFor(config) {
|
|
|
4811
5317
|
}
|
|
4812
5318
|
function warnAboutSettings(config) {
|
|
4813
5319
|
if (config.reportMode !== "on" && config.annotationToolName !== void 0) {
|
|
4814
|
-
|
|
4815
|
-
`baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered
|
|
4816
|
-
`
|
|
5320
|
+
stderrLine(
|
|
5321
|
+
`baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered`
|
|
4817
5322
|
);
|
|
4818
5323
|
}
|
|
5324
|
+
candidateNeedsConsole(config.settings);
|
|
4819
5325
|
if (config.resultCaptureMode === WITHHELD) {
|
|
4820
5326
|
warn(
|
|
4821
5327
|
'baton: resultCaptureMode "off" does not withhold the message of a failed tool list, resource or prompt request. tool_list_error, resource_list_error, resource_read_error, prompt_list_error and prompt_get_error carry that message, which can include text your handler or middleware threw. Throw a message that does not quote what your code fetched.'
|
|
@@ -4855,7 +5361,7 @@ function principalFromOAuthEmail(context) {
|
|
|
4855
5361
|
}
|
|
4856
5362
|
|
|
4857
5363
|
// src/library/session.ts
|
|
4858
|
-
var
|
|
5364
|
+
var asyncHooks2 = __toESM(require("async_hooks"), 1);
|
|
4859
5365
|
var TRANSPORT_LIBRARY = "library";
|
|
4860
5366
|
var TURN_ID_META_KEY = "baton/turn_id";
|
|
4861
5367
|
function sessionEnvelope(session) {
|
|
@@ -4871,8 +5377,7 @@ function sessionEnvelope(session) {
|
|
|
4871
5377
|
};
|
|
4872
5378
|
}
|
|
4873
5379
|
function warn2(message) {
|
|
4874
|
-
|
|
4875
|
-
`);
|
|
5380
|
+
stderrLine(`baton: ${message}`);
|
|
4876
5381
|
}
|
|
4877
5382
|
function vendorId(name, value) {
|
|
4878
5383
|
const cleaned = typeof value === "string" ? stripWhiteSpace(value) : "";
|
|
@@ -4909,7 +5414,7 @@ function newSession(values, scrubber, disabled) {
|
|
|
4909
5414
|
runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
|
|
4910
5415
|
};
|
|
4911
5416
|
}
|
|
4912
|
-
var current = new
|
|
5417
|
+
var current = new asyncHooks2.AsyncLocalStorage();
|
|
4913
5418
|
function runInSession(owner, session, fn) {
|
|
4914
5419
|
return current.run({ owner, session }, fn);
|
|
4915
5420
|
}
|
|
@@ -4924,8 +5429,7 @@ function serveTools(tools, options) {
|
|
|
4924
5429
|
try {
|
|
4925
5430
|
served = tools.map(servedEntry);
|
|
4926
5431
|
} catch (err) {
|
|
4927
|
-
|
|
4928
|
-
`);
|
|
5432
|
+
stderrLine(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}`);
|
|
4929
5433
|
return { served: tools, surface: null };
|
|
4930
5434
|
}
|
|
4931
5435
|
try {
|
|
@@ -4944,8 +5448,7 @@ function serveTools(tools, options) {
|
|
|
4944
5448
|
);
|
|
4945
5449
|
return { served, surface: { surface, digest: surfaceHash(surface) } };
|
|
4946
5450
|
} catch (err) {
|
|
4947
|
-
|
|
4948
|
-
`);
|
|
5451
|
+
stderrLine(`baton: surface snapshot capture failed: ${printable(err)}`);
|
|
4949
5452
|
return { served, surface: null };
|
|
4950
5453
|
}
|
|
4951
5454
|
}
|
|
@@ -5109,8 +5612,7 @@ var Core = class {
|
|
|
5109
5612
|
});
|
|
5110
5613
|
} catch (err) {
|
|
5111
5614
|
PROCESS_DROPS.add("encode_failed");
|
|
5112
|
-
|
|
5113
|
-
`);
|
|
5615
|
+
stderrLine(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}`);
|
|
5114
5616
|
return Promise.resolve();
|
|
5115
5617
|
}
|
|
5116
5618
|
return safeWrite(this.sink, event);
|
|
@@ -5168,7 +5670,7 @@ var Trace = class _Trace {
|
|
|
5168
5670
|
observed(result, failure) {
|
|
5169
5671
|
if ((this.#result !== UNSET || this.#error !== null) && !this.#observedWarned) {
|
|
5170
5672
|
this.#observedWarned = true;
|
|
5171
|
-
|
|
5673
|
+
stderrLine("baton: Trace.observed() called more than once; the last call wins.");
|
|
5172
5674
|
}
|
|
5173
5675
|
this.#result = UNSET;
|
|
5174
5676
|
this.#error = null;
|
|
@@ -5188,8 +5690,7 @@ var Trace = class _Trace {
|
|
|
5188
5690
|
try {
|
|
5189
5691
|
this.#result = this.#core.scrubber(result);
|
|
5190
5692
|
} catch (err) {
|
|
5191
|
-
|
|
5192
|
-
`);
|
|
5693
|
+
stderrLine(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}`);
|
|
5193
5694
|
this.#result = SCRUB_FAILED;
|
|
5194
5695
|
}
|
|
5195
5696
|
}
|
|
@@ -5335,8 +5836,7 @@ var Client = class {
|
|
|
5335
5836
|
try {
|
|
5336
5837
|
block = newSession(options, this.#core.scrubber, this.#core.disabled);
|
|
5337
5838
|
} catch (err) {
|
|
5338
|
-
|
|
5339
|
-
`);
|
|
5839
|
+
stderrLine(`baton: session values could not be read; using a minted session: ${printable(err)}`);
|
|
5340
5840
|
block = newSession({}, this.#core.scrubber, this.#core.disabled);
|
|
5341
5841
|
}
|
|
5342
5842
|
return runInSession(this, block, fn);
|