@goodtiming/baton-sdk 1.2.2 → 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.2";
56
+ var SDK_VERSION = "ts-1.3.0";
57
57
 
58
58
  // src/events.ts
59
59
  var import_zod = require("zod");
@@ -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");
@@ -3550,12 +3553,16 @@ function resolveInstallConfig(config) {
3550
3553
  return { resolved, unconfigured };
3551
3554
  }
3552
3555
  var consoleOffWarned = false;
3553
- function withoutConsoleOnWorkers(config) {
3554
- if (config.settings !== "console" || !onWorkers()) return config;
3556
+ function consoleDroppedOnWorkers(settings) {
3557
+ if (settings !== "console" || !onWorkers()) return false;
3555
3558
  if (!consoleOffWarned) {
3556
3559
  consoleOffWarned = true;
3557
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.`);
3558
3561
  }
3562
+ return true;
3563
+ }
3564
+ function withoutConsoleOnWorkers(config) {
3565
+ if (!consoleDroppedOnWorkers(config.settings)) return config;
3559
3566
  const rest = { ...config, reportMode: config.reportMode ?? "on" };
3560
3567
  delete rest.settings;
3561
3568
  return rest;
@@ -3616,18 +3623,7 @@ function resolveBatonConfig(supplied) {
3616
3623
  // itself, exactly as it does for an explicitly-constructed sink.
3617
3624
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
3618
3625
  ...identity.settings === "console" ? {
3619
- captureSettings: new CaptureSettings(
3620
- dsn.vendorId,
3621
- new SettingsFetcher({
3622
- origin: dsn.origin,
3623
- apiKey: dsn.key,
3624
- tenantId: dsn.tenantId,
3625
- vendorId: dsn.vendorId,
3626
- refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
3627
- }),
3628
- envCandidate(),
3629
- envTask()
3630
- )
3626
+ captureSettings: consoleCaptureSettings(dsn, identity.settingsRefreshMs)
3631
3627
  } : {}
3632
3628
  };
3633
3629
  }
@@ -3642,6 +3638,36 @@ function withServerDisplayName(resolved, supplied, serverName) {
3642
3638
  var RENAMED_KEYS = {
3643
3639
  resolveUser: "resolvePrincipal"
3644
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
+ }
3645
3671
  function validateBatonConfig(config) {
3646
3672
  for (const [was, now] of Object.entries(RENAMED_KEYS)) {
3647
3673
  if (was in config) {
@@ -3658,11 +3684,7 @@ function validateBatonConfig(config) {
3658
3684
  `vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
3659
3685
  );
3660
3686
  }
3661
- if (config.reportMode !== void 0 && !REPORT_MODES.has(config.reportMode)) {
3662
- throw new Error(
3663
- `BatonConfig.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
3664
- );
3665
- }
3687
+ validateReportMode(config, "BatonConfig");
3666
3688
  if (!config.vendorDisplayName && config.reportMode === "on") {
3667
3689
  throw new Error(
3668
3690
  'BatonConfig needs a vendorDisplayName with reportMode: "on" \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4).'
@@ -3693,17 +3715,7 @@ function validateBatonConfig(config) {
3693
3715
  `BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
3694
3716
  );
3695
3717
  }
3696
- if (config.settings !== void 0 && !SETTINGS_MODES.includes(config.settings)) {
3697
- throw new Error(
3698
- `BatonConfig.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`
3699
- );
3700
- }
3701
- const refresh = config.settingsRefreshMs;
3702
- if (refresh !== void 0 && (typeof refresh !== "number" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))) {
3703
- throw new Error(
3704
- `BatonConfig.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} to ${String(MAX_TIMER_MS)}.`
3705
- );
3706
- }
3718
+ validateSettings(config, "BatonConfig");
3707
3719
  if (config.scrubber !== void 0 && typeof config.scrubber !== "function") {
3708
3720
  throw new Error("BatonConfig.scrubber must be a function.");
3709
3721
  }
@@ -3837,33 +3849,35 @@ var PerCallerSurface = class {
3837
3849
  }
3838
3850
  /** `result` with the caller's goal, reports and overlay; as served on any failure. */
3839
3851
  toolsFor(result, caller) {
3840
- const settings = caller.settings;
3841
- if (settings === void 0) return result;
3842
- const { intentParamMode, annotationToolName, injectsGoal } = this.options;
3843
- const goal = settings.intentParamMode ?? intentParamMode;
3844
- const hideReports = annotationToolName !== "" && settings.reportMode === "off";
3845
- const overlay = settings.overlay;
3846
- if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
3847
- try {
3848
- const tools = result?.tools;
3849
- if (!Array.isArray(tools)) return result;
3850
- const served = [];
3851
- const injected = [];
3852
- for (const tool of tools) {
3853
- const name = tool?.name;
3854
- if (hideReports && name === annotationToolName) continue;
3855
- const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
3856
- served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
3857
- injected.push(ours);
3858
- }
3859
- const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
3860
- return { ...result, tools: rewritten };
3861
- } catch (err) {
3862
- stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
3863
- return result;
3864
- }
3852
+ return toolsForCaller(result, caller.settings, this.options);
3865
3853
  }
3866
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
+ }
3867
3881
  function batonParagraphs(pointer, overlay, subagentLine) {
3868
3882
  const parts = overlay?.instructionAppends() ?? [];
3869
3883
  if (pointer !== void 0) parts.push(overlaid(pointer, overlay, "instructions.report_pointer"));
@@ -3874,7 +3888,7 @@ function batonParagraphs(pointer, overlay, subagentLine) {
3874
3888
  function withOverlay(tools, injected, overlay, reportTool2) {
3875
3889
  const position = /* @__PURE__ */ new Map();
3876
3890
  tools.forEach((tool, i) => position.set(tool?.name, i));
3877
- const hidden = /* @__PURE__ */ new Set();
3891
+ const hidden2 = /* @__PURE__ */ new Set();
3878
3892
  for (const action of overlay.actions) {
3879
3893
  if (action.tool === void 0) continue;
3880
3894
  const i = position.get(action.tool);
@@ -3883,7 +3897,7 @@ function withOverlay(tools, injected, overlay, reportTool2) {
3883
3897
  } else if (action.tool === reportTool2) {
3884
3898
  warnSkipped(overlay.id, action.index, "the report tool takes agent_text targets only");
3885
3899
  } else if (action.param === void 0 && action.change === "remove") {
3886
- hidden.add(i);
3900
+ hidden2.add(i);
3887
3901
  } else if (action.param === void 0) {
3888
3902
  tools[i] = withDescription(tools[i], [action]);
3889
3903
  } else {
@@ -3902,7 +3916,7 @@ function withOverlay(tools, injected, overlay, reportTool2) {
3902
3916
  if (reportActions.length > 0 && reportAt !== void 0) {
3903
3917
  tools[reportAt] = withDescription(tools[reportAt], reportActions);
3904
3918
  }
3905
- return tools.filter((_, i) => !hidden.has(i));
3919
+ return tools.filter((_, i) => !hidden2.has(i));
3906
3920
  }
3907
3921
  function withDescription(tool, actions) {
3908
3922
  const description = typeof tool.description === "string" ? tool.description : void 0;
@@ -4929,7 +4943,7 @@ async function hiddenFrom(slot, name, params, extra, ctx) {
4929
4943
  }
4930
4944
  async function answerHidden(lowLevel, name, settle) {
4931
4945
  if (lowLevelMajor(lowLevel) === 1) {
4932
- 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 };
4933
4947
  await settle({ failed: true, raised: false, result });
4934
4948
  return result;
4935
4949
  }
@@ -5453,6 +5467,9 @@ function principalFromOAuthEmail(context) {
5453
5467
  };
5454
5468
  }
5455
5469
 
5470
+ // src/library/client.ts
5471
+ var asyncHooks3 = __toESM(require("async_hooks"), 1);
5472
+
5456
5473
  // src/library/session.ts
5457
5474
  var asyncHooks2 = __toESM(require("async_hooks"), 1);
5458
5475
  var TRANSPORT_LIBRARY = "library";
@@ -5466,7 +5483,8 @@ function sessionEnvelope(session) {
5466
5483
  organization: session.organization,
5467
5484
  labels: wireLabels(session.labels),
5468
5485
  client_observed: session.clientObserved,
5469
- runtime_meta: session.runtimeMeta
5486
+ runtime_meta: session.runtimeMeta,
5487
+ capture: session.settings?.capture ?? null
5470
5488
  };
5471
5489
  }
5472
5490
  function warn2(message) {
@@ -5481,7 +5499,7 @@ function vendorId(name, value) {
5481
5499
  return null;
5482
5500
  }
5483
5501
  function blank(sessionId, origin) {
5484
- return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };
5502
+ return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null, candidate: null, task: null };
5485
5503
  }
5486
5504
  function requestMeta(meta) {
5487
5505
  if (isRecord(meta)) return meta;
@@ -5504,16 +5522,48 @@ function newSession(values, scrubber, disabled) {
5504
5522
  ...base,
5505
5523
  ...callerFor(values.principal, (_key, message) => warn2(`principal ${message}`)),
5506
5524
  clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber, meta),
5507
- 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)
5508
5528
  };
5509
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
+ }
5510
5540
  var current = new asyncHooks2.AsyncLocalStorage();
5511
5541
  function runInSession(owner, session, fn) {
5512
5542
  return current.run({ owner, session }, fn);
5513
5543
  }
5514
- function sessionForCall(owner) {
5515
- const entry = current.getStore();
5516
- 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;
5517
5567
  }
5518
5568
 
5519
5569
  // src/library/surface.ts
@@ -5545,11 +5595,11 @@ function serveTools(tools, options) {
5545
5595
  return { served, surface: null };
5546
5596
  }
5547
5597
  }
5548
- function snapshotPayload({ surface, digest }) {
5598
+ function snapshotPayload({ surface, digest }, seam) {
5549
5599
  return {
5550
5600
  surface_hash: digest,
5551
5601
  ...surface,
5552
- seam_augmentations: buildSeamAugmentations({
5602
+ seam_augmentations: seam ?? buildSeamAugmentations({
5553
5603
  injectedToolNames: [],
5554
5604
  intentParamNames: [USER_GOAL_PARAM_NAME],
5555
5605
  intentParamMode: DEFAULT_INTENT_PARAM_MODE,
@@ -5569,6 +5619,315 @@ function servedEntry(tool) {
5569
5619
  return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, DEFAULT_INTENT_PARAM_MODE, true) };
5570
5620
  }
5571
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
+
5572
5931
  // src/library/client.ts
5573
5932
  function fromEnv(name) {
5574
5933
  const value = typeof process !== "undefined" ? process.env?.[name] : void 0;
@@ -5592,6 +5951,7 @@ function resolveClientOptions(options) {
5592
5951
  if (options.scrubber !== void 0 && typeof options.scrubber !== "function") {
5593
5952
  throw new Error("Client scrubber must be a function.");
5594
5953
  }
5954
+ validateServeOptions(options);
5595
5955
  const dsnString = selectDsn(
5596
5956
  options.dsn,
5597
5957
  {
@@ -5601,15 +5961,25 @@ function resolveClientOptions(options) {
5601
5961
  },
5602
5962
  "Client"
5603
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";
5604
5969
  const consentToken = resolveConsentToken(options.consentToken);
5605
5970
  if (dsnString !== void 0) {
5606
5971
  const dsn = parseDsn(dsnString);
5972
+ const consoleSettings = options.settings === "console" && !consoleDroppedOnWorkers(options.settings);
5607
5973
  return {
5608
5974
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
5609
5975
  vendorId: dsn.vendorId,
5610
5976
  tenantId: dsn.tenantId,
5611
5977
  consentToken,
5612
- resultCaptureMode
5978
+ resultCaptureMode,
5979
+ ...consoleSettings ? {
5980
+ captureSettings: consoleCaptureSettings(dsn, options.settingsRefreshMs)
5981
+ } : {},
5982
+ ...reportOn ? { report: serveReport(dsn.vendorId, options.vendorDisplayName) } : {}
5613
5983
  };
5614
5984
  }
5615
5985
  if (options.sink === void 0) {
@@ -5626,9 +5996,22 @@ function resolveClientOptions(options) {
5626
5996
  vendorId: vendorId2,
5627
5997
  tenantId: resolveTenantId(options.tenantId || void 0, vendorId2),
5628
5998
  consentToken,
5629
- resultCaptureMode
5999
+ resultCaptureMode,
6000
+ ...reportOn ? { report: serveReport(vendorId2, options.vendorDisplayName) } : {}
5630
6001
  };
5631
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
+ }
5632
6015
  var hasText2 = (value) => typeof value === "string" && !isBlank(value);
5633
6016
  function describeError(err) {
5634
6017
  let type = "Error";
@@ -5660,6 +6043,7 @@ var Core = class {
5660
6043
  resultCaptureMode;
5661
6044
  scrubber;
5662
6045
  disabled;
6046
+ settings;
5663
6047
  constructor(resolved) {
5664
6048
  this.sink = offTheCall(resolved.sink);
5665
6049
  this.vendorId = resolved.vendorId;
@@ -5668,6 +6052,10 @@ var Core = class {
5668
6052
  this.resultCaptureMode = resolved.resultCaptureMode;
5669
6053
  this.scrubber = resolved.scrubber;
5670
6054
  this.disabled = resolved.disabled;
6055
+ this.settings = resolved.captureSettings;
6056
+ }
6057
+ modeFor(session) {
6058
+ return session.settings?.resultCaptureMode ?? this.resultCaptureMode;
5671
6059
  }
5672
6060
  /** The envelope members every event of `session` shares. Call inside a
5673
6061
  * build thunk, so `captured_at` is the build time. */
@@ -5681,6 +6069,9 @@ var Core = class {
5681
6069
  consent_token: consentToken
5682
6070
  };
5683
6071
  }
6072
+ errorBody(text) {
6073
+ return scrubbedErrorBody(this.scrubber, text);
6074
+ }
5684
6075
  /** False when nothing may be emitted: the off switch, or a closed client. */
5685
6076
  live() {
5686
6077
  if (this.disabled) return false;
@@ -5694,9 +6085,9 @@ var Core = class {
5694
6085
  }
5695
6086
  /** Sends `surface` unless this client already has. Never rejects. The
5696
6087
  * write only queues, so a surface counts as sent once queued. */
5697
- sendSurface(surface) {
5698
- if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();
5699
- 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);
5700
6091
  let event;
5701
6092
  try {
5702
6093
  event = SurfaceSnapshotEventSchema.parse({
@@ -5707,7 +6098,7 @@ var Core = class {
5707
6098
  sequence_number: nextClockSequence(),
5708
6099
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
5709
6100
  consent_token: this.consentToken,
5710
- payload: snapshotPayload(surface)
6101
+ payload: snapshotPayload(surface, seam?.())
5711
6102
  });
5712
6103
  } catch (err) {
5713
6104
  PROCESS_DROPS.add("encode_failed");
@@ -5742,6 +6133,7 @@ var Core = class {
5742
6133
  var UNSET = /* @__PURE__ */ Symbol("unset");
5743
6134
  var WITHHELD_RESULT = /* @__PURE__ */ Symbol("withheld");
5744
6135
  var SCRUB_FAILED = /* @__PURE__ */ Symbol("scrubFailed");
6136
+ var observeFailure;
5745
6137
  var runTrace;
5746
6138
  var Trace = class _Trace {
5747
6139
  #core;
@@ -5752,6 +6144,7 @@ var Trace = class _Trace {
5752
6144
  #startedAt = 0;
5753
6145
  #result = UNSET;
5754
6146
  #error = null;
6147
+ #failure = null;
5755
6148
  #observedWarned = false;
5756
6149
  constructor(core, session, options) {
5757
6150
  this.#core = core;
@@ -5773,6 +6166,7 @@ var Trace = class _Trace {
5773
6166
  }
5774
6167
  this.#result = UNSET;
5775
6168
  this.#error = null;
6169
+ this.#failure = null;
5776
6170
  if (this.#core.disabled) return this;
5777
6171
  let errorType = failure?.errorType;
5778
6172
  let errorBody2 = failure?.errorBody;
@@ -5783,7 +6177,7 @@ var Trace = class _Trace {
5783
6177
  }
5784
6178
  if (errorType !== void 0 || errorBody2 !== void 0) {
5785
6179
  this.#error = { type: errorType || "Error", body: errorBody2 ?? "" };
5786
- } else if (this.#core.resultCaptureMode === WITHHELD) {
6180
+ } else if (this.#core.modeFor(this.#session) === WITHHELD) {
5787
6181
  this.#result = WITHHELD_RESULT;
5788
6182
  } else {
5789
6183
  try {
@@ -5859,23 +6253,40 @@ var Trace = class _Trace {
5859
6253
  #fail(err) {
5860
6254
  const durationMs = this.#durationMs();
5861
6255
  if (!this.#core.live()) return;
5862
- 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);
5863
6263
  }
5864
6264
  #emitError(sequence, type, body, durationMs) {
6265
+ const failure = this.#failure;
5865
6266
  void this.#core.emit(
5866
6267
  () => ToolCallErrorEventSchema.parse({
5867
6268
  ...this.#envelope(sequence),
5868
6269
  payload: {
5869
6270
  tool_name: this.#options.toolName,
5870
6271
  error_type: type,
5871
- error_body: scrubbedErrorBody(this.#core.scrubber, body),
6272
+ error_body: failure === null ? scrubbedErrorBody(this.#core.scrubber, body) : body,
5872
6273
  duration_ms: durationMs,
5873
- result: null
6274
+ result: null,
6275
+ ...failure
5874
6276
  }
5875
6277
  })
5876
6278
  );
5877
6279
  }
5878
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
+ };
5879
6290
  runTrace = (core, session, options, fn) => {
5880
6291
  const trace = new _Trace(core, session, options);
5881
6292
  trace.#start();
@@ -5903,8 +6314,40 @@ var Trace = class _Trace {
5903
6314
  };
5904
6315
  }
5905
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;
5906
6347
  var Client = class {
5907
6348
  #core;
6349
+ #serving;
6350
+ #doubleWiringLogged = /* @__PURE__ */ new Set();
5908
6351
  #closing;
5909
6352
  constructor(options = {}) {
5910
6353
  const switchName = captureDisabled();
@@ -5926,6 +6369,11 @@ var Client = class {
5926
6369
  scrubber: options.scrubber ?? new Scrubber().scrub,
5927
6370
  disabled: switchName !== null
5928
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
+ }
5929
6377
  }
5930
6378
  /** Run `fn` with one session, principal, client and turn for every
5931
6379
  * `trace()` and `annotate()` inside it, including after its awaits. Open
@@ -5946,7 +6394,8 @@ var Client = class {
5946
6394
  * called exactly once, so a lazy query builder is not run twice. A throw or
5947
6395
  * rejection is recorded and passed on unchanged. */
5948
6396
  trace(options, fn) {
5949
- return runTrace(this.#core, sessionForCall(this), options ?? {}, fn);
6397
+ this.#flagDoubleWiring("trace");
6398
+ return runTrace(this.#core, sessionForCall(this, this.#core.settings), options ?? {}, fn);
5950
6399
  }
5951
6400
  /** `fn`, traced on every call. A single plain-object argument is sent as
5952
6401
  * `params`, as an MCP tool's arguments are; other arguments as
@@ -5962,7 +6411,11 @@ var Client = class {
5962
6411
  * own outside one. To report on a traced call, use `trace.annotate()`. */
5963
6412
  annotate(options) {
5964
6413
  const given = options ?? {};
5965
- 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
+ );
5966
6419
  }
5967
6420
  /** `tools`, the vendor's own `tools/list` entries, with `user_goal` added
5968
6421
  * to each `inputSchema` as `withBaton` adds it, and a `surface_snapshot`
@@ -5975,11 +6428,176 @@ var Client = class {
5975
6428
  * tool list: one it cannot read is returned as it came. Does not wait for
5976
6429
  * the snapshot to be sent; `flush()` does. */
5977
6430
  async listTools(tools, options = {}) {
6431
+ this.#flagDoubleWiring("listTools");
5978
6432
  if (this.#core.disabled) return tools;
5979
6433
  const { served, surface } = serveTools(tools, options);
5980
6434
  if (surface !== null) void this.#core.sendSurface(surface);
5981
6435
  return served;
5982
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
+ }
5983
6601
  /** Wait for events so far to reach the sink, then flush it. Never rejects;
5984
6602
  * returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
5985
6603
  async flush() {
@@ -5987,61 +6605,13 @@ var Client = class {
5987
6605
  }
5988
6606
  /** Flush, then close the sink. Later events are dropped. */
5989
6607
  aclose() {
6608
+ this.#core.settings?.stop();
5990
6609
  this.#closing ??= boundedSinkCall(this.#core.sink, "aclose").then(() => {
5991
6610
  this.#core.closed = true;
5992
6611
  });
5993
6612
  return this.#closing;
5994
6613
  }
5995
6614
  };
5996
-
5997
- // src/library/reportTool.ts
5998
- function inputSchema() {
5999
- const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
6000
- delete schema.$schema;
6001
- return { ...schema, required: [...schema.required, TOOL_NAME_PARAM_NAME] };
6002
- }
6003
- var nonEmptyText = (value) => typeof value === "string" && value !== "";
6004
- var nonEmptyObject = (value) => isRecord(value) && Object.keys(value).length > 0;
6005
- function annotateArgs(args) {
6006
- const whatHappened = args.what_happened;
6007
- if (!isReport(whatHappened)) return null;
6008
- const options = { whatHappened };
6009
- const toolName = args[TOOL_NAME_PARAM_NAME];
6010
- if (typeof toolName === "string") options.toolName = toolName;
6011
- const intent = args[USER_GOAL_PARAM_NAME];
6012
- if (nonEmptyText(intent)) options.intent = intent;
6013
- if (nonEmptyText(args.suggested_improvement)) {
6014
- options.suggestedImprovement = args.suggested_improvement;
6015
- }
6016
- if (nonEmptyObject(args.context)) options.context = args.context;
6017
- return options;
6018
- }
6019
- function reportTool(options) {
6020
- const { vendorDisplayName } = options;
6021
- if (isBlank(vendorDisplayName)) {
6022
- throw new Error("vendorDisplayName is blank. Baton's report sentence names the server by it.");
6023
- }
6024
- const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);
6025
- if (derived === void 0) {
6026
- throw new Error(
6027
- `vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, or one too long for Baton's report sentence. Pass name.`
6028
- );
6029
- }
6030
- const name = validateAnnotationToolName(derived);
6031
- if (!fitsBatonSentenceCap({ vendorDisplayName, annotationToolName: name })) {
6032
- throw new Error(
6033
- `vendorDisplayName and name ${JSON.stringify(name)} are too long together for Baton's report sentence. Shorten one of them.`
6034
- );
6035
- }
6036
- return {
6037
- name,
6038
- description: buildAnnotationToolDescription({ vendorDisplayName }),
6039
- inputSchema: inputSchema(),
6040
- instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),
6041
- refusal: buildRefusalText({ annotationToolName: name }),
6042
- annotateArgs
6043
- };
6044
- }
6045
6615
  // Annotate the CommonJS export names for ESM import in node:
6046
6616
  0 && (module.exports = {
6047
6617
  BatonHandle,