@goodtiming/baton-sdk 1.2.2 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.1";
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");
@@ -3184,19 +3187,29 @@ var ANNOTATION_INPUT_SHAPE = {
3184
3187
  // zod renders "any value" as `{}`, which some MCP clients refuse (reportToolSchema.test.ts).
3185
3188
  context: z2.record(z2.string(), z2.unknown()).meta({ additionalProperties: true }).nullable().optional()
3186
3189
  };
3190
+ var ANNOTATION_ARGS = z2.object(ANNOTATION_INPUT_SHAPE);
3187
3191
  function isReport(whatHappened) {
3188
3192
  return typeof whatHappened === "string" && !isBlank(whatHappened);
3189
3193
  }
3190
- function registerAnnotationTool(server, options) {
3194
+ var INVALID_PARAMS = -32602;
3195
+ function registerAnnotationTool(server, options, callArguments) {
3191
3196
  const tool = buildAnnotationTool(server, options);
3192
- server.registerTool(
3193
- tool.name,
3194
- { description: tool.description, inputSchema: ANNOTATION_INPUT_SHAPE },
3195
- tool.handler
3196
- );
3197
- return tool.name;
3197
+ if (callArguments === void 0) {
3198
+ server.registerTool(tool.name, { description: tool.description, inputSchema: ANNOTATION_INPUT_SHAPE }, tool.handler);
3199
+ return;
3200
+ }
3201
+ server.registerTool(tool.name, { description: tool.description }, async (extra) => {
3202
+ const args = callArguments();
3203
+ const { validateToolInput } = server;
3204
+ let parsed;
3205
+ try {
3206
+ parsed = await validateToolInput?.call(server, { inputSchema: ANNOTATION_ARGS }, args, tool.name);
3207
+ } catch (err) {
3208
+ if (err?.code === INVALID_PARAMS) throw err;
3209
+ }
3210
+ return isRecord(parsed) ? tool.handler(parsed, extra) : callAnnotationTool(tool, args, extra);
3211
+ });
3198
3212
  }
3199
- var ANNOTATION_ARGS = z2.object(ANNOTATION_INPUT_SHAPE);
3200
3213
  function annotationInputJsonSchema(major) {
3201
3214
  return annotationJsonSchemas[major] ??= (major === 2 ? standardInputJsonSchema(ANNOTATION_ARGS) : void 0) ?? toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
3202
3215
  }
@@ -3496,12 +3509,16 @@ function resolveInstallConfig(config) {
3496
3509
  return { resolved, unconfigured };
3497
3510
  }
3498
3511
  var consoleOffWarned = false;
3499
- function withoutConsoleOnWorkers(config) {
3500
- if (config.settings !== "console" || !onWorkers()) return config;
3512
+ function consoleDroppedOnWorkers(settings) {
3513
+ if (settings !== "console" || !onWorkers()) return false;
3501
3514
  if (!consoleOffWarned) {
3502
3515
  consoleOffWarned = true;
3503
3516
  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
3517
  }
3518
+ return true;
3519
+ }
3520
+ function withoutConsoleOnWorkers(config) {
3521
+ if (!consoleDroppedOnWorkers(config.settings)) return config;
3505
3522
  const rest = { ...config, reportMode: config.reportMode ?? "on" };
3506
3523
  delete rest.settings;
3507
3524
  return rest;
@@ -3562,18 +3579,7 @@ function resolveBatonConfig(supplied) {
3562
3579
  // itself, exactly as it does for an explicitly-constructed sink.
3563
3580
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
3564
3581
  ...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
- )
3582
+ captureSettings: consoleCaptureSettings(dsn, identity.settingsRefreshMs)
3577
3583
  } : {}
3578
3584
  };
3579
3585
  }
@@ -3588,6 +3594,36 @@ function withServerDisplayName(resolved, supplied, serverName) {
3588
3594
  var RENAMED_KEYS = {
3589
3595
  resolveUser: "resolvePrincipal"
3590
3596
  };
3597
+ function consoleCaptureSettings(dsn, refreshMs) {
3598
+ const fetcher = new SettingsFetcher({
3599
+ origin: dsn.origin,
3600
+ apiKey: dsn.key,
3601
+ tenantId: dsn.tenantId,
3602
+ vendorId: dsn.vendorId,
3603
+ refreshMs: refreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
3604
+ });
3605
+ return new CaptureSettings(dsn.vendorId, fetcher, envCandidate(), envTask());
3606
+ }
3607
+ function validateReportMode(config, owner) {
3608
+ if (config.reportMode !== void 0 && !REPORT_MODES.has(config.reportMode)) {
3609
+ throw new Error(
3610
+ `${owner}.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
3611
+ );
3612
+ }
3613
+ }
3614
+ function validateSettings(config, owner) {
3615
+ if (config.settings !== void 0 && !SETTINGS_MODES.includes(config.settings)) {
3616
+ throw new Error(
3617
+ `${owner}.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`
3618
+ );
3619
+ }
3620
+ const refresh = config.settingsRefreshMs;
3621
+ if (refresh !== void 0 && (typeof refresh !== "number" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))) {
3622
+ throw new Error(
3623
+ `${owner}.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} to ${String(MAX_TIMER_MS)}.`
3624
+ );
3625
+ }
3626
+ }
3591
3627
  function validateBatonConfig(config) {
3592
3628
  for (const [was, now] of Object.entries(RENAMED_KEYS)) {
3593
3629
  if (was in config) {
@@ -3604,11 +3640,7 @@ function validateBatonConfig(config) {
3604
3640
  `vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
3605
3641
  );
3606
3642
  }
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
- }
3643
+ validateReportMode(config, "BatonConfig");
3612
3644
  if (!config.vendorDisplayName && config.reportMode === "on") {
3613
3645
  throw new Error(
3614
3646
  'BatonConfig needs a vendorDisplayName with reportMode: "on" \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4).'
@@ -3639,17 +3671,7 @@ function validateBatonConfig(config) {
3639
3671
  `BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
3640
3672
  );
3641
3673
  }
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
- }
3674
+ validateSettings(config, "BatonConfig");
3653
3675
  if (config.scrubber !== void 0 && typeof config.scrubber !== "function") {
3654
3676
  throw new Error("BatonConfig.scrubber must be a function.");
3655
3677
  }
@@ -3783,33 +3805,35 @@ var PerCallerSurface = class {
3783
3805
  }
3784
3806
  /** `result` with the caller's goal, reports and overlay; as served on any failure. */
3785
3807
  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
- }
3808
+ return toolsForCaller(result, caller.settings, this.options);
3811
3809
  }
3812
3810
  };
3811
+ function toolsForCaller(result, settings, options) {
3812
+ if (settings === void 0) return result;
3813
+ const { intentParamMode, annotationToolName, injectsGoal } = options;
3814
+ const goal = settings.intentParamMode ?? intentParamMode;
3815
+ const hideReports = annotationToolName !== "" && settings.reportMode === "off";
3816
+ const overlay = settings.overlay;
3817
+ if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
3818
+ try {
3819
+ const tools = result?.tools;
3820
+ if (!Array.isArray(tools)) return result;
3821
+ const served = [];
3822
+ const injected = [];
3823
+ for (const tool of tools) {
3824
+ const name = tool?.name;
3825
+ if (hideReports && name === annotationToolName) continue;
3826
+ const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
3827
+ served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
3828
+ injected.push(ours);
3829
+ }
3830
+ const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
3831
+ return { ...result, tools: rewritten };
3832
+ } catch (err) {
3833
+ stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
3834
+ return result;
3835
+ }
3836
+ }
3813
3837
  function batonParagraphs(pointer, overlay, subagentLine) {
3814
3838
  const parts = overlay?.instructionAppends() ?? [];
3815
3839
  if (pointer !== void 0) parts.push(overlaid(pointer, overlay, "instructions.report_pointer"));
@@ -3820,7 +3844,7 @@ function batonParagraphs(pointer, overlay, subagentLine) {
3820
3844
  function withOverlay(tools, injected, overlay, reportTool2) {
3821
3845
  const position = /* @__PURE__ */ new Map();
3822
3846
  tools.forEach((tool, i) => position.set(tool?.name, i));
3823
- const hidden = /* @__PURE__ */ new Set();
3847
+ const hidden2 = /* @__PURE__ */ new Set();
3824
3848
  for (const action of overlay.actions) {
3825
3849
  if (action.tool === void 0) continue;
3826
3850
  const i = position.get(action.tool);
@@ -3829,7 +3853,7 @@ function withOverlay(tools, injected, overlay, reportTool2) {
3829
3853
  } else if (action.tool === reportTool2) {
3830
3854
  warnSkipped(overlay.id, action.index, "the report tool takes agent_text targets only");
3831
3855
  } else if (action.param === void 0 && action.change === "remove") {
3832
- hidden.add(i);
3856
+ hidden2.add(i);
3833
3857
  } else if (action.param === void 0) {
3834
3858
  tools[i] = withDescription(tools[i], [action]);
3835
3859
  } else {
@@ -3848,7 +3872,7 @@ function withOverlay(tools, injected, overlay, reportTool2) {
3848
3872
  if (reportActions.length > 0 && reportAt !== void 0) {
3849
3873
  tools[reportAt] = withDescription(tools[reportAt], reportActions);
3850
3874
  }
3851
- return tools.filter((_, i) => !hidden.has(i));
3875
+ return tools.filter((_, i) => !hidden2.has(i));
3852
3876
  }
3853
3877
  function withDescription(tool, actions) {
3854
3878
  const description = typeof tool.description === "string" ? tool.description : void 0;
@@ -4404,11 +4428,9 @@ var TOOLS_LIST_SEAM = /* @__PURE__ */ Symbol("batonToolsListSeam");
4404
4428
  var TOOLS_CALL_METHOD = "tools/call";
4405
4429
  var TOOLS_CALL_SEAM = /* @__PURE__ */ Symbol("batonToolsCallSeam");
4406
4430
  function installRequestSeam(lowLevel, method, seamTag, wrap) {
4407
- const table = lowLevel._requestHandlers;
4408
- const originalSet = lowLevel.setRequestHandler;
4409
- if (!(table instanceof Map) || typeof originalSet !== "function") return;
4410
- const handlers = table;
4411
- const setRequestHandler = originalSet;
4431
+ if (!takesRequestSeams(lowLevel)) return;
4432
+ const handlers = lowLevel._requestHandlers;
4433
+ const setRequestHandler = lowLevel.setRequestHandler;
4412
4434
  const wrapCurrent = () => {
4413
4435
  const handler = handlers.get(method);
4414
4436
  if (typeof handler !== "function" || handler[seamTag]) return;
@@ -4424,18 +4446,24 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
4424
4446
  return registered;
4425
4447
  };
4426
4448
  }
4449
+ function takesRequestSeams(lowLevel) {
4450
+ return lowLevel._requestHandlers instanceof Map && typeof lowLevel.setRequestHandler === "function";
4451
+ }
4427
4452
  function installToolsListSeam(lowLevel, ctx, listsOwnReportTool) {
4428
4453
  const names = [...requiredParamNames(ctx.intentParamMode), TOOL_NAME_PARAM_NAME];
4429
4454
  const isInjected = (toolName, paramName) => toolName === ctx.annotationToolName ? paramName === TOOL_NAME_PARAM_NAME : ctx.paramRegistry.get(toolName)?.[paramName] === "injected";
4430
4455
  const advertise = (result) => {
4456
+ let served = result;
4431
4457
  try {
4432
- const served = listsOwnReportTool || ctx.annotationToolName === "" ? result : withToolInputSchema(result, ctx.annotationToolName, annotationInputJsonSchema(lowLevelMajor(lowLevel)));
4458
+ if (!listsOwnReportTool && ctx.annotationToolName !== "") {
4459
+ served = withToolInputSchema(result, ctx.annotationToolName, annotationInputJsonSchema(lowLevelMajor(lowLevel)));
4460
+ }
4433
4461
  return advertiseIntentParamsRequired(served, names, isInjected);
4434
4462
  } catch (err) {
4435
4463
  stderrLine(
4436
- `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}`
4464
+ `baton: tools/list advertisement failed; serving the list without it: ${String(err)}`
4437
4465
  );
4438
- return result;
4466
+ return served;
4439
4467
  }
4440
4468
  };
4441
4469
  installRequestSeam(lowLevel, TOOLS_LIST_METHOD, TOOLS_LIST_SEAM, (handler) => (...args) => {
@@ -4833,14 +4861,15 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
4833
4861
  (handler) => async (...args) => {
4834
4862
  const request = args[0];
4835
4863
  const name = request?.params?.name;
4864
+ const toolArgs = request?.params?.arguments;
4836
4865
  const slot = {
4837
4866
  innerFired: false,
4838
4867
  flushTerminal: null,
4839
4868
  stripped: stripIntentParams(request?.params, ctx),
4840
4869
  strippedFor: typeof name === "string" ? name : null,
4841
- validation: "unseen"
4870
+ validation: "unseen",
4871
+ arguments: name === ctx.annotationToolName ? toolArgs : void 0
4842
4872
  };
4843
- const toolArgs = request?.params?.arguments;
4844
4873
  if (typeof name === "string" && toolEntry(name) != null && await hiddenFrom(slot, name, isRecord(toolArgs) ? toolArgs : {}, args[1], ctx)) {
4845
4874
  return answerHidden(lowLevel, name, (outcome2) => settleCall(slot, outcome2, args, toolEntry, ctx, "tool_hidden"));
4846
4875
  }
@@ -4875,7 +4904,7 @@ async function hiddenFrom(slot, name, params, extra, ctx) {
4875
4904
  }
4876
4905
  async function answerHidden(lowLevel, name, settle) {
4877
4906
  if (lowLevelMajor(lowLevel) === 1) {
4878
- const result = { content: [{ type: "text", text: `MCP error -32602: Tool ${name} not found` }], isError: true };
4907
+ const result = { content: [{ type: "text", text: unknownToolText(name) }], isError: true };
4879
4908
  await settle({ failed: true, raised: false, result });
4880
4909
  return result;
4881
4910
  }
@@ -5335,7 +5364,13 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned4, co
5335
5364
  checkGivenTools?.();
5336
5365
  return handle(annotationToolName);
5337
5366
  }
5338
- const resolvedAnnotationToolName = annotationOptions ? registerAnnotationTool(server, annotationOptions) : "";
5367
+ if (annotationOptions) {
5368
+ registerAnnotationTool(
5369
+ server,
5370
+ annotationOptions,
5371
+ takesRequestSeams(lowLevel) ? () => callSlots.getStore()?.arguments : void 0
5372
+ );
5373
+ }
5339
5374
  const existing = internals._registeredTools;
5340
5375
  if (existing) {
5341
5376
  for (const [name, entry] of Object.entries(existing)) {
@@ -5348,7 +5383,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned4, co
5348
5383
  wireEntry(String(args[0]), registered, ctx);
5349
5384
  return registered;
5350
5385
  };
5351
- return handle(resolvedAnnotationToolName);
5386
+ return handle(annotationToolName);
5352
5387
  }
5353
5388
  function reportsFor(config) {
5354
5389
  if (config.reportMode !== "on") return void 0;
@@ -5399,6 +5434,9 @@ function principalFromOAuthEmail(context) {
5399
5434
  };
5400
5435
  }
5401
5436
 
5437
+ // src/library/client.ts
5438
+ import * as asyncHooks3 from "async_hooks";
5439
+
5402
5440
  // src/library/session.ts
5403
5441
  import * as asyncHooks2 from "async_hooks";
5404
5442
  var TRANSPORT_LIBRARY = "library";
@@ -5412,7 +5450,8 @@ function sessionEnvelope(session) {
5412
5450
  organization: session.organization,
5413
5451
  labels: wireLabels(session.labels),
5414
5452
  client_observed: session.clientObserved,
5415
- runtime_meta: session.runtimeMeta
5453
+ runtime_meta: session.runtimeMeta,
5454
+ capture: session.settings?.capture ?? null
5416
5455
  };
5417
5456
  }
5418
5457
  function warn2(message) {
@@ -5427,7 +5466,7 @@ function vendorId(name, value) {
5427
5466
  return null;
5428
5467
  }
5429
5468
  function blank(sessionId, origin) {
5430
- return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };
5469
+ return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null, candidate: null, task: null };
5431
5470
  }
5432
5471
  function requestMeta(meta) {
5433
5472
  if (isRecord(meta)) return meta;
@@ -5450,16 +5489,48 @@ function newSession(values, scrubber, disabled) {
5450
5489
  ...base,
5451
5490
  ...callerFor(values.principal, (_key, message) => warn2(`principal ${message}`)),
5452
5491
  clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber, meta),
5453
- runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
5492
+ runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber),
5493
+ candidate: vendorHeader(values.headers, CANDIDATE_HEADER, candidateId),
5494
+ task: vendorHeader(values.headers, TASK_HEADER, taskId)
5454
5495
  };
5455
5496
  }
5497
+ function vendorHeader(headers, name, parse) {
5498
+ try {
5499
+ if (headers === void 0) return null;
5500
+ if (typeof headers.get === "function") return parse(headers.get(name));
5501
+ const key = Object.keys(headers).find((k) => k.toLowerCase() === name);
5502
+ return key === void 0 ? null : parse(headers[key]);
5503
+ } catch {
5504
+ return null;
5505
+ }
5506
+ }
5456
5507
  var current = new asyncHooks2.AsyncLocalStorage();
5457
5508
  function runInSession(owner, session, fn) {
5458
5509
  return current.run({ owner, session }, fn);
5459
5510
  }
5460
- function sessionForCall(owner) {
5461
- const entry = current.getStore();
5462
- return entry !== void 0 && entry.owner === owner ? entry.session : blank(uuid7(), "minted");
5511
+ var settingsWarned2 = false;
5512
+ function sessionForCall(owner, settings) {
5513
+ const session = inBlock(owner) ? current.getStore().session : blank(uuid7(), "minted");
5514
+ if (settings === void 0) return session;
5515
+ try {
5516
+ const callSettings = settings.forCaller({
5517
+ labels: session.labels,
5518
+ clientName: session.clientObserved?.info?.name ?? null,
5519
+ shareKey: session.principal?.id ?? null,
5520
+ candidate: session.candidate,
5521
+ task: session.task
5522
+ });
5523
+ return callSettings === void 0 ? session : { ...session, settings: callSettings };
5524
+ } catch (err) {
5525
+ if (!settingsWarned2) {
5526
+ settingsWarned2 = true;
5527
+ warn2(`applying capture settings failed; this call uses the client's values: ${printable(err)}`);
5528
+ }
5529
+ return session;
5530
+ }
5531
+ }
5532
+ function inBlock(owner) {
5533
+ return current.getStore()?.owner === owner;
5463
5534
  }
5464
5535
 
5465
5536
  // src/library/surface.ts
@@ -5491,11 +5562,11 @@ function serveTools(tools, options) {
5491
5562
  return { served, surface: null };
5492
5563
  }
5493
5564
  }
5494
- function snapshotPayload({ surface, digest }) {
5565
+ function snapshotPayload({ surface, digest }, seam) {
5495
5566
  return {
5496
5567
  surface_hash: digest,
5497
5568
  ...surface,
5498
- seam_augmentations: buildSeamAugmentations({
5569
+ seam_augmentations: seam ?? buildSeamAugmentations({
5499
5570
  injectedToolNames: [],
5500
5571
  intentParamNames: [USER_GOAL_PARAM_NAME],
5501
5572
  intentParamMode: DEFAULT_INTENT_PARAM_MODE,
@@ -5515,6 +5586,315 @@ function servedEntry(tool) {
5515
5586
  return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, DEFAULT_INTENT_PARAM_MODE, true) };
5516
5587
  }
5517
5588
 
5589
+ // src/library/serve.ts
5590
+ var INITIALIZE = "initialize";
5591
+ var TOOL_LIST = "tools/list";
5592
+ var TOOL_CALL = "tools/call";
5593
+ var JSONRPC_ERROR_TYPE = "JSONRPCError";
5594
+ var REMEMBERED_TOOLS = 4096;
5595
+ function readRequest(message) {
5596
+ if (!isRecord(message) || message.id === void 0 || message.id === null) return null;
5597
+ const { method } = message;
5598
+ const params = message.params === void 0 ? {} : message.params;
5599
+ if (method !== INITIALIZE && method !== TOOL_LIST && method !== TOOL_CALL || !isRecord(params)) return null;
5600
+ return { method, params };
5601
+ }
5602
+ var OWN = /* @__PURE__ */ new Set(["native", "may_take"]);
5603
+ var KEPT = /* @__PURE__ */ new Set(["native", "may_take", "unread"]);
5604
+ function goalDispositions(schema) {
5605
+ if (schema === void 0 || schema === null) return { [USER_GOAL_PARAM_NAME]: "injected" };
5606
+ const retired = Object.fromEntries(RETIRED_PARAM_NAMES.map((name) => [name, "native"]));
5607
+ if (!isRecord(schema) || !isRecord(schema.properties ?? {})) {
5608
+ return { ...retired, [USER_GOAL_PARAM_NAME]: "unread" };
5609
+ }
5610
+ if (!takesUserGoalJson(schema)) {
5611
+ if (declaresParam(schema, USER_GOAL_PARAM_NAME)) return { ...retired, [USER_GOAL_PARAM_NAME]: "native" };
5612
+ return mayDeclareParam(schema, USER_GOAL_PARAM_NAME) ? { ...retired, [USER_GOAL_PARAM_NAME]: "may_take" } : retired;
5613
+ }
5614
+ const dispositions = {};
5615
+ for (const name of RETIRED_PARAM_NAMES) if (declaresParam(schema, name)) dispositions[name] = "native";
5616
+ dispositions[USER_GOAL_PARAM_NAME] = declaresParam(schema, USER_GOAL_PARAM_NAME) ? "native" : "injected";
5617
+ return dispositions;
5618
+ }
5619
+ var ownsUserGoal = (dispositions) => OWN.has(dispositions?.[USER_GOAL_PARAM_NAME]);
5620
+ var NO_GOALS = [null, null, null];
5621
+ function popGoals(args, dispositions) {
5622
+ const pop = (name) => {
5623
+ if (!(name in args) || dispositions !== void 0 && KEPT.has(dispositions[name])) return null;
5624
+ const value = args[name];
5625
+ delete args[name];
5626
+ return typeof value === "string" && !isBlank(value) ? value : null;
5627
+ };
5628
+ if (dispositions === void 0) return [pop(USER_GOAL_PARAM_NAME), null, null];
5629
+ return [pop(USER_GOAL_PARAM_NAME), pop(RETIRED_PARAM_NAMES[0]), pop(RETIRED_PARAM_NAMES[1])];
5630
+ }
5631
+ function knownTools(tools) {
5632
+ const dispositions = /* @__PURE__ */ new Map();
5633
+ const names = /* @__PURE__ */ new Set();
5634
+ for (const tool of tools) {
5635
+ try {
5636
+ const name = isRecord(tool) ? tool.name : void 0;
5637
+ if (typeof name !== "string") continue;
5638
+ names.add(name);
5639
+ dispositions.set(name, goalDispositions(tool.inputSchema));
5640
+ } catch {
5641
+ continue;
5642
+ }
5643
+ }
5644
+ return { dispositions, names };
5645
+ }
5646
+ function traceOptions(call) {
5647
+ const [intent, expected, workflow] = call.goals;
5648
+ return {
5649
+ toolName: call.name,
5650
+ params: call.arguments,
5651
+ ...intent === null ? {} : { intent },
5652
+ ...expected === null ? {} : { expectedOutcome: expected },
5653
+ ...workflow === null ? {} : { workflow }
5654
+ };
5655
+ }
5656
+ var Serving = class {
5657
+ constructor(report, settings, tools) {
5658
+ this.report = report;
5659
+ this.settings = settings;
5660
+ this.unreadTools = tools;
5661
+ if (report !== void 0 && Array.isArray(tools)) {
5662
+ try {
5663
+ this.remember(/* @__PURE__ */ new Map(), knownTools(tools).names);
5664
+ } catch {
5665
+ }
5666
+ }
5667
+ }
5668
+ report;
5669
+ settings;
5670
+ serverMeta = { serverInfo: null, capabilities: null, instructions: null };
5671
+ dispositions = /* @__PURE__ */ new Map();
5672
+ vendorHasReportName = false;
5673
+ warnedUnlisted = false;
5674
+ unreadTools;
5675
+ /** Learn the vendor's `tools` once per process. Never throws: without them,
5676
+ * a call to a tool not yet listed is served as on a cold process. */
5677
+ readVendorTools() {
5678
+ const source = this.unreadTools;
5679
+ if (source === void 0) return;
5680
+ this.unreadTools = void 0;
5681
+ try {
5682
+ const tools = typeof source === "function" ? source() : source;
5683
+ if (isThenable(tools)) {
5684
+ throw new Error("tools must be an array or a plain function, not async");
5685
+ }
5686
+ if (!Array.isArray(tools)) throw new Error("tools gave something that is not an array");
5687
+ const known = knownTools(tools);
5688
+ this.remember(known.dispositions, known.names);
5689
+ } catch (err) {
5690
+ stderrLine(
5691
+ `baton: could not read the tools option; a call this process has not seen listed loses user_goal: ${printable(err)}`
5692
+ );
5693
+ }
5694
+ }
5695
+ remember(dispositions, names) {
5696
+ const fresh = [...dispositions.keys()].filter((name2) => !this.dispositions.has(name2)).length;
5697
+ if (this.dispositions.size + fresh > REMEMBERED_TOOLS) this.dispositions.clear();
5698
+ for (const [name2, disposition] of dispositions) {
5699
+ if (!ownsUserGoal(this.dispositions.get(name2))) this.dispositions.set(name2, disposition);
5700
+ }
5701
+ const name = this.report?.tool.name;
5702
+ if (name !== void 0 && names.has(name) && !this.vendorHasReportName) {
5703
+ this.vendorHasReportName = true;
5704
+ stderrLine(
5705
+ `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.`
5706
+ );
5707
+ }
5708
+ }
5709
+ /** The report tool, unless a vendor tool has its name. */
5710
+ ours() {
5711
+ return this.vendorHasReportName ? void 0 : this.report;
5712
+ }
5713
+ document() {
5714
+ return this.settings?.document ?? null;
5715
+ }
5716
+ initialized(answer) {
5717
+ const result = resultOf(answer);
5718
+ if (result === null) return answer;
5719
+ const vendor = result.instructions;
5720
+ this.readVendorTools();
5721
+ this.serverMeta = {
5722
+ serverInfo: isRecord(result.serverInfo) ? result.serverInfo : null,
5723
+ capabilities: isRecord(result.capabilities) ? result.capabilities : null,
5724
+ instructions: typeof vendor === "string" ? vendor : null
5725
+ };
5726
+ const nativeGoal = [...this.dispositions.values()].some((d) => d[USER_GOAL_PARAM_NAME] === "native");
5727
+ const report = this.ours();
5728
+ const document = this.document();
5729
+ const pointer = report === void 0 ? void 0 : buildReportPointer({ vendorDisplayName: report.vendorDisplayName, annotationToolName: report.tool.name });
5730
+ const shown = pointer !== void 0 && (document === null || document.reportsOnForAnyone);
5731
+ const { ours } = batonParagraphs(shown ? pointer : void 0, document?.serverOverlay, !nativeGoal);
5732
+ return { ...answer, result: { ...result, instructions: joined(vendor, ours) } };
5733
+ }
5734
+ listed(request, answer, settings) {
5735
+ const result = resultOf(answer);
5736
+ const tools = result?.tools;
5737
+ if (result === null || !Array.isArray(tools)) return null;
5738
+ this.readVendorTools();
5739
+ const { served, surface } = serveTools(tools, this.serverMeta);
5740
+ const known = knownTools(tools);
5741
+ this.remember(known.dispositions, known.names);
5742
+ const report = this.ours();
5743
+ const firstPage = request.params.cursor === void 0 || request.params.cursor === null;
5744
+ const out = [...served];
5745
+ if (report !== void 0 && firstPage) {
5746
+ const { name, description, inputSchema: inputSchema2 } = report.tool;
5747
+ out.push({ name, description, inputSchema: inputSchema2 });
5748
+ }
5749
+ const overlay = this.document()?.serverOverlay;
5750
+ const overlayId = overlay?.id ?? null;
5751
+ const listed = toolsForCaller({ ...result, tools: out }, settings, {
5752
+ intentParamMode: DEFAULT_INTENT_PARAM_MODE,
5753
+ annotationToolName: report?.tool.name ?? "",
5754
+ injectsGoal: (name) => known.dispositions.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
5755
+ });
5756
+ const whole = firstPage && (result.nextCursor === void 0 || result.nextCursor === null) ? surface : null;
5757
+ return {
5758
+ answer: { ...answer, result: listed },
5759
+ surface: whole,
5760
+ seam: () => {
5761
+ const agentText = servedAgentText({
5762
+ reportNames: report === void 0 ? void 0 : { vendorDisplayName: report.vendorDisplayName, annotationToolName: report.tool.name },
5763
+ intentParamMode: DEFAULT_INTENT_PARAM_MODE,
5764
+ ...goalTextsServed(whole?.surface.tools ?? []),
5765
+ serverOverlay: overlay
5766
+ });
5767
+ const seam = buildSeamAugmentations({
5768
+ injectedToolNames: report === void 0 ? [] : [report.tool.name],
5769
+ intentParamNames: [USER_GOAL_PARAM_NAME],
5770
+ intentParamMode: DEFAULT_INTENT_PARAM_MODE,
5771
+ requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),
5772
+ instructionsSuffix: instructionsSuffix(agentText),
5773
+ agentText
5774
+ });
5775
+ if (this.settings !== void 0) seam.server_overlay = overlayId;
5776
+ return seam;
5777
+ },
5778
+ serverOverlay: overlayId
5779
+ };
5780
+ }
5781
+ /** The plan for one `tools/call`; `null` sends it to dispatch untraced. */
5782
+ call(request, message, settings) {
5783
+ const { name } = request.params;
5784
+ const args = request.params.arguments === void 0 ? {} : request.params.arguments;
5785
+ if (typeof name !== "string" || !isRecord(args)) return null;
5786
+ this.readVendorTools();
5787
+ const dispositions = this.dispositions.get(name);
5788
+ const report = this.ours();
5789
+ if (report !== void 0 && name === report.tool.name) return reportCall(report.tool, name, args, message, settings);
5790
+ if (dispositions === void 0 && USER_GOAL_PARAM_NAME in args && !this.warnedUnlisted) {
5791
+ this.warnedUnlisted = true;
5792
+ stderrLine(
5793
+ `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`
5794
+ );
5795
+ }
5796
+ const stripped = { ...args };
5797
+ const goals = popGoals(stripped, dispositions);
5798
+ if (settings?.overlay?.hiddenTools.has(name)) return hidden(name, stripped, goals, message);
5799
+ const forwarded = Object.keys(stripped).length === Object.keys(args).length ? message : { ...message, params: { ...request.params, arguments: stripped } };
5800
+ return { name, arguments: stripped, goals, message: forwarded, kind: "forward" };
5801
+ }
5802
+ };
5803
+ function reportCall(tool, name, args, message, settings) {
5804
+ if (settings?.reportMode === "off") return hidden(name, { ...args }, NO_GOALS, message);
5805
+ const report = tool.annotateArgs(args);
5806
+ const body = report === null ? { ok: false, error: buildRefusalText({ annotationToolName: name, overlay: settings?.overlay }) } : { ok: true };
5807
+ return {
5808
+ name,
5809
+ arguments: { ...args },
5810
+ goals: NO_GOALS,
5811
+ message,
5812
+ kind: report === null ? "refused" : "report",
5813
+ answer: answerTo(message, { content: [{ type: "text", text: JSON.stringify(body) }], structuredContent: body }),
5814
+ ...report === null ? {} : { report }
5815
+ };
5816
+ }
5817
+ function hidden(name, args, goals, message) {
5818
+ const result = { content: [{ type: "text", text: unknownToolText(name) }], isError: true };
5819
+ return { name, arguments: args, goals, message, kind: "hidden", answer: answerTo(message, result) };
5820
+ }
5821
+ function withoutUserGoal(message) {
5822
+ try {
5823
+ const params = message.params;
5824
+ const args = params.arguments;
5825
+ if (!isRecord(args) || !(USER_GOAL_PARAM_NAME in args)) return message;
5826
+ const stripped = Object.fromEntries(Object.entries(args).filter(([key]) => key !== USER_GOAL_PARAM_NAME));
5827
+ return { ...message, params: { ...params, arguments: stripped } };
5828
+ } catch {
5829
+ return message;
5830
+ }
5831
+ }
5832
+ function jsonRpcError(answer) {
5833
+ return isRecord(answer) && isRecord(answer.error) ? answer.error : null;
5834
+ }
5835
+ function resultOf(answer) {
5836
+ return isRecord(answer) && isRecord(answer.result) ? { ...answer.result } : null;
5837
+ }
5838
+ function isToolErrorResult(result) {
5839
+ return result !== null && Array.isArray(result.content) && result.isError === true;
5840
+ }
5841
+ function answerTo(message, result) {
5842
+ return { jsonrpc: message.jsonrpc ?? "2.0", id: message.id, result };
5843
+ }
5844
+ function instructionsSuffix(agentText) {
5845
+ const pieces = INSTRUCTION_PIECES.filter((piece) => piece in agentText).map((piece) => agentText[piece]);
5846
+ return pieces.includes(null) ? null : pieces.length > 0;
5847
+ }
5848
+
5849
+ // src/library/reportTool.ts
5850
+ function inputSchema() {
5851
+ const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
5852
+ delete schema.$schema;
5853
+ return { ...schema, required: [...schema.required, TOOL_NAME_PARAM_NAME] };
5854
+ }
5855
+ var nonEmptyText = (value) => typeof value === "string" && value !== "";
5856
+ var nonEmptyObject = (value) => isRecord(value) && Object.keys(value).length > 0;
5857
+ function annotateArgs(args) {
5858
+ const whatHappened = args.what_happened;
5859
+ if (!isReport(whatHappened)) return null;
5860
+ const options = { whatHappened };
5861
+ const toolName = args[TOOL_NAME_PARAM_NAME];
5862
+ if (typeof toolName === "string") options.toolName = toolName;
5863
+ const intent = args[USER_GOAL_PARAM_NAME];
5864
+ if (nonEmptyText(intent)) options.intent = intent;
5865
+ if (nonEmptyText(args.suggested_improvement)) {
5866
+ options.suggestedImprovement = args.suggested_improvement;
5867
+ }
5868
+ if (nonEmptyObject(args.context)) options.context = args.context;
5869
+ return options;
5870
+ }
5871
+ function reportTool(options) {
5872
+ const { vendorDisplayName } = options;
5873
+ if (isBlank(vendorDisplayName)) {
5874
+ throw new Error("vendorDisplayName is blank. Baton's report sentence names the server by it.");
5875
+ }
5876
+ const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);
5877
+ if (derived === void 0) {
5878
+ throw new Error(
5879
+ `vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, or one too long for Baton's report sentence. Pass name.`
5880
+ );
5881
+ }
5882
+ const name = validateAnnotationToolName(derived);
5883
+ if (!fitsBatonSentenceCap({ vendorDisplayName, annotationToolName: name })) {
5884
+ throw new Error(
5885
+ `vendorDisplayName and name ${JSON.stringify(name)} are too long together for Baton's report sentence. Shorten one of them.`
5886
+ );
5887
+ }
5888
+ return {
5889
+ name,
5890
+ description: buildAnnotationToolDescription({ vendorDisplayName }),
5891
+ inputSchema: inputSchema(),
5892
+ instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),
5893
+ refusal: buildRefusalText({ annotationToolName: name }),
5894
+ annotateArgs
5895
+ };
5896
+ }
5897
+
5518
5898
  // src/library/client.ts
5519
5899
  function fromEnv(name) {
5520
5900
  const value = typeof process !== "undefined" ? process.env?.[name] : void 0;
@@ -5538,6 +5918,7 @@ function resolveClientOptions(options) {
5538
5918
  if (options.scrubber !== void 0 && typeof options.scrubber !== "function") {
5539
5919
  throw new Error("Client scrubber must be a function.");
5540
5920
  }
5921
+ validateServeOptions(options);
5541
5922
  const dsnString = selectDsn(
5542
5923
  options.dsn,
5543
5924
  {
@@ -5547,15 +5928,25 @@ function resolveClientOptions(options) {
5547
5928
  },
5548
5929
  "Client"
5549
5930
  );
5931
+ if (options.settings === "console" && dsnString === void 0) {
5932
+ throw new Error(`Client settings: "console" reads the Capture page with the dsn's key, so it needs a dsn.`);
5933
+ }
5934
+ candidateNeedsConsole(options.settings);
5935
+ const reportOn = (options.reportMode ?? (options.settings === "console" ? "on" : "off")) === "on";
5550
5936
  const consentToken = resolveConsentToken(options.consentToken);
5551
5937
  if (dsnString !== void 0) {
5552
5938
  const dsn = parseDsn(dsnString);
5939
+ const consoleSettings = options.settings === "console" && !consoleDroppedOnWorkers(options.settings);
5553
5940
  return {
5554
5941
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
5555
5942
  vendorId: dsn.vendorId,
5556
5943
  tenantId: dsn.tenantId,
5557
5944
  consentToken,
5558
- resultCaptureMode
5945
+ resultCaptureMode,
5946
+ ...consoleSettings ? {
5947
+ captureSettings: consoleCaptureSettings(dsn, options.settingsRefreshMs)
5948
+ } : {},
5949
+ ...reportOn ? { report: serveReport(dsn.vendorId, options.vendorDisplayName) } : {}
5559
5950
  };
5560
5951
  }
5561
5952
  if (options.sink === void 0) {
@@ -5572,9 +5963,22 @@ function resolveClientOptions(options) {
5572
5963
  vendorId: vendorId2,
5573
5964
  tenantId: resolveTenantId(options.tenantId || void 0, vendorId2),
5574
5965
  consentToken,
5575
- resultCaptureMode
5966
+ resultCaptureMode,
5967
+ ...reportOn ? { report: serveReport(vendorId2, options.vendorDisplayName) } : {}
5576
5968
  };
5577
5969
  }
5970
+ function validateServeOptions(options) {
5971
+ validateSettings(options, "Client");
5972
+ validateReportMode(options, "Client");
5973
+ if (options.tools !== void 0 && !Array.isArray(options.tools) && typeof options.tools !== "function") {
5974
+ throw new Error("Client tools must be an array of tools or a function that returns one.");
5975
+ }
5976
+ }
5977
+ function serveReport(vendorId2, displayName) {
5978
+ const display = displayName === void 0 || isBlank(displayName) ? vendorId2 : displayName;
5979
+ const name = deriveAnnotationToolName(vendorId2, toolNameForDisplayName(display));
5980
+ return { tool: reportTool({ vendorDisplayName: display, name }), vendorDisplayName: display };
5981
+ }
5578
5982
  var hasText2 = (value) => typeof value === "string" && !isBlank(value);
5579
5983
  function describeError(err) {
5580
5984
  let type = "Error";
@@ -5606,6 +6010,7 @@ var Core = class {
5606
6010
  resultCaptureMode;
5607
6011
  scrubber;
5608
6012
  disabled;
6013
+ settings;
5609
6014
  constructor(resolved) {
5610
6015
  this.sink = offTheCall(resolved.sink);
5611
6016
  this.vendorId = resolved.vendorId;
@@ -5614,6 +6019,10 @@ var Core = class {
5614
6019
  this.resultCaptureMode = resolved.resultCaptureMode;
5615
6020
  this.scrubber = resolved.scrubber;
5616
6021
  this.disabled = resolved.disabled;
6022
+ this.settings = resolved.captureSettings;
6023
+ }
6024
+ modeFor(session) {
6025
+ return session.settings?.resultCaptureMode ?? this.resultCaptureMode;
5617
6026
  }
5618
6027
  /** The envelope members every event of `session` shares. Call inside a
5619
6028
  * build thunk, so `captured_at` is the build time. */
@@ -5627,6 +6036,9 @@ var Core = class {
5627
6036
  consent_token: consentToken
5628
6037
  };
5629
6038
  }
6039
+ errorBody(text) {
6040
+ return scrubbedErrorBody(this.scrubber, text);
6041
+ }
5630
6042
  /** False when nothing may be emitted: the off switch, or a closed client. */
5631
6043
  live() {
5632
6044
  if (this.disabled) return false;
@@ -5640,9 +6052,9 @@ var Core = class {
5640
6052
  }
5641
6053
  /** Sends `surface` unless this client already has. Never rejects. The
5642
6054
  * 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);
6055
+ sendSurface(surface, seam, serverOverlay = null) {
6056
+ if (this.sentSurfaces.wasSent(surface.digest, serverOverlay) || !this.live()) return Promise.resolve();
6057
+ this.sentSurfaces.mark(surface.digest, serverOverlay);
5646
6058
  let event;
5647
6059
  try {
5648
6060
  event = SurfaceSnapshotEventSchema.parse({
@@ -5653,7 +6065,7 @@ var Core = class {
5653
6065
  sequence_number: nextClockSequence(),
5654
6066
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
5655
6067
  consent_token: this.consentToken,
5656
- payload: snapshotPayload(surface)
6068
+ payload: snapshotPayload(surface, seam?.())
5657
6069
  });
5658
6070
  } catch (err) {
5659
6071
  PROCESS_DROPS.add("encode_failed");
@@ -5688,6 +6100,7 @@ var Core = class {
5688
6100
  var UNSET = /* @__PURE__ */ Symbol("unset");
5689
6101
  var WITHHELD_RESULT = /* @__PURE__ */ Symbol("withheld");
5690
6102
  var SCRUB_FAILED = /* @__PURE__ */ Symbol("scrubFailed");
6103
+ var observeFailure;
5691
6104
  var runTrace;
5692
6105
  var Trace = class _Trace {
5693
6106
  #core;
@@ -5698,6 +6111,7 @@ var Trace = class _Trace {
5698
6111
  #startedAt = 0;
5699
6112
  #result = UNSET;
5700
6113
  #error = null;
6114
+ #failure = null;
5701
6115
  #observedWarned = false;
5702
6116
  constructor(core, session, options) {
5703
6117
  this.#core = core;
@@ -5719,6 +6133,7 @@ var Trace = class _Trace {
5719
6133
  }
5720
6134
  this.#result = UNSET;
5721
6135
  this.#error = null;
6136
+ this.#failure = null;
5722
6137
  if (this.#core.disabled) return this;
5723
6138
  let errorType = failure?.errorType;
5724
6139
  let errorBody2 = failure?.errorBody;
@@ -5729,7 +6144,7 @@ var Trace = class _Trace {
5729
6144
  }
5730
6145
  if (errorType !== void 0 || errorBody2 !== void 0) {
5731
6146
  this.#error = { type: errorType || "Error", body: errorBody2 ?? "" };
5732
- } else if (this.#core.resultCaptureMode === WITHHELD) {
6147
+ } else if (this.#core.modeFor(this.#session) === WITHHELD) {
5733
6148
  this.#result = WITHHELD_RESULT;
5734
6149
  } else {
5735
6150
  try {
@@ -5805,23 +6220,40 @@ var Trace = class _Trace {
5805
6220
  #fail(err) {
5806
6221
  const durationMs = this.#durationMs();
5807
6222
  if (!this.#core.live()) return;
5808
- this.#emitError(nextClockSequence(), ...describeError(err), durationMs);
6223
+ const [type, body] = describeError(err);
6224
+ if (this.#core.modeFor(this.#session) === WITHHELD) {
6225
+ this.#failure = { result: null, result_capture: WITHHELD };
6226
+ this.#emitError(nextClockSequence(), type, "", durationMs);
6227
+ return;
6228
+ }
6229
+ this.#emitError(nextClockSequence(), type, body, durationMs);
5809
6230
  }
5810
6231
  #emitError(sequence, type, body, durationMs) {
6232
+ const failure = this.#failure;
5811
6233
  void this.#core.emit(
5812
6234
  () => ToolCallErrorEventSchema.parse({
5813
6235
  ...this.#envelope(sequence),
5814
6236
  payload: {
5815
6237
  tool_name: this.#options.toolName,
5816
6238
  error_type: type,
5817
- error_body: scrubbedErrorBody(this.#core.scrubber, body),
6239
+ error_body: failure === null ? scrubbedErrorBody(this.#core.scrubber, body) : body,
5818
6240
  duration_ms: durationMs,
5819
- result: null
6241
+ result: null,
6242
+ ...failure
5820
6243
  }
5821
6244
  })
5822
6245
  );
5823
6246
  }
5824
6247
  static {
6248
+ observeFailure = (trace, errorType, fields, failureKind) => {
6249
+ trace.#result = UNSET;
6250
+ trace.#error = { type: errorType, body: fields.error_body };
6251
+ trace.#failure = {
6252
+ result: fields.result,
6253
+ ...fields.result_capture === void 0 ? {} : { result_capture: fields.result_capture },
6254
+ ...failureKind === void 0 ? {} : { failure_kind: failureKind }
6255
+ };
6256
+ };
5825
6257
  runTrace = (core, session, options, fn) => {
5826
6258
  const trace = new _Trace(core, session, options);
5827
6259
  trace.#start();
@@ -5849,8 +6281,40 @@ var Trace = class _Trace {
5849
6281
  };
5850
6282
  }
5851
6283
  };
6284
+ var Mark = class {
6285
+ constructor(owner, flags) {
6286
+ this.owner = owner;
6287
+ this.flags = flags;
6288
+ }
6289
+ owner;
6290
+ flags;
6291
+ active = true;
6292
+ };
6293
+ var inDispatch = new asyncHooks3.AsyncLocalStorage();
6294
+ async function dispatched(dispatch, message, mark = null) {
6295
+ try {
6296
+ return await inDispatch.run(mark, () => dispatch(message));
6297
+ } finally {
6298
+ if (mark !== null) mark.active = false;
6299
+ }
6300
+ }
6301
+ function messageText(message) {
6302
+ if (typeof message === "string") return message;
6303
+ return message === void 0 ? "" : JSON.stringify(message) ?? "";
6304
+ }
6305
+ function fieldsOrEmpty(build) {
6306
+ try {
6307
+ return build();
6308
+ } catch (err) {
6309
+ stderrLine(`baton: the scrubber threw on an error answer; its text is dropped: ${printable(err)}`);
6310
+ return { error_body: "", result: null };
6311
+ }
6312
+ }
6313
+ var stopWhenDropped = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((s) => s.stop()) : void 0;
5852
6314
  var Client = class {
5853
6315
  #core;
6316
+ #serving;
6317
+ #doubleWiringLogged = /* @__PURE__ */ new Set();
5854
6318
  #closing;
5855
6319
  constructor(options = {}) {
5856
6320
  const switchName = captureDisabled();
@@ -5872,6 +6336,11 @@ var Client = class {
5872
6336
  scrubber: options.scrubber ?? new Scrubber().scrub,
5873
6337
  disabled: switchName !== null
5874
6338
  });
6339
+ this.#serving = new Serving(resolved.report, resolved.captureSettings, switchName === null ? options.tools : void 0);
6340
+ if (resolved.captureSettings !== void 0) {
6341
+ resolved.captureSettings.start();
6342
+ stopWhenDropped?.register(this, resolved.captureSettings);
6343
+ }
5875
6344
  }
5876
6345
  /** Run `fn` with one session, principal, client and turn for every
5877
6346
  * `trace()` and `annotate()` inside it, including after its awaits. Open
@@ -5892,7 +6361,8 @@ var Client = class {
5892
6361
  * called exactly once, so a lazy query builder is not run twice. A throw or
5893
6362
  * rejection is recorded and passed on unchanged. */
5894
6363
  trace(options, fn) {
5895
- return runTrace(this.#core, sessionForCall(this), options ?? {}, fn);
6364
+ this.#flagDoubleWiring("trace");
6365
+ return runTrace(this.#core, sessionForCall(this, this.#core.settings), options ?? {}, fn);
5896
6366
  }
5897
6367
  /** `fn`, traced on every call. A single plain-object argument is sent as
5898
6368
  * `params`, as an MCP tool's arguments are; other arguments as
@@ -5908,7 +6378,11 @@ var Client = class {
5908
6378
  * own outside one. To report on a traced call, use `trace.annotate()`. */
5909
6379
  annotate(options) {
5910
6380
  const given = options ?? {};
5911
- return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);
6381
+ return this.#core.annotate(
6382
+ sessionForCall(this, this.#core.settings),
6383
+ given.consentToken || this.#core.consentToken,
6384
+ given
6385
+ );
5912
6386
  }
5913
6387
  /** `tools`, the vendor's own `tools/list` entries, with `user_goal` added
5914
6388
  * to each `inputSchema` as `withBaton` adds it, and a `surface_snapshot`
@@ -5921,11 +6395,176 @@ var Client = class {
5921
6395
  * tool list: one it cannot read is returned as it came. Does not wait for
5922
6396
  * the snapshot to be sent; `flush()` does. */
5923
6397
  async listTools(tools, options = {}) {
6398
+ this.#flagDoubleWiring("listTools");
5924
6399
  if (this.#core.disabled) return tools;
5925
6400
  const { served, surface } = serveTools(tools, options);
5926
6401
  if (surface !== null) void this.#core.sendSurface(surface);
5927
6402
  return served;
5928
6403
  }
6404
+ /** Answer one MCP JSON-RPC `message` with `dispatch`, the vendor's own
6405
+ * function from message to answer, and Baton around it (SPEC §5.6).
6406
+ * Experimental.
6407
+ *
6408
+ * `initialize` gets Baton's instructions. `tools/list` gets `user_goal` and
6409
+ * the report tool, under the caller's Console settings, and sends the
6410
+ * snapshot. `tools/call` is traced, with `user_goal` removed before
6411
+ * `dispatch` sees it; Baton answers the report tool and a tool the caller's
6412
+ * overlay hides itself. Anything else goes to `dispatch` as it came.
6413
+ *
6414
+ * `options` are as on `session()`. A process learns the vendor's tools from
6415
+ * the lists it serves. Until it has, a call loses `user_goal` and the report
6416
+ * tool's name is Baton's; pass the `tools` option when a tool declares its
6417
+ * own `user_goal` or has the report tool's name. `dispatch` is called at
6418
+ * most once, and what it returns or throws comes back unchanged apart from
6419
+ * Baton's additions. A failure in Baton's own work is logged, never thrown. */
6420
+ serve(message, dispatch, options = {}) {
6421
+ return inDispatch.run(null, () => this.#serve(message, dispatch, options ?? {}));
6422
+ }
6423
+ async #serve(message, dispatch, options) {
6424
+ const request = this.#request(message);
6425
+ if (request === null) return dispatched(dispatch, message);
6426
+ const settings = this.#core.settings;
6427
+ if (settings !== void 0 && !settings.isReady) await settings.ready;
6428
+ const handle = () => this.#handle(request, message, dispatch);
6429
+ const { principal, headers, sessionId } = options;
6430
+ if (inBlock(this) && principal === void 0 && headers === void 0 && sessionId === void 0) return handle();
6431
+ const values = {
6432
+ ...principal === void 0 ? {} : { principal },
6433
+ ...headers === void 0 ? {} : { headers },
6434
+ ...sessionId === void 0 ? {} : { sessionId }
6435
+ };
6436
+ try {
6437
+ if (isRecord(request.params._meta)) values.meta = request.params._meta;
6438
+ if (request.method === "initialize" && isRecord(request.params.clientInfo)) {
6439
+ values.clientInfo = request.params.clientInfo;
6440
+ }
6441
+ } catch {
6442
+ }
6443
+ return this.session(values, handle);
6444
+ }
6445
+ async #handle(request, message, dispatch) {
6446
+ let session;
6447
+ let call = null;
6448
+ try {
6449
+ session = sessionForCall(this, this.#core.settings);
6450
+ if (request.method === TOOL_CALL) call = this.#serving.call(request, message, session.settings);
6451
+ } catch (err) {
6452
+ stderrLine(`baton: serve() could not read the request; it is served as it came: ${printable(err)}`);
6453
+ return dispatched(dispatch, withoutUserGoal(message));
6454
+ }
6455
+ if (request.method !== TOOL_CALL) {
6456
+ const mark = request.method === TOOL_LIST ? new Mark(this, "listTools") : null;
6457
+ return this.#shaped(request, await dispatched(dispatch, message, mark), session);
6458
+ }
6459
+ if (call === null) return dispatched(dispatch, message);
6460
+ if (call.answer !== void 0) {
6461
+ this.#answerOurselves(call, session);
6462
+ return call.answer;
6463
+ }
6464
+ return this.#traced(call, dispatch, session);
6465
+ }
6466
+ #request(message) {
6467
+ if (this.#core.disabled) return null;
6468
+ try {
6469
+ return readRequest(message);
6470
+ } catch (err) {
6471
+ stderrLine(`baton: serve() could not read the request; it is served as it came: ${printable(err)}`);
6472
+ return null;
6473
+ }
6474
+ }
6475
+ /** Dispatch's `initialize` or `tools/list` answer with Baton's additions,
6476
+ * and its snapshot sent; the answer unchanged on failure. */
6477
+ #shaped(request, answer, session) {
6478
+ try {
6479
+ if (request.method !== TOOL_LIST) return this.#serving.initialized(answer);
6480
+ const listed = this.#serving.listed(request, answer, session.settings);
6481
+ if (listed === null) return answer;
6482
+ if (listed.surface !== null) void this.#core.sendSurface(listed.surface, listed.seam, listed.serverOverlay);
6483
+ return listed.answer;
6484
+ } catch (err) {
6485
+ stderrLine(`baton: serve() could not add to the answer; it is served as it came: ${printable(err)}`);
6486
+ return answer;
6487
+ }
6488
+ }
6489
+ async #traced(call, dispatch, session) {
6490
+ let dispatching = false;
6491
+ try {
6492
+ return await runTrace(this.#core, session, traceOptions(call), async (trace) => {
6493
+ dispatching = true;
6494
+ const answer = await dispatched(dispatch, call.message, new Mark(this, "trace"));
6495
+ this.#record(trace, answer, session);
6496
+ return answer;
6497
+ });
6498
+ } catch (err) {
6499
+ if (dispatching) throw err;
6500
+ stderrLine(`baton: serve() could not trace the call: ${printable(err)}`);
6501
+ return dispatched(dispatch, call.message, new Mark(this, "trace"));
6502
+ }
6503
+ }
6504
+ #record(trace, answer, session) {
6505
+ const mode = this.#core.modeFor(session);
6506
+ const scrubber = this.#core.scrubber;
6507
+ const errorBody2 = (text) => this.#core.errorBody(text);
6508
+ try {
6509
+ const error = jsonRpcError(answer);
6510
+ if (error !== null) {
6511
+ observeFailure(
6512
+ trace,
6513
+ JSONRPC_ERROR_TYPE,
6514
+ fieldsOrEmpty(
6515
+ () => resultDerivedFields(mode, () => messageText(error.message), { ...error }, errorBody2, scrubber)
6516
+ )
6517
+ );
6518
+ return;
6519
+ }
6520
+ const result = resultOf(answer);
6521
+ if (isToolErrorResult(result)) {
6522
+ observeFailure(
6523
+ trace,
6524
+ TOOL_ERROR_TYPE,
6525
+ fieldsOrEmpty(() => returnedErrorFields(mode, result, errorBody2, scrubber))
6526
+ );
6527
+ return;
6528
+ }
6529
+ trace.observed(result ?? answer);
6530
+ } catch (err) {
6531
+ stderrLine(`baton: serve() could not record the tool call: ${printable(err)}`);
6532
+ try {
6533
+ trace.observed(void 0);
6534
+ } catch {
6535
+ }
6536
+ }
6537
+ }
6538
+ #answerOurselves(call, session) {
6539
+ try {
6540
+ if (call.report !== void 0) {
6541
+ void this.#core.annotate(session, this.#core.consentToken, call.report);
6542
+ } else if (call.kind === "hidden") {
6543
+ const scrubber = this.#core.scrubber;
6544
+ const fields = fieldsOrEmpty(
6545
+ () => returnedErrorFields("full", call.answer.result, (text) => this.#core.errorBody(text), scrubber)
6546
+ );
6547
+ runTrace(
6548
+ this.#core,
6549
+ session,
6550
+ traceOptions(call),
6551
+ (trace) => observeFailure(trace, TOOL_ERROR_TYPE, fields, "tool_hidden")
6552
+ );
6553
+ }
6554
+ } catch (err) {
6555
+ stderrLine(`baton: serve() could not record its own answer: ${printable(err)}`);
6556
+ }
6557
+ }
6558
+ /** An error, once per client and call, when the vendor's code inside
6559
+ * `serve()` still calls what `serve()` now does: the old wiring was left in. */
6560
+ #flagDoubleWiring(call) {
6561
+ const mark = inDispatch.getStore();
6562
+ if (!mark?.active || mark.owner !== this || mark.flags !== call || this.#doubleWiringLogged.has(call)) return;
6563
+ this.#doubleWiringLogged.add(call);
6564
+ stderrLine(
6565
+ `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.`
6566
+ );
6567
+ }
5929
6568
  /** Wait for events so far to reach the sink, then flush it. Never rejects;
5930
6569
  * returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
5931
6570
  async flush() {
@@ -5933,61 +6572,13 @@ var Client = class {
5933
6572
  }
5934
6573
  /** Flush, then close the sink. Later events are dropped. */
5935
6574
  aclose() {
6575
+ this.#core.settings?.stop();
5936
6576
  this.#closing ??= boundedSinkCall(this.#core.sink, "aclose").then(() => {
5937
6577
  this.#core.closed = true;
5938
6578
  });
5939
6579
  return this.#closing;
5940
6580
  }
5941
6581
  };
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
6582
  export {
5992
6583
  BatonHandle,
5993
6584
  Client,