@goodtiming/baton-sdk 1.2.2 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -2
- package/dist/index.cjs +740 -149
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +64 -24
- package/dist/index.d.ts +64 -24
- package/dist/index.js +740 -149
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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.
|
|
56
|
+
var SDK_VERSION = "ts-1.3.1";
|
|
57
57
|
|
|
58
58
|
// src/events.ts
|
|
59
59
|
var import_zod = require("zod");
|
|
@@ -1950,6 +1950,9 @@ function buildServerInstructions(options) {
|
|
|
1950
1950
|
function buildAnnotationToolDescription(options) {
|
|
1951
1951
|
return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
|
|
1952
1952
|
}
|
|
1953
|
+
function unknownToolText(name) {
|
|
1954
|
+
return `MCP error -32602: Tool ${name} not found`;
|
|
1955
|
+
}
|
|
1953
1956
|
function buildRefusalText(options) {
|
|
1954
1957
|
const text = `${options.annotationToolName} is reactive-only on this server. Call it only AFTER a tool call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. What the user is trying to do is already recorded on each tool call, so no pre-call annotation is needed \u2014 nothing was lost. If a tool call really went wrong, or no tool covers the request, call this again and say what_happened. If neither is true, do NOT re-send: that would file a report for a call that did not go wrong.`;
|
|
1955
1958
|
return overlaid(text, options.overlay, "report_tool.refusal");
|
|
@@ -3238,19 +3241,29 @@ var ANNOTATION_INPUT_SHAPE = {
|
|
|
3238
3241
|
// zod renders "any value" as `{}`, which some MCP clients refuse (reportToolSchema.test.ts).
|
|
3239
3242
|
context: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).meta({ additionalProperties: true }).nullable().optional()
|
|
3240
3243
|
};
|
|
3244
|
+
var ANNOTATION_ARGS = import_zod3.z.object(ANNOTATION_INPUT_SHAPE);
|
|
3241
3245
|
function isReport(whatHappened) {
|
|
3242
3246
|
return typeof whatHappened === "string" && !isBlank(whatHappened);
|
|
3243
3247
|
}
|
|
3244
|
-
|
|
3248
|
+
var INVALID_PARAMS = -32602;
|
|
3249
|
+
function registerAnnotationTool(server, options, callArguments) {
|
|
3245
3250
|
const tool = buildAnnotationTool(server, options);
|
|
3246
|
-
|
|
3247
|
-
tool.name,
|
|
3248
|
-
|
|
3249
|
-
|
|
3250
|
-
)
|
|
3251
|
-
|
|
3251
|
+
if (callArguments === void 0) {
|
|
3252
|
+
server.registerTool(tool.name, { description: tool.description, inputSchema: ANNOTATION_INPUT_SHAPE }, tool.handler);
|
|
3253
|
+
return;
|
|
3254
|
+
}
|
|
3255
|
+
server.registerTool(tool.name, { description: tool.description }, async (extra) => {
|
|
3256
|
+
const args = callArguments();
|
|
3257
|
+
const { validateToolInput } = server;
|
|
3258
|
+
let parsed;
|
|
3259
|
+
try {
|
|
3260
|
+
parsed = await validateToolInput?.call(server, { inputSchema: ANNOTATION_ARGS }, args, tool.name);
|
|
3261
|
+
} catch (err) {
|
|
3262
|
+
if (err?.code === INVALID_PARAMS) throw err;
|
|
3263
|
+
}
|
|
3264
|
+
return isRecord(parsed) ? tool.handler(parsed, extra) : callAnnotationTool(tool, args, extra);
|
|
3265
|
+
});
|
|
3252
3266
|
}
|
|
3253
|
-
var ANNOTATION_ARGS = import_zod3.z.object(ANNOTATION_INPUT_SHAPE);
|
|
3254
3267
|
function annotationInputJsonSchema(major) {
|
|
3255
3268
|
return annotationJsonSchemas[major] ??= (major === 2 ? standardInputJsonSchema(ANNOTATION_ARGS) : void 0) ?? toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
|
|
3256
3269
|
}
|
|
@@ -3550,12 +3563,16 @@ function resolveInstallConfig(config) {
|
|
|
3550
3563
|
return { resolved, unconfigured };
|
|
3551
3564
|
}
|
|
3552
3565
|
var consoleOffWarned = false;
|
|
3553
|
-
function
|
|
3554
|
-
if (
|
|
3566
|
+
function consoleDroppedOnWorkers(settings) {
|
|
3567
|
+
if (settings !== "console" || !onWorkers()) return false;
|
|
3555
3568
|
if (!consoleOffWarned) {
|
|
3556
3569
|
consoleOffWarned = true;
|
|
3557
3570
|
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.`);
|
|
3558
3571
|
}
|
|
3572
|
+
return true;
|
|
3573
|
+
}
|
|
3574
|
+
function withoutConsoleOnWorkers(config) {
|
|
3575
|
+
if (!consoleDroppedOnWorkers(config.settings)) return config;
|
|
3559
3576
|
const rest = { ...config, reportMode: config.reportMode ?? "on" };
|
|
3560
3577
|
delete rest.settings;
|
|
3561
3578
|
return rest;
|
|
@@ -3616,18 +3633,7 @@ function resolveBatonConfig(supplied) {
|
|
|
3616
3633
|
// itself, exactly as it does for an explicitly-constructed sink.
|
|
3617
3634
|
sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
|
|
3618
3635
|
...identity.settings === "console" ? {
|
|
3619
|
-
captureSettings:
|
|
3620
|
-
dsn.vendorId,
|
|
3621
|
-
new SettingsFetcher({
|
|
3622
|
-
origin: dsn.origin,
|
|
3623
|
-
apiKey: dsn.key,
|
|
3624
|
-
tenantId: dsn.tenantId,
|
|
3625
|
-
vendorId: dsn.vendorId,
|
|
3626
|
-
refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
|
|
3627
|
-
}),
|
|
3628
|
-
envCandidate(),
|
|
3629
|
-
envTask()
|
|
3630
|
-
)
|
|
3636
|
+
captureSettings: consoleCaptureSettings(dsn, identity.settingsRefreshMs)
|
|
3631
3637
|
} : {}
|
|
3632
3638
|
};
|
|
3633
3639
|
}
|
|
@@ -3642,6 +3648,36 @@ function withServerDisplayName(resolved, supplied, serverName) {
|
|
|
3642
3648
|
var RENAMED_KEYS = {
|
|
3643
3649
|
resolveUser: "resolvePrincipal"
|
|
3644
3650
|
};
|
|
3651
|
+
function consoleCaptureSettings(dsn, refreshMs) {
|
|
3652
|
+
const fetcher = new SettingsFetcher({
|
|
3653
|
+
origin: dsn.origin,
|
|
3654
|
+
apiKey: dsn.key,
|
|
3655
|
+
tenantId: dsn.tenantId,
|
|
3656
|
+
vendorId: dsn.vendorId,
|
|
3657
|
+
refreshMs: refreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
|
|
3658
|
+
});
|
|
3659
|
+
return new CaptureSettings(dsn.vendorId, fetcher, envCandidate(), envTask());
|
|
3660
|
+
}
|
|
3661
|
+
function validateReportMode(config, owner) {
|
|
3662
|
+
if (config.reportMode !== void 0 && !REPORT_MODES.has(config.reportMode)) {
|
|
3663
|
+
throw new Error(
|
|
3664
|
+
`${owner}.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
|
|
3665
|
+
);
|
|
3666
|
+
}
|
|
3667
|
+
}
|
|
3668
|
+
function validateSettings(config, owner) {
|
|
3669
|
+
if (config.settings !== void 0 && !SETTINGS_MODES.includes(config.settings)) {
|
|
3670
|
+
throw new Error(
|
|
3671
|
+
`${owner}.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`
|
|
3672
|
+
);
|
|
3673
|
+
}
|
|
3674
|
+
const refresh = config.settingsRefreshMs;
|
|
3675
|
+
if (refresh !== void 0 && (typeof refresh !== "number" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))) {
|
|
3676
|
+
throw new Error(
|
|
3677
|
+
`${owner}.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} to ${String(MAX_TIMER_MS)}.`
|
|
3678
|
+
);
|
|
3679
|
+
}
|
|
3680
|
+
}
|
|
3645
3681
|
function validateBatonConfig(config) {
|
|
3646
3682
|
for (const [was, now] of Object.entries(RENAMED_KEYS)) {
|
|
3647
3683
|
if (was in config) {
|
|
@@ -3658,11 +3694,7 @@ function validateBatonConfig(config) {
|
|
|
3658
3694
|
`vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
|
|
3659
3695
|
);
|
|
3660
3696
|
}
|
|
3661
|
-
|
|
3662
|
-
throw new Error(
|
|
3663
|
-
`BatonConfig.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
|
|
3664
|
-
);
|
|
3665
|
-
}
|
|
3697
|
+
validateReportMode(config, "BatonConfig");
|
|
3666
3698
|
if (!config.vendorDisplayName && config.reportMode === "on") {
|
|
3667
3699
|
throw new Error(
|
|
3668
3700
|
'BatonConfig needs a vendorDisplayName with reportMode: "on" \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4).'
|
|
@@ -3693,17 +3725,7 @@ function validateBatonConfig(config) {
|
|
|
3693
3725
|
`BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
|
|
3694
3726
|
);
|
|
3695
3727
|
}
|
|
3696
|
-
|
|
3697
|
-
throw new Error(
|
|
3698
|
-
`BatonConfig.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`
|
|
3699
|
-
);
|
|
3700
|
-
}
|
|
3701
|
-
const refresh = config.settingsRefreshMs;
|
|
3702
|
-
if (refresh !== void 0 && (typeof refresh !== "number" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))) {
|
|
3703
|
-
throw new Error(
|
|
3704
|
-
`BatonConfig.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} to ${String(MAX_TIMER_MS)}.`
|
|
3705
|
-
);
|
|
3706
|
-
}
|
|
3728
|
+
validateSettings(config, "BatonConfig");
|
|
3707
3729
|
if (config.scrubber !== void 0 && typeof config.scrubber !== "function") {
|
|
3708
3730
|
throw new Error("BatonConfig.scrubber must be a function.");
|
|
3709
3731
|
}
|
|
@@ -3837,33 +3859,35 @@ var PerCallerSurface = class {
|
|
|
3837
3859
|
}
|
|
3838
3860
|
/** `result` with the caller's goal, reports and overlay; as served on any failure. */
|
|
3839
3861
|
toolsFor(result, caller) {
|
|
3840
|
-
|
|
3841
|
-
if (settings === void 0) return result;
|
|
3842
|
-
const { intentParamMode, annotationToolName, injectsGoal } = this.options;
|
|
3843
|
-
const goal = settings.intentParamMode ?? intentParamMode;
|
|
3844
|
-
const hideReports = annotationToolName !== "" && settings.reportMode === "off";
|
|
3845
|
-
const overlay = settings.overlay;
|
|
3846
|
-
if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
|
|
3847
|
-
try {
|
|
3848
|
-
const tools = result?.tools;
|
|
3849
|
-
if (!Array.isArray(tools)) return result;
|
|
3850
|
-
const served = [];
|
|
3851
|
-
const injected = [];
|
|
3852
|
-
for (const tool of tools) {
|
|
3853
|
-
const name = tool?.name;
|
|
3854
|
-
if (hideReports && name === annotationToolName) continue;
|
|
3855
|
-
const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
|
|
3856
|
-
served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
|
|
3857
|
-
injected.push(ours);
|
|
3858
|
-
}
|
|
3859
|
-
const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
|
|
3860
|
-
return { ...result, tools: rewritten };
|
|
3861
|
-
} catch (err) {
|
|
3862
|
-
stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
|
|
3863
|
-
return result;
|
|
3864
|
-
}
|
|
3862
|
+
return toolsForCaller(result, caller.settings, this.options);
|
|
3865
3863
|
}
|
|
3866
3864
|
};
|
|
3865
|
+
function toolsForCaller(result, settings, options) {
|
|
3866
|
+
if (settings === void 0) return result;
|
|
3867
|
+
const { intentParamMode, annotationToolName, injectsGoal } = options;
|
|
3868
|
+
const goal = settings.intentParamMode ?? intentParamMode;
|
|
3869
|
+
const hideReports = annotationToolName !== "" && settings.reportMode === "off";
|
|
3870
|
+
const overlay = settings.overlay;
|
|
3871
|
+
if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
|
|
3872
|
+
try {
|
|
3873
|
+
const tools = result?.tools;
|
|
3874
|
+
if (!Array.isArray(tools)) return result;
|
|
3875
|
+
const served = [];
|
|
3876
|
+
const injected = [];
|
|
3877
|
+
for (const tool of tools) {
|
|
3878
|
+
const name = tool?.name;
|
|
3879
|
+
if (hideReports && name === annotationToolName) continue;
|
|
3880
|
+
const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
|
|
3881
|
+
served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
|
|
3882
|
+
injected.push(ours);
|
|
3883
|
+
}
|
|
3884
|
+
const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
|
|
3885
|
+
return { ...result, tools: rewritten };
|
|
3886
|
+
} catch (err) {
|
|
3887
|
+
stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
|
|
3888
|
+
return result;
|
|
3889
|
+
}
|
|
3890
|
+
}
|
|
3867
3891
|
function batonParagraphs(pointer, overlay, subagentLine) {
|
|
3868
3892
|
const parts = overlay?.instructionAppends() ?? [];
|
|
3869
3893
|
if (pointer !== void 0) parts.push(overlaid(pointer, overlay, "instructions.report_pointer"));
|
|
@@ -3874,7 +3898,7 @@ function batonParagraphs(pointer, overlay, subagentLine) {
|
|
|
3874
3898
|
function withOverlay(tools, injected, overlay, reportTool2) {
|
|
3875
3899
|
const position = /* @__PURE__ */ new Map();
|
|
3876
3900
|
tools.forEach((tool, i) => position.set(tool?.name, i));
|
|
3877
|
-
const
|
|
3901
|
+
const hidden2 = /* @__PURE__ */ new Set();
|
|
3878
3902
|
for (const action of overlay.actions) {
|
|
3879
3903
|
if (action.tool === void 0) continue;
|
|
3880
3904
|
const i = position.get(action.tool);
|
|
@@ -3883,7 +3907,7 @@ function withOverlay(tools, injected, overlay, reportTool2) {
|
|
|
3883
3907
|
} else if (action.tool === reportTool2) {
|
|
3884
3908
|
warnSkipped(overlay.id, action.index, "the report tool takes agent_text targets only");
|
|
3885
3909
|
} else if (action.param === void 0 && action.change === "remove") {
|
|
3886
|
-
|
|
3910
|
+
hidden2.add(i);
|
|
3887
3911
|
} else if (action.param === void 0) {
|
|
3888
3912
|
tools[i] = withDescription(tools[i], [action]);
|
|
3889
3913
|
} else {
|
|
@@ -3902,7 +3926,7 @@ function withOverlay(tools, injected, overlay, reportTool2) {
|
|
|
3902
3926
|
if (reportActions.length > 0 && reportAt !== void 0) {
|
|
3903
3927
|
tools[reportAt] = withDescription(tools[reportAt], reportActions);
|
|
3904
3928
|
}
|
|
3905
|
-
return tools.filter((_, i) => !
|
|
3929
|
+
return tools.filter((_, i) => !hidden2.has(i));
|
|
3906
3930
|
}
|
|
3907
3931
|
function withDescription(tool, actions) {
|
|
3908
3932
|
const description = typeof tool.description === "string" ? tool.description : void 0;
|
|
@@ -4458,11 +4482,9 @@ var TOOLS_LIST_SEAM = /* @__PURE__ */ Symbol("batonToolsListSeam");
|
|
|
4458
4482
|
var TOOLS_CALL_METHOD = "tools/call";
|
|
4459
4483
|
var TOOLS_CALL_SEAM = /* @__PURE__ */ Symbol("batonToolsCallSeam");
|
|
4460
4484
|
function installRequestSeam(lowLevel, method, seamTag, wrap) {
|
|
4461
|
-
|
|
4462
|
-
const
|
|
4463
|
-
|
|
4464
|
-
const handlers = table;
|
|
4465
|
-
const setRequestHandler = originalSet;
|
|
4485
|
+
if (!takesRequestSeams(lowLevel)) return;
|
|
4486
|
+
const handlers = lowLevel._requestHandlers;
|
|
4487
|
+
const setRequestHandler = lowLevel.setRequestHandler;
|
|
4466
4488
|
const wrapCurrent = () => {
|
|
4467
4489
|
const handler = handlers.get(method);
|
|
4468
4490
|
if (typeof handler !== "function" || handler[seamTag]) return;
|
|
@@ -4478,18 +4500,24 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
|
|
|
4478
4500
|
return registered;
|
|
4479
4501
|
};
|
|
4480
4502
|
}
|
|
4503
|
+
function takesRequestSeams(lowLevel) {
|
|
4504
|
+
return lowLevel._requestHandlers instanceof Map && typeof lowLevel.setRequestHandler === "function";
|
|
4505
|
+
}
|
|
4481
4506
|
function installToolsListSeam(lowLevel, ctx, listsOwnReportTool) {
|
|
4482
4507
|
const names = [...requiredParamNames(ctx.intentParamMode), TOOL_NAME_PARAM_NAME];
|
|
4483
4508
|
const isInjected = (toolName, paramName) => toolName === ctx.annotationToolName ? paramName === TOOL_NAME_PARAM_NAME : ctx.paramRegistry.get(toolName)?.[paramName] === "injected";
|
|
4484
4509
|
const advertise = (result) => {
|
|
4510
|
+
let served = result;
|
|
4485
4511
|
try {
|
|
4486
|
-
|
|
4512
|
+
if (!listsOwnReportTool && ctx.annotationToolName !== "") {
|
|
4513
|
+
served = withToolInputSchema(result, ctx.annotationToolName, annotationInputJsonSchema(lowLevelMajor(lowLevel)));
|
|
4514
|
+
}
|
|
4487
4515
|
return advertiseIntentParamsRequired(served, names, isInjected);
|
|
4488
4516
|
} catch (err) {
|
|
4489
4517
|
stderrLine(
|
|
4490
|
-
`baton: tools/list advertisement failed; serving the
|
|
4518
|
+
`baton: tools/list advertisement failed; serving the list without it: ${String(err)}`
|
|
4491
4519
|
);
|
|
4492
|
-
return
|
|
4520
|
+
return served;
|
|
4493
4521
|
}
|
|
4494
4522
|
};
|
|
4495
4523
|
installRequestSeam(lowLevel, TOOLS_LIST_METHOD, TOOLS_LIST_SEAM, (handler) => (...args) => {
|
|
@@ -4887,14 +4915,15 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
4887
4915
|
(handler) => async (...args) => {
|
|
4888
4916
|
const request = args[0];
|
|
4889
4917
|
const name = request?.params?.name;
|
|
4918
|
+
const toolArgs = request?.params?.arguments;
|
|
4890
4919
|
const slot = {
|
|
4891
4920
|
innerFired: false,
|
|
4892
4921
|
flushTerminal: null,
|
|
4893
4922
|
stripped: stripIntentParams(request?.params, ctx),
|
|
4894
4923
|
strippedFor: typeof name === "string" ? name : null,
|
|
4895
|
-
validation: "unseen"
|
|
4924
|
+
validation: "unseen",
|
|
4925
|
+
arguments: name === ctx.annotationToolName ? toolArgs : void 0
|
|
4896
4926
|
};
|
|
4897
|
-
const toolArgs = request?.params?.arguments;
|
|
4898
4927
|
if (typeof name === "string" && toolEntry(name) != null && await hiddenFrom(slot, name, isRecord(toolArgs) ? toolArgs : {}, args[1], ctx)) {
|
|
4899
4928
|
return answerHidden(lowLevel, name, (outcome2) => settleCall(slot, outcome2, args, toolEntry, ctx, "tool_hidden"));
|
|
4900
4929
|
}
|
|
@@ -4929,7 +4958,7 @@ async function hiddenFrom(slot, name, params, extra, ctx) {
|
|
|
4929
4958
|
}
|
|
4930
4959
|
async function answerHidden(lowLevel, name, settle) {
|
|
4931
4960
|
if (lowLevelMajor(lowLevel) === 1) {
|
|
4932
|
-
const result = { content: [{ type: "text", text:
|
|
4961
|
+
const result = { content: [{ type: "text", text: unknownToolText(name) }], isError: true };
|
|
4933
4962
|
await settle({ failed: true, raised: false, result });
|
|
4934
4963
|
return result;
|
|
4935
4964
|
}
|
|
@@ -5389,7 +5418,13 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned4, co
|
|
|
5389
5418
|
checkGivenTools?.();
|
|
5390
5419
|
return handle(annotationToolName);
|
|
5391
5420
|
}
|
|
5392
|
-
|
|
5421
|
+
if (annotationOptions) {
|
|
5422
|
+
registerAnnotationTool(
|
|
5423
|
+
server,
|
|
5424
|
+
annotationOptions,
|
|
5425
|
+
takesRequestSeams(lowLevel) ? () => callSlots.getStore()?.arguments : void 0
|
|
5426
|
+
);
|
|
5427
|
+
}
|
|
5393
5428
|
const existing = internals._registeredTools;
|
|
5394
5429
|
if (existing) {
|
|
5395
5430
|
for (const [name, entry] of Object.entries(existing)) {
|
|
@@ -5402,7 +5437,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned4, co
|
|
|
5402
5437
|
wireEntry(String(args[0]), registered, ctx);
|
|
5403
5438
|
return registered;
|
|
5404
5439
|
};
|
|
5405
|
-
return handle(
|
|
5440
|
+
return handle(annotationToolName);
|
|
5406
5441
|
}
|
|
5407
5442
|
function reportsFor(config) {
|
|
5408
5443
|
if (config.reportMode !== "on") return void 0;
|
|
@@ -5453,6 +5488,9 @@ function principalFromOAuthEmail(context) {
|
|
|
5453
5488
|
};
|
|
5454
5489
|
}
|
|
5455
5490
|
|
|
5491
|
+
// src/library/client.ts
|
|
5492
|
+
var asyncHooks3 = __toESM(require("async_hooks"), 1);
|
|
5493
|
+
|
|
5456
5494
|
// src/library/session.ts
|
|
5457
5495
|
var asyncHooks2 = __toESM(require("async_hooks"), 1);
|
|
5458
5496
|
var TRANSPORT_LIBRARY = "library";
|
|
@@ -5466,7 +5504,8 @@ function sessionEnvelope(session) {
|
|
|
5466
5504
|
organization: session.organization,
|
|
5467
5505
|
labels: wireLabels(session.labels),
|
|
5468
5506
|
client_observed: session.clientObserved,
|
|
5469
|
-
runtime_meta: session.runtimeMeta
|
|
5507
|
+
runtime_meta: session.runtimeMeta,
|
|
5508
|
+
capture: session.settings?.capture ?? null
|
|
5470
5509
|
};
|
|
5471
5510
|
}
|
|
5472
5511
|
function warn2(message) {
|
|
@@ -5481,7 +5520,7 @@ function vendorId(name, value) {
|
|
|
5481
5520
|
return null;
|
|
5482
5521
|
}
|
|
5483
5522
|
function blank(sessionId, origin) {
|
|
5484
|
-
return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };
|
|
5523
|
+
return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null, candidate: null, task: null };
|
|
5485
5524
|
}
|
|
5486
5525
|
function requestMeta(meta) {
|
|
5487
5526
|
if (isRecord(meta)) return meta;
|
|
@@ -5504,16 +5543,48 @@ function newSession(values, scrubber, disabled) {
|
|
|
5504
5543
|
...base,
|
|
5505
5544
|
...callerFor(values.principal, (_key, message) => warn2(`principal ${message}`)),
|
|
5506
5545
|
clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber, meta),
|
|
5507
|
-
runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
|
|
5546
|
+
runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber),
|
|
5547
|
+
candidate: vendorHeader(values.headers, CANDIDATE_HEADER, candidateId),
|
|
5548
|
+
task: vendorHeader(values.headers, TASK_HEADER, taskId)
|
|
5508
5549
|
};
|
|
5509
5550
|
}
|
|
5551
|
+
function vendorHeader(headers, name, parse) {
|
|
5552
|
+
try {
|
|
5553
|
+
if (headers === void 0) return null;
|
|
5554
|
+
if (typeof headers.get === "function") return parse(headers.get(name));
|
|
5555
|
+
const key = Object.keys(headers).find((k) => k.toLowerCase() === name);
|
|
5556
|
+
return key === void 0 ? null : parse(headers[key]);
|
|
5557
|
+
} catch {
|
|
5558
|
+
return null;
|
|
5559
|
+
}
|
|
5560
|
+
}
|
|
5510
5561
|
var current = new asyncHooks2.AsyncLocalStorage();
|
|
5511
5562
|
function runInSession(owner, session, fn) {
|
|
5512
5563
|
return current.run({ owner, session }, fn);
|
|
5513
5564
|
}
|
|
5514
|
-
|
|
5515
|
-
|
|
5516
|
-
|
|
5565
|
+
var settingsWarned2 = false;
|
|
5566
|
+
function sessionForCall(owner, settings) {
|
|
5567
|
+
const session = inBlock(owner) ? current.getStore().session : blank(uuid7(), "minted");
|
|
5568
|
+
if (settings === void 0) return session;
|
|
5569
|
+
try {
|
|
5570
|
+
const callSettings = settings.forCaller({
|
|
5571
|
+
labels: session.labels,
|
|
5572
|
+
clientName: session.clientObserved?.info?.name ?? null,
|
|
5573
|
+
shareKey: session.principal?.id ?? null,
|
|
5574
|
+
candidate: session.candidate,
|
|
5575
|
+
task: session.task
|
|
5576
|
+
});
|
|
5577
|
+
return callSettings === void 0 ? session : { ...session, settings: callSettings };
|
|
5578
|
+
} catch (err) {
|
|
5579
|
+
if (!settingsWarned2) {
|
|
5580
|
+
settingsWarned2 = true;
|
|
5581
|
+
warn2(`applying capture settings failed; this call uses the client's values: ${printable(err)}`);
|
|
5582
|
+
}
|
|
5583
|
+
return session;
|
|
5584
|
+
}
|
|
5585
|
+
}
|
|
5586
|
+
function inBlock(owner) {
|
|
5587
|
+
return current.getStore()?.owner === owner;
|
|
5517
5588
|
}
|
|
5518
5589
|
|
|
5519
5590
|
// src/library/surface.ts
|
|
@@ -5545,11 +5616,11 @@ function serveTools(tools, options) {
|
|
|
5545
5616
|
return { served, surface: null };
|
|
5546
5617
|
}
|
|
5547
5618
|
}
|
|
5548
|
-
function snapshotPayload({ surface, digest }) {
|
|
5619
|
+
function snapshotPayload({ surface, digest }, seam) {
|
|
5549
5620
|
return {
|
|
5550
5621
|
surface_hash: digest,
|
|
5551
5622
|
...surface,
|
|
5552
|
-
seam_augmentations: buildSeamAugmentations({
|
|
5623
|
+
seam_augmentations: seam ?? buildSeamAugmentations({
|
|
5553
5624
|
injectedToolNames: [],
|
|
5554
5625
|
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
5555
5626
|
intentParamMode: DEFAULT_INTENT_PARAM_MODE,
|
|
@@ -5569,6 +5640,315 @@ function servedEntry(tool) {
|
|
|
5569
5640
|
return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, DEFAULT_INTENT_PARAM_MODE, true) };
|
|
5570
5641
|
}
|
|
5571
5642
|
|
|
5643
|
+
// src/library/serve.ts
|
|
5644
|
+
var INITIALIZE = "initialize";
|
|
5645
|
+
var TOOL_LIST = "tools/list";
|
|
5646
|
+
var TOOL_CALL = "tools/call";
|
|
5647
|
+
var JSONRPC_ERROR_TYPE = "JSONRPCError";
|
|
5648
|
+
var REMEMBERED_TOOLS = 4096;
|
|
5649
|
+
function readRequest(message) {
|
|
5650
|
+
if (!isRecord(message) || message.id === void 0 || message.id === null) return null;
|
|
5651
|
+
const { method } = message;
|
|
5652
|
+
const params = message.params === void 0 ? {} : message.params;
|
|
5653
|
+
if (method !== INITIALIZE && method !== TOOL_LIST && method !== TOOL_CALL || !isRecord(params)) return null;
|
|
5654
|
+
return { method, params };
|
|
5655
|
+
}
|
|
5656
|
+
var OWN = /* @__PURE__ */ new Set(["native", "may_take"]);
|
|
5657
|
+
var KEPT = /* @__PURE__ */ new Set(["native", "may_take", "unread"]);
|
|
5658
|
+
function goalDispositions(schema) {
|
|
5659
|
+
if (schema === void 0 || schema === null) return { [USER_GOAL_PARAM_NAME]: "injected" };
|
|
5660
|
+
const retired = Object.fromEntries(RETIRED_PARAM_NAMES.map((name) => [name, "native"]));
|
|
5661
|
+
if (!isRecord(schema) || !isRecord(schema.properties ?? {})) {
|
|
5662
|
+
return { ...retired, [USER_GOAL_PARAM_NAME]: "unread" };
|
|
5663
|
+
}
|
|
5664
|
+
if (!takesUserGoalJson(schema)) {
|
|
5665
|
+
if (declaresParam(schema, USER_GOAL_PARAM_NAME)) return { ...retired, [USER_GOAL_PARAM_NAME]: "native" };
|
|
5666
|
+
return mayDeclareParam(schema, USER_GOAL_PARAM_NAME) ? { ...retired, [USER_GOAL_PARAM_NAME]: "may_take" } : retired;
|
|
5667
|
+
}
|
|
5668
|
+
const dispositions = {};
|
|
5669
|
+
for (const name of RETIRED_PARAM_NAMES) if (declaresParam(schema, name)) dispositions[name] = "native";
|
|
5670
|
+
dispositions[USER_GOAL_PARAM_NAME] = declaresParam(schema, USER_GOAL_PARAM_NAME) ? "native" : "injected";
|
|
5671
|
+
return dispositions;
|
|
5672
|
+
}
|
|
5673
|
+
var ownsUserGoal = (dispositions) => OWN.has(dispositions?.[USER_GOAL_PARAM_NAME]);
|
|
5674
|
+
var NO_GOALS = [null, null, null];
|
|
5675
|
+
function popGoals(args, dispositions) {
|
|
5676
|
+
const pop = (name) => {
|
|
5677
|
+
if (!(name in args) || dispositions !== void 0 && KEPT.has(dispositions[name])) return null;
|
|
5678
|
+
const value = args[name];
|
|
5679
|
+
delete args[name];
|
|
5680
|
+
return typeof value === "string" && !isBlank(value) ? value : null;
|
|
5681
|
+
};
|
|
5682
|
+
if (dispositions === void 0) return [pop(USER_GOAL_PARAM_NAME), null, null];
|
|
5683
|
+
return [pop(USER_GOAL_PARAM_NAME), pop(RETIRED_PARAM_NAMES[0]), pop(RETIRED_PARAM_NAMES[1])];
|
|
5684
|
+
}
|
|
5685
|
+
function knownTools(tools) {
|
|
5686
|
+
const dispositions = /* @__PURE__ */ new Map();
|
|
5687
|
+
const names = /* @__PURE__ */ new Set();
|
|
5688
|
+
for (const tool of tools) {
|
|
5689
|
+
try {
|
|
5690
|
+
const name = isRecord(tool) ? tool.name : void 0;
|
|
5691
|
+
if (typeof name !== "string") continue;
|
|
5692
|
+
names.add(name);
|
|
5693
|
+
dispositions.set(name, goalDispositions(tool.inputSchema));
|
|
5694
|
+
} catch {
|
|
5695
|
+
continue;
|
|
5696
|
+
}
|
|
5697
|
+
}
|
|
5698
|
+
return { dispositions, names };
|
|
5699
|
+
}
|
|
5700
|
+
function traceOptions(call) {
|
|
5701
|
+
const [intent, expected, workflow] = call.goals;
|
|
5702
|
+
return {
|
|
5703
|
+
toolName: call.name,
|
|
5704
|
+
params: call.arguments,
|
|
5705
|
+
...intent === null ? {} : { intent },
|
|
5706
|
+
...expected === null ? {} : { expectedOutcome: expected },
|
|
5707
|
+
...workflow === null ? {} : { workflow }
|
|
5708
|
+
};
|
|
5709
|
+
}
|
|
5710
|
+
var Serving = class {
|
|
5711
|
+
constructor(report, settings, tools) {
|
|
5712
|
+
this.report = report;
|
|
5713
|
+
this.settings = settings;
|
|
5714
|
+
this.unreadTools = tools;
|
|
5715
|
+
if (report !== void 0 && Array.isArray(tools)) {
|
|
5716
|
+
try {
|
|
5717
|
+
this.remember(/* @__PURE__ */ new Map(), knownTools(tools).names);
|
|
5718
|
+
} catch {
|
|
5719
|
+
}
|
|
5720
|
+
}
|
|
5721
|
+
}
|
|
5722
|
+
report;
|
|
5723
|
+
settings;
|
|
5724
|
+
serverMeta = { serverInfo: null, capabilities: null, instructions: null };
|
|
5725
|
+
dispositions = /* @__PURE__ */ new Map();
|
|
5726
|
+
vendorHasReportName = false;
|
|
5727
|
+
warnedUnlisted = false;
|
|
5728
|
+
unreadTools;
|
|
5729
|
+
/** Learn the vendor's `tools` once per process. Never throws: without them,
|
|
5730
|
+
* a call to a tool not yet listed is served as on a cold process. */
|
|
5731
|
+
readVendorTools() {
|
|
5732
|
+
const source = this.unreadTools;
|
|
5733
|
+
if (source === void 0) return;
|
|
5734
|
+
this.unreadTools = void 0;
|
|
5735
|
+
try {
|
|
5736
|
+
const tools = typeof source === "function" ? source() : source;
|
|
5737
|
+
if (isThenable(tools)) {
|
|
5738
|
+
throw new Error("tools must be an array or a plain function, not async");
|
|
5739
|
+
}
|
|
5740
|
+
if (!Array.isArray(tools)) throw new Error("tools gave something that is not an array");
|
|
5741
|
+
const known = knownTools(tools);
|
|
5742
|
+
this.remember(known.dispositions, known.names);
|
|
5743
|
+
} catch (err) {
|
|
5744
|
+
stderrLine(
|
|
5745
|
+
`baton: could not read the tools option; a call this process has not seen listed loses user_goal: ${printable(err)}`
|
|
5746
|
+
);
|
|
5747
|
+
}
|
|
5748
|
+
}
|
|
5749
|
+
remember(dispositions, names) {
|
|
5750
|
+
const fresh = [...dispositions.keys()].filter((name2) => !this.dispositions.has(name2)).length;
|
|
5751
|
+
if (this.dispositions.size + fresh > REMEMBERED_TOOLS) this.dispositions.clear();
|
|
5752
|
+
for (const [name2, disposition] of dispositions) {
|
|
5753
|
+
if (!ownsUserGoal(this.dispositions.get(name2))) this.dispositions.set(name2, disposition);
|
|
5754
|
+
}
|
|
5755
|
+
const name = this.report?.tool.name;
|
|
5756
|
+
if (name !== void 0 && names.has(name) && !this.vendorHasReportName) {
|
|
5757
|
+
this.vendorHasReportName = true;
|
|
5758
|
+
stderrLine(
|
|
5759
|
+
`baton: your tool ${JSON.stringify(name)} has the report tool's name, so Baton serves yours and no report tool. Set vendorDisplayName to give Baton's another name.`
|
|
5760
|
+
);
|
|
5761
|
+
}
|
|
5762
|
+
}
|
|
5763
|
+
/** The report tool, unless a vendor tool has its name. */
|
|
5764
|
+
ours() {
|
|
5765
|
+
return this.vendorHasReportName ? void 0 : this.report;
|
|
5766
|
+
}
|
|
5767
|
+
document() {
|
|
5768
|
+
return this.settings?.document ?? null;
|
|
5769
|
+
}
|
|
5770
|
+
initialized(answer) {
|
|
5771
|
+
const result = resultOf(answer);
|
|
5772
|
+
if (result === null) return answer;
|
|
5773
|
+
const vendor = result.instructions;
|
|
5774
|
+
this.readVendorTools();
|
|
5775
|
+
this.serverMeta = {
|
|
5776
|
+
serverInfo: isRecord(result.serverInfo) ? result.serverInfo : null,
|
|
5777
|
+
capabilities: isRecord(result.capabilities) ? result.capabilities : null,
|
|
5778
|
+
instructions: typeof vendor === "string" ? vendor : null
|
|
5779
|
+
};
|
|
5780
|
+
const nativeGoal = [...this.dispositions.values()].some((d) => d[USER_GOAL_PARAM_NAME] === "native");
|
|
5781
|
+
const report = this.ours();
|
|
5782
|
+
const document = this.document();
|
|
5783
|
+
const pointer = report === void 0 ? void 0 : buildReportPointer({ vendorDisplayName: report.vendorDisplayName, annotationToolName: report.tool.name });
|
|
5784
|
+
const shown = pointer !== void 0 && (document === null || document.reportsOnForAnyone);
|
|
5785
|
+
const { ours } = batonParagraphs(shown ? pointer : void 0, document?.serverOverlay, !nativeGoal);
|
|
5786
|
+
return { ...answer, result: { ...result, instructions: joined(vendor, ours) } };
|
|
5787
|
+
}
|
|
5788
|
+
listed(request, answer, settings) {
|
|
5789
|
+
const result = resultOf(answer);
|
|
5790
|
+
const tools = result?.tools;
|
|
5791
|
+
if (result === null || !Array.isArray(tools)) return null;
|
|
5792
|
+
this.readVendorTools();
|
|
5793
|
+
const { served, surface } = serveTools(tools, this.serverMeta);
|
|
5794
|
+
const known = knownTools(tools);
|
|
5795
|
+
this.remember(known.dispositions, known.names);
|
|
5796
|
+
const report = this.ours();
|
|
5797
|
+
const firstPage = request.params.cursor === void 0 || request.params.cursor === null;
|
|
5798
|
+
const out = [...served];
|
|
5799
|
+
if (report !== void 0 && firstPage) {
|
|
5800
|
+
const { name, description, inputSchema: inputSchema2 } = report.tool;
|
|
5801
|
+
out.push({ name, description, inputSchema: inputSchema2 });
|
|
5802
|
+
}
|
|
5803
|
+
const overlay = this.document()?.serverOverlay;
|
|
5804
|
+
const overlayId = overlay?.id ?? null;
|
|
5805
|
+
const listed = toolsForCaller({ ...result, tools: out }, settings, {
|
|
5806
|
+
intentParamMode: DEFAULT_INTENT_PARAM_MODE,
|
|
5807
|
+
annotationToolName: report?.tool.name ?? "",
|
|
5808
|
+
injectsGoal: (name) => known.dispositions.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
|
|
5809
|
+
});
|
|
5810
|
+
const whole = firstPage && (result.nextCursor === void 0 || result.nextCursor === null) ? surface : null;
|
|
5811
|
+
return {
|
|
5812
|
+
answer: { ...answer, result: listed },
|
|
5813
|
+
surface: whole,
|
|
5814
|
+
seam: () => {
|
|
5815
|
+
const agentText = servedAgentText({
|
|
5816
|
+
reportNames: report === void 0 ? void 0 : { vendorDisplayName: report.vendorDisplayName, annotationToolName: report.tool.name },
|
|
5817
|
+
intentParamMode: DEFAULT_INTENT_PARAM_MODE,
|
|
5818
|
+
...goalTextsServed(whole?.surface.tools ?? []),
|
|
5819
|
+
serverOverlay: overlay
|
|
5820
|
+
});
|
|
5821
|
+
const seam = buildSeamAugmentations({
|
|
5822
|
+
injectedToolNames: report === void 0 ? [] : [report.tool.name],
|
|
5823
|
+
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
5824
|
+
intentParamMode: DEFAULT_INTENT_PARAM_MODE,
|
|
5825
|
+
requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),
|
|
5826
|
+
instructionsSuffix: instructionsSuffix(agentText),
|
|
5827
|
+
agentText
|
|
5828
|
+
});
|
|
5829
|
+
if (this.settings !== void 0) seam.server_overlay = overlayId;
|
|
5830
|
+
return seam;
|
|
5831
|
+
},
|
|
5832
|
+
serverOverlay: overlayId
|
|
5833
|
+
};
|
|
5834
|
+
}
|
|
5835
|
+
/** The plan for one `tools/call`; `null` sends it to dispatch untraced. */
|
|
5836
|
+
call(request, message, settings) {
|
|
5837
|
+
const { name } = request.params;
|
|
5838
|
+
const args = request.params.arguments === void 0 ? {} : request.params.arguments;
|
|
5839
|
+
if (typeof name !== "string" || !isRecord(args)) return null;
|
|
5840
|
+
this.readVendorTools();
|
|
5841
|
+
const dispositions = this.dispositions.get(name);
|
|
5842
|
+
const report = this.ours();
|
|
5843
|
+
if (report !== void 0 && name === report.tool.name) return reportCall(report.tool, name, args, message, settings);
|
|
5844
|
+
if (dispositions === void 0 && USER_GOAL_PARAM_NAME in args && !this.warnedUnlisted) {
|
|
5845
|
+
this.warnedUnlisted = true;
|
|
5846
|
+
stderrLine(
|
|
5847
|
+
`baton: removed user_goal from a call to ${JSON.stringify(name)}, a tool in no list this process has served or read from the tools option; a tool that declares its own user_goal keeps it only once Baton has seen its schema`
|
|
5848
|
+
);
|
|
5849
|
+
}
|
|
5850
|
+
const stripped = { ...args };
|
|
5851
|
+
const goals = popGoals(stripped, dispositions);
|
|
5852
|
+
if (settings?.overlay?.hiddenTools.has(name)) return hidden(name, stripped, goals, message);
|
|
5853
|
+
const forwarded = Object.keys(stripped).length === Object.keys(args).length ? message : { ...message, params: { ...request.params, arguments: stripped } };
|
|
5854
|
+
return { name, arguments: stripped, goals, message: forwarded, kind: "forward" };
|
|
5855
|
+
}
|
|
5856
|
+
};
|
|
5857
|
+
function reportCall(tool, name, args, message, settings) {
|
|
5858
|
+
if (settings?.reportMode === "off") return hidden(name, { ...args }, NO_GOALS, message);
|
|
5859
|
+
const report = tool.annotateArgs(args);
|
|
5860
|
+
const body = report === null ? { ok: false, error: buildRefusalText({ annotationToolName: name, overlay: settings?.overlay }) } : { ok: true };
|
|
5861
|
+
return {
|
|
5862
|
+
name,
|
|
5863
|
+
arguments: { ...args },
|
|
5864
|
+
goals: NO_GOALS,
|
|
5865
|
+
message,
|
|
5866
|
+
kind: report === null ? "refused" : "report",
|
|
5867
|
+
answer: answerTo(message, { content: [{ type: "text", text: JSON.stringify(body) }], structuredContent: body }),
|
|
5868
|
+
...report === null ? {} : { report }
|
|
5869
|
+
};
|
|
5870
|
+
}
|
|
5871
|
+
function hidden(name, args, goals, message) {
|
|
5872
|
+
const result = { content: [{ type: "text", text: unknownToolText(name) }], isError: true };
|
|
5873
|
+
return { name, arguments: args, goals, message, kind: "hidden", answer: answerTo(message, result) };
|
|
5874
|
+
}
|
|
5875
|
+
function withoutUserGoal(message) {
|
|
5876
|
+
try {
|
|
5877
|
+
const params = message.params;
|
|
5878
|
+
const args = params.arguments;
|
|
5879
|
+
if (!isRecord(args) || !(USER_GOAL_PARAM_NAME in args)) return message;
|
|
5880
|
+
const stripped = Object.fromEntries(Object.entries(args).filter(([key]) => key !== USER_GOAL_PARAM_NAME));
|
|
5881
|
+
return { ...message, params: { ...params, arguments: stripped } };
|
|
5882
|
+
} catch {
|
|
5883
|
+
return message;
|
|
5884
|
+
}
|
|
5885
|
+
}
|
|
5886
|
+
function jsonRpcError(answer) {
|
|
5887
|
+
return isRecord(answer) && isRecord(answer.error) ? answer.error : null;
|
|
5888
|
+
}
|
|
5889
|
+
function resultOf(answer) {
|
|
5890
|
+
return isRecord(answer) && isRecord(answer.result) ? { ...answer.result } : null;
|
|
5891
|
+
}
|
|
5892
|
+
function isToolErrorResult(result) {
|
|
5893
|
+
return result !== null && Array.isArray(result.content) && result.isError === true;
|
|
5894
|
+
}
|
|
5895
|
+
function answerTo(message, result) {
|
|
5896
|
+
return { jsonrpc: message.jsonrpc ?? "2.0", id: message.id, result };
|
|
5897
|
+
}
|
|
5898
|
+
function instructionsSuffix(agentText) {
|
|
5899
|
+
const pieces = INSTRUCTION_PIECES.filter((piece) => piece in agentText).map((piece) => agentText[piece]);
|
|
5900
|
+
return pieces.includes(null) ? null : pieces.length > 0;
|
|
5901
|
+
}
|
|
5902
|
+
|
|
5903
|
+
// src/library/reportTool.ts
|
|
5904
|
+
function inputSchema() {
|
|
5905
|
+
const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
|
|
5906
|
+
delete schema.$schema;
|
|
5907
|
+
return { ...schema, required: [...schema.required, TOOL_NAME_PARAM_NAME] };
|
|
5908
|
+
}
|
|
5909
|
+
var nonEmptyText = (value) => typeof value === "string" && value !== "";
|
|
5910
|
+
var nonEmptyObject = (value) => isRecord(value) && Object.keys(value).length > 0;
|
|
5911
|
+
function annotateArgs(args) {
|
|
5912
|
+
const whatHappened = args.what_happened;
|
|
5913
|
+
if (!isReport(whatHappened)) return null;
|
|
5914
|
+
const options = { whatHappened };
|
|
5915
|
+
const toolName = args[TOOL_NAME_PARAM_NAME];
|
|
5916
|
+
if (typeof toolName === "string") options.toolName = toolName;
|
|
5917
|
+
const intent = args[USER_GOAL_PARAM_NAME];
|
|
5918
|
+
if (nonEmptyText(intent)) options.intent = intent;
|
|
5919
|
+
if (nonEmptyText(args.suggested_improvement)) {
|
|
5920
|
+
options.suggestedImprovement = args.suggested_improvement;
|
|
5921
|
+
}
|
|
5922
|
+
if (nonEmptyObject(args.context)) options.context = args.context;
|
|
5923
|
+
return options;
|
|
5924
|
+
}
|
|
5925
|
+
function reportTool(options) {
|
|
5926
|
+
const { vendorDisplayName } = options;
|
|
5927
|
+
if (isBlank(vendorDisplayName)) {
|
|
5928
|
+
throw new Error("vendorDisplayName is blank. Baton's report sentence names the server by it.");
|
|
5929
|
+
}
|
|
5930
|
+
const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);
|
|
5931
|
+
if (derived === void 0) {
|
|
5932
|
+
throw new Error(
|
|
5933
|
+
`vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, or one too long for Baton's report sentence. Pass name.`
|
|
5934
|
+
);
|
|
5935
|
+
}
|
|
5936
|
+
const name = validateAnnotationToolName(derived);
|
|
5937
|
+
if (!fitsBatonSentenceCap({ vendorDisplayName, annotationToolName: name })) {
|
|
5938
|
+
throw new Error(
|
|
5939
|
+
`vendorDisplayName and name ${JSON.stringify(name)} are too long together for Baton's report sentence. Shorten one of them.`
|
|
5940
|
+
);
|
|
5941
|
+
}
|
|
5942
|
+
return {
|
|
5943
|
+
name,
|
|
5944
|
+
description: buildAnnotationToolDescription({ vendorDisplayName }),
|
|
5945
|
+
inputSchema: inputSchema(),
|
|
5946
|
+
instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),
|
|
5947
|
+
refusal: buildRefusalText({ annotationToolName: name }),
|
|
5948
|
+
annotateArgs
|
|
5949
|
+
};
|
|
5950
|
+
}
|
|
5951
|
+
|
|
5572
5952
|
// src/library/client.ts
|
|
5573
5953
|
function fromEnv(name) {
|
|
5574
5954
|
const value = typeof process !== "undefined" ? process.env?.[name] : void 0;
|
|
@@ -5592,6 +5972,7 @@ function resolveClientOptions(options) {
|
|
|
5592
5972
|
if (options.scrubber !== void 0 && typeof options.scrubber !== "function") {
|
|
5593
5973
|
throw new Error("Client scrubber must be a function.");
|
|
5594
5974
|
}
|
|
5975
|
+
validateServeOptions(options);
|
|
5595
5976
|
const dsnString = selectDsn(
|
|
5596
5977
|
options.dsn,
|
|
5597
5978
|
{
|
|
@@ -5601,15 +5982,25 @@ function resolveClientOptions(options) {
|
|
|
5601
5982
|
},
|
|
5602
5983
|
"Client"
|
|
5603
5984
|
);
|
|
5985
|
+
if (options.settings === "console" && dsnString === void 0) {
|
|
5986
|
+
throw new Error(`Client settings: "console" reads the Capture page with the dsn's key, so it needs a dsn.`);
|
|
5987
|
+
}
|
|
5988
|
+
candidateNeedsConsole(options.settings);
|
|
5989
|
+
const reportOn = (options.reportMode ?? (options.settings === "console" ? "on" : "off")) === "on";
|
|
5604
5990
|
const consentToken = resolveConsentToken(options.consentToken);
|
|
5605
5991
|
if (dsnString !== void 0) {
|
|
5606
5992
|
const dsn = parseDsn(dsnString);
|
|
5993
|
+
const consoleSettings = options.settings === "console" && !consoleDroppedOnWorkers(options.settings);
|
|
5607
5994
|
return {
|
|
5608
5995
|
sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
|
|
5609
5996
|
vendorId: dsn.vendorId,
|
|
5610
5997
|
tenantId: dsn.tenantId,
|
|
5611
5998
|
consentToken,
|
|
5612
|
-
resultCaptureMode
|
|
5999
|
+
resultCaptureMode,
|
|
6000
|
+
...consoleSettings ? {
|
|
6001
|
+
captureSettings: consoleCaptureSettings(dsn, options.settingsRefreshMs)
|
|
6002
|
+
} : {},
|
|
6003
|
+
...reportOn ? { report: serveReport(dsn.vendorId, options.vendorDisplayName) } : {}
|
|
5613
6004
|
};
|
|
5614
6005
|
}
|
|
5615
6006
|
if (options.sink === void 0) {
|
|
@@ -5626,9 +6017,22 @@ function resolveClientOptions(options) {
|
|
|
5626
6017
|
vendorId: vendorId2,
|
|
5627
6018
|
tenantId: resolveTenantId(options.tenantId || void 0, vendorId2),
|
|
5628
6019
|
consentToken,
|
|
5629
|
-
resultCaptureMode
|
|
6020
|
+
resultCaptureMode,
|
|
6021
|
+
...reportOn ? { report: serveReport(vendorId2, options.vendorDisplayName) } : {}
|
|
5630
6022
|
};
|
|
5631
6023
|
}
|
|
6024
|
+
function validateServeOptions(options) {
|
|
6025
|
+
validateSettings(options, "Client");
|
|
6026
|
+
validateReportMode(options, "Client");
|
|
6027
|
+
if (options.tools !== void 0 && !Array.isArray(options.tools) && typeof options.tools !== "function") {
|
|
6028
|
+
throw new Error("Client tools must be an array of tools or a function that returns one.");
|
|
6029
|
+
}
|
|
6030
|
+
}
|
|
6031
|
+
function serveReport(vendorId2, displayName) {
|
|
6032
|
+
const display = displayName === void 0 || isBlank(displayName) ? vendorId2 : displayName;
|
|
6033
|
+
const name = deriveAnnotationToolName(vendorId2, toolNameForDisplayName(display));
|
|
6034
|
+
return { tool: reportTool({ vendorDisplayName: display, name }), vendorDisplayName: display };
|
|
6035
|
+
}
|
|
5632
6036
|
var hasText2 = (value) => typeof value === "string" && !isBlank(value);
|
|
5633
6037
|
function describeError(err) {
|
|
5634
6038
|
let type = "Error";
|
|
@@ -5660,6 +6064,7 @@ var Core = class {
|
|
|
5660
6064
|
resultCaptureMode;
|
|
5661
6065
|
scrubber;
|
|
5662
6066
|
disabled;
|
|
6067
|
+
settings;
|
|
5663
6068
|
constructor(resolved) {
|
|
5664
6069
|
this.sink = offTheCall(resolved.sink);
|
|
5665
6070
|
this.vendorId = resolved.vendorId;
|
|
@@ -5668,6 +6073,10 @@ var Core = class {
|
|
|
5668
6073
|
this.resultCaptureMode = resolved.resultCaptureMode;
|
|
5669
6074
|
this.scrubber = resolved.scrubber;
|
|
5670
6075
|
this.disabled = resolved.disabled;
|
|
6076
|
+
this.settings = resolved.captureSettings;
|
|
6077
|
+
}
|
|
6078
|
+
modeFor(session) {
|
|
6079
|
+
return session.settings?.resultCaptureMode ?? this.resultCaptureMode;
|
|
5671
6080
|
}
|
|
5672
6081
|
/** The envelope members every event of `session` shares. Call inside a
|
|
5673
6082
|
* build thunk, so `captured_at` is the build time. */
|
|
@@ -5681,6 +6090,9 @@ var Core = class {
|
|
|
5681
6090
|
consent_token: consentToken
|
|
5682
6091
|
};
|
|
5683
6092
|
}
|
|
6093
|
+
errorBody(text) {
|
|
6094
|
+
return scrubbedErrorBody(this.scrubber, text);
|
|
6095
|
+
}
|
|
5684
6096
|
/** False when nothing may be emitted: the off switch, or a closed client. */
|
|
5685
6097
|
live() {
|
|
5686
6098
|
if (this.disabled) return false;
|
|
@@ -5694,9 +6106,9 @@ var Core = class {
|
|
|
5694
6106
|
}
|
|
5695
6107
|
/** Sends `surface` unless this client already has. Never rejects. The
|
|
5696
6108
|
* write only queues, so a surface counts as sent once queued. */
|
|
5697
|
-
sendSurface(surface) {
|
|
5698
|
-
if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();
|
|
5699
|
-
this.sentSurfaces.mark(surface.digest);
|
|
6109
|
+
sendSurface(surface, seam, serverOverlay = null) {
|
|
6110
|
+
if (this.sentSurfaces.wasSent(surface.digest, serverOverlay) || !this.live()) return Promise.resolve();
|
|
6111
|
+
this.sentSurfaces.mark(surface.digest, serverOverlay);
|
|
5700
6112
|
let event;
|
|
5701
6113
|
try {
|
|
5702
6114
|
event = SurfaceSnapshotEventSchema.parse({
|
|
@@ -5707,7 +6119,7 @@ var Core = class {
|
|
|
5707
6119
|
sequence_number: nextClockSequence(),
|
|
5708
6120
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5709
6121
|
consent_token: this.consentToken,
|
|
5710
|
-
payload: snapshotPayload(surface)
|
|
6122
|
+
payload: snapshotPayload(surface, seam?.())
|
|
5711
6123
|
});
|
|
5712
6124
|
} catch (err) {
|
|
5713
6125
|
PROCESS_DROPS.add("encode_failed");
|
|
@@ -5742,6 +6154,7 @@ var Core = class {
|
|
|
5742
6154
|
var UNSET = /* @__PURE__ */ Symbol("unset");
|
|
5743
6155
|
var WITHHELD_RESULT = /* @__PURE__ */ Symbol("withheld");
|
|
5744
6156
|
var SCRUB_FAILED = /* @__PURE__ */ Symbol("scrubFailed");
|
|
6157
|
+
var observeFailure;
|
|
5745
6158
|
var runTrace;
|
|
5746
6159
|
var Trace = class _Trace {
|
|
5747
6160
|
#core;
|
|
@@ -5752,6 +6165,7 @@ var Trace = class _Trace {
|
|
|
5752
6165
|
#startedAt = 0;
|
|
5753
6166
|
#result = UNSET;
|
|
5754
6167
|
#error = null;
|
|
6168
|
+
#failure = null;
|
|
5755
6169
|
#observedWarned = false;
|
|
5756
6170
|
constructor(core, session, options) {
|
|
5757
6171
|
this.#core = core;
|
|
@@ -5773,6 +6187,7 @@ var Trace = class _Trace {
|
|
|
5773
6187
|
}
|
|
5774
6188
|
this.#result = UNSET;
|
|
5775
6189
|
this.#error = null;
|
|
6190
|
+
this.#failure = null;
|
|
5776
6191
|
if (this.#core.disabled) return this;
|
|
5777
6192
|
let errorType = failure?.errorType;
|
|
5778
6193
|
let errorBody2 = failure?.errorBody;
|
|
@@ -5783,7 +6198,7 @@ var Trace = class _Trace {
|
|
|
5783
6198
|
}
|
|
5784
6199
|
if (errorType !== void 0 || errorBody2 !== void 0) {
|
|
5785
6200
|
this.#error = { type: errorType || "Error", body: errorBody2 ?? "" };
|
|
5786
|
-
} else if (this.#core.
|
|
6201
|
+
} else if (this.#core.modeFor(this.#session) === WITHHELD) {
|
|
5787
6202
|
this.#result = WITHHELD_RESULT;
|
|
5788
6203
|
} else {
|
|
5789
6204
|
try {
|
|
@@ -5859,23 +6274,40 @@ var Trace = class _Trace {
|
|
|
5859
6274
|
#fail(err) {
|
|
5860
6275
|
const durationMs = this.#durationMs();
|
|
5861
6276
|
if (!this.#core.live()) return;
|
|
5862
|
-
|
|
6277
|
+
const [type, body] = describeError(err);
|
|
6278
|
+
if (this.#core.modeFor(this.#session) === WITHHELD) {
|
|
6279
|
+
this.#failure = { result: null, result_capture: WITHHELD };
|
|
6280
|
+
this.#emitError(nextClockSequence(), type, "", durationMs);
|
|
6281
|
+
return;
|
|
6282
|
+
}
|
|
6283
|
+
this.#emitError(nextClockSequence(), type, body, durationMs);
|
|
5863
6284
|
}
|
|
5864
6285
|
#emitError(sequence, type, body, durationMs) {
|
|
6286
|
+
const failure = this.#failure;
|
|
5865
6287
|
void this.#core.emit(
|
|
5866
6288
|
() => ToolCallErrorEventSchema.parse({
|
|
5867
6289
|
...this.#envelope(sequence),
|
|
5868
6290
|
payload: {
|
|
5869
6291
|
tool_name: this.#options.toolName,
|
|
5870
6292
|
error_type: type,
|
|
5871
|
-
error_body: scrubbedErrorBody(this.#core.scrubber, body),
|
|
6293
|
+
error_body: failure === null ? scrubbedErrorBody(this.#core.scrubber, body) : body,
|
|
5872
6294
|
duration_ms: durationMs,
|
|
5873
|
-
result: null
|
|
6295
|
+
result: null,
|
|
6296
|
+
...failure
|
|
5874
6297
|
}
|
|
5875
6298
|
})
|
|
5876
6299
|
);
|
|
5877
6300
|
}
|
|
5878
6301
|
static {
|
|
6302
|
+
observeFailure = (trace, errorType, fields, failureKind) => {
|
|
6303
|
+
trace.#result = UNSET;
|
|
6304
|
+
trace.#error = { type: errorType, body: fields.error_body };
|
|
6305
|
+
trace.#failure = {
|
|
6306
|
+
result: fields.result,
|
|
6307
|
+
...fields.result_capture === void 0 ? {} : { result_capture: fields.result_capture },
|
|
6308
|
+
...failureKind === void 0 ? {} : { failure_kind: failureKind }
|
|
6309
|
+
};
|
|
6310
|
+
};
|
|
5879
6311
|
runTrace = (core, session, options, fn) => {
|
|
5880
6312
|
const trace = new _Trace(core, session, options);
|
|
5881
6313
|
trace.#start();
|
|
@@ -5903,8 +6335,40 @@ var Trace = class _Trace {
|
|
|
5903
6335
|
};
|
|
5904
6336
|
}
|
|
5905
6337
|
};
|
|
6338
|
+
var Mark = class {
|
|
6339
|
+
constructor(owner, flags) {
|
|
6340
|
+
this.owner = owner;
|
|
6341
|
+
this.flags = flags;
|
|
6342
|
+
}
|
|
6343
|
+
owner;
|
|
6344
|
+
flags;
|
|
6345
|
+
active = true;
|
|
6346
|
+
};
|
|
6347
|
+
var inDispatch = new asyncHooks3.AsyncLocalStorage();
|
|
6348
|
+
async function dispatched(dispatch, message, mark = null) {
|
|
6349
|
+
try {
|
|
6350
|
+
return await inDispatch.run(mark, () => dispatch(message));
|
|
6351
|
+
} finally {
|
|
6352
|
+
if (mark !== null) mark.active = false;
|
|
6353
|
+
}
|
|
6354
|
+
}
|
|
6355
|
+
function messageText(message) {
|
|
6356
|
+
if (typeof message === "string") return message;
|
|
6357
|
+
return message === void 0 ? "" : JSON.stringify(message) ?? "";
|
|
6358
|
+
}
|
|
6359
|
+
function fieldsOrEmpty(build) {
|
|
6360
|
+
try {
|
|
6361
|
+
return build();
|
|
6362
|
+
} catch (err) {
|
|
6363
|
+
stderrLine(`baton: the scrubber threw on an error answer; its text is dropped: ${printable(err)}`);
|
|
6364
|
+
return { error_body: "", result: null };
|
|
6365
|
+
}
|
|
6366
|
+
}
|
|
6367
|
+
var stopWhenDropped = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((s) => s.stop()) : void 0;
|
|
5906
6368
|
var Client = class {
|
|
5907
6369
|
#core;
|
|
6370
|
+
#serving;
|
|
6371
|
+
#doubleWiringLogged = /* @__PURE__ */ new Set();
|
|
5908
6372
|
#closing;
|
|
5909
6373
|
constructor(options = {}) {
|
|
5910
6374
|
const switchName = captureDisabled();
|
|
@@ -5926,6 +6390,11 @@ var Client = class {
|
|
|
5926
6390
|
scrubber: options.scrubber ?? new Scrubber().scrub,
|
|
5927
6391
|
disabled: switchName !== null
|
|
5928
6392
|
});
|
|
6393
|
+
this.#serving = new Serving(resolved.report, resolved.captureSettings, switchName === null ? options.tools : void 0);
|
|
6394
|
+
if (resolved.captureSettings !== void 0) {
|
|
6395
|
+
resolved.captureSettings.start();
|
|
6396
|
+
stopWhenDropped?.register(this, resolved.captureSettings);
|
|
6397
|
+
}
|
|
5929
6398
|
}
|
|
5930
6399
|
/** Run `fn` with one session, principal, client and turn for every
|
|
5931
6400
|
* `trace()` and `annotate()` inside it, including after its awaits. Open
|
|
@@ -5946,7 +6415,8 @@ var Client = class {
|
|
|
5946
6415
|
* called exactly once, so a lazy query builder is not run twice. A throw or
|
|
5947
6416
|
* rejection is recorded and passed on unchanged. */
|
|
5948
6417
|
trace(options, fn) {
|
|
5949
|
-
|
|
6418
|
+
this.#flagDoubleWiring("trace");
|
|
6419
|
+
return runTrace(this.#core, sessionForCall(this, this.#core.settings), options ?? {}, fn);
|
|
5950
6420
|
}
|
|
5951
6421
|
/** `fn`, traced on every call. A single plain-object argument is sent as
|
|
5952
6422
|
* `params`, as an MCP tool's arguments are; other arguments as
|
|
@@ -5962,7 +6432,11 @@ var Client = class {
|
|
|
5962
6432
|
* own outside one. To report on a traced call, use `trace.annotate()`. */
|
|
5963
6433
|
annotate(options) {
|
|
5964
6434
|
const given = options ?? {};
|
|
5965
|
-
return this.#core.annotate(
|
|
6435
|
+
return this.#core.annotate(
|
|
6436
|
+
sessionForCall(this, this.#core.settings),
|
|
6437
|
+
given.consentToken || this.#core.consentToken,
|
|
6438
|
+
given
|
|
6439
|
+
);
|
|
5966
6440
|
}
|
|
5967
6441
|
/** `tools`, the vendor's own `tools/list` entries, with `user_goal` added
|
|
5968
6442
|
* to each `inputSchema` as `withBaton` adds it, and a `surface_snapshot`
|
|
@@ -5975,11 +6449,176 @@ var Client = class {
|
|
|
5975
6449
|
* tool list: one it cannot read is returned as it came. Does not wait for
|
|
5976
6450
|
* the snapshot to be sent; `flush()` does. */
|
|
5977
6451
|
async listTools(tools, options = {}) {
|
|
6452
|
+
this.#flagDoubleWiring("listTools");
|
|
5978
6453
|
if (this.#core.disabled) return tools;
|
|
5979
6454
|
const { served, surface } = serveTools(tools, options);
|
|
5980
6455
|
if (surface !== null) void this.#core.sendSurface(surface);
|
|
5981
6456
|
return served;
|
|
5982
6457
|
}
|
|
6458
|
+
/** Answer one MCP JSON-RPC `message` with `dispatch`, the vendor's own
|
|
6459
|
+
* function from message to answer, and Baton around it (SPEC §5.6).
|
|
6460
|
+
* Experimental.
|
|
6461
|
+
*
|
|
6462
|
+
* `initialize` gets Baton's instructions. `tools/list` gets `user_goal` and
|
|
6463
|
+
* the report tool, under the caller's Console settings, and sends the
|
|
6464
|
+
* snapshot. `tools/call` is traced, with `user_goal` removed before
|
|
6465
|
+
* `dispatch` sees it; Baton answers the report tool and a tool the caller's
|
|
6466
|
+
* overlay hides itself. Anything else goes to `dispatch` as it came.
|
|
6467
|
+
*
|
|
6468
|
+
* `options` are as on `session()`. A process learns the vendor's tools from
|
|
6469
|
+
* the lists it serves. Until it has, a call loses `user_goal` and the report
|
|
6470
|
+
* tool's name is Baton's; pass the `tools` option when a tool declares its
|
|
6471
|
+
* own `user_goal` or has the report tool's name. `dispatch` is called at
|
|
6472
|
+
* most once, and what it returns or throws comes back unchanged apart from
|
|
6473
|
+
* Baton's additions. A failure in Baton's own work is logged, never thrown. */
|
|
6474
|
+
serve(message, dispatch, options = {}) {
|
|
6475
|
+
return inDispatch.run(null, () => this.#serve(message, dispatch, options ?? {}));
|
|
6476
|
+
}
|
|
6477
|
+
async #serve(message, dispatch, options) {
|
|
6478
|
+
const request = this.#request(message);
|
|
6479
|
+
if (request === null) return dispatched(dispatch, message);
|
|
6480
|
+
const settings = this.#core.settings;
|
|
6481
|
+
if (settings !== void 0 && !settings.isReady) await settings.ready;
|
|
6482
|
+
const handle = () => this.#handle(request, message, dispatch);
|
|
6483
|
+
const { principal, headers, sessionId } = options;
|
|
6484
|
+
if (inBlock(this) && principal === void 0 && headers === void 0 && sessionId === void 0) return handle();
|
|
6485
|
+
const values = {
|
|
6486
|
+
...principal === void 0 ? {} : { principal },
|
|
6487
|
+
...headers === void 0 ? {} : { headers },
|
|
6488
|
+
...sessionId === void 0 ? {} : { sessionId }
|
|
6489
|
+
};
|
|
6490
|
+
try {
|
|
6491
|
+
if (isRecord(request.params._meta)) values.meta = request.params._meta;
|
|
6492
|
+
if (request.method === "initialize" && isRecord(request.params.clientInfo)) {
|
|
6493
|
+
values.clientInfo = request.params.clientInfo;
|
|
6494
|
+
}
|
|
6495
|
+
} catch {
|
|
6496
|
+
}
|
|
6497
|
+
return this.session(values, handle);
|
|
6498
|
+
}
|
|
6499
|
+
async #handle(request, message, dispatch) {
|
|
6500
|
+
let session;
|
|
6501
|
+
let call = null;
|
|
6502
|
+
try {
|
|
6503
|
+
session = sessionForCall(this, this.#core.settings);
|
|
6504
|
+
if (request.method === TOOL_CALL) call = this.#serving.call(request, message, session.settings);
|
|
6505
|
+
} catch (err) {
|
|
6506
|
+
stderrLine(`baton: serve() could not read the request; it is served as it came: ${printable(err)}`);
|
|
6507
|
+
return dispatched(dispatch, withoutUserGoal(message));
|
|
6508
|
+
}
|
|
6509
|
+
if (request.method !== TOOL_CALL) {
|
|
6510
|
+
const mark = request.method === TOOL_LIST ? new Mark(this, "listTools") : null;
|
|
6511
|
+
return this.#shaped(request, await dispatched(dispatch, message, mark), session);
|
|
6512
|
+
}
|
|
6513
|
+
if (call === null) return dispatched(dispatch, message);
|
|
6514
|
+
if (call.answer !== void 0) {
|
|
6515
|
+
this.#answerOurselves(call, session);
|
|
6516
|
+
return call.answer;
|
|
6517
|
+
}
|
|
6518
|
+
return this.#traced(call, dispatch, session);
|
|
6519
|
+
}
|
|
6520
|
+
#request(message) {
|
|
6521
|
+
if (this.#core.disabled) return null;
|
|
6522
|
+
try {
|
|
6523
|
+
return readRequest(message);
|
|
6524
|
+
} catch (err) {
|
|
6525
|
+
stderrLine(`baton: serve() could not read the request; it is served as it came: ${printable(err)}`);
|
|
6526
|
+
return null;
|
|
6527
|
+
}
|
|
6528
|
+
}
|
|
6529
|
+
/** Dispatch's `initialize` or `tools/list` answer with Baton's additions,
|
|
6530
|
+
* and its snapshot sent; the answer unchanged on failure. */
|
|
6531
|
+
#shaped(request, answer, session) {
|
|
6532
|
+
try {
|
|
6533
|
+
if (request.method !== TOOL_LIST) return this.#serving.initialized(answer);
|
|
6534
|
+
const listed = this.#serving.listed(request, answer, session.settings);
|
|
6535
|
+
if (listed === null) return answer;
|
|
6536
|
+
if (listed.surface !== null) void this.#core.sendSurface(listed.surface, listed.seam, listed.serverOverlay);
|
|
6537
|
+
return listed.answer;
|
|
6538
|
+
} catch (err) {
|
|
6539
|
+
stderrLine(`baton: serve() could not add to the answer; it is served as it came: ${printable(err)}`);
|
|
6540
|
+
return answer;
|
|
6541
|
+
}
|
|
6542
|
+
}
|
|
6543
|
+
async #traced(call, dispatch, session) {
|
|
6544
|
+
let dispatching = false;
|
|
6545
|
+
try {
|
|
6546
|
+
return await runTrace(this.#core, session, traceOptions(call), async (trace) => {
|
|
6547
|
+
dispatching = true;
|
|
6548
|
+
const answer = await dispatched(dispatch, call.message, new Mark(this, "trace"));
|
|
6549
|
+
this.#record(trace, answer, session);
|
|
6550
|
+
return answer;
|
|
6551
|
+
});
|
|
6552
|
+
} catch (err) {
|
|
6553
|
+
if (dispatching) throw err;
|
|
6554
|
+
stderrLine(`baton: serve() could not trace the call: ${printable(err)}`);
|
|
6555
|
+
return dispatched(dispatch, call.message, new Mark(this, "trace"));
|
|
6556
|
+
}
|
|
6557
|
+
}
|
|
6558
|
+
#record(trace, answer, session) {
|
|
6559
|
+
const mode = this.#core.modeFor(session);
|
|
6560
|
+
const scrubber = this.#core.scrubber;
|
|
6561
|
+
const errorBody2 = (text) => this.#core.errorBody(text);
|
|
6562
|
+
try {
|
|
6563
|
+
const error = jsonRpcError(answer);
|
|
6564
|
+
if (error !== null) {
|
|
6565
|
+
observeFailure(
|
|
6566
|
+
trace,
|
|
6567
|
+
JSONRPC_ERROR_TYPE,
|
|
6568
|
+
fieldsOrEmpty(
|
|
6569
|
+
() => resultDerivedFields(mode, () => messageText(error.message), { ...error }, errorBody2, scrubber)
|
|
6570
|
+
)
|
|
6571
|
+
);
|
|
6572
|
+
return;
|
|
6573
|
+
}
|
|
6574
|
+
const result = resultOf(answer);
|
|
6575
|
+
if (isToolErrorResult(result)) {
|
|
6576
|
+
observeFailure(
|
|
6577
|
+
trace,
|
|
6578
|
+
TOOL_ERROR_TYPE,
|
|
6579
|
+
fieldsOrEmpty(() => returnedErrorFields(mode, result, errorBody2, scrubber))
|
|
6580
|
+
);
|
|
6581
|
+
return;
|
|
6582
|
+
}
|
|
6583
|
+
trace.observed(result ?? answer);
|
|
6584
|
+
} catch (err) {
|
|
6585
|
+
stderrLine(`baton: serve() could not record the tool call: ${printable(err)}`);
|
|
6586
|
+
try {
|
|
6587
|
+
trace.observed(void 0);
|
|
6588
|
+
} catch {
|
|
6589
|
+
}
|
|
6590
|
+
}
|
|
6591
|
+
}
|
|
6592
|
+
#answerOurselves(call, session) {
|
|
6593
|
+
try {
|
|
6594
|
+
if (call.report !== void 0) {
|
|
6595
|
+
void this.#core.annotate(session, this.#core.consentToken, call.report);
|
|
6596
|
+
} else if (call.kind === "hidden") {
|
|
6597
|
+
const scrubber = this.#core.scrubber;
|
|
6598
|
+
const fields = fieldsOrEmpty(
|
|
6599
|
+
() => returnedErrorFields("full", call.answer.result, (text) => this.#core.errorBody(text), scrubber)
|
|
6600
|
+
);
|
|
6601
|
+
runTrace(
|
|
6602
|
+
this.#core,
|
|
6603
|
+
session,
|
|
6604
|
+
traceOptions(call),
|
|
6605
|
+
(trace) => observeFailure(trace, TOOL_ERROR_TYPE, fields, "tool_hidden")
|
|
6606
|
+
);
|
|
6607
|
+
}
|
|
6608
|
+
} catch (err) {
|
|
6609
|
+
stderrLine(`baton: serve() could not record its own answer: ${printable(err)}`);
|
|
6610
|
+
}
|
|
6611
|
+
}
|
|
6612
|
+
/** An error, once per client and call, when the vendor's code inside
|
|
6613
|
+
* `serve()` still calls what `serve()` now does: the old wiring was left in. */
|
|
6614
|
+
#flagDoubleWiring(call) {
|
|
6615
|
+
const mark = inDispatch.getStore();
|
|
6616
|
+
if (!mark?.active || mark.owner !== this || mark.flags !== call || this.#doubleWiringLogged.has(call)) return;
|
|
6617
|
+
this.#doubleWiringLogged.add(call);
|
|
6618
|
+
stderrLine(
|
|
6619
|
+
`baton: client.${call}() was called inside serve(). serve() already does this, so it is recorded twice. Remove the old Baton wiring: session(), trace(), listTools() and the report tool code.`
|
|
6620
|
+
);
|
|
6621
|
+
}
|
|
5983
6622
|
/** Wait for events so far to reach the sink, then flush it. Never rejects;
|
|
5984
6623
|
* returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
|
|
5985
6624
|
async flush() {
|
|
@@ -5987,61 +6626,13 @@ var Client = class {
|
|
|
5987
6626
|
}
|
|
5988
6627
|
/** Flush, then close the sink. Later events are dropped. */
|
|
5989
6628
|
aclose() {
|
|
6629
|
+
this.#core.settings?.stop();
|
|
5990
6630
|
this.#closing ??= boundedSinkCall(this.#core.sink, "aclose").then(() => {
|
|
5991
6631
|
this.#core.closed = true;
|
|
5992
6632
|
});
|
|
5993
6633
|
return this.#closing;
|
|
5994
6634
|
}
|
|
5995
6635
|
};
|
|
5996
|
-
|
|
5997
|
-
// src/library/reportTool.ts
|
|
5998
|
-
function inputSchema() {
|
|
5999
|
-
const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
|
|
6000
|
-
delete schema.$schema;
|
|
6001
|
-
return { ...schema, required: [...schema.required, TOOL_NAME_PARAM_NAME] };
|
|
6002
|
-
}
|
|
6003
|
-
var nonEmptyText = (value) => typeof value === "string" && value !== "";
|
|
6004
|
-
var nonEmptyObject = (value) => isRecord(value) && Object.keys(value).length > 0;
|
|
6005
|
-
function annotateArgs(args) {
|
|
6006
|
-
const whatHappened = args.what_happened;
|
|
6007
|
-
if (!isReport(whatHappened)) return null;
|
|
6008
|
-
const options = { whatHappened };
|
|
6009
|
-
const toolName = args[TOOL_NAME_PARAM_NAME];
|
|
6010
|
-
if (typeof toolName === "string") options.toolName = toolName;
|
|
6011
|
-
const intent = args[USER_GOAL_PARAM_NAME];
|
|
6012
|
-
if (nonEmptyText(intent)) options.intent = intent;
|
|
6013
|
-
if (nonEmptyText(args.suggested_improvement)) {
|
|
6014
|
-
options.suggestedImprovement = args.suggested_improvement;
|
|
6015
|
-
}
|
|
6016
|
-
if (nonEmptyObject(args.context)) options.context = args.context;
|
|
6017
|
-
return options;
|
|
6018
|
-
}
|
|
6019
|
-
function reportTool(options) {
|
|
6020
|
-
const { vendorDisplayName } = options;
|
|
6021
|
-
if (isBlank(vendorDisplayName)) {
|
|
6022
|
-
throw new Error("vendorDisplayName is blank. Baton's report sentence names the server by it.");
|
|
6023
|
-
}
|
|
6024
|
-
const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);
|
|
6025
|
-
if (derived === void 0) {
|
|
6026
|
-
throw new Error(
|
|
6027
|
-
`vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, or one too long for Baton's report sentence. Pass name.`
|
|
6028
|
-
);
|
|
6029
|
-
}
|
|
6030
|
-
const name = validateAnnotationToolName(derived);
|
|
6031
|
-
if (!fitsBatonSentenceCap({ vendorDisplayName, annotationToolName: name })) {
|
|
6032
|
-
throw new Error(
|
|
6033
|
-
`vendorDisplayName and name ${JSON.stringify(name)} are too long together for Baton's report sentence. Shorten one of them.`
|
|
6034
|
-
);
|
|
6035
|
-
}
|
|
6036
|
-
return {
|
|
6037
|
-
name,
|
|
6038
|
-
description: buildAnnotationToolDescription({ vendorDisplayName }),
|
|
6039
|
-
inputSchema: inputSchema(),
|
|
6040
|
-
instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),
|
|
6041
|
-
refusal: buildRefusalText({ annotationToolName: name }),
|
|
6042
|
-
annotateArgs
|
|
6043
|
-
};
|
|
6044
|
-
}
|
|
6045
6636
|
// Annotate the CommonJS export names for ESM import in node:
|
|
6046
6637
|
0 && (module.exports = {
|
|
6047
6638
|
BatonHandle,
|