@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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-1.0.0";
2
+ var SDK_VERSION = "ts-1.1.0";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
@@ -384,9 +384,17 @@ var EventSchema = z.discriminatedUnion("event_type", [
384
384
  ToolListErrorEventSchema
385
385
  ]);
386
386
 
387
+ // src/runtime.ts
388
+ function onWorkers() {
389
+ return typeof globalThis.WebSocketPair === "function" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
390
+ }
391
+ var globalFetch = (input, init) => fetch(input, init);
392
+
387
393
  // src/warn.ts
388
394
  function warn(message) {
389
- if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
395
+ if (onWorkers()) {
396
+ console.warn(message);
397
+ } else if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
390
398
  process.emitWarning(message);
391
399
  }
392
400
  }
@@ -569,7 +577,8 @@ var SHUTDOWN_FLUSH_TIMEOUT_MS = 3e3;
569
577
  // src/drops.ts
570
578
  var RECOVERY_LOG_MS = 6e4;
571
579
  var DropCounts = class {
572
- #instanceId = uuid7();
580
+ // Made on first use: a Worker refuses random values while its modules load.
581
+ #instanceId;
573
582
  #total = /* @__PURE__ */ new Map();
574
583
  #sinceDelivery = /* @__PURE__ */ new Map();
575
584
  #lastRecoveryLog = -RECOVERY_LOG_MS;
@@ -593,13 +602,13 @@ var DropCounts = class {
593
602
  const total = lost.reduce((sum2, [, n]) => sum2 + n, 0);
594
603
  warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(", ")}.`);
595
604
  }
596
- /** For tests: the counts are one per process. */
597
605
  /** Names this process in its loss reports (SPEC §11.4.7). */
598
606
  get instanceId() {
599
- return this.#instanceId;
607
+ return this.#instanceId ??= uuid7();
600
608
  }
609
+ /** For tests: the counts are one per process. */
601
610
  clear() {
602
- this.#instanceId = uuid7();
611
+ this.#instanceId = void 0;
603
612
  this.#total.clear();
604
613
  this.#sinceDelivery.clear();
605
614
  this.#lastRecoveryLog = -RECOVERY_LOG_MS;
@@ -1039,8 +1048,12 @@ var HttpSink = class _HttpSink {
1039
1048
  /** Whether the queued pass sends everything waiting, not only what is due. */
1040
1049
  forceNext = false;
1041
1050
  flushTimer = null;
1042
- /** Set by a failed batch: only the timer, a flush or a close tries again. */
1051
+ /** Set by a failed batch: only the timer, a flush, a close or, at
1052
+ * `flushIntervalMs` 0, a write after `retryFrom` tries again. */
1043
1053
  waitForTimer = false;
1054
+ /** When a failed batch may be tried again. At `flushIntervalMs` 0 the
1055
+ * first write from then retries, as a Worker may drop the timer. */
1056
+ retryFrom = 0;
1044
1057
  /** Nothing is sent before this `Date.now()`, from a 429's `Retry-After`. */
1045
1058
  retryAt = 0;
1046
1059
  /** Set for the life of the sink by a 404 or 405 on the batch path. */
@@ -1066,7 +1079,7 @@ var HttpSink = class _HttpSink {
1066
1079
  "shutdownFlushTimeoutMs",
1067
1080
  SHUTDOWN_FLUSH_TIMEOUT_MS
1068
1081
  );
1069
- this.flushIntervalMs = timerMsOption(options.flushIntervalMs, "flushIntervalMs", FLUSH_INTERVAL_MS);
1082
+ this.flushIntervalMs = timerMsOption(options.flushIntervalMs, "flushIntervalMs", onWorkers() ? 0 : FLUSH_INTERVAL_MS);
1070
1083
  this.maxRetries = options.maxRetries ?? 3;
1071
1084
  this.backoffBaseMs = options.backoffBaseMs ?? 100;
1072
1085
  this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
@@ -1074,7 +1087,7 @@ var HttpSink = class _HttpSink {
1074
1087
  options.circuitBreakerThreshold ?? 5,
1075
1088
  options.circuitBreakerResetMs ?? 3e4
1076
1089
  );
1077
- this.fetchImpl = options.fetchImpl ?? fetch;
1090
+ this.fetchImpl = options.fetchImpl ?? globalFetch;
1078
1091
  }
1079
1092
  /**
1080
1093
  * What this sink shows when something prints it — never the bearer.
@@ -1112,8 +1125,9 @@ var HttpSink = class _HttpSink {
1112
1125
  }
1113
1126
  this.enqueue({ event, json, bytes, writtenAt: Date.now() });
1114
1127
  this.unsentWarned = false;
1115
- if (this.batchIsFull() && !this.waitForTimer) void this.scheduleDrain(false);
1116
- else this.armTimer(this.buffer[0].writtenAt + this.flushIntervalMs - Date.now());
1128
+ const held = this.waitForTimer && !(this.flushIntervalMs === 0 && Date.now() >= this.retryFrom);
1129
+ if (!held && (this.flushIntervalMs === 0 || this.batchIsFull())) void this.scheduleDrain(false);
1130
+ else this.armTimer(Math.max(this.buffer[0].writtenAt + this.flushIntervalMs, held ? this.retryFrom : 0) - Date.now());
1117
1131
  this.ensureExitHooksRegistered();
1118
1132
  }
1119
1133
  flush() {
@@ -1365,8 +1379,9 @@ var HttpSink = class _HttpSink {
1365
1379
  this.waitForTimer = failed;
1366
1380
  this.clearTimer();
1367
1381
  if (failed) {
1368
- const waits = [this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest()];
1369
- if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(Math.max(...waits));
1382
+ const wait = Math.max(this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest());
1383
+ this.retryFrom = Date.now() + wait;
1384
+ if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(wait);
1370
1385
  return;
1371
1386
  }
1372
1387
  const next = Math.min(this.buffer[0]?.writtenAt ?? Infinity, this.reportRidesHead() ? this.reportSetAt : Infinity);
@@ -1742,6 +1757,23 @@ function declaresParam(schema, name) {
1742
1757
  const props = schema?.properties;
1743
1758
  return typeof props === "object" && props !== null && name in props;
1744
1759
  }
1760
+ var NOT_ACCEPTED = /* @__PURE__ */ new Set(["not", "const", "enum", "default", "examples"]);
1761
+ var NAMED_SCHEMAS = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
1762
+ function mayDeclareParam(schema, name) {
1763
+ const seen = /* @__PURE__ */ new Set();
1764
+ const walk2 = (node) => {
1765
+ if (typeof node !== "object" || node === null || seen.has(node)) return false;
1766
+ seen.add(node);
1767
+ const { required, $ref } = node;
1768
+ if (declaresParam(node, name) || Array.isArray(required) && required.includes(name)) return true;
1769
+ if (typeof $ref === "string" && !$ref.startsWith("#")) return true;
1770
+ return Object.entries(node).some(([key, child]) => {
1771
+ if (NAMED_SCHEMAS.has(key) && typeof child === "object" && child !== null) return Object.values(child).some(walk2);
1772
+ return !NOT_ACCEPTED.has(key) && walk2(child);
1773
+ });
1774
+ };
1775
+ return walk2(schema);
1776
+ }
1745
1777
  function instructionsSuffixServed(annotationToolName, served) {
1746
1778
  if (annotationToolName) return true;
1747
1779
  return typeof served === "string" && served.includes(INTENT_INSTRUCTIONS);
@@ -2125,11 +2157,10 @@ async function resolveCaller(hook, call, settings, client = null) {
2125
2157
  const caller = await resolveIdentity(hook, call);
2126
2158
  if (settings === void 0) return caller;
2127
2159
  try {
2128
- const identity = caller.principal ?? caller.organization;
2129
2160
  const callSettings = settings.forCaller({
2130
2161
  labels: caller.labels,
2131
2162
  clientName: client?.info?.name ?? null,
2132
- shareKey: identity?.id ?? null
2163
+ shareKey: caller.principal?.id ?? null
2133
2164
  });
2134
2165
  return callSettings === void 0 ? caller : { ...caller, settings: callSettings };
2135
2166
  } catch {
@@ -2151,6 +2182,176 @@ async function resolveIdentity(hook, call) {
2151
2182
  }
2152
2183
  }
2153
2184
 
2185
+ // src/integrations/mcp/zodCompat.ts
2186
+ import * as z3rt from "zod/v3";
2187
+ import * as z4mini from "zod/v4-mini";
2188
+ import { zodToJsonSchema } from "zod-to-json-schema";
2189
+ function isZ4Schema(s) {
2190
+ const schema = s;
2191
+ return !!schema?._zod;
2192
+ }
2193
+ function objectFromShape(shape) {
2194
+ const values = Object.values(shape);
2195
+ if (values.length === 0) return z4mini.object({});
2196
+ const allV4 = values.every(isZ4Schema);
2197
+ const allV3 = values.every((s) => !isZ4Schema(s));
2198
+ if (allV4) return z4mini.object(shape);
2199
+ if (allV3) return z3rt.object(shape);
2200
+ throw new Error("Mixed Zod versions detected in object shape.");
2201
+ }
2202
+ function getObjectShape(schema) {
2203
+ if (!schema) return void 0;
2204
+ let rawShape;
2205
+ if (isZ4Schema(schema)) {
2206
+ rawShape = schema._zod?.def?.shape;
2207
+ } else {
2208
+ rawShape = schema.shape;
2209
+ }
2210
+ if (!rawShape) return void 0;
2211
+ if (typeof rawShape === "function") {
2212
+ try {
2213
+ return rawShape();
2214
+ } catch {
2215
+ return void 0;
2216
+ }
2217
+ }
2218
+ return rawShape;
2219
+ }
2220
+ function normalizeObjectSchema(schema) {
2221
+ if (!schema) return void 0;
2222
+ if (typeof schema === "object") {
2223
+ const asAny = schema;
2224
+ if (!asAny._def && !asAny._zod) {
2225
+ const values = Object.values(schema);
2226
+ if (values.length > 0 && values.every(
2227
+ (v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function")
2228
+ )) {
2229
+ return objectFromShape(schema);
2230
+ }
2231
+ }
2232
+ }
2233
+ if (isZ4Schema(schema)) {
2234
+ const def = schema._zod?.def;
2235
+ if (def && (def.type === "object" || def.shape !== void 0)) return schema;
2236
+ } else {
2237
+ if (schema.shape !== void 0) return schema;
2238
+ }
2239
+ return void 0;
2240
+ }
2241
+ function mapMiniTarget(t) {
2242
+ if (!t) return "draft-7";
2243
+ if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
2244
+ if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
2245
+ return "draft-7";
2246
+ }
2247
+ function toJsonSchemaCompat(schema, opts) {
2248
+ if (isZ4Schema(schema)) {
2249
+ return z4mini.toJSONSchema(schema, {
2250
+ target: mapMiniTarget(opts?.target),
2251
+ io: opts?.pipeStrategy ?? "input"
2252
+ });
2253
+ }
2254
+ return zodToJsonSchema(schema, {
2255
+ strictUnions: opts?.strictUnions ?? true,
2256
+ pipeStrategy: opts?.pipeStrategy ?? "input"
2257
+ });
2258
+ }
2259
+
2260
+ // src/integrations/mcp/schemaCompat.ts
2261
+ import { z as zV4 } from "zod";
2262
+ import { z as zV3 } from "zod/v3";
2263
+ var DEFAULT_INTENT_PARAM_MODE = "required";
2264
+ var ROOT_COMBINERS = ["$ref", "oneOf", "anyOf", "allOf"];
2265
+ function takesUserGoalJson(schema) {
2266
+ const properties = schema.properties ?? {};
2267
+ return isRecord(properties) && !ROOT_COMBINERS.some((key) => key in schema);
2268
+ }
2269
+ function withUserGoalJson(schema, intentParamMode, listRequired) {
2270
+ if (!takesUserGoalJson(schema) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return schema;
2271
+ const properties = schema.properties ?? {};
2272
+ const goal = { type: "string", description: buildUserGoalParamDescription({ intentParamMode }) };
2273
+ const served = { ...schema, properties: { ...properties, [USER_GOAL_PARAM_NAME]: goal } };
2274
+ const required = Array.isArray(schema.required) ? schema.required : [];
2275
+ if (listRequired && !required.includes(USER_GOAL_PARAM_NAME)) served.required = [...required, USER_GOAL_PARAM_NAME];
2276
+ return served;
2277
+ }
2278
+ var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
2279
+ function injectGoalParams(inputSchema2, intentParamMode) {
2280
+ const objSchema = normalizeObjectSchema(inputSchema2);
2281
+ if (!objSchema) return { schema: inputSchema2, dispositions: {} };
2282
+ const existingShape = getObjectShape(objSchema) ?? {};
2283
+ const values = Object.values(existingShape);
2284
+ const useV4 = values.length === 0 || isZ4Schema(values[0]);
2285
+ const zodImpl = useV4 ? zV4 : zV3;
2286
+ const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
2287
+ if (Object.keys(toInject).length === 0)
2288
+ return { schema: inputSchema2, dispositions };
2289
+ const mergedShape = { ...existingShape, ...toInject };
2290
+ const newSchema = objectFromShape(mergedShape);
2291
+ return { schema: newSchema, dispositions };
2292
+ }
2293
+ function buildIntentFields(existingShape, zodImpl, intentParamMode) {
2294
+ const dispositions = {};
2295
+ const toInject = {};
2296
+ for (const name of RETIRED_PARAM_NAMES) {
2297
+ if (name in existingShape) dispositions[name] = "native";
2298
+ }
2299
+ if (USER_GOAL_PARAM_NAME in existingShape) {
2300
+ dispositions[USER_GOAL_PARAM_NAME] = "native";
2301
+ } else {
2302
+ dispositions[USER_GOAL_PARAM_NAME] = "injected";
2303
+ toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
2304
+ }
2305
+ return { dispositions, toInject };
2306
+ }
2307
+ function injectGoalParamsV2(inputSchema2, intentParamMode) {
2308
+ const candidate = inputSchema2;
2309
+ const shape = candidate?.shape;
2310
+ if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
2311
+ return { schema: inputSchema2, dispositions: {} };
2312
+ }
2313
+ const { dispositions, toInject } = buildIntentFields(shape, zV4, intentParamMode);
2314
+ if (Object.keys(toInject).length === 0)
2315
+ return { schema: inputSchema2, dispositions };
2316
+ return { schema: candidate.extend(toInject), dispositions };
2317
+ }
2318
+ function advertiseIntentParamsRequired(result, names, isInjected) {
2319
+ const tools = result?.tools;
2320
+ if (!Array.isArray(tools)) return result;
2321
+ let changed = false;
2322
+ const advertised = tools.map((tool) => {
2323
+ const entry = tool;
2324
+ const toolName = entry?.name;
2325
+ if (typeof toolName !== "string") return tool;
2326
+ const schema = entry?.inputSchema;
2327
+ if (!schema || typeof schema !== "object") return tool;
2328
+ const declared2 = schema.required ?? [];
2329
+ if (!Array.isArray(declared2)) return tool;
2330
+ const required = declared2;
2331
+ const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
2332
+ if (missing.length === 0) return tool;
2333
+ changed = true;
2334
+ return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
2335
+ });
2336
+ return changed ? { ...result, tools: advertised } : result;
2337
+ }
2338
+ function standardInputJsonSchema(schema) {
2339
+ try {
2340
+ const standard = schema?.["~standard"];
2341
+ return standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
2342
+ } catch {
2343
+ return void 0;
2344
+ }
2345
+ }
2346
+ function toolInputJsonSchema(inputSchema2) {
2347
+ const objSchema = normalizeObjectSchema(inputSchema2);
2348
+ if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
2349
+ return toJsonSchemaCompat(objSchema, {
2350
+ strictUnions: true,
2351
+ pipeStrategy: "input"
2352
+ });
2353
+ }
2354
+
2154
2355
  // src/integrations/mcp/safeScrub.ts
2155
2356
  var warned2 = /* @__PURE__ */ new Set();
2156
2357
  function scrubOrNull(scrubber, value, field) {
@@ -2303,18 +2504,37 @@ function isReport(whatHappened) {
2303
2504
  return typeof whatHappened === "string" && !isBlank(whatHappened);
2304
2505
  }
2305
2506
  function registerAnnotationTool(server, options) {
2507
+ const tool = buildAnnotationTool(server, options);
2508
+ server.registerTool(
2509
+ tool.name,
2510
+ { description: tool.description, inputSchema: ANNOTATION_INPUT_SHAPE },
2511
+ tool.handler
2512
+ );
2513
+ return tool.name;
2514
+ }
2515
+ var ANNOTATION_ARGS = z2.object(ANNOTATION_INPUT_SHAPE);
2516
+ function annotationInputJsonSchema(major) {
2517
+ return annotationJsonSchemas[major] ??= (major === 2 ? standardInputJsonSchema(ANNOTATION_ARGS) : void 0) ?? toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
2518
+ }
2519
+ var annotationJsonSchemas = {};
2520
+ function callAnnotationTool(tool, args, extra) {
2521
+ const parsed = ANNOTATION_ARGS.safeParse(args ?? {});
2522
+ if (parsed.success) return tool.handler(parsed.data, extra);
2523
+ return Promise.resolve({
2524
+ content: [{ type: "text", text: `Invalid arguments for tool ${tool.name}: ${parsed.error.message}` }],
2525
+ isError: true
2526
+ });
2527
+ }
2528
+ function buildAnnotationTool(server, options) {
2306
2529
  const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
2307
2530
  const description = buildAnnotationToolDescription({
2308
2531
  vendorDisplayName: options.vendorDisplayName
2309
2532
  });
2310
2533
  const refusal = buildRefusalText({ annotationToolName: name });
2311
- server.registerTool(
2534
+ return {
2312
2535
  name,
2313
- {
2314
- description,
2315
- inputSchema: ANNOTATION_INPUT_SHAPE
2316
- },
2317
- async (args, extra) => {
2536
+ description,
2537
+ handler: async (args, extra) => {
2318
2538
  const whatHappened = args.what_happened;
2319
2539
  if (!isReport(whatHappened)) {
2320
2540
  return {
@@ -2374,8 +2594,7 @@ function registerAnnotationTool(server, options) {
2374
2594
  );
2375
2595
  return { content: [{ type: "text", text: JSON.stringify({ ok: true }) }] };
2376
2596
  }
2377
- );
2378
- return name;
2597
+ };
2379
2598
  }
2380
2599
 
2381
2600
  // src/dsn.ts
@@ -2758,7 +2977,7 @@ var SettingsFetcher = class {
2758
2977
  this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
2759
2978
  this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
2760
2979
  this.refreshMs = options.refreshMs;
2761
- this.fetchImpl = options.fetchImpl ?? fetch;
2980
+ this.fetchImpl = options.fetchImpl ?? globalFetch;
2762
2981
  }
2763
2982
  get document() {
2764
2983
  return this.held;
@@ -2856,19 +3075,31 @@ function resolveInstallConfig(config) {
2856
3075
  );
2857
3076
  return { resolved, unconfigured };
2858
3077
  }
2859
- function resolveBatonConfig(config) {
3078
+ var consoleOffWarned = false;
3079
+ function withoutConsoleOnWorkers(config) {
3080
+ if (config.settings !== "console" || !onWorkers()) return config;
3081
+ if (!consoleOffWarned) {
3082
+ consoleOffWarned = true;
3083
+ 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.`);
3084
+ }
3085
+ const rest = { ...config, reportMode: config.reportMode ?? "on" };
3086
+ delete rest.settings;
3087
+ return rest;
3088
+ }
3089
+ function resolveBatonConfig(supplied) {
2860
3090
  const dsnString = selectDsn(
2861
- config.dsn,
3091
+ supplied.dsn,
2862
3092
  {
2863
3093
  // Truthiness per field, mirroring Python's `bool()` / `is not None`
2864
3094
  // split: an empty `vendorId` is an unset one, while an explicitly
2865
3095
  // supplied `tenantId` or `sink` is a conflict whatever it holds.
2866
- vendorId: Boolean(config.vendorId),
2867
- tenantId: config.tenantId !== void 0,
2868
- sink: config.sink !== void 0
3096
+ vendorId: Boolean(supplied.vendorId),
3097
+ tenantId: supplied.tenantId !== void 0,
3098
+ sink: supplied.sink !== void 0
2869
3099
  },
2870
3100
  "BatonConfig"
2871
3101
  );
3102
+ const config = dsnString === void 0 ? supplied : withoutConsoleOnWorkers(supplied);
2872
3103
  if (dsnString === void 0) {
2873
3104
  const defaulted = {
2874
3105
  ...config,
@@ -3003,6 +3234,9 @@ function validateBatonConfig(config) {
3003
3234
  if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
3004
3235
  throw new Error("BatonConfig.resolvePrincipal must be a function.");
3005
3236
  }
3237
+ if (config.tools !== void 0 && !Array.isArray(config.tools) && typeof config.tools !== "function") {
3238
+ throw new Error("BatonConfig.tools must be an array of tools or a function that returns one.");
3239
+ }
3006
3240
  }
3007
3241
 
3008
3242
  // src/optout.ts
@@ -3189,154 +3423,6 @@ var ServerCounter = class extends SessionCounter {
3189
3423
  }
3190
3424
  };
3191
3425
 
3192
- // src/integrations/mcp/zodCompat.ts
3193
- import * as z3rt from "zod/v3";
3194
- import * as z4mini from "zod/v4-mini";
3195
- import { zodToJsonSchema } from "zod-to-json-schema";
3196
- function isZ4Schema(s) {
3197
- const schema = s;
3198
- return !!schema?._zod;
3199
- }
3200
- function objectFromShape(shape) {
3201
- const values = Object.values(shape);
3202
- if (values.length === 0) return z4mini.object({});
3203
- const allV4 = values.every(isZ4Schema);
3204
- const allV3 = values.every((s) => !isZ4Schema(s));
3205
- if (allV4) return z4mini.object(shape);
3206
- if (allV3) return z3rt.object(shape);
3207
- throw new Error("Mixed Zod versions detected in object shape.");
3208
- }
3209
- function getObjectShape(schema) {
3210
- if (!schema) return void 0;
3211
- let rawShape;
3212
- if (isZ4Schema(schema)) {
3213
- rawShape = schema._zod?.def?.shape;
3214
- } else {
3215
- rawShape = schema.shape;
3216
- }
3217
- if (!rawShape) return void 0;
3218
- if (typeof rawShape === "function") {
3219
- try {
3220
- return rawShape();
3221
- } catch {
3222
- return void 0;
3223
- }
3224
- }
3225
- return rawShape;
3226
- }
3227
- function normalizeObjectSchema(schema) {
3228
- if (!schema) return void 0;
3229
- if (typeof schema === "object") {
3230
- const asAny = schema;
3231
- if (!asAny._def && !asAny._zod) {
3232
- const values = Object.values(schema);
3233
- if (values.length > 0 && values.every(
3234
- (v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function")
3235
- )) {
3236
- return objectFromShape(schema);
3237
- }
3238
- }
3239
- }
3240
- if (isZ4Schema(schema)) {
3241
- const def = schema._zod?.def;
3242
- if (def && (def.type === "object" || def.shape !== void 0)) return schema;
3243
- } else {
3244
- if (schema.shape !== void 0) return schema;
3245
- }
3246
- return void 0;
3247
- }
3248
- function mapMiniTarget(t) {
3249
- if (!t) return "draft-7";
3250
- if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
3251
- if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
3252
- return "draft-7";
3253
- }
3254
- function toJsonSchemaCompat(schema, opts) {
3255
- if (isZ4Schema(schema)) {
3256
- return z4mini.toJSONSchema(schema, {
3257
- target: mapMiniTarget(opts?.target),
3258
- io: opts?.pipeStrategy ?? "input"
3259
- });
3260
- }
3261
- return zodToJsonSchema(schema, {
3262
- strictUnions: opts?.strictUnions ?? true,
3263
- pipeStrategy: opts?.pipeStrategy ?? "input"
3264
- });
3265
- }
3266
-
3267
- // src/integrations/mcp/schemaCompat.ts
3268
- import { z as zV4 } from "zod";
3269
- import { z as zV3 } from "zod/v3";
3270
- var DEFAULT_INTENT_PARAM_MODE = "required";
3271
- var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
3272
- function injectGoalParams(inputSchema2, intentParamMode) {
3273
- const objSchema = normalizeObjectSchema(inputSchema2);
3274
- if (!objSchema) return { schema: inputSchema2, dispositions: {} };
3275
- const existingShape = getObjectShape(objSchema) ?? {};
3276
- const values = Object.values(existingShape);
3277
- const useV4 = values.length === 0 || isZ4Schema(values[0]);
3278
- const zodImpl = useV4 ? zV4 : zV3;
3279
- const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
3280
- if (Object.keys(toInject).length === 0)
3281
- return { schema: inputSchema2, dispositions };
3282
- const mergedShape = { ...existingShape, ...toInject };
3283
- const newSchema = objectFromShape(mergedShape);
3284
- return { schema: newSchema, dispositions };
3285
- }
3286
- function buildIntentFields(existingShape, zodImpl, intentParamMode) {
3287
- const dispositions = {};
3288
- const toInject = {};
3289
- for (const name of RETIRED_PARAM_NAMES) {
3290
- if (name in existingShape) dispositions[name] = "native";
3291
- }
3292
- if (USER_GOAL_PARAM_NAME in existingShape) {
3293
- dispositions[USER_GOAL_PARAM_NAME] = "native";
3294
- } else {
3295
- dispositions[USER_GOAL_PARAM_NAME] = "injected";
3296
- toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
3297
- }
3298
- return { dispositions, toInject };
3299
- }
3300
- function injectGoalParamsV2(inputSchema2, intentParamMode) {
3301
- const candidate = inputSchema2;
3302
- const shape = candidate?.shape;
3303
- if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
3304
- return { schema: inputSchema2, dispositions: {} };
3305
- }
3306
- const { dispositions, toInject } = buildIntentFields(shape, zV4, intentParamMode);
3307
- if (Object.keys(toInject).length === 0)
3308
- return { schema: inputSchema2, dispositions };
3309
- return { schema: candidate.extend(toInject), dispositions };
3310
- }
3311
- function advertiseIntentParamsRequired(result, names, isInjected) {
3312
- const tools = result?.tools;
3313
- if (!Array.isArray(tools)) return result;
3314
- let changed = false;
3315
- const advertised = tools.map((tool) => {
3316
- const entry = tool;
3317
- const toolName = entry?.name;
3318
- if (typeof toolName !== "string") return tool;
3319
- const schema = entry?.inputSchema;
3320
- if (!schema || typeof schema !== "object") return tool;
3321
- const declared2 = schema.required ?? [];
3322
- if (!Array.isArray(declared2)) return tool;
3323
- const required = declared2;
3324
- const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
3325
- if (missing.length === 0) return tool;
3326
- changed = true;
3327
- return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
3328
- });
3329
- return changed ? { ...result, tools: advertised } : result;
3330
- }
3331
- function toolInputJsonSchema(inputSchema2) {
3332
- const objSchema = normalizeObjectSchema(inputSchema2);
3333
- if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
3334
- return toJsonSchemaCompat(objSchema, {
3335
- strictUnions: true,
3336
- pipeStrategy: "input"
3337
- });
3338
- }
3339
-
3340
3426
  // src/integrations/mcp/surface.ts
3341
3427
  import { createHash as createHash2 } from "crypto";
3342
3428
  function surfaceHash(surface) {
@@ -3420,10 +3506,13 @@ var SurfaceState = class {
3420
3506
  /** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
3421
3507
  * which picks the spelling THIS SDK major puts on the wire. */
3422
3508
  noteTool(name, inputSchemaJson, description) {
3423
- this.rawTools.set(name, {
3424
- disabled: this.rawTools.get(name)?.disabled ?? false,
3425
- tool: { name, description: description ?? null, inputSchema: inputSchemaJson }
3426
- });
3509
+ const before = this.rawTools.get(name);
3510
+ const tool = { name, description: description ?? null, inputSchema: inputSchemaJson };
3511
+ if (before !== void 0 && before.tool.description === tool.description) {
3512
+ const same = before.tool.inputSchema === inputSchemaJson || JSON.stringify(before.tool.inputSchema) === JSON.stringify(inputSchemaJson);
3513
+ if (same) return;
3514
+ }
3515
+ this.rawTools.set(name, { disabled: before?.disabled ?? false, tool });
3427
3516
  this.dirty = true;
3428
3517
  }
3429
3518
  pruneTool(name) {
@@ -3465,14 +3554,14 @@ async function resolveEnvelopeParts(ctx, extra) {
3465
3554
  const session = await resolveSessionId(ctx.fallbackSessionId, extra);
3466
3555
  return { ...session, scrubbedMeta };
3467
3556
  }
3468
- async function openCall(ctx, toolName, extra, params, stripped, registered = true) {
3557
+ async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn") {
3469
3558
  await maybeEmitSurfaceSnapshot(ctx);
3470
3559
  const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
3471
3560
  const dispositions = ctx.paramRegistry.get(toolName);
3472
- const rawIntent = stripped[USER_GOAL_PARAM_NAME] ?? extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
3561
+ const rawIntent = stripped[USER_GOAL_PARAM_NAME] ?? extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, unlisted);
3473
3562
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
3474
3563
  const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
3475
- (name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
3564
+ (name) => dispositions === void 0 || dispositions[name] === "native" || unlisted === "leave" || unlisted === "goalOnly" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
3476
3565
  );
3477
3566
  const client = observeClient(extra, ctx);
3478
3567
  const caller = await resolveCaller(
@@ -3518,7 +3607,7 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
3518
3607
  );
3519
3608
  return { common, session, resultCaptureMode };
3520
3609
  }
3521
- function batonWrap(nameRef, original, ctx) {
3610
+ function batonWrap(nameRef, original, ctx, unlisted = "warn") {
3522
3611
  return async (...callArgs) => {
3523
3612
  const toolName = nameRef.current;
3524
3613
  const slot = callSlots.getStore();
@@ -3527,7 +3616,7 @@ function batonWrap(nameRef, original, ctx) {
3527
3616
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
3528
3617
  const stripped = slot?.strippedFor === toolName ? slot.stripped : {};
3529
3618
  if (slot) slot.strippedFor = null;
3530
- const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped);
3619
+ const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped, unlisted);
3531
3620
  const terminate = async (build, replacement) => {
3532
3621
  if (!slot) {
3533
3622
  if (build !== null) await emit(ctx.sink, build);
@@ -3685,11 +3774,12 @@ function batonWrap(nameRef, original, ctx) {
3685
3774
  return result;
3686
3775
  };
3687
3776
  }
3688
- function extractGoalParam(args, paramName, toolName, dispositions, registered) {
3777
+ function extractGoalParam(args, paramName, toolName, dispositions, unlisted) {
3689
3778
  if (!(paramName in args)) return null;
3690
3779
  const disposition = dispositions ? dispositions[paramName] : void 0;
3691
3780
  if (disposition === "native") return null;
3692
- if (disposition === void 0 && registered) {
3781
+ if (disposition === void 0 && unlisted === "leave") return null;
3782
+ if (disposition === void 0 && unlisted === "warn") {
3693
3783
  process.stderr.write(
3694
3784
  `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
3695
3785
  `
@@ -3814,6 +3904,183 @@ function installToolsListSeam(lowLevel, ctx) {
3814
3904
  return isThenable(out) ? out.then(advertise) : advertise(out);
3815
3905
  });
3816
3906
  }
3907
+ var LOW_LEVEL_LIST_SEAM = /* @__PURE__ */ Symbol("batonLowLevelListSeam");
3908
+ var LOW_LEVEL_CALL_SEAM = /* @__PURE__ */ Symbol("batonLowLevelCallSeam");
3909
+ var LOW_LEVEL_HANDSHAKE_SEAM = /* @__PURE__ */ Symbol("batonLowLevelHandshakeSeam");
3910
+ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce2, reportToolTaken) {
3911
+ let reportTool2 = annotationTool;
3912
+ const listedReportTool = reportTool2 && {
3913
+ name: reportTool2.name,
3914
+ description: reportTool2.description,
3915
+ inputSchema: annotationInputJsonSchema(lowLevelMajor(lowLevel))
3916
+ };
3917
+ const skipTool = (name, err) => {
3918
+ known.unread.add(name);
3919
+ warnOnce2(
3920
+ `tool-unread:${name}`,
3921
+ `baton: could not read tool ${JSON.stringify(name)}; its calls keep user_goal until Baton can read it: ${printable(err)}
3922
+ `
3923
+ );
3924
+ };
3925
+ const skipNote = (name, err) => {
3926
+ if (known.unread.has(name)) return;
3927
+ warnOnce2(`tool-unnoted:${name}`, `baton: could not note tool ${JSON.stringify(name)}; Baton adds no user_goal to it: ${printable(err)}
3928
+ `);
3929
+ };
3930
+ const keepGoalIfDeclared = (tools) => {
3931
+ for (const { name, inputSchema: inputSchema2 } of tools) {
3932
+ try {
3933
+ const checked = known.served.get(name)?.inputSchema === inputSchema2 && !known.unread.has(name);
3934
+ if (!known.keepsGoal.has(name) && !checked) {
3935
+ const declares = isRecord(inputSchema2) && takesUserGoalJson(inputSchema2) ? declaresParam : mayDeclareParam;
3936
+ if (declares(inputSchema2, USER_GOAL_PARAM_NAME)) known.keepsGoal.add(name);
3937
+ }
3938
+ known.unread.delete(name);
3939
+ } catch (err) {
3940
+ skipTool(name, err);
3941
+ }
3942
+ }
3943
+ };
3944
+ const read = (tools, { surface }) => {
3945
+ if (surface && reportTool2 !== void 0 && tools.some((tool) => tool.name === reportTool2?.name)) {
3946
+ warnOnce2(
3947
+ "report-tool-name-taken",
3948
+ `baton: the server lists its own tool ${JSON.stringify(reportTool2.name)}, so Baton's report tool is not added; set annotationToolName to another name
3949
+ `
3950
+ );
3951
+ reportTool2 = void 0;
3952
+ ctx.annotationToolName = "";
3953
+ reportToolTaken();
3954
+ }
3955
+ readToolList(tools, ctx, surface, skipNote);
3956
+ };
3957
+ const learn = (tools) => {
3958
+ keepGoalIfDeclared(tools);
3959
+ for (const tool of tools) {
3960
+ const held = known.served.get(tool.name);
3961
+ const ownGoal = (info) => declaresParam(info?.inputSchema, USER_GOAL_PARAM_NAME);
3962
+ if (held === void 0 || !ownGoal(held) || ownGoal(tool)) known.served.set(tool.name, tool);
3963
+ }
3964
+ };
3965
+ let caughtUp = false;
3966
+ const catchUp = () => {
3967
+ if (caughtUp) return;
3968
+ caughtUp = true;
3969
+ if (known.given !== void 0) {
3970
+ const given = known.given;
3971
+ known.given = void 0;
3972
+ try {
3973
+ const tools = typeof given === "function" ? given() : given;
3974
+ if (!Array.isArray(tools)) throw new Error("it is not an array of tools");
3975
+ known.givenTools = toolInfos(tools, skipTool);
3976
+ keepGoalIfDeclared(known.givenTools);
3977
+ } catch (err) {
3978
+ warnOnce2(
3979
+ "tools-unread",
3980
+ `baton: could not read the tools option; Baton learns the tools from tools/list: ${printable(err)}
3981
+ `
3982
+ );
3983
+ }
3984
+ }
3985
+ read(known.givenTools, { surface: true });
3986
+ read([...known.served.values()], { surface: false });
3987
+ };
3988
+ installRequestSeam(lowLevel, TOOLS_LIST_METHOD, LOW_LEVEL_LIST_SEAM, (handler) => async (...args) => {
3989
+ catchUp();
3990
+ const result = await handler(...args);
3991
+ try {
3992
+ const listed = listedTools(result);
3993
+ if (listed === null) return result;
3994
+ const tools = toolInfos(listed, skipTool);
3995
+ learn(tools);
3996
+ read(tools, { surface: true });
3997
+ const firstPage = args[0]?.params?.cursor === void 0;
3998
+ return servedToolList(result, listed, ctx, firstPage && reportTool2 ? listedReportTool : void 0);
3999
+ } catch (err) {
4000
+ process.stderr.write(`baton: tools/list capture failed; serving the vendor's own result: ${printable(err)}
4001
+ `);
4002
+ return result;
4003
+ }
4004
+ });
4005
+ const readFirst = (handler) => (...args) => {
4006
+ catchUp();
4007
+ return handler(...args);
4008
+ };
4009
+ installRequestSeam(lowLevel, "initialize", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);
4010
+ installRequestSeam(lowLevel, "server/discover", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);
4011
+ installRequestSeam(lowLevel, TOOLS_CALL_METHOD, LOW_LEVEL_CALL_SEAM, (handler) => async (...args) => {
4012
+ catchUp();
4013
+ ctx.perCaller?.followSettings();
4014
+ const request = args[0];
4015
+ const name = request?.params?.name;
4016
+ if (typeof name !== "string") return handler(...args);
4017
+ if (name === reportTool2?.name) return callAnnotationTool(reportTool2, request?.params?.arguments, args[1]);
4018
+ const injected = ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected";
4019
+ const unlisted = injected ? "warn" : known.keepsGoal.has(name) || known.unread.has(name) ? "leave" : "goalOnly";
4020
+ const params = request?.params?.arguments;
4021
+ const toolArgs = isRecord(params) ? params : {};
4022
+ if (unlisted === "goalOnly" && USER_GOAL_PARAM_NAME in toolArgs && !known.served.has(name) && !known.givenTools.some((tool) => tool.name === name)) {
4023
+ warnOnce2(
4024
+ "user-goal-unlisted",
4025
+ `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
4026
+ `
4027
+ );
4028
+ }
4029
+ if (request?.params?.task !== void 0) {
4030
+ if (injected) stripIntentParams(request.params, ctx);
4031
+ else extractGoalParam(toolArgs, USER_GOAL_PARAM_NAME, name, ctx.paramRegistry.get(name), unlisted);
4032
+ return handler(...args);
4033
+ }
4034
+ return batonWrap({ current: name }, () => handler(...args), ctx, unlisted)(toolArgs, args[1]);
4035
+ });
4036
+ }
4037
+ function lowLevelMajor(lowLevel) {
4038
+ return typeof lowLevel._wrapHandler === "function" ? 2 : 1;
4039
+ }
4040
+ function listedTools(result) {
4041
+ return isRecord(result) && Array.isArray(result.tools) ? result.tools : null;
4042
+ }
4043
+ function toolInfos(tools, skip) {
4044
+ const infos = [];
4045
+ for (const tool of tools) {
4046
+ let name;
4047
+ try {
4048
+ name = isRecord(tool) ? tool.name : void 0;
4049
+ if (typeof name !== "string") continue;
4050
+ infos.push({ name, description: tool.description, inputSchema: tool.inputSchema });
4051
+ } catch (err) {
4052
+ if (typeof name === "string") skip(name, err);
4053
+ }
4054
+ }
4055
+ return infos;
4056
+ }
4057
+ function readToolList(tools, ctx, surface, skip) {
4058
+ for (const { name, inputSchema: inputSchema2, description } of tools) {
4059
+ try {
4060
+ const schema = isRecord(inputSchema2) ? inputSchema2 : null;
4061
+ if (surface) {
4062
+ ctx.surfaceState.noteTool(name, schema ?? EMPTY_OBJECT_JSON_SCHEMA, typeof description === "string" ? description : void 0);
4063
+ }
4064
+ const dispositions = declaredIntentParams(schema);
4065
+ if (dispositions[USER_GOAL_PARAM_NAME] === "native") ctx.dropSubagentClause(name);
4066
+ else if (schema !== null && takesUserGoalJson(schema)) dispositions[USER_GOAL_PARAM_NAME] = "injected";
4067
+ if (Object.keys(dispositions).length > 0) ctx.paramRegistry.set(name, dispositions);
4068
+ else ctx.paramRegistry.delete(name);
4069
+ } catch (err) {
4070
+ ctx.paramRegistry.delete(name);
4071
+ skip(name, err);
4072
+ }
4073
+ }
4074
+ }
4075
+ function servedToolList(result, listed, ctx, reportTool2) {
4076
+ const tools = listed.map((tool) => {
4077
+ if (!isRecord(tool) || typeof tool.name !== "string") return tool;
4078
+ if (ctx.paramRegistry.get(tool.name)?.[USER_GOAL_PARAM_NAME] !== "injected") return tool;
4079
+ return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, ctx.intentParamMode, false) };
4080
+ });
4081
+ if (reportTool2 !== void 0) tools.push(reportTool2);
4082
+ return { ...result, tools };
4083
+ }
3817
4084
  var LIFECYCLE_SEAMS = {
3818
4085
  resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
3819
4086
  resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
@@ -4087,7 +4354,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
4087
4354
  args[1],
4088
4355
  params,
4089
4356
  slot.stripped,
4090
- entry != null
4357
+ entry != null ? "warn" : "quiet"
4091
4358
  );
4092
4359
  const failureKind = requestSideFailureKind(entry, slot.validation);
4093
4360
  const text = () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result);
@@ -4261,27 +4528,34 @@ function createBaton(supplied = {}) {
4261
4528
  function inertHandle(sink, sessionId) {
4262
4529
  return new BatonHandle({ sink, sessionId, vendorId: "", annotationToolName: "" });
4263
4530
  }
4264
- function requireHighLevelServer(server) {
4531
+ function serverShapeOf(server) {
4265
4532
  const candidate = server;
4266
- if (typeof candidate?.registerTool !== "function" || typeof candidate.server !== "object" || candidate.server === null) {
4267
- throw new TypeError(
4268
- "Baton needs a high-level McpServer (from @modelcontextprotocol/sdk/server/mcp.js or @modelcontextprotocol/server); the low-level Server is not supported."
4269
- );
4533
+ if (typeof candidate?.registerTool === "function" && typeof candidate.server === "object" && candidate.server !== null) {
4534
+ return "mcpServer";
4535
+ }
4536
+ const isServer = typeof candidate?._serverInfo === "object" && candidate._serverInfo !== null;
4537
+ if (typeof candidate?.setRequestHandler === "function" && candidate._requestHandlers instanceof Map && isServer) {
4538
+ return "lowLevel";
4270
4539
  }
4540
+ throw new TypeError(
4541
+ "Baton needs an McpServer or a low-level Server, from @modelcontextprotocol/sdk or @modelcontextprotocol/server."
4542
+ );
4271
4543
  }
4272
4544
  function newBatonState(config) {
4273
4545
  return {
4274
4546
  sentSurfaces: new SentSurfaces(),
4275
4547
  warned: /* @__PURE__ */ new Set(),
4276
4548
  counter: new SessionCounter(),
4277
- scrubber: config.scrubber ?? new Scrubber().scrub
4549
+ scrubber: config.scrubber ?? new Scrubber().scrub,
4550
+ lowLevelTools: { given: config.tools, givenTools: [], served: /* @__PURE__ */ new Map(), keepsGoal: /* @__PURE__ */ new Set(), unread: /* @__PURE__ */ new Set() }
4278
4551
  };
4279
4552
  }
4280
- function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber }, unconfigured) {
4281
- requireHighLevelServer(server);
4553
+ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber, lowLevelTools }, unconfigured) {
4554
+ const shape = serverShapeOf(server);
4282
4555
  const internals = server;
4556
+ const lowLevel = shape === "mcpServer" ? internals.server : server;
4283
4557
  const serverName = usableServerName(() => ({
4284
- name: internals.server._serverInfo?.name,
4558
+ name: lowLevel._serverInfo?.name,
4285
4559
  className: internals.constructor.name
4286
4560
  }));
4287
4561
  const config = resolved.reportMode === "on" ? withServerDisplayName(resolved, supplied, serverName) : resolved;
@@ -4295,7 +4569,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4295
4569
  const fallbackSessionId = `sdk-${uuid7()}`;
4296
4570
  const counter2 = new ServerCounter(sharedCounter, fallbackSessionId);
4297
4571
  const tenantId = resolveTenantId(config.tenantId, config.vendorId);
4298
- const serverMeta = buildServerMeta(server.server);
4572
+ const serverMeta = buildServerMeta(lowLevel);
4299
4573
  const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
4300
4574
  const emitSurface = async (sessionId, digest, snapshot) => {
4301
4575
  await emit(
@@ -4329,11 +4603,11 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4329
4603
  process.stderr.write(message);
4330
4604
  };
4331
4605
  const dropSubagentClause = (name) => {
4332
- const current2 = internals.server._instructions;
4606
+ const current2 = lowLevel._instructions;
4333
4607
  if (current2 === INTENT_INSTRUCTIONS) {
4334
- internals.server._instructions = "";
4608
+ lowLevel._instructions = "";
4335
4609
  } else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
4336
- internals.server._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
4610
+ lowLevel._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
4337
4611
  } else {
4338
4612
  return;
4339
4613
  }
@@ -4347,21 +4621,17 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4347
4621
  const vendorToolJsonSchema = (name, inputSchema2) => {
4348
4622
  if (isV2Server) {
4349
4623
  try {
4350
- const json = internals.toolInputSchemaJson(name);
4351
- if (json) return json;
4352
- } catch {
4353
- }
4354
- try {
4355
- const standard = inputSchema2?.["~standard"];
4356
- const json = standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
4357
- if (json) return json;
4624
+ const json2 = internals.toolInputSchemaJson(name);
4625
+ if (json2) return json2;
4358
4626
  } catch {
4359
4627
  }
4628
+ const json = standardInputJsonSchema(inputSchema2);
4629
+ if (json) return json;
4360
4630
  }
4361
4631
  try {
4362
4632
  return toolInputJsonSchema(inputSchema2);
4363
4633
  } catch {
4364
- return { type: "object", properties: {} };
4634
+ return EMPTY_OBJECT_JSON_SCHEMA;
4365
4635
  }
4366
4636
  };
4367
4637
  installValidationProbe(server);
@@ -4384,51 +4654,38 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4384
4654
  vendorToolJsonSchema,
4385
4655
  bustSchemaMemo,
4386
4656
  dropSubagentClause,
4387
- servedInstructions: () => internals.server._instructions,
4657
+ servedInstructions: () => lowLevel._instructions,
4388
4658
  surfaceState,
4389
4659
  emitSurface
4390
4660
  };
4391
4661
  const writeInstructions = (text) => {
4392
- internals.server._instructions = withVendorInstructions(
4393
- internals.server,
4662
+ lowLevel._instructions = withVendorInstructions(
4663
+ lowLevel,
4394
4664
  text,
4395
4665
  (message) => warnOnce2("instructions-length", message)
4396
4666
  );
4397
4667
  };
4398
4668
  writeInstructions(ours);
4669
+ const rewriteInstructions = (text) => {
4670
+ writeInstructions(text);
4671
+ const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === "native");
4672
+ if (native !== void 0) dropSubagentClause(native[0]);
4673
+ };
4399
4674
  if (config.captureSettings !== void 0) {
4400
4675
  ctx.perCaller = new PerCallerSurface({
4401
4676
  settings: config.captureSettings,
4402
4677
  intentParamMode,
4403
- annotationToolName,
4404
- instructions: ours,
4405
- writeInstructions: (text) => {
4406
- writeInstructions(text);
4407
- const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === "native");
4408
- if (native !== void 0) dropSubagentClause(native[0]);
4678
+ // Read, not copied: a low-level Server's own tool can take the name.
4679
+ get annotationToolName() {
4680
+ return ctx.annotationToolName;
4409
4681
  },
4682
+ instructions: ours,
4683
+ writeInstructions: rewriteInstructions,
4410
4684
  injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
4411
4685
  });
4412
4686
  ctx.perCaller.followSettings();
4413
4687
  }
4414
- installToolsListSeam(internals.server, ctx);
4415
- installToolsCallSeam(
4416
- internals.server,
4417
- // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
4418
- // object, so `registry["constructor"]` answers `Object` and
4419
- // `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
4420
- // so the "a tool we did not wrap" guard would decline to report, and a
4421
- // caller-visible `Tool constructor disabled` would reach the client with
4422
- // this seam silent. An agent hallucinating a prototype-shaped tool name is
4423
- // exactly the kind of failure the seam exists to make visible.
4424
- (name) => {
4425
- const registry = internals._registeredTools;
4426
- return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
4427
- },
4428
- ctx
4429
- );
4430
- installLifecycleSeams(internals.server, ctx);
4431
- const resolvedAnnotationToolName = !reports ? "" : registerAnnotationTool(server, {
4688
+ const annotationOptions = !reports ? void 0 : {
4432
4689
  sink,
4433
4690
  counter: ctx.counter,
4434
4691
  tenantId: ctx.tenantId,
@@ -4443,7 +4700,43 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4443
4700
  // raw override and letting the registration re-derive would register
4444
4701
  // `srv-..._annotate` while the instructions name the server-derived one.
4445
4702
  annotationToolName
4703
+ };
4704
+ if (shape === "lowLevel") {
4705
+ installLowLevelToolSeams(
4706
+ lowLevel,
4707
+ ctx,
4708
+ annotationOptions && buildAnnotationTool(server, annotationOptions),
4709
+ lowLevelTools,
4710
+ warnOnce2,
4711
+ () => rewriteInstructions(INTENT_INSTRUCTIONS)
4712
+ );
4713
+ }
4714
+ installToolsListSeam(lowLevel, ctx);
4715
+ if (shape === "mcpServer") installToolsCallSeam(
4716
+ lowLevel,
4717
+ // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
4718
+ // object, so `registry["constructor"]` answers `Object` and
4719
+ // `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
4720
+ // so the "a tool we did not wrap" guard would decline to report, and a
4721
+ // caller-visible `Tool constructor disabled` would reach the client with
4722
+ // this seam silent. An agent hallucinating a prototype-shaped tool name is
4723
+ // exactly the kind of failure the seam exists to make visible.
4724
+ (name) => {
4725
+ const registry = internals._registeredTools;
4726
+ return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
4727
+ },
4728
+ ctx
4729
+ );
4730
+ installLifecycleSeams(lowLevel, ctx);
4731
+ const handle = (name) => new BatonHandle({
4732
+ sink: given,
4733
+ queue: sink,
4734
+ vendorId: config.vendorId,
4735
+ sessionId: fallbackSessionId,
4736
+ annotationToolName: name
4446
4737
  });
4738
+ if (shape === "lowLevel") return handle(annotationToolName);
4739
+ const resolvedAnnotationToolName = annotationOptions ? registerAnnotationTool(server, annotationOptions) : "";
4447
4740
  const existing = internals._registeredTools;
4448
4741
  if (existing) {
4449
4742
  for (const [name, entry] of Object.entries(existing)) {
@@ -4456,13 +4749,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4456
4749
  wireEntry(String(args[0]), registered, ctx);
4457
4750
  return registered;
4458
4751
  };
4459
- return new BatonHandle({
4460
- sink: given,
4461
- queue: sink,
4462
- vendorId: config.vendorId,
4463
- sessionId: fallbackSessionId,
4464
- annotationToolName: resolvedAnnotationToolName
4465
- });
4752
+ return handle(resolvedAnnotationToolName);
4466
4753
  }
4467
4754
  function reportsFor(config) {
4468
4755
  if (config.reportMode !== "on") return void 0;
@@ -4622,25 +4909,8 @@ function snapshotPayload({ surface, digest }) {
4622
4909
  };
4623
4910
  }
4624
4911
  function servedEntry(tool) {
4625
- if (!isRecord(tool)) return tool;
4626
- const entry = { ...tool };
4627
- if (isRecord(entry.inputSchema)) {
4628
- const schema = { ...entry.inputSchema };
4629
- if (isRecord(schema.properties)) schema.properties = { ...schema.properties };
4630
- injectGoalParam(schema);
4631
- entry.inputSchema = schema;
4632
- }
4633
- return entry;
4634
- }
4635
- function injectGoalParam(schema) {
4636
- if (schema.properties === void 0) schema.properties = {};
4637
- if (!isRecord(schema.properties) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return;
4638
- schema.properties[USER_GOAL_PARAM_NAME] = {
4639
- type: "string",
4640
- description: buildUserGoalParamDescription({ intentParamMode: DEFAULT_INTENT_PARAM_MODE })
4641
- };
4642
- const required = Array.isArray(schema.required) ? schema.required : [];
4643
- if (!required.includes(USER_GOAL_PARAM_NAME)) schema.required = [...required, USER_GOAL_PARAM_NAME];
4912
+ if (!isRecord(tool) || !isRecord(tool.inputSchema)) return tool;
4913
+ return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, DEFAULT_INTENT_PARAM_MODE, true) };
4644
4914
  }
4645
4915
 
4646
4916
  // src/library/client.ts
@@ -4724,7 +4994,7 @@ function paramsOf(args) {
4724
4994
  var Core = class {
4725
4995
  closed = false;
4726
4996
  // A snapshot describes the server, so it takes no block's session,
4727
- // principal or client: SPEC §11.5.1's join must not count it.
4997
+ // principal or client (SPEC §5.6 rule 7).
4728
4998
  surfaceSessionId = uuid7();
4729
4999
  sentSurfaces = new SentSurfaces();
4730
5000
  sink;