@goodtiming/baton-sdk 1.0.1 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -2
- package/dist/index.cjs +665 -362
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +37 -16
- package/dist/index.d.ts +37 -16
- package/dist/index.js +660 -357
- package/dist/index.js.map +1 -1
- package/package.json +5 -4
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.1.1";
|
|
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) {
|
|
@@ -438,10 +438,54 @@ var EventSchema = import_zod.z.discriminatedUnion("event_type", [
|
|
|
438
438
|
ToolListErrorEventSchema
|
|
439
439
|
]);
|
|
440
440
|
|
|
441
|
+
// src/runtime.ts
|
|
442
|
+
function onWorkers() {
|
|
443
|
+
return typeof globalThis.WebSocketPair === "function" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
|
|
444
|
+
}
|
|
445
|
+
var globalFetch = (input, init) => fetch(input, init);
|
|
446
|
+
function onProcess(event, listener) {
|
|
447
|
+
const target = typeof process !== "undefined" ? process : void 0;
|
|
448
|
+
if (typeof target?.on !== "function") return void 0;
|
|
449
|
+
try {
|
|
450
|
+
target.on(event, listener);
|
|
451
|
+
} catch {
|
|
452
|
+
return void 0;
|
|
453
|
+
}
|
|
454
|
+
return () => {
|
|
455
|
+
try {
|
|
456
|
+
target.off(event, listener);
|
|
457
|
+
} catch {
|
|
458
|
+
}
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
|
|
441
462
|
// src/warn.ts
|
|
442
463
|
function warn(message) {
|
|
443
|
-
if (
|
|
444
|
-
|
|
464
|
+
if (onWorkers()) {
|
|
465
|
+
console.warn(message);
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
try {
|
|
469
|
+
if (typeof process !== "undefined" && typeof process.emitWarning === "function") return process.emitWarning(message);
|
|
470
|
+
} catch {
|
|
471
|
+
}
|
|
472
|
+
stderrLine(message);
|
|
473
|
+
}
|
|
474
|
+
function stderrLine(message) {
|
|
475
|
+
stderrLines([message]);
|
|
476
|
+
}
|
|
477
|
+
function stderrLines(lines) {
|
|
478
|
+
try {
|
|
479
|
+
const stderr = typeof process !== "undefined" ? process.stderr : void 0;
|
|
480
|
+
if (typeof stderr?.write === "function") return void stderr.write(lines.map((line) => `${line}
|
|
481
|
+
`).join(""));
|
|
482
|
+
} catch {
|
|
483
|
+
}
|
|
484
|
+
for (const line of lines) {
|
|
485
|
+
try {
|
|
486
|
+
console.warn(line);
|
|
487
|
+
} catch {
|
|
488
|
+
}
|
|
445
489
|
}
|
|
446
490
|
}
|
|
447
491
|
function printable(err) {
|
|
@@ -571,8 +615,8 @@ function identityScrub(value) {
|
|
|
571
615
|
}
|
|
572
616
|
|
|
573
617
|
// src/sinks.ts
|
|
574
|
-
var
|
|
575
|
-
var
|
|
618
|
+
var fs = __toESM(require("fs"), 1);
|
|
619
|
+
var fsp = __toESM(require("fs/promises"), 1);
|
|
576
620
|
|
|
577
621
|
// src/_text.ts
|
|
578
622
|
var WHITE_SPACE = /^\p{White_Space}$/u;
|
|
@@ -623,7 +667,8 @@ var SHUTDOWN_FLUSH_TIMEOUT_MS = 3e3;
|
|
|
623
667
|
// src/drops.ts
|
|
624
668
|
var RECOVERY_LOG_MS = 6e4;
|
|
625
669
|
var DropCounts = class {
|
|
626
|
-
|
|
670
|
+
// Made on first use: a Worker refuses random values while its modules load.
|
|
671
|
+
#instanceId;
|
|
627
672
|
#total = /* @__PURE__ */ new Map();
|
|
628
673
|
#sinceDelivery = /* @__PURE__ */ new Map();
|
|
629
674
|
#lastRecoveryLog = -RECOVERY_LOG_MS;
|
|
@@ -647,13 +692,13 @@ var DropCounts = class {
|
|
|
647
692
|
const total = lost.reduce((sum2, [, n]) => sum2 + n, 0);
|
|
648
693
|
warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(", ")}.`);
|
|
649
694
|
}
|
|
650
|
-
/** For tests: the counts are one per process. */
|
|
651
695
|
/** Names this process in its loss reports (SPEC §11.4.7). */
|
|
652
696
|
get instanceId() {
|
|
653
|
-
return this.#instanceId;
|
|
697
|
+
return this.#instanceId ??= uuid7();
|
|
654
698
|
}
|
|
699
|
+
/** For tests: the counts are one per process. */
|
|
655
700
|
clear() {
|
|
656
|
-
this.#instanceId =
|
|
701
|
+
this.#instanceId = void 0;
|
|
657
702
|
this.#total.clear();
|
|
658
703
|
this.#sinceDelivery.clear();
|
|
659
704
|
this.#lastRecoveryLog = -RECOVERY_LOG_MS;
|
|
@@ -693,14 +738,9 @@ async function safeWrite(sink, event) {
|
|
|
693
738
|
} catch (err) {
|
|
694
739
|
if (isSinkClosed(err)) return droppedAfterClose(sink);
|
|
695
740
|
PROCESS_DROPS.add("write_failed");
|
|
696
|
-
|
|
697
|
-
`);
|
|
741
|
+
stderrLine(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}`);
|
|
698
742
|
}
|
|
699
743
|
}
|
|
700
|
-
function stderrLine(message) {
|
|
701
|
-
process.stderr.write(`${message}
|
|
702
|
-
`);
|
|
703
|
-
}
|
|
704
744
|
function isTimerMs(value) {
|
|
705
745
|
return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
|
|
706
746
|
}
|
|
@@ -740,11 +780,13 @@ var StdoutSink = class {
|
|
|
740
780
|
stream;
|
|
741
781
|
closed = false;
|
|
742
782
|
constructor(options = {}) {
|
|
743
|
-
this.stream = options.stream
|
|
783
|
+
this.stream = options.stream;
|
|
744
784
|
}
|
|
745
785
|
async write(event) {
|
|
746
786
|
if (this.closed) throw new SinkClosedError("StdoutSink is closed");
|
|
747
|
-
|
|
787
|
+
const line = JSON.stringify(event);
|
|
788
|
+
if (this.stream) this.stream.write(line + "\n");
|
|
789
|
+
else stderrLine(line);
|
|
748
790
|
}
|
|
749
791
|
async flush() {
|
|
750
792
|
}
|
|
@@ -766,7 +808,7 @@ var FileSink = class {
|
|
|
766
808
|
if (this.closed) throw new SinkClosedError("FileSink is closed");
|
|
767
809
|
const line = JSON.stringify(event) + "\n";
|
|
768
810
|
const written = this.last.then(async () => {
|
|
769
|
-
this.file ??= await
|
|
811
|
+
this.file ??= await fsp.open(this.path, "a");
|
|
770
812
|
await this.file.appendFile(line);
|
|
771
813
|
});
|
|
772
814
|
this.last = written.catch(() => void 0);
|
|
@@ -823,30 +865,31 @@ var later = (run) => {
|
|
|
823
865
|
else setTimeout(run, 0);
|
|
824
866
|
};
|
|
825
867
|
var withUnwrittenEvents = /* @__PURE__ */ new Set();
|
|
826
|
-
var
|
|
868
|
+
var exitTriedOn = /* @__PURE__ */ new WeakSet();
|
|
827
869
|
function hookExit() {
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
} catch {
|
|
840
|
-
}
|
|
870
|
+
const target = typeof process !== "undefined" ? process : void 0;
|
|
871
|
+
if (target === void 0 || exitTriedOn.has(target)) return;
|
|
872
|
+
exitTriedOn.add(target);
|
|
873
|
+
onProcess("exit", () => {
|
|
874
|
+
try {
|
|
875
|
+
let unsure = 0;
|
|
876
|
+
for (const sink of withUnwrittenEvents) unsure += sink.handOffAtExit();
|
|
877
|
+
if (unsure > 0) stderrLine(`baton: process exiting; ${unsure} event(s) may not have been written.`);
|
|
878
|
+
} catch {
|
|
879
|
+
}
|
|
880
|
+
});
|
|
841
881
|
}
|
|
842
882
|
function writeNow(sink, events) {
|
|
843
|
-
const
|
|
883
|
+
const json = () => events.map((event) => JSON.stringify(event));
|
|
884
|
+
const lines = () => json().map((line) => line + "\n").join("");
|
|
844
885
|
if (sink instanceof StdoutSink) {
|
|
845
886
|
const stream = sink["stream"];
|
|
846
|
-
if (stream !== process.stdout && stream !== process.stderr) return false;
|
|
847
|
-
if (
|
|
887
|
+
if (stream !== void 0 && stream !== process.stdout && stream !== process.stderr) return false;
|
|
888
|
+
if (sink["closed"]) return true;
|
|
889
|
+
if (stream === void 0) stderrLines(json());
|
|
890
|
+
else stream.write(lines());
|
|
848
891
|
} else if (sink instanceof FileSink) {
|
|
849
|
-
if (!sink["closed"])
|
|
892
|
+
if (!sink["closed"]) fs.appendFileSync(sink["path"], lines());
|
|
850
893
|
} else return false;
|
|
851
894
|
return true;
|
|
852
895
|
}
|
|
@@ -1093,13 +1136,19 @@ var HttpSink = class _HttpSink {
|
|
|
1093
1136
|
/** Whether the queued pass sends everything waiting, not only what is due. */
|
|
1094
1137
|
forceNext = false;
|
|
1095
1138
|
flushTimer = null;
|
|
1096
|
-
/** Set by a failed batch: only the timer, a flush
|
|
1139
|
+
/** Set by a failed batch: only the timer, a flush, a close or, at
|
|
1140
|
+
* `flushIntervalMs` 0, a write after `retryFrom` tries again. */
|
|
1097
1141
|
waitForTimer = false;
|
|
1142
|
+
/** When a failed batch may be tried again. At `flushIntervalMs` 0 the
|
|
1143
|
+
* first write from then retries, as a Worker may drop the timer. */
|
|
1144
|
+
retryFrom = 0;
|
|
1098
1145
|
/** Nothing is sent before this `Date.now()`, from a 429's `Retry-After`. */
|
|
1099
1146
|
retryAt = 0;
|
|
1100
1147
|
/** Set for the life of the sink by a 404 or 405 on the batch path. */
|
|
1101
1148
|
batchless = false;
|
|
1102
1149
|
exitHooks = null;
|
|
1150
|
+
/** The `process` the exit hooks were last tried on, so a refusal is not retried per write. */
|
|
1151
|
+
exitHooksTriedOn;
|
|
1103
1152
|
/** The least time between two of this sink's loss reports. */
|
|
1104
1153
|
static reportIntervalMs = 6e4;
|
|
1105
1154
|
/** Totals only grow, so their sum tells whether they changed. */
|
|
@@ -1120,7 +1169,7 @@ var HttpSink = class _HttpSink {
|
|
|
1120
1169
|
"shutdownFlushTimeoutMs",
|
|
1121
1170
|
SHUTDOWN_FLUSH_TIMEOUT_MS
|
|
1122
1171
|
);
|
|
1123
|
-
this.flushIntervalMs = timerMsOption(options.flushIntervalMs, "flushIntervalMs", FLUSH_INTERVAL_MS);
|
|
1172
|
+
this.flushIntervalMs = timerMsOption(options.flushIntervalMs, "flushIntervalMs", onWorkers() ? 0 : FLUSH_INTERVAL_MS);
|
|
1124
1173
|
this.maxRetries = options.maxRetries ?? 3;
|
|
1125
1174
|
this.backoffBaseMs = options.backoffBaseMs ?? 100;
|
|
1126
1175
|
this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
|
|
@@ -1128,7 +1177,7 @@ var HttpSink = class _HttpSink {
|
|
|
1128
1177
|
options.circuitBreakerThreshold ?? 5,
|
|
1129
1178
|
options.circuitBreakerResetMs ?? 3e4
|
|
1130
1179
|
);
|
|
1131
|
-
this.fetchImpl = options.fetchImpl ??
|
|
1180
|
+
this.fetchImpl = options.fetchImpl ?? globalFetch;
|
|
1132
1181
|
}
|
|
1133
1182
|
/**
|
|
1134
1183
|
* What this sink shows when something prints it — never the bearer.
|
|
@@ -1166,8 +1215,9 @@ var HttpSink = class _HttpSink {
|
|
|
1166
1215
|
}
|
|
1167
1216
|
this.enqueue({ event, json, bytes, writtenAt: Date.now() });
|
|
1168
1217
|
this.unsentWarned = false;
|
|
1169
|
-
|
|
1170
|
-
|
|
1218
|
+
const held = this.waitForTimer && !(this.flushIntervalMs === 0 && Date.now() >= this.retryFrom);
|
|
1219
|
+
if (!held && (this.flushIntervalMs === 0 || this.batchIsFull())) void this.scheduleDrain(false);
|
|
1220
|
+
else this.armTimer(Math.max(this.buffer[0].writtenAt + this.flushIntervalMs, held ? this.retryFrom : 0) - Date.now());
|
|
1171
1221
|
this.ensureExitHooksRegistered();
|
|
1172
1222
|
}
|
|
1173
1223
|
flush() {
|
|
@@ -1196,11 +1246,8 @@ var HttpSink = class _HttpSink {
|
|
|
1196
1246
|
warn(`baton: the sink closed with ${unsent} event(s) unsent.`);
|
|
1197
1247
|
}
|
|
1198
1248
|
this.warnUnloggedRefusals("the sink closed");
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
process.off("exit", this.exitHooks.exit);
|
|
1202
|
-
this.exitHooks = null;
|
|
1203
|
-
}
|
|
1249
|
+
this.exitHooks?.off();
|
|
1250
|
+
this.exitHooks = null;
|
|
1204
1251
|
}
|
|
1205
1252
|
/** SPEC §11.2 rule 7: an explicit flush or close returns within `ms` and
|
|
1206
1253
|
* never rejects. While an earlier wait's drain is still stuck, a flush
|
|
@@ -1294,7 +1341,9 @@ var HttpSink = class _HttpSink {
|
|
|
1294
1341
|
* both hooks: a vendor needing that guarantee must call `aclose()` from
|
|
1295
1342
|
* their own handler. */
|
|
1296
1343
|
ensureExitHooksRegistered() {
|
|
1297
|
-
|
|
1344
|
+
const target = typeof process !== "undefined" ? process : void 0;
|
|
1345
|
+
if (this.exitHooks || target === void 0 || target === this.exitHooksTriedOn) return;
|
|
1346
|
+
this.exitHooksTriedOn = target;
|
|
1298
1347
|
const beforeExit = () => {
|
|
1299
1348
|
if (this.unsent === 0 || this.exitPassRan) {
|
|
1300
1349
|
this.warnUnloggedRefusals("process exiting");
|
|
@@ -1312,9 +1361,14 @@ var HttpSink = class _HttpSink {
|
|
|
1312
1361
|
} catch {
|
|
1313
1362
|
}
|
|
1314
1363
|
};
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1364
|
+
const offBeforeExit = onProcess("beforeExit", beforeExit);
|
|
1365
|
+
const offExit = onProcess("exit", exit);
|
|
1366
|
+
if (offBeforeExit === void 0 || offExit === void 0) {
|
|
1367
|
+
offBeforeExit?.();
|
|
1368
|
+
offExit?.();
|
|
1369
|
+
return;
|
|
1370
|
+
}
|
|
1371
|
+
this.exitHooks = { beforeExit, exit, off: () => (offBeforeExit(), offExit()) };
|
|
1318
1372
|
}
|
|
1319
1373
|
/** One attempt per batch, no retry, within `shutdownFlushTimeoutMs` in
|
|
1320
1374
|
* total (SPEC §11.2); what is left is reported, not sent. */
|
|
@@ -1419,8 +1473,9 @@ var HttpSink = class _HttpSink {
|
|
|
1419
1473
|
this.waitForTimer = failed;
|
|
1420
1474
|
this.clearTimer();
|
|
1421
1475
|
if (failed) {
|
|
1422
|
-
const
|
|
1423
|
-
|
|
1476
|
+
const wait = Math.max(this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest());
|
|
1477
|
+
this.retryFrom = Date.now() + wait;
|
|
1478
|
+
if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(wait);
|
|
1424
1479
|
return;
|
|
1425
1480
|
}
|
|
1426
1481
|
const next = Math.min(this.buffer[0]?.writtenAt ?? Infinity, this.reportRidesHead() ? this.reportSetAt : Infinity);
|
|
@@ -1694,10 +1749,10 @@ var HttpSink = class _HttpSink {
|
|
|
1694
1749
|
};
|
|
1695
1750
|
|
|
1696
1751
|
// src/integrations/mcp/withBaton.ts
|
|
1697
|
-
var
|
|
1752
|
+
var asyncHooks = __toESM(require("async_hooks"), 1);
|
|
1698
1753
|
|
|
1699
1754
|
// src/integrations/mcp/annotation.ts
|
|
1700
|
-
var
|
|
1755
|
+
var import_zod3 = require("zod");
|
|
1701
1756
|
|
|
1702
1757
|
// src/metaCoordinates.ts
|
|
1703
1758
|
var COORD_FIELD_NAMES = /* @__PURE__ */ new Set(["latitude", "longitude"]);
|
|
@@ -1796,6 +1851,23 @@ function declaresParam(schema, name) {
|
|
|
1796
1851
|
const props = schema?.properties;
|
|
1797
1852
|
return typeof props === "object" && props !== null && name in props;
|
|
1798
1853
|
}
|
|
1854
|
+
var NOT_ACCEPTED = /* @__PURE__ */ new Set(["not", "const", "enum", "default", "examples"]);
|
|
1855
|
+
var NAMED_SCHEMAS = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
|
|
1856
|
+
function mayDeclareParam(schema, name) {
|
|
1857
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1858
|
+
const walk2 = (node) => {
|
|
1859
|
+
if (typeof node !== "object" || node === null || seen.has(node)) return false;
|
|
1860
|
+
seen.add(node);
|
|
1861
|
+
const { required, $ref } = node;
|
|
1862
|
+
if (declaresParam(node, name) || Array.isArray(required) && required.includes(name)) return true;
|
|
1863
|
+
if (typeof $ref === "string" && !$ref.startsWith("#")) return true;
|
|
1864
|
+
return Object.entries(node).some(([key, child]) => {
|
|
1865
|
+
if (NAMED_SCHEMAS.has(key) && typeof child === "object" && child !== null) return Object.values(child).some(walk2);
|
|
1866
|
+
return !NOT_ACCEPTED.has(key) && walk2(child);
|
|
1867
|
+
});
|
|
1868
|
+
};
|
|
1869
|
+
return walk2(schema);
|
|
1870
|
+
}
|
|
1799
1871
|
function instructionsSuffixServed(annotationToolName, served) {
|
|
1800
1872
|
if (annotationToolName) return true;
|
|
1801
1873
|
return typeof served === "string" && served.includes(INTENT_INSTRUCTIONS);
|
|
@@ -1820,7 +1892,7 @@ function endsInOurs(current2, vendor) {
|
|
|
1820
1892
|
const rest = current2.slice(prefix.length);
|
|
1821
1893
|
return OURS_STARTS.some((start) => start.test(rest));
|
|
1822
1894
|
}
|
|
1823
|
-
function withVendorInstructions(server, ours, warn3 =
|
|
1895
|
+
function withVendorInstructions(server, ours, warn3 = stderrLine) {
|
|
1824
1896
|
const holder = server;
|
|
1825
1897
|
const current2 = holder._instructions;
|
|
1826
1898
|
let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
|
|
@@ -1834,8 +1906,7 @@ function withVendorInstructions(server, ours, warn3 = (message) => process.stder
|
|
|
1834
1906
|
${ours}`;
|
|
1835
1907
|
if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
|
|
1836
1908
|
warn3(
|
|
1837
|
-
`baton: the server instructions are ${combined.length} chars (yours ${vendor.length}, Baton's ${ours.length}); Claude Code cuts them at ~${CLAUDE_CODE_TRUNCATION_CAP}, so the end of Baton's text is lost there
|
|
1838
|
-
`
|
|
1909
|
+
`baton: the server instructions are ${combined.length} chars (yours ${vendor.length}, Baton's ${ours.length}); Claude Code cuts them at ~${CLAUDE_CODE_TRUNCATION_CAP}, so the end of Baton's text is lost there`
|
|
1839
1910
|
);
|
|
1840
1911
|
}
|
|
1841
1912
|
return combined;
|
|
@@ -1942,8 +2013,7 @@ async function emit(sink, build) {
|
|
|
1942
2013
|
event = build();
|
|
1943
2014
|
} catch (err) {
|
|
1944
2015
|
PROCESS_DROPS.add("encode_failed");
|
|
1945
|
-
|
|
1946
|
-
`);
|
|
2016
|
+
stderrLine(`baton: event construction failed; event dropped: ${printable(err)}`);
|
|
1947
2017
|
return;
|
|
1948
2018
|
}
|
|
1949
2019
|
await safeWrite(sink, event);
|
|
@@ -2204,6 +2274,185 @@ async function resolveIdentity(hook, call) {
|
|
|
2204
2274
|
}
|
|
2205
2275
|
}
|
|
2206
2276
|
|
|
2277
|
+
// src/integrations/mcp/zodCompat.ts
|
|
2278
|
+
var z3rt = __toESM(require("zod/v3"), 1);
|
|
2279
|
+
var z4mini = __toESM(require("zod/v4-mini"), 1);
|
|
2280
|
+
var import_zod_to_json_schema = require("zod-to-json-schema");
|
|
2281
|
+
function isZ4Schema(s) {
|
|
2282
|
+
const schema = s;
|
|
2283
|
+
return !!schema?._zod;
|
|
2284
|
+
}
|
|
2285
|
+
function objectFromShape(shape) {
|
|
2286
|
+
const values = Object.values(shape);
|
|
2287
|
+
if (values.length === 0) return z4mini.object({});
|
|
2288
|
+
const allV4 = values.every(isZ4Schema);
|
|
2289
|
+
const allV3 = values.every((s) => !isZ4Schema(s));
|
|
2290
|
+
if (allV4) return z4mini.object(shape);
|
|
2291
|
+
if (allV3) return z3rt.object(shape);
|
|
2292
|
+
throw new Error("Mixed Zod versions detected in object shape.");
|
|
2293
|
+
}
|
|
2294
|
+
function getObjectShape(schema) {
|
|
2295
|
+
if (!schema) return void 0;
|
|
2296
|
+
let rawShape;
|
|
2297
|
+
if (isZ4Schema(schema)) {
|
|
2298
|
+
rawShape = schema._zod?.def?.shape;
|
|
2299
|
+
} else {
|
|
2300
|
+
rawShape = schema.shape;
|
|
2301
|
+
}
|
|
2302
|
+
if (!rawShape) return void 0;
|
|
2303
|
+
if (typeof rawShape === "function") {
|
|
2304
|
+
try {
|
|
2305
|
+
return rawShape();
|
|
2306
|
+
} catch {
|
|
2307
|
+
return void 0;
|
|
2308
|
+
}
|
|
2309
|
+
}
|
|
2310
|
+
return rawShape;
|
|
2311
|
+
}
|
|
2312
|
+
function normalizeObjectSchema(schema) {
|
|
2313
|
+
if (!schema) return void 0;
|
|
2314
|
+
if (typeof schema === "object") {
|
|
2315
|
+
const asAny = schema;
|
|
2316
|
+
if (!asAny._def && !asAny._zod) {
|
|
2317
|
+
const values = Object.values(schema);
|
|
2318
|
+
if (values.length > 0 && values.every(
|
|
2319
|
+
(v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function")
|
|
2320
|
+
)) {
|
|
2321
|
+
return objectFromShape(schema);
|
|
2322
|
+
}
|
|
2323
|
+
}
|
|
2324
|
+
}
|
|
2325
|
+
if (isZ4Schema(schema)) {
|
|
2326
|
+
const def = schema._zod?.def;
|
|
2327
|
+
if (def && (def.type === "object" || def.shape !== void 0)) return schema;
|
|
2328
|
+
} else {
|
|
2329
|
+
if (schema.shape !== void 0) return schema;
|
|
2330
|
+
}
|
|
2331
|
+
return void 0;
|
|
2332
|
+
}
|
|
2333
|
+
function mapMiniTarget(t) {
|
|
2334
|
+
if (!t) return "draft-7";
|
|
2335
|
+
if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
|
|
2336
|
+
if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
|
|
2337
|
+
return "draft-7";
|
|
2338
|
+
}
|
|
2339
|
+
function toJsonSchemaCompat(schema, opts) {
|
|
2340
|
+
if (isZ4Schema(schema)) {
|
|
2341
|
+
return z4mini.toJSONSchema(schema, {
|
|
2342
|
+
target: mapMiniTarget(opts?.target),
|
|
2343
|
+
io: opts?.pipeStrategy ?? "input"
|
|
2344
|
+
});
|
|
2345
|
+
}
|
|
2346
|
+
return (0, import_zod_to_json_schema.zodToJsonSchema)(schema, {
|
|
2347
|
+
strictUnions: opts?.strictUnions ?? true,
|
|
2348
|
+
pipeStrategy: opts?.pipeStrategy ?? "input"
|
|
2349
|
+
});
|
|
2350
|
+
}
|
|
2351
|
+
|
|
2352
|
+
// src/integrations/mcp/schemaCompat.ts
|
|
2353
|
+
var import_zod2 = require("zod");
|
|
2354
|
+
var import_v3 = require("zod/v3");
|
|
2355
|
+
var DEFAULT_INTENT_PARAM_MODE = "required";
|
|
2356
|
+
var ROOT_COMBINERS = ["$ref", "oneOf", "anyOf", "allOf"];
|
|
2357
|
+
function takesUserGoalJson(schema) {
|
|
2358
|
+
const properties = schema.properties ?? {};
|
|
2359
|
+
return isRecord(properties) && !ROOT_COMBINERS.some((key) => key in schema);
|
|
2360
|
+
}
|
|
2361
|
+
function withUserGoalJson(schema, intentParamMode, listRequired) {
|
|
2362
|
+
if (!takesUserGoalJson(schema) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return schema;
|
|
2363
|
+
const properties = schema.properties ?? {};
|
|
2364
|
+
const goal = { type: "string", description: buildUserGoalParamDescription({ intentParamMode }) };
|
|
2365
|
+
const served = { ...schema, properties: { ...properties, [USER_GOAL_PARAM_NAME]: goal } };
|
|
2366
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
2367
|
+
if (listRequired && !required.includes(USER_GOAL_PARAM_NAME)) served.required = [...required, USER_GOAL_PARAM_NAME];
|
|
2368
|
+
return served;
|
|
2369
|
+
}
|
|
2370
|
+
var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
|
|
2371
|
+
function injectGoalParams(inputSchema2, intentParamMode) {
|
|
2372
|
+
const objSchema = normalizeObjectSchema(inputSchema2);
|
|
2373
|
+
if (!objSchema) return { schema: inputSchema2, dispositions: {} };
|
|
2374
|
+
const existingShape = getObjectShape(objSchema) ?? {};
|
|
2375
|
+
const values = Object.values(existingShape);
|
|
2376
|
+
const useV4 = values.length === 0 || isZ4Schema(values[0]);
|
|
2377
|
+
const zodImpl = useV4 ? import_zod2.z : import_v3.z;
|
|
2378
|
+
const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
|
|
2379
|
+
if (Object.keys(toInject).length === 0)
|
|
2380
|
+
return { schema: inputSchema2, dispositions };
|
|
2381
|
+
const mergedShape = { ...existingShape, ...toInject };
|
|
2382
|
+
const newSchema = objectFromShape(mergedShape);
|
|
2383
|
+
return { schema: newSchema, dispositions };
|
|
2384
|
+
}
|
|
2385
|
+
function buildIntentFields(existingShape, zodImpl, intentParamMode) {
|
|
2386
|
+
const dispositions = {};
|
|
2387
|
+
const toInject = {};
|
|
2388
|
+
for (const name of RETIRED_PARAM_NAMES) {
|
|
2389
|
+
if (name in existingShape) dispositions[name] = "native";
|
|
2390
|
+
}
|
|
2391
|
+
if (USER_GOAL_PARAM_NAME in existingShape) {
|
|
2392
|
+
dispositions[USER_GOAL_PARAM_NAME] = "native";
|
|
2393
|
+
} else {
|
|
2394
|
+
dispositions[USER_GOAL_PARAM_NAME] = "injected";
|
|
2395
|
+
toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
|
|
2396
|
+
}
|
|
2397
|
+
return { dispositions, toInject };
|
|
2398
|
+
}
|
|
2399
|
+
function injectGoalParamsV2(inputSchema2, intentParamMode) {
|
|
2400
|
+
const candidate = inputSchema2;
|
|
2401
|
+
const shape = candidate?.shape;
|
|
2402
|
+
if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
|
|
2403
|
+
return { schema: inputSchema2, dispositions: {} };
|
|
2404
|
+
}
|
|
2405
|
+
const { dispositions, toInject } = buildIntentFields(shape, import_zod2.z, intentParamMode);
|
|
2406
|
+
if (Object.keys(toInject).length === 0)
|
|
2407
|
+
return { schema: inputSchema2, dispositions };
|
|
2408
|
+
return { schema: candidate.extend(toInject), dispositions };
|
|
2409
|
+
}
|
|
2410
|
+
function advertiseIntentParamsRequired(result, names, isInjected) {
|
|
2411
|
+
const tools = result?.tools;
|
|
2412
|
+
if (!Array.isArray(tools)) return result;
|
|
2413
|
+
let changed = false;
|
|
2414
|
+
const advertised = tools.map((tool) => {
|
|
2415
|
+
const entry = tool;
|
|
2416
|
+
const toolName = entry?.name;
|
|
2417
|
+
if (typeof toolName !== "string") return tool;
|
|
2418
|
+
const schema = entry?.inputSchema;
|
|
2419
|
+
if (!schema || typeof schema !== "object") return tool;
|
|
2420
|
+
const declared2 = schema.required ?? [];
|
|
2421
|
+
if (!Array.isArray(declared2)) return tool;
|
|
2422
|
+
const required = declared2;
|
|
2423
|
+
const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
|
|
2424
|
+
if (missing.length === 0) return tool;
|
|
2425
|
+
changed = true;
|
|
2426
|
+
return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
|
|
2427
|
+
});
|
|
2428
|
+
return changed ? { ...result, tools: advertised } : result;
|
|
2429
|
+
}
|
|
2430
|
+
function withToolInputSchema(result, name, inputSchema2) {
|
|
2431
|
+
const tools = result?.tools;
|
|
2432
|
+
if (!Array.isArray(tools)) return result;
|
|
2433
|
+
const at = tools.findIndex((tool) => isRecord(tool) && tool.name === name);
|
|
2434
|
+
if (at === -1) return result;
|
|
2435
|
+
const served = [...tools];
|
|
2436
|
+
served[at] = { ...tools[at], inputSchema: inputSchema2 };
|
|
2437
|
+
return { ...result, tools: served };
|
|
2438
|
+
}
|
|
2439
|
+
function standardInputJsonSchema(schema) {
|
|
2440
|
+
try {
|
|
2441
|
+
const standard = schema?.["~standard"];
|
|
2442
|
+
return standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
|
|
2443
|
+
} catch {
|
|
2444
|
+
return void 0;
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
function toolInputJsonSchema(inputSchema2) {
|
|
2448
|
+
const objSchema = normalizeObjectSchema(inputSchema2);
|
|
2449
|
+
if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
|
|
2450
|
+
return toJsonSchemaCompat(objSchema, {
|
|
2451
|
+
strictUnions: true,
|
|
2452
|
+
pipeStrategy: "input"
|
|
2453
|
+
});
|
|
2454
|
+
}
|
|
2455
|
+
|
|
2207
2456
|
// src/integrations/mcp/safeScrub.ts
|
|
2208
2457
|
var warned2 = /* @__PURE__ */ new Set();
|
|
2209
2458
|
function scrubOrNull(scrubber, value, field) {
|
|
@@ -2213,9 +2462,8 @@ function scrubOrNull(scrubber, value, field) {
|
|
|
2213
2462
|
} catch (err) {
|
|
2214
2463
|
if (!warned2.has(field)) {
|
|
2215
2464
|
warned2.add(field);
|
|
2216
|
-
|
|
2217
|
-
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}
|
|
2218
|
-
`
|
|
2465
|
+
stderrLine(
|
|
2466
|
+
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}`
|
|
2219
2467
|
);
|
|
2220
2468
|
}
|
|
2221
2469
|
return null;
|
|
@@ -2344,30 +2592,50 @@ function sessionIdFromHeader(extra) {
|
|
|
2344
2592
|
// src/integrations/mcp/annotation.ts
|
|
2345
2593
|
var TOOL_NAME_PARAM_NAME = "tool_name";
|
|
2346
2594
|
var ANNOTATION_INPUT_SHAPE = {
|
|
2347
|
-
user_goal:
|
|
2348
|
-
what_happened:
|
|
2595
|
+
user_goal: import_zod3.z.string(),
|
|
2596
|
+
what_happened: import_zod3.z.string().optional(),
|
|
2349
2597
|
// Nullable so a report whose agent sends an explicit null is taken,
|
|
2350
2598
|
// not rejected by validation.
|
|
2351
|
-
tool_name:
|
|
2352
|
-
suggested_improvement:
|
|
2353
|
-
|
|
2599
|
+
tool_name: import_zod3.z.string().nullable().optional(),
|
|
2600
|
+
suggested_improvement: import_zod3.z.string().optional(),
|
|
2601
|
+
// zod renders "any value" as `{}`, which some MCP clients refuse (reportToolSchema.test.ts).
|
|
2602
|
+
context: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).meta({ additionalProperties: true }).optional()
|
|
2354
2603
|
};
|
|
2355
2604
|
function isReport(whatHappened) {
|
|
2356
2605
|
return typeof whatHappened === "string" && !isBlank(whatHappened);
|
|
2357
2606
|
}
|
|
2358
2607
|
function registerAnnotationTool(server, options) {
|
|
2608
|
+
const tool = buildAnnotationTool(server, options);
|
|
2609
|
+
server.registerTool(
|
|
2610
|
+
tool.name,
|
|
2611
|
+
{ description: tool.description, inputSchema: ANNOTATION_INPUT_SHAPE },
|
|
2612
|
+
tool.handler
|
|
2613
|
+
);
|
|
2614
|
+
return tool.name;
|
|
2615
|
+
}
|
|
2616
|
+
var ANNOTATION_ARGS = import_zod3.z.object(ANNOTATION_INPUT_SHAPE);
|
|
2617
|
+
function annotationInputJsonSchema(major) {
|
|
2618
|
+
return annotationJsonSchemas[major] ??= (major === 2 ? standardInputJsonSchema(ANNOTATION_ARGS) : void 0) ?? toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
|
|
2619
|
+
}
|
|
2620
|
+
var annotationJsonSchemas = {};
|
|
2621
|
+
function callAnnotationTool(tool, args, extra) {
|
|
2622
|
+
const parsed = ANNOTATION_ARGS.safeParse(args ?? {});
|
|
2623
|
+
if (parsed.success) return tool.handler(parsed.data, extra);
|
|
2624
|
+
return Promise.resolve({
|
|
2625
|
+
content: [{ type: "text", text: `Invalid arguments for tool ${tool.name}: ${parsed.error.message}` }],
|
|
2626
|
+
isError: true
|
|
2627
|
+
});
|
|
2628
|
+
}
|
|
2629
|
+
function buildAnnotationTool(server, options) {
|
|
2359
2630
|
const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
|
|
2360
2631
|
const description = buildAnnotationToolDescription({
|
|
2361
2632
|
vendorDisplayName: options.vendorDisplayName
|
|
2362
2633
|
});
|
|
2363
2634
|
const refusal = buildRefusalText({ annotationToolName: name });
|
|
2364
|
-
|
|
2635
|
+
return {
|
|
2365
2636
|
name,
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
inputSchema: ANNOTATION_INPUT_SHAPE
|
|
2369
|
-
},
|
|
2370
|
-
async (args, extra) => {
|
|
2637
|
+
description,
|
|
2638
|
+
handler: async (args, extra) => {
|
|
2371
2639
|
const whatHappened = args.what_happened;
|
|
2372
2640
|
if (!isReport(whatHappened)) {
|
|
2373
2641
|
return {
|
|
@@ -2427,8 +2695,7 @@ function registerAnnotationTool(server, options) {
|
|
|
2427
2695
|
);
|
|
2428
2696
|
return { content: [{ type: "text", text: JSON.stringify({ ok: true }) }] };
|
|
2429
2697
|
}
|
|
2430
|
-
|
|
2431
|
-
return name;
|
|
2698
|
+
};
|
|
2432
2699
|
}
|
|
2433
2700
|
|
|
2434
2701
|
// src/dsn.ts
|
|
@@ -2703,7 +2970,7 @@ function scrubbedErrorBody(scrubber, text) {
|
|
|
2703
2970
|
}
|
|
2704
2971
|
|
|
2705
2972
|
// src/integrations/mcp/captureSettings.ts
|
|
2706
|
-
var
|
|
2973
|
+
var crypto2 = __toESM(require("crypto"), 1);
|
|
2707
2974
|
var SETTINGS_PATH = "/v0/settings";
|
|
2708
2975
|
var TENANT_HEADER = "X-Baton-Tenant-Id";
|
|
2709
2976
|
var SETTINGS_MODES = ["local", "console"];
|
|
@@ -2715,7 +2982,7 @@ var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
|
|
|
2715
2982
|
var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
|
|
2716
2983
|
var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
|
|
2717
2984
|
function shareBucket(vendorId2, key) {
|
|
2718
|
-
const digest =
|
|
2985
|
+
const digest = crypto2.createHash("sha256").update(`${vendorId2}
|
|
2719
2986
|
${key}`, "utf-8").digest();
|
|
2720
2987
|
return Number(digest.readBigUInt64BE(0) % 10000n);
|
|
2721
2988
|
}
|
|
@@ -2811,7 +3078,7 @@ var SettingsFetcher = class {
|
|
|
2811
3078
|
this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
|
|
2812
3079
|
this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
|
|
2813
3080
|
this.refreshMs = options.refreshMs;
|
|
2814
|
-
this.fetchImpl = options.fetchImpl ??
|
|
3081
|
+
this.fetchImpl = options.fetchImpl ?? globalFetch;
|
|
2815
3082
|
}
|
|
2816
3083
|
get document() {
|
|
2817
3084
|
return this.held;
|
|
@@ -2909,19 +3176,31 @@ function resolveInstallConfig(config) {
|
|
|
2909
3176
|
);
|
|
2910
3177
|
return { resolved, unconfigured };
|
|
2911
3178
|
}
|
|
2912
|
-
|
|
3179
|
+
var consoleOffWarned = false;
|
|
3180
|
+
function withoutConsoleOnWorkers(config) {
|
|
3181
|
+
if (config.settings !== "console" || !onWorkers()) return config;
|
|
3182
|
+
if (!consoleOffWarned) {
|
|
3183
|
+
consoleOffWarned = true;
|
|
3184
|
+
warn(`baton: settings: "console" is not supported on Cloudflare Workers yet; the Console's settings are not read and this config's capture values apply.`);
|
|
3185
|
+
}
|
|
3186
|
+
const rest = { ...config, reportMode: config.reportMode ?? "on" };
|
|
3187
|
+
delete rest.settings;
|
|
3188
|
+
return rest;
|
|
3189
|
+
}
|
|
3190
|
+
function resolveBatonConfig(supplied) {
|
|
2913
3191
|
const dsnString = selectDsn(
|
|
2914
|
-
|
|
3192
|
+
supplied.dsn,
|
|
2915
3193
|
{
|
|
2916
3194
|
// Truthiness per field, mirroring Python's `bool()` / `is not None`
|
|
2917
3195
|
// split: an empty `vendorId` is an unset one, while an explicitly
|
|
2918
3196
|
// supplied `tenantId` or `sink` is a conflict whatever it holds.
|
|
2919
|
-
vendorId: Boolean(
|
|
2920
|
-
tenantId:
|
|
2921
|
-
sink:
|
|
3197
|
+
vendorId: Boolean(supplied.vendorId),
|
|
3198
|
+
tenantId: supplied.tenantId !== void 0,
|
|
3199
|
+
sink: supplied.sink !== void 0
|
|
2922
3200
|
},
|
|
2923
3201
|
"BatonConfig"
|
|
2924
3202
|
);
|
|
3203
|
+
const config = dsnString === void 0 ? supplied : withoutConsoleOnWorkers(supplied);
|
|
2925
3204
|
if (dsnString === void 0) {
|
|
2926
3205
|
const defaulted = {
|
|
2927
3206
|
...config,
|
|
@@ -3056,6 +3335,9 @@ function validateBatonConfig(config) {
|
|
|
3056
3335
|
if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
|
|
3057
3336
|
throw new Error("BatonConfig.resolvePrincipal must be a function.");
|
|
3058
3337
|
}
|
|
3338
|
+
if (config.tools !== void 0 && !Array.isArray(config.tools) && typeof config.tools !== "function") {
|
|
3339
|
+
throw new Error("BatonConfig.tools must be an array of tools or a function that returns one.");
|
|
3340
|
+
}
|
|
3059
3341
|
}
|
|
3060
3342
|
|
|
3061
3343
|
// src/optout.ts
|
|
@@ -3159,8 +3441,7 @@ var PerCallerSurface = class {
|
|
|
3159
3441
|
this.options.writeInstructions(pointerOn ? this.options.instructions : INTENT_INSTRUCTIONS);
|
|
3160
3442
|
this.pointerOn = pointerOn;
|
|
3161
3443
|
} catch (err) {
|
|
3162
|
-
|
|
3163
|
-
`);
|
|
3444
|
+
stderrLine(`baton: could not update the server instructions for new settings: ${printable(err)}`);
|
|
3164
3445
|
}
|
|
3165
3446
|
}
|
|
3166
3447
|
/** `result` with the caller's goal and reports settings; as served on any failure. */
|
|
@@ -3183,8 +3464,7 @@ var PerCallerSurface = class {
|
|
|
3183
3464
|
}
|
|
3184
3465
|
return { ...result, tools: served };
|
|
3185
3466
|
} catch (err) {
|
|
3186
|
-
|
|
3187
|
-
`);
|
|
3467
|
+
stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
|
|
3188
3468
|
return result;
|
|
3189
3469
|
}
|
|
3190
3470
|
}
|
|
@@ -3242,159 +3522,11 @@ var ServerCounter = class extends SessionCounter {
|
|
|
3242
3522
|
}
|
|
3243
3523
|
};
|
|
3244
3524
|
|
|
3245
|
-
// src/integrations/mcp/zodCompat.ts
|
|
3246
|
-
var z3rt = __toESM(require("zod/v3"), 1);
|
|
3247
|
-
var z4mini = __toESM(require("zod/v4-mini"), 1);
|
|
3248
|
-
var import_zod_to_json_schema = require("zod-to-json-schema");
|
|
3249
|
-
function isZ4Schema(s) {
|
|
3250
|
-
const schema = s;
|
|
3251
|
-
return !!schema?._zod;
|
|
3252
|
-
}
|
|
3253
|
-
function objectFromShape(shape) {
|
|
3254
|
-
const values = Object.values(shape);
|
|
3255
|
-
if (values.length === 0) return z4mini.object({});
|
|
3256
|
-
const allV4 = values.every(isZ4Schema);
|
|
3257
|
-
const allV3 = values.every((s) => !isZ4Schema(s));
|
|
3258
|
-
if (allV4) return z4mini.object(shape);
|
|
3259
|
-
if (allV3) return z3rt.object(shape);
|
|
3260
|
-
throw new Error("Mixed Zod versions detected in object shape.");
|
|
3261
|
-
}
|
|
3262
|
-
function getObjectShape(schema) {
|
|
3263
|
-
if (!schema) return void 0;
|
|
3264
|
-
let rawShape;
|
|
3265
|
-
if (isZ4Schema(schema)) {
|
|
3266
|
-
rawShape = schema._zod?.def?.shape;
|
|
3267
|
-
} else {
|
|
3268
|
-
rawShape = schema.shape;
|
|
3269
|
-
}
|
|
3270
|
-
if (!rawShape) return void 0;
|
|
3271
|
-
if (typeof rawShape === "function") {
|
|
3272
|
-
try {
|
|
3273
|
-
return rawShape();
|
|
3274
|
-
} catch {
|
|
3275
|
-
return void 0;
|
|
3276
|
-
}
|
|
3277
|
-
}
|
|
3278
|
-
return rawShape;
|
|
3279
|
-
}
|
|
3280
|
-
function normalizeObjectSchema(schema) {
|
|
3281
|
-
if (!schema) return void 0;
|
|
3282
|
-
if (typeof schema === "object") {
|
|
3283
|
-
const asAny = schema;
|
|
3284
|
-
if (!asAny._def && !asAny._zod) {
|
|
3285
|
-
const values = Object.values(schema);
|
|
3286
|
-
if (values.length > 0 && values.every(
|
|
3287
|
-
(v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function")
|
|
3288
|
-
)) {
|
|
3289
|
-
return objectFromShape(schema);
|
|
3290
|
-
}
|
|
3291
|
-
}
|
|
3292
|
-
}
|
|
3293
|
-
if (isZ4Schema(schema)) {
|
|
3294
|
-
const def = schema._zod?.def;
|
|
3295
|
-
if (def && (def.type === "object" || def.shape !== void 0)) return schema;
|
|
3296
|
-
} else {
|
|
3297
|
-
if (schema.shape !== void 0) return schema;
|
|
3298
|
-
}
|
|
3299
|
-
return void 0;
|
|
3300
|
-
}
|
|
3301
|
-
function mapMiniTarget(t) {
|
|
3302
|
-
if (!t) return "draft-7";
|
|
3303
|
-
if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
|
|
3304
|
-
if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
|
|
3305
|
-
return "draft-7";
|
|
3306
|
-
}
|
|
3307
|
-
function toJsonSchemaCompat(schema, opts) {
|
|
3308
|
-
if (isZ4Schema(schema)) {
|
|
3309
|
-
return z4mini.toJSONSchema(schema, {
|
|
3310
|
-
target: mapMiniTarget(opts?.target),
|
|
3311
|
-
io: opts?.pipeStrategy ?? "input"
|
|
3312
|
-
});
|
|
3313
|
-
}
|
|
3314
|
-
return (0, import_zod_to_json_schema.zodToJsonSchema)(schema, {
|
|
3315
|
-
strictUnions: opts?.strictUnions ?? true,
|
|
3316
|
-
pipeStrategy: opts?.pipeStrategy ?? "input"
|
|
3317
|
-
});
|
|
3318
|
-
}
|
|
3319
|
-
|
|
3320
|
-
// src/integrations/mcp/schemaCompat.ts
|
|
3321
|
-
var import_zod3 = require("zod");
|
|
3322
|
-
var import_v3 = require("zod/v3");
|
|
3323
|
-
var DEFAULT_INTENT_PARAM_MODE = "required";
|
|
3324
|
-
var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
|
|
3325
|
-
function injectGoalParams(inputSchema2, intentParamMode) {
|
|
3326
|
-
const objSchema = normalizeObjectSchema(inputSchema2);
|
|
3327
|
-
if (!objSchema) return { schema: inputSchema2, dispositions: {} };
|
|
3328
|
-
const existingShape = getObjectShape(objSchema) ?? {};
|
|
3329
|
-
const values = Object.values(existingShape);
|
|
3330
|
-
const useV4 = values.length === 0 || isZ4Schema(values[0]);
|
|
3331
|
-
const zodImpl = useV4 ? import_zod3.z : import_v3.z;
|
|
3332
|
-
const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
|
|
3333
|
-
if (Object.keys(toInject).length === 0)
|
|
3334
|
-
return { schema: inputSchema2, dispositions };
|
|
3335
|
-
const mergedShape = { ...existingShape, ...toInject };
|
|
3336
|
-
const newSchema = objectFromShape(mergedShape);
|
|
3337
|
-
return { schema: newSchema, dispositions };
|
|
3338
|
-
}
|
|
3339
|
-
function buildIntentFields(existingShape, zodImpl, intentParamMode) {
|
|
3340
|
-
const dispositions = {};
|
|
3341
|
-
const toInject = {};
|
|
3342
|
-
for (const name of RETIRED_PARAM_NAMES) {
|
|
3343
|
-
if (name in existingShape) dispositions[name] = "native";
|
|
3344
|
-
}
|
|
3345
|
-
if (USER_GOAL_PARAM_NAME in existingShape) {
|
|
3346
|
-
dispositions[USER_GOAL_PARAM_NAME] = "native";
|
|
3347
|
-
} else {
|
|
3348
|
-
dispositions[USER_GOAL_PARAM_NAME] = "injected";
|
|
3349
|
-
toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
|
|
3350
|
-
}
|
|
3351
|
-
return { dispositions, toInject };
|
|
3352
|
-
}
|
|
3353
|
-
function injectGoalParamsV2(inputSchema2, intentParamMode) {
|
|
3354
|
-
const candidate = inputSchema2;
|
|
3355
|
-
const shape = candidate?.shape;
|
|
3356
|
-
if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
|
|
3357
|
-
return { schema: inputSchema2, dispositions: {} };
|
|
3358
|
-
}
|
|
3359
|
-
const { dispositions, toInject } = buildIntentFields(shape, import_zod3.z, intentParamMode);
|
|
3360
|
-
if (Object.keys(toInject).length === 0)
|
|
3361
|
-
return { schema: inputSchema2, dispositions };
|
|
3362
|
-
return { schema: candidate.extend(toInject), dispositions };
|
|
3363
|
-
}
|
|
3364
|
-
function advertiseIntentParamsRequired(result, names, isInjected) {
|
|
3365
|
-
const tools = result?.tools;
|
|
3366
|
-
if (!Array.isArray(tools)) return result;
|
|
3367
|
-
let changed = false;
|
|
3368
|
-
const advertised = tools.map((tool) => {
|
|
3369
|
-
const entry = tool;
|
|
3370
|
-
const toolName = entry?.name;
|
|
3371
|
-
if (typeof toolName !== "string") return tool;
|
|
3372
|
-
const schema = entry?.inputSchema;
|
|
3373
|
-
if (!schema || typeof schema !== "object") return tool;
|
|
3374
|
-
const declared2 = schema.required ?? [];
|
|
3375
|
-
if (!Array.isArray(declared2)) return tool;
|
|
3376
|
-
const required = declared2;
|
|
3377
|
-
const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
|
|
3378
|
-
if (missing.length === 0) return tool;
|
|
3379
|
-
changed = true;
|
|
3380
|
-
return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
|
|
3381
|
-
});
|
|
3382
|
-
return changed ? { ...result, tools: advertised } : result;
|
|
3383
|
-
}
|
|
3384
|
-
function toolInputJsonSchema(inputSchema2) {
|
|
3385
|
-
const objSchema = normalizeObjectSchema(inputSchema2);
|
|
3386
|
-
if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
|
|
3387
|
-
return toJsonSchemaCompat(objSchema, {
|
|
3388
|
-
strictUnions: true,
|
|
3389
|
-
pipeStrategy: "input"
|
|
3390
|
-
});
|
|
3391
|
-
}
|
|
3392
|
-
|
|
3393
3525
|
// src/integrations/mcp/surface.ts
|
|
3394
|
-
var
|
|
3526
|
+
var crypto3 = __toESM(require("crypto"), 1);
|
|
3395
3527
|
function surfaceHash(surface) {
|
|
3396
3528
|
const canonical = canonicalJson(surface);
|
|
3397
|
-
const digest =
|
|
3529
|
+
const digest = crypto3.createHash("sha256").update(canonical, "utf-8").digest("hex");
|
|
3398
3530
|
return `sha256:${digest}`;
|
|
3399
3531
|
}
|
|
3400
3532
|
function canonicalJson(value) {
|
|
@@ -3456,7 +3588,7 @@ var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
|
|
|
3456
3588
|
var wired = /* @__PURE__ */ new WeakSet();
|
|
3457
3589
|
var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
|
|
3458
3590
|
var INTENT_PARAM_NAMES = [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES];
|
|
3459
|
-
var callSlots = new
|
|
3591
|
+
var callSlots = new asyncHooks.AsyncLocalStorage();
|
|
3460
3592
|
var SurfaceState = class {
|
|
3461
3593
|
constructor(serverMeta, sentSurfaces) {
|
|
3462
3594
|
this.serverMeta = serverMeta;
|
|
@@ -3473,10 +3605,13 @@ var SurfaceState = class {
|
|
|
3473
3605
|
/** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
|
|
3474
3606
|
* which picks the spelling THIS SDK major puts on the wire. */
|
|
3475
3607
|
noteTool(name, inputSchemaJson, description) {
|
|
3476
|
-
this.rawTools.
|
|
3477
|
-
|
|
3478
|
-
|
|
3479
|
-
|
|
3608
|
+
const before = this.rawTools.get(name);
|
|
3609
|
+
const tool = { name, description: description ?? null, inputSchema: inputSchemaJson };
|
|
3610
|
+
if (before !== void 0 && before.tool.description === tool.description) {
|
|
3611
|
+
const same = before.tool.inputSchema === inputSchemaJson || JSON.stringify(before.tool.inputSchema) === JSON.stringify(inputSchemaJson);
|
|
3612
|
+
if (same) return;
|
|
3613
|
+
}
|
|
3614
|
+
this.rawTools.set(name, { disabled: before?.disabled ?? false, tool });
|
|
3480
3615
|
this.dirty = true;
|
|
3481
3616
|
}
|
|
3482
3617
|
pruneTool(name) {
|
|
@@ -3518,14 +3653,14 @@ async function resolveEnvelopeParts(ctx, extra) {
|
|
|
3518
3653
|
const session = await resolveSessionId(ctx.fallbackSessionId, extra);
|
|
3519
3654
|
return { ...session, scrubbedMeta };
|
|
3520
3655
|
}
|
|
3521
|
-
async function openCall(ctx, toolName, extra, params, stripped,
|
|
3656
|
+
async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn") {
|
|
3522
3657
|
await maybeEmitSurfaceSnapshot(ctx);
|
|
3523
3658
|
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
3524
3659
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
3525
|
-
const rawIntent = stripped[USER_GOAL_PARAM_NAME] ?? extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions,
|
|
3660
|
+
const rawIntent = stripped[USER_GOAL_PARAM_NAME] ?? extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, unlisted);
|
|
3526
3661
|
const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
|
|
3527
3662
|
const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
|
|
3528
|
-
(name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
|
|
3663
|
+
(name) => dispositions === void 0 || dispositions[name] === "native" || unlisted === "leave" || unlisted === "goalOnly" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
|
|
3529
3664
|
);
|
|
3530
3665
|
const client = observeClient(extra, ctx);
|
|
3531
3666
|
const caller = await resolveCaller(
|
|
@@ -3571,7 +3706,7 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
|
|
|
3571
3706
|
);
|
|
3572
3707
|
return { common, session, resultCaptureMode };
|
|
3573
3708
|
}
|
|
3574
|
-
function batonWrap(nameRef, original, ctx) {
|
|
3709
|
+
function batonWrap(nameRef, original, ctx, unlisted = "warn") {
|
|
3575
3710
|
return async (...callArgs) => {
|
|
3576
3711
|
const toolName = nameRef.current;
|
|
3577
3712
|
const slot = callSlots.getStore();
|
|
@@ -3580,7 +3715,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
3580
3715
|
const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
|
|
3581
3716
|
const stripped = slot?.strippedFor === toolName ? slot.stripped : {};
|
|
3582
3717
|
if (slot) slot.strippedFor = null;
|
|
3583
|
-
const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped);
|
|
3718
|
+
const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped, unlisted);
|
|
3584
3719
|
const terminate = async (build, replacement) => {
|
|
3585
3720
|
if (!slot) {
|
|
3586
3721
|
if (build !== null) await emit(ctx.sink, build);
|
|
@@ -3738,14 +3873,14 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
3738
3873
|
return result;
|
|
3739
3874
|
};
|
|
3740
3875
|
}
|
|
3741
|
-
function extractGoalParam(args, paramName, toolName, dispositions,
|
|
3876
|
+
function extractGoalParam(args, paramName, toolName, dispositions, unlisted) {
|
|
3742
3877
|
if (!(paramName in args)) return null;
|
|
3743
3878
|
const disposition = dispositions ? dispositions[paramName] : void 0;
|
|
3744
3879
|
if (disposition === "native") return null;
|
|
3745
|
-
if (disposition === void 0 &&
|
|
3746
|
-
|
|
3747
|
-
|
|
3748
|
-
`
|
|
3880
|
+
if (disposition === void 0 && unlisted === "leave") return null;
|
|
3881
|
+
if (disposition === void 0 && unlisted === "warn") {
|
|
3882
|
+
stderrLine(
|
|
3883
|
+
`baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)`
|
|
3749
3884
|
);
|
|
3750
3885
|
}
|
|
3751
3886
|
return popText(args, paramName);
|
|
@@ -3779,8 +3914,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
3779
3914
|
snapshot = ctx.surfaceState.buildSnapshot();
|
|
3780
3915
|
digest = surfaceHash(snapshot);
|
|
3781
3916
|
} catch (err) {
|
|
3782
|
-
|
|
3783
|
-
`);
|
|
3917
|
+
stderrLine(`baton: surface snapshot capture failed: ${String(err)}`);
|
|
3784
3918
|
return;
|
|
3785
3919
|
}
|
|
3786
3920
|
const sent = ctx.surfaceState.sentSurfaces;
|
|
@@ -3848,16 +3982,16 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
|
|
|
3848
3982
|
return registered;
|
|
3849
3983
|
};
|
|
3850
3984
|
}
|
|
3851
|
-
function installToolsListSeam(lowLevel, ctx) {
|
|
3985
|
+
function installToolsListSeam(lowLevel, ctx, listsOwnReportTool) {
|
|
3852
3986
|
const names = [...requiredParamNames(ctx.intentParamMode), TOOL_NAME_PARAM_NAME];
|
|
3853
3987
|
const isInjected = (toolName, paramName) => toolName === ctx.annotationToolName ? paramName === TOOL_NAME_PARAM_NAME : ctx.paramRegistry.get(toolName)?.[paramName] === "injected";
|
|
3854
3988
|
const advertise = (result) => {
|
|
3855
3989
|
try {
|
|
3856
|
-
|
|
3990
|
+
const served = listsOwnReportTool || ctx.annotationToolName === "" ? result : withToolInputSchema(result, ctx.annotationToolName, annotationInputJsonSchema(lowLevelMajor(lowLevel)));
|
|
3991
|
+
return advertiseIntentParamsRequired(served, names, isInjected);
|
|
3857
3992
|
} catch (err) {
|
|
3858
|
-
|
|
3859
|
-
`baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}
|
|
3860
|
-
`
|
|
3993
|
+
stderrLine(
|
|
3994
|
+
`baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}`
|
|
3861
3995
|
);
|
|
3862
3996
|
return result;
|
|
3863
3997
|
}
|
|
@@ -3867,6 +4001,177 @@ function installToolsListSeam(lowLevel, ctx) {
|
|
|
3867
4001
|
return isThenable(out) ? out.then(advertise) : advertise(out);
|
|
3868
4002
|
});
|
|
3869
4003
|
}
|
|
4004
|
+
var LOW_LEVEL_LIST_SEAM = /* @__PURE__ */ Symbol("batonLowLevelListSeam");
|
|
4005
|
+
var LOW_LEVEL_CALL_SEAM = /* @__PURE__ */ Symbol("batonLowLevelCallSeam");
|
|
4006
|
+
var LOW_LEVEL_HANDSHAKE_SEAM = /* @__PURE__ */ Symbol("batonLowLevelHandshakeSeam");
|
|
4007
|
+
function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce2, reportToolTaken) {
|
|
4008
|
+
let reportTool2 = annotationTool;
|
|
4009
|
+
const listedReportTool = reportTool2 && {
|
|
4010
|
+
name: reportTool2.name,
|
|
4011
|
+
description: reportTool2.description,
|
|
4012
|
+
inputSchema: annotationInputJsonSchema(lowLevelMajor(lowLevel))
|
|
4013
|
+
};
|
|
4014
|
+
const skipTool = (name, err) => {
|
|
4015
|
+
known.unread.add(name);
|
|
4016
|
+
warnOnce2(
|
|
4017
|
+
`tool-unread:${name}`,
|
|
4018
|
+
`baton: could not read tool ${JSON.stringify(name)}; its calls keep user_goal until Baton can read it: ${printable(err)}`
|
|
4019
|
+
);
|
|
4020
|
+
};
|
|
4021
|
+
const skipNote = (name, err) => {
|
|
4022
|
+
if (known.unread.has(name)) return;
|
|
4023
|
+
warnOnce2(`tool-unnoted:${name}`, `baton: could not note tool ${JSON.stringify(name)}; Baton adds no user_goal to it: ${printable(err)}`);
|
|
4024
|
+
};
|
|
4025
|
+
const keepGoalIfDeclared = (tools) => {
|
|
4026
|
+
for (const { name, inputSchema: inputSchema2 } of tools) {
|
|
4027
|
+
try {
|
|
4028
|
+
const checked = known.served.get(name)?.inputSchema === inputSchema2 && !known.unread.has(name);
|
|
4029
|
+
if (!known.keepsGoal.has(name) && !checked) {
|
|
4030
|
+
const declares = isRecord(inputSchema2) && takesUserGoalJson(inputSchema2) ? declaresParam : mayDeclareParam;
|
|
4031
|
+
if (declares(inputSchema2, USER_GOAL_PARAM_NAME)) known.keepsGoal.add(name);
|
|
4032
|
+
}
|
|
4033
|
+
known.unread.delete(name);
|
|
4034
|
+
} catch (err) {
|
|
4035
|
+
skipTool(name, err);
|
|
4036
|
+
}
|
|
4037
|
+
}
|
|
4038
|
+
};
|
|
4039
|
+
const read = (tools, { surface }) => {
|
|
4040
|
+
if (surface && reportTool2 !== void 0 && tools.some((tool) => tool.name === reportTool2?.name)) {
|
|
4041
|
+
warnOnce2(
|
|
4042
|
+
"report-tool-name-taken",
|
|
4043
|
+
`baton: the server lists its own tool ${JSON.stringify(reportTool2.name)}, so Baton's report tool is not added; set annotationToolName to another name`
|
|
4044
|
+
);
|
|
4045
|
+
reportTool2 = void 0;
|
|
4046
|
+
ctx.annotationToolName = "";
|
|
4047
|
+
reportToolTaken();
|
|
4048
|
+
}
|
|
4049
|
+
readToolList(tools, ctx, surface, skipNote);
|
|
4050
|
+
};
|
|
4051
|
+
const learn = (tools) => {
|
|
4052
|
+
keepGoalIfDeclared(tools);
|
|
4053
|
+
for (const tool of tools) {
|
|
4054
|
+
const held = known.served.get(tool.name);
|
|
4055
|
+
const ownGoal = (info) => declaresParam(info?.inputSchema, USER_GOAL_PARAM_NAME);
|
|
4056
|
+
if (held === void 0 || !ownGoal(held) || ownGoal(tool)) known.served.set(tool.name, tool);
|
|
4057
|
+
}
|
|
4058
|
+
};
|
|
4059
|
+
let caughtUp = false;
|
|
4060
|
+
const catchUp = () => {
|
|
4061
|
+
if (caughtUp) return;
|
|
4062
|
+
caughtUp = true;
|
|
4063
|
+
if (known.given !== void 0) {
|
|
4064
|
+
const given = known.given;
|
|
4065
|
+
known.given = void 0;
|
|
4066
|
+
try {
|
|
4067
|
+
const tools = typeof given === "function" ? given() : given;
|
|
4068
|
+
if (!Array.isArray(tools)) throw new Error("it is not an array of tools");
|
|
4069
|
+
known.givenTools = toolInfos(tools, skipTool);
|
|
4070
|
+
keepGoalIfDeclared(known.givenTools);
|
|
4071
|
+
} catch (err) {
|
|
4072
|
+
warnOnce2(
|
|
4073
|
+
"tools-unread",
|
|
4074
|
+
`baton: could not read the tools option; Baton learns the tools from tools/list: ${printable(err)}`
|
|
4075
|
+
);
|
|
4076
|
+
}
|
|
4077
|
+
}
|
|
4078
|
+
read(known.givenTools, { surface: true });
|
|
4079
|
+
read([...known.served.values()], { surface: false });
|
|
4080
|
+
};
|
|
4081
|
+
installRequestSeam(lowLevel, TOOLS_LIST_METHOD, LOW_LEVEL_LIST_SEAM, (handler) => async (...args) => {
|
|
4082
|
+
catchUp();
|
|
4083
|
+
const result = await handler(...args);
|
|
4084
|
+
try {
|
|
4085
|
+
const listed = listedTools(result);
|
|
4086
|
+
if (listed === null) return result;
|
|
4087
|
+
const tools = toolInfos(listed, skipTool);
|
|
4088
|
+
learn(tools);
|
|
4089
|
+
read(tools, { surface: true });
|
|
4090
|
+
const firstPage = args[0]?.params?.cursor === void 0;
|
|
4091
|
+
return servedToolList(result, listed, ctx, firstPage && reportTool2 ? listedReportTool : void 0);
|
|
4092
|
+
} catch (err) {
|
|
4093
|
+
stderrLine(`baton: tools/list capture failed; serving the vendor's own result: ${printable(err)}`);
|
|
4094
|
+
return result;
|
|
4095
|
+
}
|
|
4096
|
+
});
|
|
4097
|
+
const readFirst = (handler) => (...args) => {
|
|
4098
|
+
catchUp();
|
|
4099
|
+
return handler(...args);
|
|
4100
|
+
};
|
|
4101
|
+
installRequestSeam(lowLevel, "initialize", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);
|
|
4102
|
+
installRequestSeam(lowLevel, "server/discover", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);
|
|
4103
|
+
installRequestSeam(lowLevel, TOOLS_CALL_METHOD, LOW_LEVEL_CALL_SEAM, (handler) => async (...args) => {
|
|
4104
|
+
catchUp();
|
|
4105
|
+
ctx.perCaller?.followSettings();
|
|
4106
|
+
const request = args[0];
|
|
4107
|
+
const name = request?.params?.name;
|
|
4108
|
+
if (typeof name !== "string") return handler(...args);
|
|
4109
|
+
if (name === reportTool2?.name) return callAnnotationTool(reportTool2, request?.params?.arguments, args[1]);
|
|
4110
|
+
const injected = ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected";
|
|
4111
|
+
const unlisted = injected ? "warn" : known.keepsGoal.has(name) || known.unread.has(name) ? "leave" : "goalOnly";
|
|
4112
|
+
const params = request?.params?.arguments;
|
|
4113
|
+
const toolArgs = isRecord(params) ? params : {};
|
|
4114
|
+
if (unlisted === "goalOnly" && USER_GOAL_PARAM_NAME in toolArgs && !known.served.has(name) && !known.givenTools.some((tool) => tool.name === name)) {
|
|
4115
|
+
warnOnce2(
|
|
4116
|
+
"user-goal-unlisted",
|
|
4117
|
+
`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`
|
|
4118
|
+
);
|
|
4119
|
+
}
|
|
4120
|
+
if (request?.params?.task !== void 0) {
|
|
4121
|
+
if (injected) stripIntentParams(request.params, ctx);
|
|
4122
|
+
else extractGoalParam(toolArgs, USER_GOAL_PARAM_NAME, name, ctx.paramRegistry.get(name), unlisted);
|
|
4123
|
+
return handler(...args);
|
|
4124
|
+
}
|
|
4125
|
+
return batonWrap({ current: name }, () => handler(...args), ctx, unlisted)(toolArgs, args[1]);
|
|
4126
|
+
});
|
|
4127
|
+
}
|
|
4128
|
+
function lowLevelMajor(lowLevel) {
|
|
4129
|
+
return typeof lowLevel._wrapHandler === "function" ? 2 : 1;
|
|
4130
|
+
}
|
|
4131
|
+
function listedTools(result) {
|
|
4132
|
+
return isRecord(result) && Array.isArray(result.tools) ? result.tools : null;
|
|
4133
|
+
}
|
|
4134
|
+
function toolInfos(tools, skip) {
|
|
4135
|
+
const infos = [];
|
|
4136
|
+
for (const tool of tools) {
|
|
4137
|
+
let name;
|
|
4138
|
+
try {
|
|
4139
|
+
name = isRecord(tool) ? tool.name : void 0;
|
|
4140
|
+
if (typeof name !== "string") continue;
|
|
4141
|
+
infos.push({ name, description: tool.description, inputSchema: tool.inputSchema });
|
|
4142
|
+
} catch (err) {
|
|
4143
|
+
if (typeof name === "string") skip(name, err);
|
|
4144
|
+
}
|
|
4145
|
+
}
|
|
4146
|
+
return infos;
|
|
4147
|
+
}
|
|
4148
|
+
function readToolList(tools, ctx, surface, skip) {
|
|
4149
|
+
for (const { name, inputSchema: inputSchema2, description } of tools) {
|
|
4150
|
+
try {
|
|
4151
|
+
const schema = isRecord(inputSchema2) ? inputSchema2 : null;
|
|
4152
|
+
if (surface) {
|
|
4153
|
+
ctx.surfaceState.noteTool(name, schema ?? EMPTY_OBJECT_JSON_SCHEMA, typeof description === "string" ? description : void 0);
|
|
4154
|
+
}
|
|
4155
|
+
const dispositions = declaredIntentParams(schema);
|
|
4156
|
+
if (dispositions[USER_GOAL_PARAM_NAME] === "native") ctx.dropSubagentClause(name);
|
|
4157
|
+
else if (schema !== null && takesUserGoalJson(schema)) dispositions[USER_GOAL_PARAM_NAME] = "injected";
|
|
4158
|
+
if (Object.keys(dispositions).length > 0) ctx.paramRegistry.set(name, dispositions);
|
|
4159
|
+
else ctx.paramRegistry.delete(name);
|
|
4160
|
+
} catch (err) {
|
|
4161
|
+
ctx.paramRegistry.delete(name);
|
|
4162
|
+
skip(name, err);
|
|
4163
|
+
}
|
|
4164
|
+
}
|
|
4165
|
+
}
|
|
4166
|
+
function servedToolList(result, listed, ctx, reportTool2) {
|
|
4167
|
+
const tools = listed.map((tool) => {
|
|
4168
|
+
if (!isRecord(tool) || typeof tool.name !== "string") return tool;
|
|
4169
|
+
if (ctx.paramRegistry.get(tool.name)?.[USER_GOAL_PARAM_NAME] !== "injected") return tool;
|
|
4170
|
+
return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, ctx.intentParamMode, false) };
|
|
4171
|
+
});
|
|
4172
|
+
if (reportTool2 !== void 0) tools.push(reportTool2);
|
|
4173
|
+
return { ...result, tools };
|
|
4174
|
+
}
|
|
3870
4175
|
var LIFECYCLE_SEAMS = {
|
|
3871
4176
|
resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
|
|
3872
4177
|
resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
|
|
@@ -3945,8 +4250,7 @@ async function openLifecycleCall(ctx, spec, requestParams, extra) {
|
|
|
3945
4250
|
}
|
|
3946
4251
|
};
|
|
3947
4252
|
} catch (err) {
|
|
3948
|
-
|
|
3949
|
-
`);
|
|
4253
|
+
stderrLine(`baton: ${spec.method} capture failed: ${String(err)}`);
|
|
3950
4254
|
return null;
|
|
3951
4255
|
}
|
|
3952
4256
|
}
|
|
@@ -4122,8 +4426,7 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
|
4122
4426
|
await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
|
|
4123
4427
|
} catch (err) {
|
|
4124
4428
|
PROCESS_DROPS.add("encode_failed");
|
|
4125
|
-
|
|
4126
|
-
`);
|
|
4429
|
+
stderrLine(`baton: settling a tool call failed; events dropped: ${String(err)}`);
|
|
4127
4430
|
}
|
|
4128
4431
|
}
|
|
4129
4432
|
async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
@@ -4140,7 +4443,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
|
4140
4443
|
args[1],
|
|
4141
4444
|
params,
|
|
4142
4445
|
slot.stripped,
|
|
4143
|
-
entry != null
|
|
4446
|
+
entry != null ? "warn" : "quiet"
|
|
4144
4447
|
);
|
|
4145
4448
|
const failureKind = requestSideFailureKind(entry, slot.validation);
|
|
4146
4449
|
const text = () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result);
|
|
@@ -4314,27 +4617,34 @@ function createBaton(supplied = {}) {
|
|
|
4314
4617
|
function inertHandle(sink, sessionId) {
|
|
4315
4618
|
return new BatonHandle({ sink, sessionId, vendorId: "", annotationToolName: "" });
|
|
4316
4619
|
}
|
|
4317
|
-
function
|
|
4620
|
+
function serverShapeOf(server) {
|
|
4318
4621
|
const candidate = server;
|
|
4319
|
-
if (typeof candidate?.registerTool
|
|
4320
|
-
|
|
4321
|
-
"Baton needs a high-level McpServer (from @modelcontextprotocol/sdk/server/mcp.js or @modelcontextprotocol/server); the low-level Server is not supported."
|
|
4322
|
-
);
|
|
4622
|
+
if (typeof candidate?.registerTool === "function" && typeof candidate.server === "object" && candidate.server !== null) {
|
|
4623
|
+
return "mcpServer";
|
|
4323
4624
|
}
|
|
4625
|
+
const isServer = typeof candidate?._serverInfo === "object" && candidate._serverInfo !== null;
|
|
4626
|
+
if (typeof candidate?.setRequestHandler === "function" && candidate._requestHandlers instanceof Map && isServer) {
|
|
4627
|
+
return "lowLevel";
|
|
4628
|
+
}
|
|
4629
|
+
throw new TypeError(
|
|
4630
|
+
"Baton needs an McpServer or a low-level Server, from @modelcontextprotocol/sdk or @modelcontextprotocol/server."
|
|
4631
|
+
);
|
|
4324
4632
|
}
|
|
4325
4633
|
function newBatonState(config) {
|
|
4326
4634
|
return {
|
|
4327
4635
|
sentSurfaces: new SentSurfaces(),
|
|
4328
4636
|
warned: /* @__PURE__ */ new Set(),
|
|
4329
4637
|
counter: new SessionCounter(),
|
|
4330
|
-
scrubber: config.scrubber ?? new Scrubber().scrub
|
|
4638
|
+
scrubber: config.scrubber ?? new Scrubber().scrub,
|
|
4639
|
+
lowLevelTools: { given: config.tools, givenTools: [], served: /* @__PURE__ */ new Map(), keepsGoal: /* @__PURE__ */ new Set(), unread: /* @__PURE__ */ new Set() }
|
|
4331
4640
|
};
|
|
4332
4641
|
}
|
|
4333
|
-
function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber }, unconfigured) {
|
|
4334
|
-
|
|
4642
|
+
function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber, lowLevelTools }, unconfigured) {
|
|
4643
|
+
const shape = serverShapeOf(server);
|
|
4335
4644
|
const internals = server;
|
|
4645
|
+
const lowLevel = shape === "mcpServer" ? internals.server : server;
|
|
4336
4646
|
const serverName = usableServerName(() => ({
|
|
4337
|
-
name:
|
|
4647
|
+
name: lowLevel._serverInfo?.name,
|
|
4338
4648
|
className: internals.constructor.name
|
|
4339
4649
|
}));
|
|
4340
4650
|
const config = resolved.reportMode === "on" ? withServerDisplayName(resolved, supplied, serverName) : resolved;
|
|
@@ -4342,13 +4652,18 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4342
4652
|
const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
|
|
4343
4653
|
const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
|
|
4344
4654
|
if (unconfigured) return inertHandle(new DisabledSink(), "baton-unconfigured");
|
|
4655
|
+
if (shape === "mcpServer" && reports && internals._registeredTools?.[annotationToolName]) {
|
|
4656
|
+
throw new Error(
|
|
4657
|
+
`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.`
|
|
4658
|
+
);
|
|
4659
|
+
}
|
|
4345
4660
|
const given = config.sink ?? new StdoutSink();
|
|
4346
4661
|
const sink = offTheCall(given);
|
|
4347
4662
|
const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
|
|
4348
4663
|
const fallbackSessionId = `sdk-${uuid7()}`;
|
|
4349
4664
|
const counter2 = new ServerCounter(sharedCounter, fallbackSessionId);
|
|
4350
4665
|
const tenantId = resolveTenantId(config.tenantId, config.vendorId);
|
|
4351
|
-
const serverMeta = buildServerMeta(
|
|
4666
|
+
const serverMeta = buildServerMeta(lowLevel);
|
|
4352
4667
|
const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
|
|
4353
4668
|
const emitSurface = async (sessionId, digest, snapshot) => {
|
|
4354
4669
|
await emit(
|
|
@@ -4379,42 +4694,37 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4379
4694
|
const warnOnce2 = (key, message) => {
|
|
4380
4695
|
if (warned3.has(key)) return;
|
|
4381
4696
|
warned3.add(key);
|
|
4382
|
-
|
|
4697
|
+
stderrLine(message);
|
|
4383
4698
|
};
|
|
4384
4699
|
const dropSubagentClause = (name) => {
|
|
4385
|
-
const current2 =
|
|
4700
|
+
const current2 = lowLevel._instructions;
|
|
4386
4701
|
if (current2 === INTENT_INSTRUCTIONS) {
|
|
4387
|
-
|
|
4702
|
+
lowLevel._instructions = "";
|
|
4388
4703
|
} else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
|
|
4389
|
-
|
|
4704
|
+
lowLevel._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
|
|
4390
4705
|
} else {
|
|
4391
4706
|
return;
|
|
4392
4707
|
}
|
|
4393
4708
|
warnOnce2(
|
|
4394
4709
|
"native-user-goal",
|
|
4395
|
-
`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
|
|
4396
|
-
`
|
|
4710
|
+
`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`
|
|
4397
4711
|
);
|
|
4398
4712
|
};
|
|
4399
4713
|
const isV2Server = typeof internals.toolInputSchemaJson === "function";
|
|
4400
4714
|
const vendorToolJsonSchema = (name, inputSchema2) => {
|
|
4401
4715
|
if (isV2Server) {
|
|
4402
4716
|
try {
|
|
4403
|
-
const
|
|
4404
|
-
if (
|
|
4405
|
-
} catch {
|
|
4406
|
-
}
|
|
4407
|
-
try {
|
|
4408
|
-
const standard = inputSchema2?.["~standard"];
|
|
4409
|
-
const json = standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
|
|
4410
|
-
if (json) return json;
|
|
4717
|
+
const json2 = internals.toolInputSchemaJson(name);
|
|
4718
|
+
if (json2) return json2;
|
|
4411
4719
|
} catch {
|
|
4412
4720
|
}
|
|
4721
|
+
const json = standardInputJsonSchema(inputSchema2);
|
|
4722
|
+
if (json) return json;
|
|
4413
4723
|
}
|
|
4414
4724
|
try {
|
|
4415
4725
|
return toolInputJsonSchema(inputSchema2);
|
|
4416
4726
|
} catch {
|
|
4417
|
-
return
|
|
4727
|
+
return EMPTY_OBJECT_JSON_SCHEMA;
|
|
4418
4728
|
}
|
|
4419
4729
|
};
|
|
4420
4730
|
installValidationProbe(server);
|
|
@@ -4437,51 +4747,38 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4437
4747
|
vendorToolJsonSchema,
|
|
4438
4748
|
bustSchemaMemo,
|
|
4439
4749
|
dropSubagentClause,
|
|
4440
|
-
servedInstructions: () =>
|
|
4750
|
+
servedInstructions: () => lowLevel._instructions,
|
|
4441
4751
|
surfaceState,
|
|
4442
4752
|
emitSurface
|
|
4443
4753
|
};
|
|
4444
4754
|
const writeInstructions = (text) => {
|
|
4445
|
-
|
|
4446
|
-
|
|
4755
|
+
lowLevel._instructions = withVendorInstructions(
|
|
4756
|
+
lowLevel,
|
|
4447
4757
|
text,
|
|
4448
4758
|
(message) => warnOnce2("instructions-length", message)
|
|
4449
4759
|
);
|
|
4450
4760
|
};
|
|
4451
4761
|
writeInstructions(ours);
|
|
4762
|
+
const rewriteInstructions = (text) => {
|
|
4763
|
+
writeInstructions(text);
|
|
4764
|
+
const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === "native");
|
|
4765
|
+
if (native !== void 0) dropSubagentClause(native[0]);
|
|
4766
|
+
};
|
|
4452
4767
|
if (config.captureSettings !== void 0) {
|
|
4453
4768
|
ctx.perCaller = new PerCallerSurface({
|
|
4454
4769
|
settings: config.captureSettings,
|
|
4455
4770
|
intentParamMode,
|
|
4456
|
-
|
|
4457
|
-
|
|
4458
|
-
|
|
4459
|
-
writeInstructions(text);
|
|
4460
|
-
const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === "native");
|
|
4461
|
-
if (native !== void 0) dropSubagentClause(native[0]);
|
|
4771
|
+
// Read, not copied: a low-level Server's own tool can take the name.
|
|
4772
|
+
get annotationToolName() {
|
|
4773
|
+
return ctx.annotationToolName;
|
|
4462
4774
|
},
|
|
4775
|
+
instructions: ours,
|
|
4776
|
+
writeInstructions: rewriteInstructions,
|
|
4463
4777
|
injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
|
|
4464
4778
|
});
|
|
4465
4779
|
ctx.perCaller.followSettings();
|
|
4466
4780
|
}
|
|
4467
|
-
|
|
4468
|
-
installToolsCallSeam(
|
|
4469
|
-
internals.server,
|
|
4470
|
-
// ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
|
|
4471
|
-
// object, so `registry["constructor"]` answers `Object` and
|
|
4472
|
-
// `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
|
|
4473
|
-
// so the "a tool we did not wrap" guard would decline to report, and a
|
|
4474
|
-
// caller-visible `Tool constructor disabled` would reach the client with
|
|
4475
|
-
// this seam silent. An agent hallucinating a prototype-shaped tool name is
|
|
4476
|
-
// exactly the kind of failure the seam exists to make visible.
|
|
4477
|
-
(name) => {
|
|
4478
|
-
const registry = internals._registeredTools;
|
|
4479
|
-
return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
|
|
4480
|
-
},
|
|
4481
|
-
ctx
|
|
4482
|
-
);
|
|
4483
|
-
installLifecycleSeams(internals.server, ctx);
|
|
4484
|
-
const resolvedAnnotationToolName = !reports ? "" : registerAnnotationTool(server, {
|
|
4781
|
+
const annotationOptions = !reports ? void 0 : {
|
|
4485
4782
|
sink,
|
|
4486
4783
|
counter: ctx.counter,
|
|
4487
4784
|
tenantId: ctx.tenantId,
|
|
@@ -4496,7 +4793,43 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4496
4793
|
// raw override and letting the registration re-derive would register
|
|
4497
4794
|
// `srv-..._annotate` while the instructions name the server-derived one.
|
|
4498
4795
|
annotationToolName
|
|
4796
|
+
};
|
|
4797
|
+
if (shape === "lowLevel") {
|
|
4798
|
+
installLowLevelToolSeams(
|
|
4799
|
+
lowLevel,
|
|
4800
|
+
ctx,
|
|
4801
|
+
annotationOptions && buildAnnotationTool(server, annotationOptions),
|
|
4802
|
+
lowLevelTools,
|
|
4803
|
+
warnOnce2,
|
|
4804
|
+
() => rewriteInstructions(INTENT_INSTRUCTIONS)
|
|
4805
|
+
);
|
|
4806
|
+
}
|
|
4807
|
+
installToolsListSeam(lowLevel, ctx, shape === "lowLevel");
|
|
4808
|
+
if (shape === "mcpServer") installToolsCallSeam(
|
|
4809
|
+
lowLevel,
|
|
4810
|
+
// ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
|
|
4811
|
+
// object, so `registry["constructor"]` answers `Object` and
|
|
4812
|
+
// `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
|
|
4813
|
+
// so the "a tool we did not wrap" guard would decline to report, and a
|
|
4814
|
+
// caller-visible `Tool constructor disabled` would reach the client with
|
|
4815
|
+
// this seam silent. An agent hallucinating a prototype-shaped tool name is
|
|
4816
|
+
// exactly the kind of failure the seam exists to make visible.
|
|
4817
|
+
(name) => {
|
|
4818
|
+
const registry = internals._registeredTools;
|
|
4819
|
+
return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
|
|
4820
|
+
},
|
|
4821
|
+
ctx
|
|
4822
|
+
);
|
|
4823
|
+
installLifecycleSeams(lowLevel, ctx);
|
|
4824
|
+
const handle = (name) => new BatonHandle({
|
|
4825
|
+
sink: given,
|
|
4826
|
+
queue: sink,
|
|
4827
|
+
vendorId: config.vendorId,
|
|
4828
|
+
sessionId: fallbackSessionId,
|
|
4829
|
+
annotationToolName: name
|
|
4499
4830
|
});
|
|
4831
|
+
if (shape === "lowLevel") return handle(annotationToolName);
|
|
4832
|
+
const resolvedAnnotationToolName = annotationOptions ? registerAnnotationTool(server, annotationOptions) : "";
|
|
4500
4833
|
const existing = internals._registeredTools;
|
|
4501
4834
|
if (existing) {
|
|
4502
4835
|
for (const [name, entry] of Object.entries(existing)) {
|
|
@@ -4509,13 +4842,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4509
4842
|
wireEntry(String(args[0]), registered, ctx);
|
|
4510
4843
|
return registered;
|
|
4511
4844
|
};
|
|
4512
|
-
return
|
|
4513
|
-
sink: given,
|
|
4514
|
-
queue: sink,
|
|
4515
|
-
vendorId: config.vendorId,
|
|
4516
|
-
sessionId: fallbackSessionId,
|
|
4517
|
-
annotationToolName: resolvedAnnotationToolName
|
|
4518
|
-
});
|
|
4845
|
+
return handle(resolvedAnnotationToolName);
|
|
4519
4846
|
}
|
|
4520
4847
|
function reportsFor(config) {
|
|
4521
4848
|
if (config.reportMode !== "on") return void 0;
|
|
@@ -4523,9 +4850,8 @@ function reportsFor(config) {
|
|
|
4523
4850
|
}
|
|
4524
4851
|
function warnAboutSettings(config) {
|
|
4525
4852
|
if (config.reportMode !== "on" && config.annotationToolName !== void 0) {
|
|
4526
|
-
|
|
4527
|
-
`baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered
|
|
4528
|
-
`
|
|
4853
|
+
stderrLine(
|
|
4854
|
+
`baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered`
|
|
4529
4855
|
);
|
|
4530
4856
|
}
|
|
4531
4857
|
if (config.resultCaptureMode === WITHHELD) {
|
|
@@ -4567,7 +4893,7 @@ function principalFromOAuthEmail(context) {
|
|
|
4567
4893
|
}
|
|
4568
4894
|
|
|
4569
4895
|
// src/library/session.ts
|
|
4570
|
-
var
|
|
4896
|
+
var asyncHooks2 = __toESM(require("async_hooks"), 1);
|
|
4571
4897
|
var TRANSPORT_LIBRARY = "library";
|
|
4572
4898
|
var TURN_ID_META_KEY = "baton/turn_id";
|
|
4573
4899
|
function sessionEnvelope(session) {
|
|
@@ -4583,8 +4909,7 @@ function sessionEnvelope(session) {
|
|
|
4583
4909
|
};
|
|
4584
4910
|
}
|
|
4585
4911
|
function warn2(message) {
|
|
4586
|
-
|
|
4587
|
-
`);
|
|
4912
|
+
stderrLine(`baton: ${message}`);
|
|
4588
4913
|
}
|
|
4589
4914
|
function vendorId(name, value) {
|
|
4590
4915
|
const cleaned = typeof value === "string" ? stripWhiteSpace(value) : "";
|
|
@@ -4621,7 +4946,7 @@ function newSession(values, scrubber, disabled) {
|
|
|
4621
4946
|
runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
|
|
4622
4947
|
};
|
|
4623
4948
|
}
|
|
4624
|
-
var current = new
|
|
4949
|
+
var current = new asyncHooks2.AsyncLocalStorage();
|
|
4625
4950
|
function runInSession(owner, session, fn) {
|
|
4626
4951
|
return current.run({ owner, session }, fn);
|
|
4627
4952
|
}
|
|
@@ -4636,8 +4961,7 @@ function serveTools(tools, options) {
|
|
|
4636
4961
|
try {
|
|
4637
4962
|
served = tools.map(servedEntry);
|
|
4638
4963
|
} catch (err) {
|
|
4639
|
-
|
|
4640
|
-
`);
|
|
4964
|
+
stderrLine(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}`);
|
|
4641
4965
|
return { served: tools, surface: null };
|
|
4642
4966
|
}
|
|
4643
4967
|
try {
|
|
@@ -4656,8 +4980,7 @@ function serveTools(tools, options) {
|
|
|
4656
4980
|
);
|
|
4657
4981
|
return { served, surface: { surface, digest: surfaceHash(surface) } };
|
|
4658
4982
|
} catch (err) {
|
|
4659
|
-
|
|
4660
|
-
`);
|
|
4983
|
+
stderrLine(`baton: surface snapshot capture failed: ${printable(err)}`);
|
|
4661
4984
|
return { served, surface: null };
|
|
4662
4985
|
}
|
|
4663
4986
|
}
|
|
@@ -4675,25 +4998,8 @@ function snapshotPayload({ surface, digest }) {
|
|
|
4675
4998
|
};
|
|
4676
4999
|
}
|
|
4677
5000
|
function servedEntry(tool) {
|
|
4678
|
-
if (!isRecord(tool)) return tool;
|
|
4679
|
-
|
|
4680
|
-
if (isRecord(entry.inputSchema)) {
|
|
4681
|
-
const schema = { ...entry.inputSchema };
|
|
4682
|
-
if (isRecord(schema.properties)) schema.properties = { ...schema.properties };
|
|
4683
|
-
injectGoalParam(schema);
|
|
4684
|
-
entry.inputSchema = schema;
|
|
4685
|
-
}
|
|
4686
|
-
return entry;
|
|
4687
|
-
}
|
|
4688
|
-
function injectGoalParam(schema) {
|
|
4689
|
-
if (schema.properties === void 0) schema.properties = {};
|
|
4690
|
-
if (!isRecord(schema.properties) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return;
|
|
4691
|
-
schema.properties[USER_GOAL_PARAM_NAME] = {
|
|
4692
|
-
type: "string",
|
|
4693
|
-
description: buildUserGoalParamDescription({ intentParamMode: DEFAULT_INTENT_PARAM_MODE })
|
|
4694
|
-
};
|
|
4695
|
-
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
4696
|
-
if (!required.includes(USER_GOAL_PARAM_NAME)) schema.required = [...required, USER_GOAL_PARAM_NAME];
|
|
5001
|
+
if (!isRecord(tool) || !isRecord(tool.inputSchema)) return tool;
|
|
5002
|
+
return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, DEFAULT_INTENT_PARAM_MODE, true) };
|
|
4697
5003
|
}
|
|
4698
5004
|
|
|
4699
5005
|
// src/library/client.ts
|
|
@@ -4838,8 +5144,7 @@ var Core = class {
|
|
|
4838
5144
|
});
|
|
4839
5145
|
} catch (err) {
|
|
4840
5146
|
PROCESS_DROPS.add("encode_failed");
|
|
4841
|
-
|
|
4842
|
-
`);
|
|
5147
|
+
stderrLine(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}`);
|
|
4843
5148
|
return Promise.resolve();
|
|
4844
5149
|
}
|
|
4845
5150
|
return safeWrite(this.sink, event);
|
|
@@ -4897,7 +5202,7 @@ var Trace = class _Trace {
|
|
|
4897
5202
|
observed(result, failure) {
|
|
4898
5203
|
if ((this.#result !== UNSET || this.#error !== null) && !this.#observedWarned) {
|
|
4899
5204
|
this.#observedWarned = true;
|
|
4900
|
-
|
|
5205
|
+
stderrLine("baton: Trace.observed() called more than once; the last call wins.");
|
|
4901
5206
|
}
|
|
4902
5207
|
this.#result = UNSET;
|
|
4903
5208
|
this.#error = null;
|
|
@@ -4917,8 +5222,7 @@ var Trace = class _Trace {
|
|
|
4917
5222
|
try {
|
|
4918
5223
|
this.#result = this.#core.scrubber(result);
|
|
4919
5224
|
} catch (err) {
|
|
4920
|
-
|
|
4921
|
-
`);
|
|
5225
|
+
stderrLine(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}`);
|
|
4922
5226
|
this.#result = SCRUB_FAILED;
|
|
4923
5227
|
}
|
|
4924
5228
|
}
|
|
@@ -5064,8 +5368,7 @@ var Client = class {
|
|
|
5064
5368
|
try {
|
|
5065
5369
|
block = newSession(options, this.#core.scrubber, this.#core.disabled);
|
|
5066
5370
|
} catch (err) {
|
|
5067
|
-
|
|
5068
|
-
`);
|
|
5371
|
+
stderrLine(`baton: session values could not be read; using a minted session: ${printable(err)}`);
|
|
5069
5372
|
block = newSession({}, this.#core.scrubber, this.#core.disabled);
|
|
5070
5373
|
}
|
|
5071
5374
|
return runInSession(this, block, fn);
|