@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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-1.2.2";
2
+ var SDK_VERSION = "ts-1.3.0";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
@@ -1896,6 +1896,9 @@ function buildServerInstructions(options) {
1896
1896
  function buildAnnotationToolDescription(options) {
1897
1897
  return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
1898
1898
  }
1899
+ function unknownToolText(name) {
1900
+ return `MCP error -32602: Tool ${name} not found`;
1901
+ }
1899
1902
  function buildRefusalText(options) {
1900
1903
  const text = `${options.annotationToolName} is reactive-only on this server. Call it only AFTER a tool call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. What the user is trying to do is already recorded on each tool call, so no pre-call annotation is needed \u2014 nothing was lost. If a tool call really went wrong, or no tool covers the request, call this again and say what_happened. If neither is true, do NOT re-send: that would file a report for a call that did not go wrong.`;
1901
1904
  return overlaid(text, options.overlay, "report_tool.refusal");
@@ -3496,12 +3499,16 @@ function resolveInstallConfig(config) {
3496
3499
  return { resolved, unconfigured };
3497
3500
  }
3498
3501
  var consoleOffWarned = false;
3499
- function withoutConsoleOnWorkers(config) {
3500
- if (config.settings !== "console" || !onWorkers()) return config;
3502
+ function consoleDroppedOnWorkers(settings) {
3503
+ if (settings !== "console" || !onWorkers()) return false;
3501
3504
  if (!consoleOffWarned) {
3502
3505
  consoleOffWarned = true;
3503
3506
  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.`);
3504
3507
  }
3508
+ return true;
3509
+ }
3510
+ function withoutConsoleOnWorkers(config) {
3511
+ if (!consoleDroppedOnWorkers(config.settings)) return config;
3505
3512
  const rest = { ...config, reportMode: config.reportMode ?? "on" };
3506
3513
  delete rest.settings;
3507
3514
  return rest;
@@ -3562,18 +3569,7 @@ function resolveBatonConfig(supplied) {
3562
3569
  // itself, exactly as it does for an explicitly-constructed sink.
3563
3570
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
3564
3571
  ...identity.settings === "console" ? {
3565
- captureSettings: new CaptureSettings(
3566
- dsn.vendorId,
3567
- new SettingsFetcher({
3568
- origin: dsn.origin,
3569
- apiKey: dsn.key,
3570
- tenantId: dsn.tenantId,
3571
- vendorId: dsn.vendorId,
3572
- refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
3573
- }),
3574
- envCandidate(),
3575
- envTask()
3576
- )
3572
+ captureSettings: consoleCaptureSettings(dsn, identity.settingsRefreshMs)
3577
3573
  } : {}
3578
3574
  };
3579
3575
  }
@@ -3588,6 +3584,36 @@ function withServerDisplayName(resolved, supplied, serverName) {
3588
3584
  var RENAMED_KEYS = {
3589
3585
  resolveUser: "resolvePrincipal"
3590
3586
  };
3587
+ function consoleCaptureSettings(dsn, refreshMs) {
3588
+ const fetcher = new SettingsFetcher({
3589
+ origin: dsn.origin,
3590
+ apiKey: dsn.key,
3591
+ tenantId: dsn.tenantId,
3592
+ vendorId: dsn.vendorId,
3593
+ refreshMs: refreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
3594
+ });
3595
+ return new CaptureSettings(dsn.vendorId, fetcher, envCandidate(), envTask());
3596
+ }
3597
+ function validateReportMode(config, owner) {
3598
+ if (config.reportMode !== void 0 && !REPORT_MODES.has(config.reportMode)) {
3599
+ throw new Error(
3600
+ `${owner}.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
3601
+ );
3602
+ }
3603
+ }
3604
+ function validateSettings(config, owner) {
3605
+ if (config.settings !== void 0 && !SETTINGS_MODES.includes(config.settings)) {
3606
+ throw new Error(
3607
+ `${owner}.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`
3608
+ );
3609
+ }
3610
+ const refresh = config.settingsRefreshMs;
3611
+ if (refresh !== void 0 && (typeof refresh !== "number" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))) {
3612
+ throw new Error(
3613
+ `${owner}.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} to ${String(MAX_TIMER_MS)}.`
3614
+ );
3615
+ }
3616
+ }
3591
3617
  function validateBatonConfig(config) {
3592
3618
  for (const [was, now] of Object.entries(RENAMED_KEYS)) {
3593
3619
  if (was in config) {
@@ -3604,11 +3630,7 @@ function validateBatonConfig(config) {
3604
3630
  `vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
3605
3631
  );
3606
3632
  }
3607
- if (config.reportMode !== void 0 && !REPORT_MODES.has(config.reportMode)) {
3608
- throw new Error(
3609
- `BatonConfig.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
3610
- );
3611
- }
3633
+ validateReportMode(config, "BatonConfig");
3612
3634
  if (!config.vendorDisplayName && config.reportMode === "on") {
3613
3635
  throw new Error(
3614
3636
  'BatonConfig needs a vendorDisplayName with reportMode: "on" \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4).'
@@ -3639,17 +3661,7 @@ function validateBatonConfig(config) {
3639
3661
  `BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
3640
3662
  );
3641
3663
  }
3642
- if (config.settings !== void 0 && !SETTINGS_MODES.includes(config.settings)) {
3643
- throw new Error(
3644
- `BatonConfig.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`
3645
- );
3646
- }
3647
- const refresh = config.settingsRefreshMs;
3648
- if (refresh !== void 0 && (typeof refresh !== "number" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))) {
3649
- throw new Error(
3650
- `BatonConfig.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} to ${String(MAX_TIMER_MS)}.`
3651
- );
3652
- }
3664
+ validateSettings(config, "BatonConfig");
3653
3665
  if (config.scrubber !== void 0 && typeof config.scrubber !== "function") {
3654
3666
  throw new Error("BatonConfig.scrubber must be a function.");
3655
3667
  }
@@ -3783,33 +3795,35 @@ var PerCallerSurface = class {
3783
3795
  }
3784
3796
  /** `result` with the caller's goal, reports and overlay; as served on any failure. */
3785
3797
  toolsFor(result, caller) {
3786
- const settings = caller.settings;
3787
- if (settings === void 0) return result;
3788
- const { intentParamMode, annotationToolName, injectsGoal } = this.options;
3789
- const goal = settings.intentParamMode ?? intentParamMode;
3790
- const hideReports = annotationToolName !== "" && settings.reportMode === "off";
3791
- const overlay = settings.overlay;
3792
- if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
3793
- try {
3794
- const tools = result?.tools;
3795
- if (!Array.isArray(tools)) return result;
3796
- const served = [];
3797
- const injected = [];
3798
- for (const tool of tools) {
3799
- const name = tool?.name;
3800
- if (hideReports && name === annotationToolName) continue;
3801
- const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
3802
- served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
3803
- injected.push(ours);
3804
- }
3805
- const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
3806
- return { ...result, tools: rewritten };
3807
- } catch (err) {
3808
- stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
3809
- return result;
3810
- }
3798
+ return toolsForCaller(result, caller.settings, this.options);
3811
3799
  }
3812
3800
  };
3801
+ function toolsForCaller(result, settings, options) {
3802
+ if (settings === void 0) return result;
3803
+ const { intentParamMode, annotationToolName, injectsGoal } = options;
3804
+ const goal = settings.intentParamMode ?? intentParamMode;
3805
+ const hideReports = annotationToolName !== "" && settings.reportMode === "off";
3806
+ const overlay = settings.overlay;
3807
+ if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
3808
+ try {
3809
+ const tools = result?.tools;
3810
+ if (!Array.isArray(tools)) return result;
3811
+ const served = [];
3812
+ const injected = [];
3813
+ for (const tool of tools) {
3814
+ const name = tool?.name;
3815
+ if (hideReports && name === annotationToolName) continue;
3816
+ const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
3817
+ served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
3818
+ injected.push(ours);
3819
+ }
3820
+ const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
3821
+ return { ...result, tools: rewritten };
3822
+ } catch (err) {
3823
+ stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
3824
+ return result;
3825
+ }
3826
+ }
3813
3827
  function batonParagraphs(pointer, overlay, subagentLine) {
3814
3828
  const parts = overlay?.instructionAppends() ?? [];
3815
3829
  if (pointer !== void 0) parts.push(overlaid(pointer, overlay, "instructions.report_pointer"));
@@ -3820,7 +3834,7 @@ function batonParagraphs(pointer, overlay, subagentLine) {
3820
3834
  function withOverlay(tools, injected, overlay, reportTool2) {
3821
3835
  const position = /* @__PURE__ */ new Map();
3822
3836
  tools.forEach((tool, i) => position.set(tool?.name, i));
3823
- const hidden = /* @__PURE__ */ new Set();
3837
+ const hidden2 = /* @__PURE__ */ new Set();
3824
3838
  for (const action of overlay.actions) {
3825
3839
  if (action.tool === void 0) continue;
3826
3840
  const i = position.get(action.tool);
@@ -3829,7 +3843,7 @@ function withOverlay(tools, injected, overlay, reportTool2) {
3829
3843
  } else if (action.tool === reportTool2) {
3830
3844
  warnSkipped(overlay.id, action.index, "the report tool takes agent_text targets only");
3831
3845
  } else if (action.param === void 0 && action.change === "remove") {
3832
- hidden.add(i);
3846
+ hidden2.add(i);
3833
3847
  } else if (action.param === void 0) {
3834
3848
  tools[i] = withDescription(tools[i], [action]);
3835
3849
  } else {
@@ -3848,7 +3862,7 @@ function withOverlay(tools, injected, overlay, reportTool2) {
3848
3862
  if (reportActions.length > 0 && reportAt !== void 0) {
3849
3863
  tools[reportAt] = withDescription(tools[reportAt], reportActions);
3850
3864
  }
3851
- return tools.filter((_, i) => !hidden.has(i));
3865
+ return tools.filter((_, i) => !hidden2.has(i));
3852
3866
  }
3853
3867
  function withDescription(tool, actions) {
3854
3868
  const description = typeof tool.description === "string" ? tool.description : void 0;
@@ -4875,7 +4889,7 @@ async function hiddenFrom(slot, name, params, extra, ctx) {
4875
4889
  }
4876
4890
  async function answerHidden(lowLevel, name, settle) {
4877
4891
  if (lowLevelMajor(lowLevel) === 1) {
4878
- const result = { content: [{ type: "text", text: `MCP error -32602: Tool ${name} not found` }], isError: true };
4892
+ const result = { content: [{ type: "text", text: unknownToolText(name) }], isError: true };
4879
4893
  await settle({ failed: true, raised: false, result });
4880
4894
  return result;
4881
4895
  }
@@ -5399,6 +5413,9 @@ function principalFromOAuthEmail(context) {
5399
5413
  };
5400
5414
  }
5401
5415
 
5416
+ // src/library/client.ts
5417
+ import * as asyncHooks3 from "async_hooks";
5418
+
5402
5419
  // src/library/session.ts
5403
5420
  import * as asyncHooks2 from "async_hooks";
5404
5421
  var TRANSPORT_LIBRARY = "library";
@@ -5412,7 +5429,8 @@ function sessionEnvelope(session) {
5412
5429
  organization: session.organization,
5413
5430
  labels: wireLabels(session.labels),
5414
5431
  client_observed: session.clientObserved,
5415
- runtime_meta: session.runtimeMeta
5432
+ runtime_meta: session.runtimeMeta,
5433
+ capture: session.settings?.capture ?? null
5416
5434
  };
5417
5435
  }
5418
5436
  function warn2(message) {
@@ -5427,7 +5445,7 @@ function vendorId(name, value) {
5427
5445
  return null;
5428
5446
  }
5429
5447
  function blank(sessionId, origin) {
5430
- return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };
5448
+ return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null, candidate: null, task: null };
5431
5449
  }
5432
5450
  function requestMeta(meta) {
5433
5451
  if (isRecord(meta)) return meta;
@@ -5450,16 +5468,48 @@ function newSession(values, scrubber, disabled) {
5450
5468
  ...base,
5451
5469
  ...callerFor(values.principal, (_key, message) => warn2(`principal ${message}`)),
5452
5470
  clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber, meta),
5453
- runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
5471
+ runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber),
5472
+ candidate: vendorHeader(values.headers, CANDIDATE_HEADER, candidateId),
5473
+ task: vendorHeader(values.headers, TASK_HEADER, taskId)
5454
5474
  };
5455
5475
  }
5476
+ function vendorHeader(headers, name, parse) {
5477
+ try {
5478
+ if (headers === void 0) return null;
5479
+ if (typeof headers.get === "function") return parse(headers.get(name));
5480
+ const key = Object.keys(headers).find((k) => k.toLowerCase() === name);
5481
+ return key === void 0 ? null : parse(headers[key]);
5482
+ } catch {
5483
+ return null;
5484
+ }
5485
+ }
5456
5486
  var current = new asyncHooks2.AsyncLocalStorage();
5457
5487
  function runInSession(owner, session, fn) {
5458
5488
  return current.run({ owner, session }, fn);
5459
5489
  }
5460
- function sessionForCall(owner) {
5461
- const entry = current.getStore();
5462
- return entry !== void 0 && entry.owner === owner ? entry.session : blank(uuid7(), "minted");
5490
+ var settingsWarned2 = false;
5491
+ function sessionForCall(owner, settings) {
5492
+ const session = inBlock(owner) ? current.getStore().session : blank(uuid7(), "minted");
5493
+ if (settings === void 0) return session;
5494
+ try {
5495
+ const callSettings = settings.forCaller({
5496
+ labels: session.labels,
5497
+ clientName: session.clientObserved?.info?.name ?? null,
5498
+ shareKey: session.principal?.id ?? null,
5499
+ candidate: session.candidate,
5500
+ task: session.task
5501
+ });
5502
+ return callSettings === void 0 ? session : { ...session, settings: callSettings };
5503
+ } catch (err) {
5504
+ if (!settingsWarned2) {
5505
+ settingsWarned2 = true;
5506
+ warn2(`applying capture settings failed; this call uses the client's values: ${printable(err)}`);
5507
+ }
5508
+ return session;
5509
+ }
5510
+ }
5511
+ function inBlock(owner) {
5512
+ return current.getStore()?.owner === owner;
5463
5513
  }
5464
5514
 
5465
5515
  // src/library/surface.ts
@@ -5491,11 +5541,11 @@ function serveTools(tools, options) {
5491
5541
  return { served, surface: null };
5492
5542
  }
5493
5543
  }
5494
- function snapshotPayload({ surface, digest }) {
5544
+ function snapshotPayload({ surface, digest }, seam) {
5495
5545
  return {
5496
5546
  surface_hash: digest,
5497
5547
  ...surface,
5498
- seam_augmentations: buildSeamAugmentations({
5548
+ seam_augmentations: seam ?? buildSeamAugmentations({
5499
5549
  injectedToolNames: [],
5500
5550
  intentParamNames: [USER_GOAL_PARAM_NAME],
5501
5551
  intentParamMode: DEFAULT_INTENT_PARAM_MODE,
@@ -5515,6 +5565,315 @@ function servedEntry(tool) {
5515
5565
  return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, DEFAULT_INTENT_PARAM_MODE, true) };
5516
5566
  }
5517
5567
 
5568
+ // src/library/serve.ts
5569
+ var INITIALIZE = "initialize";
5570
+ var TOOL_LIST = "tools/list";
5571
+ var TOOL_CALL = "tools/call";
5572
+ var JSONRPC_ERROR_TYPE = "JSONRPCError";
5573
+ var REMEMBERED_TOOLS = 4096;
5574
+ function readRequest(message) {
5575
+ if (!isRecord(message) || message.id === void 0 || message.id === null) return null;
5576
+ const { method } = message;
5577
+ const params = message.params === void 0 ? {} : message.params;
5578
+ if (method !== INITIALIZE && method !== TOOL_LIST && method !== TOOL_CALL || !isRecord(params)) return null;
5579
+ return { method, params };
5580
+ }
5581
+ var OWN = /* @__PURE__ */ new Set(["native", "may_take"]);
5582
+ var KEPT = /* @__PURE__ */ new Set(["native", "may_take", "unread"]);
5583
+ function goalDispositions(schema) {
5584
+ if (schema === void 0 || schema === null) return { [USER_GOAL_PARAM_NAME]: "injected" };
5585
+ const retired = Object.fromEntries(RETIRED_PARAM_NAMES.map((name) => [name, "native"]));
5586
+ if (!isRecord(schema) || !isRecord(schema.properties ?? {})) {
5587
+ return { ...retired, [USER_GOAL_PARAM_NAME]: "unread" };
5588
+ }
5589
+ if (!takesUserGoalJson(schema)) {
5590
+ if (declaresParam(schema, USER_GOAL_PARAM_NAME)) return { ...retired, [USER_GOAL_PARAM_NAME]: "native" };
5591
+ return mayDeclareParam(schema, USER_GOAL_PARAM_NAME) ? { ...retired, [USER_GOAL_PARAM_NAME]: "may_take" } : retired;
5592
+ }
5593
+ const dispositions = {};
5594
+ for (const name of RETIRED_PARAM_NAMES) if (declaresParam(schema, name)) dispositions[name] = "native";
5595
+ dispositions[USER_GOAL_PARAM_NAME] = declaresParam(schema, USER_GOAL_PARAM_NAME) ? "native" : "injected";
5596
+ return dispositions;
5597
+ }
5598
+ var ownsUserGoal = (dispositions) => OWN.has(dispositions?.[USER_GOAL_PARAM_NAME]);
5599
+ var NO_GOALS = [null, null, null];
5600
+ function popGoals(args, dispositions) {
5601
+ const pop = (name) => {
5602
+ if (!(name in args) || dispositions !== void 0 && KEPT.has(dispositions[name])) return null;
5603
+ const value = args[name];
5604
+ delete args[name];
5605
+ return typeof value === "string" && !isBlank(value) ? value : null;
5606
+ };
5607
+ if (dispositions === void 0) return [pop(USER_GOAL_PARAM_NAME), null, null];
5608
+ return [pop(USER_GOAL_PARAM_NAME), pop(RETIRED_PARAM_NAMES[0]), pop(RETIRED_PARAM_NAMES[1])];
5609
+ }
5610
+ function knownTools(tools) {
5611
+ const dispositions = /* @__PURE__ */ new Map();
5612
+ const names = /* @__PURE__ */ new Set();
5613
+ for (const tool of tools) {
5614
+ try {
5615
+ const name = isRecord(tool) ? tool.name : void 0;
5616
+ if (typeof name !== "string") continue;
5617
+ names.add(name);
5618
+ dispositions.set(name, goalDispositions(tool.inputSchema));
5619
+ } catch {
5620
+ continue;
5621
+ }
5622
+ }
5623
+ return { dispositions, names };
5624
+ }
5625
+ function traceOptions(call) {
5626
+ const [intent, expected, workflow] = call.goals;
5627
+ return {
5628
+ toolName: call.name,
5629
+ params: call.arguments,
5630
+ ...intent === null ? {} : { intent },
5631
+ ...expected === null ? {} : { expectedOutcome: expected },
5632
+ ...workflow === null ? {} : { workflow }
5633
+ };
5634
+ }
5635
+ var Serving = class {
5636
+ constructor(report, settings, tools) {
5637
+ this.report = report;
5638
+ this.settings = settings;
5639
+ this.unreadTools = tools;
5640
+ if (report !== void 0 && Array.isArray(tools)) {
5641
+ try {
5642
+ this.remember(/* @__PURE__ */ new Map(), knownTools(tools).names);
5643
+ } catch {
5644
+ }
5645
+ }
5646
+ }
5647
+ report;
5648
+ settings;
5649
+ serverMeta = { serverInfo: null, capabilities: null, instructions: null };
5650
+ dispositions = /* @__PURE__ */ new Map();
5651
+ vendorHasReportName = false;
5652
+ warnedUnlisted = false;
5653
+ unreadTools;
5654
+ /** Learn the vendor's `tools` once per process. Never throws: without them,
5655
+ * a call to a tool not yet listed is served as on a cold process. */
5656
+ readVendorTools() {
5657
+ const source = this.unreadTools;
5658
+ if (source === void 0) return;
5659
+ this.unreadTools = void 0;
5660
+ try {
5661
+ const tools = typeof source === "function" ? source() : source;
5662
+ if (isThenable(tools)) {
5663
+ throw new Error("tools must be an array or a plain function, not async");
5664
+ }
5665
+ if (!Array.isArray(tools)) throw new Error("tools gave something that is not an array");
5666
+ const known = knownTools(tools);
5667
+ this.remember(known.dispositions, known.names);
5668
+ } catch (err) {
5669
+ stderrLine(
5670
+ `baton: could not read the tools option; a call this process has not seen listed loses user_goal: ${printable(err)}`
5671
+ );
5672
+ }
5673
+ }
5674
+ remember(dispositions, names) {
5675
+ const fresh = [...dispositions.keys()].filter((name2) => !this.dispositions.has(name2)).length;
5676
+ if (this.dispositions.size + fresh > REMEMBERED_TOOLS) this.dispositions.clear();
5677
+ for (const [name2, disposition] of dispositions) {
5678
+ if (!ownsUserGoal(this.dispositions.get(name2))) this.dispositions.set(name2, disposition);
5679
+ }
5680
+ const name = this.report?.tool.name;
5681
+ if (name !== void 0 && names.has(name) && !this.vendorHasReportName) {
5682
+ this.vendorHasReportName = true;
5683
+ stderrLine(
5684
+ `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.`
5685
+ );
5686
+ }
5687
+ }
5688
+ /** The report tool, unless a vendor tool has its name. */
5689
+ ours() {
5690
+ return this.vendorHasReportName ? void 0 : this.report;
5691
+ }
5692
+ document() {
5693
+ return this.settings?.document ?? null;
5694
+ }
5695
+ initialized(answer) {
5696
+ const result = resultOf(answer);
5697
+ if (result === null) return answer;
5698
+ const vendor = result.instructions;
5699
+ this.readVendorTools();
5700
+ this.serverMeta = {
5701
+ serverInfo: isRecord(result.serverInfo) ? result.serverInfo : null,
5702
+ capabilities: isRecord(result.capabilities) ? result.capabilities : null,
5703
+ instructions: typeof vendor === "string" ? vendor : null
5704
+ };
5705
+ const nativeGoal = [...this.dispositions.values()].some((d) => d[USER_GOAL_PARAM_NAME] === "native");
5706
+ const report = this.ours();
5707
+ const document = this.document();
5708
+ const pointer = report === void 0 ? void 0 : buildReportPointer({ vendorDisplayName: report.vendorDisplayName, annotationToolName: report.tool.name });
5709
+ const shown = pointer !== void 0 && (document === null || document.reportsOnForAnyone);
5710
+ const { ours } = batonParagraphs(shown ? pointer : void 0, document?.serverOverlay, !nativeGoal);
5711
+ return { ...answer, result: { ...result, instructions: joined(vendor, ours) } };
5712
+ }
5713
+ listed(request, answer, settings) {
5714
+ const result = resultOf(answer);
5715
+ const tools = result?.tools;
5716
+ if (result === null || !Array.isArray(tools)) return null;
5717
+ this.readVendorTools();
5718
+ const { served, surface } = serveTools(tools, this.serverMeta);
5719
+ const known = knownTools(tools);
5720
+ this.remember(known.dispositions, known.names);
5721
+ const report = this.ours();
5722
+ const firstPage = request.params.cursor === void 0 || request.params.cursor === null;
5723
+ const out = [...served];
5724
+ if (report !== void 0 && firstPage) {
5725
+ const { name, description, inputSchema: inputSchema2 } = report.tool;
5726
+ out.push({ name, description, inputSchema: inputSchema2 });
5727
+ }
5728
+ const overlay = this.document()?.serverOverlay;
5729
+ const overlayId = overlay?.id ?? null;
5730
+ const listed = toolsForCaller({ ...result, tools: out }, settings, {
5731
+ intentParamMode: DEFAULT_INTENT_PARAM_MODE,
5732
+ annotationToolName: report?.tool.name ?? "",
5733
+ injectsGoal: (name) => known.dispositions.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
5734
+ });
5735
+ const whole = firstPage && (result.nextCursor === void 0 || result.nextCursor === null) ? surface : null;
5736
+ return {
5737
+ answer: { ...answer, result: listed },
5738
+ surface: whole,
5739
+ seam: () => {
5740
+ const agentText = servedAgentText({
5741
+ reportNames: report === void 0 ? void 0 : { vendorDisplayName: report.vendorDisplayName, annotationToolName: report.tool.name },
5742
+ intentParamMode: DEFAULT_INTENT_PARAM_MODE,
5743
+ ...goalTextsServed(whole?.surface.tools ?? []),
5744
+ serverOverlay: overlay
5745
+ });
5746
+ const seam = buildSeamAugmentations({
5747
+ injectedToolNames: report === void 0 ? [] : [report.tool.name],
5748
+ intentParamNames: [USER_GOAL_PARAM_NAME],
5749
+ intentParamMode: DEFAULT_INTENT_PARAM_MODE,
5750
+ requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),
5751
+ instructionsSuffix: instructionsSuffix(agentText),
5752
+ agentText
5753
+ });
5754
+ if (this.settings !== void 0) seam.server_overlay = overlayId;
5755
+ return seam;
5756
+ },
5757
+ serverOverlay: overlayId
5758
+ };
5759
+ }
5760
+ /** The plan for one `tools/call`; `null` sends it to dispatch untraced. */
5761
+ call(request, message, settings) {
5762
+ const { name } = request.params;
5763
+ const args = request.params.arguments === void 0 ? {} : request.params.arguments;
5764
+ if (typeof name !== "string" || !isRecord(args)) return null;
5765
+ this.readVendorTools();
5766
+ const dispositions = this.dispositions.get(name);
5767
+ const report = this.ours();
5768
+ if (report !== void 0 && name === report.tool.name) return reportCall(report.tool, name, args, message, settings);
5769
+ if (dispositions === void 0 && USER_GOAL_PARAM_NAME in args && !this.warnedUnlisted) {
5770
+ this.warnedUnlisted = true;
5771
+ stderrLine(
5772
+ `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`
5773
+ );
5774
+ }
5775
+ const stripped = { ...args };
5776
+ const goals = popGoals(stripped, dispositions);
5777
+ if (settings?.overlay?.hiddenTools.has(name)) return hidden(name, stripped, goals, message);
5778
+ const forwarded = Object.keys(stripped).length === Object.keys(args).length ? message : { ...message, params: { ...request.params, arguments: stripped } };
5779
+ return { name, arguments: stripped, goals, message: forwarded, kind: "forward" };
5780
+ }
5781
+ };
5782
+ function reportCall(tool, name, args, message, settings) {
5783
+ if (settings?.reportMode === "off") return hidden(name, { ...args }, NO_GOALS, message);
5784
+ const report = tool.annotateArgs(args);
5785
+ const body = report === null ? { ok: false, error: buildRefusalText({ annotationToolName: name, overlay: settings?.overlay }) } : { ok: true };
5786
+ return {
5787
+ name,
5788
+ arguments: { ...args },
5789
+ goals: NO_GOALS,
5790
+ message,
5791
+ kind: report === null ? "refused" : "report",
5792
+ answer: answerTo(message, { content: [{ type: "text", text: JSON.stringify(body) }], structuredContent: body }),
5793
+ ...report === null ? {} : { report }
5794
+ };
5795
+ }
5796
+ function hidden(name, args, goals, message) {
5797
+ const result = { content: [{ type: "text", text: unknownToolText(name) }], isError: true };
5798
+ return { name, arguments: args, goals, message, kind: "hidden", answer: answerTo(message, result) };
5799
+ }
5800
+ function withoutUserGoal(message) {
5801
+ try {
5802
+ const params = message.params;
5803
+ const args = params.arguments;
5804
+ if (!isRecord(args) || !(USER_GOAL_PARAM_NAME in args)) return message;
5805
+ const stripped = Object.fromEntries(Object.entries(args).filter(([key]) => key !== USER_GOAL_PARAM_NAME));
5806
+ return { ...message, params: { ...params, arguments: stripped } };
5807
+ } catch {
5808
+ return message;
5809
+ }
5810
+ }
5811
+ function jsonRpcError(answer) {
5812
+ return isRecord(answer) && isRecord(answer.error) ? answer.error : null;
5813
+ }
5814
+ function resultOf(answer) {
5815
+ return isRecord(answer) && isRecord(answer.result) ? { ...answer.result } : null;
5816
+ }
5817
+ function isToolErrorResult(result) {
5818
+ return result !== null && Array.isArray(result.content) && result.isError === true;
5819
+ }
5820
+ function answerTo(message, result) {
5821
+ return { jsonrpc: message.jsonrpc ?? "2.0", id: message.id, result };
5822
+ }
5823
+ function instructionsSuffix(agentText) {
5824
+ const pieces = INSTRUCTION_PIECES.filter((piece) => piece in agentText).map((piece) => agentText[piece]);
5825
+ return pieces.includes(null) ? null : pieces.length > 0;
5826
+ }
5827
+
5828
+ // src/library/reportTool.ts
5829
+ function inputSchema() {
5830
+ const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
5831
+ delete schema.$schema;
5832
+ return { ...schema, required: [...schema.required, TOOL_NAME_PARAM_NAME] };
5833
+ }
5834
+ var nonEmptyText = (value) => typeof value === "string" && value !== "";
5835
+ var nonEmptyObject = (value) => isRecord(value) && Object.keys(value).length > 0;
5836
+ function annotateArgs(args) {
5837
+ const whatHappened = args.what_happened;
5838
+ if (!isReport(whatHappened)) return null;
5839
+ const options = { whatHappened };
5840
+ const toolName = args[TOOL_NAME_PARAM_NAME];
5841
+ if (typeof toolName === "string") options.toolName = toolName;
5842
+ const intent = args[USER_GOAL_PARAM_NAME];
5843
+ if (nonEmptyText(intent)) options.intent = intent;
5844
+ if (nonEmptyText(args.suggested_improvement)) {
5845
+ options.suggestedImprovement = args.suggested_improvement;
5846
+ }
5847
+ if (nonEmptyObject(args.context)) options.context = args.context;
5848
+ return options;
5849
+ }
5850
+ function reportTool(options) {
5851
+ const { vendorDisplayName } = options;
5852
+ if (isBlank(vendorDisplayName)) {
5853
+ throw new Error("vendorDisplayName is blank. Baton's report sentence names the server by it.");
5854
+ }
5855
+ const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);
5856
+ if (derived === void 0) {
5857
+ throw new Error(
5858
+ `vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, or one too long for Baton's report sentence. Pass name.`
5859
+ );
5860
+ }
5861
+ const name = validateAnnotationToolName(derived);
5862
+ if (!fitsBatonSentenceCap({ vendorDisplayName, annotationToolName: name })) {
5863
+ throw new Error(
5864
+ `vendorDisplayName and name ${JSON.stringify(name)} are too long together for Baton's report sentence. Shorten one of them.`
5865
+ );
5866
+ }
5867
+ return {
5868
+ name,
5869
+ description: buildAnnotationToolDescription({ vendorDisplayName }),
5870
+ inputSchema: inputSchema(),
5871
+ instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),
5872
+ refusal: buildRefusalText({ annotationToolName: name }),
5873
+ annotateArgs
5874
+ };
5875
+ }
5876
+
5518
5877
  // src/library/client.ts
5519
5878
  function fromEnv(name) {
5520
5879
  const value = typeof process !== "undefined" ? process.env?.[name] : void 0;
@@ -5538,6 +5897,7 @@ function resolveClientOptions(options) {
5538
5897
  if (options.scrubber !== void 0 && typeof options.scrubber !== "function") {
5539
5898
  throw new Error("Client scrubber must be a function.");
5540
5899
  }
5900
+ validateServeOptions(options);
5541
5901
  const dsnString = selectDsn(
5542
5902
  options.dsn,
5543
5903
  {
@@ -5547,15 +5907,25 @@ function resolveClientOptions(options) {
5547
5907
  },
5548
5908
  "Client"
5549
5909
  );
5910
+ if (options.settings === "console" && dsnString === void 0) {
5911
+ throw new Error(`Client settings: "console" reads the Capture page with the dsn's key, so it needs a dsn.`);
5912
+ }
5913
+ candidateNeedsConsole(options.settings);
5914
+ const reportOn = (options.reportMode ?? (options.settings === "console" ? "on" : "off")) === "on";
5550
5915
  const consentToken = resolveConsentToken(options.consentToken);
5551
5916
  if (dsnString !== void 0) {
5552
5917
  const dsn = parseDsn(dsnString);
5918
+ const consoleSettings = options.settings === "console" && !consoleDroppedOnWorkers(options.settings);
5553
5919
  return {
5554
5920
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
5555
5921
  vendorId: dsn.vendorId,
5556
5922
  tenantId: dsn.tenantId,
5557
5923
  consentToken,
5558
- resultCaptureMode
5924
+ resultCaptureMode,
5925
+ ...consoleSettings ? {
5926
+ captureSettings: consoleCaptureSettings(dsn, options.settingsRefreshMs)
5927
+ } : {},
5928
+ ...reportOn ? { report: serveReport(dsn.vendorId, options.vendorDisplayName) } : {}
5559
5929
  };
5560
5930
  }
5561
5931
  if (options.sink === void 0) {
@@ -5572,9 +5942,22 @@ function resolveClientOptions(options) {
5572
5942
  vendorId: vendorId2,
5573
5943
  tenantId: resolveTenantId(options.tenantId || void 0, vendorId2),
5574
5944
  consentToken,
5575
- resultCaptureMode
5945
+ resultCaptureMode,
5946
+ ...reportOn ? { report: serveReport(vendorId2, options.vendorDisplayName) } : {}
5576
5947
  };
5577
5948
  }
5949
+ function validateServeOptions(options) {
5950
+ validateSettings(options, "Client");
5951
+ validateReportMode(options, "Client");
5952
+ if (options.tools !== void 0 && !Array.isArray(options.tools) && typeof options.tools !== "function") {
5953
+ throw new Error("Client tools must be an array of tools or a function that returns one.");
5954
+ }
5955
+ }
5956
+ function serveReport(vendorId2, displayName) {
5957
+ const display = displayName === void 0 || isBlank(displayName) ? vendorId2 : displayName;
5958
+ const name = deriveAnnotationToolName(vendorId2, toolNameForDisplayName(display));
5959
+ return { tool: reportTool({ vendorDisplayName: display, name }), vendorDisplayName: display };
5960
+ }
5578
5961
  var hasText2 = (value) => typeof value === "string" && !isBlank(value);
5579
5962
  function describeError(err) {
5580
5963
  let type = "Error";
@@ -5606,6 +5989,7 @@ var Core = class {
5606
5989
  resultCaptureMode;
5607
5990
  scrubber;
5608
5991
  disabled;
5992
+ settings;
5609
5993
  constructor(resolved) {
5610
5994
  this.sink = offTheCall(resolved.sink);
5611
5995
  this.vendorId = resolved.vendorId;
@@ -5614,6 +5998,10 @@ var Core = class {
5614
5998
  this.resultCaptureMode = resolved.resultCaptureMode;
5615
5999
  this.scrubber = resolved.scrubber;
5616
6000
  this.disabled = resolved.disabled;
6001
+ this.settings = resolved.captureSettings;
6002
+ }
6003
+ modeFor(session) {
6004
+ return session.settings?.resultCaptureMode ?? this.resultCaptureMode;
5617
6005
  }
5618
6006
  /** The envelope members every event of `session` shares. Call inside a
5619
6007
  * build thunk, so `captured_at` is the build time. */
@@ -5627,6 +6015,9 @@ var Core = class {
5627
6015
  consent_token: consentToken
5628
6016
  };
5629
6017
  }
6018
+ errorBody(text) {
6019
+ return scrubbedErrorBody(this.scrubber, text);
6020
+ }
5630
6021
  /** False when nothing may be emitted: the off switch, or a closed client. */
5631
6022
  live() {
5632
6023
  if (this.disabled) return false;
@@ -5640,9 +6031,9 @@ var Core = class {
5640
6031
  }
5641
6032
  /** Sends `surface` unless this client already has. Never rejects. The
5642
6033
  * write only queues, so a surface counts as sent once queued. */
5643
- sendSurface(surface) {
5644
- if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();
5645
- this.sentSurfaces.mark(surface.digest);
6034
+ sendSurface(surface, seam, serverOverlay = null) {
6035
+ if (this.sentSurfaces.wasSent(surface.digest, serverOverlay) || !this.live()) return Promise.resolve();
6036
+ this.sentSurfaces.mark(surface.digest, serverOverlay);
5646
6037
  let event;
5647
6038
  try {
5648
6039
  event = SurfaceSnapshotEventSchema.parse({
@@ -5653,7 +6044,7 @@ var Core = class {
5653
6044
  sequence_number: nextClockSequence(),
5654
6045
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
5655
6046
  consent_token: this.consentToken,
5656
- payload: snapshotPayload(surface)
6047
+ payload: snapshotPayload(surface, seam?.())
5657
6048
  });
5658
6049
  } catch (err) {
5659
6050
  PROCESS_DROPS.add("encode_failed");
@@ -5688,6 +6079,7 @@ var Core = class {
5688
6079
  var UNSET = /* @__PURE__ */ Symbol("unset");
5689
6080
  var WITHHELD_RESULT = /* @__PURE__ */ Symbol("withheld");
5690
6081
  var SCRUB_FAILED = /* @__PURE__ */ Symbol("scrubFailed");
6082
+ var observeFailure;
5691
6083
  var runTrace;
5692
6084
  var Trace = class _Trace {
5693
6085
  #core;
@@ -5698,6 +6090,7 @@ var Trace = class _Trace {
5698
6090
  #startedAt = 0;
5699
6091
  #result = UNSET;
5700
6092
  #error = null;
6093
+ #failure = null;
5701
6094
  #observedWarned = false;
5702
6095
  constructor(core, session, options) {
5703
6096
  this.#core = core;
@@ -5719,6 +6112,7 @@ var Trace = class _Trace {
5719
6112
  }
5720
6113
  this.#result = UNSET;
5721
6114
  this.#error = null;
6115
+ this.#failure = null;
5722
6116
  if (this.#core.disabled) return this;
5723
6117
  let errorType = failure?.errorType;
5724
6118
  let errorBody2 = failure?.errorBody;
@@ -5729,7 +6123,7 @@ var Trace = class _Trace {
5729
6123
  }
5730
6124
  if (errorType !== void 0 || errorBody2 !== void 0) {
5731
6125
  this.#error = { type: errorType || "Error", body: errorBody2 ?? "" };
5732
- } else if (this.#core.resultCaptureMode === WITHHELD) {
6126
+ } else if (this.#core.modeFor(this.#session) === WITHHELD) {
5733
6127
  this.#result = WITHHELD_RESULT;
5734
6128
  } else {
5735
6129
  try {
@@ -5805,23 +6199,40 @@ var Trace = class _Trace {
5805
6199
  #fail(err) {
5806
6200
  const durationMs = this.#durationMs();
5807
6201
  if (!this.#core.live()) return;
5808
- this.#emitError(nextClockSequence(), ...describeError(err), durationMs);
6202
+ const [type, body] = describeError(err);
6203
+ if (this.#core.modeFor(this.#session) === WITHHELD) {
6204
+ this.#failure = { result: null, result_capture: WITHHELD };
6205
+ this.#emitError(nextClockSequence(), type, "", durationMs);
6206
+ return;
6207
+ }
6208
+ this.#emitError(nextClockSequence(), type, body, durationMs);
5809
6209
  }
5810
6210
  #emitError(sequence, type, body, durationMs) {
6211
+ const failure = this.#failure;
5811
6212
  void this.#core.emit(
5812
6213
  () => ToolCallErrorEventSchema.parse({
5813
6214
  ...this.#envelope(sequence),
5814
6215
  payload: {
5815
6216
  tool_name: this.#options.toolName,
5816
6217
  error_type: type,
5817
- error_body: scrubbedErrorBody(this.#core.scrubber, body),
6218
+ error_body: failure === null ? scrubbedErrorBody(this.#core.scrubber, body) : body,
5818
6219
  duration_ms: durationMs,
5819
- result: null
6220
+ result: null,
6221
+ ...failure
5820
6222
  }
5821
6223
  })
5822
6224
  );
5823
6225
  }
5824
6226
  static {
6227
+ observeFailure = (trace, errorType, fields, failureKind) => {
6228
+ trace.#result = UNSET;
6229
+ trace.#error = { type: errorType, body: fields.error_body };
6230
+ trace.#failure = {
6231
+ result: fields.result,
6232
+ ...fields.result_capture === void 0 ? {} : { result_capture: fields.result_capture },
6233
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind }
6234
+ };
6235
+ };
5825
6236
  runTrace = (core, session, options, fn) => {
5826
6237
  const trace = new _Trace(core, session, options);
5827
6238
  trace.#start();
@@ -5849,8 +6260,40 @@ var Trace = class _Trace {
5849
6260
  };
5850
6261
  }
5851
6262
  };
6263
+ var Mark = class {
6264
+ constructor(owner, flags) {
6265
+ this.owner = owner;
6266
+ this.flags = flags;
6267
+ }
6268
+ owner;
6269
+ flags;
6270
+ active = true;
6271
+ };
6272
+ var inDispatch = new asyncHooks3.AsyncLocalStorage();
6273
+ async function dispatched(dispatch, message, mark = null) {
6274
+ try {
6275
+ return await inDispatch.run(mark, () => dispatch(message));
6276
+ } finally {
6277
+ if (mark !== null) mark.active = false;
6278
+ }
6279
+ }
6280
+ function messageText(message) {
6281
+ if (typeof message === "string") return message;
6282
+ return message === void 0 ? "" : JSON.stringify(message) ?? "";
6283
+ }
6284
+ function fieldsOrEmpty(build) {
6285
+ try {
6286
+ return build();
6287
+ } catch (err) {
6288
+ stderrLine(`baton: the scrubber threw on an error answer; its text is dropped: ${printable(err)}`);
6289
+ return { error_body: "", result: null };
6290
+ }
6291
+ }
6292
+ var stopWhenDropped = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((s) => s.stop()) : void 0;
5852
6293
  var Client = class {
5853
6294
  #core;
6295
+ #serving;
6296
+ #doubleWiringLogged = /* @__PURE__ */ new Set();
5854
6297
  #closing;
5855
6298
  constructor(options = {}) {
5856
6299
  const switchName = captureDisabled();
@@ -5872,6 +6315,11 @@ var Client = class {
5872
6315
  scrubber: options.scrubber ?? new Scrubber().scrub,
5873
6316
  disabled: switchName !== null
5874
6317
  });
6318
+ this.#serving = new Serving(resolved.report, resolved.captureSettings, switchName === null ? options.tools : void 0);
6319
+ if (resolved.captureSettings !== void 0) {
6320
+ resolved.captureSettings.start();
6321
+ stopWhenDropped?.register(this, resolved.captureSettings);
6322
+ }
5875
6323
  }
5876
6324
  /** Run `fn` with one session, principal, client and turn for every
5877
6325
  * `trace()` and `annotate()` inside it, including after its awaits. Open
@@ -5892,7 +6340,8 @@ var Client = class {
5892
6340
  * called exactly once, so a lazy query builder is not run twice. A throw or
5893
6341
  * rejection is recorded and passed on unchanged. */
5894
6342
  trace(options, fn) {
5895
- return runTrace(this.#core, sessionForCall(this), options ?? {}, fn);
6343
+ this.#flagDoubleWiring("trace");
6344
+ return runTrace(this.#core, sessionForCall(this, this.#core.settings), options ?? {}, fn);
5896
6345
  }
5897
6346
  /** `fn`, traced on every call. A single plain-object argument is sent as
5898
6347
  * `params`, as an MCP tool's arguments are; other arguments as
@@ -5908,7 +6357,11 @@ var Client = class {
5908
6357
  * own outside one. To report on a traced call, use `trace.annotate()`. */
5909
6358
  annotate(options) {
5910
6359
  const given = options ?? {};
5911
- return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);
6360
+ return this.#core.annotate(
6361
+ sessionForCall(this, this.#core.settings),
6362
+ given.consentToken || this.#core.consentToken,
6363
+ given
6364
+ );
5912
6365
  }
5913
6366
  /** `tools`, the vendor's own `tools/list` entries, with `user_goal` added
5914
6367
  * to each `inputSchema` as `withBaton` adds it, and a `surface_snapshot`
@@ -5921,11 +6374,176 @@ var Client = class {
5921
6374
  * tool list: one it cannot read is returned as it came. Does not wait for
5922
6375
  * the snapshot to be sent; `flush()` does. */
5923
6376
  async listTools(tools, options = {}) {
6377
+ this.#flagDoubleWiring("listTools");
5924
6378
  if (this.#core.disabled) return tools;
5925
6379
  const { served, surface } = serveTools(tools, options);
5926
6380
  if (surface !== null) void this.#core.sendSurface(surface);
5927
6381
  return served;
5928
6382
  }
6383
+ /** Answer one MCP JSON-RPC `message` with `dispatch`, the vendor's own
6384
+ * function from message to answer, and Baton around it (SPEC §5.6).
6385
+ * Experimental.
6386
+ *
6387
+ * `initialize` gets Baton's instructions. `tools/list` gets `user_goal` and
6388
+ * the report tool, under the caller's Console settings, and sends the
6389
+ * snapshot. `tools/call` is traced, with `user_goal` removed before
6390
+ * `dispatch` sees it; Baton answers the report tool and a tool the caller's
6391
+ * overlay hides itself. Anything else goes to `dispatch` as it came.
6392
+ *
6393
+ * `options` are as on `session()`. A process learns the vendor's tools from
6394
+ * the lists it serves. Until it has, a call loses `user_goal` and the report
6395
+ * tool's name is Baton's; pass the `tools` option when a tool declares its
6396
+ * own `user_goal` or has the report tool's name. `dispatch` is called at
6397
+ * most once, and what it returns or throws comes back unchanged apart from
6398
+ * Baton's additions. A failure in Baton's own work is logged, never thrown. */
6399
+ serve(message, dispatch, options = {}) {
6400
+ return inDispatch.run(null, () => this.#serve(message, dispatch, options ?? {}));
6401
+ }
6402
+ async #serve(message, dispatch, options) {
6403
+ const request = this.#request(message);
6404
+ if (request === null) return dispatched(dispatch, message);
6405
+ const settings = this.#core.settings;
6406
+ if (settings !== void 0 && !settings.isReady) await settings.ready;
6407
+ const handle = () => this.#handle(request, message, dispatch);
6408
+ const { principal, headers, sessionId } = options;
6409
+ if (inBlock(this) && principal === void 0 && headers === void 0 && sessionId === void 0) return handle();
6410
+ const values = {
6411
+ ...principal === void 0 ? {} : { principal },
6412
+ ...headers === void 0 ? {} : { headers },
6413
+ ...sessionId === void 0 ? {} : { sessionId }
6414
+ };
6415
+ try {
6416
+ if (isRecord(request.params._meta)) values.meta = request.params._meta;
6417
+ if (request.method === "initialize" && isRecord(request.params.clientInfo)) {
6418
+ values.clientInfo = request.params.clientInfo;
6419
+ }
6420
+ } catch {
6421
+ }
6422
+ return this.session(values, handle);
6423
+ }
6424
+ async #handle(request, message, dispatch) {
6425
+ let session;
6426
+ let call = null;
6427
+ try {
6428
+ session = sessionForCall(this, this.#core.settings);
6429
+ if (request.method === TOOL_CALL) call = this.#serving.call(request, message, session.settings);
6430
+ } catch (err) {
6431
+ stderrLine(`baton: serve() could not read the request; it is served as it came: ${printable(err)}`);
6432
+ return dispatched(dispatch, withoutUserGoal(message));
6433
+ }
6434
+ if (request.method !== TOOL_CALL) {
6435
+ const mark = request.method === TOOL_LIST ? new Mark(this, "listTools") : null;
6436
+ return this.#shaped(request, await dispatched(dispatch, message, mark), session);
6437
+ }
6438
+ if (call === null) return dispatched(dispatch, message);
6439
+ if (call.answer !== void 0) {
6440
+ this.#answerOurselves(call, session);
6441
+ return call.answer;
6442
+ }
6443
+ return this.#traced(call, dispatch, session);
6444
+ }
6445
+ #request(message) {
6446
+ if (this.#core.disabled) return null;
6447
+ try {
6448
+ return readRequest(message);
6449
+ } catch (err) {
6450
+ stderrLine(`baton: serve() could not read the request; it is served as it came: ${printable(err)}`);
6451
+ return null;
6452
+ }
6453
+ }
6454
+ /** Dispatch's `initialize` or `tools/list` answer with Baton's additions,
6455
+ * and its snapshot sent; the answer unchanged on failure. */
6456
+ #shaped(request, answer, session) {
6457
+ try {
6458
+ if (request.method !== TOOL_LIST) return this.#serving.initialized(answer);
6459
+ const listed = this.#serving.listed(request, answer, session.settings);
6460
+ if (listed === null) return answer;
6461
+ if (listed.surface !== null) void this.#core.sendSurface(listed.surface, listed.seam, listed.serverOverlay);
6462
+ return listed.answer;
6463
+ } catch (err) {
6464
+ stderrLine(`baton: serve() could not add to the answer; it is served as it came: ${printable(err)}`);
6465
+ return answer;
6466
+ }
6467
+ }
6468
+ async #traced(call, dispatch, session) {
6469
+ let dispatching = false;
6470
+ try {
6471
+ return await runTrace(this.#core, session, traceOptions(call), async (trace) => {
6472
+ dispatching = true;
6473
+ const answer = await dispatched(dispatch, call.message, new Mark(this, "trace"));
6474
+ this.#record(trace, answer, session);
6475
+ return answer;
6476
+ });
6477
+ } catch (err) {
6478
+ if (dispatching) throw err;
6479
+ stderrLine(`baton: serve() could not trace the call: ${printable(err)}`);
6480
+ return dispatched(dispatch, call.message, new Mark(this, "trace"));
6481
+ }
6482
+ }
6483
+ #record(trace, answer, session) {
6484
+ const mode = this.#core.modeFor(session);
6485
+ const scrubber = this.#core.scrubber;
6486
+ const errorBody2 = (text) => this.#core.errorBody(text);
6487
+ try {
6488
+ const error = jsonRpcError(answer);
6489
+ if (error !== null) {
6490
+ observeFailure(
6491
+ trace,
6492
+ JSONRPC_ERROR_TYPE,
6493
+ fieldsOrEmpty(
6494
+ () => resultDerivedFields(mode, () => messageText(error.message), { ...error }, errorBody2, scrubber)
6495
+ )
6496
+ );
6497
+ return;
6498
+ }
6499
+ const result = resultOf(answer);
6500
+ if (isToolErrorResult(result)) {
6501
+ observeFailure(
6502
+ trace,
6503
+ TOOL_ERROR_TYPE,
6504
+ fieldsOrEmpty(() => returnedErrorFields(mode, result, errorBody2, scrubber))
6505
+ );
6506
+ return;
6507
+ }
6508
+ trace.observed(result ?? answer);
6509
+ } catch (err) {
6510
+ stderrLine(`baton: serve() could not record the tool call: ${printable(err)}`);
6511
+ try {
6512
+ trace.observed(void 0);
6513
+ } catch {
6514
+ }
6515
+ }
6516
+ }
6517
+ #answerOurselves(call, session) {
6518
+ try {
6519
+ if (call.report !== void 0) {
6520
+ void this.#core.annotate(session, this.#core.consentToken, call.report);
6521
+ } else if (call.kind === "hidden") {
6522
+ const scrubber = this.#core.scrubber;
6523
+ const fields = fieldsOrEmpty(
6524
+ () => returnedErrorFields("full", call.answer.result, (text) => this.#core.errorBody(text), scrubber)
6525
+ );
6526
+ runTrace(
6527
+ this.#core,
6528
+ session,
6529
+ traceOptions(call),
6530
+ (trace) => observeFailure(trace, TOOL_ERROR_TYPE, fields, "tool_hidden")
6531
+ );
6532
+ }
6533
+ } catch (err) {
6534
+ stderrLine(`baton: serve() could not record its own answer: ${printable(err)}`);
6535
+ }
6536
+ }
6537
+ /** An error, once per client and call, when the vendor's code inside
6538
+ * `serve()` still calls what `serve()` now does: the old wiring was left in. */
6539
+ #flagDoubleWiring(call) {
6540
+ const mark = inDispatch.getStore();
6541
+ if (!mark?.active || mark.owner !== this || mark.flags !== call || this.#doubleWiringLogged.has(call)) return;
6542
+ this.#doubleWiringLogged.add(call);
6543
+ stderrLine(
6544
+ `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.`
6545
+ );
6546
+ }
5929
6547
  /** Wait for events so far to reach the sink, then flush it. Never rejects;
5930
6548
  * returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
5931
6549
  async flush() {
@@ -5933,61 +6551,13 @@ var Client = class {
5933
6551
  }
5934
6552
  /** Flush, then close the sink. Later events are dropped. */
5935
6553
  aclose() {
6554
+ this.#core.settings?.stop();
5936
6555
  this.#closing ??= boundedSinkCall(this.#core.sink, "aclose").then(() => {
5937
6556
  this.#core.closed = true;
5938
6557
  });
5939
6558
  return this.#closing;
5940
6559
  }
5941
6560
  };
5942
-
5943
- // src/library/reportTool.ts
5944
- function inputSchema() {
5945
- const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
5946
- delete schema.$schema;
5947
- return { ...schema, required: [...schema.required, TOOL_NAME_PARAM_NAME] };
5948
- }
5949
- var nonEmptyText = (value) => typeof value === "string" && value !== "";
5950
- var nonEmptyObject = (value) => isRecord(value) && Object.keys(value).length > 0;
5951
- function annotateArgs(args) {
5952
- const whatHappened = args.what_happened;
5953
- if (!isReport(whatHappened)) return null;
5954
- const options = { whatHappened };
5955
- const toolName = args[TOOL_NAME_PARAM_NAME];
5956
- if (typeof toolName === "string") options.toolName = toolName;
5957
- const intent = args[USER_GOAL_PARAM_NAME];
5958
- if (nonEmptyText(intent)) options.intent = intent;
5959
- if (nonEmptyText(args.suggested_improvement)) {
5960
- options.suggestedImprovement = args.suggested_improvement;
5961
- }
5962
- if (nonEmptyObject(args.context)) options.context = args.context;
5963
- return options;
5964
- }
5965
- function reportTool(options) {
5966
- const { vendorDisplayName } = options;
5967
- if (isBlank(vendorDisplayName)) {
5968
- throw new Error("vendorDisplayName is blank. Baton's report sentence names the server by it.");
5969
- }
5970
- const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);
5971
- if (derived === void 0) {
5972
- throw new Error(
5973
- `vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, or one too long for Baton's report sentence. Pass name.`
5974
- );
5975
- }
5976
- const name = validateAnnotationToolName(derived);
5977
- if (!fitsBatonSentenceCap({ vendorDisplayName, annotationToolName: name })) {
5978
- throw new Error(
5979
- `vendorDisplayName and name ${JSON.stringify(name)} are too long together for Baton's report sentence. Shorten one of them.`
5980
- );
5981
- }
5982
- return {
5983
- name,
5984
- description: buildAnnotationToolDescription({ vendorDisplayName }),
5985
- inputSchema: inputSchema(),
5986
- instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),
5987
- refusal: buildRefusalText({ annotationToolName: name }),
5988
- annotateArgs
5989
- };
5990
- }
5991
6561
  export {
5992
6562
  BatonHandle,
5993
6563
  Client,