@goodtiming/baton-sdk 1.0.1 → 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.1";
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);
@@ -2204,6 +2236,176 @@ async function resolveIdentity(hook, call) {
2204
2236
  }
2205
2237
  }
2206
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
+
2207
2409
  // src/integrations/mcp/safeScrub.ts
2208
2410
  var warned2 = /* @__PURE__ */ new Set();
2209
2411
  function scrubOrNull(scrubber, value, field) {
@@ -2344,30 +2546,49 @@ function sessionIdFromHeader(extra) {
2344
2546
  // src/integrations/mcp/annotation.ts
2345
2547
  var TOOL_NAME_PARAM_NAME = "tool_name";
2346
2548
  var ANNOTATION_INPUT_SHAPE = {
2347
- user_goal: import_zod2.z.string(),
2348
- what_happened: import_zod2.z.string().optional(),
2549
+ user_goal: import_zod3.z.string(),
2550
+ what_happened: import_zod3.z.string().optional(),
2349
2551
  // Nullable so a report whose agent sends an explicit null is taken,
2350
2552
  // not rejected by validation.
2351
- tool_name: import_zod2.z.string().nullable().optional(),
2352
- suggested_improvement: import_zod2.z.string().optional(),
2353
- 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()
2354
2556
  };
2355
2557
  function isReport(whatHappened) {
2356
2558
  return typeof whatHappened === "string" && !isBlank(whatHappened);
2357
2559
  }
2358
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) {
2359
2583
  const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
2360
2584
  const description = buildAnnotationToolDescription({
2361
2585
  vendorDisplayName: options.vendorDisplayName
2362
2586
  });
2363
2587
  const refusal = buildRefusalText({ annotationToolName: name });
2364
- server.registerTool(
2588
+ return {
2365
2589
  name,
2366
- {
2367
- description,
2368
- inputSchema: ANNOTATION_INPUT_SHAPE
2369
- },
2370
- async (args, extra) => {
2590
+ description,
2591
+ handler: async (args, extra) => {
2371
2592
  const whatHappened = args.what_happened;
2372
2593
  if (!isReport(whatHappened)) {
2373
2594
  return {
@@ -2427,8 +2648,7 @@ function registerAnnotationTool(server, options) {
2427
2648
  );
2428
2649
  return { content: [{ type: "text", text: JSON.stringify({ ok: true }) }] };
2429
2650
  }
2430
- );
2431
- return name;
2651
+ };
2432
2652
  }
2433
2653
 
2434
2654
  // src/dsn.ts
@@ -2811,7 +3031,7 @@ var SettingsFetcher = class {
2811
3031
  this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
2812
3032
  this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
2813
3033
  this.refreshMs = options.refreshMs;
2814
- this.fetchImpl = options.fetchImpl ?? fetch;
3034
+ this.fetchImpl = options.fetchImpl ?? globalFetch;
2815
3035
  }
2816
3036
  get document() {
2817
3037
  return this.held;
@@ -2909,19 +3129,31 @@ function resolveInstallConfig(config) {
2909
3129
  );
2910
3130
  return { resolved, unconfigured };
2911
3131
  }
2912
- 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) {
2913
3144
  const dsnString = selectDsn(
2914
- config.dsn,
3145
+ supplied.dsn,
2915
3146
  {
2916
3147
  // Truthiness per field, mirroring Python's `bool()` / `is not None`
2917
3148
  // split: an empty `vendorId` is an unset one, while an explicitly
2918
3149
  // supplied `tenantId` or `sink` is a conflict whatever it holds.
2919
- vendorId: Boolean(config.vendorId),
2920
- tenantId: config.tenantId !== void 0,
2921
- sink: config.sink !== void 0
3150
+ vendorId: Boolean(supplied.vendorId),
3151
+ tenantId: supplied.tenantId !== void 0,
3152
+ sink: supplied.sink !== void 0
2922
3153
  },
2923
3154
  "BatonConfig"
2924
3155
  );
3156
+ const config = dsnString === void 0 ? supplied : withoutConsoleOnWorkers(supplied);
2925
3157
  if (dsnString === void 0) {
2926
3158
  const defaulted = {
2927
3159
  ...config,
@@ -3056,6 +3288,9 @@ function validateBatonConfig(config) {
3056
3288
  if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
3057
3289
  throw new Error("BatonConfig.resolvePrincipal must be a function.");
3058
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
+ }
3059
3294
  }
3060
3295
 
3061
3296
  // src/optout.ts
@@ -3242,154 +3477,6 @@ var ServerCounter = class extends SessionCounter {
3242
3477
  }
3243
3478
  };
3244
3479
 
3245
- // src/integrations/mcp/zodCompat.ts
3246
- var z3rt = __toESM(require("zod/v3"), 1);
3247
- var z4mini = __toESM(require("zod/v4-mini"), 1);
3248
- var import_zod_to_json_schema = require("zod-to-json-schema");
3249
- function isZ4Schema(s) {
3250
- const schema = s;
3251
- return !!schema?._zod;
3252
- }
3253
- function objectFromShape(shape) {
3254
- const values = Object.values(shape);
3255
- if (values.length === 0) return z4mini.object({});
3256
- const allV4 = values.every(isZ4Schema);
3257
- const allV3 = values.every((s) => !isZ4Schema(s));
3258
- if (allV4) return z4mini.object(shape);
3259
- if (allV3) return z3rt.object(shape);
3260
- throw new Error("Mixed Zod versions detected in object shape.");
3261
- }
3262
- function getObjectShape(schema) {
3263
- if (!schema) return void 0;
3264
- let rawShape;
3265
- if (isZ4Schema(schema)) {
3266
- rawShape = schema._zod?.def?.shape;
3267
- } else {
3268
- rawShape = schema.shape;
3269
- }
3270
- if (!rawShape) return void 0;
3271
- if (typeof rawShape === "function") {
3272
- try {
3273
- return rawShape();
3274
- } catch {
3275
- return void 0;
3276
- }
3277
- }
3278
- return rawShape;
3279
- }
3280
- function normalizeObjectSchema(schema) {
3281
- if (!schema) return void 0;
3282
- if (typeof schema === "object") {
3283
- const asAny = schema;
3284
- if (!asAny._def && !asAny._zod) {
3285
- const values = Object.values(schema);
3286
- if (values.length > 0 && values.every(
3287
- (v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function")
3288
- )) {
3289
- return objectFromShape(schema);
3290
- }
3291
- }
3292
- }
3293
- if (isZ4Schema(schema)) {
3294
- const def = schema._zod?.def;
3295
- if (def && (def.type === "object" || def.shape !== void 0)) return schema;
3296
- } else {
3297
- if (schema.shape !== void 0) return schema;
3298
- }
3299
- return void 0;
3300
- }
3301
- function mapMiniTarget(t) {
3302
- if (!t) return "draft-7";
3303
- if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
3304
- if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
3305
- return "draft-7";
3306
- }
3307
- function toJsonSchemaCompat(schema, opts) {
3308
- if (isZ4Schema(schema)) {
3309
- return z4mini.toJSONSchema(schema, {
3310
- target: mapMiniTarget(opts?.target),
3311
- io: opts?.pipeStrategy ?? "input"
3312
- });
3313
- }
3314
- return (0, import_zod_to_json_schema.zodToJsonSchema)(schema, {
3315
- strictUnions: opts?.strictUnions ?? true,
3316
- pipeStrategy: opts?.pipeStrategy ?? "input"
3317
- });
3318
- }
3319
-
3320
- // src/integrations/mcp/schemaCompat.ts
3321
- var import_zod3 = require("zod");
3322
- var import_v3 = require("zod/v3");
3323
- var DEFAULT_INTENT_PARAM_MODE = "required";
3324
- var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
3325
- function injectGoalParams(inputSchema2, intentParamMode) {
3326
- const objSchema = normalizeObjectSchema(inputSchema2);
3327
- if (!objSchema) return { schema: inputSchema2, dispositions: {} };
3328
- const existingShape = getObjectShape(objSchema) ?? {};
3329
- const values = Object.values(existingShape);
3330
- const useV4 = values.length === 0 || isZ4Schema(values[0]);
3331
- const zodImpl = useV4 ? import_zod3.z : import_v3.z;
3332
- const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
3333
- if (Object.keys(toInject).length === 0)
3334
- return { schema: inputSchema2, dispositions };
3335
- const mergedShape = { ...existingShape, ...toInject };
3336
- const newSchema = objectFromShape(mergedShape);
3337
- return { schema: newSchema, dispositions };
3338
- }
3339
- function buildIntentFields(existingShape, zodImpl, intentParamMode) {
3340
- const dispositions = {};
3341
- const toInject = {};
3342
- for (const name of RETIRED_PARAM_NAMES) {
3343
- if (name in existingShape) dispositions[name] = "native";
3344
- }
3345
- if (USER_GOAL_PARAM_NAME in existingShape) {
3346
- dispositions[USER_GOAL_PARAM_NAME] = "native";
3347
- } else {
3348
- dispositions[USER_GOAL_PARAM_NAME] = "injected";
3349
- toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
3350
- }
3351
- return { dispositions, toInject };
3352
- }
3353
- function injectGoalParamsV2(inputSchema2, intentParamMode) {
3354
- const candidate = inputSchema2;
3355
- const shape = candidate?.shape;
3356
- if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
3357
- return { schema: inputSchema2, dispositions: {} };
3358
- }
3359
- const { dispositions, toInject } = buildIntentFields(shape, import_zod3.z, intentParamMode);
3360
- if (Object.keys(toInject).length === 0)
3361
- return { schema: inputSchema2, dispositions };
3362
- return { schema: candidate.extend(toInject), dispositions };
3363
- }
3364
- function advertiseIntentParamsRequired(result, names, isInjected) {
3365
- const tools = result?.tools;
3366
- if (!Array.isArray(tools)) return result;
3367
- let changed = false;
3368
- const advertised = tools.map((tool) => {
3369
- const entry = tool;
3370
- const toolName = entry?.name;
3371
- if (typeof toolName !== "string") return tool;
3372
- const schema = entry?.inputSchema;
3373
- if (!schema || typeof schema !== "object") return tool;
3374
- const declared2 = schema.required ?? [];
3375
- if (!Array.isArray(declared2)) return tool;
3376
- const required = declared2;
3377
- const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
3378
- if (missing.length === 0) return tool;
3379
- changed = true;
3380
- return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
3381
- });
3382
- return changed ? { ...result, tools: advertised } : result;
3383
- }
3384
- function toolInputJsonSchema(inputSchema2) {
3385
- const objSchema = normalizeObjectSchema(inputSchema2);
3386
- if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
3387
- return toJsonSchemaCompat(objSchema, {
3388
- strictUnions: true,
3389
- pipeStrategy: "input"
3390
- });
3391
- }
3392
-
3393
3480
  // src/integrations/mcp/surface.ts
3394
3481
  var import_node_crypto3 = require("crypto");
3395
3482
  function surfaceHash(surface) {
@@ -3473,10 +3560,13 @@ var SurfaceState = class {
3473
3560
  /** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
3474
3561
  * which picks the spelling THIS SDK major puts on the wire. */
3475
3562
  noteTool(name, inputSchemaJson, description) {
3476
- this.rawTools.set(name, {
3477
- disabled: this.rawTools.get(name)?.disabled ?? false,
3478
- tool: { name, description: description ?? null, inputSchema: inputSchemaJson }
3479
- });
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 });
3480
3570
  this.dirty = true;
3481
3571
  }
3482
3572
  pruneTool(name) {
@@ -3518,14 +3608,14 @@ async function resolveEnvelopeParts(ctx, extra) {
3518
3608
  const session = await resolveSessionId(ctx.fallbackSessionId, extra);
3519
3609
  return { ...session, scrubbedMeta };
3520
3610
  }
3521
- async function openCall(ctx, toolName, extra, params, stripped, registered = true) {
3611
+ async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn") {
3522
3612
  await maybeEmitSurfaceSnapshot(ctx);
3523
3613
  const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
3524
3614
  const dispositions = ctx.paramRegistry.get(toolName);
3525
- 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);
3526
3616
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
3527
3617
  const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
3528
- (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)
3529
3619
  );
3530
3620
  const client = observeClient(extra, ctx);
3531
3621
  const caller = await resolveCaller(
@@ -3571,7 +3661,7 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
3571
3661
  );
3572
3662
  return { common, session, resultCaptureMode };
3573
3663
  }
3574
- function batonWrap(nameRef, original, ctx) {
3664
+ function batonWrap(nameRef, original, ctx, unlisted = "warn") {
3575
3665
  return async (...callArgs) => {
3576
3666
  const toolName = nameRef.current;
3577
3667
  const slot = callSlots.getStore();
@@ -3580,7 +3670,7 @@ function batonWrap(nameRef, original, ctx) {
3580
3670
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
3581
3671
  const stripped = slot?.strippedFor === toolName ? slot.stripped : {};
3582
3672
  if (slot) slot.strippedFor = null;
3583
- const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped);
3673
+ const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped, unlisted);
3584
3674
  const terminate = async (build, replacement) => {
3585
3675
  if (!slot) {
3586
3676
  if (build !== null) await emit(ctx.sink, build);
@@ -3738,11 +3828,12 @@ function batonWrap(nameRef, original, ctx) {
3738
3828
  return result;
3739
3829
  };
3740
3830
  }
3741
- function extractGoalParam(args, paramName, toolName, dispositions, registered) {
3831
+ function extractGoalParam(args, paramName, toolName, dispositions, unlisted) {
3742
3832
  if (!(paramName in args)) return null;
3743
3833
  const disposition = dispositions ? dispositions[paramName] : void 0;
3744
3834
  if (disposition === "native") return null;
3745
- if (disposition === void 0 && registered) {
3835
+ if (disposition === void 0 && unlisted === "leave") return null;
3836
+ if (disposition === void 0 && unlisted === "warn") {
3746
3837
  process.stderr.write(
3747
3838
  `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
3748
3839
  `
@@ -3867,6 +3958,183 @@ function installToolsListSeam(lowLevel, ctx) {
3867
3958
  return isThenable(out) ? out.then(advertise) : advertise(out);
3868
3959
  });
3869
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
+ }
3870
4138
  var LIFECYCLE_SEAMS = {
3871
4139
  resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
3872
4140
  resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
@@ -4140,7 +4408,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
4140
4408
  args[1],
4141
4409
  params,
4142
4410
  slot.stripped,
4143
- entry != null
4411
+ entry != null ? "warn" : "quiet"
4144
4412
  );
4145
4413
  const failureKind = requestSideFailureKind(entry, slot.validation);
4146
4414
  const text = () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result);
@@ -4314,27 +4582,34 @@ function createBaton(supplied = {}) {
4314
4582
  function inertHandle(sink, sessionId) {
4315
4583
  return new BatonHandle({ sink, sessionId, vendorId: "", annotationToolName: "" });
4316
4584
  }
4317
- function requireHighLevelServer(server) {
4585
+ function serverShapeOf(server) {
4318
4586
  const candidate = server;
4319
- if (typeof candidate?.registerTool !== "function" || typeof candidate.server !== "object" || candidate.server === null) {
4320
- throw new TypeError(
4321
- "Baton needs a high-level McpServer (from @modelcontextprotocol/sdk/server/mcp.js or @modelcontextprotocol/server); the low-level Server is not supported."
4322
- );
4587
+ if (typeof candidate?.registerTool === "function" && typeof candidate.server === "object" && candidate.server !== null) {
4588
+ return "mcpServer";
4323
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
+ );
4324
4597
  }
4325
4598
  function newBatonState(config) {
4326
4599
  return {
4327
4600
  sentSurfaces: new SentSurfaces(),
4328
4601
  warned: /* @__PURE__ */ new Set(),
4329
4602
  counter: new SessionCounter(),
4330
- 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() }
4331
4605
  };
4332
4606
  }
4333
- function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber }, unconfigured) {
4334
- requireHighLevelServer(server);
4607
+ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber, lowLevelTools }, unconfigured) {
4608
+ const shape = serverShapeOf(server);
4335
4609
  const internals = server;
4610
+ const lowLevel = shape === "mcpServer" ? internals.server : server;
4336
4611
  const serverName = usableServerName(() => ({
4337
- name: internals.server._serverInfo?.name,
4612
+ name: lowLevel._serverInfo?.name,
4338
4613
  className: internals.constructor.name
4339
4614
  }));
4340
4615
  const config = resolved.reportMode === "on" ? withServerDisplayName(resolved, supplied, serverName) : resolved;
@@ -4348,7 +4623,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4348
4623
  const fallbackSessionId = `sdk-${uuid7()}`;
4349
4624
  const counter2 = new ServerCounter(sharedCounter, fallbackSessionId);
4350
4625
  const tenantId = resolveTenantId(config.tenantId, config.vendorId);
4351
- const serverMeta = buildServerMeta(server.server);
4626
+ const serverMeta = buildServerMeta(lowLevel);
4352
4627
  const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
4353
4628
  const emitSurface = async (sessionId, digest, snapshot) => {
4354
4629
  await emit(
@@ -4382,11 +4657,11 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4382
4657
  process.stderr.write(message);
4383
4658
  };
4384
4659
  const dropSubagentClause = (name) => {
4385
- const current2 = internals.server._instructions;
4660
+ const current2 = lowLevel._instructions;
4386
4661
  if (current2 === INTENT_INSTRUCTIONS) {
4387
- internals.server._instructions = "";
4662
+ lowLevel._instructions = "";
4388
4663
  } else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
4389
- internals.server._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
4664
+ lowLevel._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
4390
4665
  } else {
4391
4666
  return;
4392
4667
  }
@@ -4400,21 +4675,17 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4400
4675
  const vendorToolJsonSchema = (name, inputSchema2) => {
4401
4676
  if (isV2Server) {
4402
4677
  try {
4403
- const json = internals.toolInputSchemaJson(name);
4404
- if (json) return json;
4405
- } catch {
4406
- }
4407
- try {
4408
- const standard = inputSchema2?.["~standard"];
4409
- const json = standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
4410
- if (json) return json;
4678
+ const json2 = internals.toolInputSchemaJson(name);
4679
+ if (json2) return json2;
4411
4680
  } catch {
4412
4681
  }
4682
+ const json = standardInputJsonSchema(inputSchema2);
4683
+ if (json) return json;
4413
4684
  }
4414
4685
  try {
4415
4686
  return toolInputJsonSchema(inputSchema2);
4416
4687
  } catch {
4417
- return { type: "object", properties: {} };
4688
+ return EMPTY_OBJECT_JSON_SCHEMA;
4418
4689
  }
4419
4690
  };
4420
4691
  installValidationProbe(server);
@@ -4437,51 +4708,38 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4437
4708
  vendorToolJsonSchema,
4438
4709
  bustSchemaMemo,
4439
4710
  dropSubagentClause,
4440
- servedInstructions: () => internals.server._instructions,
4711
+ servedInstructions: () => lowLevel._instructions,
4441
4712
  surfaceState,
4442
4713
  emitSurface
4443
4714
  };
4444
4715
  const writeInstructions = (text) => {
4445
- internals.server._instructions = withVendorInstructions(
4446
- internals.server,
4716
+ lowLevel._instructions = withVendorInstructions(
4717
+ lowLevel,
4447
4718
  text,
4448
4719
  (message) => warnOnce2("instructions-length", message)
4449
4720
  );
4450
4721
  };
4451
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
+ };
4452
4728
  if (config.captureSettings !== void 0) {
4453
4729
  ctx.perCaller = new PerCallerSurface({
4454
4730
  settings: config.captureSettings,
4455
4731
  intentParamMode,
4456
- annotationToolName,
4457
- instructions: ours,
4458
- writeInstructions: (text) => {
4459
- writeInstructions(text);
4460
- const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === "native");
4461
- 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;
4462
4735
  },
4736
+ instructions: ours,
4737
+ writeInstructions: rewriteInstructions,
4463
4738
  injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
4464
4739
  });
4465
4740
  ctx.perCaller.followSettings();
4466
4741
  }
4467
- installToolsListSeam(internals.server, ctx);
4468
- installToolsCallSeam(
4469
- internals.server,
4470
- // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
4471
- // object, so `registry["constructor"]` answers `Object` and
4472
- // `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
4473
- // so the "a tool we did not wrap" guard would decline to report, and a
4474
- // caller-visible `Tool constructor disabled` would reach the client with
4475
- // this seam silent. An agent hallucinating a prototype-shaped tool name is
4476
- // exactly the kind of failure the seam exists to make visible.
4477
- (name) => {
4478
- const registry = internals._registeredTools;
4479
- return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
4480
- },
4481
- ctx
4482
- );
4483
- installLifecycleSeams(internals.server, ctx);
4484
- const resolvedAnnotationToolName = !reports ? "" : registerAnnotationTool(server, {
4742
+ const annotationOptions = !reports ? void 0 : {
4485
4743
  sink,
4486
4744
  counter: ctx.counter,
4487
4745
  tenantId: ctx.tenantId,
@@ -4496,7 +4754,43 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4496
4754
  // raw override and letting the registration re-derive would register
4497
4755
  // `srv-..._annotate` while the instructions name the server-derived one.
4498
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
4499
4791
  });
4792
+ if (shape === "lowLevel") return handle(annotationToolName);
4793
+ const resolvedAnnotationToolName = annotationOptions ? registerAnnotationTool(server, annotationOptions) : "";
4500
4794
  const existing = internals._registeredTools;
4501
4795
  if (existing) {
4502
4796
  for (const [name, entry] of Object.entries(existing)) {
@@ -4509,13 +4803,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
4509
4803
  wireEntry(String(args[0]), registered, ctx);
4510
4804
  return registered;
4511
4805
  };
4512
- return new BatonHandle({
4513
- sink: given,
4514
- queue: sink,
4515
- vendorId: config.vendorId,
4516
- sessionId: fallbackSessionId,
4517
- annotationToolName: resolvedAnnotationToolName
4518
- });
4806
+ return handle(resolvedAnnotationToolName);
4519
4807
  }
4520
4808
  function reportsFor(config) {
4521
4809
  if (config.reportMode !== "on") return void 0;
@@ -4675,25 +4963,8 @@ function snapshotPayload({ surface, digest }) {
4675
4963
  };
4676
4964
  }
4677
4965
  function servedEntry(tool) {
4678
- if (!isRecord(tool)) return tool;
4679
- const entry = { ...tool };
4680
- if (isRecord(entry.inputSchema)) {
4681
- const schema = { ...entry.inputSchema };
4682
- if (isRecord(schema.properties)) schema.properties = { ...schema.properties };
4683
- injectGoalParam(schema);
4684
- entry.inputSchema = schema;
4685
- }
4686
- return entry;
4687
- }
4688
- function injectGoalParam(schema) {
4689
- if (schema.properties === void 0) schema.properties = {};
4690
- if (!isRecord(schema.properties) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return;
4691
- schema.properties[USER_GOAL_PARAM_NAME] = {
4692
- type: "string",
4693
- description: buildUserGoalParamDescription({ intentParamMode: DEFAULT_INTENT_PARAM_MODE })
4694
- };
4695
- const required = Array.isArray(schema.required) ? schema.required : [];
4696
- 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) };
4697
4968
  }
4698
4969
 
4699
4970
  // src/library/client.ts