@goodtiming/baton-sdk 1.1.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.cjs +1427 -959
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +59 -1
- package/dist/index.d.ts +59 -1
- package/dist/index.js +1427 -959
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/version.ts
|
|
2
|
-
var SDK_VERSION = "ts-1.
|
|
2
|
+
var SDK_VERSION = "ts-1.2.0";
|
|
3
3
|
|
|
4
4
|
// src/events.ts
|
|
5
5
|
import { z } from "zod";
|
|
@@ -132,7 +132,8 @@ var ClientObservedSchema = z.object({
|
|
|
132
132
|
var CaptureObservedSchema = z.object({
|
|
133
133
|
settings_version: z.number().int().min(1).optional(),
|
|
134
134
|
audience: z.string().optional(),
|
|
135
|
-
overlay: z.string().optional()
|
|
135
|
+
overlay: z.string().optional(),
|
|
136
|
+
candidate: z.string().optional()
|
|
136
137
|
}).strict();
|
|
137
138
|
var PrincipalWireSchema = z.object({
|
|
138
139
|
id: z.string(),
|
|
@@ -577,6 +578,11 @@ function stripEdges(value, space) {
|
|
|
577
578
|
function stripWhiteSpace(value) {
|
|
578
579
|
return stripEdges(value, WHITE_SPACE);
|
|
579
580
|
}
|
|
581
|
+
function stripWhiteSpaceEnd(value) {
|
|
582
|
+
let end = value.length;
|
|
583
|
+
while (end > 0 && WHITE_SPACE.test(value[end - 1])) end--;
|
|
584
|
+
return value.slice(0, end);
|
|
585
|
+
}
|
|
580
586
|
function isBlank(value) {
|
|
581
587
|
return ALL_WHITE_SPACE.test(value);
|
|
582
588
|
}
|
|
@@ -1740,6 +1746,122 @@ function roundMetaCoordinates(meta) {
|
|
|
1740
1746
|
return walk(meta, 0);
|
|
1741
1747
|
}
|
|
1742
1748
|
|
|
1749
|
+
// src/integrations/mcp/overlays.ts
|
|
1750
|
+
var INSTRUCTION_PIECES = ["instructions.subagent", "instructions.report_pointer"];
|
|
1751
|
+
var AUDIENCE_PIECES = ["goal_param.description", "report_tool.description", "report_tool.refusal"];
|
|
1752
|
+
var TEXT_CHANGES = ["append", "replace"];
|
|
1753
|
+
var FLAG_CHANGES = ["remove", "required"];
|
|
1754
|
+
var warned = /* @__PURE__ */ new Set();
|
|
1755
|
+
var unreadable = /* @__PURE__ */ new Set();
|
|
1756
|
+
function warnSkipped(overlayId, index, reason) {
|
|
1757
|
+
const key = JSON.stringify([overlayId, index]);
|
|
1758
|
+
if (warned.has(key)) return;
|
|
1759
|
+
warned.add(key);
|
|
1760
|
+
warn(`baton: overlay ${JSON.stringify(overlayId)} action ${index} is skipped: ${reason}`);
|
|
1761
|
+
}
|
|
1762
|
+
var Overlay = class {
|
|
1763
|
+
constructor(id, actions) {
|
|
1764
|
+
this.id = id;
|
|
1765
|
+
this.actions = actions;
|
|
1766
|
+
this.hiddenTools = new Set(
|
|
1767
|
+
actions.filter((a) => a.tool !== void 0 && a.param === void 0 && a.change === "remove").map((a) => a.tool)
|
|
1768
|
+
);
|
|
1769
|
+
}
|
|
1770
|
+
id;
|
|
1771
|
+
actions;
|
|
1772
|
+
hiddenTools;
|
|
1773
|
+
pieceActions(piece) {
|
|
1774
|
+
return this.actions.filter((a) => a.piece === piece);
|
|
1775
|
+
}
|
|
1776
|
+
instructionAppends() {
|
|
1777
|
+
return this.actions.filter((a) => a.instructions && a.text !== void 0).map((a) => a.text);
|
|
1778
|
+
}
|
|
1779
|
+
};
|
|
1780
|
+
function changedText(text, actions) {
|
|
1781
|
+
let source = "default";
|
|
1782
|
+
for (const action of actions) {
|
|
1783
|
+
if (action.change === "replace") {
|
|
1784
|
+
text = action.text;
|
|
1785
|
+
source = "replaced";
|
|
1786
|
+
} else if (action.change === "append" && action.text !== void 0) {
|
|
1787
|
+
const kept = stripWhiteSpaceEnd(text ?? "");
|
|
1788
|
+
text = kept ? `${kept}
|
|
1789
|
+
|
|
1790
|
+
${action.text}` : action.text;
|
|
1791
|
+
if (source === "default") source = "appended";
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
return { text, source };
|
|
1795
|
+
}
|
|
1796
|
+
function overlaid(text, overlay, piece) {
|
|
1797
|
+
if (overlay === void 0) return text;
|
|
1798
|
+
return changedText(text, overlay.pieceActions(piece)).text ?? text;
|
|
1799
|
+
}
|
|
1800
|
+
function readOverlays(value) {
|
|
1801
|
+
return isRecord(value) ? value : {};
|
|
1802
|
+
}
|
|
1803
|
+
function overlayFor(overlays, overlayId, place) {
|
|
1804
|
+
if (overlayId === void 0 || overlayId === null) return void 0;
|
|
1805
|
+
let id;
|
|
1806
|
+
let body;
|
|
1807
|
+
if (typeof overlayId === "string") {
|
|
1808
|
+
id = overlayId;
|
|
1809
|
+
body = Object.hasOwn(overlays, id) ? overlays[id] : void 0;
|
|
1810
|
+
} else {
|
|
1811
|
+
id = JSON.stringify(overlayId);
|
|
1812
|
+
}
|
|
1813
|
+
const actions = isRecord(body) ? body.actions : void 0;
|
|
1814
|
+
if (!Array.isArray(actions)) {
|
|
1815
|
+
if (!unreadable.has(id)) {
|
|
1816
|
+
unreadable.add(id);
|
|
1817
|
+
warn(`baton: overlay ${JSON.stringify(id)} cannot be read; none is applied there`);
|
|
1818
|
+
}
|
|
1819
|
+
return void 0;
|
|
1820
|
+
}
|
|
1821
|
+
const kept = [];
|
|
1822
|
+
actions.forEach((raw, index) => {
|
|
1823
|
+
const read = readAction(index, raw, place);
|
|
1824
|
+
if (typeof read === "string") warnSkipped(id, index, read);
|
|
1825
|
+
else kept.push(read);
|
|
1826
|
+
});
|
|
1827
|
+
return new Overlay(id, kept);
|
|
1828
|
+
}
|
|
1829
|
+
function readAction(index, raw, place) {
|
|
1830
|
+
if (!isRecord(raw) || !isRecord(raw.target)) return "it has no target";
|
|
1831
|
+
const target = raw.target;
|
|
1832
|
+
const changes = [...TEXT_CHANGES, ...FLAG_CHANGES].filter((c) => Object.hasOwn(raw, c));
|
|
1833
|
+
if (changes.length !== 1 || Object.keys(raw).length !== 2) return "it needs exactly one change";
|
|
1834
|
+
const change = changes[0];
|
|
1835
|
+
const value = raw[change];
|
|
1836
|
+
if (TEXT_CHANGES.includes(change) && typeof value !== "string") return `'${change}' needs text`;
|
|
1837
|
+
if (FLAG_CHANGES.includes(change) && value !== true) return `'${change}' must be true`;
|
|
1838
|
+
const text = typeof value === "string" ? { text: value } : {};
|
|
1839
|
+
const keys = Object.keys(target).sort().join(",");
|
|
1840
|
+
if (keys === "tool" && typeof target.tool === "string") {
|
|
1841
|
+
if (change === "required") return "only a param can be required";
|
|
1842
|
+
return placed({ index, change, ...text, tool: target.tool }, place, "audience");
|
|
1843
|
+
}
|
|
1844
|
+
if (keys === "param,tool" && typeof target.tool === "string" && typeof target.param === "string") {
|
|
1845
|
+
return placed({ index, change, ...text, tool: target.tool, param: target.param }, place, "audience");
|
|
1846
|
+
}
|
|
1847
|
+
if (keys === "instructions" && target.instructions === true) {
|
|
1848
|
+
if (change !== "append") return "the instructions take only 'append'";
|
|
1849
|
+
return placed({ index, change, ...text, instructions: true }, place, "server");
|
|
1850
|
+
}
|
|
1851
|
+
if (keys === "agent_text" && typeof target.agent_text === "string") {
|
|
1852
|
+
const piece = target.agent_text;
|
|
1853
|
+
if (!TEXT_CHANGES.includes(change)) return "agent_text takes only 'append' or 'replace'";
|
|
1854
|
+
if (INSTRUCTION_PIECES.includes(piece)) return placed({ index, change, ...text, piece }, place, "server");
|
|
1855
|
+
if (AUDIENCE_PIECES.includes(piece)) return placed({ index, change, ...text, piece }, place, "audience");
|
|
1856
|
+
return `unknown agent_text ${JSON.stringify(piece)}`;
|
|
1857
|
+
}
|
|
1858
|
+
return "unknown target";
|
|
1859
|
+
}
|
|
1860
|
+
function placed(action, place, allowed) {
|
|
1861
|
+
if (place === allowed) return action;
|
|
1862
|
+
return `this target goes only in ${allowed === "server" ? "server_overlay" : "an audience's overlay"}`;
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1743
1865
|
// src/integrations/mcp/llmText.ts
|
|
1744
1866
|
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.`;
|
|
1745
1867
|
var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
|
|
@@ -1755,14 +1877,14 @@ Fields:
|
|
|
1755
1877
|
- 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.`;
|
|
1756
1878
|
var CLAUDE_CODE_TRUNCATION_CAP = 2087;
|
|
1757
1879
|
var INSTRUCTIONS_LENGTH_CAP = 1500;
|
|
1758
|
-
function
|
|
1880
|
+
function buildReportPointer(options) {
|
|
1759
1881
|
return REPORT_POINTER_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
|
|
1760
1882
|
}
|
|
1761
1883
|
function fitsInstructionsCap(options) {
|
|
1762
|
-
return
|
|
1884
|
+
return buildReportPointer(options).length <= INSTRUCTIONS_LENGTH_CAP;
|
|
1763
1885
|
}
|
|
1764
1886
|
function buildServerInstructions(options) {
|
|
1765
|
-
const rendered =
|
|
1887
|
+
const rendered = buildReportPointer(options);
|
|
1766
1888
|
if (rendered.length > INSTRUCTIONS_LENGTH_CAP) {
|
|
1767
1889
|
throw new Error(
|
|
1768
1890
|
`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.`
|
|
@@ -1774,7 +1896,8 @@ function buildAnnotationToolDescription(options) {
|
|
|
1774
1896
|
return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
|
|
1775
1897
|
}
|
|
1776
1898
|
function buildRefusalText(options) {
|
|
1777
|
-
|
|
1899
|
+
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.`;
|
|
1900
|
+
return overlaid(text, options.overlay, "report_tool.refusal");
|
|
1778
1901
|
}
|
|
1779
1902
|
var USER_GOAL_PARAM_NAME = "user_goal";
|
|
1780
1903
|
var EXPECTED_RESULT_PARAM_NAME = "expected_result";
|
|
@@ -1822,37 +1945,47 @@ var INTENT_PARAMS = Object.freeze([
|
|
|
1822
1945
|
Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: "intent" })
|
|
1823
1946
|
]);
|
|
1824
1947
|
var VENDOR_INSTRUCTIONS = /* @__PURE__ */ Symbol("batonVendorInstructions");
|
|
1825
|
-
var
|
|
1826
|
-
var
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
new RegExp("^" + escapeRegExp(INTENT_INSTRUCTIONS))
|
|
1831
|
-
];
|
|
1832
|
-
function endsInOurs(current2, vendor) {
|
|
1833
|
-
if (typeof current2 !== "string") return false;
|
|
1834
|
-
const prefix = typeof vendor === "string" && !isBlank(vendor) ? `${vendor}
|
|
1948
|
+
var OURS = /* @__PURE__ */ Symbol("batonInstructions");
|
|
1949
|
+
var SUBAGENT = /* @__PURE__ */ Symbol("batonSubagentSentence");
|
|
1950
|
+
function joined(vendor, ours) {
|
|
1951
|
+
if (typeof vendor !== "string" || isBlank(vendor)) return ours;
|
|
1952
|
+
return ours ? `${vendor}
|
|
1835
1953
|
|
|
1836
|
-
` :
|
|
1837
|
-
if (!current2.startsWith(prefix)) return false;
|
|
1838
|
-
const rest = current2.slice(prefix.length);
|
|
1839
|
-
return OURS_STARTS.some((start) => start.test(rest));
|
|
1954
|
+
${ours}` : vendor;
|
|
1840
1955
|
}
|
|
1841
|
-
function
|
|
1842
|
-
const holder = server;
|
|
1956
|
+
function vendorText(holder) {
|
|
1843
1957
|
const current2 = holder._instructions;
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1958
|
+
const written = holder[OURS];
|
|
1959
|
+
const vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
|
|
1960
|
+
return written !== void 0 && current2 === joined(vendor, written) ? vendor : current2;
|
|
1961
|
+
}
|
|
1962
|
+
function writeOurs(server, ours, subagent, write, warn3 = stderrLine) {
|
|
1963
|
+
const holder = server;
|
|
1964
|
+
const vendor = vendorText(holder);
|
|
1965
|
+
write(withVendorInstructions(server, ours, warn3));
|
|
1966
|
+
holder[VENDOR_INSTRUCTIONS] = vendor;
|
|
1967
|
+
holder[OURS] = ours;
|
|
1968
|
+
holder[SUBAGENT] = subagent && ours.endsWith(subagent) ? subagent : void 0;
|
|
1969
|
+
}
|
|
1970
|
+
function removeSubagentClause(server, write, warn3 = stderrLine) {
|
|
1971
|
+
const holder = server;
|
|
1972
|
+
const ours = holder[OURS];
|
|
1973
|
+
const subagent = holder[SUBAGENT];
|
|
1974
|
+
if (ours === void 0 || !subagent || holder._instructions !== joined(holder[VENDOR_INSTRUCTIONS], ours)) {
|
|
1975
|
+
return false;
|
|
1848
1976
|
}
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1977
|
+
const kept = ours.slice(0, ours.length - subagent.length);
|
|
1978
|
+
writeOurs(server, kept.endsWith("\n\n") ? kept.slice(0, -2) : kept, null, write, warn3);
|
|
1979
|
+
return true;
|
|
1980
|
+
}
|
|
1981
|
+
function withVendorInstructions(server, ours, warn3 = stderrLine) {
|
|
1982
|
+
const vendor = vendorText(server);
|
|
1983
|
+
const combined = joined(vendor, ours);
|
|
1984
|
+
if (combined === ours) return ours;
|
|
1985
|
+
const vendorLength = vendor?.length ?? 0;
|
|
1853
1986
|
if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
|
|
1854
1987
|
warn3(
|
|
1855
|
-
`baton: the server instructions are ${combined.length} chars (yours ${
|
|
1988
|
+
`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`
|
|
1856
1989
|
);
|
|
1857
1990
|
}
|
|
1858
1991
|
return combined;
|
|
@@ -2110,998 +2243,1170 @@ function identityWire(id, stated, displayName, onUnregisteredForm) {
|
|
|
2110
2243
|
return wire;
|
|
2111
2244
|
}
|
|
2112
2245
|
|
|
2113
|
-
// src/integrations/mcp/
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
return
|
|
2246
|
+
// src/integrations/mcp/captureSettings.ts
|
|
2247
|
+
import * as crypto2 from "crypto";
|
|
2248
|
+
|
|
2249
|
+
// src/integrations/mcp/errorResult.ts
|
|
2250
|
+
var TOOL_ERROR_TYPE = "tool_error";
|
|
2251
|
+
var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
|
|
2252
|
+
var REFUSED = "refused";
|
|
2253
|
+
var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
|
|
2254
|
+
function requestSideFailureKind(entry, validation) {
|
|
2255
|
+
if (entry == null) return "unknown_tool";
|
|
2256
|
+
if (entry.enabled === false) return "tool_disabled";
|
|
2257
|
+
if (validation === "rejected") return "invalid_argument";
|
|
2258
|
+
if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
|
|
2259
|
+
return REFUSED;
|
|
2127
2260
|
}
|
|
2128
|
-
|
|
2261
|
+
var ERROR_BODY_MAX_CODE_POINTS = 2e3;
|
|
2262
|
+
function isErrorResult(value) {
|
|
2129
2263
|
try {
|
|
2130
|
-
|
|
2131
|
-
return
|
|
2264
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2265
|
+
return Boolean(value.isError);
|
|
2132
2266
|
} catch {
|
|
2133
|
-
return
|
|
2267
|
+
return false;
|
|
2134
2268
|
}
|
|
2135
2269
|
}
|
|
2136
|
-
function
|
|
2137
|
-
const
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
const
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
headers.append(name, item);
|
|
2147
|
-
} catch {
|
|
2148
|
-
}
|
|
2149
|
-
}
|
|
2270
|
+
function errorText(value) {
|
|
2271
|
+
const parts = [];
|
|
2272
|
+
try {
|
|
2273
|
+
const content = value?.content;
|
|
2274
|
+
if (!Array.isArray(content)) return "";
|
|
2275
|
+
for (const part of content) {
|
|
2276
|
+
const text = part?.text;
|
|
2277
|
+
if (typeof text !== "string") continue;
|
|
2278
|
+
const trimmed = stripWhiteSpace(text);
|
|
2279
|
+
if (trimmed) parts.push(trimmed);
|
|
2150
2280
|
}
|
|
2151
|
-
|
|
2281
|
+
} catch {
|
|
2282
|
+
return "";
|
|
2152
2283
|
}
|
|
2153
|
-
return
|
|
2284
|
+
return parts.join("\n");
|
|
2154
2285
|
}
|
|
2155
|
-
|
|
2156
|
-
|
|
2286
|
+
var RESULT_CAPTURE_MODES = ["full", "off"];
|
|
2287
|
+
var WITHHELD = "off";
|
|
2288
|
+
function endResultFields(mode, result, scrubber) {
|
|
2289
|
+
switch (mode) {
|
|
2290
|
+
case WITHHELD:
|
|
2291
|
+
return { result: null, result_capture: WITHHELD };
|
|
2292
|
+
case "full":
|
|
2293
|
+
return { result: scrubber(result) };
|
|
2294
|
+
}
|
|
2157
2295
|
}
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
function buildPrincipalResolutionContext(extra, toolName, args) {
|
|
2161
|
-
return {
|
|
2162
|
-
headers: extraHeaders(extra),
|
|
2163
|
-
meta: extraMeta(extra),
|
|
2164
|
-
toolName,
|
|
2165
|
-
arguments: args,
|
|
2166
|
-
authInfo: extraAuthInfo(extra)
|
|
2167
|
-
};
|
|
2296
|
+
function returnedErrorFields(mode, result, errorBody2, scrubber) {
|
|
2297
|
+
return resultDerivedFields(mode, () => errorText(result), result, errorBody2, scrubber);
|
|
2168
2298
|
}
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
);
|
|
2177
|
-
return null;
|
|
2299
|
+
function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
|
|
2300
|
+
switch (mode) {
|
|
2301
|
+
case WITHHELD:
|
|
2302
|
+
return { error_body: "", result: null, result_capture: WITHHELD };
|
|
2303
|
+
case "full":
|
|
2304
|
+
return { error_body: errorBody2(text()), result: scrubber(result) };
|
|
2305
|
+
}
|
|
2178
2306
|
}
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
if (warned.has(key)) return;
|
|
2182
|
-
warned.add(key);
|
|
2183
|
-
warn(`baton: resolvePrincipal ${message}`);
|
|
2307
|
+
function requestSideErrorFields(text, errorBody2) {
|
|
2308
|
+
return { error_body: errorBody2(text), result: null };
|
|
2184
2309
|
}
|
|
2185
|
-
function
|
|
2186
|
-
return
|
|
2187
|
-
principal: caller.principal,
|
|
2188
|
-
organization: caller.organization,
|
|
2189
|
-
labels: wireLabels(caller.labels),
|
|
2190
|
-
capture: caller.settings?.capture ?? null
|
|
2191
|
-
};
|
|
2310
|
+
function requestSideFailureFields(kind, mode, text, result, errorBody2, scrubber) {
|
|
2311
|
+
return kind === REFUSED ? resultDerivedFields(mode, text, result ?? null, errorBody2, scrubber) : requestSideErrorFields(text(), errorBody2);
|
|
2192
2312
|
}
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2313
|
+
function errorTypeOf(err) {
|
|
2314
|
+
return err instanceof Error ? err.constructor.name : "Error";
|
|
2315
|
+
}
|
|
2316
|
+
function messageOf(err) {
|
|
2317
|
+
return err instanceof Error ? err.message : String(err);
|
|
2318
|
+
}
|
|
2319
|
+
function scrubbedErrorBody(scrubber, text) {
|
|
2320
|
+
return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
|
|
2321
|
+
}
|
|
2322
|
+
|
|
2323
|
+
// src/integrations/mcp/captureSettings.ts
|
|
2324
|
+
var SETTINGS_PATH = "/v0/settings";
|
|
2325
|
+
var TENANT_HEADER = "X-Baton-Tenant-Id";
|
|
2326
|
+
var SETTINGS_MODES = ["local", "console"];
|
|
2327
|
+
var DEFAULT_SETTINGS_REFRESH_MS = 6e4;
|
|
2328
|
+
var MIN_SETTINGS_REFRESH_MS = 15e3;
|
|
2329
|
+
var REQUEST_TIMEOUT_MS = 1e4;
|
|
2330
|
+
var CANDIDATE_ENV = "BATON_CANDIDATE";
|
|
2331
|
+
var CANDIDATE_HEADER = "baton-candidate";
|
|
2332
|
+
var CANDIDATES_HELD = 32;
|
|
2333
|
+
var CANDIDATE_READS_AT_ONCE = 4;
|
|
2334
|
+
var CANDIDATE_START_TIMEOUT_MS = 5e3;
|
|
2335
|
+
var CANDIDATE_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
2336
|
+
function candidateId(value) {
|
|
2337
|
+
if (typeof value !== "string") return null;
|
|
2338
|
+
const id = stripWhiteSpace(value);
|
|
2339
|
+
return CANDIDATE_ID.test(id) ? id : null;
|
|
2340
|
+
}
|
|
2341
|
+
function headerCandidate(headers) {
|
|
2197
2342
|
try {
|
|
2198
|
-
|
|
2199
|
-
labels: caller.labels,
|
|
2200
|
-
clientName: client?.info?.name ?? null,
|
|
2201
|
-
shareKey: caller.principal?.id ?? null
|
|
2202
|
-
});
|
|
2203
|
-
return callSettings === void 0 ? caller : { ...caller, settings: callSettings };
|
|
2343
|
+
return candidateId(headers?.get(CANDIDATE_HEADER));
|
|
2204
2344
|
} catch {
|
|
2205
|
-
|
|
2206
|
-
settingsWarned = true;
|
|
2207
|
-
warn("baton: applying capture settings failed; this request uses the config's values");
|
|
2208
|
-
}
|
|
2209
|
-
return caller;
|
|
2345
|
+
return null;
|
|
2210
2346
|
}
|
|
2211
2347
|
}
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2348
|
+
function envCandidate() {
|
|
2349
|
+
const value = typeof process !== "undefined" ? process.env?.[CANDIDATE_ENV] : void 0;
|
|
2350
|
+
if (!value) return null;
|
|
2351
|
+
const id = candidateId(value);
|
|
2352
|
+
if (id === null) warn(`baton: ${CANDIDATE_ENV} is not a change id; today's settings apply.`);
|
|
2353
|
+
return id;
|
|
2354
|
+
}
|
|
2355
|
+
function candidateNeedsConsole(settings) {
|
|
2356
|
+
if (settings !== "console" && envCandidate() !== null) {
|
|
2357
|
+
warn(
|
|
2358
|
+
`baton: ${CANDIDATE_ENV} is set, but this server's settings are not "console", so the change is not fetched; today's settings apply.`
|
|
2359
|
+
);
|
|
2220
2360
|
}
|
|
2221
2361
|
}
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
return
|
|
2362
|
+
var MATCH_KEYS = /* @__PURE__ */ new Set(["label", "client", "share"]);
|
|
2363
|
+
var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
|
|
2364
|
+
var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
|
|
2365
|
+
var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
|
|
2366
|
+
function shareBucket(vendorId2, key) {
|
|
2367
|
+
const digest = crypto2.createHash("sha256").update(`${vendorId2}
|
|
2368
|
+
${key}`, "utf-8").digest();
|
|
2369
|
+
return Number(digest.readBigUInt64BE(0) % 10000n);
|
|
2230
2370
|
}
|
|
2231
|
-
function
|
|
2232
|
-
|
|
2233
|
-
if (values.length === 0) return z4mini.object({});
|
|
2234
|
-
const allV4 = values.every(isZ4Schema);
|
|
2235
|
-
const allV3 = values.every((s) => !isZ4Schema(s));
|
|
2236
|
-
if (allV4) return z4mini.object(shape);
|
|
2237
|
-
if (allV3) return z3rt.object(shape);
|
|
2238
|
-
throw new Error("Mixed Zod versions detected in object shape.");
|
|
2371
|
+
function matchesEveryone(audience) {
|
|
2372
|
+
return audience.labels === null && audience.clients === null && audience.shareThreshold === null;
|
|
2239
2373
|
}
|
|
2240
|
-
function
|
|
2241
|
-
if (!
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
rawShape = schema._zod?.def?.shape;
|
|
2245
|
-
} else {
|
|
2246
|
-
rawShape = schema.shape;
|
|
2247
|
-
}
|
|
2248
|
-
if (!rawShape) return void 0;
|
|
2249
|
-
if (typeof rawShape === "function") {
|
|
2250
|
-
try {
|
|
2251
|
-
return rawShape();
|
|
2252
|
-
} catch {
|
|
2253
|
-
return void 0;
|
|
2254
|
-
}
|
|
2374
|
+
function matches(audience, caller, bucket) {
|
|
2375
|
+
if (audience.labels !== null && !caller.labels.some((label) => audience.labels.has(label))) return false;
|
|
2376
|
+
if (audience.clients !== null && (caller.clientName === null || !audience.clients.has(caller.clientName))) {
|
|
2377
|
+
return false;
|
|
2255
2378
|
}
|
|
2256
|
-
return
|
|
2379
|
+
if (audience.shareThreshold !== null && (bucket === null || bucket >= audience.shareThreshold)) return false;
|
|
2380
|
+
return true;
|
|
2257
2381
|
}
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
}
|
|
2270
|
-
}
|
|
2271
|
-
if (isZ4Schema(schema)) {
|
|
2272
|
-
const def = schema._zod?.def;
|
|
2273
|
-
if (def && (def.type === "object" || def.shape !== void 0)) return schema;
|
|
2274
|
-
} else {
|
|
2275
|
-
if (schema.shape !== void 0) return schema;
|
|
2382
|
+
var SettingsDocument = class {
|
|
2383
|
+
constructor(version, audiences, serverOverlay, candidate) {
|
|
2384
|
+
this.version = version;
|
|
2385
|
+
this.audiences = audiences;
|
|
2386
|
+
this.serverOverlay = serverOverlay;
|
|
2387
|
+
const overlays = audiences.flatMap((a) => a.settings.overlay === void 0 ? [] : [a.settings.overlay]);
|
|
2388
|
+
this.hiddenSomewhere = new Set(overlays.flatMap((o) => [...o.hiddenTools]));
|
|
2389
|
+
this.audiencePieces = new Set(overlays.flatMap((o) => o.actions.flatMap((a) => a.piece === void 0 ? [] : [a.piece])));
|
|
2390
|
+
this.usesShare = audiences.some((a) => a.shareThreshold !== null);
|
|
2391
|
+
this.unmatched = { capture: { settings_version: version, ...candidate === void 0 ? {} : { candidate } } };
|
|
2392
|
+
this.reportsOnForAnyone = audiences.some((a) => a.settings.reportMode !== "off") || !audiences.some(matchesEveryone);
|
|
2276
2393
|
}
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2394
|
+
version;
|
|
2395
|
+
audiences;
|
|
2396
|
+
serverOverlay;
|
|
2397
|
+
usesShare;
|
|
2398
|
+
unmatched;
|
|
2399
|
+
/** Whether some caller can get reports, so the instructions point to the
|
|
2400
|
+
* tool. Read only where the code's value is "on": no tool exists otherwise. */
|
|
2401
|
+
reportsOnForAnyone;
|
|
2402
|
+
/** The tools some audience's overlay hides. */
|
|
2403
|
+
hiddenSomewhere;
|
|
2404
|
+
/** The pieces of Baton's text some audience's overlay changes. */
|
|
2405
|
+
audiencePieces;
|
|
2406
|
+
settingsFor(caller, vendorId2) {
|
|
2407
|
+
const bucket = caller.shareKey !== null && this.usesShare ? shareBucket(vendorId2, caller.shareKey) : null;
|
|
2408
|
+
return this.audiences.find((audience) => matches(audience, caller, bucket))?.settings ?? this.unmatched;
|
|
2291
2409
|
}
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
}
|
|
2297
|
-
|
|
2298
|
-
// src/integrations/mcp/schemaCompat.ts
|
|
2299
|
-
import { z as zV4 } from "zod";
|
|
2300
|
-
import { z as zV3 } from "zod/v3";
|
|
2301
|
-
var DEFAULT_INTENT_PARAM_MODE = "required";
|
|
2302
|
-
var ROOT_COMBINERS = ["$ref", "oneOf", "anyOf", "allOf"];
|
|
2303
|
-
function takesUserGoalJson(schema) {
|
|
2304
|
-
const properties = schema.properties ?? {};
|
|
2305
|
-
return isRecord(properties) && !ROOT_COMBINERS.some((key) => key in schema);
|
|
2306
|
-
}
|
|
2307
|
-
function withUserGoalJson(schema, intentParamMode, listRequired) {
|
|
2308
|
-
if (!takesUserGoalJson(schema) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return schema;
|
|
2309
|
-
const properties = schema.properties ?? {};
|
|
2310
|
-
const goal = { type: "string", description: buildUserGoalParamDescription({ intentParamMode }) };
|
|
2311
|
-
const served = { ...schema, properties: { ...properties, [USER_GOAL_PARAM_NAME]: goal } };
|
|
2312
|
-
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
2313
|
-
if (listRequired && !required.includes(USER_GOAL_PARAM_NAME)) served.required = [...required, USER_GOAL_PARAM_NAME];
|
|
2314
|
-
return served;
|
|
2315
|
-
}
|
|
2316
|
-
var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
|
|
2317
|
-
function injectGoalParams(inputSchema2, intentParamMode) {
|
|
2318
|
-
const objSchema = normalizeObjectSchema(inputSchema2);
|
|
2319
|
-
if (!objSchema) return { schema: inputSchema2, dispositions: {} };
|
|
2320
|
-
const existingShape = getObjectShape(objSchema) ?? {};
|
|
2321
|
-
const values = Object.values(existingShape);
|
|
2322
|
-
const useV4 = values.length === 0 || isZ4Schema(values[0]);
|
|
2323
|
-
const zodImpl = useV4 ? zV4 : zV3;
|
|
2324
|
-
const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
|
|
2325
|
-
if (Object.keys(toInject).length === 0)
|
|
2326
|
-
return { schema: inputSchema2, dispositions };
|
|
2327
|
-
const mergedShape = { ...existingShape, ...toInject };
|
|
2328
|
-
const newSchema = objectFromShape(mergedShape);
|
|
2329
|
-
return { schema: newSchema, dispositions };
|
|
2410
|
+
};
|
|
2411
|
+
function stringSet(value) {
|
|
2412
|
+
if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) return null;
|
|
2413
|
+
return new Set(value);
|
|
2330
2414
|
}
|
|
2331
|
-
function
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
if (
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2415
|
+
function readAudience(version, id, match, capture, overlay, candidate) {
|
|
2416
|
+
if (!Object.keys(match).every((key) => MATCH_KEYS.has(key))) return null;
|
|
2417
|
+
let labels = null;
|
|
2418
|
+
let clients = null;
|
|
2419
|
+
let shareThreshold = null;
|
|
2420
|
+
if (Object.hasOwn(match, "label") && (labels = stringSet(match.label)) === null) return null;
|
|
2421
|
+
if (Object.hasOwn(match, "client") && (clients = stringSet(match.client)) === null) return null;
|
|
2422
|
+
if (Object.hasOwn(match, "share")) {
|
|
2423
|
+
const share = match.share;
|
|
2424
|
+
if (typeof share !== "number" || !(share > 0 && share <= 1)) return null;
|
|
2425
|
+
shareThreshold = Math.floor(share * 1e4 + 0.5);
|
|
2342
2426
|
}
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2427
|
+
const settings = {
|
|
2428
|
+
capture: {
|
|
2429
|
+
settings_version: version,
|
|
2430
|
+
audience: id,
|
|
2431
|
+
...overlay === void 0 ? {} : { overlay: overlay.id },
|
|
2432
|
+
...candidate === void 0 ? {} : { candidate }
|
|
2433
|
+
}
|
|
2434
|
+
};
|
|
2435
|
+
if (overlay !== void 0) settings.overlay = overlay;
|
|
2436
|
+
const { results, goal, reports } = capture;
|
|
2437
|
+
if (typeof results === "string" && RESULT_CAPTURE_MODE_SET.has(results)) {
|
|
2438
|
+
settings.resultCaptureMode = results;
|
|
2350
2439
|
}
|
|
2351
|
-
|
|
2352
|
-
if (
|
|
2353
|
-
|
|
2354
|
-
return { schema: candidate.extend(toInject), dispositions };
|
|
2355
|
-
}
|
|
2356
|
-
function advertiseIntentParamsRequired(result, names, isInjected) {
|
|
2357
|
-
const tools = result?.tools;
|
|
2358
|
-
if (!Array.isArray(tools)) return result;
|
|
2359
|
-
let changed = false;
|
|
2360
|
-
const advertised = tools.map((tool) => {
|
|
2361
|
-
const entry = tool;
|
|
2362
|
-
const toolName = entry?.name;
|
|
2363
|
-
if (typeof toolName !== "string") return tool;
|
|
2364
|
-
const schema = entry?.inputSchema;
|
|
2365
|
-
if (!schema || typeof schema !== "object") return tool;
|
|
2366
|
-
const declared2 = schema.required ?? [];
|
|
2367
|
-
if (!Array.isArray(declared2)) return tool;
|
|
2368
|
-
const required = declared2;
|
|
2369
|
-
const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
|
|
2370
|
-
if (missing.length === 0) return tool;
|
|
2371
|
-
changed = true;
|
|
2372
|
-
return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
|
|
2373
|
-
});
|
|
2374
|
-
return changed ? { ...result, tools: advertised } : result;
|
|
2375
|
-
}
|
|
2376
|
-
function withToolInputSchema(result, name, inputSchema2) {
|
|
2377
|
-
const tools = result?.tools;
|
|
2378
|
-
if (!Array.isArray(tools)) return result;
|
|
2379
|
-
const at = tools.findIndex((tool) => isRecord(tool) && tool.name === name);
|
|
2380
|
-
if (at === -1) return result;
|
|
2381
|
-
const served = [...tools];
|
|
2382
|
-
served[at] = { ...tools[at], inputSchema: inputSchema2 };
|
|
2383
|
-
return { ...result, tools: served };
|
|
2440
|
+
if (typeof goal === "string" && INTENT_PARAM_MODES.has(goal)) settings.intentParamMode = goal;
|
|
2441
|
+
if (typeof reports === "string" && REPORT_MODES.has(reports)) settings.reportMode = reports;
|
|
2442
|
+
return { settings, labels, clients, shareThreshold };
|
|
2384
2443
|
}
|
|
2385
|
-
function
|
|
2444
|
+
function parseDocument(body, candidate) {
|
|
2445
|
+
let data;
|
|
2386
2446
|
try {
|
|
2387
|
-
|
|
2388
|
-
return standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
|
|
2447
|
+
data = JSON.parse(body);
|
|
2389
2448
|
} catch {
|
|
2390
|
-
return
|
|
2449
|
+
return null;
|
|
2391
2450
|
}
|
|
2451
|
+
if (!isRecord(data)) return null;
|
|
2452
|
+
const { version, audiences } = data;
|
|
2453
|
+
if (typeof version !== "number" || !Number.isInteger(version) || version < 1) return null;
|
|
2454
|
+
if (!Array.isArray(audiences) || audiences.length === 0) return null;
|
|
2455
|
+
if (candidate !== void 0 && data.candidate !== candidate) return null;
|
|
2456
|
+
const overlays = readOverlays(data.overlays);
|
|
2457
|
+
const parsed = [];
|
|
2458
|
+
for (const audience of audiences) {
|
|
2459
|
+
if (!isRecord(audience)) return null;
|
|
2460
|
+
const { id, match, capture } = audience;
|
|
2461
|
+
if (typeof id !== "string" || !isRecord(match) || !isRecord(capture)) return null;
|
|
2462
|
+
const overlay = overlayFor(overlays, audience.overlay, "audience");
|
|
2463
|
+
const readable = readAudience(version, id, match, capture, overlay, candidate);
|
|
2464
|
+
if (readable !== null) parsed.push(readable);
|
|
2465
|
+
}
|
|
2466
|
+
return new SettingsDocument(version, parsed, overlayFor(overlays, data.server_overlay, "server"), candidate);
|
|
2392
2467
|
}
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2468
|
+
var SettingsFetcher = class {
|
|
2469
|
+
url;
|
|
2470
|
+
// `#`, not `private`, so logging a config shows no key: "logging the config shows no key".
|
|
2471
|
+
#headers;
|
|
2472
|
+
refreshMs;
|
|
2473
|
+
fetchImpl;
|
|
2474
|
+
etag = null;
|
|
2475
|
+
held = null;
|
|
2476
|
+
timer = null;
|
|
2477
|
+
reading = null;
|
|
2478
|
+
candidateReads = /* @__PURE__ */ new Set();
|
|
2479
|
+
warned = false;
|
|
2480
|
+
constructor(options) {
|
|
2481
|
+
this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
|
|
2482
|
+
this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
|
|
2483
|
+
this.refreshMs = options.refreshMs;
|
|
2484
|
+
this.fetchImpl = options.fetchImpl ?? globalFetch;
|
|
2485
|
+
}
|
|
2486
|
+
get document() {
|
|
2487
|
+
return this.held;
|
|
2488
|
+
}
|
|
2489
|
+
start() {
|
|
2490
|
+
if (this.timer !== null) return;
|
|
2491
|
+
this.timer = setInterval(() => void this.readOnce(), this.refreshMs);
|
|
2492
|
+
this.timer.unref?.();
|
|
2493
|
+
void this.readOnce();
|
|
2494
|
+
}
|
|
2495
|
+
stop() {
|
|
2496
|
+
if (this.timer !== null) clearInterval(this.timer);
|
|
2497
|
+
this.timer = null;
|
|
2498
|
+
this.reading?.abort();
|
|
2499
|
+
this.reading = null;
|
|
2500
|
+
for (const read of this.candidateReads) read.abort();
|
|
2501
|
+
}
|
|
2502
|
+
async fetchCandidate(candidate, timeoutMs) {
|
|
2503
|
+
const reading = new AbortController();
|
|
2504
|
+
const timeout = setTimeout(() => reading.abort(), timeoutMs);
|
|
2505
|
+
timeout.unref?.();
|
|
2506
|
+
this.candidateReads.add(reading);
|
|
2507
|
+
try {
|
|
2508
|
+
const url = `${this.url}&${new URLSearchParams({ candidate }).toString()}`;
|
|
2509
|
+
const response = await this.fetchImpl(url, {
|
|
2510
|
+
method: "GET",
|
|
2511
|
+
headers: this.#headers,
|
|
2512
|
+
redirect: "manual",
|
|
2513
|
+
signal: reading.signal
|
|
2514
|
+
});
|
|
2515
|
+
if (response.status !== 200) void response.body?.cancel().catch(() => void 0);
|
|
2516
|
+
if (response.status === 403) return { outcome: "refused" };
|
|
2517
|
+
if (response.status === 404) return { outcome: "unknown" };
|
|
2518
|
+
if (response.status === 200) {
|
|
2519
|
+
const document = parseDocument(await response.text(), candidate);
|
|
2520
|
+
if (document !== null) return { outcome: "loaded", document };
|
|
2521
|
+
}
|
|
2522
|
+
} catch {
|
|
2523
|
+
} finally {
|
|
2524
|
+
clearTimeout(timeout);
|
|
2525
|
+
this.candidateReads.delete(reading);
|
|
2526
|
+
}
|
|
2527
|
+
return { outcome: "failed" };
|
|
2528
|
+
}
|
|
2529
|
+
/** One request. Never rejects: a failure keeps what is held. */
|
|
2530
|
+
async readOnce() {
|
|
2531
|
+
if (this.reading !== null) return;
|
|
2532
|
+
const reading = new AbortController();
|
|
2533
|
+
this.reading = reading;
|
|
2534
|
+
const timeout = setTimeout(() => reading.abort(), REQUEST_TIMEOUT_MS);
|
|
2535
|
+
timeout.unref?.();
|
|
2536
|
+
try {
|
|
2537
|
+
await this.read(reading.signal);
|
|
2538
|
+
} catch {
|
|
2539
|
+
} finally {
|
|
2540
|
+
clearTimeout(timeout);
|
|
2541
|
+
if (this.reading === reading) this.reading = null;
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2544
|
+
async read(signal) {
|
|
2545
|
+
const headers = this.etag === null ? this.#headers : { ...this.#headers, "If-None-Match": this.etag };
|
|
2546
|
+
const response = await this.fetchImpl(this.url, { method: "GET", headers, redirect: "manual", signal });
|
|
2547
|
+
if (response.status !== 200) {
|
|
2548
|
+
void response.body?.cancel().catch(() => void 0);
|
|
2549
|
+
}
|
|
2550
|
+
if (signal.aborted) return;
|
|
2551
|
+
if (response.status === 204) {
|
|
2552
|
+
this.held = null;
|
|
2553
|
+
this.etag = null;
|
|
2554
|
+
} else if (response.status === 200) {
|
|
2555
|
+
const document = parseDocument(await response.text());
|
|
2556
|
+
if (signal.aborted) return;
|
|
2557
|
+
if (document === null) {
|
|
2558
|
+
if (!this.warned) {
|
|
2559
|
+
this.warned = true;
|
|
2560
|
+
warn("baton: the collector sent capture settings this SDK cannot read");
|
|
2561
|
+
}
|
|
2562
|
+
return;
|
|
2563
|
+
}
|
|
2564
|
+
this.held = document;
|
|
2565
|
+
this.etag = response.headers.get("etag");
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
};
|
|
2569
|
+
var PENDING = /* @__PURE__ */ Symbol("pending");
|
|
2570
|
+
var CaptureSettings = class {
|
|
2571
|
+
constructor(vendorId2, source, candidate = null, startTimeoutMs = CANDIDATE_START_TIMEOUT_MS) {
|
|
2572
|
+
this.vendorId = vendorId2;
|
|
2573
|
+
this.source = source;
|
|
2574
|
+
this.candidate = candidate;
|
|
2575
|
+
this.startTimeoutMs = startTimeoutMs;
|
|
2576
|
+
}
|
|
2577
|
+
vendorId;
|
|
2578
|
+
source;
|
|
2579
|
+
candidate;
|
|
2580
|
+
startTimeoutMs;
|
|
2581
|
+
processDocument = null;
|
|
2582
|
+
/** `BATON_CANDIDATE`'s read; requests wait for it. */
|
|
2583
|
+
ready = Promise.resolve();
|
|
2584
|
+
isReady = true;
|
|
2585
|
+
// id -> its document, `null` for an unknown id, `PENDING`, or the time a failed read may be tried again.
|
|
2586
|
+
held = /* @__PURE__ */ new Map();
|
|
2587
|
+
// A 403 is about the key, so it answers every id for this process.
|
|
2588
|
+
refused = false;
|
|
2589
|
+
stopped = false;
|
|
2590
|
+
retryAfterMs = REQUEST_TIMEOUT_MS;
|
|
2591
|
+
start() {
|
|
2592
|
+
const candidate = this.candidate;
|
|
2593
|
+
if (candidate !== null && this.processDocument === null) {
|
|
2594
|
+
const cannotLoad = (why) => warn(`baton: ${CANDIDATE_ENV}=${candidate} could not be loaded (${why}); today's settings apply.`);
|
|
2595
|
+
const fetched = this.source.fetchCandidate(candidate, this.startTimeoutMs);
|
|
2596
|
+
this.isReady = false;
|
|
2597
|
+
this.ready = raceDeadline(fetched, this.startTimeoutMs).then((read) => {
|
|
2598
|
+
this.isReady = true;
|
|
2599
|
+
if (this.stopped) return;
|
|
2600
|
+
if (read === TIMED_OUT) {
|
|
2601
|
+
cannotLoad("no answer");
|
|
2602
|
+
void fetched.then((late) => {
|
|
2603
|
+
if (!this.stopped && late.outcome === "refused") this.record(candidate, late);
|
|
2604
|
+
});
|
|
2605
|
+
return;
|
|
2606
|
+
}
|
|
2607
|
+
this.record(candidate, read);
|
|
2608
|
+
if (read.outcome === "loaded") this.processDocument = read.document;
|
|
2609
|
+
else if (read.outcome !== "refused") cannotLoad(read.outcome === "unknown" ? "unknown id" : "no answer");
|
|
2610
|
+
});
|
|
2414
2611
|
}
|
|
2415
|
-
|
|
2612
|
+
this.source.start();
|
|
2416
2613
|
}
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
|
|
2421
|
-
var OBSERVED_HEADERS = ["user-agent", "x-anthropic-client"];
|
|
2422
|
-
var CLIENT_INFO_MAX_LEN = 128;
|
|
2423
|
-
var HEADER_VALUE_MAX_LEN = 256;
|
|
2424
|
-
var hasText = (value) => typeof value === "string" && value !== "";
|
|
2425
|
-
function declared(info) {
|
|
2426
|
-
if (!info || typeof info !== "object") return void 0;
|
|
2427
|
-
const { name, version } = info;
|
|
2428
|
-
return hasText(name) || hasText(version) ? { name, version } : void 0;
|
|
2429
|
-
}
|
|
2430
|
-
function declaredOnRequest(extra) {
|
|
2431
|
-
for (const source of [extraEnvelope(extra), extraMeta(extra)]) {
|
|
2432
|
-
const found = declared(source?.[CLIENT_INFO_META_KEY]);
|
|
2433
|
-
if (found) return found;
|
|
2614
|
+
stop() {
|
|
2615
|
+
this.stopped = true;
|
|
2616
|
+
this.source.stop();
|
|
2434
2617
|
}
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
if (!server) return void 0;
|
|
2439
|
-
const inner = server.server;
|
|
2440
|
-
const holder = inner ?? server;
|
|
2441
|
-
if (typeof holder.getClientVersion !== "function") return void 0;
|
|
2442
|
-
return declared(holder.getClientVersion());
|
|
2443
|
-
}
|
|
2444
|
-
function observedInfo(extra, options) {
|
|
2445
|
-
return cleanInfo(declaredOnRequest(extra) ?? declaredOnConnection(options.server), options.scrubber);
|
|
2446
|
-
}
|
|
2447
|
-
function cleanInfo(sent, scrubber) {
|
|
2448
|
-
const info = {};
|
|
2449
|
-
const name = clean(sent?.name, scrubber, CLIENT_INFO_MAX_LEN);
|
|
2450
|
-
const version = clean(sent?.version, scrubber, CLIENT_INFO_MAX_LEN);
|
|
2451
|
-
if (name !== void 0) info.name = name;
|
|
2452
|
-
if (version !== void 0) info.version = version;
|
|
2453
|
-
return Object.keys(info).length > 0 ? info : void 0;
|
|
2454
|
-
}
|
|
2455
|
-
function cleanHeaders(sent, scrubber) {
|
|
2456
|
-
const headers = {};
|
|
2457
|
-
for (const header of OBSERVED_HEADERS) {
|
|
2458
|
-
const value = clean(sent?.get(header), scrubber, HEADER_VALUE_MAX_LEN);
|
|
2459
|
-
if (value !== void 0) headers[header] = value;
|
|
2618
|
+
/** The document for a request with no header of its own. */
|
|
2619
|
+
get document() {
|
|
2620
|
+
return this.processDocument ?? this.source.document;
|
|
2460
2621
|
}
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
return
|
|
2472
|
-
} catch {
|
|
2473
|
-
return void 0;
|
|
2622
|
+
/** `undefined` while no document is held, and the config's values apply. */
|
|
2623
|
+
forCaller(caller) {
|
|
2624
|
+
const document = caller.candidate == null ? this.document : this.headerDocument(caller.candidate) ?? this.source.document;
|
|
2625
|
+
return document?.settingsFor(caller, this.vendorId);
|
|
2626
|
+
}
|
|
2627
|
+
/** Whether `test` holds for some document a request could be served under now. */
|
|
2628
|
+
someDocument(test) {
|
|
2629
|
+
const today = this.document;
|
|
2630
|
+
if (today !== null && test(today)) return true;
|
|
2631
|
+
for (const held of this.held.values()) if (held instanceof SettingsDocument && test(held)) return true;
|
|
2632
|
+
return false;
|
|
2474
2633
|
}
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2634
|
+
/** The header's change if it is held. The first sight of an id starts its
|
|
2635
|
+
* read in the background, unless too many are already running. */
|
|
2636
|
+
headerDocument(candidate) {
|
|
2637
|
+
if (this.refused) return null;
|
|
2638
|
+
const held = this.held.get(candidate);
|
|
2639
|
+
if (held !== void 0 && !(typeof held === "number" && held <= Date.now())) {
|
|
2640
|
+
this.held.delete(candidate);
|
|
2641
|
+
this.held.set(candidate, held);
|
|
2642
|
+
return held instanceof SettingsDocument ? held : null;
|
|
2643
|
+
}
|
|
2644
|
+
if ([...this.held.values()].filter((v) => v === PENDING).length >= CANDIDATE_READS_AT_ONCE) return null;
|
|
2645
|
+
this.held.delete(candidate);
|
|
2646
|
+
this.held.set(candidate, PENDING);
|
|
2647
|
+
this.evict();
|
|
2648
|
+
void this.source.fetchCandidate(candidate, REQUEST_TIMEOUT_MS).then((read) => {
|
|
2649
|
+
if (!this.stopped) this.record(candidate, read);
|
|
2650
|
+
});
|
|
2651
|
+
return null;
|
|
2490
2652
|
}
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2653
|
+
record(candidate, read) {
|
|
2654
|
+
if (read.outcome === "refused") {
|
|
2655
|
+
if (!this.refused) {
|
|
2656
|
+
warn("baton: this server's key is not a test key, so test changes are not fetched; today's settings apply.");
|
|
2657
|
+
}
|
|
2658
|
+
this.held.delete(candidate);
|
|
2659
|
+
this.refused = true;
|
|
2660
|
+
} else if (read.outcome === "failed") {
|
|
2661
|
+
this.held.set(candidate, Date.now() + this.retryAfterMs);
|
|
2662
|
+
} else {
|
|
2663
|
+
this.held.set(candidate, read.outcome === "loaded" ? read.document : null);
|
|
2664
|
+
this.evict();
|
|
2498
2665
|
}
|
|
2499
|
-
return out;
|
|
2500
2666
|
}
|
|
2501
|
-
|
|
2502
|
-
const
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
if (typeof line === "string") append(out, name, line);
|
|
2667
|
+
evict() {
|
|
2668
|
+
for (const [key, value] of this.held) {
|
|
2669
|
+
if (this.held.size <= CANDIDATES_HELD) return;
|
|
2670
|
+
if (value !== PENDING) this.held.delete(key);
|
|
2506
2671
|
}
|
|
2507
2672
|
}
|
|
2508
|
-
|
|
2673
|
+
};
|
|
2674
|
+
function overlayChanges(settings, piece) {
|
|
2675
|
+
return settings?.someDocument((d) => d.audiencePieces.has(piece)) ?? false;
|
|
2509
2676
|
}
|
|
2510
|
-
function
|
|
2511
|
-
return
|
|
2512
|
-
orNothing(() => cleanInfo(declared(meta?.[CLIENT_INFO_META_KEY]) ?? declared(clientInfo), scrubber)),
|
|
2513
|
-
orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
|
|
2514
|
-
);
|
|
2677
|
+
function mayHide(settings, name) {
|
|
2678
|
+
return settings?.someDocument((d) => d.hiddenSomewhere.has(name)) ?? false;
|
|
2515
2679
|
}
|
|
2516
2680
|
|
|
2517
|
-
// src/integrations/mcp/
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
}
|
|
2522
|
-
const fromHeader = sessionIdFromHeader(extra);
|
|
2523
|
-
if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed", perCall: false };
|
|
2524
|
-
if (observeTransport(extra) === "http") {
|
|
2525
|
-
return { sessionId: `sdk-${uuid7()}`, origin: "minted", perCall: true };
|
|
2526
|
-
}
|
|
2527
|
-
return { sessionId: fallbackSessionId, origin: "minted", perCall: false };
|
|
2681
|
+
// src/integrations/mcp/mcpTypes.ts
|
|
2682
|
+
function extraAuthInfo(extra) {
|
|
2683
|
+
const found = extra.authInfo ?? extra.http?.authInfo;
|
|
2684
|
+
return found !== null && typeof found === "object" ? found : null;
|
|
2528
2685
|
}
|
|
2529
|
-
function
|
|
2686
|
+
function extraMeta(extra) {
|
|
2687
|
+
const direct = extra._meta;
|
|
2688
|
+
if (direct) return direct;
|
|
2689
|
+
const nested = extra.mcpReq?._meta;
|
|
2690
|
+
return nested ?? null;
|
|
2691
|
+
}
|
|
2692
|
+
function extraEnvelope(extra) {
|
|
2693
|
+
const envelope = extra.mcpReq?.envelope;
|
|
2694
|
+
return envelope ?? null;
|
|
2695
|
+
}
|
|
2696
|
+
function observeTransport(extra) {
|
|
2530
2697
|
try {
|
|
2531
|
-
const
|
|
2532
|
-
return
|
|
2698
|
+
const carrier = extra.http?.req ?? extra.requestInfo;
|
|
2699
|
+
return carrier ? "http" : "no-http-request";
|
|
2533
2700
|
} catch {
|
|
2534
|
-
return
|
|
2701
|
+
return "read-failed";
|
|
2535
2702
|
}
|
|
2536
2703
|
}
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
}
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
server.registerTool(
|
|
2556
|
-
tool.name,
|
|
2557
|
-
{ description: tool.description, inputSchema: ANNOTATION_INPUT_SHAPE },
|
|
2558
|
-
tool.handler
|
|
2559
|
-
);
|
|
2560
|
-
return tool.name;
|
|
2561
|
-
}
|
|
2562
|
-
var ANNOTATION_ARGS = z2.object(ANNOTATION_INPUT_SHAPE);
|
|
2563
|
-
function annotationInputJsonSchema(major) {
|
|
2564
|
-
return annotationJsonSchemas[major] ??= (major === 2 ? standardInputJsonSchema(ANNOTATION_ARGS) : void 0) ?? toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
|
|
2565
|
-
}
|
|
2566
|
-
var annotationJsonSchemas = {};
|
|
2567
|
-
function callAnnotationTool(tool, args, extra) {
|
|
2568
|
-
const parsed = ANNOTATION_ARGS.safeParse(args ?? {});
|
|
2569
|
-
if (parsed.success) return tool.handler(parsed.data, extra);
|
|
2570
|
-
return Promise.resolve({
|
|
2571
|
-
content: [{ type: "text", text: `Invalid arguments for tool ${tool.name}: ${parsed.error.message}` }],
|
|
2572
|
-
isError: true
|
|
2573
|
-
});
|
|
2574
|
-
}
|
|
2575
|
-
function buildAnnotationTool(server, options) {
|
|
2576
|
-
const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
|
|
2577
|
-
const description = buildAnnotationToolDescription({
|
|
2578
|
-
vendorDisplayName: options.vendorDisplayName
|
|
2579
|
-
});
|
|
2580
|
-
const refusal = buildRefusalText({ annotationToolName: name });
|
|
2581
|
-
return {
|
|
2582
|
-
name,
|
|
2583
|
-
description,
|
|
2584
|
-
handler: async (args, extra) => {
|
|
2585
|
-
const whatHappened = args.what_happened;
|
|
2586
|
-
if (!isReport(whatHappened)) {
|
|
2587
|
-
return {
|
|
2588
|
-
content: [
|
|
2589
|
-
{
|
|
2590
|
-
type: "text",
|
|
2591
|
-
text: JSON.stringify({
|
|
2592
|
-
ok: false,
|
|
2593
|
-
error: refusal
|
|
2594
|
-
})
|
|
2595
|
-
}
|
|
2596
|
-
]
|
|
2597
|
-
};
|
|
2598
|
-
}
|
|
2599
|
-
const reportedTool = args.tool_name ?? null;
|
|
2600
|
-
const meta = extraMeta(extra);
|
|
2601
|
-
const scrubbedMeta = scrubOrNull(
|
|
2602
|
-
options.scrubber,
|
|
2603
|
-
meta ? roundMetaCoordinates(meta) : null,
|
|
2604
|
-
"_meta"
|
|
2605
|
-
);
|
|
2606
|
-
const session = await resolveSessionId(options.fallbackSessionId, extra);
|
|
2607
|
-
const client = observeClient(extra, { server, scrubber: options.scrubber });
|
|
2608
|
-
const caller = await resolveCaller(
|
|
2609
|
-
options.resolvePrincipal,
|
|
2610
|
-
{ extra, toolName: name, arguments: args },
|
|
2611
|
-
options.captureSettings,
|
|
2612
|
-
client
|
|
2613
|
-
);
|
|
2614
|
-
await emit(
|
|
2615
|
-
options.sink,
|
|
2616
|
-
() => AnnotationEventSchema.parse({
|
|
2617
|
-
tenant_id: options.tenantId,
|
|
2618
|
-
vendor_id: options.vendorId,
|
|
2619
|
-
session_id: session.sessionId,
|
|
2620
|
-
sequence_number: options.counter.nextFor(session),
|
|
2621
|
-
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2622
|
-
consent_token: options.consentToken,
|
|
2623
|
-
...callerEnvelope(caller),
|
|
2624
|
-
transport_observed: observeTransport(extra),
|
|
2625
|
-
session_id_origin: session.origin,
|
|
2626
|
-
client_observed: client,
|
|
2627
|
-
runtime_meta: scrubbedMeta,
|
|
2628
|
-
payload: {
|
|
2629
|
-
// The agent-facing `user_goal` is stored as the wire key `intent`.
|
|
2630
|
-
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
2631
|
-
intent: options.scrubber(args.user_goal),
|
|
2632
|
-
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
2633
|
-
what_happened: options.scrubber(whatHappened),
|
|
2634
|
-
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
2635
|
-
tool_name: reportedTool ? options.scrubber(reportedTool) : reportedTool,
|
|
2636
|
-
suggested_improvement: args.suggested_improvement ? options.scrubber(args.suggested_improvement) : null,
|
|
2637
|
-
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
2638
|
-
context: args.context ? options.scrubber(args.context) : null
|
|
2639
|
-
}
|
|
2640
|
-
})
|
|
2641
|
-
);
|
|
2642
|
-
return { content: [{ type: "text", text: JSON.stringify({ ok: true }) }] };
|
|
2643
|
-
}
|
|
2644
|
-
};
|
|
2645
|
-
}
|
|
2646
|
-
|
|
2647
|
-
// src/dsn.ts
|
|
2648
|
-
var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
|
|
2649
|
-
var WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;
|
|
2650
|
-
var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
|
|
2651
|
-
var NOT_IN_A_KEY = /[\x00\t\n\r]/;
|
|
2652
|
-
var PUBLISHABLE_PREFIX = "baton_pk_";
|
|
2653
|
-
var SECRET_PREFIX = "baton_sk_";
|
|
2654
|
-
var KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;
|
|
2655
|
-
function looksLikeAKey(value) {
|
|
2656
|
-
return value.startsWith(PUBLISHABLE_PREFIX) || value.startsWith(SECRET_PREFIX);
|
|
2704
|
+
function extraHeaders(extra) {
|
|
2705
|
+
const fromV2 = extra.http?.req?.headers;
|
|
2706
|
+
if (fromV2 && typeof fromV2.get === "function") return fromV2;
|
|
2707
|
+
const fromV1 = extra.requestInfo?.headers;
|
|
2708
|
+
if (fromV1 && typeof fromV1 === "object") {
|
|
2709
|
+
const headers = new Headers();
|
|
2710
|
+
for (const [name, value] of Object.entries(fromV1)) {
|
|
2711
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
2712
|
+
if (typeof item !== "string") continue;
|
|
2713
|
+
try {
|
|
2714
|
+
headers.append(name, item);
|
|
2715
|
+
} catch {
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2718
|
+
}
|
|
2719
|
+
return headers;
|
|
2720
|
+
}
|
|
2721
|
+
return null;
|
|
2657
2722
|
}
|
|
2658
|
-
function
|
|
2659
|
-
return
|
|
2723
|
+
function isThenable(value) {
|
|
2724
|
+
return typeof value?.then === "function";
|
|
2660
2725
|
}
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
if (schemeEnd === -1) return null;
|
|
2665
|
-
const scheme = raw.slice(0, schemeEnd).toLowerCase();
|
|
2666
|
-
const rest = raw.slice(schemeEnd + 3);
|
|
2667
|
-
const end = rest.search(/[/?#]/);
|
|
2668
|
-
if (end === -1) return { scheme, netloc: rest, slash: "", path: "" };
|
|
2669
|
-
const netloc = rest.slice(0, end);
|
|
2670
|
-
if (rest[end] !== "/") {
|
|
2671
|
-
return { scheme, netloc, slash: "", path: "" };
|
|
2672
|
-
}
|
|
2673
|
-
const afterSlash = rest.slice(end + 1);
|
|
2674
|
-
const pathEnd = afterSlash.search(/[?#]/);
|
|
2726
|
+
|
|
2727
|
+
// src/integrations/mcp/principalResolution.ts
|
|
2728
|
+
function buildPrincipalResolutionContext(extra, toolName, args) {
|
|
2675
2729
|
return {
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2730
|
+
headers: extraHeaders(extra),
|
|
2731
|
+
meta: extraMeta(extra),
|
|
2732
|
+
toolName,
|
|
2733
|
+
arguments: args,
|
|
2734
|
+
authInfo: extraAuthInfo(extra)
|
|
2680
2735
|
};
|
|
2681
2736
|
}
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
if (
|
|
2737
|
+
var HOOK_TIMEOUT_MS = 5e3;
|
|
2738
|
+
async function withinHookBudget(answer) {
|
|
2739
|
+
if (!isThenable(answer)) return answer;
|
|
2740
|
+
const first = await raceDeadline(answer, HOOK_TIMEOUT_MS);
|
|
2741
|
+
if (first !== TIMED_OUT) return first;
|
|
2742
|
+
warn(
|
|
2743
|
+
`baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
|
|
2744
|
+
);
|
|
2745
|
+
return null;
|
|
2746
|
+
}
|
|
2747
|
+
var warned2 = /* @__PURE__ */ new Set();
|
|
2748
|
+
function warnOnce(key, message) {
|
|
2749
|
+
if (warned2.has(key)) return;
|
|
2750
|
+
warned2.add(key);
|
|
2751
|
+
warn(`baton: resolvePrincipal ${message}`);
|
|
2752
|
+
}
|
|
2753
|
+
function callerEnvelope(caller) {
|
|
2685
2754
|
return {
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2755
|
+
principal: caller.principal,
|
|
2756
|
+
organization: caller.organization,
|
|
2757
|
+
labels: wireLabels(caller.labels),
|
|
2758
|
+
capture: caller.settings?.capture ?? null
|
|
2689
2759
|
};
|
|
2690
2760
|
}
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2761
|
+
var settingsWarned = false;
|
|
2762
|
+
async function resolveCaller(hook, call, settings, client = null) {
|
|
2763
|
+
const caller = await resolveIdentity(hook, call);
|
|
2764
|
+
if (settings === void 0) return caller;
|
|
2765
|
+
try {
|
|
2766
|
+
const callSettings = settings.forCaller({
|
|
2767
|
+
labels: caller.labels,
|
|
2768
|
+
clientName: client?.info?.name ?? null,
|
|
2769
|
+
shareKey: caller.principal?.id ?? null,
|
|
2770
|
+
candidate: headerCandidate(extraHeaders(call.extra))
|
|
2771
|
+
});
|
|
2772
|
+
return callSettings === void 0 ? caller : { ...caller, settings: callSettings };
|
|
2773
|
+
} catch {
|
|
2774
|
+
if (!settingsWarned) {
|
|
2775
|
+
settingsWarned = true;
|
|
2776
|
+
warn("baton: applying capture settings failed; this request uses the config's values");
|
|
2777
|
+
}
|
|
2778
|
+
return caller;
|
|
2779
|
+
}
|
|
2697
2780
|
}
|
|
2698
|
-
function
|
|
2699
|
-
|
|
2781
|
+
async function resolveIdentity(hook, call) {
|
|
2782
|
+
if (hook === void 0) return NO_CALLER;
|
|
2783
|
+
try {
|
|
2784
|
+
const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
|
|
2785
|
+
const result = await withinHookBudget(hook(context));
|
|
2786
|
+
return callerFor(result, warnOnce);
|
|
2787
|
+
} catch {
|
|
2788
|
+
return NO_CALLER;
|
|
2789
|
+
}
|
|
2700
2790
|
}
|
|
2701
|
-
|
|
2702
|
-
|
|
2791
|
+
|
|
2792
|
+
// src/integrations/mcp/zodCompat.ts
|
|
2793
|
+
import * as z3rt from "zod/v3";
|
|
2794
|
+
import * as z4mini from "zod/v4-mini";
|
|
2795
|
+
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
2796
|
+
function isZ4Schema(s) {
|
|
2797
|
+
const schema = s;
|
|
2798
|
+
return !!schema?._zod;
|
|
2703
2799
|
}
|
|
2704
|
-
function
|
|
2705
|
-
const
|
|
2706
|
-
|
|
2800
|
+
function objectFromShape(shape) {
|
|
2801
|
+
const values = Object.values(shape);
|
|
2802
|
+
if (values.length === 0) return z4mini.object({});
|
|
2803
|
+
const allV4 = values.every(isZ4Schema);
|
|
2804
|
+
const allV3 = values.every((s) => !isZ4Schema(s));
|
|
2805
|
+
if (allV4) return z4mini.object(shape);
|
|
2806
|
+
if (allV3) return z3rt.object(shape);
|
|
2807
|
+
throw new Error("Mixed Zod versions detected in object shape.");
|
|
2707
2808
|
}
|
|
2708
|
-
function
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
}
|
|
2716
|
-
return explicit;
|
|
2809
|
+
function getObjectShape(schema) {
|
|
2810
|
+
if (!schema) return void 0;
|
|
2811
|
+
let rawShape;
|
|
2812
|
+
if (isZ4Schema(schema)) {
|
|
2813
|
+
rawShape = schema._zod?.def?.shape;
|
|
2814
|
+
} else {
|
|
2815
|
+
rawShape = schema.shape;
|
|
2717
2816
|
}
|
|
2718
|
-
|
|
2719
|
-
if (
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2817
|
+
if (!rawShape) return void 0;
|
|
2818
|
+
if (typeof rawShape === "function") {
|
|
2819
|
+
try {
|
|
2820
|
+
return rawShape();
|
|
2821
|
+
} catch {
|
|
2822
|
+
return void 0;
|
|
2823
|
+
}
|
|
2725
2824
|
}
|
|
2726
|
-
return
|
|
2825
|
+
return rawShape;
|
|
2727
2826
|
}
|
|
2728
|
-
function
|
|
2729
|
-
|
|
2730
|
-
if (
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
);
|
|
2740
|
-
}
|
|
2741
|
-
const { key, at, authority } = splitKeyFromAuthority(parts.netloc);
|
|
2742
|
-
if (!at || !key) {
|
|
2743
|
-
if (looksLikeAKey(parts.netloc)) {
|
|
2744
|
-
fail(
|
|
2745
|
-
`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`
|
|
2746
|
-
);
|
|
2827
|
+
function normalizeObjectSchema(schema) {
|
|
2828
|
+
if (!schema) return void 0;
|
|
2829
|
+
if (typeof schema === "object") {
|
|
2830
|
+
const asAny = schema;
|
|
2831
|
+
if (!asAny._def && !asAny._zod) {
|
|
2832
|
+
const values = Object.values(schema);
|
|
2833
|
+
if (values.length > 0 && values.every(
|
|
2834
|
+
(v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function")
|
|
2835
|
+
)) {
|
|
2836
|
+
return objectFromShape(schema);
|
|
2837
|
+
}
|
|
2747
2838
|
}
|
|
2748
|
-
const misplaced = parts.path.split("/").some((segment) => containsKey(segment));
|
|
2749
|
-
const detail = misplaced ? "the key is in the PATH \u2014 it goes before an @" : "the value from /account has the key before an @";
|
|
2750
|
-
fail(
|
|
2751
|
-
`dsn ${safe} carries no key: ${detail}, as in https://baton_pk_...@host/ten_.../server`
|
|
2752
|
-
);
|
|
2753
2839
|
}
|
|
2754
|
-
if (
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2840
|
+
if (isZ4Schema(schema)) {
|
|
2841
|
+
const def = schema._zod?.def;
|
|
2842
|
+
if (def && (def.type === "object" || def.shape !== void 0)) return schema;
|
|
2843
|
+
} else {
|
|
2844
|
+
if (schema.shape !== void 0) return schema;
|
|
2758
2845
|
}
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2846
|
+
return void 0;
|
|
2847
|
+
}
|
|
2848
|
+
function mapMiniTarget(t) {
|
|
2849
|
+
if (!t) return "draft-7";
|
|
2850
|
+
if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
|
|
2851
|
+
if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
|
|
2852
|
+
return "draft-7";
|
|
2853
|
+
}
|
|
2854
|
+
function toJsonSchemaCompat(schema, opts) {
|
|
2855
|
+
if (isZ4Schema(schema)) {
|
|
2856
|
+
return z4mini.toJSONSchema(schema, {
|
|
2857
|
+
target: mapMiniTarget(opts?.target),
|
|
2858
|
+
io: opts?.pipeStrategy ?? "input"
|
|
2859
|
+
});
|
|
2763
2860
|
}
|
|
2764
|
-
|
|
2765
|
-
|
|
2861
|
+
return zodToJsonSchema(schema, {
|
|
2862
|
+
strictUnions: opts?.strictUnions ?? true,
|
|
2863
|
+
pipeStrategy: opts?.pipeStrategy ?? "input"
|
|
2864
|
+
});
|
|
2865
|
+
}
|
|
2866
|
+
|
|
2867
|
+
// src/integrations/mcp/schemaCompat.ts
|
|
2868
|
+
import { z as zV4 } from "zod";
|
|
2869
|
+
import { z as zV3 } from "zod/v3";
|
|
2870
|
+
var DEFAULT_INTENT_PARAM_MODE = "required";
|
|
2871
|
+
var ROOT_COMBINERS = ["$ref", "oneOf", "anyOf", "allOf"];
|
|
2872
|
+
function takesUserGoalJson(schema) {
|
|
2873
|
+
const properties = schema.properties ?? {};
|
|
2874
|
+
return isRecord(properties) && !ROOT_COMBINERS.some((key) => key in schema);
|
|
2875
|
+
}
|
|
2876
|
+
function withUserGoalJson(schema, intentParamMode, listRequired) {
|
|
2877
|
+
if (!takesUserGoalJson(schema) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return schema;
|
|
2878
|
+
const properties = schema.properties ?? {};
|
|
2879
|
+
const goal = { type: "string", description: buildUserGoalParamDescription({ intentParamMode }) };
|
|
2880
|
+
const served = { ...schema, properties: { ...properties, [USER_GOAL_PARAM_NAME]: goal } };
|
|
2881
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
2882
|
+
if (listRequired && !required.includes(USER_GOAL_PARAM_NAME)) served.required = [...required, USER_GOAL_PARAM_NAME];
|
|
2883
|
+
return served;
|
|
2884
|
+
}
|
|
2885
|
+
var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
|
|
2886
|
+
function injectGoalParams(inputSchema2, intentParamMode) {
|
|
2887
|
+
const objSchema = normalizeObjectSchema(inputSchema2);
|
|
2888
|
+
if (!objSchema) return { schema: inputSchema2, dispositions: {} };
|
|
2889
|
+
const existingShape = getObjectShape(objSchema) ?? {};
|
|
2890
|
+
const values = Object.values(existingShape);
|
|
2891
|
+
const useV4 = values.length === 0 || isZ4Schema(values[0]);
|
|
2892
|
+
const zodImpl = useV4 ? zV4 : zV3;
|
|
2893
|
+
const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
|
|
2894
|
+
if (Object.keys(toInject).length === 0)
|
|
2895
|
+
return { schema: inputSchema2, dispositions };
|
|
2896
|
+
const mergedShape = { ...existingShape, ...toInject };
|
|
2897
|
+
const newSchema = objectFromShape(mergedShape);
|
|
2898
|
+
return { schema: newSchema, dispositions };
|
|
2899
|
+
}
|
|
2900
|
+
function buildIntentFields(existingShape, zodImpl, intentParamMode) {
|
|
2901
|
+
const dispositions = {};
|
|
2902
|
+
const toInject = {};
|
|
2903
|
+
for (const name of RETIRED_PARAM_NAMES) {
|
|
2904
|
+
if (name in existingShape) dispositions[name] = "native";
|
|
2766
2905
|
}
|
|
2767
|
-
if (
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2906
|
+
if (USER_GOAL_PARAM_NAME in existingShape) {
|
|
2907
|
+
dispositions[USER_GOAL_PARAM_NAME] = "native";
|
|
2908
|
+
} else {
|
|
2909
|
+
dispositions[USER_GOAL_PARAM_NAME] = "injected";
|
|
2910
|
+
toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
|
|
2771
2911
|
}
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2912
|
+
return { dispositions, toInject };
|
|
2913
|
+
}
|
|
2914
|
+
function injectGoalParamsV2(inputSchema2, intentParamMode) {
|
|
2915
|
+
const candidate = inputSchema2;
|
|
2916
|
+
const shape = candidate?.shape;
|
|
2917
|
+
if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
|
|
2918
|
+
return { schema: inputSchema2, dispositions: {} };
|
|
2776
2919
|
}
|
|
2777
|
-
|
|
2778
|
-
|
|
2920
|
+
const { dispositions, toInject } = buildIntentFields(shape, zV4, intentParamMode);
|
|
2921
|
+
if (Object.keys(toInject).length === 0)
|
|
2922
|
+
return { schema: inputSchema2, dispositions };
|
|
2923
|
+
return { schema: candidate.extend(toInject), dispositions };
|
|
2924
|
+
}
|
|
2925
|
+
function advertiseIntentParamsRequired(result, names, isInjected) {
|
|
2926
|
+
const tools = result?.tools;
|
|
2927
|
+
if (!Array.isArray(tools)) return result;
|
|
2928
|
+
let changed = false;
|
|
2929
|
+
const advertised = tools.map((tool) => {
|
|
2930
|
+
const entry = tool;
|
|
2931
|
+
const toolName = entry?.name;
|
|
2932
|
+
if (typeof toolName !== "string") return tool;
|
|
2933
|
+
const schema = entry?.inputSchema;
|
|
2934
|
+
if (!schema || typeof schema !== "object") return tool;
|
|
2935
|
+
const declared2 = schema.required ?? [];
|
|
2936
|
+
if (!Array.isArray(declared2)) return tool;
|
|
2937
|
+
const required = declared2;
|
|
2938
|
+
const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
|
|
2939
|
+
if (missing.length === 0) return tool;
|
|
2940
|
+
changed = true;
|
|
2941
|
+
return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
|
|
2942
|
+
});
|
|
2943
|
+
return changed ? { ...result, tools: advertised } : result;
|
|
2944
|
+
}
|
|
2945
|
+
function withToolInputSchema(result, name, inputSchema2) {
|
|
2946
|
+
const tools = result?.tools;
|
|
2947
|
+
if (!Array.isArray(tools)) return result;
|
|
2948
|
+
const at = tools.findIndex((tool) => isRecord(tool) && tool.name === name);
|
|
2949
|
+
if (at === -1) return result;
|
|
2950
|
+
const served = [...tools];
|
|
2951
|
+
served[at] = { ...tools[at], inputSchema: inputSchema2 };
|
|
2952
|
+
return { ...result, tools: served };
|
|
2953
|
+
}
|
|
2954
|
+
function standardInputJsonSchema(schema) {
|
|
2779
2955
|
try {
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
if (parsedAuthority === null) {
|
|
2785
|
-
fail(`dsn ${safe} is not a parseable URL (${hostReason ?? "Error"})`);
|
|
2786
|
-
}
|
|
2787
|
-
const segments = parts.path.split("/").filter((segment) => segment !== "");
|
|
2788
|
-
const [workspace, server, ...extra] = segments;
|
|
2789
|
-
if (workspace === void 0 || server === void 0 || extra.length > 0) {
|
|
2790
|
-
fail(
|
|
2791
|
-
`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.`
|
|
2792
|
-
);
|
|
2956
|
+
const standard = schema?.["~standard"];
|
|
2957
|
+
return standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
|
|
2958
|
+
} catch {
|
|
2959
|
+
return void 0;
|
|
2793
2960
|
}
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
|
|
2961
|
+
}
|
|
2962
|
+
function toolInputJsonSchema(inputSchema2) {
|
|
2963
|
+
const objSchema = normalizeObjectSchema(inputSchema2);
|
|
2964
|
+
if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
|
|
2965
|
+
return toJsonSchemaCompat(objSchema, {
|
|
2966
|
+
strictUnions: true,
|
|
2967
|
+
pipeStrategy: "input"
|
|
2968
|
+
});
|
|
2969
|
+
}
|
|
2970
|
+
|
|
2971
|
+
// src/integrations/mcp/safeScrub.ts
|
|
2972
|
+
var warned3 = /* @__PURE__ */ new Set();
|
|
2973
|
+
function scrubOrNull(scrubber, value, field) {
|
|
2974
|
+
if (value === null) return null;
|
|
2975
|
+
try {
|
|
2976
|
+
return scrubber(value);
|
|
2977
|
+
} catch (err) {
|
|
2978
|
+
if (!warned3.has(field)) {
|
|
2979
|
+
warned3.add(field);
|
|
2980
|
+
stderrLine(
|
|
2981
|
+
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}`
|
|
2801
2982
|
);
|
|
2802
2983
|
}
|
|
2984
|
+
return null;
|
|
2803
2985
|
}
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
2986
|
+
}
|
|
2987
|
+
|
|
2988
|
+
// src/integrations/mcp/clientObserved.ts
|
|
2989
|
+
var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
|
|
2990
|
+
var OBSERVED_HEADERS = ["user-agent", "x-anthropic-client"];
|
|
2991
|
+
var CLIENT_INFO_MAX_LEN = 128;
|
|
2992
|
+
var HEADER_VALUE_MAX_LEN = 256;
|
|
2993
|
+
var hasText = (value) => typeof value === "string" && value !== "";
|
|
2994
|
+
function declared(info) {
|
|
2995
|
+
if (!info || typeof info !== "object") return void 0;
|
|
2996
|
+
const { name, version } = info;
|
|
2997
|
+
return hasText(name) || hasText(version) ? { name, version } : void 0;
|
|
2998
|
+
}
|
|
2999
|
+
function declaredOnRequest(extra) {
|
|
3000
|
+
for (const source of [extraEnvelope(extra), extraMeta(extra)]) {
|
|
3001
|
+
const found = declared(source?.[CLIENT_INFO_META_KEY]);
|
|
3002
|
+
if (found) return found;
|
|
2818
3003
|
}
|
|
2819
|
-
return
|
|
2820
|
-
origin: `${parts.scheme}://${authority}`,
|
|
2821
|
-
tenantId: workspace,
|
|
2822
|
-
vendorId: server,
|
|
2823
|
-
key
|
|
2824
|
-
});
|
|
3004
|
+
return void 0;
|
|
2825
3005
|
}
|
|
2826
|
-
function
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
};
|
|
2833
|
-
Object.defineProperty(dsn, "toJSON", {
|
|
2834
|
-
value: () => shown,
|
|
2835
|
-
enumerable: false
|
|
2836
|
-
});
|
|
2837
|
-
Object.defineProperty(dsn, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
|
|
2838
|
-
value: () => shown,
|
|
2839
|
-
enumerable: false
|
|
2840
|
-
});
|
|
2841
|
-
return dsn;
|
|
3006
|
+
function declaredOnConnection(server) {
|
|
3007
|
+
if (!server) return void 0;
|
|
3008
|
+
const inner = server.server;
|
|
3009
|
+
const holder = inner ?? server;
|
|
3010
|
+
if (typeof holder.getClientVersion !== "function") return void 0;
|
|
3011
|
+
return declared(holder.getClientVersion());
|
|
2842
3012
|
}
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
var TOOL_ERROR_TYPE = "tool_error";
|
|
2846
|
-
var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
|
|
2847
|
-
var REFUSED = "refused";
|
|
2848
|
-
var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
|
|
2849
|
-
function requestSideFailureKind(entry, validation) {
|
|
2850
|
-
if (entry == null) return "unknown_tool";
|
|
2851
|
-
if (entry.enabled === false) return "tool_disabled";
|
|
2852
|
-
if (validation === "rejected") return "invalid_argument";
|
|
2853
|
-
if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
|
|
2854
|
-
return REFUSED;
|
|
3013
|
+
function observedInfo(extra, options) {
|
|
3014
|
+
return cleanInfo(declaredOnRequest(extra) ?? declaredOnConnection(options.server), options.scrubber);
|
|
2855
3015
|
}
|
|
2856
|
-
|
|
2857
|
-
|
|
3016
|
+
function cleanInfo(sent, scrubber) {
|
|
3017
|
+
const info = {};
|
|
3018
|
+
const name = clean(sent?.name, scrubber, CLIENT_INFO_MAX_LEN);
|
|
3019
|
+
const version = clean(sent?.version, scrubber, CLIENT_INFO_MAX_LEN);
|
|
3020
|
+
if (name !== void 0) info.name = name;
|
|
3021
|
+
if (version !== void 0) info.version = version;
|
|
3022
|
+
return Object.keys(info).length > 0 ? info : void 0;
|
|
3023
|
+
}
|
|
3024
|
+
function cleanHeaders(sent, scrubber) {
|
|
3025
|
+
const headers = {};
|
|
3026
|
+
for (const header of OBSERVED_HEADERS) {
|
|
3027
|
+
const value = clean(sent?.get(header), scrubber, HEADER_VALUE_MAX_LEN);
|
|
3028
|
+
if (value !== void 0) headers[header] = value;
|
|
3029
|
+
}
|
|
3030
|
+
return Object.keys(headers).length > 0 ? headers : void 0;
|
|
3031
|
+
}
|
|
3032
|
+
function clean(value, scrubber, max) {
|
|
3033
|
+
if (!hasText(value)) return void 0;
|
|
3034
|
+
const scrubbed = scrubOrNull(scrubber, value, "client_observed");
|
|
3035
|
+
if (!hasText(scrubbed)) return void 0;
|
|
3036
|
+
return capCodePoints(scrubbed, max);
|
|
3037
|
+
}
|
|
3038
|
+
function orNothing(read) {
|
|
2858
3039
|
try {
|
|
2859
|
-
|
|
2860
|
-
return Boolean(value.isError);
|
|
3040
|
+
return read();
|
|
2861
3041
|
} catch {
|
|
2862
|
-
return
|
|
3042
|
+
return void 0;
|
|
2863
3043
|
}
|
|
2864
3044
|
}
|
|
2865
|
-
function
|
|
2866
|
-
|
|
3045
|
+
function assemble(info, headers) {
|
|
3046
|
+
if (info === void 0 && headers === void 0) return null;
|
|
3047
|
+
return { ...info && { info }, ...headers && { headers } };
|
|
3048
|
+
}
|
|
3049
|
+
function observeClient(extra, options) {
|
|
3050
|
+
return assemble(
|
|
3051
|
+
orNothing(() => observedInfo(extra, options)),
|
|
3052
|
+
orNothing(() => cleanHeaders(extraHeaders(extra), options.scrubber))
|
|
3053
|
+
);
|
|
3054
|
+
}
|
|
3055
|
+
function append(headers, name, value) {
|
|
2867
3056
|
try {
|
|
2868
|
-
|
|
2869
|
-
if (!Array.isArray(content)) return "";
|
|
2870
|
-
for (const part of content) {
|
|
2871
|
-
const text = part?.text;
|
|
2872
|
-
if (typeof text !== "string") continue;
|
|
2873
|
-
const trimmed = stripWhiteSpace(text);
|
|
2874
|
-
if (trimmed) parts.push(trimmed);
|
|
2875
|
-
}
|
|
3057
|
+
headers.append(name, value);
|
|
2876
3058
|
} catch {
|
|
2877
|
-
return "";
|
|
2878
3059
|
}
|
|
2879
|
-
return parts.join("\n");
|
|
2880
3060
|
}
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
3061
|
+
function registeredHeaders(input) {
|
|
3062
|
+
const out = new Headers();
|
|
3063
|
+
if (typeof input.get === "function") {
|
|
3064
|
+
for (const name of OBSERVED_HEADERS) {
|
|
3065
|
+
const value = input.get(name);
|
|
3066
|
+
if (typeof value === "string") append(out, name, value);
|
|
3067
|
+
}
|
|
3068
|
+
return out;
|
|
3069
|
+
}
|
|
3070
|
+
for (const [key, value] of Object.entries(input)) {
|
|
3071
|
+
const name = key.toLowerCase();
|
|
3072
|
+
if (!OBSERVED_HEADERS.includes(name)) continue;
|
|
3073
|
+
for (const line of typeof value === "string" ? [value] : Array.isArray(value) ? value : []) {
|
|
3074
|
+
if (typeof line === "string") append(out, name, line);
|
|
3075
|
+
}
|
|
2889
3076
|
}
|
|
3077
|
+
return out;
|
|
3078
|
+
}
|
|
3079
|
+
function clientObservedFrom(clientInfo, headers, scrubber, meta) {
|
|
3080
|
+
return assemble(
|
|
3081
|
+
orNothing(() => cleanInfo(declared(meta?.[CLIENT_INFO_META_KEY]) ?? declared(clientInfo), scrubber)),
|
|
3082
|
+
orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
|
|
3083
|
+
);
|
|
2890
3084
|
}
|
|
2891
|
-
|
|
2892
|
-
|
|
3085
|
+
|
|
3086
|
+
// src/integrations/mcp/sessionResolution.ts
|
|
3087
|
+
async function resolveSessionId(fallbackSessionId, extra) {
|
|
3088
|
+
if (typeof extra.sessionId === "string" && extra.sessionId) {
|
|
3089
|
+
return { sessionId: extra.sessionId, origin: "observed", perCall: false };
|
|
3090
|
+
}
|
|
3091
|
+
const fromHeader = sessionIdFromHeader(extra);
|
|
3092
|
+
if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed", perCall: false };
|
|
3093
|
+
if (observeTransport(extra) === "http") {
|
|
3094
|
+
return { sessionId: `sdk-${uuid7()}`, origin: "minted", perCall: true };
|
|
3095
|
+
}
|
|
3096
|
+
return { sessionId: fallbackSessionId, origin: "minted", perCall: false };
|
|
2893
3097
|
}
|
|
2894
|
-
function
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
|
|
3098
|
+
function sessionIdFromHeader(extra) {
|
|
3099
|
+
try {
|
|
3100
|
+
const value = extraHeaders(extra)?.get("mcp-session-id");
|
|
3101
|
+
return value ? stripWhiteSpace(value) || null : null;
|
|
3102
|
+
} catch {
|
|
3103
|
+
return null;
|
|
2900
3104
|
}
|
|
2901
3105
|
}
|
|
2902
|
-
|
|
2903
|
-
|
|
3106
|
+
|
|
3107
|
+
// src/integrations/mcp/annotation.ts
|
|
3108
|
+
var TOOL_NAME_PARAM_NAME = "tool_name";
|
|
3109
|
+
var ANNOTATION_INPUT_SHAPE = {
|
|
3110
|
+
user_goal: z2.string(),
|
|
3111
|
+
what_happened: z2.string().optional(),
|
|
3112
|
+
// Nullable so a report whose agent sends an explicit null is taken,
|
|
3113
|
+
// not rejected by validation.
|
|
3114
|
+
tool_name: z2.string().nullable().optional(),
|
|
3115
|
+
suggested_improvement: z2.string().optional(),
|
|
3116
|
+
// zod renders "any value" as `{}`, which some MCP clients refuse (reportToolSchema.test.ts).
|
|
3117
|
+
context: z2.record(z2.string(), z2.unknown()).meta({ additionalProperties: true }).optional()
|
|
3118
|
+
};
|
|
3119
|
+
function isReport(whatHappened) {
|
|
3120
|
+
return typeof whatHappened === "string" && !isBlank(whatHappened);
|
|
2904
3121
|
}
|
|
2905
|
-
function
|
|
2906
|
-
|
|
3122
|
+
function registerAnnotationTool(server, options) {
|
|
3123
|
+
const tool = buildAnnotationTool(server, options);
|
|
3124
|
+
server.registerTool(
|
|
3125
|
+
tool.name,
|
|
3126
|
+
{ description: tool.description, inputSchema: ANNOTATION_INPUT_SHAPE },
|
|
3127
|
+
tool.handler
|
|
3128
|
+
);
|
|
3129
|
+
return tool.name;
|
|
2907
3130
|
}
|
|
2908
|
-
|
|
2909
|
-
|
|
3131
|
+
var ANNOTATION_ARGS = z2.object(ANNOTATION_INPUT_SHAPE);
|
|
3132
|
+
function annotationInputJsonSchema(major) {
|
|
3133
|
+
return annotationJsonSchemas[major] ??= (major === 2 ? standardInputJsonSchema(ANNOTATION_ARGS) : void 0) ?? toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
|
|
2910
3134
|
}
|
|
2911
|
-
|
|
2912
|
-
|
|
3135
|
+
var annotationJsonSchemas = {};
|
|
3136
|
+
function callAnnotationTool(tool, args, extra) {
|
|
3137
|
+
const parsed = ANNOTATION_ARGS.safeParse(args ?? {});
|
|
3138
|
+
if (parsed.success) return tool.handler(parsed.data, extra);
|
|
3139
|
+
return Promise.resolve({
|
|
3140
|
+
content: [{ type: "text", text: `Invalid arguments for tool ${tool.name}: ${parsed.error.message}` }],
|
|
3141
|
+
isError: true
|
|
3142
|
+
});
|
|
2913
3143
|
}
|
|
2914
|
-
function
|
|
2915
|
-
|
|
3144
|
+
function buildAnnotationTool(server, options) {
|
|
3145
|
+
const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
|
|
3146
|
+
const description = buildAnnotationToolDescription({
|
|
3147
|
+
vendorDisplayName: options.vendorDisplayName
|
|
3148
|
+
});
|
|
3149
|
+
const refused = (overlay) => ({
|
|
3150
|
+
content: [
|
|
3151
|
+
{
|
|
3152
|
+
type: "text",
|
|
3153
|
+
text: JSON.stringify({ ok: false, error: buildRefusalText({ annotationToolName: name, overlay }) })
|
|
3154
|
+
}
|
|
3155
|
+
]
|
|
3156
|
+
});
|
|
3157
|
+
return {
|
|
3158
|
+
name,
|
|
3159
|
+
description,
|
|
3160
|
+
handler: async (args, extra) => {
|
|
3161
|
+
const whatHappened = args.what_happened;
|
|
3162
|
+
if (!isReport(whatHappened) && !overlayChanges(options.captureSettings, "report_tool.refusal")) return refused();
|
|
3163
|
+
const reportedTool = args.tool_name ?? null;
|
|
3164
|
+
const client = observeClient(extra, { server, scrubber: options.scrubber });
|
|
3165
|
+
const caller = await resolveCaller(
|
|
3166
|
+
options.resolvePrincipal,
|
|
3167
|
+
{ extra, toolName: name, arguments: args },
|
|
3168
|
+
options.captureSettings,
|
|
3169
|
+
client
|
|
3170
|
+
);
|
|
3171
|
+
if (!isReport(whatHappened)) return refused(caller.settings?.overlay);
|
|
3172
|
+
const meta = extraMeta(extra);
|
|
3173
|
+
const scrubbedMeta = scrubOrNull(
|
|
3174
|
+
options.scrubber,
|
|
3175
|
+
meta ? roundMetaCoordinates(meta) : null,
|
|
3176
|
+
"_meta"
|
|
3177
|
+
);
|
|
3178
|
+
const session = await resolveSessionId(options.fallbackSessionId, extra);
|
|
3179
|
+
await emit(
|
|
3180
|
+
options.sink,
|
|
3181
|
+
() => AnnotationEventSchema.parse({
|
|
3182
|
+
tenant_id: options.tenantId,
|
|
3183
|
+
vendor_id: options.vendorId,
|
|
3184
|
+
session_id: session.sessionId,
|
|
3185
|
+
sequence_number: options.counter.nextFor(session),
|
|
3186
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3187
|
+
consent_token: options.consentToken,
|
|
3188
|
+
...callerEnvelope(caller),
|
|
3189
|
+
transport_observed: observeTransport(extra),
|
|
3190
|
+
session_id_origin: session.origin,
|
|
3191
|
+
client_observed: client,
|
|
3192
|
+
runtime_meta: scrubbedMeta,
|
|
3193
|
+
payload: {
|
|
3194
|
+
// The agent-facing `user_goal` is stored as the wire key `intent`.
|
|
3195
|
+
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
3196
|
+
intent: options.scrubber(args.user_goal),
|
|
3197
|
+
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
3198
|
+
what_happened: options.scrubber(whatHappened),
|
|
3199
|
+
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
3200
|
+
tool_name: reportedTool ? options.scrubber(reportedTool) : reportedTool,
|
|
3201
|
+
suggested_improvement: args.suggested_improvement ? options.scrubber(args.suggested_improvement) : null,
|
|
3202
|
+
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
3203
|
+
context: args.context ? options.scrubber(args.context) : null
|
|
3204
|
+
}
|
|
3205
|
+
})
|
|
3206
|
+
);
|
|
3207
|
+
return { content: [{ type: "text", text: JSON.stringify({ ok: true }) }] };
|
|
3208
|
+
}
|
|
3209
|
+
};
|
|
2916
3210
|
}
|
|
2917
3211
|
|
|
2918
|
-
// src/
|
|
2919
|
-
|
|
2920
|
-
var
|
|
2921
|
-
var
|
|
2922
|
-
var
|
|
2923
|
-
var
|
|
2924
|
-
var
|
|
2925
|
-
var
|
|
2926
|
-
var
|
|
2927
|
-
var
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
function shareBucket(vendorId2, key) {
|
|
2931
|
-
const digest = crypto2.createHash("sha256").update(`${vendorId2}
|
|
2932
|
-
${key}`, "utf-8").digest();
|
|
2933
|
-
return Number(digest.readBigUInt64BE(0) % 10000n);
|
|
3212
|
+
// src/dsn.ts
|
|
3213
|
+
var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
|
|
3214
|
+
var WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;
|
|
3215
|
+
var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
|
|
3216
|
+
var NOT_IN_A_KEY = /[\x00\t\n\r]/;
|
|
3217
|
+
var PUBLISHABLE_PREFIX = "baton_pk_";
|
|
3218
|
+
var SECRET_PREFIX = "baton_sk_";
|
|
3219
|
+
var TEST_PREFIX = "baton_tk_";
|
|
3220
|
+
var KEY_PREFIXES = [PUBLISHABLE_PREFIX, SECRET_PREFIX, TEST_PREFIX];
|
|
3221
|
+
var KEY_RUN = /baton_(?:(?:pk|sk|tk)_[A-Za-z0-9_%-]{8,}|[A-Za-z0-9_%-]{43,})/g;
|
|
3222
|
+
function looksLikeAKey(value) {
|
|
3223
|
+
return KEY_PREFIXES.some((prefix) => value.startsWith(prefix));
|
|
2934
3224
|
}
|
|
2935
|
-
function
|
|
2936
|
-
return
|
|
3225
|
+
function containsKey(value) {
|
|
3226
|
+
return sweep(value) !== value;
|
|
2937
3227
|
}
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
3228
|
+
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";
|
|
3229
|
+
function splitDsn(raw) {
|
|
3230
|
+
const schemeEnd = raw.indexOf("://");
|
|
3231
|
+
if (schemeEnd === -1) return null;
|
|
3232
|
+
const scheme = raw.slice(0, schemeEnd).toLowerCase();
|
|
3233
|
+
const rest = raw.slice(schemeEnd + 3);
|
|
3234
|
+
const end = rest.search(/[/?#]/);
|
|
3235
|
+
if (end === -1) return { scheme, netloc: rest, slash: "", path: "" };
|
|
3236
|
+
const netloc = rest.slice(0, end);
|
|
3237
|
+
if (rest[end] !== "/") {
|
|
3238
|
+
return { scheme, netloc, slash: "", path: "" };
|
|
2942
3239
|
}
|
|
2943
|
-
|
|
2944
|
-
|
|
3240
|
+
const afterSlash = rest.slice(end + 1);
|
|
3241
|
+
const pathEnd = afterSlash.search(/[?#]/);
|
|
3242
|
+
return {
|
|
3243
|
+
scheme,
|
|
3244
|
+
netloc,
|
|
3245
|
+
slash: "/",
|
|
3246
|
+
path: pathEnd === -1 ? afterSlash : afterSlash.slice(0, pathEnd)
|
|
3247
|
+
};
|
|
2945
3248
|
}
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
|
|
2953
|
-
}
|
|
2954
|
-
version;
|
|
2955
|
-
audiences;
|
|
2956
|
-
usesShare;
|
|
2957
|
-
unmatched;
|
|
2958
|
-
/** Whether some caller can get reports, so the instructions point to the
|
|
2959
|
-
* tool. Read only where the code's value is "on": no tool exists otherwise. */
|
|
2960
|
-
reportsOnForAnyone;
|
|
2961
|
-
settingsFor(caller, vendorId2) {
|
|
2962
|
-
const bucket = caller.shareKey !== null && this.usesShare ? shareBucket(vendorId2, caller.shareKey) : null;
|
|
2963
|
-
return this.audiences.find((audience) => matches(audience, caller, bucket))?.settings ?? this.unmatched;
|
|
2964
|
-
}
|
|
2965
|
-
};
|
|
2966
|
-
function stringSet(value) {
|
|
2967
|
-
if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) return null;
|
|
2968
|
-
return new Set(value);
|
|
3249
|
+
function splitKeyFromAuthority(netloc) {
|
|
3250
|
+
const index = netloc.lastIndexOf("@");
|
|
3251
|
+
if (index === -1) return { key: "", at: false, authority: netloc };
|
|
3252
|
+
return {
|
|
3253
|
+
key: netloc.slice(0, index),
|
|
3254
|
+
at: true,
|
|
3255
|
+
authority: netloc.slice(index + 1)
|
|
3256
|
+
};
|
|
2969
3257
|
}
|
|
2970
|
-
function
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
|
|
2975
|
-
|
|
2976
|
-
|
|
2977
|
-
|
|
2978
|
-
|
|
2979
|
-
|
|
2980
|
-
|
|
3258
|
+
function redact(raw) {
|
|
3259
|
+
const parts = splitDsn(raw);
|
|
3260
|
+
if (parts === null) return "<dsn>";
|
|
3261
|
+
const { at, authority } = splitKeyFromAuthority(parts.netloc);
|
|
3262
|
+
const assembled = at ? `${parts.scheme}://***@${authority}${parts.slash}${parts.path}` : `${parts.scheme}://<no key>@${parts.netloc}${parts.slash}${parts.path}`;
|
|
3263
|
+
return sweep(assembled);
|
|
3264
|
+
}
|
|
3265
|
+
function sweep(message) {
|
|
3266
|
+
return message.replace(KEY_RUN, "<key>");
|
|
3267
|
+
}
|
|
3268
|
+
function fail(message) {
|
|
3269
|
+
throw new Error(sweep(message));
|
|
3270
|
+
}
|
|
3271
|
+
function dsnFromEnvironment() {
|
|
3272
|
+
const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
|
|
3273
|
+
return fromEnv2 ? fromEnv2 : void 0;
|
|
3274
|
+
}
|
|
3275
|
+
function selectDsn(explicit, supplied, door) {
|
|
3276
|
+
const conflicts = Object.keys(supplied).filter((name) => supplied[name]).sort();
|
|
3277
|
+
if (explicit) {
|
|
3278
|
+
if (conflicts.length > 0) {
|
|
3279
|
+
fail(
|
|
3280
|
+
`${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.`
|
|
3281
|
+
);
|
|
3282
|
+
}
|
|
3283
|
+
return explicit;
|
|
2981
3284
|
}
|
|
2982
|
-
const
|
|
2983
|
-
|
|
2984
|
-
if (
|
|
2985
|
-
|
|
3285
|
+
const ambient = dsnFromEnvironment();
|
|
3286
|
+
if (ambient === void 0) return void 0;
|
|
3287
|
+
if (conflicts.length > 0) {
|
|
3288
|
+
warn(
|
|
3289
|
+
`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.`
|
|
3290
|
+
);
|
|
3291
|
+
return void 0;
|
|
2986
3292
|
}
|
|
2987
|
-
|
|
2988
|
-
if (typeof reports === "string" && REPORT_MODES.has(reports)) settings.reportMode = reports;
|
|
2989
|
-
return { settings, labels, clients, shareThreshold };
|
|
3293
|
+
return ambient;
|
|
2990
3294
|
}
|
|
2991
|
-
function
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
|
|
2996
|
-
return null;
|
|
3295
|
+
function parseDsn(raw) {
|
|
3296
|
+
const dsn = typeof raw === "string" ? stripWhiteSpace(raw) : "";
|
|
3297
|
+
if (dsn === "") fail("dsn must be a non-empty string");
|
|
3298
|
+
if (looksLikeAKey(dsn)) {
|
|
3299
|
+
fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
|
|
2997
3300
|
}
|
|
2998
|
-
|
|
2999
|
-
const
|
|
3000
|
-
if (
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
|
|
3004
|
-
if (!isRecord(audience)) return null;
|
|
3005
|
-
const { id, match, capture } = audience;
|
|
3006
|
-
if (typeof id !== "string" || !isRecord(match) || !isRecord(capture)) return null;
|
|
3007
|
-
const readable = readAudience(version, id, match, capture);
|
|
3008
|
-
if (readable !== null) parsed.push(readable);
|
|
3301
|
+
const safe = redact(dsn);
|
|
3302
|
+
const parts = splitDsn(dsn);
|
|
3303
|
+
if (parts === null || parts.scheme !== "https" && parts.scheme !== "http") {
|
|
3304
|
+
fail(
|
|
3305
|
+
`dsn ${safe} must start with https:// (or http:// for local development) \u2014 ${BARE_KEY_HINT}`
|
|
3306
|
+
);
|
|
3009
3307
|
}
|
|
3010
|
-
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
warned = false;
|
|
3023
|
-
constructor(options) {
|
|
3024
|
-
this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
|
|
3025
|
-
this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
|
|
3026
|
-
this.refreshMs = options.refreshMs;
|
|
3027
|
-
this.fetchImpl = options.fetchImpl ?? globalFetch;
|
|
3308
|
+
const { key, at, authority } = splitKeyFromAuthority(parts.netloc);
|
|
3309
|
+
if (!at || !key) {
|
|
3310
|
+
if (looksLikeAKey(parts.netloc)) {
|
|
3311
|
+
fail(
|
|
3312
|
+
`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`
|
|
3313
|
+
);
|
|
3314
|
+
}
|
|
3315
|
+
const misplaced = parts.path.split("/").some((segment) => containsKey(segment));
|
|
3316
|
+
const detail = misplaced ? "the key is in the PATH \u2014 it goes before an @" : "the value from /account has the key before an @";
|
|
3317
|
+
fail(
|
|
3318
|
+
`dsn ${safe} carries no key: ${detail}, as in https://baton_pk_...@host/ten_.../server`
|
|
3319
|
+
);
|
|
3028
3320
|
}
|
|
3029
|
-
|
|
3030
|
-
|
|
3321
|
+
if (NOT_IN_A_KEY.test(key)) {
|
|
3322
|
+
fail(
|
|
3323
|
+
`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.`
|
|
3324
|
+
);
|
|
3031
3325
|
}
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
void this.readOnce();
|
|
3326
|
+
if (key.includes(":")) {
|
|
3327
|
+
fail(
|
|
3328
|
+
`dsn ${safe} has a ':' in its key \u2014 a DSN carries one credential and no password field`
|
|
3329
|
+
);
|
|
3037
3330
|
}
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
this.timer = null;
|
|
3041
|
-
this.reading?.abort();
|
|
3042
|
-
this.reading = null;
|
|
3331
|
+
if (!authority) {
|
|
3332
|
+
fail(`dsn ${safe} has no host`);
|
|
3043
3333
|
}
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
this.reading = reading;
|
|
3049
|
-
const timeout = setTimeout(() => reading.abort(), REQUEST_TIMEOUT_MS);
|
|
3050
|
-
timeout.unref?.();
|
|
3051
|
-
try {
|
|
3052
|
-
await this.read(reading.signal);
|
|
3053
|
-
} catch {
|
|
3054
|
-
} finally {
|
|
3055
|
-
clearTimeout(timeout);
|
|
3056
|
-
if (this.reading === reading) this.reading = null;
|
|
3057
|
-
}
|
|
3334
|
+
if (containsKey(authority)) {
|
|
3335
|
+
fail(
|
|
3336
|
+
`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>`
|
|
3337
|
+
);
|
|
3058
3338
|
}
|
|
3059
|
-
|
|
3060
|
-
|
|
3061
|
-
|
|
3062
|
-
|
|
3063
|
-
void response.body?.cancel().catch(() => void 0);
|
|
3064
|
-
}
|
|
3065
|
-
if (signal.aborted) return;
|
|
3066
|
-
if (response.status === 204) {
|
|
3067
|
-
this.held = null;
|
|
3068
|
-
this.etag = null;
|
|
3069
|
-
} else if (response.status === 200) {
|
|
3070
|
-
const document = parseDocument(await response.text());
|
|
3071
|
-
if (signal.aborted) return;
|
|
3072
|
-
if (document === null) {
|
|
3073
|
-
if (!this.warned) {
|
|
3074
|
-
this.warned = true;
|
|
3075
|
-
warn("baton: the collector sent capture settings this SDK cannot read");
|
|
3076
|
-
}
|
|
3077
|
-
return;
|
|
3078
|
-
}
|
|
3079
|
-
this.held = document;
|
|
3080
|
-
this.etag = response.headers.get("etag");
|
|
3081
|
-
}
|
|
3339
|
+
if (NOT_IN_A_HOST.test(authority)) {
|
|
3340
|
+
fail(
|
|
3341
|
+
`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.`
|
|
3342
|
+
);
|
|
3082
3343
|
}
|
|
3083
|
-
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
|
|
3344
|
+
let hostReason = null;
|
|
3345
|
+
let parsedAuthority = null;
|
|
3346
|
+
try {
|
|
3347
|
+
parsedAuthority = new URL(`${parts.scheme}://${authority}`);
|
|
3348
|
+
} catch (error) {
|
|
3349
|
+
hostReason = error instanceof Error ? error.constructor.name : "Error";
|
|
3088
3350
|
}
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
start() {
|
|
3092
|
-
this.source.start();
|
|
3351
|
+
if (parsedAuthority === null) {
|
|
3352
|
+
fail(`dsn ${safe} is not a parseable URL (${hostReason ?? "Error"})`);
|
|
3093
3353
|
}
|
|
3094
|
-
|
|
3095
|
-
|
|
3354
|
+
const segments = parts.path.split("/").filter((segment) => segment !== "");
|
|
3355
|
+
const [workspace, server, ...extra] = segments;
|
|
3356
|
+
if (workspace === void 0 || server === void 0 || extra.length > 0) {
|
|
3357
|
+
fail(
|
|
3358
|
+
`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.`
|
|
3359
|
+
);
|
|
3096
3360
|
}
|
|
3097
|
-
|
|
3098
|
-
|
|
3361
|
+
for (const [slot, segment] of [
|
|
3362
|
+
["workspace", workspace],
|
|
3363
|
+
["server", server]
|
|
3364
|
+
]) {
|
|
3365
|
+
if (containsKey(segment)) {
|
|
3366
|
+
fail(
|
|
3367
|
+
`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>`
|
|
3368
|
+
);
|
|
3369
|
+
}
|
|
3099
3370
|
}
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
|
|
3371
|
+
if (!WORKSPACE_PATTERN.test(workspace)) {
|
|
3372
|
+
fail(
|
|
3373
|
+
`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.`
|
|
3374
|
+
);
|
|
3103
3375
|
}
|
|
3104
|
-
|
|
3376
|
+
if (!VENDOR_ID_PATTERN.test(server)) {
|
|
3377
|
+
fail(
|
|
3378
|
+
`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.`
|
|
3379
|
+
);
|
|
3380
|
+
}
|
|
3381
|
+
if (key.startsWith(SECRET_PREFIX)) {
|
|
3382
|
+
warn(
|
|
3383
|
+
`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.`
|
|
3384
|
+
);
|
|
3385
|
+
}
|
|
3386
|
+
return sealKey({
|
|
3387
|
+
origin: `${parts.scheme}://${authority}`,
|
|
3388
|
+
tenantId: workspace,
|
|
3389
|
+
vendorId: server,
|
|
3390
|
+
key
|
|
3391
|
+
});
|
|
3392
|
+
}
|
|
3393
|
+
function sealKey(dsn) {
|
|
3394
|
+
const shown = {
|
|
3395
|
+
origin: dsn.origin,
|
|
3396
|
+
tenantId: dsn.tenantId,
|
|
3397
|
+
vendorId: dsn.vendorId,
|
|
3398
|
+
key: "<key>"
|
|
3399
|
+
};
|
|
3400
|
+
Object.defineProperty(dsn, "toJSON", {
|
|
3401
|
+
value: () => shown,
|
|
3402
|
+
enumerable: false
|
|
3403
|
+
});
|
|
3404
|
+
Object.defineProperty(dsn, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
|
|
3405
|
+
value: () => shown,
|
|
3406
|
+
enumerable: false
|
|
3407
|
+
});
|
|
3408
|
+
return dsn;
|
|
3409
|
+
}
|
|
3105
3410
|
|
|
3106
3411
|
// src/integrations/mcp/config.ts
|
|
3107
3412
|
function resolveTenantId(explicit, vendorId2) {
|
|
@@ -3197,7 +3502,8 @@ function resolveBatonConfig(supplied) {
|
|
|
3197
3502
|
tenantId: dsn.tenantId,
|
|
3198
3503
|
vendorId: dsn.vendorId,
|
|
3199
3504
|
refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
|
|
3200
|
-
})
|
|
3505
|
+
}),
|
|
3506
|
+
envCandidate()
|
|
3201
3507
|
)
|
|
3202
3508
|
} : {}
|
|
3203
3509
|
};
|
|
@@ -3370,51 +3676,148 @@ var BatonHandle = class {
|
|
|
3370
3676
|
};
|
|
3371
3677
|
|
|
3372
3678
|
// src/integrations/mcp/perCaller.ts
|
|
3679
|
+
var UNREAD = /* @__PURE__ */ Symbol("unread");
|
|
3373
3680
|
var PerCallerSurface = class {
|
|
3374
3681
|
constructor(options) {
|
|
3375
3682
|
this.options = options;
|
|
3376
3683
|
}
|
|
3377
3684
|
options;
|
|
3378
|
-
|
|
3685
|
+
document = UNREAD;
|
|
3686
|
+
served = null;
|
|
3687
|
+
serverOverlay;
|
|
3379
3688
|
/** Called at install and on every request; writes only when the report
|
|
3380
|
-
* pointer should change. */
|
|
3689
|
+
* pointer or the server overlay should change. */
|
|
3381
3690
|
followSettings() {
|
|
3382
|
-
if (this.options.annotationToolName === "") return;
|
|
3383
3691
|
try {
|
|
3384
3692
|
const document = this.options.settings.document;
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
|
|
3388
|
-
|
|
3693
|
+
if (document === this.document) return;
|
|
3694
|
+
const overlay = document?.serverOverlay;
|
|
3695
|
+
const pointer = this.options.pointer();
|
|
3696
|
+
const pointerOn = pointer !== void 0 && (document === null || document.reportsOnForAnyone);
|
|
3697
|
+
const served = JSON.stringify([pointerOn, overlay?.id ?? null]);
|
|
3698
|
+
if (served !== this.served) {
|
|
3699
|
+
const { ours, subagent } = batonParagraphs(pointerOn ? pointer : void 0, overlay, this.options.subagentLine());
|
|
3700
|
+
this.options.writeInstructions(ours, subagent);
|
|
3701
|
+
this.served = served;
|
|
3702
|
+
this.serverOverlay = overlay;
|
|
3703
|
+
}
|
|
3704
|
+
this.document = document;
|
|
3389
3705
|
} catch (err) {
|
|
3390
3706
|
stderrLine(`baton: could not update the server instructions for new settings: ${printable(err)}`);
|
|
3391
3707
|
}
|
|
3392
3708
|
}
|
|
3393
|
-
/** `
|
|
3709
|
+
/** `followSettings` after the report pointer changed outside the settings. */
|
|
3710
|
+
refresh() {
|
|
3711
|
+
this.document = UNREAD;
|
|
3712
|
+
this.served = null;
|
|
3713
|
+
this.followSettings();
|
|
3714
|
+
}
|
|
3715
|
+
/** `result` with the caller's goal, reports and overlay; as served on any failure. */
|
|
3394
3716
|
toolsFor(result, caller) {
|
|
3395
3717
|
const settings = caller.settings;
|
|
3396
3718
|
if (settings === void 0) return result;
|
|
3397
3719
|
const { intentParamMode, annotationToolName, injectsGoal } = this.options;
|
|
3398
3720
|
const goal = settings.intentParamMode ?? intentParamMode;
|
|
3399
3721
|
const hideReports = annotationToolName !== "" && settings.reportMode === "off";
|
|
3400
|
-
|
|
3722
|
+
const overlay = settings.overlay;
|
|
3723
|
+
if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
|
|
3401
3724
|
try {
|
|
3402
3725
|
const tools = result?.tools;
|
|
3403
3726
|
if (!Array.isArray(tools)) return result;
|
|
3404
3727
|
const served = [];
|
|
3728
|
+
const injected = [];
|
|
3405
3729
|
for (const tool of tools) {
|
|
3406
3730
|
const name = tool?.name;
|
|
3407
3731
|
if (hideReports && name === annotationToolName) continue;
|
|
3408
|
-
const
|
|
3409
|
-
served.push(
|
|
3732
|
+
const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
|
|
3733
|
+
served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
|
|
3734
|
+
injected.push(ours);
|
|
3410
3735
|
}
|
|
3411
|
-
|
|
3736
|
+
const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
|
|
3737
|
+
return { ...result, tools: rewritten };
|
|
3412
3738
|
} catch (err) {
|
|
3413
3739
|
stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
|
|
3414
3740
|
return result;
|
|
3415
3741
|
}
|
|
3416
3742
|
}
|
|
3417
3743
|
};
|
|
3744
|
+
function batonParagraphs(pointer, overlay, subagentLine) {
|
|
3745
|
+
const parts = overlay?.instructionAppends() ?? [];
|
|
3746
|
+
if (pointer !== void 0) parts.push(overlaid(pointer, overlay, "instructions.report_pointer"));
|
|
3747
|
+
if (subagentLine) parts.push(overlaid(INTENT_INSTRUCTIONS, overlay, "instructions.subagent"));
|
|
3748
|
+
const kept = parts.map(stripWhiteSpaceEnd);
|
|
3749
|
+
return { ours: kept.filter((part) => part).join("\n\n"), subagent: subagentLine && kept.at(-1) || null };
|
|
3750
|
+
}
|
|
3751
|
+
function withOverlay(tools, injected, overlay, reportTool2) {
|
|
3752
|
+
const position = /* @__PURE__ */ new Map();
|
|
3753
|
+
tools.forEach((tool, i) => position.set(tool?.name, i));
|
|
3754
|
+
const hidden = /* @__PURE__ */ new Set();
|
|
3755
|
+
for (const action of overlay.actions) {
|
|
3756
|
+
if (action.tool === void 0) continue;
|
|
3757
|
+
const i = position.get(action.tool);
|
|
3758
|
+
if (i === void 0) {
|
|
3759
|
+
warnSkipped(overlay.id, action.index, `no tool is named ${JSON.stringify(action.tool)}`);
|
|
3760
|
+
} else if (action.tool === reportTool2) {
|
|
3761
|
+
warnSkipped(overlay.id, action.index, "the report tool takes agent_text targets only");
|
|
3762
|
+
} else if (action.param === void 0 && action.change === "remove") {
|
|
3763
|
+
hidden.add(i);
|
|
3764
|
+
} else if (action.param === void 0) {
|
|
3765
|
+
tools[i] = withDescription(tools[i], [action]);
|
|
3766
|
+
} else {
|
|
3767
|
+
const reason = paramChange(tools, i, action, injected[i]);
|
|
3768
|
+
if (reason !== void 0) warnSkipped(overlay.id, action.index, reason);
|
|
3769
|
+
}
|
|
3770
|
+
}
|
|
3771
|
+
const goalActions = overlay.pieceActions("goal_param.description");
|
|
3772
|
+
if (goalActions.length > 0) {
|
|
3773
|
+
injected.forEach((ours, i) => {
|
|
3774
|
+
if (ours) describeParam(tools, i, USER_GOAL_PARAM_NAME, goalActions);
|
|
3775
|
+
});
|
|
3776
|
+
}
|
|
3777
|
+
const reportActions = overlay.pieceActions("report_tool.description");
|
|
3778
|
+
const reportAt = reportTool2 === void 0 ? void 0 : position.get(reportTool2);
|
|
3779
|
+
if (reportActions.length > 0 && reportAt !== void 0) {
|
|
3780
|
+
tools[reportAt] = withDescription(tools[reportAt], reportActions);
|
|
3781
|
+
}
|
|
3782
|
+
return tools.filter((_, i) => !hidden.has(i));
|
|
3783
|
+
}
|
|
3784
|
+
function withDescription(tool, actions) {
|
|
3785
|
+
const description = typeof tool.description === "string" ? tool.description : void 0;
|
|
3786
|
+
return { ...tool, description: changedText(description, actions).text };
|
|
3787
|
+
}
|
|
3788
|
+
function paramChange(tools, i, action, injected) {
|
|
3789
|
+
const param = action.param;
|
|
3790
|
+
const tool = tools[i];
|
|
3791
|
+
const schema = tool.inputSchema;
|
|
3792
|
+
const properties = isRecord(schema) && isRecord(schema.properties) ? schema.properties : void 0;
|
|
3793
|
+
if (properties === void 0 || !Object.hasOwn(properties, param)) {
|
|
3794
|
+
return `${JSON.stringify(action.tool)} has no param ${JSON.stringify(param)}`;
|
|
3795
|
+
}
|
|
3796
|
+
if (injected && param === USER_GOAL_PARAM_NAME) return "Baton's user_goal takes the goal_param.description target";
|
|
3797
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
3798
|
+
if (action.change === "remove") {
|
|
3799
|
+
if (required.includes(param)) return `${JSON.stringify(action.tool)} requires ${JSON.stringify(param)}`;
|
|
3800
|
+
const kept = Object.fromEntries(Object.entries(properties).filter(([name]) => name !== param));
|
|
3801
|
+
tools[i] = { ...tool, inputSchema: { ...schema, properties: kept } };
|
|
3802
|
+
} else if (action.change === "required") {
|
|
3803
|
+
if (!required.includes(param)) tools[i] = { ...tool, inputSchema: { ...schema, required: [...required, param] } };
|
|
3804
|
+
} else {
|
|
3805
|
+
describeParam(tools, i, param, [action]);
|
|
3806
|
+
}
|
|
3807
|
+
return void 0;
|
|
3808
|
+
}
|
|
3809
|
+
function describeParam(tools, i, param, actions) {
|
|
3810
|
+
const tool = tools[i];
|
|
3811
|
+
const schema = tool.inputSchema;
|
|
3812
|
+
const properties = schema.properties;
|
|
3813
|
+
const described = isRecord(properties[param]) ? properties[param] : {};
|
|
3814
|
+
const current2 = typeof described.description === "string" ? described.description : void 0;
|
|
3815
|
+
const description = changedText(current2, actions).text;
|
|
3816
|
+
tools[i] = {
|
|
3817
|
+
...tool,
|
|
3818
|
+
inputSchema: { ...schema, properties: { ...properties, [param]: { ...described, description } } }
|
|
3819
|
+
};
|
|
3820
|
+
}
|
|
3418
3821
|
function withGoalMode(tool, goal) {
|
|
3419
3822
|
const entry = tool;
|
|
3420
3823
|
const schema = entry.inputSchema;
|
|
@@ -3504,13 +3907,20 @@ function assembleSurface(serverMeta, tools) {
|
|
|
3504
3907
|
var SENT_SURFACES_CAP = 256;
|
|
3505
3908
|
var SentSurfaces = class {
|
|
3506
3909
|
hashes = /* @__PURE__ */ new Set();
|
|
3507
|
-
|
|
3508
|
-
|
|
3910
|
+
serverOverlay = null;
|
|
3911
|
+
/** `serverOverlay` is not in `surface_hash`, and a snapshot is sent again
|
|
3912
|
+
* whenever it changes (SPEC §11.4.2). */
|
|
3913
|
+
wasSent(digest, serverOverlay = null) {
|
|
3914
|
+
if (serverOverlay !== this.serverOverlay || !this.hashes.has(digest)) return false;
|
|
3509
3915
|
this.hashes.delete(digest);
|
|
3510
3916
|
this.hashes.add(digest);
|
|
3511
3917
|
return true;
|
|
3512
3918
|
}
|
|
3513
|
-
mark(digest) {
|
|
3919
|
+
mark(digest, serverOverlay = null) {
|
|
3920
|
+
if (serverOverlay !== this.serverOverlay) {
|
|
3921
|
+
this.hashes.clear();
|
|
3922
|
+
this.serverOverlay = serverOverlay;
|
|
3923
|
+
}
|
|
3514
3924
|
this.hashes.add(digest);
|
|
3515
3925
|
if (this.hashes.size > SENT_SURFACES_CAP) {
|
|
3516
3926
|
this.hashes.delete(this.hashes.values().next().value);
|
|
@@ -3548,6 +3958,7 @@ var SurfaceState = class {
|
|
|
3548
3958
|
* injected schema as if it were vendor-true. */
|
|
3549
3959
|
rawTools = /* @__PURE__ */ new Map();
|
|
3550
3960
|
dirty = false;
|
|
3961
|
+
servedOverlayId = null;
|
|
3551
3962
|
/** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
|
|
3552
3963
|
* which picks the spelling THIS SDK major puts on the wire. */
|
|
3553
3964
|
noteTool(name, inputSchemaJson, description) {
|
|
@@ -3599,7 +4010,7 @@ async function resolveEnvelopeParts(ctx, extra) {
|
|
|
3599
4010
|
const session = await resolveSessionId(ctx.fallbackSessionId, extra);
|
|
3600
4011
|
return { ...session, scrubbedMeta };
|
|
3601
4012
|
}
|
|
3602
|
-
async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn") {
|
|
4013
|
+
async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn", resolved) {
|
|
3603
4014
|
await maybeEmitSurfaceSnapshot(ctx);
|
|
3604
4015
|
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
3605
4016
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
@@ -3609,12 +4020,7 @@ async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn
|
|
|
3609
4020
|
(name) => dispositions === void 0 || dispositions[name] === "native" || unlisted === "leave" || unlisted === "goalOnly" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
|
|
3610
4021
|
);
|
|
3611
4022
|
const client = observeClient(extra, ctx);
|
|
3612
|
-
const caller = await resolveCaller(
|
|
3613
|
-
ctx.resolvePrincipal,
|
|
3614
|
-
{ extra, toolName, arguments: params },
|
|
3615
|
-
ctx.captureSettings,
|
|
3616
|
-
client
|
|
3617
|
-
);
|
|
4023
|
+
const caller = resolved ?? await resolveCaller(ctx.resolvePrincipal, { extra, toolName, arguments: params }, ctx.captureSettings, client);
|
|
3618
4024
|
const resultCaptureMode = caller.settings?.resultCaptureMode ?? ctx.configResultCaptureMode;
|
|
3619
4025
|
const common = {
|
|
3620
4026
|
tenant_id: ctx.tenantId,
|
|
@@ -3652,16 +4058,24 @@ async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn
|
|
|
3652
4058
|
);
|
|
3653
4059
|
return { common, session, resultCaptureMode };
|
|
3654
4060
|
}
|
|
3655
|
-
function batonWrap(nameRef, original, ctx, unlisted = "warn") {
|
|
4061
|
+
function batonWrap(nameRef, original, ctx, unlisted = "warn", resolved) {
|
|
3656
4062
|
return async (...callArgs) => {
|
|
3657
4063
|
const toolName = nameRef.current;
|
|
3658
4064
|
const slot = callSlots.getStore();
|
|
3659
4065
|
if (slot) slot.innerFired = true;
|
|
3660
4066
|
const extra = callArgs[callArgs.length - 1];
|
|
3661
4067
|
const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
|
|
3662
|
-
const
|
|
4068
|
+
const ours = slot?.strippedFor === toolName ? slot : void 0;
|
|
3663
4069
|
if (slot) slot.strippedFor = null;
|
|
3664
|
-
const { common, session, resultCaptureMode } = await openCall(
|
|
4070
|
+
const { common, session, resultCaptureMode } = await openCall(
|
|
4071
|
+
ctx,
|
|
4072
|
+
toolName,
|
|
4073
|
+
extra,
|
|
4074
|
+
params,
|
|
4075
|
+
ours?.stripped ?? {},
|
|
4076
|
+
unlisted,
|
|
4077
|
+
ours?.caller ?? resolved
|
|
4078
|
+
);
|
|
3665
4079
|
const terminate = async (build, replacement) => {
|
|
3666
4080
|
if (!slot) {
|
|
3667
4081
|
if (build !== null) await emit(ctx.sink, build);
|
|
@@ -3852,6 +4266,11 @@ function stripIntentParams(params, ctx) {
|
|
|
3852
4266
|
return stripped;
|
|
3853
4267
|
}
|
|
3854
4268
|
async function maybeEmitSurfaceSnapshot(ctx) {
|
|
4269
|
+
const overlayId = ctx.perCaller?.serverOverlay?.id ?? null;
|
|
4270
|
+
if (overlayId !== ctx.surfaceState.servedOverlayId) {
|
|
4271
|
+
ctx.surfaceState.servedOverlayId = overlayId;
|
|
4272
|
+
ctx.surfaceState.dirty = true;
|
|
4273
|
+
}
|
|
3855
4274
|
if (!ctx.surfaceState.dirty) return;
|
|
3856
4275
|
ctx.surfaceState.dirty = false;
|
|
3857
4276
|
let snapshot;
|
|
@@ -3864,8 +4283,8 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
3864
4283
|
return;
|
|
3865
4284
|
}
|
|
3866
4285
|
const sent = ctx.surfaceState.sentSurfaces;
|
|
3867
|
-
if (sent.wasSent(digest)) return;
|
|
3868
|
-
sent.mark(digest);
|
|
4286
|
+
if (sent.wasSent(digest, overlayId)) return;
|
|
4287
|
+
sent.mark(digest, overlayId);
|
|
3869
4288
|
const seam = buildSeamAugmentations({
|
|
3870
4289
|
injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
|
|
3871
4290
|
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
@@ -3873,6 +4292,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
3873
4292
|
requiredParamNames: requiredParamNames(ctx.intentParamMode),
|
|
3874
4293
|
instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions())
|
|
3875
4294
|
});
|
|
4295
|
+
if (ctx.captureSettings !== void 0) seam.server_overlay = overlayId;
|
|
3876
4296
|
await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
|
|
3877
4297
|
}
|
|
3878
4298
|
function declaredIntentParams(vendorSchema) {
|
|
@@ -3950,6 +4370,7 @@ function installToolsListSeam(lowLevel, ctx, listsOwnReportTool) {
|
|
|
3950
4370
|
var LOW_LEVEL_LIST_SEAM = /* @__PURE__ */ Symbol("batonLowLevelListSeam");
|
|
3951
4371
|
var LOW_LEVEL_CALL_SEAM = /* @__PURE__ */ Symbol("batonLowLevelCallSeam");
|
|
3952
4372
|
var LOW_LEVEL_HANDSHAKE_SEAM = /* @__PURE__ */ Symbol("batonLowLevelHandshakeSeam");
|
|
4373
|
+
var SETTINGS_SEAM = /* @__PURE__ */ Symbol("batonSettingsSeam");
|
|
3953
4374
|
function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce2, reportToolTaken) {
|
|
3954
4375
|
let reportTool2 = annotationTool;
|
|
3955
4376
|
const listedReportTool = reportTool2 && {
|
|
@@ -4048,13 +4469,23 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
|
|
|
4048
4469
|
installRequestSeam(lowLevel, "server/discover", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);
|
|
4049
4470
|
installRequestSeam(lowLevel, TOOLS_CALL_METHOD, LOW_LEVEL_CALL_SEAM, (handler) => async (...args) => {
|
|
4050
4471
|
catchUp();
|
|
4051
|
-
ctx.perCaller?.followSettings();
|
|
4052
4472
|
const request = args[0];
|
|
4053
4473
|
const name = request?.params?.name;
|
|
4054
4474
|
if (typeof name !== "string") return handler(...args);
|
|
4055
4475
|
if (name === reportTool2?.name) return callAnnotationTool(reportTool2, request?.params?.arguments, args[1]);
|
|
4056
4476
|
const injected = ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected";
|
|
4057
4477
|
const unlisted = injected ? "warn" : known.keepsGoal.has(name) || known.unread.has(name) ? "leave" : "goalOnly";
|
|
4478
|
+
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) };
|
|
4479
|
+
let slot;
|
|
4480
|
+
if (mayHide(ctx.captureSettings, name)) {
|
|
4481
|
+
const hookArgs = isRecord(request?.params?.arguments) ? { ...request.params.arguments } : {};
|
|
4482
|
+
const checked = { innerFired: false, flushTerminal: null, stripped: strip(hookArgs), strippedFor: name, validation: "unseen", unlisted };
|
|
4483
|
+
if (await hiddenFrom(checked, name, hookArgs, args[1], ctx)) {
|
|
4484
|
+
if (request?.params !== void 0 && isRecord(request.params.arguments)) request.params.arguments = hookArgs;
|
|
4485
|
+
return answerHidden(lowLevel, name, (outcome) => settleCall(checked, outcome, args, () => void 0, ctx, "tool_hidden"));
|
|
4486
|
+
}
|
|
4487
|
+
slot = checked;
|
|
4488
|
+
}
|
|
4058
4489
|
const params = request?.params?.arguments;
|
|
4059
4490
|
const toolArgs = isRecord(params) ? params : {};
|
|
4060
4491
|
if (unlisted === "goalOnly" && USER_GOAL_PARAM_NAME in toolArgs && !known.served.has(name) && !known.givenTools.some((tool) => tool.name === name)) {
|
|
@@ -4064,11 +4495,10 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
|
|
|
4064
4495
|
);
|
|
4065
4496
|
}
|
|
4066
4497
|
if (request?.params?.task !== void 0) {
|
|
4067
|
-
|
|
4068
|
-
else extractGoalParam(toolArgs, USER_GOAL_PARAM_NAME, name, ctx.paramRegistry.get(name), unlisted);
|
|
4498
|
+
strip(toolArgs);
|
|
4069
4499
|
return handler(...args);
|
|
4070
4500
|
}
|
|
4071
|
-
return batonWrap({ current: name }, () => handler(...args), ctx, unlisted)(toolArgs, args[1]);
|
|
4501
|
+
return batonWrap({ current: name }, () => handler(...args), ctx, unlisted, slot?.caller)(toolArgs, args[1]);
|
|
4072
4502
|
});
|
|
4073
4503
|
}
|
|
4074
4504
|
function lowLevelMajor(lowLevel) {
|
|
@@ -4316,7 +4746,6 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
4316
4746
|
TOOLS_CALL_METHOD,
|
|
4317
4747
|
TOOLS_CALL_SEAM,
|
|
4318
4748
|
(handler) => async (...args) => {
|
|
4319
|
-
ctx.perCaller?.followSettings();
|
|
4320
4749
|
const request = args[0];
|
|
4321
4750
|
const name = request?.params?.name;
|
|
4322
4751
|
const slot = {
|
|
@@ -4326,6 +4755,10 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
4326
4755
|
strippedFor: typeof name === "string" ? name : null,
|
|
4327
4756
|
validation: "unseen"
|
|
4328
4757
|
};
|
|
4758
|
+
const toolArgs = request?.params?.arguments;
|
|
4759
|
+
if (typeof name === "string" && toolEntry(name) != null && await hiddenFrom(slot, name, isRecord(toolArgs) ? toolArgs : {}, args[1], ctx)) {
|
|
4760
|
+
return answerHidden(lowLevel, name, (outcome2) => settleCall(slot, outcome2, args, toolEntry, ctx, "tool_hidden"));
|
|
4761
|
+
}
|
|
4329
4762
|
let outcome = CLEAN_OUTCOME;
|
|
4330
4763
|
try {
|
|
4331
4764
|
const result = await callSlots.run(slot, () => handler(...args));
|
|
@@ -4340,6 +4773,34 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
4340
4773
|
}
|
|
4341
4774
|
);
|
|
4342
4775
|
}
|
|
4776
|
+
async function hiddenFrom(slot, name, params, extra, ctx) {
|
|
4777
|
+
try {
|
|
4778
|
+
if (name === ctx.annotationToolName || !mayHide(ctx.captureSettings, name)) return false;
|
|
4779
|
+
slot.caller = await resolveCaller(
|
|
4780
|
+
ctx.resolvePrincipal,
|
|
4781
|
+
{ extra, toolName: name, arguments: params },
|
|
4782
|
+
ctx.captureSettings,
|
|
4783
|
+
observeClient(extra, ctx)
|
|
4784
|
+
);
|
|
4785
|
+
return slot.caller.settings?.overlay?.hiddenTools.has(name) ?? false;
|
|
4786
|
+
} catch (err) {
|
|
4787
|
+
stderrLine(`baton: could not check whether the tool is hidden; it is served: ${printable(err)}`);
|
|
4788
|
+
return false;
|
|
4789
|
+
}
|
|
4790
|
+
}
|
|
4791
|
+
async function answerHidden(lowLevel, name, settle) {
|
|
4792
|
+
if (lowLevelMajor(lowLevel) === 1) {
|
|
4793
|
+
const result = { content: [{ type: "text", text: `MCP error -32602: Tool ${name} not found` }], isError: true };
|
|
4794
|
+
await settle({ failed: true, raised: false, result });
|
|
4795
|
+
return result;
|
|
4796
|
+
}
|
|
4797
|
+
const err = new ProtocolError(`Tool ${name} not found`);
|
|
4798
|
+
await settle({ failed: true, raised: true, err });
|
|
4799
|
+
throw err;
|
|
4800
|
+
}
|
|
4801
|
+
var ProtocolError = class extends Error {
|
|
4802
|
+
code = -32602;
|
|
4803
|
+
};
|
|
4343
4804
|
var VALIDATION_PROBE = /* @__PURE__ */ Symbol("baton.validationProbe");
|
|
4344
4805
|
function installValidationProbe(server) {
|
|
4345
4806
|
const target = server;
|
|
@@ -4359,7 +4820,7 @@ function installValidationProbe(server) {
|
|
|
4359
4820
|
Object.assign(probe, { [VALIDATION_PROBE]: true });
|
|
4360
4821
|
target.validateToolInput = probe;
|
|
4361
4822
|
}
|
|
4362
|
-
async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
4823
|
+
async function settleCall(slot, outcome, args, toolEntry, ctx, kind) {
|
|
4363
4824
|
try {
|
|
4364
4825
|
if (slot.flushTerminal !== null) {
|
|
4365
4826
|
const flush = slot.flushTerminal;
|
|
@@ -4369,13 +4830,13 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
|
4369
4830
|
}
|
|
4370
4831
|
if (slot.innerFired) return;
|
|
4371
4832
|
if (!outcome.failed) return;
|
|
4372
|
-
await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
|
|
4833
|
+
await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx, kind);
|
|
4373
4834
|
} catch (err) {
|
|
4374
4835
|
PROCESS_DROPS.add("encode_failed");
|
|
4375
4836
|
stderrLine(`baton: settling a tool call failed; events dropped: ${String(err)}`);
|
|
4376
4837
|
}
|
|
4377
4838
|
}
|
|
4378
|
-
async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
4839
|
+
async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx, kind) {
|
|
4379
4840
|
const request = args[0];
|
|
4380
4841
|
const toolName = request?.params?.name;
|
|
4381
4842
|
if (typeof toolName !== "string") return;
|
|
@@ -4389,9 +4850,10 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
|
4389
4850
|
args[1],
|
|
4390
4851
|
params,
|
|
4391
4852
|
slot.stripped,
|
|
4392
|
-
entry != null ? "warn" : "quiet"
|
|
4853
|
+
slot.unlisted ?? (entry != null ? "warn" : "quiet"),
|
|
4854
|
+
slot.caller
|
|
4393
4855
|
);
|
|
4394
|
-
const failureKind = requestSideFailureKind(entry, slot.validation);
|
|
4856
|
+
const failureKind = kind ?? requestSideFailureKind(entry, slot.validation);
|
|
4395
4857
|
const text = () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result);
|
|
4396
4858
|
await emit(
|
|
4397
4859
|
ctx.sink,
|
|
@@ -4585,7 +5047,7 @@ function newBatonState(config) {
|
|
|
4585
5047
|
lowLevelTools: { given: config.tools, givenTools: [], served: /* @__PURE__ */ new Map(), keepsGoal: /* @__PURE__ */ new Set(), unread: /* @__PURE__ */ new Set() }
|
|
4586
5048
|
};
|
|
4587
5049
|
}
|
|
4588
|
-
function install(server, supplied, resolved, { sentSurfaces, warned:
|
|
5050
|
+
function install(server, supplied, resolved, { sentSurfaces, warned: warned4, counter: sharedCounter, scrubber, lowLevelTools }, unconfigured) {
|
|
4589
5051
|
const shape = serverShapeOf(server);
|
|
4590
5052
|
const internals = server;
|
|
4591
5053
|
const lowLevel = shape === "mcpServer" ? internals.server : server;
|
|
@@ -4638,19 +5100,16 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4638
5100
|
if (memo && typeof memo === "object") delete memo[name];
|
|
4639
5101
|
};
|
|
4640
5102
|
const warnOnce2 = (key, message) => {
|
|
4641
|
-
if (
|
|
4642
|
-
|
|
5103
|
+
if (warned4.has(key)) return;
|
|
5104
|
+
warned4.add(key);
|
|
4643
5105
|
stderrLine(message);
|
|
4644
5106
|
};
|
|
5107
|
+
const warnLength = (message) => warnOnce2("instructions-length", message);
|
|
5108
|
+
const setInstructions = (text) => {
|
|
5109
|
+
lowLevel._instructions = text;
|
|
5110
|
+
};
|
|
4645
5111
|
const dropSubagentClause = (name) => {
|
|
4646
|
-
|
|
4647
|
-
if (current2 === INTENT_INSTRUCTIONS) {
|
|
4648
|
-
lowLevel._instructions = "";
|
|
4649
|
-
} else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
|
|
4650
|
-
lowLevel._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
|
|
4651
|
-
} else {
|
|
4652
|
-
return;
|
|
4653
|
-
}
|
|
5112
|
+
if (!removeSubagentClause(lowLevel, setInstructions, warnLength)) return;
|
|
4654
5113
|
warnOnce2(
|
|
4655
5114
|
"native-user-goal",
|
|
4656
5115
|
`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`
|
|
@@ -4697,12 +5156,8 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4697
5156
|
surfaceState,
|
|
4698
5157
|
emitSurface
|
|
4699
5158
|
};
|
|
4700
|
-
const writeInstructions = (text) => {
|
|
4701
|
-
lowLevel
|
|
4702
|
-
lowLevel,
|
|
4703
|
-
text,
|
|
4704
|
-
(message) => warnOnce2("instructions-length", message)
|
|
4705
|
-
);
|
|
5159
|
+
const writeInstructions = (text, subagent = INTENT_INSTRUCTIONS) => {
|
|
5160
|
+
writeOurs(lowLevel, text, subagent, setInstructions, warnLength);
|
|
4706
5161
|
};
|
|
4707
5162
|
writeInstructions(ours);
|
|
4708
5163
|
const rewriteInstructions = (text) => {
|
|
@@ -4718,8 +5173,9 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4718
5173
|
get annotationToolName() {
|
|
4719
5174
|
return ctx.annotationToolName;
|
|
4720
5175
|
},
|
|
4721
|
-
|
|
4722
|
-
writeInstructions
|
|
5176
|
+
pointer: () => reports && ctx.annotationToolName ? buildReportPointer({ vendorDisplayName: reports.vendorDisplayName, annotationToolName: ctx.annotationToolName }) : void 0,
|
|
5177
|
+
writeInstructions,
|
|
5178
|
+
subagentLine: () => ![...ctx.paramRegistry.values()].some((d) => d[USER_GOAL_PARAM_NAME] === "native"),
|
|
4723
5179
|
injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
|
|
4724
5180
|
});
|
|
4725
5181
|
ctx.perCaller.followSettings();
|
|
@@ -4747,7 +5203,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4747
5203
|
annotationOptions && buildAnnotationTool(server, annotationOptions),
|
|
4748
5204
|
lowLevelTools,
|
|
4749
5205
|
warnOnce2,
|
|
4750
|
-
() => rewriteInstructions(INTENT_INSTRUCTIONS)
|
|
5206
|
+
() => ctx.perCaller ? ctx.perCaller.refresh() : rewriteInstructions(INTENT_INSTRUCTIONS)
|
|
4751
5207
|
);
|
|
4752
5208
|
}
|
|
4753
5209
|
installToolsListSeam(lowLevel, ctx, shape === "lowLevel");
|
|
@@ -4767,6 +5223,17 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4767
5223
|
ctx
|
|
4768
5224
|
);
|
|
4769
5225
|
installLifecycleSeams(lowLevel, ctx);
|
|
5226
|
+
const settings = config.captureSettings;
|
|
5227
|
+
if (settings !== void 0) {
|
|
5228
|
+
const waitFirst = (handler) => async (...args) => {
|
|
5229
|
+
if (!settings.isReady) await settings.ready;
|
|
5230
|
+
ctx.perCaller?.followSettings();
|
|
5231
|
+
return handler(...args);
|
|
5232
|
+
};
|
|
5233
|
+
for (const method of ["initialize", "server/discover", TOOLS_LIST_METHOD, TOOLS_CALL_METHOD]) {
|
|
5234
|
+
installRequestSeam(lowLevel, method, SETTINGS_SEAM, waitFirst);
|
|
5235
|
+
}
|
|
5236
|
+
}
|
|
4770
5237
|
const handle = (name) => new BatonHandle({
|
|
4771
5238
|
sink: given,
|
|
4772
5239
|
queue: sink,
|
|
@@ -4800,6 +5267,7 @@ function warnAboutSettings(config) {
|
|
|
4800
5267
|
`baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered`
|
|
4801
5268
|
);
|
|
4802
5269
|
}
|
|
5270
|
+
candidateNeedsConsole(config.settings);
|
|
4803
5271
|
if (config.resultCaptureMode === WITHHELD) {
|
|
4804
5272
|
warn(
|
|
4805
5273
|
'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.'
|