@goodtiming/baton-sdk 1.2.1 → 1.3.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 +48 -2
- package/dist/index.cjs +804 -160
- 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 +804 -160
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/version.ts
|
|
2
|
-
var SDK_VERSION = "ts-1.
|
|
2
|
+
var SDK_VERSION = "ts-1.3.0";
|
|
3
3
|
|
|
4
4
|
// src/events.ts
|
|
5
5
|
import { z } from "zod";
|
|
@@ -1877,18 +1877,18 @@ Fields:
|
|
|
1877
1877
|
- suggested_improvement: one concrete sentence on the product change that would have helped.
|
|
1878
1878
|
- context: supplementary info not covered above. Common keys: plan, alternatives_considered, likely_cause, user_impact, error_class, downstream_blocked, confidence_in_intent. When no tool covers the request also missing_capability_field and requested_capability.`;
|
|
1879
1879
|
var CLAUDE_CODE_TRUNCATION_CAP = 2087;
|
|
1880
|
-
var
|
|
1880
|
+
var BATON_SENTENCE_LENGTH_CAP = 1500;
|
|
1881
1881
|
function buildReportPointer(options) {
|
|
1882
1882
|
return REPORT_POINTER_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
|
|
1883
1883
|
}
|
|
1884
|
-
function
|
|
1885
|
-
return buildReportPointer(options).length <=
|
|
1884
|
+
function fitsBatonSentenceCap(options) {
|
|
1885
|
+
return buildReportPointer(options).length <= BATON_SENTENCE_LENGTH_CAP;
|
|
1886
1886
|
}
|
|
1887
1887
|
function buildServerInstructions(options) {
|
|
1888
1888
|
const rendered = buildReportPointer(options);
|
|
1889
|
-
if (rendered.length >
|
|
1889
|
+
if (rendered.length > BATON_SENTENCE_LENGTH_CAP) {
|
|
1890
1890
|
throw new Error(
|
|
1891
|
-
`
|
|
1891
|
+
`Baton's report sentence would be ${rendered.length} chars, over its ${BATON_SENTENCE_LENGTH_CAP}-char limit (Claude Code cuts server instructions at ~${CLAUDE_CODE_TRUNCATION_CAP}). Shorten vendorDisplayName or annotationToolName.`
|
|
1892
1892
|
);
|
|
1893
1893
|
}
|
|
1894
1894
|
return rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
|
|
@@ -1896,6 +1896,9 @@ function buildServerInstructions(options) {
|
|
|
1896
1896
|
function buildAnnotationToolDescription(options) {
|
|
1897
1897
|
return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
|
|
1898
1898
|
}
|
|
1899
|
+
function unknownToolText(name) {
|
|
1900
|
+
return `MCP error -32602: Tool ${name} not found`;
|
|
1901
|
+
}
|
|
1899
1902
|
function buildRefusalText(options) {
|
|
1900
1903
|
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.`;
|
|
1901
1904
|
return overlaid(text, options.overlay, "report_tool.refusal");
|
|
@@ -1938,6 +1941,30 @@ function mayDeclareParam(schema, name) {
|
|
|
1938
1941
|
};
|
|
1939
1942
|
return walk2(schema);
|
|
1940
1943
|
}
|
|
1944
|
+
var VENDOR_SERVED_PIECES = [...INSTRUCTION_PIECES, "report_tool.description", "report_tool.refusal"];
|
|
1945
|
+
function servedAgentText(options) {
|
|
1946
|
+
const served = {};
|
|
1947
|
+
if (options.subagentServed) served["instructions.subagent"] = INTENT_INSTRUCTIONS;
|
|
1948
|
+
if (options.goalParamServed) {
|
|
1949
|
+
served["goal_param.description"] = buildUserGoalParamDescription({ intentParamMode: options.intentParamMode });
|
|
1950
|
+
}
|
|
1951
|
+
if (options.reportNames !== void 0) {
|
|
1952
|
+
served["instructions.report_pointer"] = buildReportPointer(options.reportNames);
|
|
1953
|
+
served["report_tool.description"] = buildAnnotationToolDescription(options.reportNames);
|
|
1954
|
+
served["report_tool.refusal"] = buildRefusalText({ annotationToolName: options.reportNames.annotationToolName });
|
|
1955
|
+
}
|
|
1956
|
+
const pieces = {};
|
|
1957
|
+
for (const [piece, text] of Object.entries(served)) {
|
|
1958
|
+
if (options.serverOverlay !== void 0 && INSTRUCTION_PIECES.includes(piece)) {
|
|
1959
|
+
const changed = changedText(text, options.serverOverlay.pieceActions(piece));
|
|
1960
|
+
pieces[piece] = { text: changed.text ?? text, source: changed.source };
|
|
1961
|
+
} else {
|
|
1962
|
+
pieces[piece] = { text, source: "default" };
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
if (options.vendorServesText) for (const piece of VENDOR_SERVED_PIECES) pieces[piece] = null;
|
|
1966
|
+
return pieces;
|
|
1967
|
+
}
|
|
1941
1968
|
function instructionsSuffixServed(annotationToolName, served) {
|
|
1942
1969
|
if (annotationToolName) return true;
|
|
1943
1970
|
return typeof served === "string" && served.includes(INTENT_INSTRUCTIONS);
|
|
@@ -1957,8 +1984,19 @@ ${ours}` : vendor;
|
|
|
1957
1984
|
function vendorText(holder) {
|
|
1958
1985
|
const current2 = holder._instructions;
|
|
1959
1986
|
const written = holder[OURS];
|
|
1987
|
+
if (written === void 0) return current2;
|
|
1960
1988
|
const vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
|
|
1961
|
-
|
|
1989
|
+
if (current2 === joined(vendor, written)) return vendor;
|
|
1990
|
+
return withoutOurs(current2, written) ?? current2;
|
|
1991
|
+
}
|
|
1992
|
+
function withoutOurs(current2, ours) {
|
|
1993
|
+
if (!ours || typeof current2 !== "string") return void 0;
|
|
1994
|
+
const at = current2.lastIndexOf(ours);
|
|
1995
|
+
if (at < 0) return void 0;
|
|
1996
|
+
const before = current2.slice(0, at);
|
|
1997
|
+
const after = current2.slice(at + ours.length);
|
|
1998
|
+
if (before && !before.endsWith("\n\n") || after && !after.startsWith("\n\n")) return void 0;
|
|
1999
|
+
return joined(before.slice(0, -2), after.slice(2));
|
|
1962
2000
|
}
|
|
1963
2001
|
function writeOurs(server, ours, subagent, write, warn3 = stderrLine) {
|
|
1964
2002
|
const holder = server;
|
|
@@ -1972,9 +2010,7 @@ function removeSubagentClause(server, write, warn3 = stderrLine) {
|
|
|
1972
2010
|
const holder = server;
|
|
1973
2011
|
const ours = holder[OURS];
|
|
1974
2012
|
const subagent = holder[SUBAGENT];
|
|
1975
|
-
if (ours === void 0 || !subagent || holder
|
|
1976
|
-
return false;
|
|
1977
|
-
}
|
|
2013
|
+
if (ours === void 0 || !subagent || vendorText(holder) === holder._instructions) return false;
|
|
1978
2014
|
const kept = ours.slice(0, ours.length - subagent.length);
|
|
1979
2015
|
writeOurs(server, kept.endsWith("\n\n") ? kept.slice(0, -2) : kept, null, write, warn3);
|
|
1980
2016
|
return true;
|
|
@@ -2043,9 +2079,9 @@ function toolNameCandidate(serverName) {
|
|
|
2043
2079
|
function displayNameFromServer(serverName, tool) {
|
|
2044
2080
|
if (serverName === void 0) return void 0;
|
|
2045
2081
|
const proposed = tool.annotationToolName || toolNameCandidate(serverName) || `${tool.vendorId}${SUFFIX}`;
|
|
2046
|
-
if (!
|
|
2082
|
+
if (!fitsBatonSentenceCap({ vendorDisplayName: serverName, annotationToolName: proposed })) {
|
|
2047
2083
|
warn(
|
|
2048
|
-
`baton: the server name (${serverName.length} chars) does not fit the
|
|
2084
|
+
`baton: the server name (${serverName.length} chars) does not fit the budget of Baton's report sentence as the display name beside the annotation tool ${JSON.stringify(proposed)}; keeping the DSN's server segment. Pass vendorDisplayName to name the server in fewer characters.`
|
|
2049
2085
|
);
|
|
2050
2086
|
return void 0;
|
|
2051
2087
|
}
|
|
@@ -2055,9 +2091,9 @@ function annotationToolNameFromServer(serverName, vendorDisplayName) {
|
|
|
2055
2091
|
if (serverName === void 0) return void 0;
|
|
2056
2092
|
const candidate = toolNameCandidate(serverName);
|
|
2057
2093
|
if (candidate === void 0) return void 0;
|
|
2058
|
-
if (!
|
|
2094
|
+
if (!fitsBatonSentenceCap({ vendorDisplayName, annotationToolName: candidate })) {
|
|
2059
2095
|
warn(
|
|
2060
|
-
`baton: the server-derived annotation tool name ${JSON.stringify(candidate)} does not fit the
|
|
2096
|
+
`baton: the server-derived annotation tool name ${JSON.stringify(candidate)} does not fit the budget of Baton's report sentence beside the display name (${vendorDisplayName.length} chars); keeping {vendorId}_annotate. A shorter display name gets the readable one.`
|
|
2061
2097
|
);
|
|
2062
2098
|
return void 0;
|
|
2063
2099
|
}
|
|
@@ -2066,7 +2102,7 @@ function annotationToolNameFromServer(serverName, vendorDisplayName) {
|
|
|
2066
2102
|
function toolNameForDisplayName(vendorDisplayName) {
|
|
2067
2103
|
if (isPlaceholderLiteral(vendorDisplayName)) return void 0;
|
|
2068
2104
|
const candidate = toolNameCandidate(vendorDisplayName);
|
|
2069
|
-
return candidate !== void 0 &&
|
|
2105
|
+
return candidate !== void 0 && fitsBatonSentenceCap({ vendorDisplayName, annotationToolName: candidate }) ? candidate : void 0;
|
|
2070
2106
|
}
|
|
2071
2107
|
function deriveAnnotationToolName(vendorId2, override) {
|
|
2072
2108
|
return validateAnnotationToolName(override || `${vendorId2}${SUFFIX}`);
|
|
@@ -2900,6 +2936,14 @@ function takesUserGoalJson(schema) {
|
|
|
2900
2936
|
const properties = schema.properties ?? {};
|
|
2901
2937
|
return isRecord(properties) && !ROOT_COMBINERS.some((key) => key in schema);
|
|
2902
2938
|
}
|
|
2939
|
+
function goalTextsServed(tools) {
|
|
2940
|
+
const schemas = Array.isArray(tools) ? tools.map((tool) => isRecord(tool) ? tool.inputSchema : void 0) : [];
|
|
2941
|
+
const native = schemas.map((schema) => declaresParam(schema, USER_GOAL_PARAM_NAME));
|
|
2942
|
+
return {
|
|
2943
|
+
goalParamServed: schemas.some((schema, i) => isRecord(schema) && !native[i] && takesUserGoalJson(schema)),
|
|
2944
|
+
subagentServed: !native.some(Boolean)
|
|
2945
|
+
};
|
|
2946
|
+
}
|
|
2903
2947
|
function withUserGoalJson(schema, intentParamMode, listRequired) {
|
|
2904
2948
|
if (!takesUserGoalJson(schema) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return schema;
|
|
2905
2949
|
const properties = schema.properties ?? {};
|
|
@@ -3135,13 +3179,13 @@ function sessionIdFromHeader(extra) {
|
|
|
3135
3179
|
var TOOL_NAME_PARAM_NAME = "tool_name";
|
|
3136
3180
|
var ANNOTATION_INPUT_SHAPE = {
|
|
3137
3181
|
user_goal: z2.string(),
|
|
3138
|
-
what_happened: z2.string().optional(),
|
|
3139
3182
|
// Nullable so a report whose agent sends an explicit null is taken,
|
|
3140
3183
|
// not rejected by validation.
|
|
3184
|
+
what_happened: z2.string().nullable().optional(),
|
|
3141
3185
|
tool_name: z2.string().nullable().optional(),
|
|
3142
|
-
suggested_improvement: z2.string().optional(),
|
|
3186
|
+
suggested_improvement: z2.string().nullable().optional(),
|
|
3143
3187
|
// zod renders "any value" as `{}`, which some MCP clients refuse (reportToolSchema.test.ts).
|
|
3144
|
-
context: z2.record(z2.string(), z2.unknown()).meta({ additionalProperties: true }).optional()
|
|
3188
|
+
context: z2.record(z2.string(), z2.unknown()).meta({ additionalProperties: true }).nullable().optional()
|
|
3145
3189
|
};
|
|
3146
3190
|
function isReport(whatHappened) {
|
|
3147
3191
|
return typeof whatHappened === "string" && !isBlank(whatHappened);
|
|
@@ -3220,7 +3264,7 @@ function buildAnnotationTool(server, options) {
|
|
|
3220
3264
|
payload: {
|
|
3221
3265
|
// The agent-facing `user_goal` is stored as the wire key `intent`.
|
|
3222
3266
|
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
3223
|
-
intent: options.scrubber(args.user_goal),
|
|
3267
|
+
intent: args.user_goal ? options.scrubber(args.user_goal) : null,
|
|
3224
3268
|
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
3225
3269
|
what_happened: options.scrubber(whatHappened),
|
|
3226
3270
|
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
@@ -3245,7 +3289,7 @@ var PUBLISHABLE_PREFIX = "baton_pk_";
|
|
|
3245
3289
|
var SECRET_PREFIX = "baton_sk_";
|
|
3246
3290
|
var TEST_PREFIX = "baton_tk_";
|
|
3247
3291
|
var KEY_PREFIXES = [PUBLISHABLE_PREFIX, SECRET_PREFIX, TEST_PREFIX];
|
|
3248
|
-
var KEY_RUN = /baton_(?:(?:pk|sk|tk)_[A-Za-z0-9_%-]{8,}|[A-Za-z0-9_%-]{43,})/
|
|
3292
|
+
var KEY_RUN = /baton_(?:(?:pk|sk|tk)_[A-Za-z0-9_%-]{8,}|[A-Za-z0-9_%-]{43,})/gi;
|
|
3249
3293
|
function looksLikeAKey(value) {
|
|
3250
3294
|
return KEY_PREFIXES.some((prefix) => value.startsWith(prefix));
|
|
3251
3295
|
}
|
|
@@ -3455,12 +3499,16 @@ function resolveInstallConfig(config) {
|
|
|
3455
3499
|
return { resolved, unconfigured };
|
|
3456
3500
|
}
|
|
3457
3501
|
var consoleOffWarned = false;
|
|
3458
|
-
function
|
|
3459
|
-
if (
|
|
3502
|
+
function consoleDroppedOnWorkers(settings) {
|
|
3503
|
+
if (settings !== "console" || !onWorkers()) return false;
|
|
3460
3504
|
if (!consoleOffWarned) {
|
|
3461
3505
|
consoleOffWarned = true;
|
|
3462
3506
|
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.`);
|
|
3463
3507
|
}
|
|
3508
|
+
return true;
|
|
3509
|
+
}
|
|
3510
|
+
function withoutConsoleOnWorkers(config) {
|
|
3511
|
+
if (!consoleDroppedOnWorkers(config.settings)) return config;
|
|
3464
3512
|
const rest = { ...config, reportMode: config.reportMode ?? "on" };
|
|
3465
3513
|
delete rest.settings;
|
|
3466
3514
|
return rest;
|
|
@@ -3521,18 +3569,7 @@ function resolveBatonConfig(supplied) {
|
|
|
3521
3569
|
// itself, exactly as it does for an explicitly-constructed sink.
|
|
3522
3570
|
sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
|
|
3523
3571
|
...identity.settings === "console" ? {
|
|
3524
|
-
captureSettings:
|
|
3525
|
-
dsn.vendorId,
|
|
3526
|
-
new SettingsFetcher({
|
|
3527
|
-
origin: dsn.origin,
|
|
3528
|
-
apiKey: dsn.key,
|
|
3529
|
-
tenantId: dsn.tenantId,
|
|
3530
|
-
vendorId: dsn.vendorId,
|
|
3531
|
-
refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
|
|
3532
|
-
}),
|
|
3533
|
-
envCandidate(),
|
|
3534
|
-
envTask()
|
|
3535
|
-
)
|
|
3572
|
+
captureSettings: consoleCaptureSettings(dsn, identity.settingsRefreshMs)
|
|
3536
3573
|
} : {}
|
|
3537
3574
|
};
|
|
3538
3575
|
}
|
|
@@ -3547,6 +3584,36 @@ function withServerDisplayName(resolved, supplied, serverName) {
|
|
|
3547
3584
|
var RENAMED_KEYS = {
|
|
3548
3585
|
resolveUser: "resolvePrincipal"
|
|
3549
3586
|
};
|
|
3587
|
+
function consoleCaptureSettings(dsn, refreshMs) {
|
|
3588
|
+
const fetcher = new SettingsFetcher({
|
|
3589
|
+
origin: dsn.origin,
|
|
3590
|
+
apiKey: dsn.key,
|
|
3591
|
+
tenantId: dsn.tenantId,
|
|
3592
|
+
vendorId: dsn.vendorId,
|
|
3593
|
+
refreshMs: refreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
|
|
3594
|
+
});
|
|
3595
|
+
return new CaptureSettings(dsn.vendorId, fetcher, envCandidate(), envTask());
|
|
3596
|
+
}
|
|
3597
|
+
function validateReportMode(config, owner) {
|
|
3598
|
+
if (config.reportMode !== void 0 && !REPORT_MODES.has(config.reportMode)) {
|
|
3599
|
+
throw new Error(
|
|
3600
|
+
`${owner}.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
|
|
3601
|
+
);
|
|
3602
|
+
}
|
|
3603
|
+
}
|
|
3604
|
+
function validateSettings(config, owner) {
|
|
3605
|
+
if (config.settings !== void 0 && !SETTINGS_MODES.includes(config.settings)) {
|
|
3606
|
+
throw new Error(
|
|
3607
|
+
`${owner}.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`
|
|
3608
|
+
);
|
|
3609
|
+
}
|
|
3610
|
+
const refresh = config.settingsRefreshMs;
|
|
3611
|
+
if (refresh !== void 0 && (typeof refresh !== "number" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))) {
|
|
3612
|
+
throw new Error(
|
|
3613
|
+
`${owner}.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} to ${String(MAX_TIMER_MS)}.`
|
|
3614
|
+
);
|
|
3615
|
+
}
|
|
3616
|
+
}
|
|
3550
3617
|
function validateBatonConfig(config) {
|
|
3551
3618
|
for (const [was, now] of Object.entries(RENAMED_KEYS)) {
|
|
3552
3619
|
if (was in config) {
|
|
@@ -3563,11 +3630,7 @@ function validateBatonConfig(config) {
|
|
|
3563
3630
|
`vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
|
|
3564
3631
|
);
|
|
3565
3632
|
}
|
|
3566
|
-
|
|
3567
|
-
throw new Error(
|
|
3568
|
-
`BatonConfig.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
|
|
3569
|
-
);
|
|
3570
|
-
}
|
|
3633
|
+
validateReportMode(config, "BatonConfig");
|
|
3571
3634
|
if (!config.vendorDisplayName && config.reportMode === "on") {
|
|
3572
3635
|
throw new Error(
|
|
3573
3636
|
'BatonConfig needs a vendorDisplayName with reportMode: "on" \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4).'
|
|
@@ -3598,17 +3661,7 @@ function validateBatonConfig(config) {
|
|
|
3598
3661
|
`BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
|
|
3599
3662
|
);
|
|
3600
3663
|
}
|
|
3601
|
-
|
|
3602
|
-
throw new Error(
|
|
3603
|
-
`BatonConfig.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`
|
|
3604
|
-
);
|
|
3605
|
-
}
|
|
3606
|
-
const refresh = config.settingsRefreshMs;
|
|
3607
|
-
if (refresh !== void 0 && (typeof refresh !== "number" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))) {
|
|
3608
|
-
throw new Error(
|
|
3609
|
-
`BatonConfig.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} to ${String(MAX_TIMER_MS)}.`
|
|
3610
|
-
);
|
|
3611
|
-
}
|
|
3664
|
+
validateSettings(config, "BatonConfig");
|
|
3612
3665
|
if (config.scrubber !== void 0 && typeof config.scrubber !== "function") {
|
|
3613
3666
|
throw new Error("BatonConfig.scrubber must be a function.");
|
|
3614
3667
|
}
|
|
@@ -3742,33 +3795,35 @@ var PerCallerSurface = class {
|
|
|
3742
3795
|
}
|
|
3743
3796
|
/** `result` with the caller's goal, reports and overlay; as served on any failure. */
|
|
3744
3797
|
toolsFor(result, caller) {
|
|
3745
|
-
|
|
3746
|
-
if (settings === void 0) return result;
|
|
3747
|
-
const { intentParamMode, annotationToolName, injectsGoal } = this.options;
|
|
3748
|
-
const goal = settings.intentParamMode ?? intentParamMode;
|
|
3749
|
-
const hideReports = annotationToolName !== "" && settings.reportMode === "off";
|
|
3750
|
-
const overlay = settings.overlay;
|
|
3751
|
-
if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
|
|
3752
|
-
try {
|
|
3753
|
-
const tools = result?.tools;
|
|
3754
|
-
if (!Array.isArray(tools)) return result;
|
|
3755
|
-
const served = [];
|
|
3756
|
-
const injected = [];
|
|
3757
|
-
for (const tool of tools) {
|
|
3758
|
-
const name = tool?.name;
|
|
3759
|
-
if (hideReports && name === annotationToolName) continue;
|
|
3760
|
-
const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
|
|
3761
|
-
served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
|
|
3762
|
-
injected.push(ours);
|
|
3763
|
-
}
|
|
3764
|
-
const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
|
|
3765
|
-
return { ...result, tools: rewritten };
|
|
3766
|
-
} catch (err) {
|
|
3767
|
-
stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
|
|
3768
|
-
return result;
|
|
3769
|
-
}
|
|
3798
|
+
return toolsForCaller(result, caller.settings, this.options);
|
|
3770
3799
|
}
|
|
3771
3800
|
};
|
|
3801
|
+
function toolsForCaller(result, settings, options) {
|
|
3802
|
+
if (settings === void 0) return result;
|
|
3803
|
+
const { intentParamMode, annotationToolName, injectsGoal } = options;
|
|
3804
|
+
const goal = settings.intentParamMode ?? intentParamMode;
|
|
3805
|
+
const hideReports = annotationToolName !== "" && settings.reportMode === "off";
|
|
3806
|
+
const overlay = settings.overlay;
|
|
3807
|
+
if (goal === intentParamMode && !hideReports && overlay === void 0) return result;
|
|
3808
|
+
try {
|
|
3809
|
+
const tools = result?.tools;
|
|
3810
|
+
if (!Array.isArray(tools)) return result;
|
|
3811
|
+
const served = [];
|
|
3812
|
+
const injected = [];
|
|
3813
|
+
for (const tool of tools) {
|
|
3814
|
+
const name = tool?.name;
|
|
3815
|
+
if (hideReports && name === annotationToolName) continue;
|
|
3816
|
+
const ours = typeof name === "string" && injectsGoal(name) && declaresParam(tool?.inputSchema, USER_GOAL_PARAM_NAME);
|
|
3817
|
+
served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);
|
|
3818
|
+
injected.push(ours);
|
|
3819
|
+
}
|
|
3820
|
+
const rewritten = overlay === void 0 ? served : withOverlay(served, injected, overlay, annotationToolName || void 0);
|
|
3821
|
+
return { ...result, tools: rewritten };
|
|
3822
|
+
} catch (err) {
|
|
3823
|
+
stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);
|
|
3824
|
+
return result;
|
|
3825
|
+
}
|
|
3826
|
+
}
|
|
3772
3827
|
function batonParagraphs(pointer, overlay, subagentLine) {
|
|
3773
3828
|
const parts = overlay?.instructionAppends() ?? [];
|
|
3774
3829
|
if (pointer !== void 0) parts.push(overlaid(pointer, overlay, "instructions.report_pointer"));
|
|
@@ -3779,7 +3834,7 @@ function batonParagraphs(pointer, overlay, subagentLine) {
|
|
|
3779
3834
|
function withOverlay(tools, injected, overlay, reportTool2) {
|
|
3780
3835
|
const position = /* @__PURE__ */ new Map();
|
|
3781
3836
|
tools.forEach((tool, i) => position.set(tool?.name, i));
|
|
3782
|
-
const
|
|
3837
|
+
const hidden2 = /* @__PURE__ */ new Set();
|
|
3783
3838
|
for (const action of overlay.actions) {
|
|
3784
3839
|
if (action.tool === void 0) continue;
|
|
3785
3840
|
const i = position.get(action.tool);
|
|
@@ -3788,7 +3843,7 @@ function withOverlay(tools, injected, overlay, reportTool2) {
|
|
|
3788
3843
|
} else if (action.tool === reportTool2) {
|
|
3789
3844
|
warnSkipped(overlay.id, action.index, "the report tool takes agent_text targets only");
|
|
3790
3845
|
} else if (action.param === void 0 && action.change === "remove") {
|
|
3791
|
-
|
|
3846
|
+
hidden2.add(i);
|
|
3792
3847
|
} else if (action.param === void 0) {
|
|
3793
3848
|
tools[i] = withDescription(tools[i], [action]);
|
|
3794
3849
|
} else {
|
|
@@ -3807,7 +3862,7 @@ function withOverlay(tools, injected, overlay, reportTool2) {
|
|
|
3807
3862
|
if (reportActions.length > 0 && reportAt !== void 0) {
|
|
3808
3863
|
tools[reportAt] = withDescription(tools[reportAt], reportActions);
|
|
3809
3864
|
}
|
|
3810
|
-
return tools.filter((_, i) => !
|
|
3865
|
+
return tools.filter((_, i) => !hidden2.has(i));
|
|
3811
3866
|
}
|
|
3812
3867
|
function withDescription(tool, actions) {
|
|
3813
3868
|
const description = typeof tool.description === "string" ? tool.description : void 0;
|
|
@@ -3963,7 +4018,8 @@ function buildSeamAugmentations(options) {
|
|
|
3963
4018
|
required_names: [...options.requiredParamNames].sort(),
|
|
3964
4019
|
mode: options.intentParamMode
|
|
3965
4020
|
},
|
|
3966
|
-
instructions_suffix: options.instructionsSuffix
|
|
4021
|
+
instructions_suffix: options.instructionsSuffix,
|
|
4022
|
+
agent_text: options.agentText
|
|
3967
4023
|
};
|
|
3968
4024
|
}
|
|
3969
4025
|
|
|
@@ -4318,7 +4374,13 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
4318
4374
|
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
4319
4375
|
intentParamMode: ctx.intentParamMode,
|
|
4320
4376
|
requiredParamNames: requiredParamNames(ctx.intentParamMode),
|
|
4321
|
-
instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions())
|
|
4377
|
+
instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions()),
|
|
4378
|
+
agentText: servedAgentText({
|
|
4379
|
+
reportNames: ctx.reportNames(),
|
|
4380
|
+
intentParamMode: ctx.intentParamMode,
|
|
4381
|
+
...goalTextsServed(snapshot.tools),
|
|
4382
|
+
serverOverlay: ctx.perCaller?.serverOverlay
|
|
4383
|
+
})
|
|
4322
4384
|
});
|
|
4323
4385
|
if (ctx.captureSettings !== void 0) seam.server_overlay = overlayId;
|
|
4324
4386
|
await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
|
|
@@ -4431,16 +4493,21 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
|
|
|
4431
4493
|
}
|
|
4432
4494
|
}
|
|
4433
4495
|
};
|
|
4496
|
+
const leaveReportNameToVendor = (name) => {
|
|
4497
|
+
warnOnce2(
|
|
4498
|
+
"report-tool-name-taken",
|
|
4499
|
+
`baton: the server lists its own tool ${JSON.stringify(name)}, so Baton's report tool is not added; set annotationToolName to another name`
|
|
4500
|
+
);
|
|
4501
|
+
reportTool2 = void 0;
|
|
4502
|
+
ctx.annotationToolName = "";
|
|
4503
|
+
reportToolTaken();
|
|
4504
|
+
};
|
|
4505
|
+
const takeReportNameIfListed = (tools) => {
|
|
4506
|
+
const name = reportTool2?.name;
|
|
4507
|
+
if (name !== void 0 && tools.some((tool) => tool.name === name)) leaveReportNameToVendor(name);
|
|
4508
|
+
};
|
|
4434
4509
|
const read = (tools, { surface }) => {
|
|
4435
|
-
if (surface
|
|
4436
|
-
warnOnce2(
|
|
4437
|
-
"report-tool-name-taken",
|
|
4438
|
-
`baton: the server lists its own tool ${JSON.stringify(reportTool2.name)}, so Baton's report tool is not added; set annotationToolName to another name`
|
|
4439
|
-
);
|
|
4440
|
-
reportTool2 = void 0;
|
|
4441
|
-
ctx.annotationToolName = "";
|
|
4442
|
-
reportToolTaken();
|
|
4443
|
-
}
|
|
4510
|
+
if (surface) takeReportNameIfListed(tools);
|
|
4444
4511
|
readToolList(tools, ctx, surface, skipNote);
|
|
4445
4512
|
};
|
|
4446
4513
|
const learn = (tools) => {
|
|
@@ -4528,6 +4595,10 @@ function installLowLevelToolSeams(lowLevel, ctx, annotationTool, known, warnOnce
|
|
|
4528
4595
|
}
|
|
4529
4596
|
return batonWrap({ current: name }, () => handler(...args), ctx, unlisted, slot?.caller)(toolArgs, args[1]);
|
|
4530
4597
|
});
|
|
4598
|
+
return () => {
|
|
4599
|
+
if (Array.isArray(known.given)) takeReportNameIfListed(toolInfos(known.given, () => {
|
|
4600
|
+
}));
|
|
4601
|
+
};
|
|
4531
4602
|
}
|
|
4532
4603
|
function lowLevelMajor(lowLevel) {
|
|
4533
4604
|
return typeof lowLevel._wrapHandler === "function" ? 2 : 1;
|
|
@@ -4818,7 +4889,7 @@ async function hiddenFrom(slot, name, params, extra, ctx) {
|
|
|
4818
4889
|
}
|
|
4819
4890
|
async function answerHidden(lowLevel, name, settle) {
|
|
4820
4891
|
if (lowLevelMajor(lowLevel) === 1) {
|
|
4821
|
-
const result = { content: [{ type: "text", text:
|
|
4892
|
+
const result = { content: [{ type: "text", text: unknownToolText(name) }], isError: true };
|
|
4822
4893
|
await settle({ failed: true, raised: false, result });
|
|
4823
4894
|
return result;
|
|
4824
4895
|
}
|
|
@@ -5171,6 +5242,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned4, co
|
|
|
5171
5242
|
server,
|
|
5172
5243
|
scrubber,
|
|
5173
5244
|
annotationToolName,
|
|
5245
|
+
reportNames: () => reports && ctx.annotationToolName ? { vendorDisplayName: reports.vendorDisplayName, annotationToolName: ctx.annotationToolName } : void 0,
|
|
5174
5246
|
intentParamMode,
|
|
5175
5247
|
configResultCaptureMode: config.resultCaptureMode ?? "full",
|
|
5176
5248
|
paramRegistry: /* @__PURE__ */ new Map(),
|
|
@@ -5201,7 +5273,10 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned4, co
|
|
|
5201
5273
|
get annotationToolName() {
|
|
5202
5274
|
return ctx.annotationToolName;
|
|
5203
5275
|
},
|
|
5204
|
-
pointer: () =>
|
|
5276
|
+
pointer: () => {
|
|
5277
|
+
const names = ctx.reportNames();
|
|
5278
|
+
return names && buildReportPointer(names);
|
|
5279
|
+
},
|
|
5205
5280
|
writeInstructions,
|
|
5206
5281
|
subagentLine: () => ![...ctx.paramRegistry.values()].some((d) => d[USER_GOAL_PARAM_NAME] === "native"),
|
|
5207
5282
|
injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
|
|
@@ -5224,8 +5299,9 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned4, co
|
|
|
5224
5299
|
// `srv-..._annotate` while the instructions name the server-derived one.
|
|
5225
5300
|
annotationToolName
|
|
5226
5301
|
};
|
|
5302
|
+
let checkGivenTools;
|
|
5227
5303
|
if (shape === "lowLevel") {
|
|
5228
|
-
installLowLevelToolSeams(
|
|
5304
|
+
checkGivenTools = installLowLevelToolSeams(
|
|
5229
5305
|
lowLevel,
|
|
5230
5306
|
ctx,
|
|
5231
5307
|
annotationOptions && buildAnnotationTool(server, annotationOptions),
|
|
@@ -5269,7 +5345,10 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned4, co
|
|
|
5269
5345
|
sessionId: fallbackSessionId,
|
|
5270
5346
|
annotationToolName: name
|
|
5271
5347
|
});
|
|
5272
|
-
if (shape === "lowLevel")
|
|
5348
|
+
if (shape === "lowLevel") {
|
|
5349
|
+
checkGivenTools?.();
|
|
5350
|
+
return handle(annotationToolName);
|
|
5351
|
+
}
|
|
5273
5352
|
const resolvedAnnotationToolName = annotationOptions ? registerAnnotationTool(server, annotationOptions) : "";
|
|
5274
5353
|
const existing = internals._registeredTools;
|
|
5275
5354
|
if (existing) {
|
|
@@ -5334,6 +5413,9 @@ function principalFromOAuthEmail(context) {
|
|
|
5334
5413
|
};
|
|
5335
5414
|
}
|
|
5336
5415
|
|
|
5416
|
+
// src/library/client.ts
|
|
5417
|
+
import * as asyncHooks3 from "async_hooks";
|
|
5418
|
+
|
|
5337
5419
|
// src/library/session.ts
|
|
5338
5420
|
import * as asyncHooks2 from "async_hooks";
|
|
5339
5421
|
var TRANSPORT_LIBRARY = "library";
|
|
@@ -5347,7 +5429,8 @@ function sessionEnvelope(session) {
|
|
|
5347
5429
|
organization: session.organization,
|
|
5348
5430
|
labels: wireLabels(session.labels),
|
|
5349
5431
|
client_observed: session.clientObserved,
|
|
5350
|
-
runtime_meta: session.runtimeMeta
|
|
5432
|
+
runtime_meta: session.runtimeMeta,
|
|
5433
|
+
capture: session.settings?.capture ?? null
|
|
5351
5434
|
};
|
|
5352
5435
|
}
|
|
5353
5436
|
function warn2(message) {
|
|
@@ -5362,7 +5445,7 @@ function vendorId(name, value) {
|
|
|
5362
5445
|
return null;
|
|
5363
5446
|
}
|
|
5364
5447
|
function blank(sessionId, origin) {
|
|
5365
|
-
return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };
|
|
5448
|
+
return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null, candidate: null, task: null };
|
|
5366
5449
|
}
|
|
5367
5450
|
function requestMeta(meta) {
|
|
5368
5451
|
if (isRecord(meta)) return meta;
|
|
@@ -5385,16 +5468,48 @@ function newSession(values, scrubber, disabled) {
|
|
|
5385
5468
|
...base,
|
|
5386
5469
|
...callerFor(values.principal, (_key, message) => warn2(`principal ${message}`)),
|
|
5387
5470
|
clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber, meta),
|
|
5388
|
-
runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
|
|
5471
|
+
runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber),
|
|
5472
|
+
candidate: vendorHeader(values.headers, CANDIDATE_HEADER, candidateId),
|
|
5473
|
+
task: vendorHeader(values.headers, TASK_HEADER, taskId)
|
|
5389
5474
|
};
|
|
5390
5475
|
}
|
|
5476
|
+
function vendorHeader(headers, name, parse) {
|
|
5477
|
+
try {
|
|
5478
|
+
if (headers === void 0) return null;
|
|
5479
|
+
if (typeof headers.get === "function") return parse(headers.get(name));
|
|
5480
|
+
const key = Object.keys(headers).find((k) => k.toLowerCase() === name);
|
|
5481
|
+
return key === void 0 ? null : parse(headers[key]);
|
|
5482
|
+
} catch {
|
|
5483
|
+
return null;
|
|
5484
|
+
}
|
|
5485
|
+
}
|
|
5391
5486
|
var current = new asyncHooks2.AsyncLocalStorage();
|
|
5392
5487
|
function runInSession(owner, session, fn) {
|
|
5393
5488
|
return current.run({ owner, session }, fn);
|
|
5394
5489
|
}
|
|
5395
|
-
|
|
5396
|
-
|
|
5397
|
-
|
|
5490
|
+
var settingsWarned2 = false;
|
|
5491
|
+
function sessionForCall(owner, settings) {
|
|
5492
|
+
const session = inBlock(owner) ? current.getStore().session : blank(uuid7(), "minted");
|
|
5493
|
+
if (settings === void 0) return session;
|
|
5494
|
+
try {
|
|
5495
|
+
const callSettings = settings.forCaller({
|
|
5496
|
+
labels: session.labels,
|
|
5497
|
+
clientName: session.clientObserved?.info?.name ?? null,
|
|
5498
|
+
shareKey: session.principal?.id ?? null,
|
|
5499
|
+
candidate: session.candidate,
|
|
5500
|
+
task: session.task
|
|
5501
|
+
});
|
|
5502
|
+
return callSettings === void 0 ? session : { ...session, settings: callSettings };
|
|
5503
|
+
} catch (err) {
|
|
5504
|
+
if (!settingsWarned2) {
|
|
5505
|
+
settingsWarned2 = true;
|
|
5506
|
+
warn2(`applying capture settings failed; this call uses the client's values: ${printable(err)}`);
|
|
5507
|
+
}
|
|
5508
|
+
return session;
|
|
5509
|
+
}
|
|
5510
|
+
}
|
|
5511
|
+
function inBlock(owner) {
|
|
5512
|
+
return current.getStore()?.owner === owner;
|
|
5398
5513
|
}
|
|
5399
5514
|
|
|
5400
5515
|
// src/library/surface.ts
|
|
@@ -5426,16 +5541,22 @@ function serveTools(tools, options) {
|
|
|
5426
5541
|
return { served, surface: null };
|
|
5427
5542
|
}
|
|
5428
5543
|
}
|
|
5429
|
-
function snapshotPayload({ surface, digest }) {
|
|
5544
|
+
function snapshotPayload({ surface, digest }, seam) {
|
|
5430
5545
|
return {
|
|
5431
5546
|
surface_hash: digest,
|
|
5432
5547
|
...surface,
|
|
5433
|
-
seam_augmentations: buildSeamAugmentations({
|
|
5548
|
+
seam_augmentations: seam ?? buildSeamAugmentations({
|
|
5434
5549
|
injectedToolNames: [],
|
|
5435
5550
|
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
5436
5551
|
intentParamMode: DEFAULT_INTENT_PARAM_MODE,
|
|
5437
5552
|
requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),
|
|
5438
|
-
instructionsSuffix: null
|
|
5553
|
+
instructionsSuffix: null,
|
|
5554
|
+
agentText: servedAgentText({
|
|
5555
|
+
reportNames: void 0,
|
|
5556
|
+
intentParamMode: DEFAULT_INTENT_PARAM_MODE,
|
|
5557
|
+
...goalTextsServed(surface.tools),
|
|
5558
|
+
vendorServesText: true
|
|
5559
|
+
})
|
|
5439
5560
|
})
|
|
5440
5561
|
};
|
|
5441
5562
|
}
|
|
@@ -5444,6 +5565,315 @@ function servedEntry(tool) {
|
|
|
5444
5565
|
return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, DEFAULT_INTENT_PARAM_MODE, true) };
|
|
5445
5566
|
}
|
|
5446
5567
|
|
|
5568
|
+
// src/library/serve.ts
|
|
5569
|
+
var INITIALIZE = "initialize";
|
|
5570
|
+
var TOOL_LIST = "tools/list";
|
|
5571
|
+
var TOOL_CALL = "tools/call";
|
|
5572
|
+
var JSONRPC_ERROR_TYPE = "JSONRPCError";
|
|
5573
|
+
var REMEMBERED_TOOLS = 4096;
|
|
5574
|
+
function readRequest(message) {
|
|
5575
|
+
if (!isRecord(message) || message.id === void 0 || message.id === null) return null;
|
|
5576
|
+
const { method } = message;
|
|
5577
|
+
const params = message.params === void 0 ? {} : message.params;
|
|
5578
|
+
if (method !== INITIALIZE && method !== TOOL_LIST && method !== TOOL_CALL || !isRecord(params)) return null;
|
|
5579
|
+
return { method, params };
|
|
5580
|
+
}
|
|
5581
|
+
var OWN = /* @__PURE__ */ new Set(["native", "may_take"]);
|
|
5582
|
+
var KEPT = /* @__PURE__ */ new Set(["native", "may_take", "unread"]);
|
|
5583
|
+
function goalDispositions(schema) {
|
|
5584
|
+
if (schema === void 0 || schema === null) return { [USER_GOAL_PARAM_NAME]: "injected" };
|
|
5585
|
+
const retired = Object.fromEntries(RETIRED_PARAM_NAMES.map((name) => [name, "native"]));
|
|
5586
|
+
if (!isRecord(schema) || !isRecord(schema.properties ?? {})) {
|
|
5587
|
+
return { ...retired, [USER_GOAL_PARAM_NAME]: "unread" };
|
|
5588
|
+
}
|
|
5589
|
+
if (!takesUserGoalJson(schema)) {
|
|
5590
|
+
if (declaresParam(schema, USER_GOAL_PARAM_NAME)) return { ...retired, [USER_GOAL_PARAM_NAME]: "native" };
|
|
5591
|
+
return mayDeclareParam(schema, USER_GOAL_PARAM_NAME) ? { ...retired, [USER_GOAL_PARAM_NAME]: "may_take" } : retired;
|
|
5592
|
+
}
|
|
5593
|
+
const dispositions = {};
|
|
5594
|
+
for (const name of RETIRED_PARAM_NAMES) if (declaresParam(schema, name)) dispositions[name] = "native";
|
|
5595
|
+
dispositions[USER_GOAL_PARAM_NAME] = declaresParam(schema, USER_GOAL_PARAM_NAME) ? "native" : "injected";
|
|
5596
|
+
return dispositions;
|
|
5597
|
+
}
|
|
5598
|
+
var ownsUserGoal = (dispositions) => OWN.has(dispositions?.[USER_GOAL_PARAM_NAME]);
|
|
5599
|
+
var NO_GOALS = [null, null, null];
|
|
5600
|
+
function popGoals(args, dispositions) {
|
|
5601
|
+
const pop = (name) => {
|
|
5602
|
+
if (!(name in args) || dispositions !== void 0 && KEPT.has(dispositions[name])) return null;
|
|
5603
|
+
const value = args[name];
|
|
5604
|
+
delete args[name];
|
|
5605
|
+
return typeof value === "string" && !isBlank(value) ? value : null;
|
|
5606
|
+
};
|
|
5607
|
+
if (dispositions === void 0) return [pop(USER_GOAL_PARAM_NAME), null, null];
|
|
5608
|
+
return [pop(USER_GOAL_PARAM_NAME), pop(RETIRED_PARAM_NAMES[0]), pop(RETIRED_PARAM_NAMES[1])];
|
|
5609
|
+
}
|
|
5610
|
+
function knownTools(tools) {
|
|
5611
|
+
const dispositions = /* @__PURE__ */ new Map();
|
|
5612
|
+
const names = /* @__PURE__ */ new Set();
|
|
5613
|
+
for (const tool of tools) {
|
|
5614
|
+
try {
|
|
5615
|
+
const name = isRecord(tool) ? tool.name : void 0;
|
|
5616
|
+
if (typeof name !== "string") continue;
|
|
5617
|
+
names.add(name);
|
|
5618
|
+
dispositions.set(name, goalDispositions(tool.inputSchema));
|
|
5619
|
+
} catch {
|
|
5620
|
+
continue;
|
|
5621
|
+
}
|
|
5622
|
+
}
|
|
5623
|
+
return { dispositions, names };
|
|
5624
|
+
}
|
|
5625
|
+
function traceOptions(call) {
|
|
5626
|
+
const [intent, expected, workflow] = call.goals;
|
|
5627
|
+
return {
|
|
5628
|
+
toolName: call.name,
|
|
5629
|
+
params: call.arguments,
|
|
5630
|
+
...intent === null ? {} : { intent },
|
|
5631
|
+
...expected === null ? {} : { expectedOutcome: expected },
|
|
5632
|
+
...workflow === null ? {} : { workflow }
|
|
5633
|
+
};
|
|
5634
|
+
}
|
|
5635
|
+
var Serving = class {
|
|
5636
|
+
constructor(report, settings, tools) {
|
|
5637
|
+
this.report = report;
|
|
5638
|
+
this.settings = settings;
|
|
5639
|
+
this.unreadTools = tools;
|
|
5640
|
+
if (report !== void 0 && Array.isArray(tools)) {
|
|
5641
|
+
try {
|
|
5642
|
+
this.remember(/* @__PURE__ */ new Map(), knownTools(tools).names);
|
|
5643
|
+
} catch {
|
|
5644
|
+
}
|
|
5645
|
+
}
|
|
5646
|
+
}
|
|
5647
|
+
report;
|
|
5648
|
+
settings;
|
|
5649
|
+
serverMeta = { serverInfo: null, capabilities: null, instructions: null };
|
|
5650
|
+
dispositions = /* @__PURE__ */ new Map();
|
|
5651
|
+
vendorHasReportName = false;
|
|
5652
|
+
warnedUnlisted = false;
|
|
5653
|
+
unreadTools;
|
|
5654
|
+
/** Learn the vendor's `tools` once per process. Never throws: without them,
|
|
5655
|
+
* a call to a tool not yet listed is served as on a cold process. */
|
|
5656
|
+
readVendorTools() {
|
|
5657
|
+
const source = this.unreadTools;
|
|
5658
|
+
if (source === void 0) return;
|
|
5659
|
+
this.unreadTools = void 0;
|
|
5660
|
+
try {
|
|
5661
|
+
const tools = typeof source === "function" ? source() : source;
|
|
5662
|
+
if (isThenable(tools)) {
|
|
5663
|
+
throw new Error("tools must be an array or a plain function, not async");
|
|
5664
|
+
}
|
|
5665
|
+
if (!Array.isArray(tools)) throw new Error("tools gave something that is not an array");
|
|
5666
|
+
const known = knownTools(tools);
|
|
5667
|
+
this.remember(known.dispositions, known.names);
|
|
5668
|
+
} catch (err) {
|
|
5669
|
+
stderrLine(
|
|
5670
|
+
`baton: could not read the tools option; a call this process has not seen listed loses user_goal: ${printable(err)}`
|
|
5671
|
+
);
|
|
5672
|
+
}
|
|
5673
|
+
}
|
|
5674
|
+
remember(dispositions, names) {
|
|
5675
|
+
const fresh = [...dispositions.keys()].filter((name2) => !this.dispositions.has(name2)).length;
|
|
5676
|
+
if (this.dispositions.size + fresh > REMEMBERED_TOOLS) this.dispositions.clear();
|
|
5677
|
+
for (const [name2, disposition] of dispositions) {
|
|
5678
|
+
if (!ownsUserGoal(this.dispositions.get(name2))) this.dispositions.set(name2, disposition);
|
|
5679
|
+
}
|
|
5680
|
+
const name = this.report?.tool.name;
|
|
5681
|
+
if (name !== void 0 && names.has(name) && !this.vendorHasReportName) {
|
|
5682
|
+
this.vendorHasReportName = true;
|
|
5683
|
+
stderrLine(
|
|
5684
|
+
`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.`
|
|
5685
|
+
);
|
|
5686
|
+
}
|
|
5687
|
+
}
|
|
5688
|
+
/** The report tool, unless a vendor tool has its name. */
|
|
5689
|
+
ours() {
|
|
5690
|
+
return this.vendorHasReportName ? void 0 : this.report;
|
|
5691
|
+
}
|
|
5692
|
+
document() {
|
|
5693
|
+
return this.settings?.document ?? null;
|
|
5694
|
+
}
|
|
5695
|
+
initialized(answer) {
|
|
5696
|
+
const result = resultOf(answer);
|
|
5697
|
+
if (result === null) return answer;
|
|
5698
|
+
const vendor = result.instructions;
|
|
5699
|
+
this.readVendorTools();
|
|
5700
|
+
this.serverMeta = {
|
|
5701
|
+
serverInfo: isRecord(result.serverInfo) ? result.serverInfo : null,
|
|
5702
|
+
capabilities: isRecord(result.capabilities) ? result.capabilities : null,
|
|
5703
|
+
instructions: typeof vendor === "string" ? vendor : null
|
|
5704
|
+
};
|
|
5705
|
+
const nativeGoal = [...this.dispositions.values()].some((d) => d[USER_GOAL_PARAM_NAME] === "native");
|
|
5706
|
+
const report = this.ours();
|
|
5707
|
+
const document = this.document();
|
|
5708
|
+
const pointer = report === void 0 ? void 0 : buildReportPointer({ vendorDisplayName: report.vendorDisplayName, annotationToolName: report.tool.name });
|
|
5709
|
+
const shown = pointer !== void 0 && (document === null || document.reportsOnForAnyone);
|
|
5710
|
+
const { ours } = batonParagraphs(shown ? pointer : void 0, document?.serverOverlay, !nativeGoal);
|
|
5711
|
+
return { ...answer, result: { ...result, instructions: joined(vendor, ours) } };
|
|
5712
|
+
}
|
|
5713
|
+
listed(request, answer, settings) {
|
|
5714
|
+
const result = resultOf(answer);
|
|
5715
|
+
const tools = result?.tools;
|
|
5716
|
+
if (result === null || !Array.isArray(tools)) return null;
|
|
5717
|
+
this.readVendorTools();
|
|
5718
|
+
const { served, surface } = serveTools(tools, this.serverMeta);
|
|
5719
|
+
const known = knownTools(tools);
|
|
5720
|
+
this.remember(known.dispositions, known.names);
|
|
5721
|
+
const report = this.ours();
|
|
5722
|
+
const firstPage = request.params.cursor === void 0 || request.params.cursor === null;
|
|
5723
|
+
const out = [...served];
|
|
5724
|
+
if (report !== void 0 && firstPage) {
|
|
5725
|
+
const { name, description, inputSchema: inputSchema2 } = report.tool;
|
|
5726
|
+
out.push({ name, description, inputSchema: inputSchema2 });
|
|
5727
|
+
}
|
|
5728
|
+
const overlay = this.document()?.serverOverlay;
|
|
5729
|
+
const overlayId = overlay?.id ?? null;
|
|
5730
|
+
const listed = toolsForCaller({ ...result, tools: out }, settings, {
|
|
5731
|
+
intentParamMode: DEFAULT_INTENT_PARAM_MODE,
|
|
5732
|
+
annotationToolName: report?.tool.name ?? "",
|
|
5733
|
+
injectsGoal: (name) => known.dispositions.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
|
|
5734
|
+
});
|
|
5735
|
+
const whole = firstPage && (result.nextCursor === void 0 || result.nextCursor === null) ? surface : null;
|
|
5736
|
+
return {
|
|
5737
|
+
answer: { ...answer, result: listed },
|
|
5738
|
+
surface: whole,
|
|
5739
|
+
seam: () => {
|
|
5740
|
+
const agentText = servedAgentText({
|
|
5741
|
+
reportNames: report === void 0 ? void 0 : { vendorDisplayName: report.vendorDisplayName, annotationToolName: report.tool.name },
|
|
5742
|
+
intentParamMode: DEFAULT_INTENT_PARAM_MODE,
|
|
5743
|
+
...goalTextsServed(whole?.surface.tools ?? []),
|
|
5744
|
+
serverOverlay: overlay
|
|
5745
|
+
});
|
|
5746
|
+
const seam = buildSeamAugmentations({
|
|
5747
|
+
injectedToolNames: report === void 0 ? [] : [report.tool.name],
|
|
5748
|
+
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
5749
|
+
intentParamMode: DEFAULT_INTENT_PARAM_MODE,
|
|
5750
|
+
requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),
|
|
5751
|
+
instructionsSuffix: instructionsSuffix(agentText),
|
|
5752
|
+
agentText
|
|
5753
|
+
});
|
|
5754
|
+
if (this.settings !== void 0) seam.server_overlay = overlayId;
|
|
5755
|
+
return seam;
|
|
5756
|
+
},
|
|
5757
|
+
serverOverlay: overlayId
|
|
5758
|
+
};
|
|
5759
|
+
}
|
|
5760
|
+
/** The plan for one `tools/call`; `null` sends it to dispatch untraced. */
|
|
5761
|
+
call(request, message, settings) {
|
|
5762
|
+
const { name } = request.params;
|
|
5763
|
+
const args = request.params.arguments === void 0 ? {} : request.params.arguments;
|
|
5764
|
+
if (typeof name !== "string" || !isRecord(args)) return null;
|
|
5765
|
+
this.readVendorTools();
|
|
5766
|
+
const dispositions = this.dispositions.get(name);
|
|
5767
|
+
const report = this.ours();
|
|
5768
|
+
if (report !== void 0 && name === report.tool.name) return reportCall(report.tool, name, args, message, settings);
|
|
5769
|
+
if (dispositions === void 0 && USER_GOAL_PARAM_NAME in args && !this.warnedUnlisted) {
|
|
5770
|
+
this.warnedUnlisted = true;
|
|
5771
|
+
stderrLine(
|
|
5772
|
+
`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`
|
|
5773
|
+
);
|
|
5774
|
+
}
|
|
5775
|
+
const stripped = { ...args };
|
|
5776
|
+
const goals = popGoals(stripped, dispositions);
|
|
5777
|
+
if (settings?.overlay?.hiddenTools.has(name)) return hidden(name, stripped, goals, message);
|
|
5778
|
+
const forwarded = Object.keys(stripped).length === Object.keys(args).length ? message : { ...message, params: { ...request.params, arguments: stripped } };
|
|
5779
|
+
return { name, arguments: stripped, goals, message: forwarded, kind: "forward" };
|
|
5780
|
+
}
|
|
5781
|
+
};
|
|
5782
|
+
function reportCall(tool, name, args, message, settings) {
|
|
5783
|
+
if (settings?.reportMode === "off") return hidden(name, { ...args }, NO_GOALS, message);
|
|
5784
|
+
const report = tool.annotateArgs(args);
|
|
5785
|
+
const body = report === null ? { ok: false, error: buildRefusalText({ annotationToolName: name, overlay: settings?.overlay }) } : { ok: true };
|
|
5786
|
+
return {
|
|
5787
|
+
name,
|
|
5788
|
+
arguments: { ...args },
|
|
5789
|
+
goals: NO_GOALS,
|
|
5790
|
+
message,
|
|
5791
|
+
kind: report === null ? "refused" : "report",
|
|
5792
|
+
answer: answerTo(message, { content: [{ type: "text", text: JSON.stringify(body) }], structuredContent: body }),
|
|
5793
|
+
...report === null ? {} : { report }
|
|
5794
|
+
};
|
|
5795
|
+
}
|
|
5796
|
+
function hidden(name, args, goals, message) {
|
|
5797
|
+
const result = { content: [{ type: "text", text: unknownToolText(name) }], isError: true };
|
|
5798
|
+
return { name, arguments: args, goals, message, kind: "hidden", answer: answerTo(message, result) };
|
|
5799
|
+
}
|
|
5800
|
+
function withoutUserGoal(message) {
|
|
5801
|
+
try {
|
|
5802
|
+
const params = message.params;
|
|
5803
|
+
const args = params.arguments;
|
|
5804
|
+
if (!isRecord(args) || !(USER_GOAL_PARAM_NAME in args)) return message;
|
|
5805
|
+
const stripped = Object.fromEntries(Object.entries(args).filter(([key]) => key !== USER_GOAL_PARAM_NAME));
|
|
5806
|
+
return { ...message, params: { ...params, arguments: stripped } };
|
|
5807
|
+
} catch {
|
|
5808
|
+
return message;
|
|
5809
|
+
}
|
|
5810
|
+
}
|
|
5811
|
+
function jsonRpcError(answer) {
|
|
5812
|
+
return isRecord(answer) && isRecord(answer.error) ? answer.error : null;
|
|
5813
|
+
}
|
|
5814
|
+
function resultOf(answer) {
|
|
5815
|
+
return isRecord(answer) && isRecord(answer.result) ? { ...answer.result } : null;
|
|
5816
|
+
}
|
|
5817
|
+
function isToolErrorResult(result) {
|
|
5818
|
+
return result !== null && Array.isArray(result.content) && result.isError === true;
|
|
5819
|
+
}
|
|
5820
|
+
function answerTo(message, result) {
|
|
5821
|
+
return { jsonrpc: message.jsonrpc ?? "2.0", id: message.id, result };
|
|
5822
|
+
}
|
|
5823
|
+
function instructionsSuffix(agentText) {
|
|
5824
|
+
const pieces = INSTRUCTION_PIECES.filter((piece) => piece in agentText).map((piece) => agentText[piece]);
|
|
5825
|
+
return pieces.includes(null) ? null : pieces.length > 0;
|
|
5826
|
+
}
|
|
5827
|
+
|
|
5828
|
+
// src/library/reportTool.ts
|
|
5829
|
+
function inputSchema() {
|
|
5830
|
+
const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
|
|
5831
|
+
delete schema.$schema;
|
|
5832
|
+
return { ...schema, required: [...schema.required, TOOL_NAME_PARAM_NAME] };
|
|
5833
|
+
}
|
|
5834
|
+
var nonEmptyText = (value) => typeof value === "string" && value !== "";
|
|
5835
|
+
var nonEmptyObject = (value) => isRecord(value) && Object.keys(value).length > 0;
|
|
5836
|
+
function annotateArgs(args) {
|
|
5837
|
+
const whatHappened = args.what_happened;
|
|
5838
|
+
if (!isReport(whatHappened)) return null;
|
|
5839
|
+
const options = { whatHappened };
|
|
5840
|
+
const toolName = args[TOOL_NAME_PARAM_NAME];
|
|
5841
|
+
if (typeof toolName === "string") options.toolName = toolName;
|
|
5842
|
+
const intent = args[USER_GOAL_PARAM_NAME];
|
|
5843
|
+
if (nonEmptyText(intent)) options.intent = intent;
|
|
5844
|
+
if (nonEmptyText(args.suggested_improvement)) {
|
|
5845
|
+
options.suggestedImprovement = args.suggested_improvement;
|
|
5846
|
+
}
|
|
5847
|
+
if (nonEmptyObject(args.context)) options.context = args.context;
|
|
5848
|
+
return options;
|
|
5849
|
+
}
|
|
5850
|
+
function reportTool(options) {
|
|
5851
|
+
const { vendorDisplayName } = options;
|
|
5852
|
+
if (isBlank(vendorDisplayName)) {
|
|
5853
|
+
throw new Error("vendorDisplayName is blank. Baton's report sentence names the server by it.");
|
|
5854
|
+
}
|
|
5855
|
+
const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);
|
|
5856
|
+
if (derived === void 0) {
|
|
5857
|
+
throw new Error(
|
|
5858
|
+
`vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, or one too long for Baton's report sentence. Pass name.`
|
|
5859
|
+
);
|
|
5860
|
+
}
|
|
5861
|
+
const name = validateAnnotationToolName(derived);
|
|
5862
|
+
if (!fitsBatonSentenceCap({ vendorDisplayName, annotationToolName: name })) {
|
|
5863
|
+
throw new Error(
|
|
5864
|
+
`vendorDisplayName and name ${JSON.stringify(name)} are too long together for Baton's report sentence. Shorten one of them.`
|
|
5865
|
+
);
|
|
5866
|
+
}
|
|
5867
|
+
return {
|
|
5868
|
+
name,
|
|
5869
|
+
description: buildAnnotationToolDescription({ vendorDisplayName }),
|
|
5870
|
+
inputSchema: inputSchema(),
|
|
5871
|
+
instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),
|
|
5872
|
+
refusal: buildRefusalText({ annotationToolName: name }),
|
|
5873
|
+
annotateArgs
|
|
5874
|
+
};
|
|
5875
|
+
}
|
|
5876
|
+
|
|
5447
5877
|
// src/library/client.ts
|
|
5448
5878
|
function fromEnv(name) {
|
|
5449
5879
|
const value = typeof process !== "undefined" ? process.env?.[name] : void 0;
|
|
@@ -5467,6 +5897,7 @@ function resolveClientOptions(options) {
|
|
|
5467
5897
|
if (options.scrubber !== void 0 && typeof options.scrubber !== "function") {
|
|
5468
5898
|
throw new Error("Client scrubber must be a function.");
|
|
5469
5899
|
}
|
|
5900
|
+
validateServeOptions(options);
|
|
5470
5901
|
const dsnString = selectDsn(
|
|
5471
5902
|
options.dsn,
|
|
5472
5903
|
{
|
|
@@ -5476,15 +5907,25 @@ function resolveClientOptions(options) {
|
|
|
5476
5907
|
},
|
|
5477
5908
|
"Client"
|
|
5478
5909
|
);
|
|
5910
|
+
if (options.settings === "console" && dsnString === void 0) {
|
|
5911
|
+
throw new Error(`Client settings: "console" reads the Capture page with the dsn's key, so it needs a dsn.`);
|
|
5912
|
+
}
|
|
5913
|
+
candidateNeedsConsole(options.settings);
|
|
5914
|
+
const reportOn = (options.reportMode ?? (options.settings === "console" ? "on" : "off")) === "on";
|
|
5479
5915
|
const consentToken = resolveConsentToken(options.consentToken);
|
|
5480
5916
|
if (dsnString !== void 0) {
|
|
5481
5917
|
const dsn = parseDsn(dsnString);
|
|
5918
|
+
const consoleSettings = options.settings === "console" && !consoleDroppedOnWorkers(options.settings);
|
|
5482
5919
|
return {
|
|
5483
5920
|
sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
|
|
5484
5921
|
vendorId: dsn.vendorId,
|
|
5485
5922
|
tenantId: dsn.tenantId,
|
|
5486
5923
|
consentToken,
|
|
5487
|
-
resultCaptureMode
|
|
5924
|
+
resultCaptureMode,
|
|
5925
|
+
...consoleSettings ? {
|
|
5926
|
+
captureSettings: consoleCaptureSettings(dsn, options.settingsRefreshMs)
|
|
5927
|
+
} : {},
|
|
5928
|
+
...reportOn ? { report: serveReport(dsn.vendorId, options.vendorDisplayName) } : {}
|
|
5488
5929
|
};
|
|
5489
5930
|
}
|
|
5490
5931
|
if (options.sink === void 0) {
|
|
@@ -5501,9 +5942,22 @@ function resolveClientOptions(options) {
|
|
|
5501
5942
|
vendorId: vendorId2,
|
|
5502
5943
|
tenantId: resolveTenantId(options.tenantId || void 0, vendorId2),
|
|
5503
5944
|
consentToken,
|
|
5504
|
-
resultCaptureMode
|
|
5945
|
+
resultCaptureMode,
|
|
5946
|
+
...reportOn ? { report: serveReport(vendorId2, options.vendorDisplayName) } : {}
|
|
5505
5947
|
};
|
|
5506
5948
|
}
|
|
5949
|
+
function validateServeOptions(options) {
|
|
5950
|
+
validateSettings(options, "Client");
|
|
5951
|
+
validateReportMode(options, "Client");
|
|
5952
|
+
if (options.tools !== void 0 && !Array.isArray(options.tools) && typeof options.tools !== "function") {
|
|
5953
|
+
throw new Error("Client tools must be an array of tools or a function that returns one.");
|
|
5954
|
+
}
|
|
5955
|
+
}
|
|
5956
|
+
function serveReport(vendorId2, displayName) {
|
|
5957
|
+
const display = displayName === void 0 || isBlank(displayName) ? vendorId2 : displayName;
|
|
5958
|
+
const name = deriveAnnotationToolName(vendorId2, toolNameForDisplayName(display));
|
|
5959
|
+
return { tool: reportTool({ vendorDisplayName: display, name }), vendorDisplayName: display };
|
|
5960
|
+
}
|
|
5507
5961
|
var hasText2 = (value) => typeof value === "string" && !isBlank(value);
|
|
5508
5962
|
function describeError(err) {
|
|
5509
5963
|
let type = "Error";
|
|
@@ -5535,6 +5989,7 @@ var Core = class {
|
|
|
5535
5989
|
resultCaptureMode;
|
|
5536
5990
|
scrubber;
|
|
5537
5991
|
disabled;
|
|
5992
|
+
settings;
|
|
5538
5993
|
constructor(resolved) {
|
|
5539
5994
|
this.sink = offTheCall(resolved.sink);
|
|
5540
5995
|
this.vendorId = resolved.vendorId;
|
|
@@ -5543,6 +5998,10 @@ var Core = class {
|
|
|
5543
5998
|
this.resultCaptureMode = resolved.resultCaptureMode;
|
|
5544
5999
|
this.scrubber = resolved.scrubber;
|
|
5545
6000
|
this.disabled = resolved.disabled;
|
|
6001
|
+
this.settings = resolved.captureSettings;
|
|
6002
|
+
}
|
|
6003
|
+
modeFor(session) {
|
|
6004
|
+
return session.settings?.resultCaptureMode ?? this.resultCaptureMode;
|
|
5546
6005
|
}
|
|
5547
6006
|
/** The envelope members every event of `session` shares. Call inside a
|
|
5548
6007
|
* build thunk, so `captured_at` is the build time. */
|
|
@@ -5556,6 +6015,9 @@ var Core = class {
|
|
|
5556
6015
|
consent_token: consentToken
|
|
5557
6016
|
};
|
|
5558
6017
|
}
|
|
6018
|
+
errorBody(text) {
|
|
6019
|
+
return scrubbedErrorBody(this.scrubber, text);
|
|
6020
|
+
}
|
|
5559
6021
|
/** False when nothing may be emitted: the off switch, or a closed client. */
|
|
5560
6022
|
live() {
|
|
5561
6023
|
if (this.disabled) return false;
|
|
@@ -5569,9 +6031,9 @@ var Core = class {
|
|
|
5569
6031
|
}
|
|
5570
6032
|
/** Sends `surface` unless this client already has. Never rejects. The
|
|
5571
6033
|
* write only queues, so a surface counts as sent once queued. */
|
|
5572
|
-
sendSurface(surface) {
|
|
5573
|
-
if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();
|
|
5574
|
-
this.sentSurfaces.mark(surface.digest);
|
|
6034
|
+
sendSurface(surface, seam, serverOverlay = null) {
|
|
6035
|
+
if (this.sentSurfaces.wasSent(surface.digest, serverOverlay) || !this.live()) return Promise.resolve();
|
|
6036
|
+
this.sentSurfaces.mark(surface.digest, serverOverlay);
|
|
5575
6037
|
let event;
|
|
5576
6038
|
try {
|
|
5577
6039
|
event = SurfaceSnapshotEventSchema.parse({
|
|
@@ -5582,7 +6044,7 @@ var Core = class {
|
|
|
5582
6044
|
sequence_number: nextClockSequence(),
|
|
5583
6045
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5584
6046
|
consent_token: this.consentToken,
|
|
5585
|
-
payload: snapshotPayload(surface)
|
|
6047
|
+
payload: snapshotPayload(surface, seam?.())
|
|
5586
6048
|
});
|
|
5587
6049
|
} catch (err) {
|
|
5588
6050
|
PROCESS_DROPS.add("encode_failed");
|
|
@@ -5617,6 +6079,7 @@ var Core = class {
|
|
|
5617
6079
|
var UNSET = /* @__PURE__ */ Symbol("unset");
|
|
5618
6080
|
var WITHHELD_RESULT = /* @__PURE__ */ Symbol("withheld");
|
|
5619
6081
|
var SCRUB_FAILED = /* @__PURE__ */ Symbol("scrubFailed");
|
|
6082
|
+
var observeFailure;
|
|
5620
6083
|
var runTrace;
|
|
5621
6084
|
var Trace = class _Trace {
|
|
5622
6085
|
#core;
|
|
@@ -5627,6 +6090,7 @@ var Trace = class _Trace {
|
|
|
5627
6090
|
#startedAt = 0;
|
|
5628
6091
|
#result = UNSET;
|
|
5629
6092
|
#error = null;
|
|
6093
|
+
#failure = null;
|
|
5630
6094
|
#observedWarned = false;
|
|
5631
6095
|
constructor(core, session, options) {
|
|
5632
6096
|
this.#core = core;
|
|
@@ -5648,6 +6112,7 @@ var Trace = class _Trace {
|
|
|
5648
6112
|
}
|
|
5649
6113
|
this.#result = UNSET;
|
|
5650
6114
|
this.#error = null;
|
|
6115
|
+
this.#failure = null;
|
|
5651
6116
|
if (this.#core.disabled) return this;
|
|
5652
6117
|
let errorType = failure?.errorType;
|
|
5653
6118
|
let errorBody2 = failure?.errorBody;
|
|
@@ -5658,7 +6123,7 @@ var Trace = class _Trace {
|
|
|
5658
6123
|
}
|
|
5659
6124
|
if (errorType !== void 0 || errorBody2 !== void 0) {
|
|
5660
6125
|
this.#error = { type: errorType || "Error", body: errorBody2 ?? "" };
|
|
5661
|
-
} else if (this.#core.
|
|
6126
|
+
} else if (this.#core.modeFor(this.#session) === WITHHELD) {
|
|
5662
6127
|
this.#result = WITHHELD_RESULT;
|
|
5663
6128
|
} else {
|
|
5664
6129
|
try {
|
|
@@ -5734,23 +6199,40 @@ var Trace = class _Trace {
|
|
|
5734
6199
|
#fail(err) {
|
|
5735
6200
|
const durationMs = this.#durationMs();
|
|
5736
6201
|
if (!this.#core.live()) return;
|
|
5737
|
-
|
|
6202
|
+
const [type, body] = describeError(err);
|
|
6203
|
+
if (this.#core.modeFor(this.#session) === WITHHELD) {
|
|
6204
|
+
this.#failure = { result: null, result_capture: WITHHELD };
|
|
6205
|
+
this.#emitError(nextClockSequence(), type, "", durationMs);
|
|
6206
|
+
return;
|
|
6207
|
+
}
|
|
6208
|
+
this.#emitError(nextClockSequence(), type, body, durationMs);
|
|
5738
6209
|
}
|
|
5739
6210
|
#emitError(sequence, type, body, durationMs) {
|
|
6211
|
+
const failure = this.#failure;
|
|
5740
6212
|
void this.#core.emit(
|
|
5741
6213
|
() => ToolCallErrorEventSchema.parse({
|
|
5742
6214
|
...this.#envelope(sequence),
|
|
5743
6215
|
payload: {
|
|
5744
6216
|
tool_name: this.#options.toolName,
|
|
5745
6217
|
error_type: type,
|
|
5746
|
-
error_body: scrubbedErrorBody(this.#core.scrubber, body),
|
|
6218
|
+
error_body: failure === null ? scrubbedErrorBody(this.#core.scrubber, body) : body,
|
|
5747
6219
|
duration_ms: durationMs,
|
|
5748
|
-
result: null
|
|
6220
|
+
result: null,
|
|
6221
|
+
...failure
|
|
5749
6222
|
}
|
|
5750
6223
|
})
|
|
5751
6224
|
);
|
|
5752
6225
|
}
|
|
5753
6226
|
static {
|
|
6227
|
+
observeFailure = (trace, errorType, fields, failureKind) => {
|
|
6228
|
+
trace.#result = UNSET;
|
|
6229
|
+
trace.#error = { type: errorType, body: fields.error_body };
|
|
6230
|
+
trace.#failure = {
|
|
6231
|
+
result: fields.result,
|
|
6232
|
+
...fields.result_capture === void 0 ? {} : { result_capture: fields.result_capture },
|
|
6233
|
+
...failureKind === void 0 ? {} : { failure_kind: failureKind }
|
|
6234
|
+
};
|
|
6235
|
+
};
|
|
5754
6236
|
runTrace = (core, session, options, fn) => {
|
|
5755
6237
|
const trace = new _Trace(core, session, options);
|
|
5756
6238
|
trace.#start();
|
|
@@ -5778,8 +6260,40 @@ var Trace = class _Trace {
|
|
|
5778
6260
|
};
|
|
5779
6261
|
}
|
|
5780
6262
|
};
|
|
6263
|
+
var Mark = class {
|
|
6264
|
+
constructor(owner, flags) {
|
|
6265
|
+
this.owner = owner;
|
|
6266
|
+
this.flags = flags;
|
|
6267
|
+
}
|
|
6268
|
+
owner;
|
|
6269
|
+
flags;
|
|
6270
|
+
active = true;
|
|
6271
|
+
};
|
|
6272
|
+
var inDispatch = new asyncHooks3.AsyncLocalStorage();
|
|
6273
|
+
async function dispatched(dispatch, message, mark = null) {
|
|
6274
|
+
try {
|
|
6275
|
+
return await inDispatch.run(mark, () => dispatch(message));
|
|
6276
|
+
} finally {
|
|
6277
|
+
if (mark !== null) mark.active = false;
|
|
6278
|
+
}
|
|
6279
|
+
}
|
|
6280
|
+
function messageText(message) {
|
|
6281
|
+
if (typeof message === "string") return message;
|
|
6282
|
+
return message === void 0 ? "" : JSON.stringify(message) ?? "";
|
|
6283
|
+
}
|
|
6284
|
+
function fieldsOrEmpty(build) {
|
|
6285
|
+
try {
|
|
6286
|
+
return build();
|
|
6287
|
+
} catch (err) {
|
|
6288
|
+
stderrLine(`baton: the scrubber threw on an error answer; its text is dropped: ${printable(err)}`);
|
|
6289
|
+
return { error_body: "", result: null };
|
|
6290
|
+
}
|
|
6291
|
+
}
|
|
6292
|
+
var stopWhenDropped = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((s) => s.stop()) : void 0;
|
|
5781
6293
|
var Client = class {
|
|
5782
6294
|
#core;
|
|
6295
|
+
#serving;
|
|
6296
|
+
#doubleWiringLogged = /* @__PURE__ */ new Set();
|
|
5783
6297
|
#closing;
|
|
5784
6298
|
constructor(options = {}) {
|
|
5785
6299
|
const switchName = captureDisabled();
|
|
@@ -5801,6 +6315,11 @@ var Client = class {
|
|
|
5801
6315
|
scrubber: options.scrubber ?? new Scrubber().scrub,
|
|
5802
6316
|
disabled: switchName !== null
|
|
5803
6317
|
});
|
|
6318
|
+
this.#serving = new Serving(resolved.report, resolved.captureSettings, switchName === null ? options.tools : void 0);
|
|
6319
|
+
if (resolved.captureSettings !== void 0) {
|
|
6320
|
+
resolved.captureSettings.start();
|
|
6321
|
+
stopWhenDropped?.register(this, resolved.captureSettings);
|
|
6322
|
+
}
|
|
5804
6323
|
}
|
|
5805
6324
|
/** Run `fn` with one session, principal, client and turn for every
|
|
5806
6325
|
* `trace()` and `annotate()` inside it, including after its awaits. Open
|
|
@@ -5821,7 +6340,8 @@ var Client = class {
|
|
|
5821
6340
|
* called exactly once, so a lazy query builder is not run twice. A throw or
|
|
5822
6341
|
* rejection is recorded and passed on unchanged. */
|
|
5823
6342
|
trace(options, fn) {
|
|
5824
|
-
|
|
6343
|
+
this.#flagDoubleWiring("trace");
|
|
6344
|
+
return runTrace(this.#core, sessionForCall(this, this.#core.settings), options ?? {}, fn);
|
|
5825
6345
|
}
|
|
5826
6346
|
/** `fn`, traced on every call. A single plain-object argument is sent as
|
|
5827
6347
|
* `params`, as an MCP tool's arguments are; other arguments as
|
|
@@ -5837,7 +6357,11 @@ var Client = class {
|
|
|
5837
6357
|
* own outside one. To report on a traced call, use `trace.annotate()`. */
|
|
5838
6358
|
annotate(options) {
|
|
5839
6359
|
const given = options ?? {};
|
|
5840
|
-
return this.#core.annotate(
|
|
6360
|
+
return this.#core.annotate(
|
|
6361
|
+
sessionForCall(this, this.#core.settings),
|
|
6362
|
+
given.consentToken || this.#core.consentToken,
|
|
6363
|
+
given
|
|
6364
|
+
);
|
|
5841
6365
|
}
|
|
5842
6366
|
/** `tools`, the vendor's own `tools/list` entries, with `user_goal` added
|
|
5843
6367
|
* to each `inputSchema` as `withBaton` adds it, and a `surface_snapshot`
|
|
@@ -5850,11 +6374,176 @@ var Client = class {
|
|
|
5850
6374
|
* tool list: one it cannot read is returned as it came. Does not wait for
|
|
5851
6375
|
* the snapshot to be sent; `flush()` does. */
|
|
5852
6376
|
async listTools(tools, options = {}) {
|
|
6377
|
+
this.#flagDoubleWiring("listTools");
|
|
5853
6378
|
if (this.#core.disabled) return tools;
|
|
5854
6379
|
const { served, surface } = serveTools(tools, options);
|
|
5855
6380
|
if (surface !== null) void this.#core.sendSurface(surface);
|
|
5856
6381
|
return served;
|
|
5857
6382
|
}
|
|
6383
|
+
/** Answer one MCP JSON-RPC `message` with `dispatch`, the vendor's own
|
|
6384
|
+
* function from message to answer, and Baton around it (SPEC §5.6).
|
|
6385
|
+
* Experimental.
|
|
6386
|
+
*
|
|
6387
|
+
* `initialize` gets Baton's instructions. `tools/list` gets `user_goal` and
|
|
6388
|
+
* the report tool, under the caller's Console settings, and sends the
|
|
6389
|
+
* snapshot. `tools/call` is traced, with `user_goal` removed before
|
|
6390
|
+
* `dispatch` sees it; Baton answers the report tool and a tool the caller's
|
|
6391
|
+
* overlay hides itself. Anything else goes to `dispatch` as it came.
|
|
6392
|
+
*
|
|
6393
|
+
* `options` are as on `session()`. A process learns the vendor's tools from
|
|
6394
|
+
* the lists it serves. Until it has, a call loses `user_goal` and the report
|
|
6395
|
+
* tool's name is Baton's; pass the `tools` option when a tool declares its
|
|
6396
|
+
* own `user_goal` or has the report tool's name. `dispatch` is called at
|
|
6397
|
+
* most once, and what it returns or throws comes back unchanged apart from
|
|
6398
|
+
* Baton's additions. A failure in Baton's own work is logged, never thrown. */
|
|
6399
|
+
serve(message, dispatch, options = {}) {
|
|
6400
|
+
return inDispatch.run(null, () => this.#serve(message, dispatch, options ?? {}));
|
|
6401
|
+
}
|
|
6402
|
+
async #serve(message, dispatch, options) {
|
|
6403
|
+
const request = this.#request(message);
|
|
6404
|
+
if (request === null) return dispatched(dispatch, message);
|
|
6405
|
+
const settings = this.#core.settings;
|
|
6406
|
+
if (settings !== void 0 && !settings.isReady) await settings.ready;
|
|
6407
|
+
const handle = () => this.#handle(request, message, dispatch);
|
|
6408
|
+
const { principal, headers, sessionId } = options;
|
|
6409
|
+
if (inBlock(this) && principal === void 0 && headers === void 0 && sessionId === void 0) return handle();
|
|
6410
|
+
const values = {
|
|
6411
|
+
...principal === void 0 ? {} : { principal },
|
|
6412
|
+
...headers === void 0 ? {} : { headers },
|
|
6413
|
+
...sessionId === void 0 ? {} : { sessionId }
|
|
6414
|
+
};
|
|
6415
|
+
try {
|
|
6416
|
+
if (isRecord(request.params._meta)) values.meta = request.params._meta;
|
|
6417
|
+
if (request.method === "initialize" && isRecord(request.params.clientInfo)) {
|
|
6418
|
+
values.clientInfo = request.params.clientInfo;
|
|
6419
|
+
}
|
|
6420
|
+
} catch {
|
|
6421
|
+
}
|
|
6422
|
+
return this.session(values, handle);
|
|
6423
|
+
}
|
|
6424
|
+
async #handle(request, message, dispatch) {
|
|
6425
|
+
let session;
|
|
6426
|
+
let call = null;
|
|
6427
|
+
try {
|
|
6428
|
+
session = sessionForCall(this, this.#core.settings);
|
|
6429
|
+
if (request.method === TOOL_CALL) call = this.#serving.call(request, message, session.settings);
|
|
6430
|
+
} catch (err) {
|
|
6431
|
+
stderrLine(`baton: serve() could not read the request; it is served as it came: ${printable(err)}`);
|
|
6432
|
+
return dispatched(dispatch, withoutUserGoal(message));
|
|
6433
|
+
}
|
|
6434
|
+
if (request.method !== TOOL_CALL) {
|
|
6435
|
+
const mark = request.method === TOOL_LIST ? new Mark(this, "listTools") : null;
|
|
6436
|
+
return this.#shaped(request, await dispatched(dispatch, message, mark), session);
|
|
6437
|
+
}
|
|
6438
|
+
if (call === null) return dispatched(dispatch, message);
|
|
6439
|
+
if (call.answer !== void 0) {
|
|
6440
|
+
this.#answerOurselves(call, session);
|
|
6441
|
+
return call.answer;
|
|
6442
|
+
}
|
|
6443
|
+
return this.#traced(call, dispatch, session);
|
|
6444
|
+
}
|
|
6445
|
+
#request(message) {
|
|
6446
|
+
if (this.#core.disabled) return null;
|
|
6447
|
+
try {
|
|
6448
|
+
return readRequest(message);
|
|
6449
|
+
} catch (err) {
|
|
6450
|
+
stderrLine(`baton: serve() could not read the request; it is served as it came: ${printable(err)}`);
|
|
6451
|
+
return null;
|
|
6452
|
+
}
|
|
6453
|
+
}
|
|
6454
|
+
/** Dispatch's `initialize` or `tools/list` answer with Baton's additions,
|
|
6455
|
+
* and its snapshot sent; the answer unchanged on failure. */
|
|
6456
|
+
#shaped(request, answer, session) {
|
|
6457
|
+
try {
|
|
6458
|
+
if (request.method !== TOOL_LIST) return this.#serving.initialized(answer);
|
|
6459
|
+
const listed = this.#serving.listed(request, answer, session.settings);
|
|
6460
|
+
if (listed === null) return answer;
|
|
6461
|
+
if (listed.surface !== null) void this.#core.sendSurface(listed.surface, listed.seam, listed.serverOverlay);
|
|
6462
|
+
return listed.answer;
|
|
6463
|
+
} catch (err) {
|
|
6464
|
+
stderrLine(`baton: serve() could not add to the answer; it is served as it came: ${printable(err)}`);
|
|
6465
|
+
return answer;
|
|
6466
|
+
}
|
|
6467
|
+
}
|
|
6468
|
+
async #traced(call, dispatch, session) {
|
|
6469
|
+
let dispatching = false;
|
|
6470
|
+
try {
|
|
6471
|
+
return await runTrace(this.#core, session, traceOptions(call), async (trace) => {
|
|
6472
|
+
dispatching = true;
|
|
6473
|
+
const answer = await dispatched(dispatch, call.message, new Mark(this, "trace"));
|
|
6474
|
+
this.#record(trace, answer, session);
|
|
6475
|
+
return answer;
|
|
6476
|
+
});
|
|
6477
|
+
} catch (err) {
|
|
6478
|
+
if (dispatching) throw err;
|
|
6479
|
+
stderrLine(`baton: serve() could not trace the call: ${printable(err)}`);
|
|
6480
|
+
return dispatched(dispatch, call.message, new Mark(this, "trace"));
|
|
6481
|
+
}
|
|
6482
|
+
}
|
|
6483
|
+
#record(trace, answer, session) {
|
|
6484
|
+
const mode = this.#core.modeFor(session);
|
|
6485
|
+
const scrubber = this.#core.scrubber;
|
|
6486
|
+
const errorBody2 = (text) => this.#core.errorBody(text);
|
|
6487
|
+
try {
|
|
6488
|
+
const error = jsonRpcError(answer);
|
|
6489
|
+
if (error !== null) {
|
|
6490
|
+
observeFailure(
|
|
6491
|
+
trace,
|
|
6492
|
+
JSONRPC_ERROR_TYPE,
|
|
6493
|
+
fieldsOrEmpty(
|
|
6494
|
+
() => resultDerivedFields(mode, () => messageText(error.message), { ...error }, errorBody2, scrubber)
|
|
6495
|
+
)
|
|
6496
|
+
);
|
|
6497
|
+
return;
|
|
6498
|
+
}
|
|
6499
|
+
const result = resultOf(answer);
|
|
6500
|
+
if (isToolErrorResult(result)) {
|
|
6501
|
+
observeFailure(
|
|
6502
|
+
trace,
|
|
6503
|
+
TOOL_ERROR_TYPE,
|
|
6504
|
+
fieldsOrEmpty(() => returnedErrorFields(mode, result, errorBody2, scrubber))
|
|
6505
|
+
);
|
|
6506
|
+
return;
|
|
6507
|
+
}
|
|
6508
|
+
trace.observed(result ?? answer);
|
|
6509
|
+
} catch (err) {
|
|
6510
|
+
stderrLine(`baton: serve() could not record the tool call: ${printable(err)}`);
|
|
6511
|
+
try {
|
|
6512
|
+
trace.observed(void 0);
|
|
6513
|
+
} catch {
|
|
6514
|
+
}
|
|
6515
|
+
}
|
|
6516
|
+
}
|
|
6517
|
+
#answerOurselves(call, session) {
|
|
6518
|
+
try {
|
|
6519
|
+
if (call.report !== void 0) {
|
|
6520
|
+
void this.#core.annotate(session, this.#core.consentToken, call.report);
|
|
6521
|
+
} else if (call.kind === "hidden") {
|
|
6522
|
+
const scrubber = this.#core.scrubber;
|
|
6523
|
+
const fields = fieldsOrEmpty(
|
|
6524
|
+
() => returnedErrorFields("full", call.answer.result, (text) => this.#core.errorBody(text), scrubber)
|
|
6525
|
+
);
|
|
6526
|
+
runTrace(
|
|
6527
|
+
this.#core,
|
|
6528
|
+
session,
|
|
6529
|
+
traceOptions(call),
|
|
6530
|
+
(trace) => observeFailure(trace, TOOL_ERROR_TYPE, fields, "tool_hidden")
|
|
6531
|
+
);
|
|
6532
|
+
}
|
|
6533
|
+
} catch (err) {
|
|
6534
|
+
stderrLine(`baton: serve() could not record its own answer: ${printable(err)}`);
|
|
6535
|
+
}
|
|
6536
|
+
}
|
|
6537
|
+
/** An error, once per client and call, when the vendor's code inside
|
|
6538
|
+
* `serve()` still calls what `serve()` now does: the old wiring was left in. */
|
|
6539
|
+
#flagDoubleWiring(call) {
|
|
6540
|
+
const mark = inDispatch.getStore();
|
|
6541
|
+
if (!mark?.active || mark.owner !== this || mark.flags !== call || this.#doubleWiringLogged.has(call)) return;
|
|
6542
|
+
this.#doubleWiringLogged.add(call);
|
|
6543
|
+
stderrLine(
|
|
6544
|
+
`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.`
|
|
6545
|
+
);
|
|
6546
|
+
}
|
|
5858
6547
|
/** Wait for events so far to reach the sink, then flush it. Never rejects;
|
|
5859
6548
|
* returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
|
|
5860
6549
|
async flush() {
|
|
@@ -5862,58 +6551,13 @@ var Client = class {
|
|
|
5862
6551
|
}
|
|
5863
6552
|
/** Flush, then close the sink. Later events are dropped. */
|
|
5864
6553
|
aclose() {
|
|
6554
|
+
this.#core.settings?.stop();
|
|
5865
6555
|
this.#closing ??= boundedSinkCall(this.#core.sink, "aclose").then(() => {
|
|
5866
6556
|
this.#core.closed = true;
|
|
5867
6557
|
});
|
|
5868
6558
|
return this.#closing;
|
|
5869
6559
|
}
|
|
5870
6560
|
};
|
|
5871
|
-
|
|
5872
|
-
// src/library/reportTool.ts
|
|
5873
|
-
function inputSchema() {
|
|
5874
|
-
const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
|
|
5875
|
-
delete schema.$schema;
|
|
5876
|
-
return { ...schema, required: [...schema.required, TOOL_NAME_PARAM_NAME] };
|
|
5877
|
-
}
|
|
5878
|
-
var nonEmptyText = (value) => typeof value === "string" && value !== "";
|
|
5879
|
-
var nonEmptyObject = (value) => isRecord(value) && Object.keys(value).length > 0;
|
|
5880
|
-
function annotateArgs(args) {
|
|
5881
|
-
const whatHappened = args.what_happened;
|
|
5882
|
-
if (!isReport(whatHappened)) return null;
|
|
5883
|
-
const options = { whatHappened };
|
|
5884
|
-
const toolName = args[TOOL_NAME_PARAM_NAME];
|
|
5885
|
-
if (typeof toolName === "string") options.toolName = toolName;
|
|
5886
|
-
const intent = args[USER_GOAL_PARAM_NAME];
|
|
5887
|
-
if (nonEmptyText(intent)) options.intent = intent;
|
|
5888
|
-
if (nonEmptyText(args.suggested_improvement)) {
|
|
5889
|
-
options.suggestedImprovement = args.suggested_improvement;
|
|
5890
|
-
}
|
|
5891
|
-
if (nonEmptyObject(args.context)) options.context = args.context;
|
|
5892
|
-
return options;
|
|
5893
|
-
}
|
|
5894
|
-
function reportTool(options) {
|
|
5895
|
-
const { vendorDisplayName } = options;
|
|
5896
|
-
const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);
|
|
5897
|
-
if (derived === void 0) {
|
|
5898
|
-
throw new Error(
|
|
5899
|
-
`vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, or one too long for the instructions. Pass name.`
|
|
5900
|
-
);
|
|
5901
|
-
}
|
|
5902
|
-
const name = validateAnnotationToolName(derived);
|
|
5903
|
-
if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: name })) {
|
|
5904
|
-
throw new Error(
|
|
5905
|
-
`vendorDisplayName and name ${JSON.stringify(name)} are too long together for the instructions. Shorten one of them.`
|
|
5906
|
-
);
|
|
5907
|
-
}
|
|
5908
|
-
return {
|
|
5909
|
-
name,
|
|
5910
|
-
description: buildAnnotationToolDescription({ vendorDisplayName }),
|
|
5911
|
-
inputSchema: inputSchema(),
|
|
5912
|
-
instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),
|
|
5913
|
-
refusal: buildRefusalText({ annotationToolName: name }),
|
|
5914
|
-
annotateArgs
|
|
5915
|
-
};
|
|
5916
|
-
}
|
|
5917
6561
|
export {
|
|
5918
6562
|
BatonHandle,
|
|
5919
6563
|
Client,
|