@goodtiming/baton-sdk 1.1.1 → 1.2.0

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