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