@goodtiming/baton-sdk 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -53,7 +53,7 @@ __export(index_exports, {
53
53
  module.exports = __toCommonJS(index_exports);
54
54
 
55
55
  // src/version.ts
56
- var SDK_VERSION = "ts-1.0.0";
56
+ var SDK_VERSION = "ts-1.1.0";
57
57
 
58
58
  // src/events.ts
59
59
  var import_zod = require("zod");
@@ -438,9 +438,17 @@ var EventSchema = import_zod.z.discriminatedUnion("event_type", [
438
438
  ToolListErrorEventSchema
439
439
  ]);
440
440
 
441
+ // src/runtime.ts
442
+ function onWorkers() {
443
+ return typeof globalThis.WebSocketPair === "function" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
444
+ }
445
+ var globalFetch = (input, init) => fetch(input, init);
446
+
441
447
  // src/warn.ts
442
448
  function warn(message) {
443
- if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
449
+ if (onWorkers()) {
450
+ console.warn(message);
451
+ } else if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
444
452
  process.emitWarning(message);
445
453
  }
446
454
  }
@@ -623,7 +631,8 @@ var SHUTDOWN_FLUSH_TIMEOUT_MS = 3e3;
623
631
  // src/drops.ts
624
632
  var RECOVERY_LOG_MS = 6e4;
625
633
  var DropCounts = class {
626
- #instanceId = uuid7();
634
+ // Made on first use: a Worker refuses random values while its modules load.
635
+ #instanceId;
627
636
  #total = /* @__PURE__ */ new Map();
628
637
  #sinceDelivery = /* @__PURE__ */ new Map();
629
638
  #lastRecoveryLog = -RECOVERY_LOG_MS;
@@ -647,13 +656,13 @@ var DropCounts = class {
647
656
  const total = lost.reduce((sum2, [, n]) => sum2 + n, 0);
648
657
  warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(", ")}.`);
649
658
  }
650
- /** For tests: the counts are one per process. */
651
659
  /** Names this process in its loss reports (SPEC §11.4.7). */
652
660
  get instanceId() {
653
- return this.#instanceId;
661
+ return this.#instanceId ??= uuid7();
654
662
  }
663
+ /** For tests: the counts are one per process. */
655
664
  clear() {
656
- this.#instanceId = uuid7();
665
+ this.#instanceId = void 0;
657
666
  this.#total.clear();
658
667
  this.#sinceDelivery.clear();
659
668
  this.#lastRecoveryLog = -RECOVERY_LOG_MS;
@@ -1093,8 +1102,12 @@ var HttpSink = class _HttpSink {
1093
1102
  /** Whether the queued pass sends everything waiting, not only what is due. */
1094
1103
  forceNext = false;
1095
1104
  flushTimer = null;
1096
- /** Set by a failed batch: only the timer, a flush or a close tries again. */
1105
+ /** Set by a failed batch: only the timer, a flush, a close or, at
1106
+ * `flushIntervalMs` 0, a write after `retryFrom` tries again. */
1097
1107
  waitForTimer = false;
1108
+ /** When a failed batch may be tried again. At `flushIntervalMs` 0 the
1109
+ * first write from then retries, as a Worker may drop the timer. */
1110
+ retryFrom = 0;
1098
1111
  /** Nothing is sent before this `Date.now()`, from a 429's `Retry-After`. */
1099
1112
  retryAt = 0;
1100
1113
  /** Set for the life of the sink by a 404 or 405 on the batch path. */
@@ -1120,7 +1133,7 @@ var HttpSink = class _HttpSink {
1120
1133
  "shutdownFlushTimeoutMs",
1121
1134
  SHUTDOWN_FLUSH_TIMEOUT_MS
1122
1135
  );
1123
- this.flushIntervalMs = timerMsOption(options.flushIntervalMs, "flushIntervalMs", FLUSH_INTERVAL_MS);
1136
+ this.flushIntervalMs = timerMsOption(options.flushIntervalMs, "flushIntervalMs", onWorkers() ? 0 : FLUSH_INTERVAL_MS);
1124
1137
  this.maxRetries = options.maxRetries ?? 3;
1125
1138
  this.backoffBaseMs = options.backoffBaseMs ?? 100;
1126
1139
  this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
@@ -1128,7 +1141,7 @@ var HttpSink = class _HttpSink {
1128
1141
  options.circuitBreakerThreshold ?? 5,
1129
1142
  options.circuitBreakerResetMs ?? 3e4
1130
1143
  );
1131
- this.fetchImpl = options.fetchImpl ?? fetch;
1144
+ this.fetchImpl = options.fetchImpl ?? globalFetch;
1132
1145
  }
1133
1146
  /**
1134
1147
  * What this sink shows when something prints it — never the bearer.
@@ -1166,8 +1179,9 @@ var HttpSink = class _HttpSink {
1166
1179
  }
1167
1180
  this.enqueue({ event, json, bytes, writtenAt: Date.now() });
1168
1181
  this.unsentWarned = false;
1169
- if (this.batchIsFull() && !this.waitForTimer) void this.scheduleDrain(false);
1170
- else this.armTimer(this.buffer[0].writtenAt + this.flushIntervalMs - Date.now());
1182
+ const held = this.waitForTimer && !(this.flushIntervalMs === 0 && Date.now() >= this.retryFrom);
1183
+ if (!held && (this.flushIntervalMs === 0 || this.batchIsFull())) void this.scheduleDrain(false);
1184
+ else this.armTimer(Math.max(this.buffer[0].writtenAt + this.flushIntervalMs, held ? this.retryFrom : 0) - Date.now());
1171
1185
  this.ensureExitHooksRegistered();
1172
1186
  }
1173
1187
  flush() {
@@ -1419,8 +1433,9 @@ var HttpSink = class _HttpSink {
1419
1433
  this.waitForTimer = failed;
1420
1434
  this.clearTimer();
1421
1435
  if (failed) {
1422
- const waits = [this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest()];
1423
- if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(Math.max(...waits));
1436
+ const wait = Math.max(this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest());
1437
+ this.retryFrom = Date.now() + wait;
1438
+ if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(wait);
1424
1439
  return;
1425
1440
  }
1426
1441
  const next = Math.min(this.buffer[0]?.writtenAt ?? Infinity, this.reportRidesHead() ? this.reportSetAt : Infinity);
@@ -1697,7 +1712,7 @@ var HttpSink = class _HttpSink {
1697
1712
  var import_node_async_hooks = require("async_hooks");
1698
1713
 
1699
1714
  // src/integrations/mcp/annotation.ts
1700
- var import_zod2 = require("zod");
1715
+ var import_zod3 = require("zod");
1701
1716
 
1702
1717
  // src/metaCoordinates.ts
1703
1718
  var COORD_FIELD_NAMES = /* @__PURE__ */ new Set(["latitude", "longitude"]);
@@ -1796,6 +1811,23 @@ function declaresParam(schema, name) {
1796
1811
  const props = schema?.properties;
1797
1812
  return typeof props === "object" && props !== null && name in props;
1798
1813
  }
1814
+ var NOT_ACCEPTED = /* @__PURE__ */ new Set(["not", "const", "enum", "default", "examples"]);
1815
+ var NAMED_SCHEMAS = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
1816
+ function mayDeclareParam(schema, name) {
1817
+ const seen = /* @__PURE__ */ new Set();
1818
+ const walk2 = (node) => {
1819
+ if (typeof node !== "object" || node === null || seen.has(node)) return false;
1820
+ seen.add(node);
1821
+ const { required, $ref } = node;
1822
+ if (declaresParam(node, name) || Array.isArray(required) && required.includes(name)) return true;
1823
+ if (typeof $ref === "string" && !$ref.startsWith("#")) return true;
1824
+ return Object.entries(node).some(([key, child]) => {
1825
+ if (NAMED_SCHEMAS.has(key) && typeof child === "object" && child !== null) return Object.values(child).some(walk2);
1826
+ return !NOT_ACCEPTED.has(key) && walk2(child);
1827
+ });
1828
+ };
1829
+ return walk2(schema);
1830
+ }
1799
1831
  function instructionsSuffixServed(annotationToolName, served) {
1800
1832
  if (annotationToolName) return true;
1801
1833
  return typeof served === "string" && served.includes(INTENT_INSTRUCTIONS);
@@ -2179,11 +2211,10 @@ async function resolveCaller(hook, call, settings, client = null) {
2179
2211
  const caller = await resolveIdentity(hook, call);
2180
2212
  if (settings === void 0) return caller;
2181
2213
  try {
2182
- const identity = caller.principal ?? caller.organization;
2183
2214
  const callSettings = settings.forCaller({
2184
2215
  labels: caller.labels,
2185
2216
  clientName: client?.info?.name ?? null,
2186
- shareKey: identity?.id ?? null
2217
+ shareKey: caller.principal?.id ?? null
2187
2218
  });
2188
2219
  return callSettings === void 0 ? caller : { ...caller, settings: callSettings };
2189
2220
  } catch {
@@ -2205,6 +2236,176 @@ async function resolveIdentity(hook, call) {
2205
2236
  }
2206
2237
  }
2207
2238
 
2239
+ // src/integrations/mcp/zodCompat.ts
2240
+ var z3rt = __toESM(require("zod/v3"), 1);
2241
+ var z4mini = __toESM(require("zod/v4-mini"), 1);
2242
+ var import_zod_to_json_schema = require("zod-to-json-schema");
2243
+ function isZ4Schema(s) {
2244
+ const schema = s;
2245
+ return !!schema?._zod;
2246
+ }
2247
+ function objectFromShape(shape) {
2248
+ const values = Object.values(shape);
2249
+ if (values.length === 0) return z4mini.object({});
2250
+ const allV4 = values.every(isZ4Schema);
2251
+ const allV3 = values.every((s) => !isZ4Schema(s));
2252
+ if (allV4) return z4mini.object(shape);
2253
+ if (allV3) return z3rt.object(shape);
2254
+ throw new Error("Mixed Zod versions detected in object shape.");
2255
+ }
2256
+ function getObjectShape(schema) {
2257
+ if (!schema) return void 0;
2258
+ let rawShape;
2259
+ if (isZ4Schema(schema)) {
2260
+ rawShape = schema._zod?.def?.shape;
2261
+ } else {
2262
+ rawShape = schema.shape;
2263
+ }
2264
+ if (!rawShape) return void 0;
2265
+ if (typeof rawShape === "function") {
2266
+ try {
2267
+ return rawShape();
2268
+ } catch {
2269
+ return void 0;
2270
+ }
2271
+ }
2272
+ return rawShape;
2273
+ }
2274
+ function normalizeObjectSchema(schema) {
2275
+ if (!schema) return void 0;
2276
+ if (typeof schema === "object") {
2277
+ const asAny = schema;
2278
+ if (!asAny._def && !asAny._zod) {
2279
+ const values = Object.values(schema);
2280
+ if (values.length > 0 && values.every(
2281
+ (v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function")
2282
+ )) {
2283
+ return objectFromShape(schema);
2284
+ }
2285
+ }
2286
+ }
2287
+ if (isZ4Schema(schema)) {
2288
+ const def = schema._zod?.def;
2289
+ if (def && (def.type === "object" || def.shape !== void 0)) return schema;
2290
+ } else {
2291
+ if (schema.shape !== void 0) return schema;
2292
+ }
2293
+ return void 0;
2294
+ }
2295
+ function mapMiniTarget(t) {
2296
+ if (!t) return "draft-7";
2297
+ if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
2298
+ if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
2299
+ return "draft-7";
2300
+ }
2301
+ function toJsonSchemaCompat(schema, opts) {
2302
+ if (isZ4Schema(schema)) {
2303
+ return z4mini.toJSONSchema(schema, {
2304
+ target: mapMiniTarget(opts?.target),
2305
+ io: opts?.pipeStrategy ?? "input"
2306
+ });
2307
+ }
2308
+ return (0, import_zod_to_json_schema.zodToJsonSchema)(schema, {
2309
+ strictUnions: opts?.strictUnions ?? true,
2310
+ pipeStrategy: opts?.pipeStrategy ?? "input"
2311
+ });
2312
+ }
2313
+
2314
+ // src/integrations/mcp/schemaCompat.ts
2315
+ var import_zod2 = require("zod");
2316
+ var import_v3 = require("zod/v3");
2317
+ var DEFAULT_INTENT_PARAM_MODE = "required";
2318
+ var ROOT_COMBINERS = ["$ref", "oneOf", "anyOf", "allOf"];
2319
+ function takesUserGoalJson(schema) {
2320
+ const properties = schema.properties ?? {};
2321
+ return isRecord(properties) && !ROOT_COMBINERS.some((key) => key in schema);
2322
+ }
2323
+ function withUserGoalJson(schema, intentParamMode, listRequired) {
2324
+ if (!takesUserGoalJson(schema) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return schema;
2325
+ const properties = schema.properties ?? {};
2326
+ const goal = { type: "string", description: buildUserGoalParamDescription({ intentParamMode }) };
2327
+ const served = { ...schema, properties: { ...properties, [USER_GOAL_PARAM_NAME]: goal } };
2328
+ const required = Array.isArray(schema.required) ? schema.required : [];
2329
+ if (listRequired && !required.includes(USER_GOAL_PARAM_NAME)) served.required = [...required, USER_GOAL_PARAM_NAME];
2330
+ return served;
2331
+ }
2332
+ var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
2333
+ function injectGoalParams(inputSchema2, intentParamMode) {
2334
+ const objSchema = normalizeObjectSchema(inputSchema2);
2335
+ if (!objSchema) return { schema: inputSchema2, dispositions: {} };
2336
+ const existingShape = getObjectShape(objSchema) ?? {};
2337
+ const values = Object.values(existingShape);
2338
+ const useV4 = values.length === 0 || isZ4Schema(values[0]);
2339
+ const zodImpl = useV4 ? import_zod2.z : import_v3.z;
2340
+ const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
2341
+ if (Object.keys(toInject).length === 0)
2342
+ return { schema: inputSchema2, dispositions };
2343
+ const mergedShape = { ...existingShape, ...toInject };
2344
+ const newSchema = objectFromShape(mergedShape);
2345
+ return { schema: newSchema, dispositions };
2346
+ }
2347
+ function buildIntentFields(existingShape, zodImpl, intentParamMode) {
2348
+ const dispositions = {};
2349
+ const toInject = {};
2350
+ for (const name of RETIRED_PARAM_NAMES) {
2351
+ if (name in existingShape) dispositions[name] = "native";
2352
+ }
2353
+ if (USER_GOAL_PARAM_NAME in existingShape) {
2354
+ dispositions[USER_GOAL_PARAM_NAME] = "native";
2355
+ } else {
2356
+ dispositions[USER_GOAL_PARAM_NAME] = "injected";
2357
+ toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
2358
+ }
2359
+ return { dispositions, toInject };
2360
+ }
2361
+ function injectGoalParamsV2(inputSchema2, intentParamMode) {
2362
+ const candidate = inputSchema2;
2363
+ const shape = candidate?.shape;
2364
+ if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
2365
+ return { schema: inputSchema2, dispositions: {} };
2366
+ }
2367
+ const { dispositions, toInject } = buildIntentFields(shape, import_zod2.z, intentParamMode);
2368
+ if (Object.keys(toInject).length === 0)
2369
+ return { schema: inputSchema2, dispositions };
2370
+ return { schema: candidate.extend(toInject), dispositions };
2371
+ }
2372
+ function advertiseIntentParamsRequired(result, names, isInjected) {
2373
+ const tools = result?.tools;
2374
+ if (!Array.isArray(tools)) return result;
2375
+ let changed = false;
2376
+ const advertised = tools.map((tool) => {
2377
+ const entry = tool;
2378
+ const toolName = entry?.name;
2379
+ if (typeof toolName !== "string") return tool;
2380
+ const schema = entry?.inputSchema;
2381
+ if (!schema || typeof schema !== "object") return tool;
2382
+ const declared2 = schema.required ?? [];
2383
+ if (!Array.isArray(declared2)) return tool;
2384
+ const required = declared2;
2385
+ const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
2386
+ if (missing.length === 0) return tool;
2387
+ changed = true;
2388
+ return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
2389
+ });
2390
+ return changed ? { ...result, tools: advertised } : result;
2391
+ }
2392
+ function standardInputJsonSchema(schema) {
2393
+ try {
2394
+ const standard = schema?.["~standard"];
2395
+ return standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
2396
+ } catch {
2397
+ return void 0;
2398
+ }
2399
+ }
2400
+ function toolInputJsonSchema(inputSchema2) {
2401
+ const objSchema = normalizeObjectSchema(inputSchema2);
2402
+ if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
2403
+ return toJsonSchemaCompat(objSchema, {
2404
+ strictUnions: true,
2405
+ pipeStrategy: "input"
2406
+ });
2407
+ }
2408
+
2208
2409
  // src/integrations/mcp/safeScrub.ts
2209
2410
  var warned2 = /* @__PURE__ */ new Set();
2210
2411
  function scrubOrNull(scrubber, value, field) {
@@ -2345,30 +2546,49 @@ function sessionIdFromHeader(extra) {
2345
2546
  // src/integrations/mcp/annotation.ts
2346
2547
  var TOOL_NAME_PARAM_NAME = "tool_name";
2347
2548
  var ANNOTATION_INPUT_SHAPE = {
2348
- user_goal: import_zod2.z.string(),
2349
- what_happened: import_zod2.z.string().optional(),
2549
+ user_goal: import_zod3.z.string(),
2550
+ what_happened: import_zod3.z.string().optional(),
2350
2551
  // Nullable so a report whose agent sends an explicit null is taken,
2351
2552
  // not rejected by validation.
2352
- tool_name: import_zod2.z.string().nullable().optional(),
2353
- suggested_improvement: import_zod2.z.string().optional(),
2354
- context: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).optional()
2553
+ tool_name: import_zod3.z.string().nullable().optional(),
2554
+ suggested_improvement: import_zod3.z.string().optional(),
2555
+ context: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).optional()
2355
2556
  };
2356
2557
  function isReport(whatHappened) {
2357
2558
  return typeof whatHappened === "string" && !isBlank(whatHappened);
2358
2559
  }
2359
2560
  function registerAnnotationTool(server, options) {
2561
+ const tool = buildAnnotationTool(server, options);
2562
+ server.registerTool(
2563
+ tool.name,
2564
+ { description: tool.description, inputSchema: ANNOTATION_INPUT_SHAPE },
2565
+ tool.handler
2566
+ );
2567
+ return tool.name;
2568
+ }
2569
+ var ANNOTATION_ARGS = import_zod3.z.object(ANNOTATION_INPUT_SHAPE);
2570
+ function annotationInputJsonSchema(major) {
2571
+ return annotationJsonSchemas[major] ??= (major === 2 ? standardInputJsonSchema(ANNOTATION_ARGS) : void 0) ?? toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
2572
+ }
2573
+ var annotationJsonSchemas = {};
2574
+ function callAnnotationTool(tool, args, extra) {
2575
+ const parsed = ANNOTATION_ARGS.safeParse(args ?? {});
2576
+ if (parsed.success) return tool.handler(parsed.data, extra);
2577
+ return Promise.resolve({
2578
+ content: [{ type: "text", text: `Invalid arguments for tool ${tool.name}: ${parsed.error.message}` }],
2579
+ isError: true
2580
+ });
2581
+ }
2582
+ function buildAnnotationTool(server, options) {
2360
2583
  const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
2361
2584
  const description = buildAnnotationToolDescription({
2362
2585
  vendorDisplayName: options.vendorDisplayName
2363
2586
  });
2364
2587
  const refusal = buildRefusalText({ annotationToolName: name });
2365
- server.registerTool(
2588
+ return {
2366
2589
  name,
2367
- {
2368
- description,
2369
- inputSchema: ANNOTATION_INPUT_SHAPE
2370
- },
2371
- async (args, extra) => {
2590
+ description,
2591
+ handler: async (args, extra) => {
2372
2592
  const whatHappened = args.what_happened;
2373
2593
  if (!isReport(whatHappened)) {
2374
2594
  return {
@@ -2428,8 +2648,7 @@ function registerAnnotationTool(server, options) {
2428
2648
  );
2429
2649
  return { content: [{ type: "text", text: JSON.stringify({ ok: true }) }] };
2430
2650
  }
2431
- );
2432
- return name;
2651
+ };
2433
2652
  }
2434
2653
 
2435
2654
  // src/dsn.ts
@@ -2812,7 +3031,7 @@ var SettingsFetcher = class {
2812
3031
  this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
2813
3032
  this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
2814
3033
  this.refreshMs = options.refreshMs;
2815
- this.fetchImpl = options.fetchImpl ?? fetch;
3034
+ this.fetchImpl = options.fetchImpl ?? globalFetch;
2816
3035
  }
2817
3036
  get document() {
2818
3037
  return this.held;
@@ -2910,19 +3129,31 @@ function resolveInstallConfig(config) {
2910
3129
  );
2911
3130
  return { resolved, unconfigured };
2912
3131
  }
2913
- function resolveBatonConfig(config) {
3132
+ var consoleOffWarned = false;
3133
+ function withoutConsoleOnWorkers(config) {
3134
+ if (config.settings !== "console" || !onWorkers()) return config;
3135
+ if (!consoleOffWarned) {
3136
+ consoleOffWarned = true;
3137
+ 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.`);
3138
+ }
3139
+ const rest = { ...config, reportMode: config.reportMode ?? "on" };
3140
+ delete rest.settings;
3141
+ return rest;
3142
+ }
3143
+ function resolveBatonConfig(supplied) {
2914
3144
  const dsnString = selectDsn(
2915
- config.dsn,
3145
+ supplied.dsn,
2916
3146
  {
2917
3147
  // Truthiness per field, mirroring Python's `bool()` / `is not None`
2918
3148
  // split: an empty `vendorId` is an unset one, while an explicitly
2919
3149
  // supplied `tenantId` or `sink` is a conflict whatever it holds.
2920
- vendorId: Boolean(config.vendorId),
2921
- tenantId: config.tenantId !== void 0,
2922
- sink: config.sink !== void 0
3150
+ vendorId: Boolean(supplied.vendorId),
3151
+ tenantId: supplied.tenantId !== void 0,
3152
+ sink: supplied.sink !== void 0
2923
3153
  },
2924
3154
  "BatonConfig"
2925
3155
  );
3156
+ const config = dsnString === void 0 ? supplied : withoutConsoleOnWorkers(supplied);
2926
3157
  if (dsnString === void 0) {
2927
3158
  const defaulted = {
2928
3159
  ...config,
@@ -3057,6 +3288,9 @@ function validateBatonConfig(config) {
3057
3288
  if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
3058
3289
  throw new Error("BatonConfig.resolvePrincipal must be a function.");
3059
3290
  }
3291
+ if (config.tools !== void 0 && !Array.isArray(config.tools) && typeof config.tools !== "function") {
3292
+ throw new Error("BatonConfig.tools must be an array of tools or a function that returns one.");
3293
+ }
3060
3294
  }
3061
3295
 
3062
3296
  // src/optout.ts
@@ -3243,154 +3477,6 @@ var ServerCounter = class extends SessionCounter {
3243
3477
  }
3244
3478
  };
3245
3479
 
3246
- // src/integrations/mcp/zodCompat.ts
3247
- var z3rt = __toESM(require("zod/v3"), 1);
3248
- var z4mini = __toESM(require("zod/v4-mini"), 1);
3249
- var import_zod_to_json_schema = require("zod-to-json-schema");
3250
- function isZ4Schema(s) {
3251
- const schema = s;
3252
- return !!schema?._zod;
3253
- }
3254
- function objectFromShape(shape) {
3255
- const values = Object.values(shape);
3256
- if (values.length === 0) return z4mini.object({});
3257
- const allV4 = values.every(isZ4Schema);
3258
- const allV3 = values.every((s) => !isZ4Schema(s));
3259
- if (allV4) return z4mini.object(shape);
3260
- if (allV3) return z3rt.object(shape);
3261
- throw new Error("Mixed Zod versions detected in object shape.");
3262
- }
3263
- function getObjectShape(schema) {
3264
- if (!schema) return void 0;
3265
- let rawShape;
3266
- if (isZ4Schema(schema)) {
3267
- rawShape = schema._zod?.def?.shape;
3268
- } else {
3269
- rawShape = schema.shape;
3270
- }
3271
- if (!rawShape) return void 0;
3272
- if (typeof rawShape === "function") {
3273
- try {
3274
- return rawShape();
3275
- } catch {
3276
- return void 0;
3277
- }
3278
- }
3279
- return rawShape;
3280
- }
3281
- function normalizeObjectSchema(schema) {
3282
- if (!schema) return void 0;
3283
- if (typeof schema === "object") {
3284
- const asAny = schema;
3285
- if (!asAny._def && !asAny._zod) {
3286
- const values = Object.values(schema);
3287
- if (values.length > 0 && values.every(
3288
- (v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function")
3289
- )) {
3290
- return objectFromShape(schema);
3291
- }
3292
- }
3293
- }
3294
- if (isZ4Schema(schema)) {
3295
- const def = schema._zod?.def;
3296
- if (def && (def.type === "object" || def.shape !== void 0)) return schema;
3297
- } else {
3298
- if (schema.shape !== void 0) return schema;
3299
- }
3300
- return void 0;
3301
- }
3302
- function mapMiniTarget(t) {
3303
- if (!t) return "draft-7";
3304
- if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
3305
- if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
3306
- return "draft-7";
3307
- }
3308
- function toJsonSchemaCompat(schema, opts) {
3309
- if (isZ4Schema(schema)) {
3310
- return z4mini.toJSONSchema(schema, {
3311
- target: mapMiniTarget(opts?.target),
3312
- io: opts?.pipeStrategy ?? "input"
3313
- });
3314
- }
3315
- return (0, import_zod_to_json_schema.zodToJsonSchema)(schema, {
3316
- strictUnions: opts?.strictUnions ?? true,
3317
- pipeStrategy: opts?.pipeStrategy ?? "input"
3318
- });
3319
- }
3320
-
3321
- // src/integrations/mcp/schemaCompat.ts
3322
- var import_zod3 = require("zod");
3323
- var import_v3 = require("zod/v3");
3324
- var DEFAULT_INTENT_PARAM_MODE = "required";
3325
- var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
3326
- function injectGoalParams(inputSchema2, intentParamMode) {
3327
- const objSchema = normalizeObjectSchema(inputSchema2);
3328
- if (!objSchema) return { schema: inputSchema2, dispositions: {} };
3329
- const existingShape = getObjectShape(objSchema) ?? {};
3330
- const values = Object.values(existingShape);
3331
- const useV4 = values.length === 0 || isZ4Schema(values[0]);
3332
- const zodImpl = useV4 ? import_zod3.z : import_v3.z;
3333
- const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
3334
- if (Object.keys(toInject).length === 0)
3335
- return { schema: inputSchema2, dispositions };
3336
- const mergedShape = { ...existingShape, ...toInject };
3337
- const newSchema = objectFromShape(mergedShape);
3338
- return { schema: newSchema, dispositions };
3339
- }
3340
- function buildIntentFields(existingShape, zodImpl, intentParamMode) {
3341
- const dispositions = {};
3342
- const toInject = {};
3343
- for (const name of RETIRED_PARAM_NAMES) {
3344
- if (name in existingShape) dispositions[name] = "native";
3345
- }
3346
- if (USER_GOAL_PARAM_NAME in existingShape) {
3347
- dispositions[USER_GOAL_PARAM_NAME] = "native";
3348
- } else {
3349
- dispositions[USER_GOAL_PARAM_NAME] = "injected";
3350
- toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
3351
- }
3352
- return { dispositions, toInject };
3353
- }
3354
- function injectGoalParamsV2(inputSchema2, intentParamMode) {
3355
- const candidate = inputSchema2;
3356
- const shape = candidate?.shape;
3357
- if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
3358
- return { schema: inputSchema2, dispositions: {} };
3359
- }
3360
- const { dispositions, toInject } = buildIntentFields(shape, import_zod3.z, intentParamMode);
3361
- if (Object.keys(toInject).length === 0)
3362
- return { schema: inputSchema2, dispositions };
3363
- return { schema: candidate.extend(toInject), dispositions };
3364
- }
3365
- function advertiseIntentParamsRequired(result, names, isInjected) {
3366
- const tools = result?.tools;
3367
- if (!Array.isArray(tools)) return result;
3368
- let changed = false;
3369
- const advertised = tools.map((tool) => {
3370
- const entry = tool;
3371
- const toolName = entry?.name;
3372
- if (typeof toolName !== "string") return tool;
3373
- const schema = entry?.inputSchema;
3374
- if (!schema || typeof schema !== "object") return tool;
3375
- const declared2 = schema.required ?? [];
3376
- if (!Array.isArray(declared2)) return tool;
3377
- const required = declared2;
3378
- const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
3379
- if (missing.length === 0) return tool;
3380
- changed = true;
3381
- return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
3382
- });
3383
- return changed ? { ...result, tools: advertised } : result;
3384
- }
3385
- function toolInputJsonSchema(inputSchema2) {
3386
- const objSchema = normalizeObjectSchema(inputSchema2);
3387
- if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
3388
- return toJsonSchemaCompat(objSchema, {
3389
- strictUnions: true,
3390
- pipeStrategy: "input"
3391
- });
3392
- }
3393
-
3394
3480
  // src/integrations/mcp/surface.ts
3395
3481
  var import_node_crypto3 = require("crypto");
3396
3482
  function surfaceHash(surface) {
@@ -3474,10 +3560,13 @@ var SurfaceState = class {
3474
3560
  /** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
3475
3561
  * which picks the spelling THIS SDK major puts on the wire. */
3476
3562
  noteTool(name, inputSchemaJson, description) {
3477
- this.rawTools.set(name, {
3478
- disabled: this.rawTools.get(name)?.disabled ?? false,
3479
- tool: { name, description: description ?? null, inputSchema: inputSchemaJson }
3480
- });
3563
+ const before = this.rawTools.get(name);
3564
+ const tool = { name, description: description ?? null, inputSchema: inputSchemaJson };
3565
+ if (before !== void 0 && before.tool.description === tool.description) {
3566
+ const same = before.tool.inputSchema === inputSchemaJson || JSON.stringify(before.tool.inputSchema) === JSON.stringify(inputSchemaJson);
3567
+ if (same) return;
3568
+ }
3569
+ this.rawTools.set(name, { disabled: before?.disabled ?? false, tool });
3481
3570
  this.dirty = true;
3482
3571
  }
3483
3572
  pruneTool(name) {
@@ -3519,14 +3608,14 @@ async function resolveEnvelopeParts(ctx, extra) {
3519
3608
  const session = await resolveSessionId(ctx.fallbackSessionId, extra);
3520
3609
  return { ...session, scrubbedMeta };
3521
3610
  }
3522
- async function openCall(ctx, toolName, extra, params, stripped, registered = true) {
3611
+ async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn") {
3523
3612
  await maybeEmitSurfaceSnapshot(ctx);
3524
3613
  const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
3525
3614
  const dispositions = ctx.paramRegistry.get(toolName);
3526
- const rawIntent = stripped[USER_GOAL_PARAM_NAME] ?? extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
3615
+ const rawIntent = stripped[USER_GOAL_PARAM_NAME] ?? extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, unlisted);
3527
3616
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
3528
3617
  const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
3529
- (name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
3618
+ (name) => dispositions === void 0 || dispositions[name] === "native" || unlisted === "leave" || unlisted === "goalOnly" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
3530
3619
  );
3531
3620
  const client = observeClient(extra, ctx);
3532
3621
  const caller = await resolveCaller(
@@ -3572,7 +3661,7 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
3572
3661
  );
3573
3662
  return { common, session, resultCaptureMode };
3574
3663
  }
3575
- function batonWrap(nameRef, original, ctx) {
3664
+ function batonWrap(nameRef, original, ctx, unlisted = "warn") {
3576
3665
  return async (...callArgs) => {
3577
3666
  const toolName = nameRef.current;
3578
3667
  const slot = callSlots.getStore();
@@ -3581,7 +3670,7 @@ function batonWrap(nameRef, original, ctx) {
3581
3670
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
3582
3671
  const stripped = slot?.strippedFor === toolName ? slot.stripped : {};
3583
3672
  if (slot) slot.strippedFor = null;
3584
- const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped);
3673
+ const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped, unlisted);
3585
3674
  const terminate = async (build, replacement) => {
3586
3675
  if (!slot) {
3587
3676
  if (build !== null) await emit(ctx.sink, build);
@@ -3739,11 +3828,12 @@ function batonWrap(nameRef, original, ctx) {
3739
3828
  return result;
3740
3829
  };
3741
3830
  }
3742
- function extractGoalParam(args, paramName, toolName, dispositions, registered) {
3831
+ function extractGoalParam(args, paramName, toolName, dispositions, unlisted) {
3743
3832
  if (!(paramName in args)) return null;
3744
3833
  const disposition = dispositions ? dispositions[paramName] : void 0;
3745
3834
  if (disposition === "native") return null;
3746
- if (disposition === void 0 && registered) {
3835
+ if (disposition === void 0 && unlisted === "leave") return null;
3836
+ if (disposition === void 0 && unlisted === "warn") {
3747
3837
  process.stderr.write(
3748
3838
  `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
3749
3839
  `
@@ -3868,6 +3958,183 @@ function installToolsListSeam(lowLevel, ctx) {
3868
3958
  return isThenable(out) ? out.then(advertise) : advertise(out);
3869
3959
  });
3870
3960
  }
3961
+ var LOW_LEVEL_LIST_SEAM = /* @__PURE__ */ Symbol("batonLowLevelListSeam");
3962
+ var LOW_LEVEL_CALL_SEAM = /* @__PURE__ */ Symbol("batonLowLevelCallSeam");
3963
+ var LOW_LEVEL_HANDSHAKE_SEAM = /* @__PURE__ */ Symbol("batonLowLevelHandshakeSeam");
3964
+ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce2, reportToolTaken) {
3965
+ let reportTool2 = annotationTool;
3966
+ const listedReportTool = reportTool2 && {
3967
+ name: reportTool2.name,
3968
+ description: reportTool2.description,
3969
+ inputSchema: annotationInputJsonSchema(lowLevelMajor(lowLevel))
3970
+ };
3971
+ const skipTool = (name, err) => {
3972
+ known.unread.add(name);
3973
+ warnOnce2(
3974
+ `tool-unread:${name}`,
3975
+ `baton: could not read tool ${JSON.stringify(name)}; its calls keep user_goal until Baton can read it: ${printable(err)}
3976
+ `
3977
+ );
3978
+ };
3979
+ const skipNote = (name, err) => {
3980
+ if (known.unread.has(name)) return;
3981
+ warnOnce2(`tool-unnoted:${name}`, `baton: could not note tool ${JSON.stringify(name)}; Baton adds no user_goal to it: ${printable(err)}
3982
+ `);
3983
+ };
3984
+ const keepGoalIfDeclared = (tools) => {
3985
+ for (const { name, inputSchema: inputSchema2 } of tools) {
3986
+ try {
3987
+ const checked = known.served.get(name)?.inputSchema === inputSchema2 && !known.unread.has(name);
3988
+ if (!known.keepsGoal.has(name) && !checked) {
3989
+ const declares = isRecord(inputSchema2) && takesUserGoalJson(inputSchema2) ? declaresParam : mayDeclareParam;
3990
+ if (declares(inputSchema2, USER_GOAL_PARAM_NAME)) known.keepsGoal.add(name);
3991
+ }
3992
+ known.unread.delete(name);
3993
+ } catch (err) {
3994
+ skipTool(name, err);
3995
+ }
3996
+ }
3997
+ };
3998
+ const read = (tools, { surface }) => {
3999
+ if (surface && reportTool2 !== void 0 && tools.some((tool) => tool.name === reportTool2?.name)) {
4000
+ warnOnce2(
4001
+ "report-tool-name-taken",
4002
+ `baton: the server lists its own tool ${JSON.stringify(reportTool2.name)}, so Baton's report tool is not added; set annotationToolName to another name
4003
+ `
4004
+ );
4005
+ reportTool2 = void 0;
4006
+ ctx.annotationToolName = "";
4007
+ reportToolTaken();
4008
+ }
4009
+ readToolList(tools, ctx, surface, skipNote);
4010
+ };
4011
+ const learn = (tools) => {
4012
+ keepGoalIfDeclared(tools);
4013
+ for (const tool of tools) {
4014
+ const held = known.served.get(tool.name);
4015
+ const ownGoal = (info) => declaresParam(info?.inputSchema, USER_GOAL_PARAM_NAME);
4016
+ if (held === void 0 || !ownGoal(held) || ownGoal(tool)) known.served.set(tool.name, tool);
4017
+ }
4018
+ };
4019
+ let caughtUp = false;
4020
+ const catchUp = () => {
4021
+ if (caughtUp) return;
4022
+ caughtUp = true;
4023
+ if (known.given !== void 0) {
4024
+ const given = known.given;
4025
+ known.given = void 0;
4026
+ try {
4027
+ const tools = typeof given === "function" ? given() : given;
4028
+ if (!Array.isArray(tools)) throw new Error("it is not an array of tools");
4029
+ known.givenTools = toolInfos(tools, skipTool);
4030
+ keepGoalIfDeclared(known.givenTools);
4031
+ } catch (err) {
4032
+ warnOnce2(
4033
+ "tools-unread",
4034
+ `baton: could not read the tools option; Baton learns the tools from tools/list: ${printable(err)}
4035
+ `
4036
+ );
4037
+ }
4038
+ }
4039
+ read(known.givenTools, { surface: true });
4040
+ read([...known.served.values()], { surface: false });
4041
+ };
4042
+ installRequestSeam(lowLevel, TOOLS_LIST_METHOD, LOW_LEVEL_LIST_SEAM, (handler) => async (...args) => {
4043
+ catchUp();
4044
+ const result = await handler(...args);
4045
+ try {
4046
+ const listed = listedTools(result);
4047
+ if (listed === null) return result;
4048
+ const tools = toolInfos(listed, skipTool);
4049
+ learn(tools);
4050
+ read(tools, { surface: true });
4051
+ const firstPage = args[0]?.params?.cursor === void 0;
4052
+ return servedToolList(result, listed, ctx, firstPage && reportTool2 ? listedReportTool : void 0);
4053
+ } catch (err) {
4054
+ process.stderr.write(`baton: tools/list capture failed; serving the vendor's own result: ${printable(err)}
4055
+ `);
4056
+ return result;
4057
+ }
4058
+ });
4059
+ const readFirst = (handler) => (...args) => {
4060
+ catchUp();
4061
+ return handler(...args);
4062
+ };
4063
+ installRequestSeam(lowLevel, "initialize", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);
4064
+ installRequestSeam(lowLevel, "server/discover", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);
4065
+ installRequestSeam(lowLevel, TOOLS_CALL_METHOD, LOW_LEVEL_CALL_SEAM, (handler) => async (...args) => {
4066
+ catchUp();
4067
+ ctx.perCaller?.followSettings();
4068
+ const request = args[0];
4069
+ const name = request?.params?.name;
4070
+ if (typeof name !== "string") return handler(...args);
4071
+ if (name === reportTool2?.name) return callAnnotationTool(reportTool2, request?.params?.arguments, args[1]);
4072
+ const injected = ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected";
4073
+ const unlisted = injected ? "warn" : known.keepsGoal.has(name) || known.unread.has(name) ? "leave" : "goalOnly";
4074
+ const params = request?.params?.arguments;
4075
+ const toolArgs = isRecord(params) ? params : {};
4076
+ if (unlisted === "goalOnly" && USER_GOAL_PARAM_NAME in toolArgs && !known.served.has(name) && !known.givenTools.some((tool) => tool.name === name)) {
4077
+ warnOnce2(
4078
+ "user-goal-unlisted",
4079
+ `baton: ${JSON.stringify(name)} is not in any tool list this process has read, so Baton took user_goal off it without knowing whether the tool declares its own; pass your tools as the tools option
4080
+ `
4081
+ );
4082
+ }
4083
+ if (request?.params?.task !== void 0) {
4084
+ if (injected) stripIntentParams(request.params, ctx);
4085
+ else extractGoalParam(toolArgs, USER_GOAL_PARAM_NAME, name, ctx.paramRegistry.get(name), unlisted);
4086
+ return handler(...args);
4087
+ }
4088
+ return batonWrap({ current: name }, () => handler(...args), ctx, unlisted)(toolArgs, args[1]);
4089
+ });
4090
+ }
4091
+ function lowLevelMajor(lowLevel) {
4092
+ return typeof lowLevel._wrapHandler === "function" ? 2 : 1;
4093
+ }
4094
+ function listedTools(result) {
4095
+ return isRecord(result) && Array.isArray(result.tools) ? result.tools : null;
4096
+ }
4097
+ function toolInfos(tools, skip) {
4098
+ const infos = [];
4099
+ for (const tool of tools) {
4100
+ let name;
4101
+ try {
4102
+ name = isRecord(tool) ? tool.name : void 0;
4103
+ if (typeof name !== "string") continue;
4104
+ infos.push({ name, description: tool.description, inputSchema: tool.inputSchema });
4105
+ } catch (err) {
4106
+ if (typeof name === "string") skip(name, err);
4107
+ }
4108
+ }
4109
+ return infos;
4110
+ }
4111
+ function readToolList(tools, ctx, surface, skip) {
4112
+ for (const { name, inputSchema: inputSchema2, description } of tools) {
4113
+ try {
4114
+ const schema = isRecord(inputSchema2) ? inputSchema2 : null;
4115
+ if (surface) {
4116
+ ctx.surfaceState.noteTool(name, schema ?? EMPTY_OBJECT_JSON_SCHEMA, typeof description === "string" ? description : void 0);
4117
+ }
4118
+ const dispositions = declaredIntentParams(schema);
4119
+ if (dispositions[USER_GOAL_PARAM_NAME] === "native") ctx.dropSubagentClause(name);
4120
+ else if (schema !== null && takesUserGoalJson(schema)) dispositions[USER_GOAL_PARAM_NAME] = "injected";
4121
+ if (Object.keys(dispositions).length > 0) ctx.paramRegistry.set(name, dispositions);
4122
+ else ctx.paramRegistry.delete(name);
4123
+ } catch (err) {
4124
+ ctx.paramRegistry.delete(name);
4125
+ skip(name, err);
4126
+ }
4127
+ }
4128
+ }
4129
+ function servedToolList(result, listed, ctx, reportTool2) {
4130
+ const tools = listed.map((tool) => {
4131
+ if (!isRecord(tool) || typeof tool.name !== "string") return tool;
4132
+ if (ctx.paramRegistry.get(tool.name)?.[USER_GOAL_PARAM_NAME] !== "injected") return tool;
4133
+ return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, ctx.intentParamMode, false) };
4134
+ });
4135
+ if (reportTool2 !== void 0) tools.push(reportTool2);
4136
+ return { ...result, tools };
4137
+ }
3871
4138
  var LIFECYCLE_SEAMS = {
3872
4139
  resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
3873
4140
  resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
@@ -4141,7 +4408,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
4141
4408
  args[1],
4142
4409
  params,
4143
4410
  slot.stripped,
4144
- entry != null
4411
+ entry != null ? "warn" : "quiet"
4145
4412
  );
4146
4413
  const failureKind = requestSideFailureKind(entry, slot.validation);
4147
4414
  const text = () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result);
@@ -4315,27 +4582,34 @@ function createBaton(supplied = {}) {
4315
4582
  function inertHandle(sink, sessionId) {
4316
4583
  return new BatonHandle({ sink, sessionId, vendorId: "", annotationToolName: "" });
4317
4584
  }
4318
- function requireHighLevelServer(server) {
4585
+ function serverShapeOf(server) {
4319
4586
  const candidate = server;
4320
- if (typeof candidate?.registerTool !== "function" || typeof candidate.server !== "object" || candidate.server === null) {
4321
- throw new TypeError(
4322
- "Baton needs a high-level McpServer (from @modelcontextprotocol/sdk/server/mcp.js or @modelcontextprotocol/server); the low-level Server is not supported."
4323
- );
4587
+ if (typeof candidate?.registerTool === "function" && typeof candidate.server === "object" && candidate.server !== null) {
4588
+ return "mcpServer";
4324
4589
  }
4590
+ const isServer = typeof candidate?._serverInfo === "object" && candidate._serverInfo !== null;
4591
+ if (typeof candidate?.setRequestHandler === "function" && candidate._requestHandlers instanceof Map && isServer) {
4592
+ return "lowLevel";
4593
+ }
4594
+ throw new TypeError(
4595
+ "Baton needs an McpServer or a low-level Server, from @modelcontextprotocol/sdk or @modelcontextprotocol/server."
4596
+ );
4325
4597
  }
4326
4598
  function newBatonState(config) {
4327
4599
  return {
4328
4600
  sentSurfaces: new SentSurfaces(),
4329
4601
  warned: /* @__PURE__ */ new Set(),
4330
4602
  counter: new SessionCounter(),
4331
- scrubber: config.scrubber ?? new Scrubber().scrub
4603
+ scrubber: config.scrubber ?? new Scrubber().scrub,
4604
+ lowLevelTools: { given: config.tools, givenTools: [], served: /* @__PURE__ */ new Map(), keepsGoal: /* @__PURE__ */ new Set(), unread: /* @__PURE__ */ new Set() }
4332
4605
  };
4333
4606
  }
4334
- function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber }, unconfigured) {
4335
- requireHighLevelServer(server);
4607
+ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber, lowLevelTools }, unconfigured) {
4608
+ const shape = serverShapeOf(server);
4336
4609
  const internals = server;
4610
+ const lowLevel = shape === "mcpServer" ? internals.server : server;
4337
4611
  const serverName = usableServerName(() => ({
4338
- name: internals.server._serverInfo?.name,
4612
+ name: lowLevel._serverInfo?.name,
4339
4613
  className: internals.constructor.name
4340
4614
  }));
4341
4615
  const config = resolved.reportMode === "on" ? withServerDisplayName(resolved, supplied, serverName) : resolved;
@@ -4349,7 +4623,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4349
4623
  const fallbackSessionId = `sdk-${uuid7()}`;
4350
4624
  const counter2 = new ServerCounter(sharedCounter, fallbackSessionId);
4351
4625
  const tenantId = resolveTenantId(config.tenantId, config.vendorId);
4352
- const serverMeta = buildServerMeta(server.server);
4626
+ const serverMeta = buildServerMeta(lowLevel);
4353
4627
  const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
4354
4628
  const emitSurface = async (sessionId, digest, snapshot) => {
4355
4629
  await emit(
@@ -4383,11 +4657,11 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4383
4657
  process.stderr.write(message);
4384
4658
  };
4385
4659
  const dropSubagentClause = (name) => {
4386
- const current2 = internals.server._instructions;
4660
+ const current2 = lowLevel._instructions;
4387
4661
  if (current2 === INTENT_INSTRUCTIONS) {
4388
- internals.server._instructions = "";
4662
+ lowLevel._instructions = "";
4389
4663
  } else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
4390
- internals.server._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
4664
+ lowLevel._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
4391
4665
  } else {
4392
4666
  return;
4393
4667
  }
@@ -4401,21 +4675,17 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4401
4675
  const vendorToolJsonSchema = (name, inputSchema2) => {
4402
4676
  if (isV2Server) {
4403
4677
  try {
4404
- const json = internals.toolInputSchemaJson(name);
4405
- if (json) return json;
4406
- } catch {
4407
- }
4408
- try {
4409
- const standard = inputSchema2?.["~standard"];
4410
- const json = standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
4411
- if (json) return json;
4678
+ const json2 = internals.toolInputSchemaJson(name);
4679
+ if (json2) return json2;
4412
4680
  } catch {
4413
4681
  }
4682
+ const json = standardInputJsonSchema(inputSchema2);
4683
+ if (json) return json;
4414
4684
  }
4415
4685
  try {
4416
4686
  return toolInputJsonSchema(inputSchema2);
4417
4687
  } catch {
4418
- return { type: "object", properties: {} };
4688
+ return EMPTY_OBJECT_JSON_SCHEMA;
4419
4689
  }
4420
4690
  };
4421
4691
  installValidationProbe(server);
@@ -4438,51 +4708,38 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4438
4708
  vendorToolJsonSchema,
4439
4709
  bustSchemaMemo,
4440
4710
  dropSubagentClause,
4441
- servedInstructions: () => internals.server._instructions,
4711
+ servedInstructions: () => lowLevel._instructions,
4442
4712
  surfaceState,
4443
4713
  emitSurface
4444
4714
  };
4445
4715
  const writeInstructions = (text) => {
4446
- internals.server._instructions = withVendorInstructions(
4447
- internals.server,
4716
+ lowLevel._instructions = withVendorInstructions(
4717
+ lowLevel,
4448
4718
  text,
4449
4719
  (message) => warnOnce2("instructions-length", message)
4450
4720
  );
4451
4721
  };
4452
4722
  writeInstructions(ours);
4723
+ const rewriteInstructions = (text) => {
4724
+ writeInstructions(text);
4725
+ const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === "native");
4726
+ if (native !== void 0) dropSubagentClause(native[0]);
4727
+ };
4453
4728
  if (config.captureSettings !== void 0) {
4454
4729
  ctx.perCaller = new PerCallerSurface({
4455
4730
  settings: config.captureSettings,
4456
4731
  intentParamMode,
4457
- annotationToolName,
4458
- instructions: ours,
4459
- writeInstructions: (text) => {
4460
- writeInstructions(text);
4461
- const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === "native");
4462
- if (native !== void 0) dropSubagentClause(native[0]);
4732
+ // Read, not copied: a low-level Server's own tool can take the name.
4733
+ get annotationToolName() {
4734
+ return ctx.annotationToolName;
4463
4735
  },
4736
+ instructions: ours,
4737
+ writeInstructions: rewriteInstructions,
4464
4738
  injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
4465
4739
  });
4466
4740
  ctx.perCaller.followSettings();
4467
4741
  }
4468
- installToolsListSeam(internals.server, ctx);
4469
- installToolsCallSeam(
4470
- internals.server,
4471
- // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
4472
- // object, so `registry["constructor"]` answers `Object` and
4473
- // `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
4474
- // so the "a tool we did not wrap" guard would decline to report, and a
4475
- // caller-visible `Tool constructor disabled` would reach the client with
4476
- // this seam silent. An agent hallucinating a prototype-shaped tool name is
4477
- // exactly the kind of failure the seam exists to make visible.
4478
- (name) => {
4479
- const registry = internals._registeredTools;
4480
- return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
4481
- },
4482
- ctx
4483
- );
4484
- installLifecycleSeams(internals.server, ctx);
4485
- const resolvedAnnotationToolName = !reports ? "" : registerAnnotationTool(server, {
4742
+ const annotationOptions = !reports ? void 0 : {
4486
4743
  sink,
4487
4744
  counter: ctx.counter,
4488
4745
  tenantId: ctx.tenantId,
@@ -4497,7 +4754,43 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4497
4754
  // raw override and letting the registration re-derive would register
4498
4755
  // `srv-..._annotate` while the instructions name the server-derived one.
4499
4756
  annotationToolName
4757
+ };
4758
+ if (shape === "lowLevel") {
4759
+ installLowLevelToolSeams(
4760
+ lowLevel,
4761
+ ctx,
4762
+ annotationOptions && buildAnnotationTool(server, annotationOptions),
4763
+ lowLevelTools,
4764
+ warnOnce2,
4765
+ () => rewriteInstructions(INTENT_INSTRUCTIONS)
4766
+ );
4767
+ }
4768
+ installToolsListSeam(lowLevel, ctx);
4769
+ if (shape === "mcpServer") installToolsCallSeam(
4770
+ lowLevel,
4771
+ // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
4772
+ // object, so `registry["constructor"]` answers `Object` and
4773
+ // `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
4774
+ // so the "a tool we did not wrap" guard would decline to report, and a
4775
+ // caller-visible `Tool constructor disabled` would reach the client with
4776
+ // this seam silent. An agent hallucinating a prototype-shaped tool name is
4777
+ // exactly the kind of failure the seam exists to make visible.
4778
+ (name) => {
4779
+ const registry = internals._registeredTools;
4780
+ return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
4781
+ },
4782
+ ctx
4783
+ );
4784
+ installLifecycleSeams(lowLevel, ctx);
4785
+ const handle = (name) => new BatonHandle({
4786
+ sink: given,
4787
+ queue: sink,
4788
+ vendorId: config.vendorId,
4789
+ sessionId: fallbackSessionId,
4790
+ annotationToolName: name
4500
4791
  });
4792
+ if (shape === "lowLevel") return handle(annotationToolName);
4793
+ const resolvedAnnotationToolName = annotationOptions ? registerAnnotationTool(server, annotationOptions) : "";
4501
4794
  const existing = internals._registeredTools;
4502
4795
  if (existing) {
4503
4796
  for (const [name, entry] of Object.entries(existing)) {
@@ -4510,13 +4803,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4510
4803
  wireEntry(String(args[0]), registered, ctx);
4511
4804
  return registered;
4512
4805
  };
4513
- return new BatonHandle({
4514
- sink: given,
4515
- queue: sink,
4516
- vendorId: config.vendorId,
4517
- sessionId: fallbackSessionId,
4518
- annotationToolName: resolvedAnnotationToolName
4519
- });
4806
+ return handle(resolvedAnnotationToolName);
4520
4807
  }
4521
4808
  function reportsFor(config) {
4522
4809
  if (config.reportMode !== "on") return void 0;
@@ -4676,25 +4963,8 @@ function snapshotPayload({ surface, digest }) {
4676
4963
  };
4677
4964
  }
4678
4965
  function servedEntry(tool) {
4679
- if (!isRecord(tool)) return tool;
4680
- const entry = { ...tool };
4681
- if (isRecord(entry.inputSchema)) {
4682
- const schema = { ...entry.inputSchema };
4683
- if (isRecord(schema.properties)) schema.properties = { ...schema.properties };
4684
- injectGoalParam(schema);
4685
- entry.inputSchema = schema;
4686
- }
4687
- return entry;
4688
- }
4689
- function injectGoalParam(schema) {
4690
- if (schema.properties === void 0) schema.properties = {};
4691
- if (!isRecord(schema.properties) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return;
4692
- schema.properties[USER_GOAL_PARAM_NAME] = {
4693
- type: "string",
4694
- description: buildUserGoalParamDescription({ intentParamMode: DEFAULT_INTENT_PARAM_MODE })
4695
- };
4696
- const required = Array.isArray(schema.required) ? schema.required : [];
4697
- if (!required.includes(USER_GOAL_PARAM_NAME)) schema.required = [...required, USER_GOAL_PARAM_NAME];
4966
+ if (!isRecord(tool) || !isRecord(tool.inputSchema)) return tool;
4967
+ return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, DEFAULT_INTENT_PARAM_MODE, true) };
4698
4968
  }
4699
4969
 
4700
4970
  // src/library/client.ts
@@ -4778,7 +5048,7 @@ function paramsOf(args) {
4778
5048
  var Core = class {
4779
5049
  closed = false;
4780
5050
  // A snapshot describes the server, so it takes no block's session,
4781
- // principal or client: SPEC §11.5.1's join must not count it.
5051
+ // principal or client (SPEC §5.6 rule 7).
4782
5052
  surfaceSessionId = uuid7();
4783
5053
  sentSurfaces = new SentSurfaces();
4784
5054
  sink;