@goodtiming/baton-sdk 1.2.1 → 1.3.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.2.1";
56
+ var SDK_VERSION = "ts-1.3.0";
57
57
 
58
58
  // src/events.ts
59
59
  var import_zod = require("zod");
@@ -1931,18 +1931,18 @@ Fields:
1931
1931
  - suggested_improvement: one concrete sentence on the product change that would have helped.
1932
1932
  - context: supplementary info not covered above. Common keys: plan, alternatives_considered, likely_cause, user_impact, error_class, downstream_blocked, confidence_in_intent. When no tool covers the request also missing_capability_field and requested_capability.`;
1933
1933
  var CLAUDE_CODE_TRUNCATION_CAP = 2087;
1934
- var INSTRUCTIONS_LENGTH_CAP = 1500;
1934
+ var BATON_SENTENCE_LENGTH_CAP = 1500;
1935
1935
  function buildReportPointer(options) {
1936
1936
  return REPORT_POINTER_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
1937
1937
  }
1938
- function fitsInstructionsCap(options) {
1939
- return buildReportPointer(options).length <= INSTRUCTIONS_LENGTH_CAP;
1938
+ function fitsBatonSentenceCap(options) {
1939
+ return buildReportPointer(options).length <= BATON_SENTENCE_LENGTH_CAP;
1940
1940
  }
1941
1941
  function buildServerInstructions(options) {
1942
1942
  const rendered = buildReportPointer(options);
1943
- if (rendered.length > INSTRUCTIONS_LENGTH_CAP) {
1943
+ if (rendered.length > BATON_SENTENCE_LENGTH_CAP) {
1944
1944
  throw new Error(
1945
- `Rendered server instructions are ${rendered.length} chars, which exceeds the ${INSTRUCTIONS_LENGTH_CAP}-char safety cap (Claude Code truncates at ~${CLAUDE_CODE_TRUNCATION_CAP}). Shorten vendorDisplayName or annotationToolName.`
1945
+ `Baton's report sentence would be ${rendered.length} chars, over its ${BATON_SENTENCE_LENGTH_CAP}-char limit (Claude Code cuts server instructions at ~${CLAUDE_CODE_TRUNCATION_CAP}). Shorten vendorDisplayName or annotationToolName.`
1946
1946
  );
1947
1947
  }
1948
1948
  return rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
@@ -1950,6 +1950,9 @@ function buildServerInstructions(options) {
1950
1950
  function buildAnnotationToolDescription(options) {
1951
1951
  return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
1952
1952
  }
1953
+ function unknownToolText(name) {
1954
+ return `MCP error -32602: Tool ${name} not found`;
1955
+ }
1953
1956
  function buildRefusalText(options) {
1954
1957
  const text = `${options.annotationToolName} is reactive-only on this server. Call it only AFTER a tool call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. What the user is trying to do is already recorded on each tool call, so no pre-call annotation is needed \u2014 nothing was lost. If a tool call really went wrong, or no tool covers the request, call this again and say what_happened. If neither is true, do NOT re-send: that would file a report for a call that did not go wrong.`;
1955
1958
  return overlaid(text, options.overlay, "report_tool.refusal");
@@ -1992,6 +1995,30 @@ function mayDeclareParam(schema, name) {
1992
1995
  };
1993
1996
  return walk2(schema);
1994
1997
  }
1998
+ var VENDOR_SERVED_PIECES = [...INSTRUCTION_PIECES, "report_tool.description", "report_tool.refusal"];
1999
+ function servedAgentText(options) {
2000
+ const served = {};
2001
+ if (options.subagentServed) served["instructions.subagent"] = INTENT_INSTRUCTIONS;
2002
+ if (options.goalParamServed) {
2003
+ served["goal_param.description"] = buildUserGoalParamDescription({ intentParamMode: options.intentParamMode });
2004
+ }
2005
+ if (options.reportNames !== void 0) {
2006
+ served["instructions.report_pointer"] = buildReportPointer(options.reportNames);
2007
+ served["report_tool.description"] = buildAnnotationToolDescription(options.reportNames);
2008
+ served["report_tool.refusal"] = buildRefusalText({ annotationToolName: options.reportNames.annotationToolName });
2009
+ }
2010
+ const pieces = {};
2011
+ for (const [piece, text] of Object.entries(served)) {
2012
+ if (options.serverOverlay !== void 0 && INSTRUCTION_PIECES.includes(piece)) {
2013
+ const changed = changedText(text, options.serverOverlay.pieceActions(piece));
2014
+ pieces[piece] = { text: changed.text ?? text, source: changed.source };
2015
+ } else {
2016
+ pieces[piece] = { text, source: "default" };
2017
+ }
2018
+ }
2019
+ if (options.vendorServesText) for (const piece of VENDOR_SERVED_PIECES) pieces[piece] = null;
2020
+ return pieces;
2021
+ }
1995
2022
  function instructionsSuffixServed(annotationToolName, served) {
1996
2023
  if (annotationToolName) return true;
1997
2024
  return typeof served === "string" && served.includes(INTENT_INSTRUCTIONS);
@@ -2011,8 +2038,19 @@ ${ours}` : vendor;
2011
2038
  function vendorText(holder) {
2012
2039
  const current2 = holder._instructions;
2013
2040
  const written = holder[OURS];
2041
+ if (written === void 0) return current2;
2014
2042
  const vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
2015
- return written !== void 0 && current2 === joined(vendor, written) ? vendor : current2;
2043
+ if (current2 === joined(vendor, written)) return vendor;
2044
+ return withoutOurs(current2, written) ?? current2;
2045
+ }
2046
+ function withoutOurs(current2, ours) {
2047
+ if (!ours || typeof current2 !== "string") return void 0;
2048
+ const at = current2.lastIndexOf(ours);
2049
+ if (at < 0) return void 0;
2050
+ const before = current2.slice(0, at);
2051
+ const after = current2.slice(at + ours.length);
2052
+ if (before && !before.endsWith("\n\n") || after && !after.startsWith("\n\n")) return void 0;
2053
+ return joined(before.slice(0, -2), after.slice(2));
2016
2054
  }
2017
2055
  function writeOurs(server, ours, subagent, write, warn3 = stderrLine) {
2018
2056
  const holder = server;
@@ -2026,9 +2064,7 @@ function removeSubagentClause(server, write, warn3 = stderrLine) {
2026
2064
  const holder = server;
2027
2065
  const ours = holder[OURS];
2028
2066
  const subagent = holder[SUBAGENT];
2029
- if (ours === void 0 || !subagent || holder._instructions !== joined(holder[VENDOR_INSTRUCTIONS], ours)) {
2030
- return false;
2031
- }
2067
+ if (ours === void 0 || !subagent || vendorText(holder) === holder._instructions) return false;
2032
2068
  const kept = ours.slice(0, ours.length - subagent.length);
2033
2069
  writeOurs(server, kept.endsWith("\n\n") ? kept.slice(0, -2) : kept, null, write, warn3);
2034
2070
  return true;
@@ -2097,9 +2133,9 @@ function toolNameCandidate(serverName) {
2097
2133
  function displayNameFromServer(serverName, tool) {
2098
2134
  if (serverName === void 0) return void 0;
2099
2135
  const proposed = tool.annotationToolName || toolNameCandidate(serverName) || `${tool.vendorId}${SUFFIX}`;
2100
- if (!fitsInstructionsCap({ vendorDisplayName: serverName, annotationToolName: proposed })) {
2136
+ if (!fitsBatonSentenceCap({ vendorDisplayName: serverName, annotationToolName: proposed })) {
2101
2137
  warn(
2102
- `baton: the server name (${serverName.length} chars) does not fit the server-instructions budget as the display name beside the annotation tool ${JSON.stringify(proposed)}; keeping the DSN's server segment. Pass vendorDisplayName to name the server in fewer characters.`
2138
+ `baton: the server name (${serverName.length} chars) does not fit the budget of Baton's report sentence as the display name beside the annotation tool ${JSON.stringify(proposed)}; keeping the DSN's server segment. Pass vendorDisplayName to name the server in fewer characters.`
2103
2139
  );
2104
2140
  return void 0;
2105
2141
  }
@@ -2109,9 +2145,9 @@ function annotationToolNameFromServer(serverName, vendorDisplayName) {
2109
2145
  if (serverName === void 0) return void 0;
2110
2146
  const candidate = toolNameCandidate(serverName);
2111
2147
  if (candidate === void 0) return void 0;
2112
- if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: candidate })) {
2148
+ if (!fitsBatonSentenceCap({ vendorDisplayName, annotationToolName: candidate })) {
2113
2149
  warn(
2114
- `baton: the server-derived annotation tool name ${JSON.stringify(candidate)} does not fit the server-instructions budget beside the display name (${vendorDisplayName.length} chars); keeping {vendorId}_annotate. A shorter display name gets the readable one.`
2150
+ `baton: the server-derived annotation tool name ${JSON.stringify(candidate)} does not fit the budget of Baton's report sentence beside the display name (${vendorDisplayName.length} chars); keeping {vendorId}_annotate. A shorter display name gets the readable one.`
2115
2151
  );
2116
2152
  return void 0;
2117
2153
  }
@@ -2120,7 +2156,7 @@ function annotationToolNameFromServer(serverName, vendorDisplayName) {
2120
2156
  function toolNameForDisplayName(vendorDisplayName) {
2121
2157
  if (isPlaceholderLiteral(vendorDisplayName)) return void 0;
2122
2158
  const candidate = toolNameCandidate(vendorDisplayName);
2123
- return candidate !== void 0 && fitsInstructionsCap({ vendorDisplayName, annotationToolName: candidate }) ? candidate : void 0;
2159
+ return candidate !== void 0 && fitsBatonSentenceCap({ vendorDisplayName, annotationToolName: candidate }) ? candidate : void 0;
2124
2160
  }
2125
2161
  function deriveAnnotationToolName(vendorId2, override) {
2126
2162
  return validateAnnotationToolName(override || `${vendorId2}${SUFFIX}`);
@@ -2954,6 +2990,14 @@ function takesUserGoalJson(schema) {
2954
2990
  const properties = schema.properties ?? {};
2955
2991
  return isRecord(properties) && !ROOT_COMBINERS.some((key) => key in schema);
2956
2992
  }
2993
+ function goalTextsServed(tools) {
2994
+ const schemas = Array.isArray(tools) ? tools.map((tool) => isRecord(tool) ? tool.inputSchema : void 0) : [];
2995
+ const native = schemas.map((schema) => declaresParam(schema, USER_GOAL_PARAM_NAME));
2996
+ return {
2997
+ goalParamServed: schemas.some((schema, i) => isRecord(schema) && !native[i] && takesUserGoalJson(schema)),
2998
+ subagentServed: !native.some(Boolean)
2999
+ };
3000
+ }
2957
3001
  function withUserGoalJson(schema, intentParamMode, listRequired) {
2958
3002
  if (!takesUserGoalJson(schema) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return schema;
2959
3003
  const properties = schema.properties ?? {};
@@ -3189,13 +3233,13 @@ function sessionIdFromHeader(extra) {
3189
3233
  var TOOL_NAME_PARAM_NAME = "tool_name";
3190
3234
  var ANNOTATION_INPUT_SHAPE = {
3191
3235
  user_goal: import_zod3.z.string(),
3192
- what_happened: import_zod3.z.string().optional(),
3193
3236
  // Nullable so a report whose agent sends an explicit null is taken,
3194
3237
  // not rejected by validation.
3238
+ what_happened: import_zod3.z.string().nullable().optional(),
3195
3239
  tool_name: import_zod3.z.string().nullable().optional(),
3196
- suggested_improvement: import_zod3.z.string().optional(),
3240
+ suggested_improvement: import_zod3.z.string().nullable().optional(),
3197
3241
  // zod renders "any value" as `{}`, which some MCP clients refuse (reportToolSchema.test.ts).
3198
- context: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).meta({ additionalProperties: true }).optional()
3242
+ context: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).meta({ additionalProperties: true }).nullable().optional()
3199
3243
  };
3200
3244
  function isReport(whatHappened) {
3201
3245
  return typeof whatHappened === "string" && !isBlank(whatHappened);
@@ -3274,7 +3318,7 @@ function buildAnnotationTool(server, options) {
3274
3318
  payload: {
3275
3319
  // The agent-facing `user_goal` is stored as the wire key `intent`.
3276
3320
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
3277
- intent: options.scrubber(args.user_goal),
3321
+ intent: args.user_goal ? options.scrubber(args.user_goal) : null,
3278
3322
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
3279
3323
  what_happened: options.scrubber(whatHappened),
3280
3324
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
@@ -3299,7 +3343,7 @@ var PUBLISHABLE_PREFIX = "baton_pk_";
3299
3343
  var SECRET_PREFIX = "baton_sk_";
3300
3344
  var TEST_PREFIX = "baton_tk_";
3301
3345
  var KEY_PREFIXES = [PUBLISHABLE_PREFIX, SECRET_PREFIX, TEST_PREFIX];
3302
- var KEY_RUN = /baton_(?:(?:pk|sk|tk)_[A-Za-z0-9_%-]{8,}|[A-Za-z0-9_%-]{43,})/g;
3346
+ var KEY_RUN = /baton_(?:(?:pk|sk|tk)_[A-Za-z0-9_%-]{8,}|[A-Za-z0-9_%-]{43,})/gi;
3303
3347
  function looksLikeAKey(value) {
3304
3348
  return KEY_PREFIXES.some((prefix) => value.startsWith(prefix));
3305
3349
  }
@@ -3509,12 +3553,16 @@ function resolveInstallConfig(config) {
3509
3553
  return { resolved, unconfigured };
3510
3554
  }
3511
3555
  var consoleOffWarned = false;
3512
- function withoutConsoleOnWorkers(config) {
3513
- if (config.settings !== "console" || !onWorkers()) return config;
3556
+ function consoleDroppedOnWorkers(settings) {
3557
+ if (settings !== "console" || !onWorkers()) return false;
3514
3558
  if (!consoleOffWarned) {
3515
3559
  consoleOffWarned = true;
3516
3560
  warn(`baton: settings: "console" is not supported on Cloudflare Workers yet; the Console's settings are not read and this config's capture values apply.`);
3517
3561
  }
3562
+ return true;
3563
+ }
3564
+ function withoutConsoleOnWorkers(config) {
3565
+ if (!consoleDroppedOnWorkers(config.settings)) return config;
3518
3566
  const rest = { ...config, reportMode: config.reportMode ?? "on" };
3519
3567
  delete rest.settings;
3520
3568
  return rest;
@@ -3575,18 +3623,7 @@ function resolveBatonConfig(supplied) {
3575
3623
  // itself, exactly as it does for an explicitly-constructed sink.
3576
3624
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
3577
3625
  ...identity.settings === "console" ? {
3578
- captureSettings: new CaptureSettings(
3579
- dsn.vendorId,
3580
- new SettingsFetcher({
3581
- origin: dsn.origin,
3582
- apiKey: dsn.key,
3583
- tenantId: dsn.tenantId,
3584
- vendorId: dsn.vendorId,
3585
- refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
3586
- }),
3587
- envCandidate(),
3588
- envTask()
3589
- )
3626
+ captureSettings: consoleCaptureSettings(dsn, identity.settingsRefreshMs)
3590
3627
  } : {}
3591
3628
  };
3592
3629
  }
@@ -3601,6 +3638,36 @@ function withServerDisplayName(resolved, supplied, serverName) {
3601
3638
  var RENAMED_KEYS = {
3602
3639
  resolveUser: "resolvePrincipal"
3603
3640
  };
3641
+ function consoleCaptureSettings(dsn, refreshMs) {
3642
+ const fetcher = new SettingsFetcher({
3643
+ origin: dsn.origin,
3644
+ apiKey: dsn.key,
3645
+ tenantId: dsn.tenantId,
3646
+ vendorId: dsn.vendorId,
3647
+ refreshMs: refreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
3648
+ });
3649
+ return new CaptureSettings(dsn.vendorId, fetcher, envCandidate(), envTask());
3650
+ }
3651
+ function validateReportMode(config, owner) {
3652
+ if (config.reportMode !== void 0 && !REPORT_MODES.has(config.reportMode)) {
3653
+ throw new Error(
3654
+ `${owner}.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
3655
+ );
3656
+ }
3657
+ }
3658
+ function validateSettings(config, owner) {
3659
+ if (config.settings !== void 0 && !SETTINGS_MODES.includes(config.settings)) {
3660
+ throw new Error(
3661
+ `${owner}.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`
3662
+ );
3663
+ }
3664
+ const refresh = config.settingsRefreshMs;
3665
+ if (refresh !== void 0 && (typeof refresh !== "number" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))) {
3666
+ throw new Error(
3667
+ `${owner}.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} to ${String(MAX_TIMER_MS)}.`
3668
+ );
3669
+ }
3670
+ }
3604
3671
  function validateBatonConfig(config) {
3605
3672
  for (const [was, now] of Object.entries(RENAMED_KEYS)) {
3606
3673
  if (was in config) {
@@ -3617,11 +3684,7 @@ function validateBatonConfig(config) {
3617
3684
  `vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
3618
3685
  );
3619
3686
  }
3620
- if (config.reportMode !== void 0 && !REPORT_MODES.has(config.reportMode)) {
3621
- throw new Error(
3622
- `BatonConfig.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
3623
- );
3624
- }
3687
+ validateReportMode(config, "BatonConfig");
3625
3688
  if (!config.vendorDisplayName && config.reportMode === "on") {
3626
3689
  throw new Error(
3627
3690
  'BatonConfig needs a vendorDisplayName with reportMode: "on" \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4).'
@@ -3652,17 +3715,7 @@ function validateBatonConfig(config) {
3652
3715
  `BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
3653
3716
  );
3654
3717
  }
3655
- if (config.settings !== void 0 && !SETTINGS_MODES.includes(config.settings)) {
3656
- throw new Error(
3657
- `BatonConfig.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`
3658
- );
3659
- }
3660
- const refresh = config.settingsRefreshMs;
3661
- if (refresh !== void 0 && (typeof refresh !== "number" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))) {
3662
- throw new Error(
3663
- `BatonConfig.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} to ${String(MAX_TIMER_MS)}.`
3664
- );
3665
- }
3718
+ validateSettings(config, "BatonConfig");
3666
3719
  if (config.scrubber !== void 0 && typeof config.scrubber !== "function") {
3667
3720
  throw new Error("BatonConfig.scrubber must be a function.");
3668
3721
  }
@@ -3796,33 +3849,35 @@ var PerCallerSurface = class {
3796
3849
  }
3797
3850
  /** `result` with the caller's goal, reports and overlay; as served on any failure. */
3798
3851
  toolsFor(result, caller) {
3799
- const settings = caller.settings;
3800
- if (settings === void 0) return result;
3801
- const { intentParamMode, annotationToolName, injectsGoal } = this.options;
3802
- const goal = settings.intentParamMode ?? intentParamMode;
3803
- const hideReports = annotationToolName !== "" && settings.reportMode === "off";
3804
- const overlay = settings.overlay;
3805
- if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
3806
- try {
3807
- const tools = result?.tools;
3808
- if (!Array.isArray(tools)) return result;
3809
- const served = [];
3810
- const injected = [];
3811
- for (const tool of tools) {
3812
- const name = tool?.name;
3813
- if (hideReports && name === annotationToolName) continue;
3814
- const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
3815
- served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
3816
- injected.push(ours);
3817
- }
3818
- const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
3819
- return { ...result, tools: rewritten };
3820
- } catch (err) {
3821
- stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
3822
- return result;
3823
- }
3852
+ return toolsForCaller(result, caller.settings, this.options);
3824
3853
  }
3825
3854
  };
3855
+ function toolsForCaller(result, settings, options) {
3856
+ if (settings === void 0) return result;
3857
+ const { intentParamMode, annotationToolName, injectsGoal } = options;
3858
+ const goal = settings.intentParamMode ?? intentParamMode;
3859
+ const hideReports = annotationToolName !== "" && settings.reportMode === "off";
3860
+ const overlay = settings.overlay;
3861
+ if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
3862
+ try {
3863
+ const tools = result?.tools;
3864
+ if (!Array.isArray(tools)) return result;
3865
+ const served = [];
3866
+ const injected = [];
3867
+ for (const tool of tools) {
3868
+ const name = tool?.name;
3869
+ if (hideReports && name === annotationToolName) continue;
3870
+ const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
3871
+ served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
3872
+ injected.push(ours);
3873
+ }
3874
+ const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
3875
+ return { ...result, tools: rewritten };
3876
+ } catch (err) {
3877
+ stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
3878
+ return result;
3879
+ }
3880
+ }
3826
3881
  function batonParagraphs(pointer, overlay, subagentLine) {
3827
3882
  const parts = overlay?.instructionAppends() ?? [];
3828
3883
  if (pointer !== void 0) parts.push(overlaid(pointer, overlay, "instructions.report_pointer"));
@@ -3833,7 +3888,7 @@ function batonParagraphs(pointer, overlay, subagentLine) {
3833
3888
  function withOverlay(tools, injected, overlay, reportTool2) {
3834
3889
  const position = /* @__PURE__ */ new Map();
3835
3890
  tools.forEach((tool, i) => position.set(tool?.name, i));
3836
- const hidden = /* @__PURE__ */ new Set();
3891
+ const hidden2 = /* @__PURE__ */ new Set();
3837
3892
  for (const action of overlay.actions) {
3838
3893
  if (action.tool === void 0) continue;
3839
3894
  const i = position.get(action.tool);
@@ -3842,7 +3897,7 @@ function withOverlay(tools, injected, overlay, reportTool2) {
3842
3897
  } else if (action.tool === reportTool2) {
3843
3898
  warnSkipped(overlay.id, action.index, "the report tool takes agent_text targets only");
3844
3899
  } else if (action.param === void 0 && action.change === "remove") {
3845
- hidden.add(i);
3900
+ hidden2.add(i);
3846
3901
  } else if (action.param === void 0) {
3847
3902
  tools[i] = withDescription(tools[i], [action]);
3848
3903
  } else {
@@ -3861,7 +3916,7 @@ function withOverlay(tools, injected, overlay, reportTool2) {
3861
3916
  if (reportActions.length > 0 && reportAt !== void 0) {
3862
3917
  tools[reportAt] = withDescription(tools[reportAt], reportActions);
3863
3918
  }
3864
- return tools.filter((_, i) => !hidden.has(i));
3919
+ return tools.filter((_, i) => !hidden2.has(i));
3865
3920
  }
3866
3921
  function withDescription(tool, actions) {
3867
3922
  const description = typeof tool.description === "string" ? tool.description : void 0;
@@ -4017,7 +4072,8 @@ function buildSeamAugmentations(options) {
4017
4072
  required_names: [...options.requiredParamNames].sort(),
4018
4073
  mode: options.intentParamMode
4019
4074
  },
4020
- instructions_suffix: options.instructionsSuffix
4075
+ instructions_suffix: options.instructionsSuffix,
4076
+ agent_text: options.agentText
4021
4077
  };
4022
4078
  }
4023
4079
 
@@ -4372,7 +4428,13 @@ async function maybeEmitSurfaceSnapshot(ctx) {
4372
4428
  intentParamNames: [USER_GOAL_PARAM_NAME],
4373
4429
  intentParamMode: ctx.intentParamMode,
4374
4430
  requiredParamNames: requiredParamNames(ctx.intentParamMode),
4375
- instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions())
4431
+ instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions()),
4432
+ agentText: servedAgentText({
4433
+ reportNames: ctx.reportNames(),
4434
+ intentParamMode: ctx.intentParamMode,
4435
+ ...goalTextsServed(snapshot.tools),
4436
+ serverOverlay: ctx.perCaller?.serverOverlay
4437
+ })
4376
4438
  });
4377
4439
  if (ctx.captureSettings !== void 0) seam.server_overlay = overlayId;
4378
4440
  await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
@@ -4485,16 +4547,21 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
4485
4547
  }
4486
4548
  }
4487
4549
  };
4550
+ const leaveReportNameToVendor = (name) => {
4551
+ warnOnce2(
4552
+ "report-tool-name-taken",
4553
+ `baton: the server lists its own tool ${JSON.stringify(name)}, so Baton's report tool is not added; set annotationToolName to another name`
4554
+ );
4555
+ reportTool2 = void 0;
4556
+ ctx.annotationToolName = "";
4557
+ reportToolTaken();
4558
+ };
4559
+ const takeReportNameIfListed = (tools) => {
4560
+ const name = reportTool2?.name;
4561
+ if (name !== void 0 && tools.some((tool) => tool.name === name)) leaveReportNameToVendor(name);
4562
+ };
4488
4563
  const read = (tools, { surface }) => {
4489
- if (surface && reportTool2 !== void 0 && tools.some((tool) => tool.name === reportTool2?.name)) {
4490
- warnOnce2(
4491
- "report-tool-name-taken",
4492
- `baton: the server lists its own tool ${JSON.stringify(reportTool2.name)}, so Baton's report tool is not added; set annotationToolName to another name`
4493
- );
4494
- reportTool2 = void 0;
4495
- ctx.annotationToolName = "";
4496
- reportToolTaken();
4497
- }
4564
+ if (surface) takeReportNameIfListed(tools);
4498
4565
  readToolList(tools, ctx, surface, skipNote);
4499
4566
  };
4500
4567
  const learn = (tools) => {
@@ -4582,6 +4649,10 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
4582
4649
  }
4583
4650
  return batonWrap({ current: name }, () => handler(...args), ctx, unlisted, slot?.caller)(toolArgs, args[1]);
4584
4651
  });
4652
+ return () => {
4653
+ if (Array.isArray(known.given)) takeReportNameIfListed(toolInfos(known.given, () => {
4654
+ }));
4655
+ };
4585
4656
  }
4586
4657
  function lowLevelMajor(lowLevel) {
4587
4658
  return typeof lowLevel._wrapHandler === "function" ? 2 : 1;
@@ -4872,7 +4943,7 @@ async function hiddenFrom(slot, name, params, extra, ctx) {
4872
4943
  }
4873
4944
  async function answerHidden(lowLevel, name, settle) {
4874
4945
  if (lowLevelMajor(lowLevel) === 1) {
4875
- const result = { content: [{ type: "text", text: `MCP error -32602: Tool ${name} not found` }], isError: true };
4946
+ const result = { content: [{ type: "text", text: unknownToolText(name) }], isError: true };
4876
4947
  await settle({ failed: true, raised: false, result });
4877
4948
  return result;
4878
4949
  }
@@ -5225,6 +5296,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned4, co
5225
5296
  server,
5226
5297
  scrubber,
5227
5298
  annotationToolName,
5299
+ reportNames: () => reports && ctx.annotationToolName ? { vendorDisplayName: reports.vendorDisplayName, annotationToolName: ctx.annotationToolName } : void 0,
5228
5300
  intentParamMode,
5229
5301
  configResultCaptureMode: config.resultCaptureMode ?? "full",
5230
5302
  paramRegistry: /* @__PURE__ */ new Map(),
@@ -5255,7 +5327,10 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned4, co
5255
5327
  get annotationToolName() {
5256
5328
  return ctx.annotationToolName;
5257
5329
  },
5258
- pointer: () => reports && ctx.annotationToolName ? buildReportPointer({ vendorDisplayName: reports.vendorDisplayName, annotationToolName: ctx.annotationToolName }) : void 0,
5330
+ pointer: () => {
5331
+ const names = ctx.reportNames();
5332
+ return names && buildReportPointer(names);
5333
+ },
5259
5334
  writeInstructions,
5260
5335
  subagentLine: () => ![...ctx.paramRegistry.values()].some((d) => d[USER_GOAL_PARAM_NAME] === "native"),
5261
5336
  injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
@@ -5278,8 +5353,9 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned4, co
5278
5353
  // `srv-..._annotate` while the instructions name the server-derived one.
5279
5354
  annotationToolName
5280
5355
  };
5356
+ let checkGivenTools;
5281
5357
  if (shape === "lowLevel") {
5282
- installLowLevelToolSeams(
5358
+ checkGivenTools = installLowLevelToolSeams(
5283
5359
  lowLevel,
5284
5360
  ctx,
5285
5361
  annotationOptions && buildAnnotationTool(server, annotationOptions),
@@ -5323,7 +5399,10 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned4, co
5323
5399
  sessionId: fallbackSessionId,
5324
5400
  annotationToolName: name
5325
5401
  });
5326
- if (shape === "lowLevel") return handle(annotationToolName);
5402
+ if (shape === "lowLevel") {
5403
+ checkGivenTools?.();
5404
+ return handle(annotationToolName);
5405
+ }
5327
5406
  const resolvedAnnotationToolName = annotationOptions ? registerAnnotationTool(server, annotationOptions) : "";
5328
5407
  const existing = internals._registeredTools;
5329
5408
  if (existing) {
@@ -5388,6 +5467,9 @@ function principalFromOAuthEmail(context) {
5388
5467
  };
5389
5468
  }
5390
5469
 
5470
+ // src/library/client.ts
5471
+ var asyncHooks3 = __toESM(require("async_hooks"), 1);
5472
+
5391
5473
  // src/library/session.ts
5392
5474
  var asyncHooks2 = __toESM(require("async_hooks"), 1);
5393
5475
  var TRANSPORT_LIBRARY = "library";
@@ -5401,7 +5483,8 @@ function sessionEnvelope(session) {
5401
5483
  organization: session.organization,
5402
5484
  labels: wireLabels(session.labels),
5403
5485
  client_observed: session.clientObserved,
5404
- runtime_meta: session.runtimeMeta
5486
+ runtime_meta: session.runtimeMeta,
5487
+ capture: session.settings?.capture ?? null
5405
5488
  };
5406
5489
  }
5407
5490
  function warn2(message) {
@@ -5416,7 +5499,7 @@ function vendorId(name, value) {
5416
5499
  return null;
5417
5500
  }
5418
5501
  function blank(sessionId, origin) {
5419
- return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };
5502
+ return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null, candidate: null, task: null };
5420
5503
  }
5421
5504
  function requestMeta(meta) {
5422
5505
  if (isRecord(meta)) return meta;
@@ -5439,16 +5522,48 @@ function newSession(values, scrubber, disabled) {
5439
5522
  ...base,
5440
5523
  ...callerFor(values.principal, (_key, message) => warn2(`principal ${message}`)),
5441
5524
  clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber, meta),
5442
- runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
5525
+ runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber),
5526
+ candidate: vendorHeader(values.headers, CANDIDATE_HEADER, candidateId),
5527
+ task: vendorHeader(values.headers, TASK_HEADER, taskId)
5443
5528
  };
5444
5529
  }
5530
+ function vendorHeader(headers, name, parse) {
5531
+ try {
5532
+ if (headers === void 0) return null;
5533
+ if (typeof headers.get === "function") return parse(headers.get(name));
5534
+ const key = Object.keys(headers).find((k) => k.toLowerCase() === name);
5535
+ return key === void 0 ? null : parse(headers[key]);
5536
+ } catch {
5537
+ return null;
5538
+ }
5539
+ }
5445
5540
  var current = new asyncHooks2.AsyncLocalStorage();
5446
5541
  function runInSession(owner, session, fn) {
5447
5542
  return current.run({ owner, session }, fn);
5448
5543
  }
5449
- function sessionForCall(owner) {
5450
- const entry = current.getStore();
5451
- return entry !== void 0 && entry.owner === owner ? entry.session : blank(uuid7(), "minted");
5544
+ var settingsWarned2 = false;
5545
+ function sessionForCall(owner, settings) {
5546
+ const session = inBlock(owner) ? current.getStore().session : blank(uuid7(), "minted");
5547
+ if (settings === void 0) return session;
5548
+ try {
5549
+ const callSettings = settings.forCaller({
5550
+ labels: session.labels,
5551
+ clientName: session.clientObserved?.info?.name ?? null,
5552
+ shareKey: session.principal?.id ?? null,
5553
+ candidate: session.candidate,
5554
+ task: session.task
5555
+ });
5556
+ return callSettings === void 0 ? session : { ...session, settings: callSettings };
5557
+ } catch (err) {
5558
+ if (!settingsWarned2) {
5559
+ settingsWarned2 = true;
5560
+ warn2(`applying capture settings failed; this call uses the client's values: ${printable(err)}`);
5561
+ }
5562
+ return session;
5563
+ }
5564
+ }
5565
+ function inBlock(owner) {
5566
+ return current.getStore()?.owner === owner;
5452
5567
  }
5453
5568
 
5454
5569
  // src/library/surface.ts
@@ -5480,16 +5595,22 @@ function serveTools(tools, options) {
5480
5595
  return { served, surface: null };
5481
5596
  }
5482
5597
  }
5483
- function snapshotPayload({ surface, digest }) {
5598
+ function snapshotPayload({ surface, digest }, seam) {
5484
5599
  return {
5485
5600
  surface_hash: digest,
5486
5601
  ...surface,
5487
- seam_augmentations: buildSeamAugmentations({
5602
+ seam_augmentations: seam ?? buildSeamAugmentations({
5488
5603
  injectedToolNames: [],
5489
5604
  intentParamNames: [USER_GOAL_PARAM_NAME],
5490
5605
  intentParamMode: DEFAULT_INTENT_PARAM_MODE,
5491
5606
  requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),
5492
- instructionsSuffix: null
5607
+ instructionsSuffix: null,
5608
+ agentText: servedAgentText({
5609
+ reportNames: void 0,
5610
+ intentParamMode: DEFAULT_INTENT_PARAM_MODE,
5611
+ ...goalTextsServed(surface.tools),
5612
+ vendorServesText: true
5613
+ })
5493
5614
  })
5494
5615
  };
5495
5616
  }
@@ -5498,6 +5619,315 @@ function servedEntry(tool) {
5498
5619
  return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, DEFAULT_INTENT_PARAM_MODE, true) };
5499
5620
  }
5500
5621
 
5622
+ // src/library/serve.ts
5623
+ var INITIALIZE = "initialize";
5624
+ var TOOL_LIST = "tools/list";
5625
+ var TOOL_CALL = "tools/call";
5626
+ var JSONRPC_ERROR_TYPE = "JSONRPCError";
5627
+ var REMEMBERED_TOOLS = 4096;
5628
+ function readRequest(message) {
5629
+ if (!isRecord(message) || message.id === void 0 || message.id === null) return null;
5630
+ const { method } = message;
5631
+ const params = message.params === void 0 ? {} : message.params;
5632
+ if (method !== INITIALIZE && method !== TOOL_LIST && method !== TOOL_CALL || !isRecord(params)) return null;
5633
+ return { method, params };
5634
+ }
5635
+ var OWN = /* @__PURE__ */ new Set(["native", "may_take"]);
5636
+ var KEPT = /* @__PURE__ */ new Set(["native", "may_take", "unread"]);
5637
+ function goalDispositions(schema) {
5638
+ if (schema === void 0 || schema === null) return { [USER_GOAL_PARAM_NAME]: "injected" };
5639
+ const retired = Object.fromEntries(RETIRED_PARAM_NAMES.map((name) => [name, "native"]));
5640
+ if (!isRecord(schema) || !isRecord(schema.properties ?? {})) {
5641
+ return { ...retired, [USER_GOAL_PARAM_NAME]: "unread" };
5642
+ }
5643
+ if (!takesUserGoalJson(schema)) {
5644
+ if (declaresParam(schema, USER_GOAL_PARAM_NAME)) return { ...retired, [USER_GOAL_PARAM_NAME]: "native" };
5645
+ return mayDeclareParam(schema, USER_GOAL_PARAM_NAME) ? { ...retired, [USER_GOAL_PARAM_NAME]: "may_take" } : retired;
5646
+ }
5647
+ const dispositions = {};
5648
+ for (const name of RETIRED_PARAM_NAMES) if (declaresParam(schema, name)) dispositions[name] = "native";
5649
+ dispositions[USER_GOAL_PARAM_NAME] = declaresParam(schema, USER_GOAL_PARAM_NAME) ? "native" : "injected";
5650
+ return dispositions;
5651
+ }
5652
+ var ownsUserGoal = (dispositions) => OWN.has(dispositions?.[USER_GOAL_PARAM_NAME]);
5653
+ var NO_GOALS = [null, null, null];
5654
+ function popGoals(args, dispositions) {
5655
+ const pop = (name) => {
5656
+ if (!(name in args) || dispositions !== void 0 && KEPT.has(dispositions[name])) return null;
5657
+ const value = args[name];
5658
+ delete args[name];
5659
+ return typeof value === "string" && !isBlank(value) ? value : null;
5660
+ };
5661
+ if (dispositions === void 0) return [pop(USER_GOAL_PARAM_NAME), null, null];
5662
+ return [pop(USER_GOAL_PARAM_NAME), pop(RETIRED_PARAM_NAMES[0]), pop(RETIRED_PARAM_NAMES[1])];
5663
+ }
5664
+ function knownTools(tools) {
5665
+ const dispositions = /* @__PURE__ */ new Map();
5666
+ const names = /* @__PURE__ */ new Set();
5667
+ for (const tool of tools) {
5668
+ try {
5669
+ const name = isRecord(tool) ? tool.name : void 0;
5670
+ if (typeof name !== "string") continue;
5671
+ names.add(name);
5672
+ dispositions.set(name, goalDispositions(tool.inputSchema));
5673
+ } catch {
5674
+ continue;
5675
+ }
5676
+ }
5677
+ return { dispositions, names };
5678
+ }
5679
+ function traceOptions(call) {
5680
+ const [intent, expected, workflow] = call.goals;
5681
+ return {
5682
+ toolName: call.name,
5683
+ params: call.arguments,
5684
+ ...intent === null ? {} : { intent },
5685
+ ...expected === null ? {} : { expectedOutcome: expected },
5686
+ ...workflow === null ? {} : { workflow }
5687
+ };
5688
+ }
5689
+ var Serving = class {
5690
+ constructor(report, settings, tools) {
5691
+ this.report = report;
5692
+ this.settings = settings;
5693
+ this.unreadTools = tools;
5694
+ if (report !== void 0 && Array.isArray(tools)) {
5695
+ try {
5696
+ this.remember(/* @__PURE__ */ new Map(), knownTools(tools).names);
5697
+ } catch {
5698
+ }
5699
+ }
5700
+ }
5701
+ report;
5702
+ settings;
5703
+ serverMeta = { serverInfo: null, capabilities: null, instructions: null };
5704
+ dispositions = /* @__PURE__ */ new Map();
5705
+ vendorHasReportName = false;
5706
+ warnedUnlisted = false;
5707
+ unreadTools;
5708
+ /** Learn the vendor's `tools` once per process. Never throws: without them,
5709
+ * a call to a tool not yet listed is served as on a cold process. */
5710
+ readVendorTools() {
5711
+ const source = this.unreadTools;
5712
+ if (source === void 0) return;
5713
+ this.unreadTools = void 0;
5714
+ try {
5715
+ const tools = typeof source === "function" ? source() : source;
5716
+ if (isThenable(tools)) {
5717
+ throw new Error("tools must be an array or a plain function, not async");
5718
+ }
5719
+ if (!Array.isArray(tools)) throw new Error("tools gave something that is not an array");
5720
+ const known = knownTools(tools);
5721
+ this.remember(known.dispositions, known.names);
5722
+ } catch (err) {
5723
+ stderrLine(
5724
+ `baton: could not read the tools option; a call this process has not seen listed loses user_goal: ${printable(err)}`
5725
+ );
5726
+ }
5727
+ }
5728
+ remember(dispositions, names) {
5729
+ const fresh = [...dispositions.keys()].filter((name2) => !this.dispositions.has(name2)).length;
5730
+ if (this.dispositions.size + fresh > REMEMBERED_TOOLS) this.dispositions.clear();
5731
+ for (const [name2, disposition] of dispositions) {
5732
+ if (!ownsUserGoal(this.dispositions.get(name2))) this.dispositions.set(name2, disposition);
5733
+ }
5734
+ const name = this.report?.tool.name;
5735
+ if (name !== void 0 && names.has(name) && !this.vendorHasReportName) {
5736
+ this.vendorHasReportName = true;
5737
+ stderrLine(
5738
+ `baton: your tool ${JSON.stringify(name)} has the report tool's name, so Baton serves yours and no report tool. Set vendorDisplayName to give Baton's another name.`
5739
+ );
5740
+ }
5741
+ }
5742
+ /** The report tool, unless a vendor tool has its name. */
5743
+ ours() {
5744
+ return this.vendorHasReportName ? void 0 : this.report;
5745
+ }
5746
+ document() {
5747
+ return this.settings?.document ?? null;
5748
+ }
5749
+ initialized(answer) {
5750
+ const result = resultOf(answer);
5751
+ if (result === null) return answer;
5752
+ const vendor = result.instructions;
5753
+ this.readVendorTools();
5754
+ this.serverMeta = {
5755
+ serverInfo: isRecord(result.serverInfo) ? result.serverInfo : null,
5756
+ capabilities: isRecord(result.capabilities) ? result.capabilities : null,
5757
+ instructions: typeof vendor === "string" ? vendor : null
5758
+ };
5759
+ const nativeGoal = [...this.dispositions.values()].some((d) => d[USER_GOAL_PARAM_NAME] === "native");
5760
+ const report = this.ours();
5761
+ const document = this.document();
5762
+ const pointer = report === void 0 ? void 0 : buildReportPointer({ vendorDisplayName: report.vendorDisplayName, annotationToolName: report.tool.name });
5763
+ const shown = pointer !== void 0 && (document === null || document.reportsOnForAnyone);
5764
+ const { ours } = batonParagraphs(shown ? pointer : void 0, document?.serverOverlay, !nativeGoal);
5765
+ return { ...answer, result: { ...result, instructions: joined(vendor, ours) } };
5766
+ }
5767
+ listed(request, answer, settings) {
5768
+ const result = resultOf(answer);
5769
+ const tools = result?.tools;
5770
+ if (result === null || !Array.isArray(tools)) return null;
5771
+ this.readVendorTools();
5772
+ const { served, surface } = serveTools(tools, this.serverMeta);
5773
+ const known = knownTools(tools);
5774
+ this.remember(known.dispositions, known.names);
5775
+ const report = this.ours();
5776
+ const firstPage = request.params.cursor === void 0 || request.params.cursor === null;
5777
+ const out = [...served];
5778
+ if (report !== void 0 && firstPage) {
5779
+ const { name, description, inputSchema: inputSchema2 } = report.tool;
5780
+ out.push({ name, description, inputSchema: inputSchema2 });
5781
+ }
5782
+ const overlay = this.document()?.serverOverlay;
5783
+ const overlayId = overlay?.id ?? null;
5784
+ const listed = toolsForCaller({ ...result, tools: out }, settings, {
5785
+ intentParamMode: DEFAULT_INTENT_PARAM_MODE,
5786
+ annotationToolName: report?.tool.name ?? "",
5787
+ injectsGoal: (name) => known.dispositions.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
5788
+ });
5789
+ const whole = firstPage && (result.nextCursor === void 0 || result.nextCursor === null) ? surface : null;
5790
+ return {
5791
+ answer: { ...answer, result: listed },
5792
+ surface: whole,
5793
+ seam: () => {
5794
+ const agentText = servedAgentText({
5795
+ reportNames: report === void 0 ? void 0 : { vendorDisplayName: report.vendorDisplayName, annotationToolName: report.tool.name },
5796
+ intentParamMode: DEFAULT_INTENT_PARAM_MODE,
5797
+ ...goalTextsServed(whole?.surface.tools ?? []),
5798
+ serverOverlay: overlay
5799
+ });
5800
+ const seam = buildSeamAugmentations({
5801
+ injectedToolNames: report === void 0 ? [] : [report.tool.name],
5802
+ intentParamNames: [USER_GOAL_PARAM_NAME],
5803
+ intentParamMode: DEFAULT_INTENT_PARAM_MODE,
5804
+ requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),
5805
+ instructionsSuffix: instructionsSuffix(agentText),
5806
+ agentText
5807
+ });
5808
+ if (this.settings !== void 0) seam.server_overlay = overlayId;
5809
+ return seam;
5810
+ },
5811
+ serverOverlay: overlayId
5812
+ };
5813
+ }
5814
+ /** The plan for one `tools/call`; `null` sends it to dispatch untraced. */
5815
+ call(request, message, settings) {
5816
+ const { name } = request.params;
5817
+ const args = request.params.arguments === void 0 ? {} : request.params.arguments;
5818
+ if (typeof name !== "string" || !isRecord(args)) return null;
5819
+ this.readVendorTools();
5820
+ const dispositions = this.dispositions.get(name);
5821
+ const report = this.ours();
5822
+ if (report !== void 0 && name === report.tool.name) return reportCall(report.tool, name, args, message, settings);
5823
+ if (dispositions === void 0 && USER_GOAL_PARAM_NAME in args && !this.warnedUnlisted) {
5824
+ this.warnedUnlisted = true;
5825
+ stderrLine(
5826
+ `baton: removed user_goal from a call to ${JSON.stringify(name)}, a tool in no list this process has served or read from the tools option; a tool that declares its own user_goal keeps it only once Baton has seen its schema`
5827
+ );
5828
+ }
5829
+ const stripped = { ...args };
5830
+ const goals = popGoals(stripped, dispositions);
5831
+ if (settings?.overlay?.hiddenTools.has(name)) return hidden(name, stripped, goals, message);
5832
+ const forwarded = Object.keys(stripped).length === Object.keys(args).length ? message : { ...message, params: { ...request.params, arguments: stripped } };
5833
+ return { name, arguments: stripped, goals, message: forwarded, kind: "forward" };
5834
+ }
5835
+ };
5836
+ function reportCall(tool, name, args, message, settings) {
5837
+ if (settings?.reportMode === "off") return hidden(name, { ...args }, NO_GOALS, message);
5838
+ const report = tool.annotateArgs(args);
5839
+ const body = report === null ? { ok: false, error: buildRefusalText({ annotationToolName: name, overlay: settings?.overlay }) } : { ok: true };
5840
+ return {
5841
+ name,
5842
+ arguments: { ...args },
5843
+ goals: NO_GOALS,
5844
+ message,
5845
+ kind: report === null ? "refused" : "report",
5846
+ answer: answerTo(message, { content: [{ type: "text", text: JSON.stringify(body) }], structuredContent: body }),
5847
+ ...report === null ? {} : { report }
5848
+ };
5849
+ }
5850
+ function hidden(name, args, goals, message) {
5851
+ const result = { content: [{ type: "text", text: unknownToolText(name) }], isError: true };
5852
+ return { name, arguments: args, goals, message, kind: "hidden", answer: answerTo(message, result) };
5853
+ }
5854
+ function withoutUserGoal(message) {
5855
+ try {
5856
+ const params = message.params;
5857
+ const args = params.arguments;
5858
+ if (!isRecord(args) || !(USER_GOAL_PARAM_NAME in args)) return message;
5859
+ const stripped = Object.fromEntries(Object.entries(args).filter(([key]) => key !== USER_GOAL_PARAM_NAME));
5860
+ return { ...message, params: { ...params, arguments: stripped } };
5861
+ } catch {
5862
+ return message;
5863
+ }
5864
+ }
5865
+ function jsonRpcError(answer) {
5866
+ return isRecord(answer) && isRecord(answer.error) ? answer.error : null;
5867
+ }
5868
+ function resultOf(answer) {
5869
+ return isRecord(answer) && isRecord(answer.result) ? { ...answer.result } : null;
5870
+ }
5871
+ function isToolErrorResult(result) {
5872
+ return result !== null && Array.isArray(result.content) && result.isError === true;
5873
+ }
5874
+ function answerTo(message, result) {
5875
+ return { jsonrpc: message.jsonrpc ?? "2.0", id: message.id, result };
5876
+ }
5877
+ function instructionsSuffix(agentText) {
5878
+ const pieces = INSTRUCTION_PIECES.filter((piece) => piece in agentText).map((piece) => agentText[piece]);
5879
+ return pieces.includes(null) ? null : pieces.length > 0;
5880
+ }
5881
+
5882
+ // src/library/reportTool.ts
5883
+ function inputSchema() {
5884
+ const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
5885
+ delete schema.$schema;
5886
+ return { ...schema, required: [...schema.required, TOOL_NAME_PARAM_NAME] };
5887
+ }
5888
+ var nonEmptyText = (value) => typeof value === "string" && value !== "";
5889
+ var nonEmptyObject = (value) => isRecord(value) && Object.keys(value).length > 0;
5890
+ function annotateArgs(args) {
5891
+ const whatHappened = args.what_happened;
5892
+ if (!isReport(whatHappened)) return null;
5893
+ const options = { whatHappened };
5894
+ const toolName = args[TOOL_NAME_PARAM_NAME];
5895
+ if (typeof toolName === "string") options.toolName = toolName;
5896
+ const intent = args[USER_GOAL_PARAM_NAME];
5897
+ if (nonEmptyText(intent)) options.intent = intent;
5898
+ if (nonEmptyText(args.suggested_improvement)) {
5899
+ options.suggestedImprovement = args.suggested_improvement;
5900
+ }
5901
+ if (nonEmptyObject(args.context)) options.context = args.context;
5902
+ return options;
5903
+ }
5904
+ function reportTool(options) {
5905
+ const { vendorDisplayName } = options;
5906
+ if (isBlank(vendorDisplayName)) {
5907
+ throw new Error("vendorDisplayName is blank. Baton's report sentence names the server by it.");
5908
+ }
5909
+ const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);
5910
+ if (derived === void 0) {
5911
+ throw new Error(
5912
+ `vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, or one too long for Baton's report sentence. Pass name.`
5913
+ );
5914
+ }
5915
+ const name = validateAnnotationToolName(derived);
5916
+ if (!fitsBatonSentenceCap({ vendorDisplayName, annotationToolName: name })) {
5917
+ throw new Error(
5918
+ `vendorDisplayName and name ${JSON.stringify(name)} are too long together for Baton's report sentence. Shorten one of them.`
5919
+ );
5920
+ }
5921
+ return {
5922
+ name,
5923
+ description: buildAnnotationToolDescription({ vendorDisplayName }),
5924
+ inputSchema: inputSchema(),
5925
+ instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),
5926
+ refusal: buildRefusalText({ annotationToolName: name }),
5927
+ annotateArgs
5928
+ };
5929
+ }
5930
+
5501
5931
  // src/library/client.ts
5502
5932
  function fromEnv(name) {
5503
5933
  const value = typeof process !== "undefined" ? process.env?.[name] : void 0;
@@ -5521,6 +5951,7 @@ function resolveClientOptions(options) {
5521
5951
  if (options.scrubber !== void 0 && typeof options.scrubber !== "function") {
5522
5952
  throw new Error("Client scrubber must be a function.");
5523
5953
  }
5954
+ validateServeOptions(options);
5524
5955
  const dsnString = selectDsn(
5525
5956
  options.dsn,
5526
5957
  {
@@ -5530,15 +5961,25 @@ function resolveClientOptions(options) {
5530
5961
  },
5531
5962
  "Client"
5532
5963
  );
5964
+ if (options.settings === "console" && dsnString === void 0) {
5965
+ throw new Error(`Client settings: "console" reads the Capture page with the dsn's key, so it needs a dsn.`);
5966
+ }
5967
+ candidateNeedsConsole(options.settings);
5968
+ const reportOn = (options.reportMode ?? (options.settings === "console" ? "on" : "off")) === "on";
5533
5969
  const consentToken = resolveConsentToken(options.consentToken);
5534
5970
  if (dsnString !== void 0) {
5535
5971
  const dsn = parseDsn(dsnString);
5972
+ const consoleSettings = options.settings === "console" && !consoleDroppedOnWorkers(options.settings);
5536
5973
  return {
5537
5974
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
5538
5975
  vendorId: dsn.vendorId,
5539
5976
  tenantId: dsn.tenantId,
5540
5977
  consentToken,
5541
- resultCaptureMode
5978
+ resultCaptureMode,
5979
+ ...consoleSettings ? {
5980
+ captureSettings: consoleCaptureSettings(dsn, options.settingsRefreshMs)
5981
+ } : {},
5982
+ ...reportOn ? { report: serveReport(dsn.vendorId, options.vendorDisplayName) } : {}
5542
5983
  };
5543
5984
  }
5544
5985
  if (options.sink === void 0) {
@@ -5555,9 +5996,22 @@ function resolveClientOptions(options) {
5555
5996
  vendorId: vendorId2,
5556
5997
  tenantId: resolveTenantId(options.tenantId || void 0, vendorId2),
5557
5998
  consentToken,
5558
- resultCaptureMode
5999
+ resultCaptureMode,
6000
+ ...reportOn ? { report: serveReport(vendorId2, options.vendorDisplayName) } : {}
5559
6001
  };
5560
6002
  }
6003
+ function validateServeOptions(options) {
6004
+ validateSettings(options, "Client");
6005
+ validateReportMode(options, "Client");
6006
+ if (options.tools !== void 0 && !Array.isArray(options.tools) && typeof options.tools !== "function") {
6007
+ throw new Error("Client tools must be an array of tools or a function that returns one.");
6008
+ }
6009
+ }
6010
+ function serveReport(vendorId2, displayName) {
6011
+ const display = displayName === void 0 || isBlank(displayName) ? vendorId2 : displayName;
6012
+ const name = deriveAnnotationToolName(vendorId2, toolNameForDisplayName(display));
6013
+ return { tool: reportTool({ vendorDisplayName: display, name }), vendorDisplayName: display };
6014
+ }
5561
6015
  var hasText2 = (value) => typeof value === "string" && !isBlank(value);
5562
6016
  function describeError(err) {
5563
6017
  let type = "Error";
@@ -5589,6 +6043,7 @@ var Core = class {
5589
6043
  resultCaptureMode;
5590
6044
  scrubber;
5591
6045
  disabled;
6046
+ settings;
5592
6047
  constructor(resolved) {
5593
6048
  this.sink = offTheCall(resolved.sink);
5594
6049
  this.vendorId = resolved.vendorId;
@@ -5597,6 +6052,10 @@ var Core = class {
5597
6052
  this.resultCaptureMode = resolved.resultCaptureMode;
5598
6053
  this.scrubber = resolved.scrubber;
5599
6054
  this.disabled = resolved.disabled;
6055
+ this.settings = resolved.captureSettings;
6056
+ }
6057
+ modeFor(session) {
6058
+ return session.settings?.resultCaptureMode ?? this.resultCaptureMode;
5600
6059
  }
5601
6060
  /** The envelope members every event of `session` shares. Call inside a
5602
6061
  * build thunk, so `captured_at` is the build time. */
@@ -5610,6 +6069,9 @@ var Core = class {
5610
6069
  consent_token: consentToken
5611
6070
  };
5612
6071
  }
6072
+ errorBody(text) {
6073
+ return scrubbedErrorBody(this.scrubber, text);
6074
+ }
5613
6075
  /** False when nothing may be emitted: the off switch, or a closed client. */
5614
6076
  live() {
5615
6077
  if (this.disabled) return false;
@@ -5623,9 +6085,9 @@ var Core = class {
5623
6085
  }
5624
6086
  /** Sends `surface` unless this client already has. Never rejects. The
5625
6087
  * write only queues, so a surface counts as sent once queued. */
5626
- sendSurface(surface) {
5627
- if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();
5628
- this.sentSurfaces.mark(surface.digest);
6088
+ sendSurface(surface, seam, serverOverlay = null) {
6089
+ if (this.sentSurfaces.wasSent(surface.digest, serverOverlay) || !this.live()) return Promise.resolve();
6090
+ this.sentSurfaces.mark(surface.digest, serverOverlay);
5629
6091
  let event;
5630
6092
  try {
5631
6093
  event = SurfaceSnapshotEventSchema.parse({
@@ -5636,7 +6098,7 @@ var Core = class {
5636
6098
  sequence_number: nextClockSequence(),
5637
6099
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
5638
6100
  consent_token: this.consentToken,
5639
- payload: snapshotPayload(surface)
6101
+ payload: snapshotPayload(surface, seam?.())
5640
6102
  });
5641
6103
  } catch (err) {
5642
6104
  PROCESS_DROPS.add("encode_failed");
@@ -5671,6 +6133,7 @@ var Core = class {
5671
6133
  var UNSET = /* @__PURE__ */ Symbol("unset");
5672
6134
  var WITHHELD_RESULT = /* @__PURE__ */ Symbol("withheld");
5673
6135
  var SCRUB_FAILED = /* @__PURE__ */ Symbol("scrubFailed");
6136
+ var observeFailure;
5674
6137
  var runTrace;
5675
6138
  var Trace = class _Trace {
5676
6139
  #core;
@@ -5681,6 +6144,7 @@ var Trace = class _Trace {
5681
6144
  #startedAt = 0;
5682
6145
  #result = UNSET;
5683
6146
  #error = null;
6147
+ #failure = null;
5684
6148
  #observedWarned = false;
5685
6149
  constructor(core, session, options) {
5686
6150
  this.#core = core;
@@ -5702,6 +6166,7 @@ var Trace = class _Trace {
5702
6166
  }
5703
6167
  this.#result = UNSET;
5704
6168
  this.#error = null;
6169
+ this.#failure = null;
5705
6170
  if (this.#core.disabled) return this;
5706
6171
  let errorType = failure?.errorType;
5707
6172
  let errorBody2 = failure?.errorBody;
@@ -5712,7 +6177,7 @@ var Trace = class _Trace {
5712
6177
  }
5713
6178
  if (errorType !== void 0 || errorBody2 !== void 0) {
5714
6179
  this.#error = { type: errorType || "Error", body: errorBody2 ?? "" };
5715
- } else if (this.#core.resultCaptureMode === WITHHELD) {
6180
+ } else if (this.#core.modeFor(this.#session) === WITHHELD) {
5716
6181
  this.#result = WITHHELD_RESULT;
5717
6182
  } else {
5718
6183
  try {
@@ -5788,23 +6253,40 @@ var Trace = class _Trace {
5788
6253
  #fail(err) {
5789
6254
  const durationMs = this.#durationMs();
5790
6255
  if (!this.#core.live()) return;
5791
- this.#emitError(nextClockSequence(), ...describeError(err), durationMs);
6256
+ const [type, body] = describeError(err);
6257
+ if (this.#core.modeFor(this.#session) === WITHHELD) {
6258
+ this.#failure = { result: null, result_capture: WITHHELD };
6259
+ this.#emitError(nextClockSequence(), type, "", durationMs);
6260
+ return;
6261
+ }
6262
+ this.#emitError(nextClockSequence(), type, body, durationMs);
5792
6263
  }
5793
6264
  #emitError(sequence, type, body, durationMs) {
6265
+ const failure = this.#failure;
5794
6266
  void this.#core.emit(
5795
6267
  () => ToolCallErrorEventSchema.parse({
5796
6268
  ...this.#envelope(sequence),
5797
6269
  payload: {
5798
6270
  tool_name: this.#options.toolName,
5799
6271
  error_type: type,
5800
- error_body: scrubbedErrorBody(this.#core.scrubber, body),
6272
+ error_body: failure === null ? scrubbedErrorBody(this.#core.scrubber, body) : body,
5801
6273
  duration_ms: durationMs,
5802
- result: null
6274
+ result: null,
6275
+ ...failure
5803
6276
  }
5804
6277
  })
5805
6278
  );
5806
6279
  }
5807
6280
  static {
6281
+ observeFailure = (trace, errorType, fields, failureKind) => {
6282
+ trace.#result = UNSET;
6283
+ trace.#error = { type: errorType, body: fields.error_body };
6284
+ trace.#failure = {
6285
+ result: fields.result,
6286
+ ...fields.result_capture === void 0 ? {} : { result_capture: fields.result_capture },
6287
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind }
6288
+ };
6289
+ };
5808
6290
  runTrace = (core, session, options, fn) => {
5809
6291
  const trace = new _Trace(core, session, options);
5810
6292
  trace.#start();
@@ -5832,8 +6314,40 @@ var Trace = class _Trace {
5832
6314
  };
5833
6315
  }
5834
6316
  };
6317
+ var Mark = class {
6318
+ constructor(owner, flags) {
6319
+ this.owner = owner;
6320
+ this.flags = flags;
6321
+ }
6322
+ owner;
6323
+ flags;
6324
+ active = true;
6325
+ };
6326
+ var inDispatch = new asyncHooks3.AsyncLocalStorage();
6327
+ async function dispatched(dispatch, message, mark = null) {
6328
+ try {
6329
+ return await inDispatch.run(mark, () => dispatch(message));
6330
+ } finally {
6331
+ if (mark !== null) mark.active = false;
6332
+ }
6333
+ }
6334
+ function messageText(message) {
6335
+ if (typeof message === "string") return message;
6336
+ return message === void 0 ? "" : JSON.stringify(message) ?? "";
6337
+ }
6338
+ function fieldsOrEmpty(build) {
6339
+ try {
6340
+ return build();
6341
+ } catch (err) {
6342
+ stderrLine(`baton: the scrubber threw on an error answer; its text is dropped: ${printable(err)}`);
6343
+ return { error_body: "", result: null };
6344
+ }
6345
+ }
6346
+ var stopWhenDropped = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((s) => s.stop()) : void 0;
5835
6347
  var Client = class {
5836
6348
  #core;
6349
+ #serving;
6350
+ #doubleWiringLogged = /* @__PURE__ */ new Set();
5837
6351
  #closing;
5838
6352
  constructor(options = {}) {
5839
6353
  const switchName = captureDisabled();
@@ -5855,6 +6369,11 @@ var Client = class {
5855
6369
  scrubber: options.scrubber ?? new Scrubber().scrub,
5856
6370
  disabled: switchName !== null
5857
6371
  });
6372
+ this.#serving = new Serving(resolved.report, resolved.captureSettings, switchName === null ? options.tools : void 0);
6373
+ if (resolved.captureSettings !== void 0) {
6374
+ resolved.captureSettings.start();
6375
+ stopWhenDropped?.register(this, resolved.captureSettings);
6376
+ }
5858
6377
  }
5859
6378
  /** Run `fn` with one session, principal, client and turn for every
5860
6379
  * `trace()` and `annotate()` inside it, including after its awaits. Open
@@ -5875,7 +6394,8 @@ var Client = class {
5875
6394
  * called exactly once, so a lazy query builder is not run twice. A throw or
5876
6395
  * rejection is recorded and passed on unchanged. */
5877
6396
  trace(options, fn) {
5878
- return runTrace(this.#core, sessionForCall(this), options ?? {}, fn);
6397
+ this.#flagDoubleWiring("trace");
6398
+ return runTrace(this.#core, sessionForCall(this, this.#core.settings), options ?? {}, fn);
5879
6399
  }
5880
6400
  /** `fn`, traced on every call. A single plain-object argument is sent as
5881
6401
  * `params`, as an MCP tool's arguments are; other arguments as
@@ -5891,7 +6411,11 @@ var Client = class {
5891
6411
  * own outside one. To report on a traced call, use `trace.annotate()`. */
5892
6412
  annotate(options) {
5893
6413
  const given = options ?? {};
5894
- return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);
6414
+ return this.#core.annotate(
6415
+ sessionForCall(this, this.#core.settings),
6416
+ given.consentToken || this.#core.consentToken,
6417
+ given
6418
+ );
5895
6419
  }
5896
6420
  /** `tools`, the vendor's own `tools/list` entries, with `user_goal` added
5897
6421
  * to each `inputSchema` as `withBaton` adds it, and a `surface_snapshot`
@@ -5904,11 +6428,176 @@ var Client = class {
5904
6428
  * tool list: one it cannot read is returned as it came. Does not wait for
5905
6429
  * the snapshot to be sent; `flush()` does. */
5906
6430
  async listTools(tools, options = {}) {
6431
+ this.#flagDoubleWiring("listTools");
5907
6432
  if (this.#core.disabled) return tools;
5908
6433
  const { served, surface } = serveTools(tools, options);
5909
6434
  if (surface !== null) void this.#core.sendSurface(surface);
5910
6435
  return served;
5911
6436
  }
6437
+ /** Answer one MCP JSON-RPC `message` with `dispatch`, the vendor's own
6438
+ * function from message to answer, and Baton around it (SPEC §5.6).
6439
+ * Experimental.
6440
+ *
6441
+ * `initialize` gets Baton's instructions. `tools/list` gets `user_goal` and
6442
+ * the report tool, under the caller's Console settings, and sends the
6443
+ * snapshot. `tools/call` is traced, with `user_goal` removed before
6444
+ * `dispatch` sees it; Baton answers the report tool and a tool the caller's
6445
+ * overlay hides itself. Anything else goes to `dispatch` as it came.
6446
+ *
6447
+ * `options` are as on `session()`. A process learns the vendor's tools from
6448
+ * the lists it serves. Until it has, a call loses `user_goal` and the report
6449
+ * tool's name is Baton's; pass the `tools` option when a tool declares its
6450
+ * own `user_goal` or has the report tool's name. `dispatch` is called at
6451
+ * most once, and what it returns or throws comes back unchanged apart from
6452
+ * Baton's additions. A failure in Baton's own work is logged, never thrown. */
6453
+ serve(message, dispatch, options = {}) {
6454
+ return inDispatch.run(null, () => this.#serve(message, dispatch, options ?? {}));
6455
+ }
6456
+ async #serve(message, dispatch, options) {
6457
+ const request = this.#request(message);
6458
+ if (request === null) return dispatched(dispatch, message);
6459
+ const settings = this.#core.settings;
6460
+ if (settings !== void 0 && !settings.isReady) await settings.ready;
6461
+ const handle = () => this.#handle(request, message, dispatch);
6462
+ const { principal, headers, sessionId } = options;
6463
+ if (inBlock(this) && principal === void 0 && headers === void 0 && sessionId === void 0) return handle();
6464
+ const values = {
6465
+ ...principal === void 0 ? {} : { principal },
6466
+ ...headers === void 0 ? {} : { headers },
6467
+ ...sessionId === void 0 ? {} : { sessionId }
6468
+ };
6469
+ try {
6470
+ if (isRecord(request.params._meta)) values.meta = request.params._meta;
6471
+ if (request.method === "initialize" && isRecord(request.params.clientInfo)) {
6472
+ values.clientInfo = request.params.clientInfo;
6473
+ }
6474
+ } catch {
6475
+ }
6476
+ return this.session(values, handle);
6477
+ }
6478
+ async #handle(request, message, dispatch) {
6479
+ let session;
6480
+ let call = null;
6481
+ try {
6482
+ session = sessionForCall(this, this.#core.settings);
6483
+ if (request.method === TOOL_CALL) call = this.#serving.call(request, message, session.settings);
6484
+ } catch (err) {
6485
+ stderrLine(`baton: serve() could not read the request; it is served as it came: ${printable(err)}`);
6486
+ return dispatched(dispatch, withoutUserGoal(message));
6487
+ }
6488
+ if (request.method !== TOOL_CALL) {
6489
+ const mark = request.method === TOOL_LIST ? new Mark(this, "listTools") : null;
6490
+ return this.#shaped(request, await dispatched(dispatch, message, mark), session);
6491
+ }
6492
+ if (call === null) return dispatched(dispatch, message);
6493
+ if (call.answer !== void 0) {
6494
+ this.#answerOurselves(call, session);
6495
+ return call.answer;
6496
+ }
6497
+ return this.#traced(call, dispatch, session);
6498
+ }
6499
+ #request(message) {
6500
+ if (this.#core.disabled) return null;
6501
+ try {
6502
+ return readRequest(message);
6503
+ } catch (err) {
6504
+ stderrLine(`baton: serve() could not read the request; it is served as it came: ${printable(err)}`);
6505
+ return null;
6506
+ }
6507
+ }
6508
+ /** Dispatch's `initialize` or `tools/list` answer with Baton's additions,
6509
+ * and its snapshot sent; the answer unchanged on failure. */
6510
+ #shaped(request, answer, session) {
6511
+ try {
6512
+ if (request.method !== TOOL_LIST) return this.#serving.initialized(answer);
6513
+ const listed = this.#serving.listed(request, answer, session.settings);
6514
+ if (listed === null) return answer;
6515
+ if (listed.surface !== null) void this.#core.sendSurface(listed.surface, listed.seam, listed.serverOverlay);
6516
+ return listed.answer;
6517
+ } catch (err) {
6518
+ stderrLine(`baton: serve() could not add to the answer; it is served as it came: ${printable(err)}`);
6519
+ return answer;
6520
+ }
6521
+ }
6522
+ async #traced(call, dispatch, session) {
6523
+ let dispatching = false;
6524
+ try {
6525
+ return await runTrace(this.#core, session, traceOptions(call), async (trace) => {
6526
+ dispatching = true;
6527
+ const answer = await dispatched(dispatch, call.message, new Mark(this, "trace"));
6528
+ this.#record(trace, answer, session);
6529
+ return answer;
6530
+ });
6531
+ } catch (err) {
6532
+ if (dispatching) throw err;
6533
+ stderrLine(`baton: serve() could not trace the call: ${printable(err)}`);
6534
+ return dispatched(dispatch, call.message, new Mark(this, "trace"));
6535
+ }
6536
+ }
6537
+ #record(trace, answer, session) {
6538
+ const mode = this.#core.modeFor(session);
6539
+ const scrubber = this.#core.scrubber;
6540
+ const errorBody2 = (text) => this.#core.errorBody(text);
6541
+ try {
6542
+ const error = jsonRpcError(answer);
6543
+ if (error !== null) {
6544
+ observeFailure(
6545
+ trace,
6546
+ JSONRPC_ERROR_TYPE,
6547
+ fieldsOrEmpty(
6548
+ () => resultDerivedFields(mode, () => messageText(error.message), { ...error }, errorBody2, scrubber)
6549
+ )
6550
+ );
6551
+ return;
6552
+ }
6553
+ const result = resultOf(answer);
6554
+ if (isToolErrorResult(result)) {
6555
+ observeFailure(
6556
+ trace,
6557
+ TOOL_ERROR_TYPE,
6558
+ fieldsOrEmpty(() => returnedErrorFields(mode, result, errorBody2, scrubber))
6559
+ );
6560
+ return;
6561
+ }
6562
+ trace.observed(result ?? answer);
6563
+ } catch (err) {
6564
+ stderrLine(`baton: serve() could not record the tool call: ${printable(err)}`);
6565
+ try {
6566
+ trace.observed(void 0);
6567
+ } catch {
6568
+ }
6569
+ }
6570
+ }
6571
+ #answerOurselves(call, session) {
6572
+ try {
6573
+ if (call.report !== void 0) {
6574
+ void this.#core.annotate(session, this.#core.consentToken, call.report);
6575
+ } else if (call.kind === "hidden") {
6576
+ const scrubber = this.#core.scrubber;
6577
+ const fields = fieldsOrEmpty(
6578
+ () => returnedErrorFields("full", call.answer.result, (text) => this.#core.errorBody(text), scrubber)
6579
+ );
6580
+ runTrace(
6581
+ this.#core,
6582
+ session,
6583
+ traceOptions(call),
6584
+ (trace) => observeFailure(trace, TOOL_ERROR_TYPE, fields, "tool_hidden")
6585
+ );
6586
+ }
6587
+ } catch (err) {
6588
+ stderrLine(`baton: serve() could not record its own answer: ${printable(err)}`);
6589
+ }
6590
+ }
6591
+ /** An error, once per client and call, when the vendor's code inside
6592
+ * `serve()` still calls what `serve()` now does: the old wiring was left in. */
6593
+ #flagDoubleWiring(call) {
6594
+ const mark = inDispatch.getStore();
6595
+ if (!mark?.active || mark.owner !== this || mark.flags !== call || this.#doubleWiringLogged.has(call)) return;
6596
+ this.#doubleWiringLogged.add(call);
6597
+ stderrLine(
6598
+ `baton: client.${call}() was called inside serve(). serve() already does this, so it is recorded twice. Remove the old Baton wiring: session(), trace(), listTools() and the report tool code.`
6599
+ );
6600
+ }
5912
6601
  /** Wait for events so far to reach the sink, then flush it. Never rejects;
5913
6602
  * returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
5914
6603
  async flush() {
@@ -5916,58 +6605,13 @@ var Client = class {
5916
6605
  }
5917
6606
  /** Flush, then close the sink. Later events are dropped. */
5918
6607
  aclose() {
6608
+ this.#core.settings?.stop();
5919
6609
  this.#closing ??= boundedSinkCall(this.#core.sink, "aclose").then(() => {
5920
6610
  this.#core.closed = true;
5921
6611
  });
5922
6612
  return this.#closing;
5923
6613
  }
5924
6614
  };
5925
-
5926
- // src/library/reportTool.ts
5927
- function inputSchema() {
5928
- const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
5929
- delete schema.$schema;
5930
- return { ...schema, required: [...schema.required, TOOL_NAME_PARAM_NAME] };
5931
- }
5932
- var nonEmptyText = (value) => typeof value === "string" && value !== "";
5933
- var nonEmptyObject = (value) => isRecord(value) && Object.keys(value).length > 0;
5934
- function annotateArgs(args) {
5935
- const whatHappened = args.what_happened;
5936
- if (!isReport(whatHappened)) return null;
5937
- const options = { whatHappened };
5938
- const toolName = args[TOOL_NAME_PARAM_NAME];
5939
- if (typeof toolName === "string") options.toolName = toolName;
5940
- const intent = args[USER_GOAL_PARAM_NAME];
5941
- if (nonEmptyText(intent)) options.intent = intent;
5942
- if (nonEmptyText(args.suggested_improvement)) {
5943
- options.suggestedImprovement = args.suggested_improvement;
5944
- }
5945
- if (nonEmptyObject(args.context)) options.context = args.context;
5946
- return options;
5947
- }
5948
- function reportTool(options) {
5949
- const { vendorDisplayName } = options;
5950
- const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);
5951
- if (derived === void 0) {
5952
- throw new Error(
5953
- `vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, or one too long for the instructions. Pass name.`
5954
- );
5955
- }
5956
- const name = validateAnnotationToolName(derived);
5957
- if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: name })) {
5958
- throw new Error(
5959
- `vendorDisplayName and name ${JSON.stringify(name)} are too long together for the instructions. Shorten one of them.`
5960
- );
5961
- }
5962
- return {
5963
- name,
5964
- description: buildAnnotationToolDescription({ vendorDisplayName }),
5965
- inputSchema: inputSchema(),
5966
- instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),
5967
- refusal: buildRefusalText({ annotationToolName: name }),
5968
- annotateArgs
5969
- };
5970
- }
5971
6615
  // Annotate the CommonJS export names for ESM import in node:
5972
6616
  0 && (module.exports = {
5973
6617
  BatonHandle,