@goodtiming/baton-sdk 0.5.6 → 0.5.8
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 +31 -2
- package/dist/index.cjs +739 -130
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +168 -19
- package/dist/index.d.ts +168 -19
- package/dist/index.js +735 -130
- 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-0.5.
|
|
2
|
+
var SDK_VERSION = "ts-0.5.8";
|
|
3
3
|
|
|
4
4
|
// src/events.ts
|
|
5
5
|
import { z } from "zod";
|
|
@@ -769,25 +769,22 @@ function principalFor(principal, onUnregisteredForm) {
|
|
|
769
769
|
}
|
|
770
770
|
|
|
771
771
|
// src/integrations/mcp/llmText.ts
|
|
772
|
-
var
|
|
772
|
+
var REPORT_POINTER_TEMPLATE = (vendorDisplayName, annotationToolName) => `Use \`${annotationToolName}\` to report a ${vendorDisplayName} tool call that went wrong, or a request no tool covers; its description says when and how.`;
|
|
773
|
+
var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
|
|
774
|
+
var ANNOTATION_TOOL_DESCRIPTION_TEMPLATE = (vendorDisplayName) => `Report a ${vendorDisplayName} tool call that went wrong, so ${vendorDisplayName} can fix it. Call this right after a call errors, times out, or returns an empty, unhelpful or contradictory result. Also call it once per user request when no tool or field covers what they asked for, or you had to work around one. Do not call it before a tool call or for normal successful work.
|
|
773
775
|
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
IF a ${vendorDisplayName} tool response lacks a structured field for what the user asked about, OR you satisfied the user's intent via a workaround because no tool matched what they asked for, OR the user asked for something this server can't do \u2014 you MUST call \`${annotationToolName}\` once per user request, not per call, with what_happened and tool_name (none if no tool) AND still answer the user with your best inference. Filing the annotation does NOT replace answering.`;
|
|
777
|
-
var ANNOTATION_TOOL_DESCRIPTION_TEMPLATE = (vendorDisplayName) => `Report a ${vendorDisplayName} tool call that went wrong \u2014 call this AFTER a call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. Do NOT call it before a tool call or to narrate normal successful work.
|
|
776
|
+
A report does not replace the work: after it, work out why the call failed, fix the input and try again (do not repeat the same failing call), and still answer the user.
|
|
778
777
|
|
|
779
778
|
Fields:
|
|
780
|
-
- user_goal:
|
|
781
|
-
- what_happened: REQUIRED
|
|
782
|
-
- tool_name: REQUIRED
|
|
783
|
-
-
|
|
784
|
-
- overall_task: short stable label for the broader task this call serves, e.g., 'morning meeting prep', 'pre-outreach research'. REPEAT the exact same string on every call serving the same task; change it only when the user starts a different task.
|
|
785
|
-
- suggested_improvement: A concrete sentence about what product change would have helped.
|
|
779
|
+
- user_goal: the same ${USER_GOAL_FORMAT} as on this server's other tools.
|
|
780
|
+
- what_happened: REQUIRED. 1-2 plain sentences in your own words: what you asked for, what came back, and why it was unusable. Not a category.
|
|
781
|
+
- tool_name: REQUIRED. The ${vendorDisplayName} tool that went wrong, or none if no tool exists for the request.
|
|
782
|
+
- suggested_improvement: one concrete sentence on the product change that would have helped.
|
|
786
783
|
- 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.`;
|
|
787
784
|
var CLAUDE_CODE_TRUNCATION_CAP = 2087;
|
|
788
785
|
var INSTRUCTIONS_LENGTH_CAP = 1500;
|
|
789
786
|
function renderServerInstructions(options) {
|
|
790
|
-
return
|
|
787
|
+
return REPORT_POINTER_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
|
|
791
788
|
}
|
|
792
789
|
function fitsInstructionsCap(options) {
|
|
793
790
|
return renderServerInstructions(options).length <= INSTRUCTIONS_LENGTH_CAP;
|
|
@@ -799,7 +796,7 @@ function buildServerInstructions(options) {
|
|
|
799
796
|
`Rendered server instructions are ${rendered.length} chars, which exceeds the ${INSTRUCTIONS_LENGTH_CAP}-char safety cap (Claude Code truncates at ~${CLAUDE_CODE_TRUNCATION_CAP}). Shorten vendorDisplayName or annotationToolName.`
|
|
800
797
|
);
|
|
801
798
|
}
|
|
802
|
-
return
|
|
799
|
+
return rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
|
|
803
800
|
}
|
|
804
801
|
function buildAnnotationToolDescription(options) {
|
|
805
802
|
return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
|
|
@@ -807,28 +804,67 @@ function buildAnnotationToolDescription(options) {
|
|
|
807
804
|
var USER_GOAL_PARAM_NAME = "user_goal";
|
|
808
805
|
var EXPECTED_RESULT_PARAM_NAME = "expected_result";
|
|
809
806
|
var OVERALL_TASK_PARAM_NAME = "overall_task";
|
|
807
|
+
var RETIRED_PARAM_NAMES = [EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME];
|
|
810
808
|
var INTENT_SOURCE_PARAM = "injected_param";
|
|
811
|
-
var
|
|
809
|
+
var INTENT_SOURCE_LIBRARY = "library_arg";
|
|
810
|
+
var USER_GOAL_PARAM_BODY = `Write it as ${USER_GOAL_FORMAT}. n is the number of the user's current message in this conversation (1 for the first). Use the same number on every call you make for that message, including calls made after reading tool results; it goes up only when the user sends another message.`;
|
|
812
811
|
var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
|
|
813
812
|
var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
|
|
814
|
-
var
|
|
815
|
-
var
|
|
816
|
-
var EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + EXPECTED_RESULT_PARAM_BODY;
|
|
817
|
-
var OVERALL_TASK_PARAM_BODY = "The number of the user's current message in this conversation (1 for the first), a colon, then a short stable label for the broader task this call serves (e.g. '3: prepare campaign approval'). Use the same number on every call you make for that message, including calls made after reading tool results; it goes up only when the user sends another message. REPEAT the exact same label text after the colon on every call serving the same task, across messages; change the label only when the user starts a different task.";
|
|
818
|
-
var OVERALL_TASK_PARAM_DESCRIPTION = "OPTIONAL. " + OVERALL_TASK_PARAM_BODY;
|
|
819
|
-
var OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + OVERALL_TASK_PARAM_BODY;
|
|
820
|
-
var INSTRUCTIONS_SUBAGENT_CLAUSE = "\n\nWhen you hand work to a subagent that may call this server's tools, tell it the number of the user's current message in this conversation, and that it must start overall_task with that number on every call to this server's tools. This applies only to this server's tools.";
|
|
813
|
+
var INSTRUCTIONS_SUBAGENT_CLAUSE = "\n\nWhen you hand work to a subagent that may call this server's tools, tell it the number of the user's current message in this conversation, and that it must start user_goal with that number on every call to this server's tools. This applies only to this server's tools.";
|
|
814
|
+
var INTENT_INSTRUCTIONS = INSTRUCTIONS_SUBAGENT_CLAUSE.trim();
|
|
821
815
|
function buildUserGoalParamDescription(options = {}) {
|
|
822
816
|
return options.intentParamMode === "required" ? USER_GOAL_PARAM_DESCRIPTION_REQUIRED : USER_GOAL_PARAM_DESCRIPTION;
|
|
823
817
|
}
|
|
824
|
-
function
|
|
825
|
-
return
|
|
818
|
+
function requiredParamNames(intentParamMode) {
|
|
819
|
+
return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME] : [];
|
|
820
|
+
}
|
|
821
|
+
function declaresParam(schema, name) {
|
|
822
|
+
const props = schema?.properties;
|
|
823
|
+
return typeof props === "object" && props !== null && name in props;
|
|
826
824
|
}
|
|
827
|
-
function
|
|
828
|
-
|
|
825
|
+
function instructionsSuffixServed(annotationToolName, served) {
|
|
826
|
+
if (annotationToolName) return true;
|
|
827
|
+
return typeof served === "string" && served.includes(INTENT_INSTRUCTIONS);
|
|
829
828
|
}
|
|
830
|
-
|
|
831
|
-
|
|
829
|
+
var INTENT_PARAMS = Object.freeze([
|
|
830
|
+
Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: "intent" })
|
|
831
|
+
]);
|
|
832
|
+
var VENDOR_INSTRUCTIONS = /* @__PURE__ */ Symbol("batonVendorInstructions");
|
|
833
|
+
var escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
834
|
+
var OURS_STARTS = [
|
|
835
|
+
new RegExp(
|
|
836
|
+
"^" + REPORT_POINTER_TEMPLATE("\0", "\0").split("\0").map(escapeRegExp).join(".+?")
|
|
837
|
+
),
|
|
838
|
+
new RegExp("^" + escapeRegExp(INTENT_INSTRUCTIONS))
|
|
839
|
+
];
|
|
840
|
+
function endsInOurs(current2, vendor) {
|
|
841
|
+
if (typeof current2 !== "string") return false;
|
|
842
|
+
const prefix = typeof vendor === "string" && vendor.trim() ? `${vendor}
|
|
843
|
+
|
|
844
|
+
` : "";
|
|
845
|
+
if (!current2.startsWith(prefix)) return false;
|
|
846
|
+
const rest = current2.slice(prefix.length);
|
|
847
|
+
return OURS_STARTS.some((start) => start.test(rest));
|
|
848
|
+
}
|
|
849
|
+
function withVendorInstructions(server, ours, warn4 = (message) => process.stderr.write(message)) {
|
|
850
|
+
const holder = server;
|
|
851
|
+
const current2 = holder._instructions;
|
|
852
|
+
let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
|
|
853
|
+
if (!endsInOurs(current2, vendor)) {
|
|
854
|
+
vendor = current2;
|
|
855
|
+
holder[VENDOR_INSTRUCTIONS] = vendor;
|
|
856
|
+
}
|
|
857
|
+
if (typeof vendor !== "string" || !vendor.trim()) return ours;
|
|
858
|
+
const combined = `${vendor}
|
|
859
|
+
|
|
860
|
+
${ours}`;
|
|
861
|
+
if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
|
|
862
|
+
warn4(
|
|
863
|
+
`baton: the server instructions are ${combined.length} chars (yours ${vendor.length}, Baton's ${ours.length}); Claude Code cuts them at ~${CLAUDE_CODE_TRUNCATION_CAP}, so the end of Baton's text is lost there
|
|
864
|
+
`
|
|
865
|
+
);
|
|
866
|
+
}
|
|
867
|
+
return combined;
|
|
832
868
|
}
|
|
833
869
|
|
|
834
870
|
// src/integrations/mcp/annotationName.ts
|
|
@@ -899,8 +935,8 @@ function annotationToolNameFromServer(serverName, vendorDisplayName) {
|
|
|
899
935
|
}
|
|
900
936
|
return candidate;
|
|
901
937
|
}
|
|
902
|
-
function deriveAnnotationToolName(
|
|
903
|
-
const name = override || `${
|
|
938
|
+
function deriveAnnotationToolName(vendorId2, override) {
|
|
939
|
+
const name = override || `${vendorId2}${SUFFIX}`;
|
|
904
940
|
if (!TOOL_NAME_PATTERN.test(name)) {
|
|
905
941
|
throw new Error(
|
|
906
942
|
`Annotation tool name ${JSON.stringify(name)} violates the cross-runtime pattern ${TOOL_NAME_PATTERN.source} (Claude Desktop and others reject names with dots or other separators).`
|
|
@@ -1080,19 +1116,20 @@ function declaredOnConnection(server) {
|
|
|
1080
1116
|
return declared(holder.getClientVersion());
|
|
1081
1117
|
}
|
|
1082
1118
|
function observedInfo(extra, options) {
|
|
1083
|
-
|
|
1119
|
+
return cleanInfo(declaredOnRequest(extra) ?? declaredOnConnection(options.server), options.scrubber);
|
|
1120
|
+
}
|
|
1121
|
+
function cleanInfo(sent, scrubber) {
|
|
1084
1122
|
const info = {};
|
|
1085
|
-
const name = clean(sent?.name,
|
|
1086
|
-
const version = clean(sent?.version,
|
|
1123
|
+
const name = clean(sent?.name, scrubber, CLIENT_INFO_MAX_LEN);
|
|
1124
|
+
const version = clean(sent?.version, scrubber, CLIENT_INFO_MAX_LEN);
|
|
1087
1125
|
if (name !== void 0) info.name = name;
|
|
1088
1126
|
if (version !== void 0) info.version = version;
|
|
1089
1127
|
return Object.keys(info).length > 0 ? info : void 0;
|
|
1090
1128
|
}
|
|
1091
|
-
function
|
|
1092
|
-
const sent = extraHeaders(extra);
|
|
1129
|
+
function cleanHeaders(sent, scrubber) {
|
|
1093
1130
|
const headers = {};
|
|
1094
1131
|
for (const header of OBSERVED_HEADERS) {
|
|
1095
|
-
const value = clean(sent?.get(header),
|
|
1132
|
+
const value = clean(sent?.get(header), scrubber, HEADER_VALUE_MAX_LEN);
|
|
1096
1133
|
if (value !== void 0) headers[header] = value;
|
|
1097
1134
|
}
|
|
1098
1135
|
return Object.keys(headers).length > 0 ? headers : void 0;
|
|
@@ -1110,12 +1147,46 @@ function orNothing(read) {
|
|
|
1110
1147
|
return void 0;
|
|
1111
1148
|
}
|
|
1112
1149
|
}
|
|
1113
|
-
function
|
|
1114
|
-
const info = orNothing(() => observedInfo(extra, options));
|
|
1115
|
-
const headers = orNothing(() => observedHeaders(extra, options));
|
|
1150
|
+
function assemble(info, headers) {
|
|
1116
1151
|
if (info === void 0 && headers === void 0) return null;
|
|
1117
1152
|
return { ...info && { info }, ...headers && { headers } };
|
|
1118
1153
|
}
|
|
1154
|
+
function observeClient(extra, options) {
|
|
1155
|
+
return assemble(
|
|
1156
|
+
orNothing(() => observedInfo(extra, options)),
|
|
1157
|
+
orNothing(() => cleanHeaders(extraHeaders(extra), options.scrubber))
|
|
1158
|
+
);
|
|
1159
|
+
}
|
|
1160
|
+
function append(headers, name, value) {
|
|
1161
|
+
try {
|
|
1162
|
+
headers.append(name, value);
|
|
1163
|
+
} catch {
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
function registeredHeaders(input) {
|
|
1167
|
+
const out = new Headers();
|
|
1168
|
+
if (typeof input.get === "function") {
|
|
1169
|
+
for (const name of OBSERVED_HEADERS) {
|
|
1170
|
+
const value = input.get(name);
|
|
1171
|
+
if (typeof value === "string") append(out, name, value);
|
|
1172
|
+
}
|
|
1173
|
+
return out;
|
|
1174
|
+
}
|
|
1175
|
+
for (const [key, value] of Object.entries(input)) {
|
|
1176
|
+
const name = key.toLowerCase();
|
|
1177
|
+
if (!OBSERVED_HEADERS.includes(name)) continue;
|
|
1178
|
+
for (const line of typeof value === "string" ? [value] : Array.isArray(value) ? value : []) {
|
|
1179
|
+
if (typeof line === "string") append(out, name, line);
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
return out;
|
|
1183
|
+
}
|
|
1184
|
+
function clientObservedFrom(clientInfo, headers, scrubber) {
|
|
1185
|
+
return assemble(
|
|
1186
|
+
orNothing(() => cleanInfo(declared(clientInfo), scrubber)),
|
|
1187
|
+
orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
|
|
1188
|
+
);
|
|
1189
|
+
}
|
|
1119
1190
|
|
|
1120
1191
|
// src/integrations/mcp/sessionResolution.ts
|
|
1121
1192
|
async function resolveSessionId(fallbackSessionId, extra) {
|
|
@@ -1151,12 +1222,10 @@ function registerAnnotationTool(server, options) {
|
|
|
1151
1222
|
description,
|
|
1152
1223
|
inputSchema: {
|
|
1153
1224
|
user_goal: z2.string(),
|
|
1154
|
-
expected_result: z2.string().optional(),
|
|
1155
1225
|
what_happened: z2.string().optional(),
|
|
1156
1226
|
// Nullable so a report whose agent sends an explicit null is taken,
|
|
1157
1227
|
// not rejected by validation.
|
|
1158
1228
|
tool_name: z2.string().nullable().optional(),
|
|
1159
|
-
overall_task: z2.string().optional(),
|
|
1160
1229
|
suggested_improvement: z2.string().optional(),
|
|
1161
1230
|
context: z2.record(z2.string(), z2.unknown()).optional()
|
|
1162
1231
|
}
|
|
@@ -1203,21 +1272,13 @@ function registerAnnotationTool(server, options) {
|
|
|
1203
1272
|
client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
|
|
1204
1273
|
runtime_meta: scrubbedMeta,
|
|
1205
1274
|
payload: {
|
|
1206
|
-
//
|
|
1207
|
-
// below: `user_goal` is stored as `intent`, `expected_result` as
|
|
1208
|
-
// `expected_outcome`.
|
|
1275
|
+
// The agent-facing `user_goal` is stored as the wire key `intent`.
|
|
1209
1276
|
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
1210
1277
|
intent: options.scrubber(args.user_goal),
|
|
1211
|
-
expected_outcome: args.expected_result ? options.scrubber(args.expected_result) : null,
|
|
1212
1278
|
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
1213
1279
|
what_happened: options.scrubber(whatHappened),
|
|
1214
1280
|
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
1215
1281
|
tool_name: reportedTool ? options.scrubber(reportedTool) : reportedTool,
|
|
1216
|
-
// Agent-facing param `overall_task` -> wire key `workflow`, the same
|
|
1217
|
-
// split the injected params use (`overall_task` -> `call_workflow`):
|
|
1218
|
-
// renaming the param must not move the key the console groups on.
|
|
1219
|
-
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
1220
|
-
workflow: args.overall_task ? options.scrubber(args.overall_task) : null,
|
|
1221
1282
|
suggested_improvement: args.suggested_improvement ? options.scrubber(args.suggested_improvement) : null,
|
|
1222
1283
|
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
1223
1284
|
context: args.context ? options.scrubber(args.context) : null
|
|
@@ -1293,8 +1354,8 @@ function fail(message) {
|
|
|
1293
1354
|
throw new Error(sweep(message));
|
|
1294
1355
|
}
|
|
1295
1356
|
function dsnFromEnvironment() {
|
|
1296
|
-
const
|
|
1297
|
-
return
|
|
1357
|
+
const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
|
|
1358
|
+
return fromEnv2 ? fromEnv2 : void 0;
|
|
1298
1359
|
}
|
|
1299
1360
|
function selectDsn(explicit, supplied, door) {
|
|
1300
1361
|
const conflicts = Object.keys(supplied).filter((name) => supplied[name]).sort();
|
|
@@ -1492,15 +1553,25 @@ function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
|
|
|
1492
1553
|
function requestSideErrorFields(text, errorBody2) {
|
|
1493
1554
|
return { error_body: errorBody2(text), result: null };
|
|
1494
1555
|
}
|
|
1556
|
+
function errorTypeOf(err) {
|
|
1557
|
+
return err instanceof Error ? err.constructor.name : "Error";
|
|
1558
|
+
}
|
|
1559
|
+
function messageOf(err) {
|
|
1560
|
+
return err instanceof Error ? err.message : String(err);
|
|
1561
|
+
}
|
|
1562
|
+
function scrubbedErrorBody(scrubber, text) {
|
|
1563
|
+
return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
|
|
1564
|
+
}
|
|
1495
1565
|
|
|
1496
1566
|
// src/integrations/mcp/config.ts
|
|
1497
|
-
var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"
|
|
1567
|
+
var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
|
|
1568
|
+
var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
|
|
1498
1569
|
var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
|
|
1499
|
-
function resolveTenantId(explicit,
|
|
1570
|
+
function resolveTenantId(explicit, vendorId2) {
|
|
1500
1571
|
if (explicit) return explicit;
|
|
1501
|
-
const
|
|
1502
|
-
if (
|
|
1503
|
-
return
|
|
1572
|
+
const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
|
|
1573
|
+
if (fromEnv2) return fromEnv2;
|
|
1574
|
+
return vendorId2;
|
|
1504
1575
|
}
|
|
1505
1576
|
function resolveBatonConfig(config) {
|
|
1506
1577
|
const dsnString = selectDsn(
|
|
@@ -1579,9 +1650,14 @@ function validateBatonConfig(config) {
|
|
|
1579
1650
|
`vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
|
|
1580
1651
|
);
|
|
1581
1652
|
}
|
|
1582
|
-
if (!config.
|
|
1653
|
+
if (config.reportMode !== void 0 && !REPORT_MODES.has(config.reportMode)) {
|
|
1583
1654
|
throw new Error(
|
|
1584
|
-
|
|
1655
|
+
`BatonConfig.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
|
|
1656
|
+
);
|
|
1657
|
+
}
|
|
1658
|
+
if (!config.vendorDisplayName && config.reportMode === "on") {
|
|
1659
|
+
throw new Error(
|
|
1660
|
+
'BatonConfig needs a vendorDisplayName with reportMode: "on" \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4).'
|
|
1585
1661
|
);
|
|
1586
1662
|
}
|
|
1587
1663
|
if (config.consentToken !== void 0 && !config.consentToken) {
|
|
@@ -1594,6 +1670,11 @@ function validateBatonConfig(config) {
|
|
|
1594
1670
|
"BatonConfig.consentToken is required per SPEC \xA72.3 \u2014 events without a valid consent_token MUST be rejected by the consumer."
|
|
1595
1671
|
);
|
|
1596
1672
|
}
|
|
1673
|
+
if (config.intentParamMode === "off") {
|
|
1674
|
+
throw new Error(
|
|
1675
|
+
'BatonConfig.intentParamMode: "off" would leave nothing capturing what the user is trying to do. Use "required" (the default) or "optional".'
|
|
1676
|
+
);
|
|
1677
|
+
}
|
|
1597
1678
|
if (config.intentParamMode !== void 0 && !INTENT_PARAM_MODES.has(config.intentParamMode)) {
|
|
1598
1679
|
throw new Error(
|
|
1599
1680
|
`BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
|
|
@@ -1676,8 +1757,8 @@ var BatonHandle = class {
|
|
|
1676
1757
|
var SessionCounter = class {
|
|
1677
1758
|
counters = /* @__PURE__ */ new Map();
|
|
1678
1759
|
next(sessionId) {
|
|
1679
|
-
const
|
|
1680
|
-
const next =
|
|
1760
|
+
const current2 = this.counters.get(sessionId) ?? 0;
|
|
1761
|
+
const next = current2 + 1;
|
|
1681
1762
|
this.counters.set(sessionId, next);
|
|
1682
1763
|
return next;
|
|
1683
1764
|
}
|
|
@@ -1779,17 +1860,14 @@ function injectGoalParams(inputSchema, intentParamMode) {
|
|
|
1779
1860
|
function buildIntentFields(existingShape, zodImpl, intentParamMode) {
|
|
1780
1861
|
const dispositions = {};
|
|
1781
1862
|
const toInject = {};
|
|
1782
|
-
for (const
|
|
1783
|
-
[
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
dispositions[name] = "injected";
|
|
1791
|
-
toInject[name] = zodImpl.string().optional().describe(buildDescription({ intentParamMode }));
|
|
1792
|
-
}
|
|
1863
|
+
for (const name of RETIRED_PARAM_NAMES) {
|
|
1864
|
+
if (name in existingShape) dispositions[name] = "native";
|
|
1865
|
+
}
|
|
1866
|
+
if (USER_GOAL_PARAM_NAME in existingShape) {
|
|
1867
|
+
dispositions[USER_GOAL_PARAM_NAME] = "native";
|
|
1868
|
+
} else {
|
|
1869
|
+
dispositions[USER_GOAL_PARAM_NAME] = "injected";
|
|
1870
|
+
toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
|
|
1793
1871
|
}
|
|
1794
1872
|
return { dispositions, toInject };
|
|
1795
1873
|
}
|
|
@@ -1869,12 +1947,12 @@ function assembleSurface(serverMeta, tools) {
|
|
|
1869
1947
|
function buildSeamAugmentations(options) {
|
|
1870
1948
|
return {
|
|
1871
1949
|
injected_tools: [...options.injectedToolNames].sort(),
|
|
1872
|
-
intent_param:
|
|
1950
|
+
intent_param: {
|
|
1873
1951
|
names: [...options.intentParamNames].sort(),
|
|
1874
1952
|
required_names: [...options.requiredParamNames].sort(),
|
|
1875
1953
|
mode: options.intentParamMode
|
|
1876
|
-
}
|
|
1877
|
-
instructions_suffix:
|
|
1954
|
+
},
|
|
1955
|
+
instructions_suffix: options.instructionsSuffix
|
|
1878
1956
|
};
|
|
1879
1957
|
}
|
|
1880
1958
|
|
|
@@ -1936,13 +2014,7 @@ var SurfaceState = class {
|
|
|
1936
2014
|
}
|
|
1937
2015
|
};
|
|
1938
2016
|
function errorBody(ctx, text) {
|
|
1939
|
-
return
|
|
1940
|
-
}
|
|
1941
|
-
function errorTypeOf(err) {
|
|
1942
|
-
return err instanceof Error ? err.constructor.name : "Error";
|
|
1943
|
-
}
|
|
1944
|
-
function messageOf(err) {
|
|
1945
|
-
return err instanceof Error ? err.message : String(err);
|
|
2017
|
+
return scrubbedErrorBody(ctx.scrubber, text);
|
|
1946
2018
|
}
|
|
1947
2019
|
async function resolveEnvelopeParts(ctx, extra) {
|
|
1948
2020
|
const meta = extraMeta(extra);
|
|
@@ -1950,22 +2022,15 @@ async function resolveEnvelopeParts(ctx, extra) {
|
|
|
1950
2022
|
const session = await resolveSessionId(ctx.fallbackSessionId, extra);
|
|
1951
2023
|
return { ...session, scrubbedMeta };
|
|
1952
2024
|
}
|
|
1953
|
-
async function openCall(ctx, toolName, extra, params, registered = true) {
|
|
2025
|
+
async function openCall(ctx, toolName, extra, params, retired, registered = true) {
|
|
1954
2026
|
await maybeEmitSurfaceSnapshot(ctx);
|
|
1955
2027
|
const { sessionId, origin, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
|
|
1956
2028
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
1957
2029
|
const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
|
|
1958
|
-
const rawExpected = extractGoalParam(
|
|
1959
|
-
params,
|
|
1960
|
-
EXPECTED_RESULT_PARAM_NAME,
|
|
1961
|
-
toolName,
|
|
1962
|
-
dispositions,
|
|
1963
|
-
registered
|
|
1964
|
-
);
|
|
1965
|
-
const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions, registered);
|
|
1966
2030
|
const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
|
|
1967
|
-
const scrubbedExpected =
|
|
1968
|
-
|
|
2031
|
+
const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
|
|
2032
|
+
(name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, retired[name] ?? popText(params, name), name)
|
|
2033
|
+
);
|
|
1969
2034
|
const principal = await resolveCallPrincipal(
|
|
1970
2035
|
ctx.resolvePrincipal,
|
|
1971
2036
|
{ extra, toolName, arguments: params }
|
|
@@ -2012,7 +2077,9 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2012
2077
|
if (slot) slot.innerFired = true;
|
|
2013
2078
|
const extra = callArgs[callArgs.length - 1];
|
|
2014
2079
|
const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
|
|
2015
|
-
const
|
|
2080
|
+
const retired = slot?.retired ?? {};
|
|
2081
|
+
if (slot) slot.retired = {};
|
|
2082
|
+
const { common, sessionId } = await openCall(ctx, toolName, extra, params, retired);
|
|
2016
2083
|
const terminate = async (build, replacement) => {
|
|
2017
2084
|
if (!slot) {
|
|
2018
2085
|
await emit(ctx.sink, build);
|
|
@@ -2180,10 +2247,28 @@ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
|
|
|
2180
2247
|
`
|
|
2181
2248
|
);
|
|
2182
2249
|
}
|
|
2250
|
+
return popText(args, paramName);
|
|
2251
|
+
}
|
|
2252
|
+
function popText(args, paramName) {
|
|
2253
|
+
if (!(paramName in args)) return null;
|
|
2183
2254
|
const raw = args[paramName];
|
|
2184
2255
|
delete args[paramName];
|
|
2185
2256
|
return typeof raw === "string" && raw.trim() ? raw : null;
|
|
2186
2257
|
}
|
|
2258
|
+
function stripRetiredParams(params, ctx) {
|
|
2259
|
+
const toolName = params?.name;
|
|
2260
|
+
const args = params?.arguments;
|
|
2261
|
+
if (typeof toolName !== "string") return {};
|
|
2262
|
+
if (toolName === ctx.annotationToolName) return {};
|
|
2263
|
+
if (typeof args !== "object" || args === null || Array.isArray(args)) return {};
|
|
2264
|
+
const dispositions = ctx.paramRegistry.get(toolName);
|
|
2265
|
+
const retired = {};
|
|
2266
|
+
for (const name of RETIRED_PARAM_NAMES) {
|
|
2267
|
+
if (dispositions === void 0 || dispositions[name] === "native" || !(name in args)) continue;
|
|
2268
|
+
retired[name] = popText(args, name);
|
|
2269
|
+
}
|
|
2270
|
+
return retired;
|
|
2271
|
+
}
|
|
2187
2272
|
var MAX_REMEMBERED_SURFACES = 1024;
|
|
2188
2273
|
async function maybeEmitSurfaceSnapshot(ctx) {
|
|
2189
2274
|
if (!ctx.surfaceState.dirty) return;
|
|
@@ -2203,10 +2288,11 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
2203
2288
|
if (emitted.size >= MAX_REMEMBERED_SURFACES) emitted.clear();
|
|
2204
2289
|
emitted.add(digest);
|
|
2205
2290
|
const seam = buildSeamAugmentations({
|
|
2206
|
-
injectedToolNames: [ctx.annotationToolName],
|
|
2207
|
-
intentParamNames: [USER_GOAL_PARAM_NAME
|
|
2291
|
+
injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
|
|
2292
|
+
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
2208
2293
|
intentParamMode: ctx.intentParamMode,
|
|
2209
|
-
requiredParamNames: requiredParamNames(ctx.intentParamMode)
|
|
2294
|
+
requiredParamNames: requiredParamNames(ctx.intentParamMode),
|
|
2295
|
+
instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions())
|
|
2210
2296
|
});
|
|
2211
2297
|
try {
|
|
2212
2298
|
await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
|
|
@@ -2217,11 +2303,19 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
2217
2303
|
ctx.surfaceState.dirty = true;
|
|
2218
2304
|
}
|
|
2219
2305
|
}
|
|
2306
|
+
function declaredIntentParams(vendorSchema) {
|
|
2307
|
+
const declared2 = {};
|
|
2308
|
+
for (const name of [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES]) {
|
|
2309
|
+
if (declaresParam(vendorSchema, name)) declared2[name] = "native";
|
|
2310
|
+
}
|
|
2311
|
+
return declared2;
|
|
2312
|
+
}
|
|
2220
2313
|
function captureAndInject(name, entry, ctx) {
|
|
2221
2314
|
if (!entry || typeof entry !== "object") return;
|
|
2222
2315
|
const mutable = entry;
|
|
2223
|
-
|
|
2224
|
-
|
|
2316
|
+
const vendorSchema = ctx.vendorToolJsonSchema(name, mutable.inputSchema);
|
|
2317
|
+
ctx.surfaceState.noteTool(name, vendorSchema, mutable.description);
|
|
2318
|
+
if (declaresParam(vendorSchema, USER_GOAL_PARAM_NAME)) ctx.dropSubagentClause(name);
|
|
2225
2319
|
const isV2 = typeof mutable.executor === "function";
|
|
2226
2320
|
try {
|
|
2227
2321
|
const { schema, dispositions } = isV2 ? injectGoalParamsV2(mutable.inputSchema, ctx.intentParamMode) : injectGoalParams(mutable.inputSchema, ctx.intentParamMode);
|
|
@@ -2229,9 +2323,10 @@ function captureAndInject(name, entry, ctx) {
|
|
|
2229
2323
|
mutable.inputSchema = schema;
|
|
2230
2324
|
ctx.bustSchemaMemo(name);
|
|
2231
2325
|
ctx.paramRegistry.set(name, dispositions);
|
|
2232
|
-
if (dispositions[OVERALL_TASK_PARAM_NAME] === "native") ctx.dropSubagentClause(name);
|
|
2233
2326
|
} else {
|
|
2234
|
-
|
|
2327
|
+
const declared2 = declaredIntentParams(vendorSchema);
|
|
2328
|
+
if (Object.keys(declared2).length > 0) ctx.paramRegistry.set(name, declared2);
|
|
2329
|
+
else ctx.paramRegistry.delete(name);
|
|
2235
2330
|
}
|
|
2236
2331
|
} catch {
|
|
2237
2332
|
}
|
|
@@ -2473,7 +2568,12 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
2473
2568
|
TOOLS_CALL_METHOD,
|
|
2474
2569
|
TOOLS_CALL_SEAM,
|
|
2475
2570
|
(handler) => async (...args) => {
|
|
2476
|
-
const
|
|
2571
|
+
const request = args[0];
|
|
2572
|
+
const slot = {
|
|
2573
|
+
innerFired: false,
|
|
2574
|
+
flushTerminal: null,
|
|
2575
|
+
retired: stripRetiredParams(request?.params, ctx)
|
|
2576
|
+
};
|
|
2477
2577
|
let outcome = CLEAN_OUTCOME;
|
|
2478
2578
|
try {
|
|
2479
2579
|
const result = await callSlots.run(slot, () => handler(...args));
|
|
@@ -2498,13 +2598,13 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
|
2498
2598
|
}
|
|
2499
2599
|
if (slot.innerFired) return;
|
|
2500
2600
|
if (!outcome.failed) return;
|
|
2501
|
-
await emitRequestSideFailure(outcome, args, toolEntry, ctx);
|
|
2601
|
+
await emitRequestSideFailure(outcome, args, slot.retired, toolEntry, ctx);
|
|
2502
2602
|
} catch (err) {
|
|
2503
2603
|
process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
|
|
2504
2604
|
`);
|
|
2505
2605
|
}
|
|
2506
2606
|
}
|
|
2507
|
-
async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
|
|
2607
|
+
async function emitRequestSideFailure(outcome, args, retired, toolEntry, ctx) {
|
|
2508
2608
|
const request = args[0];
|
|
2509
2609
|
const toolName = request?.params?.name;
|
|
2510
2610
|
if (typeof toolName !== "string") return;
|
|
@@ -2512,13 +2612,7 @@ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
|
|
|
2512
2612
|
const entry = toolEntry(toolName);
|
|
2513
2613
|
if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
|
|
2514
2614
|
const params = { ...request?.params?.arguments ?? {} };
|
|
2515
|
-
const { common, sessionId } = await openCall(
|
|
2516
|
-
ctx,
|
|
2517
|
-
toolName,
|
|
2518
|
-
args[1],
|
|
2519
|
-
params,
|
|
2520
|
-
entry != null
|
|
2521
|
-
);
|
|
2615
|
+
const { common, sessionId } = await openCall(ctx, toolName, args[1], params, retired, entry != null);
|
|
2522
2616
|
const failureKind = requestSideFailureKind(entry);
|
|
2523
2617
|
await emit(
|
|
2524
2618
|
ctx.sink,
|
|
@@ -2636,7 +2730,9 @@ function withBaton(server, supplied = {}) {
|
|
|
2636
2730
|
annotationToolName: ""
|
|
2637
2731
|
});
|
|
2638
2732
|
}
|
|
2639
|
-
|
|
2733
|
+
const resolved = resolveBatonConfig(supplied);
|
|
2734
|
+
warnUnusedReportSettings(resolved);
|
|
2735
|
+
return install(server, supplied, resolved, /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set());
|
|
2640
2736
|
}
|
|
2641
2737
|
function createBaton(supplied = {}) {
|
|
2642
2738
|
const disabledBy = captureDisabled();
|
|
@@ -2647,7 +2743,8 @@ function createBaton(supplied = {}) {
|
|
|
2647
2743
|
}, flush: () => unused.flush(), aclose: () => unused.aclose() };
|
|
2648
2744
|
}
|
|
2649
2745
|
const resolved = resolveBatonConfig(supplied);
|
|
2650
|
-
|
|
2746
|
+
warnUnusedReportSettings(resolved);
|
|
2747
|
+
if (resolved.reportMode === "on") deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
|
|
2651
2748
|
const sink = resolved.sink ?? new StdoutSink();
|
|
2652
2749
|
const config = {
|
|
2653
2750
|
...resolved,
|
|
@@ -2655,23 +2752,25 @@ function createBaton(supplied = {}) {
|
|
|
2655
2752
|
tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
|
|
2656
2753
|
};
|
|
2657
2754
|
const emittedSurfaceHashes = /* @__PURE__ */ new Set();
|
|
2755
|
+
const warned2 = /* @__PURE__ */ new Set();
|
|
2658
2756
|
return {
|
|
2659
2757
|
wrap: (server) => {
|
|
2660
|
-
install(server, supplied, config, emittedSurfaceHashes);
|
|
2758
|
+
install(server, supplied, config, emittedSurfaceHashes, warned2);
|
|
2661
2759
|
},
|
|
2662
2760
|
flush: () => sink.flush(),
|
|
2663
2761
|
aclose: () => sink.aclose()
|
|
2664
2762
|
};
|
|
2665
2763
|
}
|
|
2666
|
-
function install(server, supplied, resolved, emittedSurfaceHashes) {
|
|
2764
|
+
function install(server, supplied, resolved, emittedSurfaceHashes, warned2) {
|
|
2667
2765
|
const internals = server;
|
|
2668
2766
|
const serverName = usableServerName(() => ({
|
|
2669
2767
|
name: internals.server._serverInfo?.name,
|
|
2670
2768
|
className: internals.constructor.name
|
|
2671
2769
|
}));
|
|
2672
|
-
const config = withServerDisplayName(resolved, supplied, serverName);
|
|
2770
|
+
const config = resolved.reportMode === "on" ? withServerDisplayName(resolved, supplied, serverName) : resolved;
|
|
2673
2771
|
const sink = config.sink ?? new StdoutSink();
|
|
2674
|
-
const
|
|
2772
|
+
const reports = reportsFor(config);
|
|
2773
|
+
const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
|
|
2675
2774
|
const intentParamMode = config.intentParamMode ?? "required";
|
|
2676
2775
|
const counter2 = new SessionCounter();
|
|
2677
2776
|
const fallbackSessionId = `sdk-${uuid7()}`;
|
|
@@ -2703,12 +2802,23 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
|
|
|
2703
2802
|
const memo = internals._toolInputSchemaJson;
|
|
2704
2803
|
if (memo && typeof memo === "object") delete memo[name];
|
|
2705
2804
|
};
|
|
2805
|
+
const warnOnce = (key, message) => {
|
|
2806
|
+
if (warned2.has(key)) return;
|
|
2807
|
+
warned2.add(key);
|
|
2808
|
+
process.stderr.write(message);
|
|
2809
|
+
};
|
|
2706
2810
|
const dropSubagentClause = (name) => {
|
|
2707
|
-
const
|
|
2708
|
-
if (
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2811
|
+
const current2 = internals.server._instructions;
|
|
2812
|
+
if (current2 === INTENT_INSTRUCTIONS) {
|
|
2813
|
+
internals.server._instructions = "";
|
|
2814
|
+
} else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
|
|
2815
|
+
internals.server._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
|
|
2816
|
+
} else {
|
|
2817
|
+
return;
|
|
2818
|
+
}
|
|
2819
|
+
warnOnce(
|
|
2820
|
+
"native-user-goal",
|
|
2821
|
+
`baton: tool ${JSON.stringify(name)} declares its own user_goal, so the subagent sentence was removed from the server instructions; a session that already started keeps it
|
|
2712
2822
|
`
|
|
2713
2823
|
);
|
|
2714
2824
|
};
|
|
@@ -2750,15 +2860,16 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
|
|
|
2750
2860
|
vendorToolJsonSchema,
|
|
2751
2861
|
bustSchemaMemo,
|
|
2752
2862
|
dropSubagentClause,
|
|
2863
|
+
servedInstructions: () => internals.server._instructions,
|
|
2753
2864
|
surfaceState,
|
|
2754
2865
|
emitSurface
|
|
2755
2866
|
};
|
|
2756
|
-
const
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2867
|
+
const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
|
|
2868
|
+
internals.server._instructions = withVendorInstructions(
|
|
2869
|
+
internals.server,
|
|
2870
|
+
ours,
|
|
2871
|
+
(message) => warnOnce("instructions-length", message)
|
|
2872
|
+
);
|
|
2762
2873
|
installToolsListSeam(internals.server, ctx);
|
|
2763
2874
|
installToolsCallSeam(
|
|
2764
2875
|
internals.server,
|
|
@@ -2776,12 +2887,12 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
|
|
|
2776
2887
|
ctx
|
|
2777
2888
|
);
|
|
2778
2889
|
installLifecycleSeams(internals.server, ctx);
|
|
2779
|
-
const resolvedAnnotationToolName = registerAnnotationTool(server, {
|
|
2890
|
+
const resolvedAnnotationToolName = !reports ? "" : registerAnnotationTool(server, {
|
|
2780
2891
|
sink,
|
|
2781
2892
|
counter: ctx.counter,
|
|
2782
2893
|
tenantId: ctx.tenantId,
|
|
2783
2894
|
vendorId: ctx.vendorId,
|
|
2784
|
-
vendorDisplayName:
|
|
2895
|
+
vendorDisplayName: reports.vendorDisplayName,
|
|
2785
2896
|
consentToken: ctx.consentToken,
|
|
2786
2897
|
resolvePrincipal: ctx.resolvePrincipal,
|
|
2787
2898
|
fallbackSessionId: ctx.fallbackSessionId,
|
|
@@ -2810,6 +2921,18 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
|
|
|
2810
2921
|
annotationToolName: resolvedAnnotationToolName
|
|
2811
2922
|
});
|
|
2812
2923
|
}
|
|
2924
|
+
function reportsFor(config) {
|
|
2925
|
+
if (config.reportMode !== "on") return void 0;
|
|
2926
|
+
return { vendorDisplayName: config.vendorDisplayName ?? "" };
|
|
2927
|
+
}
|
|
2928
|
+
function warnUnusedReportSettings(config) {
|
|
2929
|
+
if (config.reportMode !== "on" && config.annotationToolName !== void 0) {
|
|
2930
|
+
process.stderr.write(
|
|
2931
|
+
`baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered
|
|
2932
|
+
`
|
|
2933
|
+
);
|
|
2934
|
+
}
|
|
2935
|
+
}
|
|
2813
2936
|
|
|
2814
2937
|
// src/integrations/mcp/oauthHooks.ts
|
|
2815
2938
|
function claimsOf(context) {
|
|
@@ -2841,15 +2964,496 @@ function principalFromOAuthEmail(context) {
|
|
|
2841
2964
|
displayName: at > 0 ? email.slice(0, at) : null
|
|
2842
2965
|
};
|
|
2843
2966
|
}
|
|
2967
|
+
|
|
2968
|
+
// src/library/session.ts
|
|
2969
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
2970
|
+
var TRANSPORT_LIBRARY = "library";
|
|
2971
|
+
var TURN_ID_META_KEY = "baton/turn_id";
|
|
2972
|
+
function sessionEnvelope(session) {
|
|
2973
|
+
return {
|
|
2974
|
+
session_id: session.sessionId,
|
|
2975
|
+
session_id_origin: session.origin,
|
|
2976
|
+
transport_observed: TRANSPORT_LIBRARY,
|
|
2977
|
+
principal: session.principal,
|
|
2978
|
+
client_observed: session.clientObserved,
|
|
2979
|
+
runtime_meta: session.turnId !== null ? { [TURN_ID_META_KEY]: session.turnId } : null
|
|
2980
|
+
};
|
|
2981
|
+
}
|
|
2982
|
+
function warn3(message) {
|
|
2983
|
+
process.stderr.write(`baton: ${message}
|
|
2984
|
+
`);
|
|
2985
|
+
}
|
|
2986
|
+
function vendorId(name, value) {
|
|
2987
|
+
const cleaned = typeof value === "string" ? pythonStrip(value) : "";
|
|
2988
|
+
if (cleaned !== "") return cleaned;
|
|
2989
|
+
if (value !== void 0 && value !== null) {
|
|
2990
|
+
warn3(`${name} is not a non-blank string \u2014 ignoring it.`);
|
|
2991
|
+
}
|
|
2992
|
+
return null;
|
|
2993
|
+
}
|
|
2994
|
+
function minted() {
|
|
2995
|
+
return { sessionId: uuid7(), origin: "minted", principal: null, clientObserved: null, turnId: null };
|
|
2996
|
+
}
|
|
2997
|
+
function wirePrincipal(value) {
|
|
2998
|
+
if (value === void 0 || value === null) return null;
|
|
2999
|
+
const principal = normalizePrincipal(value);
|
|
3000
|
+
if (principal === null) {
|
|
3001
|
+
warn3("principal was given but has no usable principalId \u2014 sending none.");
|
|
3002
|
+
return null;
|
|
3003
|
+
}
|
|
3004
|
+
return principalFor(
|
|
3005
|
+
principal,
|
|
3006
|
+
(form) => warn3(`principal form ${JSON.stringify(form)} is not registered \u2014 sending "raw".`)
|
|
3007
|
+
);
|
|
3008
|
+
}
|
|
3009
|
+
function newSession(values, scrubber, disabled) {
|
|
3010
|
+
const id = vendorId("sessionId", values.sessionId);
|
|
3011
|
+
const base = id !== null ? { sessionId: id, origin: "observed", principal: null, clientObserved: null, turnId: null } : minted();
|
|
3012
|
+
if (disabled) return base;
|
|
3013
|
+
return {
|
|
3014
|
+
...base,
|
|
3015
|
+
principal: wirePrincipal(values.principal),
|
|
3016
|
+
clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber),
|
|
3017
|
+
turnId: vendorId("turnId", values.turnId)
|
|
3018
|
+
};
|
|
3019
|
+
}
|
|
3020
|
+
var current = new AsyncLocalStorage2();
|
|
3021
|
+
function runInSession(owner, session, fn) {
|
|
3022
|
+
return current.run({ owner, session }, fn);
|
|
3023
|
+
}
|
|
3024
|
+
function sessionForCall(owner) {
|
|
3025
|
+
const entry = current.getStore();
|
|
3026
|
+
return entry !== void 0 && entry.owner === owner ? entry.session : minted();
|
|
3027
|
+
}
|
|
3028
|
+
var lastSequence = 0;
|
|
3029
|
+
function nextSequence() {
|
|
3030
|
+
const nowMicros = Math.floor((performance.timeOrigin + performance.now()) * 1e3);
|
|
3031
|
+
lastSequence = Math.max(lastSequence + 1, nowMicros);
|
|
3032
|
+
return lastSequence;
|
|
3033
|
+
}
|
|
3034
|
+
|
|
3035
|
+
// src/library/client.ts
|
|
3036
|
+
function fromEnv(name) {
|
|
3037
|
+
const value = typeof process !== "undefined" ? process.env?.[name] : void 0;
|
|
3038
|
+
return value ? value : void 0;
|
|
3039
|
+
}
|
|
3040
|
+
function resolveConsentToken(explicit) {
|
|
3041
|
+
if (explicit !== void 0 && !explicit) {
|
|
3042
|
+
throw new Error(
|
|
3043
|
+
"Client consentToken was set to an empty string, and events without one MUST be rejected by the consumer per SPEC \xA72.3. Omit it to take the SDK's default."
|
|
3044
|
+
);
|
|
3045
|
+
}
|
|
3046
|
+
return explicit ?? fromEnv("BATON_CONSENT_TOKEN") ?? DEFAULT_CONSENT_TOKEN;
|
|
3047
|
+
}
|
|
3048
|
+
function resolveClientOptions(options) {
|
|
3049
|
+
const resultCaptureMode = options.resultCaptureMode ?? "full";
|
|
3050
|
+
if (!RESULT_CAPTURE_MODES.includes(resultCaptureMode)) {
|
|
3051
|
+
throw new Error(
|
|
3052
|
+
`Client resultCaptureMode ${JSON.stringify(resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
|
|
3053
|
+
);
|
|
3054
|
+
}
|
|
3055
|
+
if (options.scrubber !== void 0 && typeof options.scrubber !== "function") {
|
|
3056
|
+
throw new Error("Client scrubber must be a function.");
|
|
3057
|
+
}
|
|
3058
|
+
const dsnString = selectDsn(
|
|
3059
|
+
options.dsn,
|
|
3060
|
+
{
|
|
3061
|
+
vendorId: Boolean(options.vendorId),
|
|
3062
|
+
tenantId: Boolean(options.tenantId),
|
|
3063
|
+
sink: options.sink !== void 0
|
|
3064
|
+
},
|
|
3065
|
+
"Client"
|
|
3066
|
+
);
|
|
3067
|
+
const consentToken = resolveConsentToken(options.consentToken);
|
|
3068
|
+
if (dsnString !== void 0) {
|
|
3069
|
+
const dsn = parseDsn(dsnString);
|
|
3070
|
+
return {
|
|
3071
|
+
sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
|
|
3072
|
+
vendorId: dsn.vendorId,
|
|
3073
|
+
tenantId: dsn.tenantId,
|
|
3074
|
+
consentToken,
|
|
3075
|
+
resultCaptureMode
|
|
3076
|
+
};
|
|
3077
|
+
}
|
|
3078
|
+
if (options.sink === void 0) {
|
|
3079
|
+
throw new Error(
|
|
3080
|
+
"Client needs somewhere to send events: pass sink (for example new HttpSink(url, { apiKey }) or new StdoutSink()), or dsn \u2014 the packed value from /account, which builds the sink for you."
|
|
3081
|
+
);
|
|
3082
|
+
}
|
|
3083
|
+
const vendorId2 = options.vendorId || fromEnv("BATON_VENDOR_ID");
|
|
3084
|
+
if (!vendorId2) {
|
|
3085
|
+
throw new Error("Client needs a vendorId, or the BATON_VENDOR_ID environment variable.");
|
|
3086
|
+
}
|
|
3087
|
+
return {
|
|
3088
|
+
sink: options.sink,
|
|
3089
|
+
vendorId: vendorId2,
|
|
3090
|
+
tenantId: resolveTenantId(options.tenantId || void 0, vendorId2),
|
|
3091
|
+
consentToken,
|
|
3092
|
+
resultCaptureMode
|
|
3093
|
+
};
|
|
3094
|
+
}
|
|
3095
|
+
var hasText2 = (value) => typeof value === "string" && pythonStrip(value) !== "";
|
|
3096
|
+
function describeError(err) {
|
|
3097
|
+
let type = "Error";
|
|
3098
|
+
let body = "";
|
|
3099
|
+
try {
|
|
3100
|
+
type = errorTypeOf(err);
|
|
3101
|
+
} catch {
|
|
3102
|
+
}
|
|
3103
|
+
try {
|
|
3104
|
+
body = messageOf(err) || (err instanceof Error && typeof err.stack === "string" ? err.stack : "");
|
|
3105
|
+
} catch {
|
|
3106
|
+
}
|
|
3107
|
+
return [type, body];
|
|
3108
|
+
}
|
|
3109
|
+
function isPlainObject3(value) {
|
|
3110
|
+
if (typeof value !== "object" || value === null) return false;
|
|
3111
|
+
const proto = Object.getPrototypeOf(value);
|
|
3112
|
+
return proto === Object.prototype || proto === null;
|
|
3113
|
+
}
|
|
3114
|
+
function paramsOf(args) {
|
|
3115
|
+
if (args.length === 1 && isPlainObject3(args[0])) return args[0];
|
|
3116
|
+
return args.length === 0 ? {} : { args };
|
|
3117
|
+
}
|
|
3118
|
+
var Core = class {
|
|
3119
|
+
closed = false;
|
|
3120
|
+
pending = /* @__PURE__ */ new Set();
|
|
3121
|
+
closedWarned = false;
|
|
3122
|
+
sink;
|
|
3123
|
+
vendorId;
|
|
3124
|
+
tenantId;
|
|
3125
|
+
consentToken;
|
|
3126
|
+
resultCaptureMode;
|
|
3127
|
+
scrubber;
|
|
3128
|
+
disabled;
|
|
3129
|
+
constructor(resolved) {
|
|
3130
|
+
this.sink = resolved.sink;
|
|
3131
|
+
this.vendorId = resolved.vendorId;
|
|
3132
|
+
this.tenantId = resolved.tenantId;
|
|
3133
|
+
this.consentToken = resolved.consentToken;
|
|
3134
|
+
this.resultCaptureMode = resolved.resultCaptureMode;
|
|
3135
|
+
this.scrubber = resolved.scrubber;
|
|
3136
|
+
this.disabled = resolved.disabled;
|
|
3137
|
+
}
|
|
3138
|
+
/** The envelope members every event of `session` shares. Call inside a
|
|
3139
|
+
* build thunk, so `captured_at` is the build time. */
|
|
3140
|
+
envelope(session, consentToken, sequence) {
|
|
3141
|
+
return {
|
|
3142
|
+
tenant_id: this.tenantId,
|
|
3143
|
+
vendor_id: this.vendorId,
|
|
3144
|
+
...sessionEnvelope(session),
|
|
3145
|
+
sequence_number: sequence,
|
|
3146
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3147
|
+
consent_token: consentToken
|
|
3148
|
+
};
|
|
3149
|
+
}
|
|
3150
|
+
/** False when nothing may be emitted: the off switch, or a closed client. */
|
|
3151
|
+
live() {
|
|
3152
|
+
if (this.disabled) return false;
|
|
3153
|
+
if (!this.closed) return true;
|
|
3154
|
+
if (!this.closedWarned) {
|
|
3155
|
+
this.closedWarned = true;
|
|
3156
|
+
process.stderr.write("baton: Client is closed; further events are dropped.\n");
|
|
3157
|
+
}
|
|
3158
|
+
return false;
|
|
3159
|
+
}
|
|
3160
|
+
/** Never rejects. Tracked so `flush()` can wait for it. */
|
|
3161
|
+
emit(build) {
|
|
3162
|
+
const write = emit(this.sink, build).finally(() => this.pending.delete(write));
|
|
3163
|
+
this.pending.add(write);
|
|
3164
|
+
return write;
|
|
3165
|
+
}
|
|
3166
|
+
async settle() {
|
|
3167
|
+
while (this.pending.size > 0) await Promise.all([...this.pending]);
|
|
3168
|
+
}
|
|
3169
|
+
scrub(value, field) {
|
|
3170
|
+
return scrubOrNull(this.scrubber, value, field);
|
|
3171
|
+
}
|
|
3172
|
+
annotate(session, consentToken, options) {
|
|
3173
|
+
if (!this.live()) return Promise.resolve();
|
|
3174
|
+
const sequence = nextSequence();
|
|
3175
|
+
const text = (value) => value === void 0 ? null : this.scrubber(value);
|
|
3176
|
+
return this.emit(
|
|
3177
|
+
() => AnnotationEventSchema.parse({
|
|
3178
|
+
...this.envelope(session, consentToken, sequence),
|
|
3179
|
+
payload: {
|
|
3180
|
+
intent: text(options.intent),
|
|
3181
|
+
expected_outcome: text(options.expectedOutcome),
|
|
3182
|
+
what_happened: hasText2(options.whatHappened) ? text(options.whatHappened) : null,
|
|
3183
|
+
tool_name: options.toolName ? text(options.toolName) : options.toolName ?? null,
|
|
3184
|
+
workflow: text(options.workflow),
|
|
3185
|
+
suggested_improvement: text(options.suggestedImprovement),
|
|
3186
|
+
context: options.context && Object.keys(options.context).length > 0 ? this.scrub(options.context, "context") : null
|
|
3187
|
+
}
|
|
3188
|
+
})
|
|
3189
|
+
);
|
|
3190
|
+
}
|
|
3191
|
+
};
|
|
3192
|
+
var UNSET = /* @__PURE__ */ Symbol("unset");
|
|
3193
|
+
var WITHHELD_RESULT = /* @__PURE__ */ Symbol("withheld");
|
|
3194
|
+
var SCRUB_FAILED = /* @__PURE__ */ Symbol("scrubFailed");
|
|
3195
|
+
var runTrace;
|
|
3196
|
+
var Trace = class _Trace {
|
|
3197
|
+
#core;
|
|
3198
|
+
#session;
|
|
3199
|
+
#options;
|
|
3200
|
+
#consentToken;
|
|
3201
|
+
#callId = uuid7();
|
|
3202
|
+
#startedAt = 0;
|
|
3203
|
+
#result = UNSET;
|
|
3204
|
+
#error = null;
|
|
3205
|
+
#observedWarned = false;
|
|
3206
|
+
constructor(core, session, options) {
|
|
3207
|
+
this.#core = core;
|
|
3208
|
+
this.#session = session;
|
|
3209
|
+
this.#options = options;
|
|
3210
|
+
this.#consentToken = options.consentToken || core.consentToken;
|
|
3211
|
+
}
|
|
3212
|
+
/** The session this call's events carry. */
|
|
3213
|
+
get sessionId() {
|
|
3214
|
+
return this.#session.sessionId;
|
|
3215
|
+
}
|
|
3216
|
+
/** Record the outcome. Without a call, the callback's return value is the
|
|
3217
|
+
* result. `observed(undefined, { error })` records a failure the callback
|
|
3218
|
+
* caught and did not rethrow. The last call wins. */
|
|
3219
|
+
observed(result, failure) {
|
|
3220
|
+
if ((this.#result !== UNSET || this.#error !== null) && !this.#observedWarned) {
|
|
3221
|
+
this.#observedWarned = true;
|
|
3222
|
+
process.stderr.write("baton: Trace.observed() called more than once; the last call wins.\n");
|
|
3223
|
+
}
|
|
3224
|
+
this.#result = UNSET;
|
|
3225
|
+
this.#error = null;
|
|
3226
|
+
if (this.#core.disabled) return this;
|
|
3227
|
+
let errorType = failure?.errorType;
|
|
3228
|
+
let errorBody2 = failure?.errorBody;
|
|
3229
|
+
if (failure?.error !== void 0) {
|
|
3230
|
+
const [derivedType, derivedBody] = describeError(failure.error);
|
|
3231
|
+
errorType ||= derivedType;
|
|
3232
|
+
errorBody2 ||= derivedBody;
|
|
3233
|
+
}
|
|
3234
|
+
if (errorType !== void 0 || errorBody2 !== void 0) {
|
|
3235
|
+
this.#error = { type: errorType || "Error", body: errorBody2 ?? "" };
|
|
3236
|
+
} else if (this.#core.resultCaptureMode === WITHHELD) {
|
|
3237
|
+
this.#result = WITHHELD_RESULT;
|
|
3238
|
+
} else {
|
|
3239
|
+
try {
|
|
3240
|
+
this.#result = this.#core.scrubber(result);
|
|
3241
|
+
} catch (err) {
|
|
3242
|
+
process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${String(err)}
|
|
3243
|
+
`);
|
|
3244
|
+
this.#result = SCRUB_FAILED;
|
|
3245
|
+
}
|
|
3246
|
+
}
|
|
3247
|
+
return this;
|
|
3248
|
+
}
|
|
3249
|
+
/** Report on this call, in its session. */
|
|
3250
|
+
annotate(options) {
|
|
3251
|
+
return this.#core.annotate(this.#session, this.#consentToken, options);
|
|
3252
|
+
}
|
|
3253
|
+
#envelope(sequence) {
|
|
3254
|
+
return { ...this.#core.envelope(this.#session, this.#consentToken, sequence), call_id: this.#callId };
|
|
3255
|
+
}
|
|
3256
|
+
#durationMs() {
|
|
3257
|
+
return Math.trunc(performance.now() - this.#startedAt);
|
|
3258
|
+
}
|
|
3259
|
+
#start() {
|
|
3260
|
+
this.#startedAt = performance.now();
|
|
3261
|
+
if (!this.#core.live()) return;
|
|
3262
|
+
const sequence = nextSequence();
|
|
3263
|
+
const o = this.#options;
|
|
3264
|
+
const params = o.params === void 0 ? {} : this.#core.scrub(o.params, "params") ?? {};
|
|
3265
|
+
const textOf = (value, field) => {
|
|
3266
|
+
const scrubbed = value === void 0 ? null : this.#core.scrub(value, field);
|
|
3267
|
+
return typeof scrubbed === "string" ? scrubbed : null;
|
|
3268
|
+
};
|
|
3269
|
+
const intent = textOf(o.intent, "intent");
|
|
3270
|
+
const expected = textOf(o.expectedOutcome, "expected_outcome");
|
|
3271
|
+
const workflow = textOf(o.workflow, "workflow");
|
|
3272
|
+
const stated = [intent, expected, workflow].some(hasText2);
|
|
3273
|
+
void this.#core.emit(
|
|
3274
|
+
() => ToolCallStartEventSchema.parse({
|
|
3275
|
+
...this.#envelope(sequence),
|
|
3276
|
+
payload: {
|
|
3277
|
+
tool_name: o.toolName,
|
|
3278
|
+
params,
|
|
3279
|
+
call_intent: intent,
|
|
3280
|
+
call_expected: expected,
|
|
3281
|
+
call_workflow: workflow,
|
|
3282
|
+
intent_source: stated ? INTENT_SOURCE_LIBRARY : null
|
|
3283
|
+
}
|
|
3284
|
+
})
|
|
3285
|
+
);
|
|
3286
|
+
}
|
|
3287
|
+
#end(value) {
|
|
3288
|
+
const durationMs = this.#durationMs();
|
|
3289
|
+
if (!this.#core.live()) return;
|
|
3290
|
+
if (this.#result === UNSET && this.#error === null) this.observed(value);
|
|
3291
|
+
const sequence = nextSequence();
|
|
3292
|
+
const error = this.#error;
|
|
3293
|
+
if (error !== null) {
|
|
3294
|
+
this.#emitError(sequence, error.type, error.body, durationMs);
|
|
3295
|
+
return;
|
|
3296
|
+
}
|
|
3297
|
+
const result = this.#result;
|
|
3298
|
+
void this.#core.emit(() => {
|
|
3299
|
+
if (result === SCRUB_FAILED) throw new Error("the scrubber threw on this result");
|
|
3300
|
+
return ToolCallEndEventSchema.parse({
|
|
3301
|
+
...this.#envelope(sequence),
|
|
3302
|
+
payload: {
|
|
3303
|
+
tool_name: this.#options.toolName,
|
|
3304
|
+
duration_ms: durationMs,
|
|
3305
|
+
...result === WITHHELD_RESULT ? { result: null, result_capture: WITHHELD } : { result }
|
|
3306
|
+
}
|
|
3307
|
+
});
|
|
3308
|
+
});
|
|
3309
|
+
}
|
|
3310
|
+
#fail(err) {
|
|
3311
|
+
const durationMs = this.#durationMs();
|
|
3312
|
+
if (!this.#core.live()) return;
|
|
3313
|
+
this.#emitError(nextSequence(), ...describeError(err), durationMs);
|
|
3314
|
+
}
|
|
3315
|
+
#emitError(sequence, type, body, durationMs) {
|
|
3316
|
+
void this.#core.emit(
|
|
3317
|
+
() => ToolCallErrorEventSchema.parse({
|
|
3318
|
+
...this.#envelope(sequence),
|
|
3319
|
+
payload: {
|
|
3320
|
+
tool_name: this.#options.toolName,
|
|
3321
|
+
error_type: type,
|
|
3322
|
+
error_body: scrubbedErrorBody(this.#core.scrubber, body),
|
|
3323
|
+
duration_ms: durationMs,
|
|
3324
|
+
result: null
|
|
3325
|
+
}
|
|
3326
|
+
})
|
|
3327
|
+
);
|
|
3328
|
+
}
|
|
3329
|
+
static {
|
|
3330
|
+
runTrace = (core, session, options, fn) => {
|
|
3331
|
+
const trace = new _Trace(core, session, options);
|
|
3332
|
+
trace.#start();
|
|
3333
|
+
let value;
|
|
3334
|
+
try {
|
|
3335
|
+
value = fn(trace);
|
|
3336
|
+
} catch (err) {
|
|
3337
|
+
trace.#fail(err);
|
|
3338
|
+
throw err;
|
|
3339
|
+
}
|
|
3340
|
+
if (!isThenable(value)) {
|
|
3341
|
+
trace.#end(value);
|
|
3342
|
+
return value;
|
|
3343
|
+
}
|
|
3344
|
+
return Promise.resolve(value).then(
|
|
3345
|
+
(resolved) => {
|
|
3346
|
+
trace.#end(resolved);
|
|
3347
|
+
return resolved;
|
|
3348
|
+
},
|
|
3349
|
+
(err) => {
|
|
3350
|
+
trace.#fail(err);
|
|
3351
|
+
throw err;
|
|
3352
|
+
}
|
|
3353
|
+
);
|
|
3354
|
+
};
|
|
3355
|
+
}
|
|
3356
|
+
};
|
|
3357
|
+
var Client = class {
|
|
3358
|
+
#core;
|
|
3359
|
+
#closing;
|
|
3360
|
+
constructor(options = {}) {
|
|
3361
|
+
const switchName = captureDisabled();
|
|
3362
|
+
let resolved;
|
|
3363
|
+
if (switchName !== null) {
|
|
3364
|
+
logDisabled(switchName, "Client");
|
|
3365
|
+
resolved = {
|
|
3366
|
+
sink: options.sink ?? new DisabledSink(),
|
|
3367
|
+
vendorId: "",
|
|
3368
|
+
tenantId: "",
|
|
3369
|
+
consentToken: DEFAULT_CONSENT_TOKEN,
|
|
3370
|
+
resultCaptureMode: "full"
|
|
3371
|
+
};
|
|
3372
|
+
} else {
|
|
3373
|
+
resolved = resolveClientOptions(options);
|
|
3374
|
+
}
|
|
3375
|
+
this.#core = new Core({
|
|
3376
|
+
...resolved,
|
|
3377
|
+
scrubber: options.scrubber ?? new Scrubber().scrub,
|
|
3378
|
+
disabled: switchName !== null
|
|
3379
|
+
});
|
|
3380
|
+
}
|
|
3381
|
+
/** Run `fn` with one session, principal, client and turn for every
|
|
3382
|
+
* `trace()` and `annotate()` inside it, including after its awaits. Open
|
|
3383
|
+
* one per request or conversation. Returns what `fn` returns. */
|
|
3384
|
+
session(options, fn) {
|
|
3385
|
+
let block;
|
|
3386
|
+
try {
|
|
3387
|
+
block = newSession(options, this.#core.scrubber, this.#core.disabled);
|
|
3388
|
+
} catch (err) {
|
|
3389
|
+
process.stderr.write(`baton: session values could not be read; using a minted session: ${String(err)}
|
|
3390
|
+
`);
|
|
3391
|
+
block = newSession({}, this.#core.scrubber, this.#core.disabled);
|
|
3392
|
+
}
|
|
3393
|
+
return runInSession(this, block, fn);
|
|
3394
|
+
}
|
|
3395
|
+
/** Run `fn` as one traced tool call and return what it returns. When `fn`
|
|
3396
|
+
* returns a promise or other thenable, the call ends when it settles, and
|
|
3397
|
+
* what comes back is a new native Promise of the same value: `then` is
|
|
3398
|
+
* called exactly once, so a lazy query builder is not run twice. A throw or
|
|
3399
|
+
* rejection is recorded and passed on unchanged. */
|
|
3400
|
+
trace(options, fn) {
|
|
3401
|
+
return runTrace(this.#core, sessionForCall(this), options ?? {}, fn);
|
|
3402
|
+
}
|
|
3403
|
+
/** `fn`, traced on every call. A single plain-object argument is sent as
|
|
3404
|
+
* `params`, as an MCP tool's arguments are; other arguments as
|
|
3405
|
+
* `{ args: [...] }`, unless `options.params` is given. */
|
|
3406
|
+
wrap(options, fn) {
|
|
3407
|
+
const base = typeof options === "string" ? { toolName: options } : options ?? {};
|
|
3408
|
+
const client = this;
|
|
3409
|
+
return function(...args) {
|
|
3410
|
+
return client.trace({ ...base, params: base.params ?? paramsOf(args) }, () => fn.apply(this, args));
|
|
3411
|
+
};
|
|
3412
|
+
}
|
|
3413
|
+
/** Emit an annotation in the open `session()` block, or in a session of its
|
|
3414
|
+
* own outside one. To report on a traced call, use `trace.annotate()`. */
|
|
3415
|
+
annotate(options) {
|
|
3416
|
+
const given = options ?? {};
|
|
3417
|
+
return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);
|
|
3418
|
+
}
|
|
3419
|
+
/** Wait until every event so far has reached the sink and the sink has flushed. */
|
|
3420
|
+
async flush() {
|
|
3421
|
+
await this.#core.settle();
|
|
3422
|
+
try {
|
|
3423
|
+
await this.#core.sink.flush();
|
|
3424
|
+
} catch (err) {
|
|
3425
|
+
process.stderr.write(`baton: sink.flush failed: ${String(err)}
|
|
3426
|
+
`);
|
|
3427
|
+
}
|
|
3428
|
+
}
|
|
3429
|
+
/** Flush, then close the sink. Later events are dropped. */
|
|
3430
|
+
aclose() {
|
|
3431
|
+
this.#closing ??= this.#close();
|
|
3432
|
+
return this.#closing;
|
|
3433
|
+
}
|
|
3434
|
+
async #close() {
|
|
3435
|
+
await this.#core.settle();
|
|
3436
|
+
this.#core.closed = true;
|
|
3437
|
+
try {
|
|
3438
|
+
await this.#core.sink.aclose();
|
|
3439
|
+
} catch (err) {
|
|
3440
|
+
process.stderr.write(`baton: sink.aclose failed: ${String(err)}
|
|
3441
|
+
`);
|
|
3442
|
+
}
|
|
3443
|
+
}
|
|
3444
|
+
};
|
|
2844
3445
|
export {
|
|
2845
3446
|
AnnotationEventSchema,
|
|
2846
3447
|
AnnotationPayloadSchema,
|
|
2847
3448
|
BatonHandle,
|
|
3449
|
+
Client,
|
|
2848
3450
|
DEFAULT_CONSENT_TOKEN,
|
|
2849
3451
|
DEPTH_LIMIT,
|
|
2850
3452
|
EventSchema,
|
|
2851
3453
|
EventTypeSchema,
|
|
2852
3454
|
HttpSink,
|
|
3455
|
+
INTENT_INSTRUCTIONS,
|
|
3456
|
+
INTENT_PARAMS,
|
|
2853
3457
|
PRINCIPAL_FORM_HASHED,
|
|
2854
3458
|
PRINCIPAL_FORM_RAW,
|
|
2855
3459
|
PRINCIPAL_SOURCE_ASSERTED,
|
|
@@ -2895,6 +3499,7 @@ export {
|
|
|
2895
3499
|
ToolListErrorPayloadSchema,
|
|
2896
3500
|
ToolListStartEventSchema,
|
|
2897
3501
|
ToolListStartPayloadSchema,
|
|
3502
|
+
Trace,
|
|
2898
3503
|
createBaton,
|
|
2899
3504
|
identityScrub,
|
|
2900
3505
|
principalFromOAuthEmail,
|