@goodtiming/baton-sdk 1.1.1 → 1.2.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 +1 -1
- package/dist/index.cjs +1453 -957
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +102 -1
- package/dist/index.d.ts +102 -1
- package/dist/index.js +1453 -957
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -53,7 +53,7 @@ __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.1";
|
|
57
57
|
|
|
58
58
|
// src/events.ts
|
|
59
59
|
var import_zod = require("zod");
|
|
@@ -186,7 +186,9 @@ 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(),
|
|
191
|
+
task: import_zod.z.string().optional()
|
|
190
192
|
}).strict();
|
|
191
193
|
var PrincipalWireSchema = import_zod.z.object({
|
|
192
194
|
id: import_zod.z.string(),
|
|
@@ -631,6 +633,11 @@ function stripEdges(value, space) {
|
|
|
631
633
|
function stripWhiteSpace(value) {
|
|
632
634
|
return stripEdges(value, WHITE_SPACE);
|
|
633
635
|
}
|
|
636
|
+
function stripWhiteSpaceEnd(value) {
|
|
637
|
+
let end = value.length;
|
|
638
|
+
while (end > 0 && WHITE_SPACE.test(value[end - 1])) end--;
|
|
639
|
+
return value.slice(0, end);
|
|
640
|
+
}
|
|
634
641
|
function isBlank(value) {
|
|
635
642
|
return ALL_WHITE_SPACE.test(value);
|
|
636
643
|
}
|
|
@@ -1794,6 +1801,122 @@ function roundMetaCoordinates(meta) {
|
|
|
1794
1801
|
return walk(meta, 0);
|
|
1795
1802
|
}
|
|
1796
1803
|
|
|
1804
|
+
// src/integrations/mcp/overlays.ts
|
|
1805
|
+
var INSTRUCTION_PIECES = ["instructions.subagent", "instructions.report_pointer"];
|
|
1806
|
+
var AUDIENCE_PIECES = ["goal_param.description", "report_tool.description", "report_tool.refusal"];
|
|
1807
|
+
var TEXT_CHANGES = ["append", "replace"];
|
|
1808
|
+
var FLAG_CHANGES = ["remove", "required"];
|
|
1809
|
+
var warned = /* @__PURE__ */ new Set();
|
|
1810
|
+
var unreadable = /* @__PURE__ */ new Set();
|
|
1811
|
+
function warnSkipped(overlayId, index, reason) {
|
|
1812
|
+
const key = JSON.stringify([overlayId, index]);
|
|
1813
|
+
if (warned.has(key)) return;
|
|
1814
|
+
warned.add(key);
|
|
1815
|
+
warn(`baton: overlay ${JSON.stringify(overlayId)} action ${index} is skipped: ${reason}`);
|
|
1816
|
+
}
|
|
1817
|
+
var Overlay = class {
|
|
1818
|
+
constructor(id, actions) {
|
|
1819
|
+
this.id = id;
|
|
1820
|
+
this.actions = actions;
|
|
1821
|
+
this.hiddenTools = new Set(
|
|
1822
|
+
actions.filter((a) => a.tool !== void 0 && a.param === void 0 && a.change === "remove").map((a) => a.tool)
|
|
1823
|
+
);
|
|
1824
|
+
}
|
|
1825
|
+
id;
|
|
1826
|
+
actions;
|
|
1827
|
+
hiddenTools;
|
|
1828
|
+
pieceActions(piece) {
|
|
1829
|
+
return this.actions.filter((a) => a.piece === piece);
|
|
1830
|
+
}
|
|
1831
|
+
instructionAppends() {
|
|
1832
|
+
return this.actions.filter((a) => a.instructions && a.text !== void 0).map((a) => a.text);
|
|
1833
|
+
}
|
|
1834
|
+
};
|
|
1835
|
+
function changedText(text, actions) {
|
|
1836
|
+
let source = "default";
|
|
1837
|
+
for (const action of actions) {
|
|
1838
|
+
if (action.change === "replace") {
|
|
1839
|
+
text = action.text;
|
|
1840
|
+
source = "replaced";
|
|
1841
|
+
} else if (action.change === "append" && action.text !== void 0) {
|
|
1842
|
+
const kept = stripWhiteSpaceEnd(text ?? "");
|
|
1843
|
+
text = kept ? `${kept}
|
|
1844
|
+
|
|
1845
|
+
${action.text}` : action.text;
|
|
1846
|
+
if (source === "default") source = "appended";
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
return { text, source };
|
|
1850
|
+
}
|
|
1851
|
+
function overlaid(text, overlay, piece) {
|
|
1852
|
+
if (overlay === void 0) return text;
|
|
1853
|
+
return changedText(text, overlay.pieceActions(piece)).text ?? text;
|
|
1854
|
+
}
|
|
1855
|
+
function readOverlays(value) {
|
|
1856
|
+
return isRecord(value) ? value : {};
|
|
1857
|
+
}
|
|
1858
|
+
function overlayFor(overlays, overlayId, place) {
|
|
1859
|
+
if (overlayId === void 0 || overlayId === null) return void 0;
|
|
1860
|
+
let id;
|
|
1861
|
+
let body;
|
|
1862
|
+
if (typeof overlayId === "string") {
|
|
1863
|
+
id = overlayId;
|
|
1864
|
+
body = Object.hasOwn(overlays, id) ? overlays[id] : void 0;
|
|
1865
|
+
} else {
|
|
1866
|
+
id = JSON.stringify(overlayId);
|
|
1867
|
+
}
|
|
1868
|
+
const actions = isRecord(body) ? body.actions : void 0;
|
|
1869
|
+
if (!Array.isArray(actions)) {
|
|
1870
|
+
if (!unreadable.has(id)) {
|
|
1871
|
+
unreadable.add(id);
|
|
1872
|
+
warn(`baton: overlay ${JSON.stringify(id)} cannot be read; none is applied there`);
|
|
1873
|
+
}
|
|
1874
|
+
return void 0;
|
|
1875
|
+
}
|
|
1876
|
+
const kept = [];
|
|
1877
|
+
actions.forEach((raw, index) => {
|
|
1878
|
+
const read = readAction(index, raw, place);
|
|
1879
|
+
if (typeof read === "string") warnSkipped(id, index, read);
|
|
1880
|
+
else kept.push(read);
|
|
1881
|
+
});
|
|
1882
|
+
return new Overlay(id, kept);
|
|
1883
|
+
}
|
|
1884
|
+
function readAction(index, raw, place) {
|
|
1885
|
+
if (!isRecord(raw) || !isRecord(raw.target)) return "it has no target";
|
|
1886
|
+
const target = raw.target;
|
|
1887
|
+
const changes = [...TEXT_CHANGES, ...FLAG_CHANGES].filter((c) => Object.hasOwn(raw, c));
|
|
1888
|
+
if (changes.length !== 1 || Object.keys(raw).length !== 2) return "it needs exactly one change";
|
|
1889
|
+
const change = changes[0];
|
|
1890
|
+
const value = raw[change];
|
|
1891
|
+
if (TEXT_CHANGES.includes(change) && typeof value !== "string") return `'${change}' needs text`;
|
|
1892
|
+
if (FLAG_CHANGES.includes(change) && value !== true) return `'${change}' must be true`;
|
|
1893
|
+
const text = typeof value === "string" ? { text: value } : {};
|
|
1894
|
+
const keys = Object.keys(target).sort().join(",");
|
|
1895
|
+
if (keys === "tool" && typeof target.tool === "string") {
|
|
1896
|
+
if (change === "required") return "only a param can be required";
|
|
1897
|
+
return placed({ index, change, ...text, tool: target.tool }, place, "audience");
|
|
1898
|
+
}
|
|
1899
|
+
if (keys === "param,tool" && typeof target.tool === "string" && typeof target.param === "string") {
|
|
1900
|
+
return placed({ index, change, ...text, tool: target.tool, param: target.param }, place, "audience");
|
|
1901
|
+
}
|
|
1902
|
+
if (keys === "instructions" && target.instructions === true) {
|
|
1903
|
+
if (change !== "append") return "the instructions take only 'append'";
|
|
1904
|
+
return placed({ index, change, ...text, instructions: true }, place, "server");
|
|
1905
|
+
}
|
|
1906
|
+
if (keys === "agent_text" && typeof target.agent_text === "string") {
|
|
1907
|
+
const piece = target.agent_text;
|
|
1908
|
+
if (!TEXT_CHANGES.includes(change)) return "agent_text takes only 'append' or 'replace'";
|
|
1909
|
+
if (INSTRUCTION_PIECES.includes(piece)) return placed({ index, change, ...text, piece }, place, "server");
|
|
1910
|
+
if (AUDIENCE_PIECES.includes(piece)) return placed({ index, change, ...text, piece }, place, "audience");
|
|
1911
|
+
return `unknown agent_text ${JSON.stringify(piece)}`;
|
|
1912
|
+
}
|
|
1913
|
+
return "unknown target";
|
|
1914
|
+
}
|
|
1915
|
+
function placed(action, place, allowed) {
|
|
1916
|
+
if (place === allowed) return action;
|
|
1917
|
+
return `this target goes only in ${allowed === "server" ? "server_overlay" : "an audience's overlay"}`;
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1797
1920
|
// src/integrations/mcp/llmText.ts
|
|
1798
1921
|
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.`;
|
|
1799
1922
|
var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
|
|
@@ -1809,14 +1932,14 @@ Fields:
|
|
|
1809
1932
|
- 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.`;
|
|
1810
1933
|
var CLAUDE_CODE_TRUNCATION_CAP = 2087;
|
|
1811
1934
|
var INSTRUCTIONS_LENGTH_CAP = 1500;
|
|
1812
|
-
function
|
|
1935
|
+
function buildReportPointer(options) {
|
|
1813
1936
|
return REPORT_POINTER_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
|
|
1814
1937
|
}
|
|
1815
1938
|
function fitsInstructionsCap(options) {
|
|
1816
|
-
return
|
|
1939
|
+
return buildReportPointer(options).length <= INSTRUCTIONS_LENGTH_CAP;
|
|
1817
1940
|
}
|
|
1818
1941
|
function buildServerInstructions(options) {
|
|
1819
|
-
const rendered =
|
|
1942
|
+
const rendered = buildReportPointer(options);
|
|
1820
1943
|
if (rendered.length > INSTRUCTIONS_LENGTH_CAP) {
|
|
1821
1944
|
throw new Error(
|
|
1822
1945
|
`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.`
|
|
@@ -1828,7 +1951,8 @@ function buildAnnotationToolDescription(options) {
|
|
|
1828
1951
|
return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
|
|
1829
1952
|
}
|
|
1830
1953
|
function buildRefusalText(options) {
|
|
1831
|
-
|
|
1954
|
+
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.`;
|
|
1955
|
+
return overlaid(text, options.overlay, "report_tool.refusal");
|
|
1832
1956
|
}
|
|
1833
1957
|
var USER_GOAL_PARAM_NAME = "user_goal";
|
|
1834
1958
|
var EXPECTED_RESULT_PARAM_NAME = "expected_result";
|
|
@@ -1876,37 +2000,47 @@ var INTENT_PARAMS = Object.freeze([
|
|
|
1876
2000
|
Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: "intent" })
|
|
1877
2001
|
]);
|
|
1878
2002
|
var VENDOR_INSTRUCTIONS = /* @__PURE__ */ Symbol("batonVendorInstructions");
|
|
1879
|
-
var
|
|
1880
|
-
var
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
new RegExp("^" + escapeRegExp(INTENT_INSTRUCTIONS))
|
|
1885
|
-
];
|
|
1886
|
-
function endsInOurs(current2, vendor) {
|
|
1887
|
-
if (typeof current2 !== "string") return false;
|
|
1888
|
-
const prefix = typeof vendor === "string" && !isBlank(vendor) ? `${vendor}
|
|
2003
|
+
var OURS = /* @__PURE__ */ Symbol("batonInstructions");
|
|
2004
|
+
var SUBAGENT = /* @__PURE__ */ Symbol("batonSubagentSentence");
|
|
2005
|
+
function joined(vendor, ours) {
|
|
2006
|
+
if (typeof vendor !== "string" || isBlank(vendor)) return ours;
|
|
2007
|
+
return ours ? `${vendor}
|
|
1889
2008
|
|
|
1890
|
-
` :
|
|
1891
|
-
if (!current2.startsWith(prefix)) return false;
|
|
1892
|
-
const rest = current2.slice(prefix.length);
|
|
1893
|
-
return OURS_STARTS.some((start) => start.test(rest));
|
|
2009
|
+
${ours}` : vendor;
|
|
1894
2010
|
}
|
|
1895
|
-
function
|
|
1896
|
-
const holder = server;
|
|
2011
|
+
function vendorText(holder) {
|
|
1897
2012
|
const current2 = holder._instructions;
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
2013
|
+
const written = holder[OURS];
|
|
2014
|
+
const vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
|
|
2015
|
+
return written !== void 0 && current2 === joined(vendor, written) ? vendor : current2;
|
|
2016
|
+
}
|
|
2017
|
+
function writeOurs(server, ours, subagent, write, warn3 = stderrLine) {
|
|
2018
|
+
const holder = server;
|
|
2019
|
+
const vendor = vendorText(holder);
|
|
2020
|
+
write(withVendorInstructions(server, ours, warn3));
|
|
2021
|
+
holder[VENDOR_INSTRUCTIONS] = vendor;
|
|
2022
|
+
holder[OURS] = ours;
|
|
2023
|
+
holder[SUBAGENT] = subagent && ours.endsWith(subagent) ? subagent : void 0;
|
|
2024
|
+
}
|
|
2025
|
+
function removeSubagentClause(server, write, warn3 = stderrLine) {
|
|
2026
|
+
const holder = server;
|
|
2027
|
+
const ours = holder[OURS];
|
|
2028
|
+
const subagent = holder[SUBAGENT];
|
|
2029
|
+
if (ours === void 0 || !subagent || holder._instructions !== joined(holder[VENDOR_INSTRUCTIONS], ours)) {
|
|
2030
|
+
return false;
|
|
1902
2031
|
}
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
2032
|
+
const kept = ours.slice(0, ours.length - subagent.length);
|
|
2033
|
+
writeOurs(server, kept.endsWith("\n\n") ? kept.slice(0, -2) : kept, null, write, warn3);
|
|
2034
|
+
return true;
|
|
2035
|
+
}
|
|
2036
|
+
function withVendorInstructions(server, ours, warn3 = stderrLine) {
|
|
2037
|
+
const vendor = vendorText(server);
|
|
2038
|
+
const combined = joined(vendor, ours);
|
|
2039
|
+
if (combined === ours) return ours;
|
|
2040
|
+
const vendorLength = vendor?.length ?? 0;
|
|
1907
2041
|
if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
|
|
1908
2042
|
warn3(
|
|
1909
|
-
`baton: the server instructions are ${combined.length} chars (yours ${
|
|
2043
|
+
`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`
|
|
1910
2044
|
);
|
|
1911
2045
|
}
|
|
1912
2046
|
return combined;
|
|
@@ -2164,998 +2298,1196 @@ function identityWire(id, stated, displayName, onUnregisteredForm) {
|
|
|
2164
2298
|
return wire;
|
|
2165
2299
|
}
|
|
2166
2300
|
|
|
2167
|
-
// src/integrations/mcp/
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
return
|
|
2301
|
+
// src/integrations/mcp/captureSettings.ts
|
|
2302
|
+
var crypto2 = __toESM(require("crypto"), 1);
|
|
2303
|
+
|
|
2304
|
+
// src/integrations/mcp/errorResult.ts
|
|
2305
|
+
var TOOL_ERROR_TYPE = "tool_error";
|
|
2306
|
+
var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
|
|
2307
|
+
var REFUSED = "refused";
|
|
2308
|
+
var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
|
|
2309
|
+
function requestSideFailureKind(entry, validation) {
|
|
2310
|
+
if (entry == null) return "unknown_tool";
|
|
2311
|
+
if (entry.enabled === false) return "tool_disabled";
|
|
2312
|
+
if (validation === "rejected") return "invalid_argument";
|
|
2313
|
+
if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
|
|
2314
|
+
return REFUSED;
|
|
2181
2315
|
}
|
|
2182
|
-
|
|
2316
|
+
var ERROR_BODY_MAX_CODE_POINTS = 2e3;
|
|
2317
|
+
function isErrorResult(value) {
|
|
2183
2318
|
try {
|
|
2184
|
-
|
|
2185
|
-
return
|
|
2319
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2320
|
+
return Boolean(value.isError);
|
|
2186
2321
|
} catch {
|
|
2187
|
-
return
|
|
2322
|
+
return false;
|
|
2188
2323
|
}
|
|
2189
2324
|
}
|
|
2190
|
-
function
|
|
2191
|
-
const
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
const
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
headers.append(name, item);
|
|
2201
|
-
} catch {
|
|
2202
|
-
}
|
|
2203
|
-
}
|
|
2325
|
+
function errorText(value) {
|
|
2326
|
+
const parts = [];
|
|
2327
|
+
try {
|
|
2328
|
+
const content = value?.content;
|
|
2329
|
+
if (!Array.isArray(content)) return "";
|
|
2330
|
+
for (const part of content) {
|
|
2331
|
+
const text = part?.text;
|
|
2332
|
+
if (typeof text !== "string") continue;
|
|
2333
|
+
const trimmed = stripWhiteSpace(text);
|
|
2334
|
+
if (trimmed) parts.push(trimmed);
|
|
2204
2335
|
}
|
|
2205
|
-
|
|
2336
|
+
} catch {
|
|
2337
|
+
return "";
|
|
2206
2338
|
}
|
|
2207
|
-
return
|
|
2339
|
+
return parts.join("\n");
|
|
2208
2340
|
}
|
|
2209
|
-
|
|
2210
|
-
|
|
2341
|
+
var RESULT_CAPTURE_MODES = ["full", "off"];
|
|
2342
|
+
var WITHHELD = "off";
|
|
2343
|
+
function endResultFields(mode, result, scrubber) {
|
|
2344
|
+
switch (mode) {
|
|
2345
|
+
case WITHHELD:
|
|
2346
|
+
return { result: null, result_capture: WITHHELD };
|
|
2347
|
+
case "full":
|
|
2348
|
+
return { result: scrubber(result) };
|
|
2349
|
+
}
|
|
2211
2350
|
}
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
function buildPrincipalResolutionContext(extra, toolName, args) {
|
|
2215
|
-
return {
|
|
2216
|
-
headers: extraHeaders(extra),
|
|
2217
|
-
meta: extraMeta(extra),
|
|
2218
|
-
toolName,
|
|
2219
|
-
arguments: args,
|
|
2220
|
-
authInfo: extraAuthInfo(extra)
|
|
2221
|
-
};
|
|
2351
|
+
function returnedErrorFields(mode, result, errorBody2, scrubber) {
|
|
2352
|
+
return resultDerivedFields(mode, () => errorText(result), result, errorBody2, scrubber);
|
|
2222
2353
|
}
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
);
|
|
2231
|
-
return null;
|
|
2354
|
+
function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
|
|
2355
|
+
switch (mode) {
|
|
2356
|
+
case WITHHELD:
|
|
2357
|
+
return { error_body: "", result: null, result_capture: WITHHELD };
|
|
2358
|
+
case "full":
|
|
2359
|
+
return { error_body: errorBody2(text()), result: scrubber(result) };
|
|
2360
|
+
}
|
|
2232
2361
|
}
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
if (warned.has(key)) return;
|
|
2236
|
-
warned.add(key);
|
|
2237
|
-
warn(`baton: resolvePrincipal ${message}`);
|
|
2362
|
+
function requestSideErrorFields(text, errorBody2) {
|
|
2363
|
+
return { error_body: errorBody2(text), result: null };
|
|
2238
2364
|
}
|
|
2239
|
-
function
|
|
2240
|
-
return
|
|
2241
|
-
principal: caller.principal,
|
|
2242
|
-
organization: caller.organization,
|
|
2243
|
-
labels: wireLabels(caller.labels),
|
|
2244
|
-
capture: caller.settings?.capture ?? null
|
|
2245
|
-
};
|
|
2365
|
+
function requestSideFailureFields(kind, mode, text, result, errorBody2, scrubber) {
|
|
2366
|
+
return kind === REFUSED ? resultDerivedFields(mode, text, result ?? null, errorBody2, scrubber) : requestSideErrorFields(text(), errorBody2);
|
|
2246
2367
|
}
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
const caller = await resolveIdentity(hook, call);
|
|
2250
|
-
if (settings === void 0) return caller;
|
|
2251
|
-
try {
|
|
2252
|
-
const callSettings = settings.forCaller({
|
|
2253
|
-
labels: caller.labels,
|
|
2254
|
-
clientName: client?.info?.name ?? null,
|
|
2255
|
-
shareKey: caller.principal?.id ?? null
|
|
2256
|
-
});
|
|
2257
|
-
return callSettings === void 0 ? caller : { ...caller, settings: callSettings };
|
|
2258
|
-
} catch {
|
|
2259
|
-
if (!settingsWarned) {
|
|
2260
|
-
settingsWarned = true;
|
|
2261
|
-
warn("baton: applying capture settings failed; this request uses the config's values");
|
|
2262
|
-
}
|
|
2263
|
-
return caller;
|
|
2264
|
-
}
|
|
2368
|
+
function errorTypeOf(err) {
|
|
2369
|
+
return err instanceof Error ? err.constructor.name : "Error";
|
|
2265
2370
|
}
|
|
2266
|
-
|
|
2267
|
-
|
|
2371
|
+
function messageOf(err) {
|
|
2372
|
+
return err instanceof Error ? err.message : String(err);
|
|
2373
|
+
}
|
|
2374
|
+
function scrubbedErrorBody(scrubber, text) {
|
|
2375
|
+
return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
|
|
2376
|
+
}
|
|
2377
|
+
|
|
2378
|
+
// src/integrations/mcp/captureSettings.ts
|
|
2379
|
+
var SETTINGS_PATH = "/v0/settings";
|
|
2380
|
+
var TENANT_HEADER = "X-Baton-Tenant-Id";
|
|
2381
|
+
var SETTINGS_MODES = ["local", "console"];
|
|
2382
|
+
var DEFAULT_SETTINGS_REFRESH_MS = 6e4;
|
|
2383
|
+
var MIN_SETTINGS_REFRESH_MS = 15e3;
|
|
2384
|
+
var REQUEST_TIMEOUT_MS = 1e4;
|
|
2385
|
+
var CANDIDATE_ENV = "BATON_CANDIDATE";
|
|
2386
|
+
var CANDIDATE_HEADER = "baton-candidate";
|
|
2387
|
+
var CANDIDATES_HELD = 32;
|
|
2388
|
+
var CANDIDATE_READS_AT_ONCE = 4;
|
|
2389
|
+
var CANDIDATE_START_TIMEOUT_MS = 5e3;
|
|
2390
|
+
var CANDIDATE_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
2391
|
+
var TASK_ENV = "BATON_TASK";
|
|
2392
|
+
var TASK_HEADER = "baton-task";
|
|
2393
|
+
var TASK_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
2394
|
+
function matchingId(pattern, value) {
|
|
2395
|
+
if (typeof value !== "string") return null;
|
|
2396
|
+
const id = stripWhiteSpace(value);
|
|
2397
|
+
return pattern.test(id) ? id : null;
|
|
2398
|
+
}
|
|
2399
|
+
function headerId(headers, name, parse) {
|
|
2268
2400
|
try {
|
|
2269
|
-
|
|
2270
|
-
const result = await withinHookBudget(hook(context));
|
|
2271
|
-
return callerFor(result, warnOnce);
|
|
2401
|
+
return parse(headers?.get(name));
|
|
2272
2402
|
} catch {
|
|
2273
|
-
return
|
|
2403
|
+
return null;
|
|
2274
2404
|
}
|
|
2275
2405
|
}
|
|
2276
|
-
|
|
2277
|
-
|
|
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;
|
|
2406
|
+
function candidateId(value) {
|
|
2407
|
+
return matchingId(CANDIDATE_ID, value);
|
|
2284
2408
|
}
|
|
2285
|
-
function
|
|
2286
|
-
|
|
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.");
|
|
2409
|
+
function headerCandidate(headers) {
|
|
2410
|
+
return headerId(headers, CANDIDATE_HEADER, candidateId);
|
|
2293
2411
|
}
|
|
2294
|
-
function
|
|
2295
|
-
|
|
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;
|
|
2412
|
+
function taskId(value) {
|
|
2413
|
+
return matchingId(TASK_ID, value);
|
|
2311
2414
|
}
|
|
2312
|
-
function
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2415
|
+
function headerTask(headers) {
|
|
2416
|
+
return headerId(headers, TASK_HEADER, taskId);
|
|
2417
|
+
}
|
|
2418
|
+
function envTask() {
|
|
2419
|
+
return taskId(typeof process !== "undefined" ? process.env?.[TASK_ENV] : void 0);
|
|
2420
|
+
}
|
|
2421
|
+
function envCandidate() {
|
|
2422
|
+
const value = typeof process !== "undefined" ? process.env?.[CANDIDATE_ENV] : void 0;
|
|
2423
|
+
if (!value) return null;
|
|
2424
|
+
const id = candidateId(value);
|
|
2425
|
+
if (id === null) warn(`baton: ${CANDIDATE_ENV} is not a change id; today's settings apply.`);
|
|
2426
|
+
return id;
|
|
2427
|
+
}
|
|
2428
|
+
function candidateNeedsConsole(settings) {
|
|
2429
|
+
if (settings !== "console" && envCandidate() !== null) {
|
|
2430
|
+
warn(
|
|
2431
|
+
`baton: ${CANDIDATE_ENV} is set, but this server's settings are not "console", so the change is not fetched; today's settings apply.`
|
|
2432
|
+
);
|
|
2330
2433
|
}
|
|
2331
|
-
return void 0;
|
|
2332
2434
|
}
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
}
|
|
2339
|
-
|
|
2340
|
-
|
|
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);
|
|
2435
|
+
var MATCH_KEYS = /* @__PURE__ */ new Set(["label", "client", "share"]);
|
|
2436
|
+
var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
|
|
2437
|
+
var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
|
|
2438
|
+
var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
|
|
2439
|
+
function shareBucket(vendorId2, key) {
|
|
2440
|
+
const digest = crypto2.createHash("sha256").update(`${vendorId2}
|
|
2441
|
+
${key}`, "utf-8").digest();
|
|
2442
|
+
return Number(digest.readBigUInt64BE(0) % 10000n);
|
|
2360
2443
|
}
|
|
2361
|
-
function
|
|
2362
|
-
|
|
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;
|
|
2444
|
+
function matchesEveryone(audience) {
|
|
2445
|
+
return audience.labels === null && audience.clients === null && audience.shareThreshold === null;
|
|
2369
2446
|
}
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
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 };
|
|
2447
|
+
function matches(audience, caller, bucket) {
|
|
2448
|
+
if (audience.labels !== null && !caller.labels.some((label) => audience.labels.has(label))) return false;
|
|
2449
|
+
if (audience.clients !== null && (caller.clientName === null || !audience.clients.has(caller.clientName))) {
|
|
2450
|
+
return false;
|
|
2451
|
+
}
|
|
2452
|
+
if (audience.shareThreshold !== null && (bucket === null || bucket >= audience.shareThreshold)) return false;
|
|
2453
|
+
return true;
|
|
2384
2454
|
}
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2455
|
+
var SettingsDocument = class {
|
|
2456
|
+
constructor(version, audiences, serverOverlay, candidate) {
|
|
2457
|
+
this.version = version;
|
|
2458
|
+
this.audiences = audiences;
|
|
2459
|
+
this.serverOverlay = serverOverlay;
|
|
2460
|
+
const overlays = audiences.flatMap((a) => a.settings.overlay === void 0 ? [] : [a.settings.overlay]);
|
|
2461
|
+
this.hiddenSomewhere = new Set(overlays.flatMap((o) => [...o.hiddenTools]));
|
|
2462
|
+
this.audiencePieces = new Set(overlays.flatMap((o) => o.actions.flatMap((a) => a.piece === void 0 ? [] : [a.piece])));
|
|
2463
|
+
this.usesShare = audiences.some((a) => a.shareThreshold !== null);
|
|
2464
|
+
this.unmatched = { capture: { settings_version: version, ...candidate === void 0 ? {} : { candidate } } };
|
|
2465
|
+
this.reportsOnForAnyone = audiences.some((a) => a.settings.reportMode !== "off") || !audiences.some(matchesEveryone);
|
|
2390
2466
|
}
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2467
|
+
version;
|
|
2468
|
+
audiences;
|
|
2469
|
+
serverOverlay;
|
|
2470
|
+
usesShare;
|
|
2471
|
+
unmatched;
|
|
2472
|
+
/** Whether some caller can get reports, so the instructions point to the
|
|
2473
|
+
* tool. Read only where the code's value is "on": no tool exists otherwise. */
|
|
2474
|
+
reportsOnForAnyone;
|
|
2475
|
+
/** The tools some audience's overlay hides. */
|
|
2476
|
+
hiddenSomewhere;
|
|
2477
|
+
/** The pieces of Baton's text some audience's overlay changes. */
|
|
2478
|
+
audiencePieces;
|
|
2479
|
+
settingsFor(caller, vendorId2) {
|
|
2480
|
+
const bucket = caller.shareKey !== null && this.usesShare ? shareBucket(vendorId2, caller.shareKey) : null;
|
|
2481
|
+
return this.audiences.find((audience) => matches(audience, caller, bucket))?.settings ?? this.unmatched;
|
|
2396
2482
|
}
|
|
2397
|
-
|
|
2483
|
+
};
|
|
2484
|
+
function stringSet(value) {
|
|
2485
|
+
if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) return null;
|
|
2486
|
+
return new Set(value);
|
|
2398
2487
|
}
|
|
2399
|
-
function
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2488
|
+
function readAudience(version, id, match, capture, overlay, candidate) {
|
|
2489
|
+
if (!Object.keys(match).every((key) => MATCH_KEYS.has(key))) return null;
|
|
2490
|
+
let labels = null;
|
|
2491
|
+
let clients = null;
|
|
2492
|
+
let shareThreshold = null;
|
|
2493
|
+
if (Object.hasOwn(match, "label") && (labels = stringSet(match.label)) === null) return null;
|
|
2494
|
+
if (Object.hasOwn(match, "client") && (clients = stringSet(match.client)) === null) return null;
|
|
2495
|
+
if (Object.hasOwn(match, "share")) {
|
|
2496
|
+
const share = match.share;
|
|
2497
|
+
if (typeof share !== "number" || !(share > 0 && share <= 1)) return null;
|
|
2498
|
+
shareThreshold = Math.floor(share * 1e4 + 0.5);
|
|
2404
2499
|
}
|
|
2405
|
-
const
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
}
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
const
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
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 };
|
|
2500
|
+
const settings = {
|
|
2501
|
+
capture: {
|
|
2502
|
+
settings_version: version,
|
|
2503
|
+
audience: id,
|
|
2504
|
+
...overlay === void 0 ? {} : { overlay: overlay.id },
|
|
2505
|
+
...candidate === void 0 ? {} : { candidate }
|
|
2506
|
+
}
|
|
2507
|
+
};
|
|
2508
|
+
if (overlay !== void 0) settings.overlay = overlay;
|
|
2509
|
+
const { results, goal, reports } = capture;
|
|
2510
|
+
if (typeof results === "string" && RESULT_CAPTURE_MODE_SET.has(results)) {
|
|
2511
|
+
settings.resultCaptureMode = results;
|
|
2512
|
+
}
|
|
2513
|
+
if (typeof goal === "string" && INTENT_PARAM_MODES.has(goal)) settings.intentParamMode = goal;
|
|
2514
|
+
if (typeof reports === "string" && REPORT_MODES.has(reports)) settings.reportMode = reports;
|
|
2515
|
+
return { settings, labels, clients, shareThreshold };
|
|
2438
2516
|
}
|
|
2439
|
-
function
|
|
2517
|
+
function parseDocument(body, candidate) {
|
|
2518
|
+
let data;
|
|
2440
2519
|
try {
|
|
2441
|
-
|
|
2442
|
-
return standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
|
|
2520
|
+
data = JSON.parse(body);
|
|
2443
2521
|
} catch {
|
|
2444
|
-
return
|
|
2522
|
+
return null;
|
|
2445
2523
|
}
|
|
2524
|
+
if (!isRecord(data)) return null;
|
|
2525
|
+
const { version, audiences } = data;
|
|
2526
|
+
if (typeof version !== "number" || !Number.isInteger(version) || version < 1) return null;
|
|
2527
|
+
if (!Array.isArray(audiences) || audiences.length === 0) return null;
|
|
2528
|
+
if (candidate !== void 0 && data.candidate !== candidate) return null;
|
|
2529
|
+
const overlays = readOverlays(data.overlays);
|
|
2530
|
+
const parsed = [];
|
|
2531
|
+
for (const audience of audiences) {
|
|
2532
|
+
if (!isRecord(audience)) return null;
|
|
2533
|
+
const { id, match, capture } = audience;
|
|
2534
|
+
if (typeof id !== "string" || !isRecord(match) || !isRecord(capture)) return null;
|
|
2535
|
+
const overlay = overlayFor(overlays, audience.overlay, "audience");
|
|
2536
|
+
const readable = readAudience(version, id, match, capture, overlay, candidate);
|
|
2537
|
+
if (readable !== null) parsed.push(readable);
|
|
2538
|
+
}
|
|
2539
|
+
return new SettingsDocument(version, parsed, overlayFor(overlays, data.server_overlay, "server"), candidate);
|
|
2446
2540
|
}
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2541
|
+
var SettingsFetcher = class {
|
|
2542
|
+
url;
|
|
2543
|
+
// `#`, not `private`, so logging a config shows no key: "logging the config shows no key".
|
|
2544
|
+
#headers;
|
|
2545
|
+
refreshMs;
|
|
2546
|
+
fetchImpl;
|
|
2547
|
+
etag = null;
|
|
2548
|
+
held = null;
|
|
2549
|
+
timer = null;
|
|
2550
|
+
reading = null;
|
|
2551
|
+
candidateReads = /* @__PURE__ */ new Set();
|
|
2552
|
+
warned = false;
|
|
2553
|
+
constructor(options) {
|
|
2554
|
+
this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
|
|
2555
|
+
this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
|
|
2556
|
+
this.refreshMs = options.refreshMs;
|
|
2557
|
+
this.fetchImpl = options.fetchImpl ?? globalFetch;
|
|
2558
|
+
}
|
|
2559
|
+
get document() {
|
|
2560
|
+
return this.held;
|
|
2561
|
+
}
|
|
2562
|
+
start() {
|
|
2563
|
+
if (this.timer !== null) return;
|
|
2564
|
+
this.timer = setInterval(() => void this.readOnce(), this.refreshMs);
|
|
2565
|
+
this.timer.unref?.();
|
|
2566
|
+
void this.readOnce();
|
|
2567
|
+
}
|
|
2568
|
+
stop() {
|
|
2569
|
+
if (this.timer !== null) clearInterval(this.timer);
|
|
2570
|
+
this.timer = null;
|
|
2571
|
+
this.reading?.abort();
|
|
2572
|
+
this.reading = null;
|
|
2573
|
+
for (const read of this.candidateReads) read.abort();
|
|
2574
|
+
}
|
|
2575
|
+
async fetchCandidate(candidate, timeoutMs) {
|
|
2576
|
+
const reading = new AbortController();
|
|
2577
|
+
const timeout = setTimeout(() => reading.abort(), timeoutMs);
|
|
2578
|
+
timeout.unref?.();
|
|
2579
|
+
this.candidateReads.add(reading);
|
|
2580
|
+
try {
|
|
2581
|
+
const url = `${this.url}&${new URLSearchParams({ candidate }).toString()}`;
|
|
2582
|
+
const response = await this.fetchImpl(url, {
|
|
2583
|
+
method: "GET",
|
|
2584
|
+
headers: this.#headers,
|
|
2585
|
+
redirect: "manual",
|
|
2586
|
+
signal: reading.signal
|
|
2587
|
+
});
|
|
2588
|
+
if (response.status !== 200) void response.body?.cancel().catch(() => void 0);
|
|
2589
|
+
if (response.status === 403) return { outcome: "refused" };
|
|
2590
|
+
if (response.status === 404) return { outcome: "unknown" };
|
|
2591
|
+
if (response.status === 200) {
|
|
2592
|
+
const document = parseDocument(await response.text(), candidate);
|
|
2593
|
+
if (document !== null) return { outcome: "loaded", document };
|
|
2594
|
+
}
|
|
2595
|
+
} catch {
|
|
2596
|
+
} finally {
|
|
2597
|
+
clearTimeout(timeout);
|
|
2598
|
+
this.candidateReads.delete(reading);
|
|
2599
|
+
}
|
|
2600
|
+
return { outcome: "failed" };
|
|
2601
|
+
}
|
|
2602
|
+
/** One request. Never rejects: a failure keeps what is held. */
|
|
2603
|
+
async readOnce() {
|
|
2604
|
+
if (this.reading !== null) return;
|
|
2605
|
+
const reading = new AbortController();
|
|
2606
|
+
this.reading = reading;
|
|
2607
|
+
const timeout = setTimeout(() => reading.abort(), REQUEST_TIMEOUT_MS);
|
|
2608
|
+
timeout.unref?.();
|
|
2609
|
+
try {
|
|
2610
|
+
await this.read(reading.signal);
|
|
2611
|
+
} catch {
|
|
2612
|
+
} finally {
|
|
2613
|
+
clearTimeout(timeout);
|
|
2614
|
+
if (this.reading === reading) this.reading = null;
|
|
2615
|
+
}
|
|
2616
|
+
}
|
|
2617
|
+
async read(signal) {
|
|
2618
|
+
const headers = this.etag === null ? this.#headers : { ...this.#headers, "If-None-Match": this.etag };
|
|
2619
|
+
const response = await this.fetchImpl(this.url, { method: "GET", headers, redirect: "manual", signal });
|
|
2620
|
+
if (response.status !== 200) {
|
|
2621
|
+
void response.body?.cancel().catch(() => void 0);
|
|
2622
|
+
}
|
|
2623
|
+
if (signal.aborted) return;
|
|
2624
|
+
if (response.status === 204) {
|
|
2625
|
+
this.held = null;
|
|
2626
|
+
this.etag = null;
|
|
2627
|
+
} else if (response.status === 200) {
|
|
2628
|
+
const document = parseDocument(await response.text());
|
|
2629
|
+
if (signal.aborted) return;
|
|
2630
|
+
if (document === null) {
|
|
2631
|
+
if (!this.warned) {
|
|
2632
|
+
this.warned = true;
|
|
2633
|
+
warn("baton: the collector sent capture settings this SDK cannot read");
|
|
2634
|
+
}
|
|
2635
|
+
return;
|
|
2636
|
+
}
|
|
2637
|
+
this.held = document;
|
|
2638
|
+
this.etag = response.headers.get("etag");
|
|
2639
|
+
}
|
|
2640
|
+
}
|
|
2641
|
+
};
|
|
2642
|
+
var PENDING = /* @__PURE__ */ Symbol("pending");
|
|
2643
|
+
var CaptureSettings = class {
|
|
2644
|
+
constructor(vendorId2, source, candidate = null, task = null, startTimeoutMs = CANDIDATE_START_TIMEOUT_MS) {
|
|
2645
|
+
this.vendorId = vendorId2;
|
|
2646
|
+
this.source = source;
|
|
2647
|
+
this.candidate = candidate;
|
|
2648
|
+
this.task = task;
|
|
2649
|
+
this.startTimeoutMs = startTimeoutMs;
|
|
2650
|
+
}
|
|
2651
|
+
vendorId;
|
|
2652
|
+
source;
|
|
2653
|
+
candidate;
|
|
2654
|
+
task;
|
|
2655
|
+
startTimeoutMs;
|
|
2656
|
+
processDocument = null;
|
|
2657
|
+
/** `BATON_CANDIDATE`'s read; requests wait for it. */
|
|
2658
|
+
ready = Promise.resolve();
|
|
2659
|
+
isReady = true;
|
|
2660
|
+
// id -> its document, `null` for an unknown id, `PENDING`, or the time a failed read may be tried again.
|
|
2661
|
+
held = /* @__PURE__ */ new Map();
|
|
2662
|
+
// A 403 is about the key, so it answers every id for this process.
|
|
2663
|
+
refused = false;
|
|
2664
|
+
stopped = false;
|
|
2665
|
+
retryAfterMs = REQUEST_TIMEOUT_MS;
|
|
2666
|
+
start() {
|
|
2667
|
+
const candidate = this.candidate;
|
|
2668
|
+
if (candidate !== null && this.processDocument === null) {
|
|
2669
|
+
const cannotLoad = (why) => warn(`baton: ${CANDIDATE_ENV}=${candidate} could not be loaded (${why}); today's settings apply.`);
|
|
2670
|
+
const fetched = this.source.fetchCandidate(candidate, this.startTimeoutMs);
|
|
2671
|
+
this.isReady = false;
|
|
2672
|
+
this.ready = raceDeadline(fetched, this.startTimeoutMs).then((read) => {
|
|
2673
|
+
this.isReady = true;
|
|
2674
|
+
if (this.stopped) return;
|
|
2675
|
+
if (read === TIMED_OUT) {
|
|
2676
|
+
cannotLoad("no answer");
|
|
2677
|
+
void fetched.then((late) => {
|
|
2678
|
+
if (!this.stopped && late.outcome === "refused") this.record(candidate, late);
|
|
2679
|
+
});
|
|
2680
|
+
return;
|
|
2681
|
+
}
|
|
2682
|
+
this.record(candidate, read);
|
|
2683
|
+
if (read.outcome === "loaded") this.processDocument = read.document;
|
|
2684
|
+
else if (read.outcome !== "refused") cannotLoad(read.outcome === "unknown" ? "unknown id" : "no answer");
|
|
2685
|
+
});
|
|
2468
2686
|
}
|
|
2469
|
-
|
|
2687
|
+
this.source.start();
|
|
2470
2688
|
}
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
|
|
2475
|
-
var OBSERVED_HEADERS = ["user-agent", "x-anthropic-client"];
|
|
2476
|
-
var CLIENT_INFO_MAX_LEN = 128;
|
|
2477
|
-
var HEADER_VALUE_MAX_LEN = 256;
|
|
2478
|
-
var hasText = (value) => typeof value === "string" && value !== "";
|
|
2479
|
-
function declared(info) {
|
|
2480
|
-
if (!info || typeof info !== "object") return void 0;
|
|
2481
|
-
const { name, version } = info;
|
|
2482
|
-
return hasText(name) || hasText(version) ? { name, version } : void 0;
|
|
2483
|
-
}
|
|
2484
|
-
function declaredOnRequest(extra) {
|
|
2485
|
-
for (const source of [extraEnvelope(extra), extraMeta(extra)]) {
|
|
2486
|
-
const found = declared(source?.[CLIENT_INFO_META_KEY]);
|
|
2487
|
-
if (found) return found;
|
|
2689
|
+
stop() {
|
|
2690
|
+
this.stopped = true;
|
|
2691
|
+
this.source.stop();
|
|
2488
2692
|
}
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
if (!server) return void 0;
|
|
2493
|
-
const inner = server.server;
|
|
2494
|
-
const holder = inner ?? server;
|
|
2495
|
-
if (typeof holder.getClientVersion !== "function") return void 0;
|
|
2496
|
-
return declared(holder.getClientVersion());
|
|
2497
|
-
}
|
|
2498
|
-
function observedInfo(extra, options) {
|
|
2499
|
-
return cleanInfo(declaredOnRequest(extra) ?? declaredOnConnection(options.server), options.scrubber);
|
|
2500
|
-
}
|
|
2501
|
-
function cleanInfo(sent, scrubber) {
|
|
2502
|
-
const info = {};
|
|
2503
|
-
const name = clean(sent?.name, scrubber, CLIENT_INFO_MAX_LEN);
|
|
2504
|
-
const version = clean(sent?.version, scrubber, CLIENT_INFO_MAX_LEN);
|
|
2505
|
-
if (name !== void 0) info.name = name;
|
|
2506
|
-
if (version !== void 0) info.version = version;
|
|
2507
|
-
return Object.keys(info).length > 0 ? info : void 0;
|
|
2508
|
-
}
|
|
2509
|
-
function cleanHeaders(sent, scrubber) {
|
|
2510
|
-
const headers = {};
|
|
2511
|
-
for (const header of OBSERVED_HEADERS) {
|
|
2512
|
-
const value = clean(sent?.get(header), scrubber, HEADER_VALUE_MAX_LEN);
|
|
2513
|
-
if (value !== void 0) headers[header] = value;
|
|
2693
|
+
/** The document for a request with no header of its own. */
|
|
2694
|
+
get document() {
|
|
2695
|
+
return this.processDocument ?? this.source.document;
|
|
2514
2696
|
}
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
}
|
|
2523
|
-
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
return
|
|
2697
|
+
/** `undefined` while no document is held, and the config's values apply. */
|
|
2698
|
+
forCaller(caller) {
|
|
2699
|
+
const document = caller.candidate == null ? this.document : this.headerDocument(caller.candidate) ?? this.source.document;
|
|
2700
|
+
const settings = document?.settingsFor(caller, this.vendorId);
|
|
2701
|
+
const task = caller.candidate == null ? this.task : caller.task;
|
|
2702
|
+
if (settings === void 0 || task == null || settings.capture.candidate === void 0) return settings;
|
|
2703
|
+
return { ...settings, capture: { ...settings.capture, task } };
|
|
2704
|
+
}
|
|
2705
|
+
/** Whether `test` holds for some document a request could be served under now. */
|
|
2706
|
+
someDocument(test) {
|
|
2707
|
+
const today = this.document;
|
|
2708
|
+
if (today !== null && test(today)) return true;
|
|
2709
|
+
for (const held of this.held.values()) if (held instanceof SettingsDocument && test(held)) return true;
|
|
2710
|
+
return false;
|
|
2528
2711
|
}
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2712
|
+
/** The header's change if it is held. The first sight of an id starts its
|
|
2713
|
+
* read in the background, unless too many are already running. */
|
|
2714
|
+
headerDocument(candidate) {
|
|
2715
|
+
if (this.refused) return null;
|
|
2716
|
+
const held = this.held.get(candidate);
|
|
2717
|
+
if (held !== void 0 && !(typeof held === "number" && held <= Date.now())) {
|
|
2718
|
+
this.held.delete(candidate);
|
|
2719
|
+
this.held.set(candidate, held);
|
|
2720
|
+
return held instanceof SettingsDocument ? held : null;
|
|
2721
|
+
}
|
|
2722
|
+
if ([...this.held.values()].filter((v) => v === PENDING).length >= CANDIDATE_READS_AT_ONCE) return null;
|
|
2723
|
+
this.held.delete(candidate);
|
|
2724
|
+
this.held.set(candidate, PENDING);
|
|
2725
|
+
this.evict();
|
|
2726
|
+
void this.source.fetchCandidate(candidate, REQUEST_TIMEOUT_MS).then((read) => {
|
|
2727
|
+
if (!this.stopped) this.record(candidate, read);
|
|
2728
|
+
});
|
|
2729
|
+
return null;
|
|
2544
2730
|
}
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2731
|
+
record(candidate, read) {
|
|
2732
|
+
if (read.outcome === "refused") {
|
|
2733
|
+
if (!this.refused) {
|
|
2734
|
+
warn("baton: this server's key is not a test key, so test changes are not fetched; today's settings apply.");
|
|
2735
|
+
}
|
|
2736
|
+
this.held.delete(candidate);
|
|
2737
|
+
this.refused = true;
|
|
2738
|
+
} else if (read.outcome === "failed") {
|
|
2739
|
+
this.held.set(candidate, Date.now() + this.retryAfterMs);
|
|
2740
|
+
} else {
|
|
2741
|
+
this.held.set(candidate, read.outcome === "loaded" ? read.document : null);
|
|
2742
|
+
this.evict();
|
|
2552
2743
|
}
|
|
2553
|
-
return out;
|
|
2554
2744
|
}
|
|
2555
|
-
|
|
2556
|
-
const
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
if (typeof line === "string") append(out, name, line);
|
|
2745
|
+
evict() {
|
|
2746
|
+
for (const [key, value] of this.held) {
|
|
2747
|
+
if (this.held.size <= CANDIDATES_HELD) return;
|
|
2748
|
+
if (value !== PENDING) this.held.delete(key);
|
|
2560
2749
|
}
|
|
2561
2750
|
}
|
|
2562
|
-
|
|
2751
|
+
};
|
|
2752
|
+
function overlayChanges(settings, piece) {
|
|
2753
|
+
return settings?.someDocument((d) => d.audiencePieces.has(piece)) ?? false;
|
|
2563
2754
|
}
|
|
2564
|
-
function
|
|
2565
|
-
return
|
|
2566
|
-
orNothing(() => cleanInfo(declared(meta?.[CLIENT_INFO_META_KEY]) ?? declared(clientInfo), scrubber)),
|
|
2567
|
-
orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
|
|
2568
|
-
);
|
|
2755
|
+
function mayHide(settings, name) {
|
|
2756
|
+
return settings?.someDocument((d) => d.hiddenSomewhere.has(name)) ?? false;
|
|
2569
2757
|
}
|
|
2570
2758
|
|
|
2571
|
-
// src/integrations/mcp/
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
}
|
|
2576
|
-
const fromHeader = sessionIdFromHeader(extra);
|
|
2577
|
-
if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed", perCall: false };
|
|
2578
|
-
if (observeTransport(extra) === "http") {
|
|
2579
|
-
return { sessionId: `sdk-${uuid7()}`, origin: "minted", perCall: true };
|
|
2580
|
-
}
|
|
2581
|
-
return { sessionId: fallbackSessionId, origin: "minted", perCall: false };
|
|
2759
|
+
// src/integrations/mcp/mcpTypes.ts
|
|
2760
|
+
function extraAuthInfo(extra) {
|
|
2761
|
+
const found = extra.authInfo ?? extra.http?.authInfo;
|
|
2762
|
+
return found !== null && typeof found === "object" ? found : null;
|
|
2582
2763
|
}
|
|
2583
|
-
function
|
|
2764
|
+
function extraMeta(extra) {
|
|
2765
|
+
const direct = extra._meta;
|
|
2766
|
+
if (direct) return direct;
|
|
2767
|
+
const nested = extra.mcpReq?._meta;
|
|
2768
|
+
return nested ?? null;
|
|
2769
|
+
}
|
|
2770
|
+
function extraEnvelope(extra) {
|
|
2771
|
+
const envelope = extra.mcpReq?.envelope;
|
|
2772
|
+
return envelope ?? null;
|
|
2773
|
+
}
|
|
2774
|
+
function observeTransport(extra) {
|
|
2584
2775
|
try {
|
|
2585
|
-
const
|
|
2586
|
-
return
|
|
2776
|
+
const carrier = extra.http?.req ?? extra.requestInfo;
|
|
2777
|
+
return carrier ? "http" : "no-http-request";
|
|
2587
2778
|
} catch {
|
|
2588
|
-
return
|
|
2779
|
+
return "read-failed";
|
|
2589
2780
|
}
|
|
2590
2781
|
}
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
}
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
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) {
|
|
2630
|
-
const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
|
|
2631
|
-
const description = buildAnnotationToolDescription({
|
|
2632
|
-
vendorDisplayName: options.vendorDisplayName
|
|
2633
|
-
});
|
|
2634
|
-
const refusal = buildRefusalText({ annotationToolName: name });
|
|
2635
|
-
return {
|
|
2636
|
-
name,
|
|
2637
|
-
description,
|
|
2638
|
-
handler: async (args, extra) => {
|
|
2639
|
-
const whatHappened = args.what_happened;
|
|
2640
|
-
if (!isReport(whatHappened)) {
|
|
2641
|
-
return {
|
|
2642
|
-
content: [
|
|
2643
|
-
{
|
|
2644
|
-
type: "text",
|
|
2645
|
-
text: JSON.stringify({
|
|
2646
|
-
ok: false,
|
|
2647
|
-
error: refusal
|
|
2648
|
-
})
|
|
2649
|
-
}
|
|
2650
|
-
]
|
|
2651
|
-
};
|
|
2652
|
-
}
|
|
2653
|
-
const reportedTool = args.tool_name ?? null;
|
|
2654
|
-
const meta = extraMeta(extra);
|
|
2655
|
-
const scrubbedMeta = scrubOrNull(
|
|
2656
|
-
options.scrubber,
|
|
2657
|
-
meta ? roundMetaCoordinates(meta) : null,
|
|
2658
|
-
"_meta"
|
|
2659
|
-
);
|
|
2660
|
-
const session = await resolveSessionId(options.fallbackSessionId, extra);
|
|
2661
|
-
const client = observeClient(extra, { server, scrubber: options.scrubber });
|
|
2662
|
-
const caller = await resolveCaller(
|
|
2663
|
-
options.resolvePrincipal,
|
|
2664
|
-
{ extra, toolName: name, arguments: args },
|
|
2665
|
-
options.captureSettings,
|
|
2666
|
-
client
|
|
2667
|
-
);
|
|
2668
|
-
await emit(
|
|
2669
|
-
options.sink,
|
|
2670
|
-
() => AnnotationEventSchema.parse({
|
|
2671
|
-
tenant_id: options.tenantId,
|
|
2672
|
-
vendor_id: options.vendorId,
|
|
2673
|
-
session_id: session.sessionId,
|
|
2674
|
-
sequence_number: options.counter.nextFor(session),
|
|
2675
|
-
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2676
|
-
consent_token: options.consentToken,
|
|
2677
|
-
...callerEnvelope(caller),
|
|
2678
|
-
transport_observed: observeTransport(extra),
|
|
2679
|
-
session_id_origin: session.origin,
|
|
2680
|
-
client_observed: client,
|
|
2681
|
-
runtime_meta: scrubbedMeta,
|
|
2682
|
-
payload: {
|
|
2683
|
-
// The agent-facing `user_goal` is stored as the wire key `intent`.
|
|
2684
|
-
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
2685
|
-
intent: options.scrubber(args.user_goal),
|
|
2686
|
-
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
2687
|
-
what_happened: options.scrubber(whatHappened),
|
|
2688
|
-
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
2689
|
-
tool_name: reportedTool ? options.scrubber(reportedTool) : reportedTool,
|
|
2690
|
-
suggested_improvement: args.suggested_improvement ? options.scrubber(args.suggested_improvement) : null,
|
|
2691
|
-
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
2692
|
-
context: args.context ? options.scrubber(args.context) : null
|
|
2693
|
-
}
|
|
2694
|
-
})
|
|
2695
|
-
);
|
|
2696
|
-
return { content: [{ type: "text", text: JSON.stringify({ ok: true }) }] };
|
|
2697
|
-
}
|
|
2698
|
-
};
|
|
2699
|
-
}
|
|
2700
|
-
|
|
2701
|
-
// src/dsn.ts
|
|
2702
|
-
var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
|
|
2703
|
-
var WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;
|
|
2704
|
-
var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
|
|
2705
|
-
var NOT_IN_A_KEY = /[\x00\t\n\r]/;
|
|
2706
|
-
var PUBLISHABLE_PREFIX = "baton_pk_";
|
|
2707
|
-
var SECRET_PREFIX = "baton_sk_";
|
|
2708
|
-
var KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;
|
|
2709
|
-
function looksLikeAKey(value) {
|
|
2710
|
-
return value.startsWith(PUBLISHABLE_PREFIX) || value.startsWith(SECRET_PREFIX);
|
|
2782
|
+
function extraHeaders(extra) {
|
|
2783
|
+
const fromV2 = extra.http?.req?.headers;
|
|
2784
|
+
if (fromV2 && typeof fromV2.get === "function") return fromV2;
|
|
2785
|
+
const fromV1 = extra.requestInfo?.headers;
|
|
2786
|
+
if (fromV1 && typeof fromV1 === "object") {
|
|
2787
|
+
const headers = new Headers();
|
|
2788
|
+
for (const [name, value] of Object.entries(fromV1)) {
|
|
2789
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
2790
|
+
if (typeof item !== "string") continue;
|
|
2791
|
+
try {
|
|
2792
|
+
headers.append(name, item);
|
|
2793
|
+
} catch {
|
|
2794
|
+
}
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2797
|
+
return headers;
|
|
2798
|
+
}
|
|
2799
|
+
return null;
|
|
2711
2800
|
}
|
|
2712
|
-
function
|
|
2713
|
-
return
|
|
2801
|
+
function isThenable(value) {
|
|
2802
|
+
return typeof value?.then === "function";
|
|
2714
2803
|
}
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
if (schemeEnd === -1) return null;
|
|
2719
|
-
const scheme = raw.slice(0, schemeEnd).toLowerCase();
|
|
2720
|
-
const rest = raw.slice(schemeEnd + 3);
|
|
2721
|
-
const end = rest.search(/[/?#]/);
|
|
2722
|
-
if (end === -1) return { scheme, netloc: rest, slash: "", path: "" };
|
|
2723
|
-
const netloc = rest.slice(0, end);
|
|
2724
|
-
if (rest[end] !== "/") {
|
|
2725
|
-
return { scheme, netloc, slash: "", path: "" };
|
|
2726
|
-
}
|
|
2727
|
-
const afterSlash = rest.slice(end + 1);
|
|
2728
|
-
const pathEnd = afterSlash.search(/[?#]/);
|
|
2804
|
+
|
|
2805
|
+
// src/integrations/mcp/principalResolution.ts
|
|
2806
|
+
function buildPrincipalResolutionContext(extra, toolName, args) {
|
|
2729
2807
|
return {
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2808
|
+
headers: extraHeaders(extra),
|
|
2809
|
+
meta: extraMeta(extra),
|
|
2810
|
+
toolName,
|
|
2811
|
+
arguments: args,
|
|
2812
|
+
authInfo: extraAuthInfo(extra)
|
|
2734
2813
|
};
|
|
2735
2814
|
}
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
if (
|
|
2815
|
+
var HOOK_TIMEOUT_MS = 5e3;
|
|
2816
|
+
async function withinHookBudget(answer) {
|
|
2817
|
+
if (!isThenable(answer)) return answer;
|
|
2818
|
+
const first = await raceDeadline(answer, HOOK_TIMEOUT_MS);
|
|
2819
|
+
if (first !== TIMED_OUT) return first;
|
|
2820
|
+
warn(
|
|
2821
|
+
`baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
|
|
2822
|
+
);
|
|
2823
|
+
return null;
|
|
2824
|
+
}
|
|
2825
|
+
var warned2 = /* @__PURE__ */ new Set();
|
|
2826
|
+
function warnOnce(key, message) {
|
|
2827
|
+
if (warned2.has(key)) return;
|
|
2828
|
+
warned2.add(key);
|
|
2829
|
+
warn(`baton: resolvePrincipal ${message}`);
|
|
2830
|
+
}
|
|
2831
|
+
function callerEnvelope(caller) {
|
|
2739
2832
|
return {
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2833
|
+
principal: caller.principal,
|
|
2834
|
+
organization: caller.organization,
|
|
2835
|
+
labels: wireLabels(caller.labels),
|
|
2836
|
+
capture: caller.settings?.capture ?? null
|
|
2743
2837
|
};
|
|
2744
2838
|
}
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2839
|
+
var settingsWarned = false;
|
|
2840
|
+
async function resolveCaller(hook, call, settings, client = null) {
|
|
2841
|
+
const caller = await resolveIdentity(hook, call);
|
|
2842
|
+
if (settings === void 0) return caller;
|
|
2843
|
+
try {
|
|
2844
|
+
const headers = extraHeaders(call.extra);
|
|
2845
|
+
const candidate = headerCandidate(headers);
|
|
2846
|
+
const callSettings = settings.forCaller({
|
|
2847
|
+
labels: caller.labels,
|
|
2848
|
+
clientName: client?.info?.name ?? null,
|
|
2849
|
+
shareKey: caller.principal?.id ?? null,
|
|
2850
|
+
candidate,
|
|
2851
|
+
task: candidate === null ? null : headerTask(headers)
|
|
2852
|
+
});
|
|
2853
|
+
return callSettings === void 0 ? caller : { ...caller, settings: callSettings };
|
|
2854
|
+
} catch {
|
|
2855
|
+
if (!settingsWarned) {
|
|
2856
|
+
settingsWarned = true;
|
|
2857
|
+
warn("baton: applying capture settings failed; this request uses the config's values");
|
|
2858
|
+
}
|
|
2859
|
+
return caller;
|
|
2860
|
+
}
|
|
2751
2861
|
}
|
|
2752
|
-
function
|
|
2753
|
-
|
|
2862
|
+
async function resolveIdentity(hook, call) {
|
|
2863
|
+
if (hook === void 0) return NO_CALLER;
|
|
2864
|
+
try {
|
|
2865
|
+
const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
|
|
2866
|
+
const result = await withinHookBudget(hook(context));
|
|
2867
|
+
return callerFor(result, warnOnce);
|
|
2868
|
+
} catch {
|
|
2869
|
+
return NO_CALLER;
|
|
2870
|
+
}
|
|
2754
2871
|
}
|
|
2755
|
-
|
|
2756
|
-
|
|
2872
|
+
|
|
2873
|
+
// src/integrations/mcp/zodCompat.ts
|
|
2874
|
+
var z3rt = __toESM(require("zod/v3"), 1);
|
|
2875
|
+
var z4mini = __toESM(require("zod/v4-mini"), 1);
|
|
2876
|
+
var import_zod_to_json_schema = require("zod-to-json-schema");
|
|
2877
|
+
function isZ4Schema(s) {
|
|
2878
|
+
const schema = s;
|
|
2879
|
+
return !!schema?._zod;
|
|
2757
2880
|
}
|
|
2758
|
-
function
|
|
2759
|
-
const
|
|
2760
|
-
|
|
2881
|
+
function objectFromShape(shape) {
|
|
2882
|
+
const values = Object.values(shape);
|
|
2883
|
+
if (values.length === 0) return z4mini.object({});
|
|
2884
|
+
const allV4 = values.every(isZ4Schema);
|
|
2885
|
+
const allV3 = values.every((s) => !isZ4Schema(s));
|
|
2886
|
+
if (allV4) return z4mini.object(shape);
|
|
2887
|
+
if (allV3) return z3rt.object(shape);
|
|
2888
|
+
throw new Error("Mixed Zod versions detected in object shape.");
|
|
2761
2889
|
}
|
|
2762
|
-
function
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
}
|
|
2770
|
-
return explicit;
|
|
2890
|
+
function getObjectShape(schema) {
|
|
2891
|
+
if (!schema) return void 0;
|
|
2892
|
+
let rawShape;
|
|
2893
|
+
if (isZ4Schema(schema)) {
|
|
2894
|
+
rawShape = schema._zod?.def?.shape;
|
|
2895
|
+
} else {
|
|
2896
|
+
rawShape = schema.shape;
|
|
2771
2897
|
}
|
|
2772
|
-
|
|
2773
|
-
if (
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2898
|
+
if (!rawShape) return void 0;
|
|
2899
|
+
if (typeof rawShape === "function") {
|
|
2900
|
+
try {
|
|
2901
|
+
return rawShape();
|
|
2902
|
+
} catch {
|
|
2903
|
+
return void 0;
|
|
2904
|
+
}
|
|
2779
2905
|
}
|
|
2780
|
-
return
|
|
2906
|
+
return rawShape;
|
|
2781
2907
|
}
|
|
2782
|
-
function
|
|
2783
|
-
|
|
2784
|
-
if (
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
);
|
|
2794
|
-
}
|
|
2795
|
-
const { key, at, authority } = splitKeyFromAuthority(parts.netloc);
|
|
2796
|
-
if (!at || !key) {
|
|
2797
|
-
if (looksLikeAKey(parts.netloc)) {
|
|
2798
|
-
fail(
|
|
2799
|
-
`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`
|
|
2800
|
-
);
|
|
2908
|
+
function normalizeObjectSchema(schema) {
|
|
2909
|
+
if (!schema) return void 0;
|
|
2910
|
+
if (typeof schema === "object") {
|
|
2911
|
+
const asAny = schema;
|
|
2912
|
+
if (!asAny._def && !asAny._zod) {
|
|
2913
|
+
const values = Object.values(schema);
|
|
2914
|
+
if (values.length > 0 && values.every(
|
|
2915
|
+
(v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function")
|
|
2916
|
+
)) {
|
|
2917
|
+
return objectFromShape(schema);
|
|
2918
|
+
}
|
|
2801
2919
|
}
|
|
2802
|
-
const misplaced = parts.path.split("/").some((segment) => containsKey(segment));
|
|
2803
|
-
const detail = misplaced ? "the key is in the PATH \u2014 it goes before an @" : "the value from /account has the key before an @";
|
|
2804
|
-
fail(
|
|
2805
|
-
`dsn ${safe} carries no key: ${detail}, as in https://baton_pk_...@host/ten_.../server`
|
|
2806
|
-
);
|
|
2807
2920
|
}
|
|
2808
|
-
if (
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2921
|
+
if (isZ4Schema(schema)) {
|
|
2922
|
+
const def = schema._zod?.def;
|
|
2923
|
+
if (def && (def.type === "object" || def.shape !== void 0)) return schema;
|
|
2924
|
+
} else {
|
|
2925
|
+
if (schema.shape !== void 0) return schema;
|
|
2812
2926
|
}
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
2927
|
+
return void 0;
|
|
2928
|
+
}
|
|
2929
|
+
function mapMiniTarget(t) {
|
|
2930
|
+
if (!t) return "draft-7";
|
|
2931
|
+
if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
|
|
2932
|
+
if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
|
|
2933
|
+
return "draft-7";
|
|
2934
|
+
}
|
|
2935
|
+
function toJsonSchemaCompat(schema, opts) {
|
|
2936
|
+
if (isZ4Schema(schema)) {
|
|
2937
|
+
return z4mini.toJSONSchema(schema, {
|
|
2938
|
+
target: mapMiniTarget(opts?.target),
|
|
2939
|
+
io: opts?.pipeStrategy ?? "input"
|
|
2940
|
+
});
|
|
2817
2941
|
}
|
|
2818
|
-
|
|
2819
|
-
|
|
2942
|
+
return (0, import_zod_to_json_schema.zodToJsonSchema)(schema, {
|
|
2943
|
+
strictUnions: opts?.strictUnions ?? true,
|
|
2944
|
+
pipeStrategy: opts?.pipeStrategy ?? "input"
|
|
2945
|
+
});
|
|
2946
|
+
}
|
|
2947
|
+
|
|
2948
|
+
// src/integrations/mcp/schemaCompat.ts
|
|
2949
|
+
var import_zod2 = require("zod");
|
|
2950
|
+
var import_v3 = require("zod/v3");
|
|
2951
|
+
var DEFAULT_INTENT_PARAM_MODE = "required";
|
|
2952
|
+
var ROOT_COMBINERS = ["$ref", "oneOf", "anyOf", "allOf"];
|
|
2953
|
+
function takesUserGoalJson(schema) {
|
|
2954
|
+
const properties = schema.properties ?? {};
|
|
2955
|
+
return isRecord(properties) && !ROOT_COMBINERS.some((key) => key in schema);
|
|
2956
|
+
}
|
|
2957
|
+
function withUserGoalJson(schema, intentParamMode, listRequired) {
|
|
2958
|
+
if (!takesUserGoalJson(schema) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return schema;
|
|
2959
|
+
const properties = schema.properties ?? {};
|
|
2960
|
+
const goal = { type: "string", description: buildUserGoalParamDescription({ intentParamMode }) };
|
|
2961
|
+
const served = { ...schema, properties: { ...properties, [USER_GOAL_PARAM_NAME]: goal } };
|
|
2962
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
2963
|
+
if (listRequired && !required.includes(USER_GOAL_PARAM_NAME)) served.required = [...required, USER_GOAL_PARAM_NAME];
|
|
2964
|
+
return served;
|
|
2965
|
+
}
|
|
2966
|
+
var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
|
|
2967
|
+
function injectGoalParams(inputSchema2, intentParamMode) {
|
|
2968
|
+
const objSchema = normalizeObjectSchema(inputSchema2);
|
|
2969
|
+
if (!objSchema) return { schema: inputSchema2, dispositions: {} };
|
|
2970
|
+
const existingShape = getObjectShape(objSchema) ?? {};
|
|
2971
|
+
const values = Object.values(existingShape);
|
|
2972
|
+
const useV4 = values.length === 0 || isZ4Schema(values[0]);
|
|
2973
|
+
const zodImpl = useV4 ? import_zod2.z : import_v3.z;
|
|
2974
|
+
const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
|
|
2975
|
+
if (Object.keys(toInject).length === 0)
|
|
2976
|
+
return { schema: inputSchema2, dispositions };
|
|
2977
|
+
const mergedShape = { ...existingShape, ...toInject };
|
|
2978
|
+
const newSchema = objectFromShape(mergedShape);
|
|
2979
|
+
return { schema: newSchema, dispositions };
|
|
2980
|
+
}
|
|
2981
|
+
function buildIntentFields(existingShape, zodImpl, intentParamMode) {
|
|
2982
|
+
const dispositions = {};
|
|
2983
|
+
const toInject = {};
|
|
2984
|
+
for (const name of RETIRED_PARAM_NAMES) {
|
|
2985
|
+
if (name in existingShape) dispositions[name] = "native";
|
|
2820
2986
|
}
|
|
2821
|
-
if (
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2987
|
+
if (USER_GOAL_PARAM_NAME in existingShape) {
|
|
2988
|
+
dispositions[USER_GOAL_PARAM_NAME] = "native";
|
|
2989
|
+
} else {
|
|
2990
|
+
dispositions[USER_GOAL_PARAM_NAME] = "injected";
|
|
2991
|
+
toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
|
|
2825
2992
|
}
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2993
|
+
return { dispositions, toInject };
|
|
2994
|
+
}
|
|
2995
|
+
function injectGoalParamsV2(inputSchema2, intentParamMode) {
|
|
2996
|
+
const candidate = inputSchema2;
|
|
2997
|
+
const shape = candidate?.shape;
|
|
2998
|
+
if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
|
|
2999
|
+
return { schema: inputSchema2, dispositions: {} };
|
|
2830
3000
|
}
|
|
2831
|
-
|
|
2832
|
-
|
|
3001
|
+
const { dispositions, toInject } = buildIntentFields(shape, import_zod2.z, intentParamMode);
|
|
3002
|
+
if (Object.keys(toInject).length === 0)
|
|
3003
|
+
return { schema: inputSchema2, dispositions };
|
|
3004
|
+
return { schema: candidate.extend(toInject), dispositions };
|
|
3005
|
+
}
|
|
3006
|
+
function advertiseIntentParamsRequired(result, names, isInjected) {
|
|
3007
|
+
const tools = result?.tools;
|
|
3008
|
+
if (!Array.isArray(tools)) return result;
|
|
3009
|
+
let changed = false;
|
|
3010
|
+
const advertised = tools.map((tool) => {
|
|
3011
|
+
const entry = tool;
|
|
3012
|
+
const toolName = entry?.name;
|
|
3013
|
+
if (typeof toolName !== "string") return tool;
|
|
3014
|
+
const schema = entry?.inputSchema;
|
|
3015
|
+
if (!schema || typeof schema !== "object") return tool;
|
|
3016
|
+
const declared2 = schema.required ?? [];
|
|
3017
|
+
if (!Array.isArray(declared2)) return tool;
|
|
3018
|
+
const required = declared2;
|
|
3019
|
+
const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
|
|
3020
|
+
if (missing.length === 0) return tool;
|
|
3021
|
+
changed = true;
|
|
3022
|
+
return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
|
|
3023
|
+
});
|
|
3024
|
+
return changed ? { ...result, tools: advertised } : result;
|
|
3025
|
+
}
|
|
3026
|
+
function withToolInputSchema(result, name, inputSchema2) {
|
|
3027
|
+
const tools = result?.tools;
|
|
3028
|
+
if (!Array.isArray(tools)) return result;
|
|
3029
|
+
const at = tools.findIndex((tool) => isRecord(tool) && tool.name === name);
|
|
3030
|
+
if (at === -1) return result;
|
|
3031
|
+
const served = [...tools];
|
|
3032
|
+
served[at] = { ...tools[at], inputSchema: inputSchema2 };
|
|
3033
|
+
return { ...result, tools: served };
|
|
3034
|
+
}
|
|
3035
|
+
function standardInputJsonSchema(schema) {
|
|
2833
3036
|
try {
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
if (parsedAuthority === null) {
|
|
2839
|
-
fail(`dsn ${safe} is not a parseable URL (${hostReason ?? "Error"})`);
|
|
2840
|
-
}
|
|
2841
|
-
const segments = parts.path.split("/").filter((segment) => segment !== "");
|
|
2842
|
-
const [workspace, server, ...extra] = segments;
|
|
2843
|
-
if (workspace === void 0 || server === void 0 || extra.length > 0) {
|
|
2844
|
-
fail(
|
|
2845
|
-
`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.`
|
|
2846
|
-
);
|
|
3037
|
+
const standard = schema?.["~standard"];
|
|
3038
|
+
return standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
|
|
3039
|
+
} catch {
|
|
3040
|
+
return void 0;
|
|
2847
3041
|
}
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
|
|
3042
|
+
}
|
|
3043
|
+
function toolInputJsonSchema(inputSchema2) {
|
|
3044
|
+
const objSchema = normalizeObjectSchema(inputSchema2);
|
|
3045
|
+
if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
|
|
3046
|
+
return toJsonSchemaCompat(objSchema, {
|
|
3047
|
+
strictUnions: true,
|
|
3048
|
+
pipeStrategy: "input"
|
|
3049
|
+
});
|
|
3050
|
+
}
|
|
3051
|
+
|
|
3052
|
+
// src/integrations/mcp/safeScrub.ts
|
|
3053
|
+
var warned3 = /* @__PURE__ */ new Set();
|
|
3054
|
+
function scrubOrNull(scrubber, value, field) {
|
|
3055
|
+
if (value === null) return null;
|
|
3056
|
+
try {
|
|
3057
|
+
return scrubber(value);
|
|
3058
|
+
} catch (err) {
|
|
3059
|
+
if (!warned3.has(field)) {
|
|
3060
|
+
warned3.add(field);
|
|
3061
|
+
stderrLine(
|
|
3062
|
+
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}`
|
|
2855
3063
|
);
|
|
2856
3064
|
}
|
|
3065
|
+
return null;
|
|
2857
3066
|
}
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
|
|
3067
|
+
}
|
|
3068
|
+
|
|
3069
|
+
// src/integrations/mcp/clientObserved.ts
|
|
3070
|
+
var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
|
|
3071
|
+
var OBSERVED_HEADERS = ["user-agent", "x-anthropic-client"];
|
|
3072
|
+
var CLIENT_INFO_MAX_LEN = 128;
|
|
3073
|
+
var HEADER_VALUE_MAX_LEN = 256;
|
|
3074
|
+
var hasText = (value) => typeof value === "string" && value !== "";
|
|
3075
|
+
function declared(info) {
|
|
3076
|
+
if (!info || typeof info !== "object") return void 0;
|
|
3077
|
+
const { name, version } = info;
|
|
3078
|
+
return hasText(name) || hasText(version) ? { name, version } : void 0;
|
|
3079
|
+
}
|
|
3080
|
+
function declaredOnRequest(extra) {
|
|
3081
|
+
for (const source of [extraEnvelope(extra), extraMeta(extra)]) {
|
|
3082
|
+
const found = declared(source?.[CLIENT_INFO_META_KEY]);
|
|
3083
|
+
if (found) return found;
|
|
2872
3084
|
}
|
|
2873
|
-
return
|
|
2874
|
-
origin: `${parts.scheme}://${authority}`,
|
|
2875
|
-
tenantId: workspace,
|
|
2876
|
-
vendorId: server,
|
|
2877
|
-
key
|
|
2878
|
-
});
|
|
3085
|
+
return void 0;
|
|
2879
3086
|
}
|
|
2880
|
-
function
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
};
|
|
2887
|
-
Object.defineProperty(dsn, "toJSON", {
|
|
2888
|
-
value: () => shown,
|
|
2889
|
-
enumerable: false
|
|
2890
|
-
});
|
|
2891
|
-
Object.defineProperty(dsn, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
|
|
2892
|
-
value: () => shown,
|
|
2893
|
-
enumerable: false
|
|
2894
|
-
});
|
|
2895
|
-
return dsn;
|
|
3087
|
+
function declaredOnConnection(server) {
|
|
3088
|
+
if (!server) return void 0;
|
|
3089
|
+
const inner = server.server;
|
|
3090
|
+
const holder = inner ?? server;
|
|
3091
|
+
if (typeof holder.getClientVersion !== "function") return void 0;
|
|
3092
|
+
return declared(holder.getClientVersion());
|
|
2896
3093
|
}
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
var TOOL_ERROR_TYPE = "tool_error";
|
|
2900
|
-
var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
|
|
2901
|
-
var REFUSED = "refused";
|
|
2902
|
-
var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
|
|
2903
|
-
function requestSideFailureKind(entry, validation) {
|
|
2904
|
-
if (entry == null) return "unknown_tool";
|
|
2905
|
-
if (entry.enabled === false) return "tool_disabled";
|
|
2906
|
-
if (validation === "rejected") return "invalid_argument";
|
|
2907
|
-
if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
|
|
2908
|
-
return REFUSED;
|
|
3094
|
+
function observedInfo(extra, options) {
|
|
3095
|
+
return cleanInfo(declaredOnRequest(extra) ?? declaredOnConnection(options.server), options.scrubber);
|
|
2909
3096
|
}
|
|
2910
|
-
|
|
2911
|
-
|
|
3097
|
+
function cleanInfo(sent, scrubber) {
|
|
3098
|
+
const info = {};
|
|
3099
|
+
const name = clean(sent?.name, scrubber, CLIENT_INFO_MAX_LEN);
|
|
3100
|
+
const version = clean(sent?.version, scrubber, CLIENT_INFO_MAX_LEN);
|
|
3101
|
+
if (name !== void 0) info.name = name;
|
|
3102
|
+
if (version !== void 0) info.version = version;
|
|
3103
|
+
return Object.keys(info).length > 0 ? info : void 0;
|
|
3104
|
+
}
|
|
3105
|
+
function cleanHeaders(sent, scrubber) {
|
|
3106
|
+
const headers = {};
|
|
3107
|
+
for (const header of OBSERVED_HEADERS) {
|
|
3108
|
+
const value = clean(sent?.get(header), scrubber, HEADER_VALUE_MAX_LEN);
|
|
3109
|
+
if (value !== void 0) headers[header] = value;
|
|
3110
|
+
}
|
|
3111
|
+
return Object.keys(headers).length > 0 ? headers : void 0;
|
|
3112
|
+
}
|
|
3113
|
+
function clean(value, scrubber, max) {
|
|
3114
|
+
if (!hasText(value)) return void 0;
|
|
3115
|
+
const scrubbed = scrubOrNull(scrubber, value, "client_observed");
|
|
3116
|
+
if (!hasText(scrubbed)) return void 0;
|
|
3117
|
+
return capCodePoints(scrubbed, max);
|
|
3118
|
+
}
|
|
3119
|
+
function orNothing(read) {
|
|
2912
3120
|
try {
|
|
2913
|
-
|
|
2914
|
-
return Boolean(value.isError);
|
|
3121
|
+
return read();
|
|
2915
3122
|
} catch {
|
|
2916
|
-
return
|
|
3123
|
+
return void 0;
|
|
2917
3124
|
}
|
|
2918
3125
|
}
|
|
2919
|
-
function
|
|
2920
|
-
|
|
3126
|
+
function assemble(info, headers) {
|
|
3127
|
+
if (info === void 0 && headers === void 0) return null;
|
|
3128
|
+
return { ...info && { info }, ...headers && { headers } };
|
|
3129
|
+
}
|
|
3130
|
+
function observeClient(extra, options) {
|
|
3131
|
+
return assemble(
|
|
3132
|
+
orNothing(() => observedInfo(extra, options)),
|
|
3133
|
+
orNothing(() => cleanHeaders(extraHeaders(extra), options.scrubber))
|
|
3134
|
+
);
|
|
3135
|
+
}
|
|
3136
|
+
function append(headers, name, value) {
|
|
2921
3137
|
try {
|
|
2922
|
-
|
|
2923
|
-
if (!Array.isArray(content)) return "";
|
|
2924
|
-
for (const part of content) {
|
|
2925
|
-
const text = part?.text;
|
|
2926
|
-
if (typeof text !== "string") continue;
|
|
2927
|
-
const trimmed = stripWhiteSpace(text);
|
|
2928
|
-
if (trimmed) parts.push(trimmed);
|
|
2929
|
-
}
|
|
3138
|
+
headers.append(name, value);
|
|
2930
3139
|
} catch {
|
|
2931
|
-
return "";
|
|
2932
3140
|
}
|
|
2933
|
-
return parts.join("\n");
|
|
2934
3141
|
}
|
|
2935
|
-
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
3142
|
+
function registeredHeaders(input) {
|
|
3143
|
+
const out = new Headers();
|
|
3144
|
+
if (typeof input.get === "function") {
|
|
3145
|
+
for (const name of OBSERVED_HEADERS) {
|
|
3146
|
+
const value = input.get(name);
|
|
3147
|
+
if (typeof value === "string") append(out, name, value);
|
|
3148
|
+
}
|
|
3149
|
+
return out;
|
|
3150
|
+
}
|
|
3151
|
+
for (const [key, value] of Object.entries(input)) {
|
|
3152
|
+
const name = key.toLowerCase();
|
|
3153
|
+
if (!OBSERVED_HEADERS.includes(name)) continue;
|
|
3154
|
+
for (const line of typeof value === "string" ? [value] : Array.isArray(value) ? value : []) {
|
|
3155
|
+
if (typeof line === "string") append(out, name, line);
|
|
3156
|
+
}
|
|
2943
3157
|
}
|
|
3158
|
+
return out;
|
|
3159
|
+
}
|
|
3160
|
+
function clientObservedFrom(clientInfo, headers, scrubber, meta) {
|
|
3161
|
+
return assemble(
|
|
3162
|
+
orNothing(() => cleanInfo(declared(meta?.[CLIENT_INFO_META_KEY]) ?? declared(clientInfo), scrubber)),
|
|
3163
|
+
orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
|
|
3164
|
+
);
|
|
2944
3165
|
}
|
|
2945
|
-
|
|
2946
|
-
|
|
3166
|
+
|
|
3167
|
+
// src/integrations/mcp/sessionResolution.ts
|
|
3168
|
+
async function resolveSessionId(fallbackSessionId, extra) {
|
|
3169
|
+
if (typeof extra.sessionId === "string" && extra.sessionId) {
|
|
3170
|
+
return { sessionId: extra.sessionId, origin: "observed", perCall: false };
|
|
3171
|
+
}
|
|
3172
|
+
const fromHeader = sessionIdFromHeader(extra);
|
|
3173
|
+
if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed", perCall: false };
|
|
3174
|
+
if (observeTransport(extra) === "http") {
|
|
3175
|
+
return { sessionId: `sdk-${uuid7()}`, origin: "minted", perCall: true };
|
|
3176
|
+
}
|
|
3177
|
+
return { sessionId: fallbackSessionId, origin: "minted", perCall: false };
|
|
2947
3178
|
}
|
|
2948
|
-
function
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
|
|
2953
|
-
|
|
3179
|
+
function sessionIdFromHeader(extra) {
|
|
3180
|
+
try {
|
|
3181
|
+
const value = extraHeaders(extra)?.get("mcp-session-id");
|
|
3182
|
+
return value ? stripWhiteSpace(value) || null : null;
|
|
3183
|
+
} catch {
|
|
3184
|
+
return null;
|
|
2954
3185
|
}
|
|
2955
3186
|
}
|
|
2956
|
-
|
|
2957
|
-
|
|
3187
|
+
|
|
3188
|
+
// src/integrations/mcp/annotation.ts
|
|
3189
|
+
var TOOL_NAME_PARAM_NAME = "tool_name";
|
|
3190
|
+
var ANNOTATION_INPUT_SHAPE = {
|
|
3191
|
+
user_goal: import_zod3.z.string(),
|
|
3192
|
+
what_happened: import_zod3.z.string().optional(),
|
|
3193
|
+
// Nullable so a report whose agent sends an explicit null is taken,
|
|
3194
|
+
// not rejected by validation.
|
|
3195
|
+
tool_name: import_zod3.z.string().nullable().optional(),
|
|
3196
|
+
suggested_improvement: import_zod3.z.string().optional(),
|
|
3197
|
+
// zod renders "any value" as `{}`, which some MCP clients refuse (reportToolSchema.test.ts).
|
|
3198
|
+
context: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).meta({ additionalProperties: true }).optional()
|
|
3199
|
+
};
|
|
3200
|
+
function isReport(whatHappened) {
|
|
3201
|
+
return typeof whatHappened === "string" && !isBlank(whatHappened);
|
|
2958
3202
|
}
|
|
2959
|
-
function
|
|
2960
|
-
|
|
3203
|
+
function registerAnnotationTool(server, options) {
|
|
3204
|
+
const tool = buildAnnotationTool(server, options);
|
|
3205
|
+
server.registerTool(
|
|
3206
|
+
tool.name,
|
|
3207
|
+
{ description: tool.description, inputSchema: ANNOTATION_INPUT_SHAPE },
|
|
3208
|
+
tool.handler
|
|
3209
|
+
);
|
|
3210
|
+
return tool.name;
|
|
2961
3211
|
}
|
|
2962
|
-
|
|
2963
|
-
|
|
3212
|
+
var ANNOTATION_ARGS = import_zod3.z.object(ANNOTATION_INPUT_SHAPE);
|
|
3213
|
+
function annotationInputJsonSchema(major) {
|
|
3214
|
+
return annotationJsonSchemas[major] ??= (major === 2 ? standardInputJsonSchema(ANNOTATION_ARGS) : void 0) ?? toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
|
|
2964
3215
|
}
|
|
2965
|
-
|
|
2966
|
-
|
|
3216
|
+
var annotationJsonSchemas = {};
|
|
3217
|
+
function callAnnotationTool(tool, args, extra) {
|
|
3218
|
+
const parsed = ANNOTATION_ARGS.safeParse(args ?? {});
|
|
3219
|
+
if (parsed.success) return tool.handler(parsed.data, extra);
|
|
3220
|
+
return Promise.resolve({
|
|
3221
|
+
content: [{ type: "text", text: `Invalid arguments for tool ${tool.name}: ${parsed.error.message}` }],
|
|
3222
|
+
isError: true
|
|
3223
|
+
});
|
|
2967
3224
|
}
|
|
2968
|
-
function
|
|
2969
|
-
|
|
3225
|
+
function buildAnnotationTool(server, options) {
|
|
3226
|
+
const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
|
|
3227
|
+
const description = buildAnnotationToolDescription({
|
|
3228
|
+
vendorDisplayName: options.vendorDisplayName
|
|
3229
|
+
});
|
|
3230
|
+
const refused = (overlay) => ({
|
|
3231
|
+
content: [
|
|
3232
|
+
{
|
|
3233
|
+
type: "text",
|
|
3234
|
+
text: JSON.stringify({ ok: false, error: buildRefusalText({ annotationToolName: name, overlay }) })
|
|
3235
|
+
}
|
|
3236
|
+
]
|
|
3237
|
+
});
|
|
3238
|
+
return {
|
|
3239
|
+
name,
|
|
3240
|
+
description,
|
|
3241
|
+
handler: async (args, extra) => {
|
|
3242
|
+
const whatHappened = args.what_happened;
|
|
3243
|
+
if (!isReport(whatHappened) && !overlayChanges(options.captureSettings, "report_tool.refusal")) return refused();
|
|
3244
|
+
const reportedTool = args.tool_name ?? null;
|
|
3245
|
+
const client = observeClient(extra, { server, scrubber: options.scrubber });
|
|
3246
|
+
const caller = await resolveCaller(
|
|
3247
|
+
options.resolvePrincipal,
|
|
3248
|
+
{ extra, toolName: name, arguments: args },
|
|
3249
|
+
options.captureSettings,
|
|
3250
|
+
client
|
|
3251
|
+
);
|
|
3252
|
+
if (!isReport(whatHappened)) return refused(caller.settings?.overlay);
|
|
3253
|
+
const meta = extraMeta(extra);
|
|
3254
|
+
const scrubbedMeta = scrubOrNull(
|
|
3255
|
+
options.scrubber,
|
|
3256
|
+
meta ? roundMetaCoordinates(meta) : null,
|
|
3257
|
+
"_meta"
|
|
3258
|
+
);
|
|
3259
|
+
const session = await resolveSessionId(options.fallbackSessionId, extra);
|
|
3260
|
+
await emit(
|
|
3261
|
+
options.sink,
|
|
3262
|
+
() => AnnotationEventSchema.parse({
|
|
3263
|
+
tenant_id: options.tenantId,
|
|
3264
|
+
vendor_id: options.vendorId,
|
|
3265
|
+
session_id: session.sessionId,
|
|
3266
|
+
sequence_number: options.counter.nextFor(session),
|
|
3267
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3268
|
+
consent_token: options.consentToken,
|
|
3269
|
+
...callerEnvelope(caller),
|
|
3270
|
+
transport_observed: observeTransport(extra),
|
|
3271
|
+
session_id_origin: session.origin,
|
|
3272
|
+
client_observed: client,
|
|
3273
|
+
runtime_meta: scrubbedMeta,
|
|
3274
|
+
payload: {
|
|
3275
|
+
// The agent-facing `user_goal` is stored as the wire key `intent`.
|
|
3276
|
+
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
3277
|
+
intent: options.scrubber(args.user_goal),
|
|
3278
|
+
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
3279
|
+
what_happened: options.scrubber(whatHappened),
|
|
3280
|
+
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
3281
|
+
tool_name: reportedTool ? options.scrubber(reportedTool) : reportedTool,
|
|
3282
|
+
suggested_improvement: args.suggested_improvement ? options.scrubber(args.suggested_improvement) : null,
|
|
3283
|
+
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
3284
|
+
context: args.context ? options.scrubber(args.context) : null
|
|
3285
|
+
}
|
|
3286
|
+
})
|
|
3287
|
+
);
|
|
3288
|
+
return { content: [{ type: "text", text: JSON.stringify({ ok: true }) }] };
|
|
3289
|
+
}
|
|
3290
|
+
};
|
|
2970
3291
|
}
|
|
2971
3292
|
|
|
2972
|
-
// src/
|
|
2973
|
-
var
|
|
2974
|
-
var
|
|
2975
|
-
var
|
|
2976
|
-
var
|
|
2977
|
-
var
|
|
2978
|
-
var
|
|
2979
|
-
var
|
|
2980
|
-
var
|
|
2981
|
-
var
|
|
2982
|
-
|
|
2983
|
-
|
|
2984
|
-
function shareBucket(vendorId2, key) {
|
|
2985
|
-
const digest = crypto2.createHash("sha256").update(`${vendorId2}
|
|
2986
|
-
${key}`, "utf-8").digest();
|
|
2987
|
-
return Number(digest.readBigUInt64BE(0) % 10000n);
|
|
3293
|
+
// src/dsn.ts
|
|
3294
|
+
var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
|
|
3295
|
+
var WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;
|
|
3296
|
+
var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
|
|
3297
|
+
var NOT_IN_A_KEY = /[\x00\t\n\r]/;
|
|
3298
|
+
var PUBLISHABLE_PREFIX = "baton_pk_";
|
|
3299
|
+
var SECRET_PREFIX = "baton_sk_";
|
|
3300
|
+
var TEST_PREFIX = "baton_tk_";
|
|
3301
|
+
var KEY_PREFIXES = [PUBLISHABLE_PREFIX, SECRET_PREFIX, TEST_PREFIX];
|
|
3302
|
+
var KEY_RUN = /baton_(?:(?:pk|sk|tk)_[A-Za-z0-9_%-]{8,}|[A-Za-z0-9_%-]{43,})/g;
|
|
3303
|
+
function looksLikeAKey(value) {
|
|
3304
|
+
return KEY_PREFIXES.some((prefix) => value.startsWith(prefix));
|
|
2988
3305
|
}
|
|
2989
|
-
function
|
|
2990
|
-
return
|
|
3306
|
+
function containsKey(value) {
|
|
3307
|
+
return sweep(value) !== value;
|
|
2991
3308
|
}
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
|
|
3309
|
+
var BARE_KEY_HINT = "this looks like a bare key, not a DSN \u2014 copy the full value from /account, which starts with https:// and ends with your server's name";
|
|
3310
|
+
function splitDsn(raw) {
|
|
3311
|
+
const schemeEnd = raw.indexOf("://");
|
|
3312
|
+
if (schemeEnd === -1) return null;
|
|
3313
|
+
const scheme = raw.slice(0, schemeEnd).toLowerCase();
|
|
3314
|
+
const rest = raw.slice(schemeEnd + 3);
|
|
3315
|
+
const end = rest.search(/[/?#]/);
|
|
3316
|
+
if (end === -1) return { scheme, netloc: rest, slash: "", path: "" };
|
|
3317
|
+
const netloc = rest.slice(0, end);
|
|
3318
|
+
if (rest[end] !== "/") {
|
|
3319
|
+
return { scheme, netloc, slash: "", path: "" };
|
|
2996
3320
|
}
|
|
2997
|
-
|
|
2998
|
-
|
|
3321
|
+
const afterSlash = rest.slice(end + 1);
|
|
3322
|
+
const pathEnd = afterSlash.search(/[?#]/);
|
|
3323
|
+
return {
|
|
3324
|
+
scheme,
|
|
3325
|
+
netloc,
|
|
3326
|
+
slash: "/",
|
|
3327
|
+
path: pathEnd === -1 ? afterSlash : afterSlash.slice(0, pathEnd)
|
|
3328
|
+
};
|
|
2999
3329
|
}
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
}
|
|
3008
|
-
version;
|
|
3009
|
-
audiences;
|
|
3010
|
-
usesShare;
|
|
3011
|
-
unmatched;
|
|
3012
|
-
/** Whether some caller can get reports, so the instructions point to the
|
|
3013
|
-
* tool. Read only where the code's value is "on": no tool exists otherwise. */
|
|
3014
|
-
reportsOnForAnyone;
|
|
3015
|
-
settingsFor(caller, vendorId2) {
|
|
3016
|
-
const bucket = caller.shareKey !== null && this.usesShare ? shareBucket(vendorId2, caller.shareKey) : null;
|
|
3017
|
-
return this.audiences.find((audience) => matches(audience, caller, bucket))?.settings ?? this.unmatched;
|
|
3018
|
-
}
|
|
3019
|
-
};
|
|
3020
|
-
function stringSet(value) {
|
|
3021
|
-
if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) return null;
|
|
3022
|
-
return new Set(value);
|
|
3330
|
+
function splitKeyFromAuthority(netloc) {
|
|
3331
|
+
const index = netloc.lastIndexOf("@");
|
|
3332
|
+
if (index === -1) return { key: "", at: false, authority: netloc };
|
|
3333
|
+
return {
|
|
3334
|
+
key: netloc.slice(0, index),
|
|
3335
|
+
at: true,
|
|
3336
|
+
authority: netloc.slice(index + 1)
|
|
3337
|
+
};
|
|
3023
3338
|
}
|
|
3024
|
-
function
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3339
|
+
function redact(raw) {
|
|
3340
|
+
const parts = splitDsn(raw);
|
|
3341
|
+
if (parts === null) return "<dsn>";
|
|
3342
|
+
const { at, authority } = splitKeyFromAuthority(parts.netloc);
|
|
3343
|
+
const assembled = at ? `${parts.scheme}://***@${authority}${parts.slash}${parts.path}` : `${parts.scheme}://<no key>@${parts.netloc}${parts.slash}${parts.path}`;
|
|
3344
|
+
return sweep(assembled);
|
|
3345
|
+
}
|
|
3346
|
+
function sweep(message) {
|
|
3347
|
+
return message.replace(KEY_RUN, "<key>");
|
|
3348
|
+
}
|
|
3349
|
+
function fail(message) {
|
|
3350
|
+
throw new Error(sweep(message));
|
|
3351
|
+
}
|
|
3352
|
+
function dsnFromEnvironment() {
|
|
3353
|
+
const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
|
|
3354
|
+
return fromEnv2 ? fromEnv2 : void 0;
|
|
3355
|
+
}
|
|
3356
|
+
function selectDsn(explicit, supplied, door) {
|
|
3357
|
+
const conflicts = Object.keys(supplied).filter((name) => supplied[name]).sort();
|
|
3358
|
+
if (explicit) {
|
|
3359
|
+
if (conflicts.length > 0) {
|
|
3360
|
+
fail(
|
|
3361
|
+
`${door} got both a dsn and an explicit ${conflicts[0]} \u2014 the dsn already supplies it. Drop one: the dsn is the single value from /account, and ${conflicts[0]} is what it unpacks to.`
|
|
3362
|
+
);
|
|
3363
|
+
}
|
|
3364
|
+
return explicit;
|
|
3035
3365
|
}
|
|
3036
|
-
const
|
|
3037
|
-
|
|
3038
|
-
if (
|
|
3039
|
-
|
|
3366
|
+
const ambient = dsnFromEnvironment();
|
|
3367
|
+
if (ambient === void 0) return void 0;
|
|
3368
|
+
if (conflicts.length > 0) {
|
|
3369
|
+
warn(
|
|
3370
|
+
`baton: BATON_DSN is set, but this ${door} supplies ${conflicts.join(", ")} directly, so BATON_DSN is being IGNORED and these events are NOT going to the collector it names. Remove the explicit value to use it, or unset BATON_DSN if it was meant for a different server.`
|
|
3371
|
+
);
|
|
3372
|
+
return void 0;
|
|
3040
3373
|
}
|
|
3041
|
-
|
|
3042
|
-
if (typeof reports === "string" && REPORT_MODES.has(reports)) settings.reportMode = reports;
|
|
3043
|
-
return { settings, labels, clients, shareThreshold };
|
|
3374
|
+
return ambient;
|
|
3044
3375
|
}
|
|
3045
|
-
function
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
|
|
3049
|
-
|
|
3050
|
-
return null;
|
|
3376
|
+
function parseDsn(raw) {
|
|
3377
|
+
const dsn = typeof raw === "string" ? stripWhiteSpace(raw) : "";
|
|
3378
|
+
if (dsn === "") fail("dsn must be a non-empty string");
|
|
3379
|
+
if (looksLikeAKey(dsn)) {
|
|
3380
|
+
fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
|
|
3051
3381
|
}
|
|
3052
|
-
|
|
3053
|
-
const
|
|
3054
|
-
if (
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
|
|
3058
|
-
if (!isRecord(audience)) return null;
|
|
3059
|
-
const { id, match, capture } = audience;
|
|
3060
|
-
if (typeof id !== "string" || !isRecord(match) || !isRecord(capture)) return null;
|
|
3061
|
-
const readable = readAudience(version, id, match, capture);
|
|
3062
|
-
if (readable !== null) parsed.push(readable);
|
|
3382
|
+
const safe = redact(dsn);
|
|
3383
|
+
const parts = splitDsn(dsn);
|
|
3384
|
+
if (parts === null || parts.scheme !== "https" && parts.scheme !== "http") {
|
|
3385
|
+
fail(
|
|
3386
|
+
`dsn ${safe} must start with https:// (or http:// for local development) \u2014 ${BARE_KEY_HINT}`
|
|
3387
|
+
);
|
|
3063
3388
|
}
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3071
|
-
|
|
3072
|
-
|
|
3073
|
-
|
|
3074
|
-
|
|
3075
|
-
|
|
3076
|
-
warned = false;
|
|
3077
|
-
constructor(options) {
|
|
3078
|
-
this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
|
|
3079
|
-
this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
|
|
3080
|
-
this.refreshMs = options.refreshMs;
|
|
3081
|
-
this.fetchImpl = options.fetchImpl ?? globalFetch;
|
|
3389
|
+
const { key, at, authority } = splitKeyFromAuthority(parts.netloc);
|
|
3390
|
+
if (!at || !key) {
|
|
3391
|
+
if (looksLikeAKey(parts.netloc)) {
|
|
3392
|
+
fail(
|
|
3393
|
+
`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`
|
|
3394
|
+
);
|
|
3395
|
+
}
|
|
3396
|
+
const misplaced = parts.path.split("/").some((segment) => containsKey(segment));
|
|
3397
|
+
const detail = misplaced ? "the key is in the PATH \u2014 it goes before an @" : "the value from /account has the key before an @";
|
|
3398
|
+
fail(
|
|
3399
|
+
`dsn ${safe} carries no key: ${detail}, as in https://baton_pk_...@host/ten_.../server`
|
|
3400
|
+
);
|
|
3082
3401
|
}
|
|
3083
|
-
|
|
3084
|
-
|
|
3402
|
+
if (NOT_IN_A_KEY.test(key)) {
|
|
3403
|
+
fail(
|
|
3404
|
+
`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.`
|
|
3405
|
+
);
|
|
3085
3406
|
}
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
|
|
3089
|
-
|
|
3090
|
-
void this.readOnce();
|
|
3407
|
+
if (key.includes(":")) {
|
|
3408
|
+
fail(
|
|
3409
|
+
`dsn ${safe} has a ':' in its key \u2014 a DSN carries one credential and no password field`
|
|
3410
|
+
);
|
|
3091
3411
|
}
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
this.timer = null;
|
|
3095
|
-
this.reading?.abort();
|
|
3096
|
-
this.reading = null;
|
|
3412
|
+
if (!authority) {
|
|
3413
|
+
fail(`dsn ${safe} has no host`);
|
|
3097
3414
|
}
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
this.reading = reading;
|
|
3103
|
-
const timeout = setTimeout(() => reading.abort(), REQUEST_TIMEOUT_MS);
|
|
3104
|
-
timeout.unref?.();
|
|
3105
|
-
try {
|
|
3106
|
-
await this.read(reading.signal);
|
|
3107
|
-
} catch {
|
|
3108
|
-
} finally {
|
|
3109
|
-
clearTimeout(timeout);
|
|
3110
|
-
if (this.reading === reading) this.reading = null;
|
|
3111
|
-
}
|
|
3415
|
+
if (containsKey(authority)) {
|
|
3416
|
+
fail(
|
|
3417
|
+
`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>`
|
|
3418
|
+
);
|
|
3112
3419
|
}
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
void response.body?.cancel().catch(() => void 0);
|
|
3118
|
-
}
|
|
3119
|
-
if (signal.aborted) return;
|
|
3120
|
-
if (response.status === 204) {
|
|
3121
|
-
this.held = null;
|
|
3122
|
-
this.etag = null;
|
|
3123
|
-
} else if (response.status === 200) {
|
|
3124
|
-
const document = parseDocument(await response.text());
|
|
3125
|
-
if (signal.aborted) return;
|
|
3126
|
-
if (document === null) {
|
|
3127
|
-
if (!this.warned) {
|
|
3128
|
-
this.warned = true;
|
|
3129
|
-
warn("baton: the collector sent capture settings this SDK cannot read");
|
|
3130
|
-
}
|
|
3131
|
-
return;
|
|
3132
|
-
}
|
|
3133
|
-
this.held = document;
|
|
3134
|
-
this.etag = response.headers.get("etag");
|
|
3135
|
-
}
|
|
3420
|
+
if (NOT_IN_A_HOST.test(authority)) {
|
|
3421
|
+
fail(
|
|
3422
|
+
`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.`
|
|
3423
|
+
);
|
|
3136
3424
|
}
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
|
|
3141
|
-
|
|
3425
|
+
let hostReason = null;
|
|
3426
|
+
let parsedAuthority = null;
|
|
3427
|
+
try {
|
|
3428
|
+
parsedAuthority = new URL(`${parts.scheme}://${authority}`);
|
|
3429
|
+
} catch (error) {
|
|
3430
|
+
hostReason = error instanceof Error ? error.constructor.name : "Error";
|
|
3142
3431
|
}
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
start() {
|
|
3146
|
-
this.source.start();
|
|
3432
|
+
if (parsedAuthority === null) {
|
|
3433
|
+
fail(`dsn ${safe} is not a parseable URL (${hostReason ?? "Error"})`);
|
|
3147
3434
|
}
|
|
3148
|
-
|
|
3149
|
-
|
|
3435
|
+
const segments = parts.path.split("/").filter((segment) => segment !== "");
|
|
3436
|
+
const [workspace, server, ...extra] = segments;
|
|
3437
|
+
if (workspace === void 0 || server === void 0 || extra.length > 0) {
|
|
3438
|
+
fail(
|
|
3439
|
+
`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.`
|
|
3440
|
+
);
|
|
3150
3441
|
}
|
|
3151
|
-
|
|
3152
|
-
|
|
3442
|
+
for (const [slot, segment] of [
|
|
3443
|
+
["workspace", workspace],
|
|
3444
|
+
["server", server]
|
|
3445
|
+
]) {
|
|
3446
|
+
if (containsKey(segment)) {
|
|
3447
|
+
fail(
|
|
3448
|
+
`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>`
|
|
3449
|
+
);
|
|
3450
|
+
}
|
|
3153
3451
|
}
|
|
3154
|
-
|
|
3155
|
-
|
|
3156
|
-
|
|
3452
|
+
if (!WORKSPACE_PATTERN.test(workspace)) {
|
|
3453
|
+
fail(
|
|
3454
|
+
`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.`
|
|
3455
|
+
);
|
|
3157
3456
|
}
|
|
3158
|
-
|
|
3457
|
+
if (!VENDOR_ID_PATTERN.test(server)) {
|
|
3458
|
+
fail(
|
|
3459
|
+
`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.`
|
|
3460
|
+
);
|
|
3461
|
+
}
|
|
3462
|
+
if (key.startsWith(SECRET_PREFIX)) {
|
|
3463
|
+
warn(
|
|
3464
|
+
`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.`
|
|
3465
|
+
);
|
|
3466
|
+
}
|
|
3467
|
+
return sealKey({
|
|
3468
|
+
origin: `${parts.scheme}://${authority}`,
|
|
3469
|
+
tenantId: workspace,
|
|
3470
|
+
vendorId: server,
|
|
3471
|
+
key
|
|
3472
|
+
});
|
|
3473
|
+
}
|
|
3474
|
+
function sealKey(dsn) {
|
|
3475
|
+
const shown = {
|
|
3476
|
+
origin: dsn.origin,
|
|
3477
|
+
tenantId: dsn.tenantId,
|
|
3478
|
+
vendorId: dsn.vendorId,
|
|
3479
|
+
key: "<key>"
|
|
3480
|
+
};
|
|
3481
|
+
Object.defineProperty(dsn, "toJSON", {
|
|
3482
|
+
value: () => shown,
|
|
3483
|
+
enumerable: false
|
|
3484
|
+
});
|
|
3485
|
+
Object.defineProperty(dsn, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
|
|
3486
|
+
value: () => shown,
|
|
3487
|
+
enumerable: false
|
|
3488
|
+
});
|
|
3489
|
+
return dsn;
|
|
3490
|
+
}
|
|
3159
3491
|
|
|
3160
3492
|
// src/integrations/mcp/config.ts
|
|
3161
3493
|
function resolveTenantId(explicit, vendorId2) {
|
|
@@ -3251,7 +3583,9 @@ function resolveBatonConfig(supplied) {
|
|
|
3251
3583
|
tenantId: dsn.tenantId,
|
|
3252
3584
|
vendorId: dsn.vendorId,
|
|
3253
3585
|
refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
|
|
3254
|
-
})
|
|
3586
|
+
}),
|
|
3587
|
+
envCandidate(),
|
|
3588
|
+
envTask()
|
|
3255
3589
|
)
|
|
3256
3590
|
} : {}
|
|
3257
3591
|
};
|
|
@@ -3424,51 +3758,148 @@ var BatonHandle = class {
|
|
|
3424
3758
|
};
|
|
3425
3759
|
|
|
3426
3760
|
// src/integrations/mcp/perCaller.ts
|
|
3761
|
+
var UNREAD = /* @__PURE__ */ Symbol("unread");
|
|
3427
3762
|
var PerCallerSurface = class {
|
|
3428
3763
|
constructor(options) {
|
|
3429
3764
|
this.options = options;
|
|
3430
3765
|
}
|
|
3431
3766
|
options;
|
|
3432
|
-
|
|
3767
|
+
document = UNREAD;
|
|
3768
|
+
served = null;
|
|
3769
|
+
serverOverlay;
|
|
3433
3770
|
/** Called at install and on every request; writes only when the report
|
|
3434
|
-
* pointer should change. */
|
|
3771
|
+
* pointer or the server overlay should change. */
|
|
3435
3772
|
followSettings() {
|
|
3436
|
-
if (this.options.annotationToolName === "") return;
|
|
3437
3773
|
try {
|
|
3438
3774
|
const document = this.options.settings.document;
|
|
3439
|
-
|
|
3440
|
-
|
|
3441
|
-
|
|
3442
|
-
|
|
3775
|
+
if (document === this.document) return;
|
|
3776
|
+
const overlay = document?.serverOverlay;
|
|
3777
|
+
const pointer = this.options.pointer();
|
|
3778
|
+
const pointerOn = pointer !== void 0 && (document === null || document.reportsOnForAnyone);
|
|
3779
|
+
const served = JSON.stringify([pointerOn, overlay?.id ?? null]);
|
|
3780
|
+
if (served !== this.served) {
|
|
3781
|
+
const { ours, subagent } = batonParagraphs(pointerOn ? pointer : void 0, overlay, this.options.subagentLine());
|
|
3782
|
+
this.options.writeInstructions(ours, subagent);
|
|
3783
|
+
this.served = served;
|
|
3784
|
+
this.serverOverlay = overlay;
|
|
3785
|
+
}
|
|
3786
|
+
this.document = document;
|
|
3443
3787
|
} catch (err) {
|
|
3444
3788
|
stderrLine(`baton: could not update the server instructions for new settings: ${printable(err)}`);
|
|
3445
3789
|
}
|
|
3446
3790
|
}
|
|
3447
|
-
/** `
|
|
3791
|
+
/** `followSettings` after the report pointer changed outside the settings. */
|
|
3792
|
+
refresh() {
|
|
3793
|
+
this.document = UNREAD;
|
|
3794
|
+
this.served = null;
|
|
3795
|
+
this.followSettings();
|
|
3796
|
+
}
|
|
3797
|
+
/** `result` with the caller's goal, reports and overlay; as served on any failure. */
|
|
3448
3798
|
toolsFor(result, caller) {
|
|
3449
3799
|
const settings = caller.settings;
|
|
3450
3800
|
if (settings === void 0) return result;
|
|
3451
3801
|
const { intentParamMode, annotationToolName, injectsGoal } = this.options;
|
|
3452
3802
|
const goal = settings.intentParamMode ?? intentParamMode;
|
|
3453
3803
|
const hideReports = annotationToolName !== "" && settings.reportMode === "off";
|
|
3454
|
-
|
|
3804
|
+
const overlay = settings.overlay;
|
|
3805
|
+
if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
|
|
3455
3806
|
try {
|
|
3456
3807
|
const tools = result?.tools;
|
|
3457
3808
|
if (!Array.isArray(tools)) return result;
|
|
3458
3809
|
const served = [];
|
|
3810
|
+
const injected = [];
|
|
3459
3811
|
for (const tool of tools) {
|
|
3460
3812
|
const name = tool?.name;
|
|
3461
3813
|
if (hideReports && name === annotationToolName) continue;
|
|
3462
|
-
const
|
|
3463
|
-
served.push(
|
|
3814
|
+
const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
|
|
3815
|
+
served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
|
|
3816
|
+
injected.push(ours);
|
|
3464
3817
|
}
|
|
3465
|
-
|
|
3818
|
+
const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
|
|
3819
|
+
return { ...result, tools: rewritten };
|
|
3466
3820
|
} catch (err) {
|
|
3467
3821
|
stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
|
|
3468
3822
|
return result;
|
|
3469
3823
|
}
|
|
3470
3824
|
}
|
|
3471
3825
|
};
|
|
3826
|
+
function batonParagraphs(pointer, overlay, subagentLine) {
|
|
3827
|
+
const parts = overlay?.instructionAppends() ?? [];
|
|
3828
|
+
if (pointer !== void 0) parts.push(overlaid(pointer, overlay, "instructions.report_pointer"));
|
|
3829
|
+
if (subagentLine) parts.push(overlaid(INTENT_INSTRUCTIONS, overlay, "instructions.subagent"));
|
|
3830
|
+
const kept = parts.map(stripWhiteSpaceEnd);
|
|
3831
|
+
return { ours: kept.filter((part) => part).join("\n\n"), subagent: subagentLine && kept.at(-1) || null };
|
|
3832
|
+
}
|
|
3833
|
+
function withOverlay(tools, injected, overlay, reportTool2) {
|
|
3834
|
+
const position = /* @__PURE__ */ new Map();
|
|
3835
|
+
tools.forEach((tool, i) => position.set(tool?.name, i));
|
|
3836
|
+
const hidden = /* @__PURE__ */ new Set();
|
|
3837
|
+
for (const action of overlay.actions) {
|
|
3838
|
+
if (action.tool === void 0) continue;
|
|
3839
|
+
const i = position.get(action.tool);
|
|
3840
|
+
if (i === void 0) {
|
|
3841
|
+
warnSkipped(overlay.id, action.index, `no tool is named ${JSON.stringify(action.tool)}`);
|
|
3842
|
+
} else if (action.tool === reportTool2) {
|
|
3843
|
+
warnSkipped(overlay.id, action.index, "the report tool takes agent_text targets only");
|
|
3844
|
+
} else if (action.param === void 0 && action.change === "remove") {
|
|
3845
|
+
hidden.add(i);
|
|
3846
|
+
} else if (action.param === void 0) {
|
|
3847
|
+
tools[i] = withDescription(tools[i], [action]);
|
|
3848
|
+
} else {
|
|
3849
|
+
const reason = paramChange(tools, i, action, injected[i]);
|
|
3850
|
+
if (reason !== void 0) warnSkipped(overlay.id, action.index, reason);
|
|
3851
|
+
}
|
|
3852
|
+
}
|
|
3853
|
+
const goalActions = overlay.pieceActions("goal_param.description");
|
|
3854
|
+
if (goalActions.length > 0) {
|
|
3855
|
+
injected.forEach((ours, i) => {
|
|
3856
|
+
if (ours) describeParam(tools, i, USER_GOAL_PARAM_NAME, goalActions);
|
|
3857
|
+
});
|
|
3858
|
+
}
|
|
3859
|
+
const reportActions = overlay.pieceActions("report_tool.description");
|
|
3860
|
+
const reportAt = reportTool2 === void 0 ? void 0 : position.get(reportTool2);
|
|
3861
|
+
if (reportActions.length > 0 && reportAt !== void 0) {
|
|
3862
|
+
tools[reportAt] = withDescription(tools[reportAt], reportActions);
|
|
3863
|
+
}
|
|
3864
|
+
return tools.filter((_, i) => !hidden.has(i));
|
|
3865
|
+
}
|
|
3866
|
+
function withDescription(tool, actions) {
|
|
3867
|
+
const description = typeof tool.description === "string" ? tool.description : void 0;
|
|
3868
|
+
return { ...tool, description: changedText(description, actions).text };
|
|
3869
|
+
}
|
|
3870
|
+
function paramChange(tools, i, action, injected) {
|
|
3871
|
+
const param = action.param;
|
|
3872
|
+
const tool = tools[i];
|
|
3873
|
+
const schema = tool.inputSchema;
|
|
3874
|
+
const properties = isRecord(schema) && isRecord(schema.properties) ? schema.properties : void 0;
|
|
3875
|
+
if (properties === void 0 || !Object.hasOwn(properties, param)) {
|
|
3876
|
+
return `${JSON.stringify(action.tool)} has no param ${JSON.stringify(param)}`;
|
|
3877
|
+
}
|
|
3878
|
+
if (injected && param === USER_GOAL_PARAM_NAME) return "Baton's user_goal takes the goal_param.description target";
|
|
3879
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
3880
|
+
if (action.change === "remove") {
|
|
3881
|
+
if (required.includes(param)) return `${JSON.stringify(action.tool)} requires ${JSON.stringify(param)}`;
|
|
3882
|
+
const kept = Object.fromEntries(Object.entries(properties).filter(([name]) => name !== param));
|
|
3883
|
+
tools[i] = { ...tool, inputSchema: { ...schema, properties: kept } };
|
|
3884
|
+
} else if (action.change === "required") {
|
|
3885
|
+
if (!required.includes(param)) tools[i] = { ...tool, inputSchema: { ...schema, required: [...required, param] } };
|
|
3886
|
+
} else {
|
|
3887
|
+
describeParam(tools, i, param, [action]);
|
|
3888
|
+
}
|
|
3889
|
+
return void 0;
|
|
3890
|
+
}
|
|
3891
|
+
function describeParam(tools, i, param, actions) {
|
|
3892
|
+
const tool = tools[i];
|
|
3893
|
+
const schema = tool.inputSchema;
|
|
3894
|
+
const properties = schema.properties;
|
|
3895
|
+
const described = isRecord(properties[param]) ? properties[param] : {};
|
|
3896
|
+
const current2 = typeof described.description === "string" ? described.description : void 0;
|
|
3897
|
+
const description = changedText(current2, actions).text;
|
|
3898
|
+
tools[i] = {
|
|
3899
|
+
...tool,
|
|
3900
|
+
inputSchema: { ...schema, properties: { ...properties, [param]: { ...described, description } } }
|
|
3901
|
+
};
|
|
3902
|
+
}
|
|
3472
3903
|
function withGoalMode(tool, goal) {
|
|
3473
3904
|
const entry = tool;
|
|
3474
3905
|
const schema = entry.inputSchema;
|
|
@@ -3558,13 +3989,20 @@ function assembleSurface(serverMeta, tools) {
|
|
|
3558
3989
|
var SENT_SURFACES_CAP = 256;
|
|
3559
3990
|
var SentSurfaces = class {
|
|
3560
3991
|
hashes = /* @__PURE__ */ new Set();
|
|
3561
|
-
|
|
3562
|
-
|
|
3992
|
+
serverOverlay = null;
|
|
3993
|
+
/** `serverOverlay` is not in `surface_hash`, and a snapshot is sent again
|
|
3994
|
+
* whenever it changes (SPEC §11.4.2). */
|
|
3995
|
+
wasSent(digest, serverOverlay = null) {
|
|
3996
|
+
if (serverOverlay !== this.serverOverlay || !this.hashes.has(digest)) return false;
|
|
3563
3997
|
this.hashes.delete(digest);
|
|
3564
3998
|
this.hashes.add(digest);
|
|
3565
3999
|
return true;
|
|
3566
4000
|
}
|
|
3567
|
-
mark(digest) {
|
|
4001
|
+
mark(digest, serverOverlay = null) {
|
|
4002
|
+
if (serverOverlay !== this.serverOverlay) {
|
|
4003
|
+
this.hashes.clear();
|
|
4004
|
+
this.serverOverlay = serverOverlay;
|
|
4005
|
+
}
|
|
3568
4006
|
this.hashes.add(digest);
|
|
3569
4007
|
if (this.hashes.size > SENT_SURFACES_CAP) {
|
|
3570
4008
|
this.hashes.delete(this.hashes.values().next().value);
|
|
@@ -3602,6 +4040,7 @@ var SurfaceState = class {
|
|
|
3602
4040
|
* injected schema as if it were vendor-true. */
|
|
3603
4041
|
rawTools = /* @__PURE__ */ new Map();
|
|
3604
4042
|
dirty = false;
|
|
4043
|
+
servedOverlayId = null;
|
|
3605
4044
|
/** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
|
|
3606
4045
|
* which picks the spelling THIS SDK major puts on the wire. */
|
|
3607
4046
|
noteTool(name, inputSchemaJson, description) {
|
|
@@ -3653,7 +4092,7 @@ async function resolveEnvelopeParts(ctx, extra) {
|
|
|
3653
4092
|
const session = await resolveSessionId(ctx.fallbackSessionId, extra);
|
|
3654
4093
|
return { ...session, scrubbedMeta };
|
|
3655
4094
|
}
|
|
3656
|
-
async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn") {
|
|
4095
|
+
async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn", resolved) {
|
|
3657
4096
|
await maybeEmitSurfaceSnapshot(ctx);
|
|
3658
4097
|
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
3659
4098
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
@@ -3663,12 +4102,7 @@ async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn
|
|
|
3663
4102
|
(name) => dispositions === void 0 || dispositions[name] === "native" || unlisted === "leave" || unlisted === "goalOnly" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
|
|
3664
4103
|
);
|
|
3665
4104
|
const client = observeClient(extra, ctx);
|
|
3666
|
-
const caller = await resolveCaller(
|
|
3667
|
-
ctx.resolvePrincipal,
|
|
3668
|
-
{ extra, toolName, arguments: params },
|
|
3669
|
-
ctx.captureSettings,
|
|
3670
|
-
client
|
|
3671
|
-
);
|
|
4105
|
+
const caller = resolved ?? await resolveCaller(ctx.resolvePrincipal, { extra, toolName, arguments: params }, ctx.captureSettings, client);
|
|
3672
4106
|
const resultCaptureMode = caller.settings?.resultCaptureMode ?? ctx.configResultCaptureMode;
|
|
3673
4107
|
const common = {
|
|
3674
4108
|
tenant_id: ctx.tenantId,
|
|
@@ -3706,16 +4140,24 @@ async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn
|
|
|
3706
4140
|
);
|
|
3707
4141
|
return { common, session, resultCaptureMode };
|
|
3708
4142
|
}
|
|
3709
|
-
function batonWrap(nameRef, original, ctx, unlisted = "warn") {
|
|
4143
|
+
function batonWrap(nameRef, original, ctx, unlisted = "warn", resolved) {
|
|
3710
4144
|
return async (...callArgs) => {
|
|
3711
4145
|
const toolName = nameRef.current;
|
|
3712
4146
|
const slot = callSlots.getStore();
|
|
3713
4147
|
if (slot) slot.innerFired = true;
|
|
3714
4148
|
const extra = callArgs[callArgs.length - 1];
|
|
3715
4149
|
const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
|
|
3716
|
-
const
|
|
4150
|
+
const ours = slot?.strippedFor === toolName ? slot : void 0;
|
|
3717
4151
|
if (slot) slot.strippedFor = null;
|
|
3718
|
-
const { common, session, resultCaptureMode } = await openCall(
|
|
4152
|
+
const { common, session, resultCaptureMode } = await openCall(
|
|
4153
|
+
ctx,
|
|
4154
|
+
toolName,
|
|
4155
|
+
extra,
|
|
4156
|
+
params,
|
|
4157
|
+
ours?.stripped ?? {},
|
|
4158
|
+
unlisted,
|
|
4159
|
+
ours?.caller ?? resolved
|
|
4160
|
+
);
|
|
3719
4161
|
const terminate = async (build, replacement) => {
|
|
3720
4162
|
if (!slot) {
|
|
3721
4163
|
if (build !== null) await emit(ctx.sink, build);
|
|
@@ -3906,6 +4348,11 @@ function stripIntentParams(params, ctx) {
|
|
|
3906
4348
|
return stripped;
|
|
3907
4349
|
}
|
|
3908
4350
|
async function maybeEmitSurfaceSnapshot(ctx) {
|
|
4351
|
+
const overlayId = ctx.perCaller?.serverOverlay?.id ?? null;
|
|
4352
|
+
if (overlayId !== ctx.surfaceState.servedOverlayId) {
|
|
4353
|
+
ctx.surfaceState.servedOverlayId = overlayId;
|
|
4354
|
+
ctx.surfaceState.dirty = true;
|
|
4355
|
+
}
|
|
3909
4356
|
if (!ctx.surfaceState.dirty) return;
|
|
3910
4357
|
ctx.surfaceState.dirty = false;
|
|
3911
4358
|
let snapshot;
|
|
@@ -3918,8 +4365,8 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
3918
4365
|
return;
|
|
3919
4366
|
}
|
|
3920
4367
|
const sent = ctx.surfaceState.sentSurfaces;
|
|
3921
|
-
if (sent.wasSent(digest)) return;
|
|
3922
|
-
sent.mark(digest);
|
|
4368
|
+
if (sent.wasSent(digest, overlayId)) return;
|
|
4369
|
+
sent.mark(digest, overlayId);
|
|
3923
4370
|
const seam = buildSeamAugmentations({
|
|
3924
4371
|
injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
|
|
3925
4372
|
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
@@ -3927,6 +4374,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
3927
4374
|
requiredParamNames: requiredParamNames(ctx.intentParamMode),
|
|
3928
4375
|
instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions())
|
|
3929
4376
|
});
|
|
4377
|
+
if (ctx.captureSettings !== void 0) seam.server_overlay = overlayId;
|
|
3930
4378
|
await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
|
|
3931
4379
|
}
|
|
3932
4380
|
function declaredIntentParams(vendorSchema) {
|
|
@@ -4004,6 +4452,7 @@ function installToolsListSeam(lowLevel, ctx, listsOwnReportTool) {
|
|
|
4004
4452
|
var LOW_LEVEL_LIST_SEAM = /* @__PURE__ */ Symbol("batonLowLevelListSeam");
|
|
4005
4453
|
var LOW_LEVEL_CALL_SEAM = /* @__PURE__ */ Symbol("batonLowLevelCallSeam");
|
|
4006
4454
|
var LOW_LEVEL_HANDSHAKE_SEAM = /* @__PURE__ */ Symbol("batonLowLevelHandshakeSeam");
|
|
4455
|
+
var SETTINGS_SEAM = /* @__PURE__ */ Symbol("batonSettingsSeam");
|
|
4007
4456
|
function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce2, reportToolTaken) {
|
|
4008
4457
|
let reportTool2 = annotationTool;
|
|
4009
4458
|
const listedReportTool = reportTool2 && {
|
|
@@ -4102,13 +4551,23 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
|
|
|
4102
4551
|
installRequestSeam(lowLevel, "server/discover", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);
|
|
4103
4552
|
installRequestSeam(lowLevel, TOOLS_CALL_METHOD, LOW_LEVEL_CALL_SEAM, (handler) => async (...args) => {
|
|
4104
4553
|
catchUp();
|
|
4105
|
-
ctx.perCaller?.followSettings();
|
|
4106
4554
|
const request = args[0];
|
|
4107
4555
|
const name = request?.params?.name;
|
|
4108
4556
|
if (typeof name !== "string") return handler(...args);
|
|
4109
4557
|
if (name === reportTool2?.name) return callAnnotationTool(reportTool2, request?.params?.arguments, args[1]);
|
|
4110
4558
|
const injected = ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected";
|
|
4111
4559
|
const unlisted = injected ? "warn" : known.keepsGoal.has(name) || known.unread.has(name) ? "leave" : "goalOnly";
|
|
4560
|
+
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) };
|
|
4561
|
+
let slot;
|
|
4562
|
+
if (mayHide(ctx.captureSettings, name)) {
|
|
4563
|
+
const hookArgs = isRecord(request?.params?.arguments) ? { ...request.params.arguments } : {};
|
|
4564
|
+
const checked = { innerFired: false, flushTerminal: null, stripped: strip(hookArgs), strippedFor: name, validation: "unseen", unlisted };
|
|
4565
|
+
if (await hiddenFrom(checked, name, hookArgs, args[1], ctx)) {
|
|
4566
|
+
if (request?.params !== void 0 && isRecord(request.params.arguments)) request.params.arguments = hookArgs;
|
|
4567
|
+
return answerHidden(lowLevel, name, (outcome) => settleCall(checked, outcome, args, () => void 0, ctx, "tool_hidden"));
|
|
4568
|
+
}
|
|
4569
|
+
slot = checked;
|
|
4570
|
+
}
|
|
4112
4571
|
const params = request?.params?.arguments;
|
|
4113
4572
|
const toolArgs = isRecord(params) ? params : {};
|
|
4114
4573
|
if (unlisted === "goalOnly" && USER_GOAL_PARAM_NAME in toolArgs && !known.served.has(name) && !known.givenTools.some((tool) => tool.name === name)) {
|
|
@@ -4118,11 +4577,10 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
|
|
|
4118
4577
|
);
|
|
4119
4578
|
}
|
|
4120
4579
|
if (request?.params?.task !== void 0) {
|
|
4121
|
-
|
|
4122
|
-
else extractGoalParam(toolArgs, USER_GOAL_PARAM_NAME, name, ctx.paramRegistry.get(name), unlisted);
|
|
4580
|
+
strip(toolArgs);
|
|
4123
4581
|
return handler(...args);
|
|
4124
4582
|
}
|
|
4125
|
-
return batonWrap({ current: name }, () => handler(...args), ctx, unlisted)(toolArgs, args[1]);
|
|
4583
|
+
return batonWrap({ current: name }, () => handler(...args), ctx, unlisted, slot?.caller)(toolArgs, args[1]);
|
|
4126
4584
|
});
|
|
4127
4585
|
}
|
|
4128
4586
|
function lowLevelMajor(lowLevel) {
|
|
@@ -4370,7 +4828,6 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
4370
4828
|
TOOLS_CALL_METHOD,
|
|
4371
4829
|
TOOLS_CALL_SEAM,
|
|
4372
4830
|
(handler) => async (...args) => {
|
|
4373
|
-
ctx.perCaller?.followSettings();
|
|
4374
4831
|
const request = args[0];
|
|
4375
4832
|
const name = request?.params?.name;
|
|
4376
4833
|
const slot = {
|
|
@@ -4380,6 +4837,10 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
4380
4837
|
strippedFor: typeof name === "string" ? name : null,
|
|
4381
4838
|
validation: "unseen"
|
|
4382
4839
|
};
|
|
4840
|
+
const toolArgs = request?.params?.arguments;
|
|
4841
|
+
if (typeof name === "string" && toolEntry(name) != null && await hiddenFrom(slot, name, isRecord(toolArgs) ? toolArgs : {}, args[1], ctx)) {
|
|
4842
|
+
return answerHidden(lowLevel, name, (outcome2) => settleCall(slot, outcome2, args, toolEntry, ctx, "tool_hidden"));
|
|
4843
|
+
}
|
|
4383
4844
|
let outcome = CLEAN_OUTCOME;
|
|
4384
4845
|
try {
|
|
4385
4846
|
const result = await callSlots.run(slot, () => handler(...args));
|
|
@@ -4394,6 +4855,34 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
4394
4855
|
}
|
|
4395
4856
|
);
|
|
4396
4857
|
}
|
|
4858
|
+
async function hiddenFrom(slot, name, params, extra, ctx) {
|
|
4859
|
+
try {
|
|
4860
|
+
if (name === ctx.annotationToolName || !mayHide(ctx.captureSettings, name)) return false;
|
|
4861
|
+
slot.caller = await resolveCaller(
|
|
4862
|
+
ctx.resolvePrincipal,
|
|
4863
|
+
{ extra, toolName: name, arguments: params },
|
|
4864
|
+
ctx.captureSettings,
|
|
4865
|
+
observeClient(extra, ctx)
|
|
4866
|
+
);
|
|
4867
|
+
return slot.caller.settings?.overlay?.hiddenTools.has(name) ?? false;
|
|
4868
|
+
} catch (err) {
|
|
4869
|
+
stderrLine(`baton: could not check whether the tool is hidden; it is served: ${printable(err)}`);
|
|
4870
|
+
return false;
|
|
4871
|
+
}
|
|
4872
|
+
}
|
|
4873
|
+
async function answerHidden(lowLevel, name, settle) {
|
|
4874
|
+
if (lowLevelMajor(lowLevel) === 1) {
|
|
4875
|
+
const result = { content: [{ type: "text", text: `MCP error -32602: Tool ${name} not found` }], isError: true };
|
|
4876
|
+
await settle({ failed: true, raised: false, result });
|
|
4877
|
+
return result;
|
|
4878
|
+
}
|
|
4879
|
+
const err = new ProtocolError(`Tool ${name} not found`);
|
|
4880
|
+
await settle({ failed: true, raised: true, err });
|
|
4881
|
+
throw err;
|
|
4882
|
+
}
|
|
4883
|
+
var ProtocolError = class extends Error {
|
|
4884
|
+
code = -32602;
|
|
4885
|
+
};
|
|
4397
4886
|
var VALIDATION_PROBE = /* @__PURE__ */ Symbol("baton.validationProbe");
|
|
4398
4887
|
function installValidationProbe(server) {
|
|
4399
4888
|
const target = server;
|
|
@@ -4413,7 +4902,7 @@ function installValidationProbe(server) {
|
|
|
4413
4902
|
Object.assign(probe, { [VALIDATION_PROBE]: true });
|
|
4414
4903
|
target.validateToolInput = probe;
|
|
4415
4904
|
}
|
|
4416
|
-
async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
4905
|
+
async function settleCall(slot, outcome, args, toolEntry, ctx, kind) {
|
|
4417
4906
|
try {
|
|
4418
4907
|
if (slot.flushTerminal !== null) {
|
|
4419
4908
|
const flush = slot.flushTerminal;
|
|
@@ -4423,13 +4912,13 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
|
4423
4912
|
}
|
|
4424
4913
|
if (slot.innerFired) return;
|
|
4425
4914
|
if (!outcome.failed) return;
|
|
4426
|
-
await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
|
|
4915
|
+
await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx, kind);
|
|
4427
4916
|
} catch (err) {
|
|
4428
4917
|
PROCESS_DROPS.add("encode_failed");
|
|
4429
4918
|
stderrLine(`baton: settling a tool call failed; events dropped: ${String(err)}`);
|
|
4430
4919
|
}
|
|
4431
4920
|
}
|
|
4432
|
-
async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
4921
|
+
async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx, kind) {
|
|
4433
4922
|
const request = args[0];
|
|
4434
4923
|
const toolName = request?.params?.name;
|
|
4435
4924
|
if (typeof toolName !== "string") return;
|
|
@@ -4443,9 +4932,10 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
|
4443
4932
|
args[1],
|
|
4444
4933
|
params,
|
|
4445
4934
|
slot.stripped,
|
|
4446
|
-
entry != null ? "warn" : "quiet"
|
|
4935
|
+
slot.unlisted ?? (entry != null ? "warn" : "quiet"),
|
|
4936
|
+
slot.caller
|
|
4447
4937
|
);
|
|
4448
|
-
const failureKind = requestSideFailureKind(entry, slot.validation);
|
|
4938
|
+
const failureKind = kind ?? requestSideFailureKind(entry, slot.validation);
|
|
4449
4939
|
const text = () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result);
|
|
4450
4940
|
await emit(
|
|
4451
4941
|
ctx.sink,
|
|
@@ -4639,7 +5129,7 @@ function newBatonState(config) {
|
|
|
4639
5129
|
lowLevelTools: { given: config.tools, givenTools: [], served: /* @__PURE__ */ new Map(), keepsGoal: /* @__PURE__ */ new Set(), unread: /* @__PURE__ */ new Set() }
|
|
4640
5130
|
};
|
|
4641
5131
|
}
|
|
4642
|
-
function install(server, supplied, resolved, { sentSurfaces, warned:
|
|
5132
|
+
function install(server, supplied, resolved, { sentSurfaces, warned: warned4, counter: sharedCounter, scrubber, lowLevelTools }, unconfigured) {
|
|
4643
5133
|
const shape = serverShapeOf(server);
|
|
4644
5134
|
const internals = server;
|
|
4645
5135
|
const lowLevel = shape === "mcpServer" ? internals.server : server;
|
|
@@ -4692,19 +5182,16 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4692
5182
|
if (memo && typeof memo === "object") delete memo[name];
|
|
4693
5183
|
};
|
|
4694
5184
|
const warnOnce2 = (key, message) => {
|
|
4695
|
-
if (
|
|
4696
|
-
|
|
5185
|
+
if (warned4.has(key)) return;
|
|
5186
|
+
warned4.add(key);
|
|
4697
5187
|
stderrLine(message);
|
|
4698
5188
|
};
|
|
5189
|
+
const warnLength = (message) => warnOnce2("instructions-length", message);
|
|
5190
|
+
const setInstructions = (text) => {
|
|
5191
|
+
lowLevel._instructions = text;
|
|
5192
|
+
};
|
|
4699
5193
|
const dropSubagentClause = (name) => {
|
|
4700
|
-
|
|
4701
|
-
if (current2 === INTENT_INSTRUCTIONS) {
|
|
4702
|
-
lowLevel._instructions = "";
|
|
4703
|
-
} else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
|
|
4704
|
-
lowLevel._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
|
|
4705
|
-
} else {
|
|
4706
|
-
return;
|
|
4707
|
-
}
|
|
5194
|
+
if (!removeSubagentClause(lowLevel, setInstructions, warnLength)) return;
|
|
4708
5195
|
warnOnce2(
|
|
4709
5196
|
"native-user-goal",
|
|
4710
5197
|
`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`
|
|
@@ -4751,12 +5238,8 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4751
5238
|
surfaceState,
|
|
4752
5239
|
emitSurface
|
|
4753
5240
|
};
|
|
4754
|
-
const writeInstructions = (text) => {
|
|
4755
|
-
lowLevel
|
|
4756
|
-
lowLevel,
|
|
4757
|
-
text,
|
|
4758
|
-
(message) => warnOnce2("instructions-length", message)
|
|
4759
|
-
);
|
|
5241
|
+
const writeInstructions = (text, subagent = INTENT_INSTRUCTIONS) => {
|
|
5242
|
+
writeOurs(lowLevel, text, subagent, setInstructions, warnLength);
|
|
4760
5243
|
};
|
|
4761
5244
|
writeInstructions(ours);
|
|
4762
5245
|
const rewriteInstructions = (text) => {
|
|
@@ -4772,8 +5255,9 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4772
5255
|
get annotationToolName() {
|
|
4773
5256
|
return ctx.annotationToolName;
|
|
4774
5257
|
},
|
|
4775
|
-
|
|
4776
|
-
writeInstructions
|
|
5258
|
+
pointer: () => reports && ctx.annotationToolName ? buildReportPointer({ vendorDisplayName: reports.vendorDisplayName, annotationToolName: ctx.annotationToolName }) : void 0,
|
|
5259
|
+
writeInstructions,
|
|
5260
|
+
subagentLine: () => ![...ctx.paramRegistry.values()].some((d) => d[USER_GOAL_PARAM_NAME] === "native"),
|
|
4777
5261
|
injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
|
|
4778
5262
|
});
|
|
4779
5263
|
ctx.perCaller.followSettings();
|
|
@@ -4801,7 +5285,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4801
5285
|
annotationOptions && buildAnnotationTool(server, annotationOptions),
|
|
4802
5286
|
lowLevelTools,
|
|
4803
5287
|
warnOnce2,
|
|
4804
|
-
() => rewriteInstructions(INTENT_INSTRUCTIONS)
|
|
5288
|
+
() => ctx.perCaller ? ctx.perCaller.refresh() : rewriteInstructions(INTENT_INSTRUCTIONS)
|
|
4805
5289
|
);
|
|
4806
5290
|
}
|
|
4807
5291
|
installToolsListSeam(lowLevel, ctx, shape === "lowLevel");
|
|
@@ -4821,6 +5305,17 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4821
5305
|
ctx
|
|
4822
5306
|
);
|
|
4823
5307
|
installLifecycleSeams(lowLevel, ctx);
|
|
5308
|
+
const settings = config.captureSettings;
|
|
5309
|
+
if (settings !== void 0) {
|
|
5310
|
+
const waitFirst = (handler) => async (...args) => {
|
|
5311
|
+
if (!settings.isReady) await settings.ready;
|
|
5312
|
+
ctx.perCaller?.followSettings();
|
|
5313
|
+
return handler(...args);
|
|
5314
|
+
};
|
|
5315
|
+
for (const method of ["initialize", "server/discover", TOOLS_LIST_METHOD, TOOLS_CALL_METHOD]) {
|
|
5316
|
+
installRequestSeam(lowLevel, method, SETTINGS_SEAM, waitFirst);
|
|
5317
|
+
}
|
|
5318
|
+
}
|
|
4824
5319
|
const handle = (name) => new BatonHandle({
|
|
4825
5320
|
sink: given,
|
|
4826
5321
|
queue: sink,
|
|
@@ -4854,6 +5349,7 @@ function warnAboutSettings(config) {
|
|
|
4854
5349
|
`baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered`
|
|
4855
5350
|
);
|
|
4856
5351
|
}
|
|
5352
|
+
candidateNeedsConsole(config.settings);
|
|
4857
5353
|
if (config.resultCaptureMode === WITHHELD) {
|
|
4858
5354
|
warn(
|
|
4859
5355
|
'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.'
|