@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/README.md +43 -2
- package/dist/index.cjs +539 -268
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +29 -10
- package/dist/index.d.ts +29 -10
- package/dist/index.js +533 -262
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/version.ts
|
|
2
|
-
var SDK_VERSION = "ts-1.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 (
|
|
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
|
-
|
|
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 =
|
|
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
|
|
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 ??
|
|
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
|
-
|
|
1116
|
-
|
|
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
|
|
1369
|
-
|
|
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);
|
|
@@ -2150,6 +2182,176 @@ async function resolveIdentity(hook, call) {
|
|
|
2150
2182
|
}
|
|
2151
2183
|
}
|
|
2152
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
|
+
|
|
2153
2355
|
// src/integrations/mcp/safeScrub.ts
|
|
2154
2356
|
var warned2 = /* @__PURE__ */ new Set();
|
|
2155
2357
|
function scrubOrNull(scrubber, value, field) {
|
|
@@ -2302,18 +2504,37 @@ function isReport(whatHappened) {
|
|
|
2302
2504
|
return typeof whatHappened === "string" && !isBlank(whatHappened);
|
|
2303
2505
|
}
|
|
2304
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) {
|
|
2305
2529
|
const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
|
|
2306
2530
|
const description = buildAnnotationToolDescription({
|
|
2307
2531
|
vendorDisplayName: options.vendorDisplayName
|
|
2308
2532
|
});
|
|
2309
2533
|
const refusal = buildRefusalText({ annotationToolName: name });
|
|
2310
|
-
|
|
2534
|
+
return {
|
|
2311
2535
|
name,
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
inputSchema: ANNOTATION_INPUT_SHAPE
|
|
2315
|
-
},
|
|
2316
|
-
async (args, extra) => {
|
|
2536
|
+
description,
|
|
2537
|
+
handler: async (args, extra) => {
|
|
2317
2538
|
const whatHappened = args.what_happened;
|
|
2318
2539
|
if (!isReport(whatHappened)) {
|
|
2319
2540
|
return {
|
|
@@ -2373,8 +2594,7 @@ function registerAnnotationTool(server, options) {
|
|
|
2373
2594
|
);
|
|
2374
2595
|
return { content: [{ type: "text", text: JSON.stringify({ ok: true }) }] };
|
|
2375
2596
|
}
|
|
2376
|
-
|
|
2377
|
-
return name;
|
|
2597
|
+
};
|
|
2378
2598
|
}
|
|
2379
2599
|
|
|
2380
2600
|
// src/dsn.ts
|
|
@@ -2757,7 +2977,7 @@ var SettingsFetcher = class {
|
|
|
2757
2977
|
this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
|
|
2758
2978
|
this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
|
|
2759
2979
|
this.refreshMs = options.refreshMs;
|
|
2760
|
-
this.fetchImpl = options.fetchImpl ??
|
|
2980
|
+
this.fetchImpl = options.fetchImpl ?? globalFetch;
|
|
2761
2981
|
}
|
|
2762
2982
|
get document() {
|
|
2763
2983
|
return this.held;
|
|
@@ -2855,19 +3075,31 @@ function resolveInstallConfig(config) {
|
|
|
2855
3075
|
);
|
|
2856
3076
|
return { resolved, unconfigured };
|
|
2857
3077
|
}
|
|
2858
|
-
|
|
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) {
|
|
2859
3090
|
const dsnString = selectDsn(
|
|
2860
|
-
|
|
3091
|
+
supplied.dsn,
|
|
2861
3092
|
{
|
|
2862
3093
|
// Truthiness per field, mirroring Python's `bool()` / `is not None`
|
|
2863
3094
|
// split: an empty `vendorId` is an unset one, while an explicitly
|
|
2864
3095
|
// supplied `tenantId` or `sink` is a conflict whatever it holds.
|
|
2865
|
-
vendorId: Boolean(
|
|
2866
|
-
tenantId:
|
|
2867
|
-
sink:
|
|
3096
|
+
vendorId: Boolean(supplied.vendorId),
|
|
3097
|
+
tenantId: supplied.tenantId !== void 0,
|
|
3098
|
+
sink: supplied.sink !== void 0
|
|
2868
3099
|
},
|
|
2869
3100
|
"BatonConfig"
|
|
2870
3101
|
);
|
|
3102
|
+
const config = dsnString === void 0 ? supplied : withoutConsoleOnWorkers(supplied);
|
|
2871
3103
|
if (dsnString === void 0) {
|
|
2872
3104
|
const defaulted = {
|
|
2873
3105
|
...config,
|
|
@@ -3002,6 +3234,9 @@ function validateBatonConfig(config) {
|
|
|
3002
3234
|
if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
|
|
3003
3235
|
throw new Error("BatonConfig.resolvePrincipal must be a function.");
|
|
3004
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
|
+
}
|
|
3005
3240
|
}
|
|
3006
3241
|
|
|
3007
3242
|
// src/optout.ts
|
|
@@ -3188,154 +3423,6 @@ var ServerCounter = class extends SessionCounter {
|
|
|
3188
3423
|
}
|
|
3189
3424
|
};
|
|
3190
3425
|
|
|
3191
|
-
// src/integrations/mcp/zodCompat.ts
|
|
3192
|
-
import * as z3rt from "zod/v3";
|
|
3193
|
-
import * as z4mini from "zod/v4-mini";
|
|
3194
|
-
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
3195
|
-
function isZ4Schema(s) {
|
|
3196
|
-
const schema = s;
|
|
3197
|
-
return !!schema?._zod;
|
|
3198
|
-
}
|
|
3199
|
-
function objectFromShape(shape) {
|
|
3200
|
-
const values = Object.values(shape);
|
|
3201
|
-
if (values.length === 0) return z4mini.object({});
|
|
3202
|
-
const allV4 = values.every(isZ4Schema);
|
|
3203
|
-
const allV3 = values.every((s) => !isZ4Schema(s));
|
|
3204
|
-
if (allV4) return z4mini.object(shape);
|
|
3205
|
-
if (allV3) return z3rt.object(shape);
|
|
3206
|
-
throw new Error("Mixed Zod versions detected in object shape.");
|
|
3207
|
-
}
|
|
3208
|
-
function getObjectShape(schema) {
|
|
3209
|
-
if (!schema) return void 0;
|
|
3210
|
-
let rawShape;
|
|
3211
|
-
if (isZ4Schema(schema)) {
|
|
3212
|
-
rawShape = schema._zod?.def?.shape;
|
|
3213
|
-
} else {
|
|
3214
|
-
rawShape = schema.shape;
|
|
3215
|
-
}
|
|
3216
|
-
if (!rawShape) return void 0;
|
|
3217
|
-
if (typeof rawShape === "function") {
|
|
3218
|
-
try {
|
|
3219
|
-
return rawShape();
|
|
3220
|
-
} catch {
|
|
3221
|
-
return void 0;
|
|
3222
|
-
}
|
|
3223
|
-
}
|
|
3224
|
-
return rawShape;
|
|
3225
|
-
}
|
|
3226
|
-
function normalizeObjectSchema(schema) {
|
|
3227
|
-
if (!schema) return void 0;
|
|
3228
|
-
if (typeof schema === "object") {
|
|
3229
|
-
const asAny = schema;
|
|
3230
|
-
if (!asAny._def && !asAny._zod) {
|
|
3231
|
-
const values = Object.values(schema);
|
|
3232
|
-
if (values.length > 0 && values.every(
|
|
3233
|
-
(v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function")
|
|
3234
|
-
)) {
|
|
3235
|
-
return objectFromShape(schema);
|
|
3236
|
-
}
|
|
3237
|
-
}
|
|
3238
|
-
}
|
|
3239
|
-
if (isZ4Schema(schema)) {
|
|
3240
|
-
const def = schema._zod?.def;
|
|
3241
|
-
if (def && (def.type === "object" || def.shape !== void 0)) return schema;
|
|
3242
|
-
} else {
|
|
3243
|
-
if (schema.shape !== void 0) return schema;
|
|
3244
|
-
}
|
|
3245
|
-
return void 0;
|
|
3246
|
-
}
|
|
3247
|
-
function mapMiniTarget(t) {
|
|
3248
|
-
if (!t) return "draft-7";
|
|
3249
|
-
if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
|
|
3250
|
-
if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
|
|
3251
|
-
return "draft-7";
|
|
3252
|
-
}
|
|
3253
|
-
function toJsonSchemaCompat(schema, opts) {
|
|
3254
|
-
if (isZ4Schema(schema)) {
|
|
3255
|
-
return z4mini.toJSONSchema(schema, {
|
|
3256
|
-
target: mapMiniTarget(opts?.target),
|
|
3257
|
-
io: opts?.pipeStrategy ?? "input"
|
|
3258
|
-
});
|
|
3259
|
-
}
|
|
3260
|
-
return zodToJsonSchema(schema, {
|
|
3261
|
-
strictUnions: opts?.strictUnions ?? true,
|
|
3262
|
-
pipeStrategy: opts?.pipeStrategy ?? "input"
|
|
3263
|
-
});
|
|
3264
|
-
}
|
|
3265
|
-
|
|
3266
|
-
// src/integrations/mcp/schemaCompat.ts
|
|
3267
|
-
import { z as zV4 } from "zod";
|
|
3268
|
-
import { z as zV3 } from "zod/v3";
|
|
3269
|
-
var DEFAULT_INTENT_PARAM_MODE = "required";
|
|
3270
|
-
var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
|
|
3271
|
-
function injectGoalParams(inputSchema2, intentParamMode) {
|
|
3272
|
-
const objSchema = normalizeObjectSchema(inputSchema2);
|
|
3273
|
-
if (!objSchema) return { schema: inputSchema2, dispositions: {} };
|
|
3274
|
-
const existingShape = getObjectShape(objSchema) ?? {};
|
|
3275
|
-
const values = Object.values(existingShape);
|
|
3276
|
-
const useV4 = values.length === 0 || isZ4Schema(values[0]);
|
|
3277
|
-
const zodImpl = useV4 ? zV4 : zV3;
|
|
3278
|
-
const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
|
|
3279
|
-
if (Object.keys(toInject).length === 0)
|
|
3280
|
-
return { schema: inputSchema2, dispositions };
|
|
3281
|
-
const mergedShape = { ...existingShape, ...toInject };
|
|
3282
|
-
const newSchema = objectFromShape(mergedShape);
|
|
3283
|
-
return { schema: newSchema, dispositions };
|
|
3284
|
-
}
|
|
3285
|
-
function buildIntentFields(existingShape, zodImpl, intentParamMode) {
|
|
3286
|
-
const dispositions = {};
|
|
3287
|
-
const toInject = {};
|
|
3288
|
-
for (const name of RETIRED_PARAM_NAMES) {
|
|
3289
|
-
if (name in existingShape) dispositions[name] = "native";
|
|
3290
|
-
}
|
|
3291
|
-
if (USER_GOAL_PARAM_NAME in existingShape) {
|
|
3292
|
-
dispositions[USER_GOAL_PARAM_NAME] = "native";
|
|
3293
|
-
} else {
|
|
3294
|
-
dispositions[USER_GOAL_PARAM_NAME] = "injected";
|
|
3295
|
-
toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
|
|
3296
|
-
}
|
|
3297
|
-
return { dispositions, toInject };
|
|
3298
|
-
}
|
|
3299
|
-
function injectGoalParamsV2(inputSchema2, intentParamMode) {
|
|
3300
|
-
const candidate = inputSchema2;
|
|
3301
|
-
const shape = candidate?.shape;
|
|
3302
|
-
if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
|
|
3303
|
-
return { schema: inputSchema2, dispositions: {} };
|
|
3304
|
-
}
|
|
3305
|
-
const { dispositions, toInject } = buildIntentFields(shape, zV4, intentParamMode);
|
|
3306
|
-
if (Object.keys(toInject).length === 0)
|
|
3307
|
-
return { schema: inputSchema2, dispositions };
|
|
3308
|
-
return { schema: candidate.extend(toInject), dispositions };
|
|
3309
|
-
}
|
|
3310
|
-
function advertiseIntentParamsRequired(result, names, isInjected) {
|
|
3311
|
-
const tools = result?.tools;
|
|
3312
|
-
if (!Array.isArray(tools)) return result;
|
|
3313
|
-
let changed = false;
|
|
3314
|
-
const advertised = tools.map((tool) => {
|
|
3315
|
-
const entry = tool;
|
|
3316
|
-
const toolName = entry?.name;
|
|
3317
|
-
if (typeof toolName !== "string") return tool;
|
|
3318
|
-
const schema = entry?.inputSchema;
|
|
3319
|
-
if (!schema || typeof schema !== "object") return tool;
|
|
3320
|
-
const declared2 = schema.required ?? [];
|
|
3321
|
-
if (!Array.isArray(declared2)) return tool;
|
|
3322
|
-
const required = declared2;
|
|
3323
|
-
const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
|
|
3324
|
-
if (missing.length === 0) return tool;
|
|
3325
|
-
changed = true;
|
|
3326
|
-
return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
|
|
3327
|
-
});
|
|
3328
|
-
return changed ? { ...result, tools: advertised } : result;
|
|
3329
|
-
}
|
|
3330
|
-
function toolInputJsonSchema(inputSchema2) {
|
|
3331
|
-
const objSchema = normalizeObjectSchema(inputSchema2);
|
|
3332
|
-
if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
|
|
3333
|
-
return toJsonSchemaCompat(objSchema, {
|
|
3334
|
-
strictUnions: true,
|
|
3335
|
-
pipeStrategy: "input"
|
|
3336
|
-
});
|
|
3337
|
-
}
|
|
3338
|
-
|
|
3339
3426
|
// src/integrations/mcp/surface.ts
|
|
3340
3427
|
import { createHash as createHash2 } from "crypto";
|
|
3341
3428
|
function surfaceHash(surface) {
|
|
@@ -3419,10 +3506,13 @@ var SurfaceState = class {
|
|
|
3419
3506
|
/** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
|
|
3420
3507
|
* which picks the spelling THIS SDK major puts on the wire. */
|
|
3421
3508
|
noteTool(name, inputSchemaJson, description) {
|
|
3422
|
-
this.rawTools.
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
|
|
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 });
|
|
3426
3516
|
this.dirty = true;
|
|
3427
3517
|
}
|
|
3428
3518
|
pruneTool(name) {
|
|
@@ -3464,14 +3554,14 @@ async function resolveEnvelopeParts(ctx, extra) {
|
|
|
3464
3554
|
const session = await resolveSessionId(ctx.fallbackSessionId, extra);
|
|
3465
3555
|
return { ...session, scrubbedMeta };
|
|
3466
3556
|
}
|
|
3467
|
-
async function openCall(ctx, toolName, extra, params, stripped,
|
|
3557
|
+
async function openCall(ctx, toolName, extra, params, stripped, unlisted = "warn") {
|
|
3468
3558
|
await maybeEmitSurfaceSnapshot(ctx);
|
|
3469
3559
|
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
3470
3560
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
3471
|
-
const rawIntent = stripped[USER_GOAL_PARAM_NAME] ?? extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions,
|
|
3561
|
+
const rawIntent = stripped[USER_GOAL_PARAM_NAME] ?? extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, unlisted);
|
|
3472
3562
|
const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
|
|
3473
3563
|
const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
|
|
3474
|
-
(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)
|
|
3475
3565
|
);
|
|
3476
3566
|
const client = observeClient(extra, ctx);
|
|
3477
3567
|
const caller = await resolveCaller(
|
|
@@ -3517,7 +3607,7 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
|
|
|
3517
3607
|
);
|
|
3518
3608
|
return { common, session, resultCaptureMode };
|
|
3519
3609
|
}
|
|
3520
|
-
function batonWrap(nameRef, original, ctx) {
|
|
3610
|
+
function batonWrap(nameRef, original, ctx, unlisted = "warn") {
|
|
3521
3611
|
return async (...callArgs) => {
|
|
3522
3612
|
const toolName = nameRef.current;
|
|
3523
3613
|
const slot = callSlots.getStore();
|
|
@@ -3526,7 +3616,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
3526
3616
|
const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
|
|
3527
3617
|
const stripped = slot?.strippedFor === toolName ? slot.stripped : {};
|
|
3528
3618
|
if (slot) slot.strippedFor = null;
|
|
3529
|
-
const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped);
|
|
3619
|
+
const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped, unlisted);
|
|
3530
3620
|
const terminate = async (build, replacement) => {
|
|
3531
3621
|
if (!slot) {
|
|
3532
3622
|
if (build !== null) await emit(ctx.sink, build);
|
|
@@ -3684,11 +3774,12 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
3684
3774
|
return result;
|
|
3685
3775
|
};
|
|
3686
3776
|
}
|
|
3687
|
-
function extractGoalParam(args, paramName, toolName, dispositions,
|
|
3777
|
+
function extractGoalParam(args, paramName, toolName, dispositions, unlisted) {
|
|
3688
3778
|
if (!(paramName in args)) return null;
|
|
3689
3779
|
const disposition = dispositions ? dispositions[paramName] : void 0;
|
|
3690
3780
|
if (disposition === "native") return null;
|
|
3691
|
-
if (disposition === void 0 &&
|
|
3781
|
+
if (disposition === void 0 && unlisted === "leave") return null;
|
|
3782
|
+
if (disposition === void 0 && unlisted === "warn") {
|
|
3692
3783
|
process.stderr.write(
|
|
3693
3784
|
`baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
|
|
3694
3785
|
`
|
|
@@ -3813,6 +3904,183 @@ function installToolsListSeam(lowLevel, ctx) {
|
|
|
3813
3904
|
return isThenable(out) ? out.then(advertise) : advertise(out);
|
|
3814
3905
|
});
|
|
3815
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
|
+
}
|
|
3816
4084
|
var LIFECYCLE_SEAMS = {
|
|
3817
4085
|
resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
|
|
3818
4086
|
resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
|
|
@@ -4086,7 +4354,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
|
4086
4354
|
args[1],
|
|
4087
4355
|
params,
|
|
4088
4356
|
slot.stripped,
|
|
4089
|
-
entry != null
|
|
4357
|
+
entry != null ? "warn" : "quiet"
|
|
4090
4358
|
);
|
|
4091
4359
|
const failureKind = requestSideFailureKind(entry, slot.validation);
|
|
4092
4360
|
const text = () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result);
|
|
@@ -4260,27 +4528,34 @@ function createBaton(supplied = {}) {
|
|
|
4260
4528
|
function inertHandle(sink, sessionId) {
|
|
4261
4529
|
return new BatonHandle({ sink, sessionId, vendorId: "", annotationToolName: "" });
|
|
4262
4530
|
}
|
|
4263
|
-
function
|
|
4531
|
+
function serverShapeOf(server) {
|
|
4264
4532
|
const candidate = server;
|
|
4265
|
-
if (typeof candidate?.registerTool
|
|
4266
|
-
|
|
4267
|
-
|
|
4268
|
-
|
|
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";
|
|
4269
4539
|
}
|
|
4540
|
+
throw new TypeError(
|
|
4541
|
+
"Baton needs an McpServer or a low-level Server, from @modelcontextprotocol/sdk or @modelcontextprotocol/server."
|
|
4542
|
+
);
|
|
4270
4543
|
}
|
|
4271
4544
|
function newBatonState(config) {
|
|
4272
4545
|
return {
|
|
4273
4546
|
sentSurfaces: new SentSurfaces(),
|
|
4274
4547
|
warned: /* @__PURE__ */ new Set(),
|
|
4275
4548
|
counter: new SessionCounter(),
|
|
4276
|
-
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() }
|
|
4277
4551
|
};
|
|
4278
4552
|
}
|
|
4279
|
-
function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber }, unconfigured) {
|
|
4280
|
-
|
|
4553
|
+
function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber, lowLevelTools }, unconfigured) {
|
|
4554
|
+
const shape = serverShapeOf(server);
|
|
4281
4555
|
const internals = server;
|
|
4556
|
+
const lowLevel = shape === "mcpServer" ? internals.server : server;
|
|
4282
4557
|
const serverName = usableServerName(() => ({
|
|
4283
|
-
name:
|
|
4558
|
+
name: lowLevel._serverInfo?.name,
|
|
4284
4559
|
className: internals.constructor.name
|
|
4285
4560
|
}));
|
|
4286
4561
|
const config = resolved.reportMode === "on" ? withServerDisplayName(resolved, supplied, serverName) : resolved;
|
|
@@ -4294,7 +4569,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4294
4569
|
const fallbackSessionId = `sdk-${uuid7()}`;
|
|
4295
4570
|
const counter2 = new ServerCounter(sharedCounter, fallbackSessionId);
|
|
4296
4571
|
const tenantId = resolveTenantId(config.tenantId, config.vendorId);
|
|
4297
|
-
const serverMeta = buildServerMeta(
|
|
4572
|
+
const serverMeta = buildServerMeta(lowLevel);
|
|
4298
4573
|
const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
|
|
4299
4574
|
const emitSurface = async (sessionId, digest, snapshot) => {
|
|
4300
4575
|
await emit(
|
|
@@ -4328,11 +4603,11 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4328
4603
|
process.stderr.write(message);
|
|
4329
4604
|
};
|
|
4330
4605
|
const dropSubagentClause = (name) => {
|
|
4331
|
-
const current2 =
|
|
4606
|
+
const current2 = lowLevel._instructions;
|
|
4332
4607
|
if (current2 === INTENT_INSTRUCTIONS) {
|
|
4333
|
-
|
|
4608
|
+
lowLevel._instructions = "";
|
|
4334
4609
|
} else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
|
|
4335
|
-
|
|
4610
|
+
lowLevel._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
|
|
4336
4611
|
} else {
|
|
4337
4612
|
return;
|
|
4338
4613
|
}
|
|
@@ -4346,21 +4621,17 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4346
4621
|
const vendorToolJsonSchema = (name, inputSchema2) => {
|
|
4347
4622
|
if (isV2Server) {
|
|
4348
4623
|
try {
|
|
4349
|
-
const
|
|
4350
|
-
if (
|
|
4351
|
-
} catch {
|
|
4352
|
-
}
|
|
4353
|
-
try {
|
|
4354
|
-
const standard = inputSchema2?.["~standard"];
|
|
4355
|
-
const json = standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
|
|
4356
|
-
if (json) return json;
|
|
4624
|
+
const json2 = internals.toolInputSchemaJson(name);
|
|
4625
|
+
if (json2) return json2;
|
|
4357
4626
|
} catch {
|
|
4358
4627
|
}
|
|
4628
|
+
const json = standardInputJsonSchema(inputSchema2);
|
|
4629
|
+
if (json) return json;
|
|
4359
4630
|
}
|
|
4360
4631
|
try {
|
|
4361
4632
|
return toolInputJsonSchema(inputSchema2);
|
|
4362
4633
|
} catch {
|
|
4363
|
-
return
|
|
4634
|
+
return EMPTY_OBJECT_JSON_SCHEMA;
|
|
4364
4635
|
}
|
|
4365
4636
|
};
|
|
4366
4637
|
installValidationProbe(server);
|
|
@@ -4383,51 +4654,38 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4383
4654
|
vendorToolJsonSchema,
|
|
4384
4655
|
bustSchemaMemo,
|
|
4385
4656
|
dropSubagentClause,
|
|
4386
|
-
servedInstructions: () =>
|
|
4657
|
+
servedInstructions: () => lowLevel._instructions,
|
|
4387
4658
|
surfaceState,
|
|
4388
4659
|
emitSurface
|
|
4389
4660
|
};
|
|
4390
4661
|
const writeInstructions = (text) => {
|
|
4391
|
-
|
|
4392
|
-
|
|
4662
|
+
lowLevel._instructions = withVendorInstructions(
|
|
4663
|
+
lowLevel,
|
|
4393
4664
|
text,
|
|
4394
4665
|
(message) => warnOnce2("instructions-length", message)
|
|
4395
4666
|
);
|
|
4396
4667
|
};
|
|
4397
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
|
+
};
|
|
4398
4674
|
if (config.captureSettings !== void 0) {
|
|
4399
4675
|
ctx.perCaller = new PerCallerSurface({
|
|
4400
4676
|
settings: config.captureSettings,
|
|
4401
4677
|
intentParamMode,
|
|
4402
|
-
|
|
4403
|
-
|
|
4404
|
-
|
|
4405
|
-
writeInstructions(text);
|
|
4406
|
-
const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === "native");
|
|
4407
|
-
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;
|
|
4408
4681
|
},
|
|
4682
|
+
instructions: ours,
|
|
4683
|
+
writeInstructions: rewriteInstructions,
|
|
4409
4684
|
injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
|
|
4410
4685
|
});
|
|
4411
4686
|
ctx.perCaller.followSettings();
|
|
4412
4687
|
}
|
|
4413
|
-
|
|
4414
|
-
installToolsCallSeam(
|
|
4415
|
-
internals.server,
|
|
4416
|
-
// ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
|
|
4417
|
-
// object, so `registry["constructor"]` answers `Object` and
|
|
4418
|
-
// `registry["__proto__"]` answers `Object.prototype` — both non-undefined,
|
|
4419
|
-
// so the "a tool we did not wrap" guard would decline to report, and a
|
|
4420
|
-
// caller-visible `Tool constructor disabled` would reach the client with
|
|
4421
|
-
// this seam silent. An agent hallucinating a prototype-shaped tool name is
|
|
4422
|
-
// exactly the kind of failure the seam exists to make visible.
|
|
4423
|
-
(name) => {
|
|
4424
|
-
const registry = internals._registeredTools;
|
|
4425
|
-
return registry && Object.hasOwn(registry, name) ? registry[name] : void 0;
|
|
4426
|
-
},
|
|
4427
|
-
ctx
|
|
4428
|
-
);
|
|
4429
|
-
installLifecycleSeams(internals.server, ctx);
|
|
4430
|
-
const resolvedAnnotationToolName = !reports ? "" : registerAnnotationTool(server, {
|
|
4688
|
+
const annotationOptions = !reports ? void 0 : {
|
|
4431
4689
|
sink,
|
|
4432
4690
|
counter: ctx.counter,
|
|
4433
4691
|
tenantId: ctx.tenantId,
|
|
@@ -4442,7 +4700,43 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4442
4700
|
// raw override and letting the registration re-derive would register
|
|
4443
4701
|
// `srv-..._annotate` while the instructions name the server-derived one.
|
|
4444
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
|
|
4445
4737
|
});
|
|
4738
|
+
if (shape === "lowLevel") return handle(annotationToolName);
|
|
4739
|
+
const resolvedAnnotationToolName = annotationOptions ? registerAnnotationTool(server, annotationOptions) : "";
|
|
4446
4740
|
const existing = internals._registeredTools;
|
|
4447
4741
|
if (existing) {
|
|
4448
4742
|
for (const [name, entry] of Object.entries(existing)) {
|
|
@@ -4455,13 +4749,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
|
|
|
4455
4749
|
wireEntry(String(args[0]), registered, ctx);
|
|
4456
4750
|
return registered;
|
|
4457
4751
|
};
|
|
4458
|
-
return
|
|
4459
|
-
sink: given,
|
|
4460
|
-
queue: sink,
|
|
4461
|
-
vendorId: config.vendorId,
|
|
4462
|
-
sessionId: fallbackSessionId,
|
|
4463
|
-
annotationToolName: resolvedAnnotationToolName
|
|
4464
|
-
});
|
|
4752
|
+
return handle(resolvedAnnotationToolName);
|
|
4465
4753
|
}
|
|
4466
4754
|
function reportsFor(config) {
|
|
4467
4755
|
if (config.reportMode !== "on") return void 0;
|
|
@@ -4621,25 +4909,8 @@ function snapshotPayload({ surface, digest }) {
|
|
|
4621
4909
|
};
|
|
4622
4910
|
}
|
|
4623
4911
|
function servedEntry(tool) {
|
|
4624
|
-
if (!isRecord(tool)) return tool;
|
|
4625
|
-
|
|
4626
|
-
if (isRecord(entry.inputSchema)) {
|
|
4627
|
-
const schema = { ...entry.inputSchema };
|
|
4628
|
-
if (isRecord(schema.properties)) schema.properties = { ...schema.properties };
|
|
4629
|
-
injectGoalParam(schema);
|
|
4630
|
-
entry.inputSchema = schema;
|
|
4631
|
-
}
|
|
4632
|
-
return entry;
|
|
4633
|
-
}
|
|
4634
|
-
function injectGoalParam(schema) {
|
|
4635
|
-
if (schema.properties === void 0) schema.properties = {};
|
|
4636
|
-
if (!isRecord(schema.properties) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return;
|
|
4637
|
-
schema.properties[USER_GOAL_PARAM_NAME] = {
|
|
4638
|
-
type: "string",
|
|
4639
|
-
description: buildUserGoalParamDescription({ intentParamMode: DEFAULT_INTENT_PARAM_MODE })
|
|
4640
|
-
};
|
|
4641
|
-
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
4642
|
-
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) };
|
|
4643
4914
|
}
|
|
4644
4915
|
|
|
4645
4916
|
// src/library/client.ts
|