@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/dist/index.cjs CHANGED
@@ -33,11 +33,14 @@ __export(index_exports, {
33
33
  AnnotationEventSchema: () => AnnotationEventSchema,
34
34
  AnnotationPayloadSchema: () => AnnotationPayloadSchema,
35
35
  BatonHandle: () => BatonHandle,
36
+ Client: () => Client,
36
37
  DEFAULT_CONSENT_TOKEN: () => DEFAULT_CONSENT_TOKEN,
37
38
  DEPTH_LIMIT: () => DEPTH_LIMIT,
38
39
  EventSchema: () => EventSchema,
39
40
  EventTypeSchema: () => EventTypeSchema,
40
41
  HttpSink: () => HttpSink,
42
+ INTENT_INSTRUCTIONS: () => INTENT_INSTRUCTIONS,
43
+ INTENT_PARAMS: () => INTENT_PARAMS,
41
44
  PRINCIPAL_FORM_HASHED: () => PRINCIPAL_FORM_HASHED,
42
45
  PRINCIPAL_FORM_RAW: () => PRINCIPAL_FORM_RAW,
43
46
  PRINCIPAL_SOURCE_ASSERTED: () => PRINCIPAL_SOURCE_ASSERTED,
@@ -83,6 +86,7 @@ __export(index_exports, {
83
86
  ToolListErrorPayloadSchema: () => ToolListErrorPayloadSchema,
84
87
  ToolListStartEventSchema: () => ToolListStartEventSchema,
85
88
  ToolListStartPayloadSchema: () => ToolListStartPayloadSchema,
89
+ Trace: () => Trace,
86
90
  createBaton: () => createBaton,
87
91
  identityScrub: () => identityScrub,
88
92
  principalFromOAuthEmail: () => principalFromOAuthEmail,
@@ -93,7 +97,7 @@ __export(index_exports, {
93
97
  module.exports = __toCommonJS(index_exports);
94
98
 
95
99
  // src/version.ts
96
- var SDK_VERSION = "ts-0.5.6";
100
+ var SDK_VERSION = "ts-0.5.8";
97
101
 
98
102
  // src/events.ts
99
103
  var import_zod = require("zod");
@@ -863,25 +867,22 @@ function principalFor(principal, onUnregisteredForm) {
863
867
  }
864
868
 
865
869
  // src/integrations/mcp/llmText.ts
866
- var SERVER_INSTRUCTIONS_TEMPLATE = (vendorDisplayName, annotationToolName) => `This server is wrapped in the ${vendorDisplayName} usage and friction SDK. Use \`${annotationToolName}\` to report when a ${vendorDisplayName} tool call goes wrong, or when a tool you needed does not exist, so ${vendorDisplayName} can improve their product. See that tool's description for field-level detail.
870
+ 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.`;
871
+ var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
872
+ 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.
867
873
 
868
- AFTER any ${vendorDisplayName} tool errors, times out, returns an unhelpful or contradictory result, or the user shows signs of giving up, you MUST call \`${annotationToolName}\` with what_happened (REQUIRED, your own words, NOT a category), tool_name (REQUIRED) and suggested_improvement (REQUIRED whenever you can articulate one).
869
-
870
- 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.`;
871
- 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.
874
+ 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.
872
875
 
873
876
  Fields:
874
- - user_goal: one sentence on what the user is trying to accomplish.
875
- - what_happened: REQUIRED on a report. 1-2 plain sentences in YOUR OWN WORDS: what you asked for, what came back, and why it was unusable. Do NOT pick a category or invent a label \u2014 describe it.
876
- - tool_name: REQUIRED on a report. The ${vendorDisplayName} tool that went wrong. Write none if no tool exists for the request.
877
- - expected_result: what a successful result should look like, so a silent/thin failure can be told apart from success.
878
- - 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.
879
- - suggested_improvement: A concrete sentence about what product change would have helped.
877
+ - user_goal: the same ${USER_GOAL_FORMAT} as on this server's other tools.
878
+ - 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.
879
+ - tool_name: REQUIRED. The ${vendorDisplayName} tool that went wrong, or none if no tool exists for the request.
880
+ - suggested_improvement: one concrete sentence on the product change that would have helped.
880
881
  - 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.`;
881
882
  var CLAUDE_CODE_TRUNCATION_CAP = 2087;
882
883
  var INSTRUCTIONS_LENGTH_CAP = 1500;
883
884
  function renderServerInstructions(options) {
884
- return SERVER_INSTRUCTIONS_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
885
+ return REPORT_POINTER_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
885
886
  }
886
887
  function fitsInstructionsCap(options) {
887
888
  return renderServerInstructions(options).length <= INSTRUCTIONS_LENGTH_CAP;
@@ -893,7 +894,7 @@ function buildServerInstructions(options) {
893
894
  `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.`
894
895
  );
895
896
  }
896
- return options.intentParamMode === "off" ? rendered : rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
897
+ return rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
897
898
  }
898
899
  function buildAnnotationToolDescription(options) {
899
900
  return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
@@ -901,28 +902,67 @@ function buildAnnotationToolDescription(options) {
901
902
  var USER_GOAL_PARAM_NAME = "user_goal";
902
903
  var EXPECTED_RESULT_PARAM_NAME = "expected_result";
903
904
  var OVERALL_TASK_PARAM_NAME = "overall_task";
905
+ var RETIRED_PARAM_NAMES = [EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME];
904
906
  var INTENT_SOURCE_PARAM = "injected_param";
905
- var USER_GOAL_PARAM_BODY = "One sentence: what the user is actually trying to accomplish with this call (their goal, not a restatement of the arguments).";
907
+ var INTENT_SOURCE_LIBRARY = "library_arg";
908
+ 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.`;
906
909
  var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
907
910
  var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
908
- var EXPECTED_RESULT_PARAM_BODY = "One sentence: what a successful result should look like, so a silent/thin failure can be told apart from success.";
909
- var EXPECTED_RESULT_PARAM_DESCRIPTION = "OPTIONAL. " + EXPECTED_RESULT_PARAM_BODY;
910
- var EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + EXPECTED_RESULT_PARAM_BODY;
911
- 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.";
912
- var OVERALL_TASK_PARAM_DESCRIPTION = "OPTIONAL. " + OVERALL_TASK_PARAM_BODY;
913
- var OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + OVERALL_TASK_PARAM_BODY;
914
- 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.";
911
+ 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.";
912
+ var INTENT_INSTRUCTIONS = INSTRUCTIONS_SUBAGENT_CLAUSE.trim();
915
913
  function buildUserGoalParamDescription(options = {}) {
916
914
  return options.intentParamMode === "required" ? USER_GOAL_PARAM_DESCRIPTION_REQUIRED : USER_GOAL_PARAM_DESCRIPTION;
917
915
  }
918
- function buildOverallTaskParamDescription(options = {}) {
919
- return options.intentParamMode === "required" ? OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED : OVERALL_TASK_PARAM_DESCRIPTION;
916
+ function requiredParamNames(intentParamMode) {
917
+ return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME] : [];
918
+ }
919
+ function declaresParam(schema, name) {
920
+ const props = schema?.properties;
921
+ return typeof props === "object" && props !== null && name in props;
920
922
  }
921
- function buildExpectedResultParamDescription(options = {}) {
922
- return options.intentParamMode === "required" ? EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED : EXPECTED_RESULT_PARAM_DESCRIPTION;
923
+ function instructionsSuffixServed(annotationToolName, served) {
924
+ if (annotationToolName) return true;
925
+ return typeof served === "string" && served.includes(INTENT_INSTRUCTIONS);
923
926
  }
924
- function requiredParamNames(intentParamMode) {
925
- return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME] : [];
927
+ var INTENT_PARAMS = Object.freeze([
928
+ Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: "intent" })
929
+ ]);
930
+ var VENDOR_INSTRUCTIONS = /* @__PURE__ */ Symbol("batonVendorInstructions");
931
+ var escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
932
+ var OURS_STARTS = [
933
+ new RegExp(
934
+ "^" + REPORT_POINTER_TEMPLATE("\0", "\0").split("\0").map(escapeRegExp).join(".+?")
935
+ ),
936
+ new RegExp("^" + escapeRegExp(INTENT_INSTRUCTIONS))
937
+ ];
938
+ function endsInOurs(current2, vendor) {
939
+ if (typeof current2 !== "string") return false;
940
+ const prefix = typeof vendor === "string" && vendor.trim() ? `${vendor}
941
+
942
+ ` : "";
943
+ if (!current2.startsWith(prefix)) return false;
944
+ const rest = current2.slice(prefix.length);
945
+ return OURS_STARTS.some((start) => start.test(rest));
946
+ }
947
+ function withVendorInstructions(server, ours, warn4 = (message) => process.stderr.write(message)) {
948
+ const holder = server;
949
+ const current2 = holder._instructions;
950
+ let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
951
+ if (!endsInOurs(current2, vendor)) {
952
+ vendor = current2;
953
+ holder[VENDOR_INSTRUCTIONS] = vendor;
954
+ }
955
+ if (typeof vendor !== "string" || !vendor.trim()) return ours;
956
+ const combined = `${vendor}
957
+
958
+ ${ours}`;
959
+ if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
960
+ warn4(
961
+ `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
962
+ `
963
+ );
964
+ }
965
+ return combined;
926
966
  }
927
967
 
928
968
  // src/integrations/mcp/annotationName.ts
@@ -993,8 +1033,8 @@ function annotationToolNameFromServer(serverName, vendorDisplayName) {
993
1033
  }
994
1034
  return candidate;
995
1035
  }
996
- function deriveAnnotationToolName(vendorId, override) {
997
- const name = override || `${vendorId}${SUFFIX}`;
1036
+ function deriveAnnotationToolName(vendorId2, override) {
1037
+ const name = override || `${vendorId2}${SUFFIX}`;
998
1038
  if (!TOOL_NAME_PATTERN.test(name)) {
999
1039
  throw new Error(
1000
1040
  `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).`
@@ -1174,19 +1214,20 @@ function declaredOnConnection(server) {
1174
1214
  return declared(holder.getClientVersion());
1175
1215
  }
1176
1216
  function observedInfo(extra, options) {
1177
- const sent = declaredOnRequest(extra) ?? declaredOnConnection(options.server);
1217
+ return cleanInfo(declaredOnRequest(extra) ?? declaredOnConnection(options.server), options.scrubber);
1218
+ }
1219
+ function cleanInfo(sent, scrubber) {
1178
1220
  const info = {};
1179
- const name = clean(sent?.name, options.scrubber, CLIENT_INFO_MAX_LEN);
1180
- const version = clean(sent?.version, options.scrubber, CLIENT_INFO_MAX_LEN);
1221
+ const name = clean(sent?.name, scrubber, CLIENT_INFO_MAX_LEN);
1222
+ const version = clean(sent?.version, scrubber, CLIENT_INFO_MAX_LEN);
1181
1223
  if (name !== void 0) info.name = name;
1182
1224
  if (version !== void 0) info.version = version;
1183
1225
  return Object.keys(info).length > 0 ? info : void 0;
1184
1226
  }
1185
- function observedHeaders(extra, options) {
1186
- const sent = extraHeaders(extra);
1227
+ function cleanHeaders(sent, scrubber) {
1187
1228
  const headers = {};
1188
1229
  for (const header of OBSERVED_HEADERS) {
1189
- const value = clean(sent?.get(header), options.scrubber, HEADER_VALUE_MAX_LEN);
1230
+ const value = clean(sent?.get(header), scrubber, HEADER_VALUE_MAX_LEN);
1190
1231
  if (value !== void 0) headers[header] = value;
1191
1232
  }
1192
1233
  return Object.keys(headers).length > 0 ? headers : void 0;
@@ -1204,12 +1245,46 @@ function orNothing(read) {
1204
1245
  return void 0;
1205
1246
  }
1206
1247
  }
1207
- function observeClient(extra, options) {
1208
- const info = orNothing(() => observedInfo(extra, options));
1209
- const headers = orNothing(() => observedHeaders(extra, options));
1248
+ function assemble(info, headers) {
1210
1249
  if (info === void 0 && headers === void 0) return null;
1211
1250
  return { ...info && { info }, ...headers && { headers } };
1212
1251
  }
1252
+ function observeClient(extra, options) {
1253
+ return assemble(
1254
+ orNothing(() => observedInfo(extra, options)),
1255
+ orNothing(() => cleanHeaders(extraHeaders(extra), options.scrubber))
1256
+ );
1257
+ }
1258
+ function append(headers, name, value) {
1259
+ try {
1260
+ headers.append(name, value);
1261
+ } catch {
1262
+ }
1263
+ }
1264
+ function registeredHeaders(input) {
1265
+ const out = new Headers();
1266
+ if (typeof input.get === "function") {
1267
+ for (const name of OBSERVED_HEADERS) {
1268
+ const value = input.get(name);
1269
+ if (typeof value === "string") append(out, name, value);
1270
+ }
1271
+ return out;
1272
+ }
1273
+ for (const [key, value] of Object.entries(input)) {
1274
+ const name = key.toLowerCase();
1275
+ if (!OBSERVED_HEADERS.includes(name)) continue;
1276
+ for (const line of typeof value === "string" ? [value] : Array.isArray(value) ? value : []) {
1277
+ if (typeof line === "string") append(out, name, line);
1278
+ }
1279
+ }
1280
+ return out;
1281
+ }
1282
+ function clientObservedFrom(clientInfo, headers, scrubber) {
1283
+ return assemble(
1284
+ orNothing(() => cleanInfo(declared(clientInfo), scrubber)),
1285
+ orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
1286
+ );
1287
+ }
1213
1288
 
1214
1289
  // src/integrations/mcp/sessionResolution.ts
1215
1290
  async function resolveSessionId(fallbackSessionId, extra) {
@@ -1245,12 +1320,10 @@ function registerAnnotationTool(server, options) {
1245
1320
  description,
1246
1321
  inputSchema: {
1247
1322
  user_goal: import_zod2.z.string(),
1248
- expected_result: import_zod2.z.string().optional(),
1249
1323
  what_happened: import_zod2.z.string().optional(),
1250
1324
  // Nullable so a report whose agent sends an explicit null is taken,
1251
1325
  // not rejected by validation.
1252
1326
  tool_name: import_zod2.z.string().nullable().optional(),
1253
- overall_task: import_zod2.z.string().optional(),
1254
1327
  suggested_improvement: import_zod2.z.string().optional(),
1255
1328
  context: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).optional()
1256
1329
  }
@@ -1297,21 +1370,13 @@ function registerAnnotationTool(server, options) {
1297
1370
  client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
1298
1371
  runtime_meta: scrubbedMeta,
1299
1372
  payload: {
1300
- // Agent-facing names -> wire keys, as with `overall_task`
1301
- // below: `user_goal` is stored as `intent`, `expected_result` as
1302
- // `expected_outcome`.
1373
+ // The agent-facing `user_goal` is stored as the wire key `intent`.
1303
1374
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1304
1375
  intent: options.scrubber(args.user_goal),
1305
- expected_outcome: args.expected_result ? options.scrubber(args.expected_result) : null,
1306
1376
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1307
1377
  what_happened: options.scrubber(whatHappened),
1308
1378
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1309
1379
  tool_name: reportedTool ? options.scrubber(reportedTool) : reportedTool,
1310
- // Agent-facing param `overall_task` -> wire key `workflow`, the same
1311
- // split the injected params use (`overall_task` -> `call_workflow`):
1312
- // renaming the param must not move the key the console groups on.
1313
- // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1314
- workflow: args.overall_task ? options.scrubber(args.overall_task) : null,
1315
1380
  suggested_improvement: args.suggested_improvement ? options.scrubber(args.suggested_improvement) : null,
1316
1381
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1317
1382
  context: args.context ? options.scrubber(args.context) : null
@@ -1387,8 +1452,8 @@ function fail(message) {
1387
1452
  throw new Error(sweep(message));
1388
1453
  }
1389
1454
  function dsnFromEnvironment() {
1390
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
1391
- return fromEnv ? fromEnv : void 0;
1455
+ const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
1456
+ return fromEnv2 ? fromEnv2 : void 0;
1392
1457
  }
1393
1458
  function selectDsn(explicit, supplied, door) {
1394
1459
  const conflicts = Object.keys(supplied).filter((name) => supplied[name]).sort();
@@ -1586,15 +1651,25 @@ function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
1586
1651
  function requestSideErrorFields(text, errorBody2) {
1587
1652
  return { error_body: errorBody2(text), result: null };
1588
1653
  }
1654
+ function errorTypeOf(err) {
1655
+ return err instanceof Error ? err.constructor.name : "Error";
1656
+ }
1657
+ function messageOf(err) {
1658
+ return err instanceof Error ? err.message : String(err);
1659
+ }
1660
+ function scrubbedErrorBody(scrubber, text) {
1661
+ return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
1662
+ }
1589
1663
 
1590
1664
  // src/integrations/mcp/config.ts
1591
- var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1665
+ var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
1666
+ var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
1592
1667
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1593
- function resolveTenantId(explicit, vendorId) {
1668
+ function resolveTenantId(explicit, vendorId2) {
1594
1669
  if (explicit) return explicit;
1595
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
1596
- if (fromEnv) return fromEnv;
1597
- return vendorId;
1670
+ const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
1671
+ if (fromEnv2) return fromEnv2;
1672
+ return vendorId2;
1598
1673
  }
1599
1674
  function resolveBatonConfig(config) {
1600
1675
  const dsnString = selectDsn(
@@ -1673,9 +1748,14 @@ function validateBatonConfig(config) {
1673
1748
  `vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
1674
1749
  );
1675
1750
  }
1676
- if (!config.vendorDisplayName) {
1751
+ if (config.reportMode !== void 0 && !REPORT_MODES.has(config.reportMode)) {
1677
1752
  throw new Error(
1678
- "BatonConfig.vendorDisplayName is required \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4)."
1753
+ `BatonConfig.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
1754
+ );
1755
+ }
1756
+ if (!config.vendorDisplayName && config.reportMode === "on") {
1757
+ throw new Error(
1758
+ 'BatonConfig needs a vendorDisplayName with reportMode: "on" \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4).'
1679
1759
  );
1680
1760
  }
1681
1761
  if (config.consentToken !== void 0 && !config.consentToken) {
@@ -1688,6 +1768,11 @@ function validateBatonConfig(config) {
1688
1768
  "BatonConfig.consentToken is required per SPEC \xA72.3 \u2014 events without a valid consent_token MUST be rejected by the consumer."
1689
1769
  );
1690
1770
  }
1771
+ if (config.intentParamMode === "off") {
1772
+ throw new Error(
1773
+ 'BatonConfig.intentParamMode: "off" would leave nothing capturing what the user is trying to do. Use "required" (the default) or "optional".'
1774
+ );
1775
+ }
1691
1776
  if (config.intentParamMode !== void 0 && !INTENT_PARAM_MODES.has(config.intentParamMode)) {
1692
1777
  throw new Error(
1693
1778
  `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
@@ -1770,8 +1855,8 @@ var BatonHandle = class {
1770
1855
  var SessionCounter = class {
1771
1856
  counters = /* @__PURE__ */ new Map();
1772
1857
  next(sessionId) {
1773
- const current = this.counters.get(sessionId) ?? 0;
1774
- const next = current + 1;
1858
+ const current2 = this.counters.get(sessionId) ?? 0;
1859
+ const next = current2 + 1;
1775
1860
  this.counters.set(sessionId, next);
1776
1861
  return next;
1777
1862
  }
@@ -1873,17 +1958,14 @@ function injectGoalParams(inputSchema, intentParamMode) {
1873
1958
  function buildIntentFields(existingShape, zodImpl, intentParamMode) {
1874
1959
  const dispositions = {};
1875
1960
  const toInject = {};
1876
- for (const [name, buildDescription] of [
1877
- [USER_GOAL_PARAM_NAME, buildUserGoalParamDescription],
1878
- [EXPECTED_RESULT_PARAM_NAME, buildExpectedResultParamDescription],
1879
- [OVERALL_TASK_PARAM_NAME, buildOverallTaskParamDescription]
1880
- ]) {
1881
- if (name in existingShape) {
1882
- dispositions[name] = "native";
1883
- } else {
1884
- dispositions[name] = "injected";
1885
- toInject[name] = zodImpl.string().optional().describe(buildDescription({ intentParamMode }));
1886
- }
1961
+ for (const name of RETIRED_PARAM_NAMES) {
1962
+ if (name in existingShape) dispositions[name] = "native";
1963
+ }
1964
+ if (USER_GOAL_PARAM_NAME in existingShape) {
1965
+ dispositions[USER_GOAL_PARAM_NAME] = "native";
1966
+ } else {
1967
+ dispositions[USER_GOAL_PARAM_NAME] = "injected";
1968
+ toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
1887
1969
  }
1888
1970
  return { dispositions, toInject };
1889
1971
  }
@@ -1963,12 +2045,12 @@ function assembleSurface(serverMeta, tools) {
1963
2045
  function buildSeamAugmentations(options) {
1964
2046
  return {
1965
2047
  injected_tools: [...options.injectedToolNames].sort(),
1966
- intent_param: options.intentParamMode !== "off" ? {
2048
+ intent_param: {
1967
2049
  names: [...options.intentParamNames].sort(),
1968
2050
  required_names: [...options.requiredParamNames].sort(),
1969
2051
  mode: options.intentParamMode
1970
- } : null,
1971
- instructions_suffix: true
2052
+ },
2053
+ instructions_suffix: options.instructionsSuffix
1972
2054
  };
1973
2055
  }
1974
2056
 
@@ -2030,13 +2112,7 @@ var SurfaceState = class {
2030
2112
  }
2031
2113
  };
2032
2114
  function errorBody(ctx, text) {
2033
- return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
2034
- }
2035
- function errorTypeOf(err) {
2036
- return err instanceof Error ? err.constructor.name : "Error";
2037
- }
2038
- function messageOf(err) {
2039
- return err instanceof Error ? err.message : String(err);
2115
+ return scrubbedErrorBody(ctx.scrubber, text);
2040
2116
  }
2041
2117
  async function resolveEnvelopeParts(ctx, extra) {
2042
2118
  const meta = extraMeta(extra);
@@ -2044,22 +2120,15 @@ async function resolveEnvelopeParts(ctx, extra) {
2044
2120
  const session = await resolveSessionId(ctx.fallbackSessionId, extra);
2045
2121
  return { ...session, scrubbedMeta };
2046
2122
  }
2047
- async function openCall(ctx, toolName, extra, params, registered = true) {
2123
+ async function openCall(ctx, toolName, extra, params, retired, registered = true) {
2048
2124
  await maybeEmitSurfaceSnapshot(ctx);
2049
2125
  const { sessionId, origin, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
2050
2126
  const dispositions = ctx.paramRegistry.get(toolName);
2051
2127
  const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
2052
- const rawExpected = extractGoalParam(
2053
- params,
2054
- EXPECTED_RESULT_PARAM_NAME,
2055
- toolName,
2056
- dispositions,
2057
- registered
2058
- );
2059
- const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions, registered);
2060
2128
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
2061
- const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);
2062
- const scrubbedWorkflow = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);
2129
+ const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
2130
+ (name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, retired[name] ?? popText(params, name), name)
2131
+ );
2063
2132
  const principal = await resolveCallPrincipal(
2064
2133
  ctx.resolvePrincipal,
2065
2134
  { extra, toolName, arguments: params }
@@ -2106,7 +2175,9 @@ function batonWrap(nameRef, original, ctx) {
2106
2175
  if (slot) slot.innerFired = true;
2107
2176
  const extra = callArgs[callArgs.length - 1];
2108
2177
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
2109
- const { common, sessionId } = await openCall(ctx, toolName, extra, params);
2178
+ const retired = slot?.retired ?? {};
2179
+ if (slot) slot.retired = {};
2180
+ const { common, sessionId } = await openCall(ctx, toolName, extra, params, retired);
2110
2181
  const terminate = async (build, replacement) => {
2111
2182
  if (!slot) {
2112
2183
  await emit(ctx.sink, build);
@@ -2274,10 +2345,28 @@ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
2274
2345
  `
2275
2346
  );
2276
2347
  }
2348
+ return popText(args, paramName);
2349
+ }
2350
+ function popText(args, paramName) {
2351
+ if (!(paramName in args)) return null;
2277
2352
  const raw = args[paramName];
2278
2353
  delete args[paramName];
2279
2354
  return typeof raw === "string" && raw.trim() ? raw : null;
2280
2355
  }
2356
+ function stripRetiredParams(params, ctx) {
2357
+ const toolName = params?.name;
2358
+ const args = params?.arguments;
2359
+ if (typeof toolName !== "string") return {};
2360
+ if (toolName === ctx.annotationToolName) return {};
2361
+ if (typeof args !== "object" || args === null || Array.isArray(args)) return {};
2362
+ const dispositions = ctx.paramRegistry.get(toolName);
2363
+ const retired = {};
2364
+ for (const name of RETIRED_PARAM_NAMES) {
2365
+ if (dispositions === void 0 || dispositions[name] === "native" || !(name in args)) continue;
2366
+ retired[name] = popText(args, name);
2367
+ }
2368
+ return retired;
2369
+ }
2281
2370
  var MAX_REMEMBERED_SURFACES = 1024;
2282
2371
  async function maybeEmitSurfaceSnapshot(ctx) {
2283
2372
  if (!ctx.surfaceState.dirty) return;
@@ -2297,10 +2386,11 @@ async function maybeEmitSurfaceSnapshot(ctx) {
2297
2386
  if (emitted.size >= MAX_REMEMBERED_SURFACES) emitted.clear();
2298
2387
  emitted.add(digest);
2299
2388
  const seam = buildSeamAugmentations({
2300
- injectedToolNames: [ctx.annotationToolName],
2301
- intentParamNames: [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME],
2389
+ injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
2390
+ intentParamNames: [USER_GOAL_PARAM_NAME],
2302
2391
  intentParamMode: ctx.intentParamMode,
2303
- requiredParamNames: requiredParamNames(ctx.intentParamMode)
2392
+ requiredParamNames: requiredParamNames(ctx.intentParamMode),
2393
+ instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions())
2304
2394
  });
2305
2395
  try {
2306
2396
  await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
@@ -2311,11 +2401,19 @@ async function maybeEmitSurfaceSnapshot(ctx) {
2311
2401
  ctx.surfaceState.dirty = true;
2312
2402
  }
2313
2403
  }
2404
+ function declaredIntentParams(vendorSchema) {
2405
+ const declared2 = {};
2406
+ for (const name of [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES]) {
2407
+ if (declaresParam(vendorSchema, name)) declared2[name] = "native";
2408
+ }
2409
+ return declared2;
2410
+ }
2314
2411
  function captureAndInject(name, entry, ctx) {
2315
2412
  if (!entry || typeof entry !== "object") return;
2316
2413
  const mutable = entry;
2317
- ctx.surfaceState.noteTool(name, ctx.vendorToolJsonSchema(name, mutable.inputSchema), mutable.description);
2318
- if (ctx.intentParamMode === "off") return;
2414
+ const vendorSchema = ctx.vendorToolJsonSchema(name, mutable.inputSchema);
2415
+ ctx.surfaceState.noteTool(name, vendorSchema, mutable.description);
2416
+ if (declaresParam(vendorSchema, USER_GOAL_PARAM_NAME)) ctx.dropSubagentClause(name);
2319
2417
  const isV2 = typeof mutable.executor === "function";
2320
2418
  try {
2321
2419
  const { schema, dispositions } = isV2 ? injectGoalParamsV2(mutable.inputSchema, ctx.intentParamMode) : injectGoalParams(mutable.inputSchema, ctx.intentParamMode);
@@ -2323,9 +2421,10 @@ function captureAndInject(name, entry, ctx) {
2323
2421
  mutable.inputSchema = schema;
2324
2422
  ctx.bustSchemaMemo(name);
2325
2423
  ctx.paramRegistry.set(name, dispositions);
2326
- if (dispositions[OVERALL_TASK_PARAM_NAME] === "native") ctx.dropSubagentClause(name);
2327
2424
  } else {
2328
- ctx.paramRegistry.delete(name);
2425
+ const declared2 = declaredIntentParams(vendorSchema);
2426
+ if (Object.keys(declared2).length > 0) ctx.paramRegistry.set(name, declared2);
2427
+ else ctx.paramRegistry.delete(name);
2329
2428
  }
2330
2429
  } catch {
2331
2430
  }
@@ -2567,7 +2666,12 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
2567
2666
  TOOLS_CALL_METHOD,
2568
2667
  TOOLS_CALL_SEAM,
2569
2668
  (handler) => async (...args) => {
2570
- const slot = { innerFired: false, flushTerminal: null };
2669
+ const request = args[0];
2670
+ const slot = {
2671
+ innerFired: false,
2672
+ flushTerminal: null,
2673
+ retired: stripRetiredParams(request?.params, ctx)
2674
+ };
2571
2675
  let outcome = CLEAN_OUTCOME;
2572
2676
  try {
2573
2677
  const result = await callSlots.run(slot, () => handler(...args));
@@ -2592,13 +2696,13 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
2592
2696
  }
2593
2697
  if (slot.innerFired) return;
2594
2698
  if (!outcome.failed) return;
2595
- await emitRequestSideFailure(outcome, args, toolEntry, ctx);
2699
+ await emitRequestSideFailure(outcome, args, slot.retired, toolEntry, ctx);
2596
2700
  } catch (err) {
2597
2701
  process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
2598
2702
  `);
2599
2703
  }
2600
2704
  }
2601
- async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2705
+ async function emitRequestSideFailure(outcome, args, retired, toolEntry, ctx) {
2602
2706
  const request = args[0];
2603
2707
  const toolName = request?.params?.name;
2604
2708
  if (typeof toolName !== "string") return;
@@ -2606,13 +2710,7 @@ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2606
2710
  const entry = toolEntry(toolName);
2607
2711
  if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
2608
2712
  const params = { ...request?.params?.arguments ?? {} };
2609
- const { common, sessionId } = await openCall(
2610
- ctx,
2611
- toolName,
2612
- args[1],
2613
- params,
2614
- entry != null
2615
- );
2713
+ const { common, sessionId } = await openCall(ctx, toolName, args[1], params, retired, entry != null);
2616
2714
  const failureKind = requestSideFailureKind(entry);
2617
2715
  await emit(
2618
2716
  ctx.sink,
@@ -2730,7 +2828,9 @@ function withBaton(server, supplied = {}) {
2730
2828
  annotationToolName: ""
2731
2829
  });
2732
2830
  }
2733
- return install(server, supplied, resolveBatonConfig(supplied), /* @__PURE__ */ new Set());
2831
+ const resolved = resolveBatonConfig(supplied);
2832
+ warnUnusedReportSettings(resolved);
2833
+ return install(server, supplied, resolved, /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set());
2734
2834
  }
2735
2835
  function createBaton(supplied = {}) {
2736
2836
  const disabledBy = captureDisabled();
@@ -2741,7 +2841,8 @@ function createBaton(supplied = {}) {
2741
2841
  }, flush: () => unused.flush(), aclose: () => unused.aclose() };
2742
2842
  }
2743
2843
  const resolved = resolveBatonConfig(supplied);
2744
- deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
2844
+ warnUnusedReportSettings(resolved);
2845
+ if (resolved.reportMode === "on") deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
2745
2846
  const sink = resolved.sink ?? new StdoutSink();
2746
2847
  const config = {
2747
2848
  ...resolved,
@@ -2749,23 +2850,25 @@ function createBaton(supplied = {}) {
2749
2850
  tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
2750
2851
  };
2751
2852
  const emittedSurfaceHashes = /* @__PURE__ */ new Set();
2853
+ const warned2 = /* @__PURE__ */ new Set();
2752
2854
  return {
2753
2855
  wrap: (server) => {
2754
- install(server, supplied, config, emittedSurfaceHashes);
2856
+ install(server, supplied, config, emittedSurfaceHashes, warned2);
2755
2857
  },
2756
2858
  flush: () => sink.flush(),
2757
2859
  aclose: () => sink.aclose()
2758
2860
  };
2759
2861
  }
2760
- function install(server, supplied, resolved, emittedSurfaceHashes) {
2862
+ function install(server, supplied, resolved, emittedSurfaceHashes, warned2) {
2761
2863
  const internals = server;
2762
2864
  const serverName = usableServerName(() => ({
2763
2865
  name: internals.server._serverInfo?.name,
2764
2866
  className: internals.constructor.name
2765
2867
  }));
2766
- const config = withServerDisplayName(resolved, supplied, serverName);
2868
+ const config = resolved.reportMode === "on" ? withServerDisplayName(resolved, supplied, serverName) : resolved;
2767
2869
  const sink = config.sink ?? new StdoutSink();
2768
- const annotationToolName = resolveAnnotationToolName(serverName, config);
2870
+ const reports = reportsFor(config);
2871
+ const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
2769
2872
  const intentParamMode = config.intentParamMode ?? "required";
2770
2873
  const counter2 = new SessionCounter();
2771
2874
  const fallbackSessionId = `sdk-${uuid7()}`;
@@ -2797,12 +2900,23 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2797
2900
  const memo = internals._toolInputSchemaJson;
2798
2901
  if (memo && typeof memo === "object") delete memo[name];
2799
2902
  };
2903
+ const warnOnce = (key, message) => {
2904
+ if (warned2.has(key)) return;
2905
+ warned2.add(key);
2906
+ process.stderr.write(message);
2907
+ };
2800
2908
  const dropSubagentClause = (name) => {
2801
- const current = internals.server._instructions;
2802
- if (typeof current !== "string" || !current.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) return;
2803
- internals.server._instructions = current.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
2804
- process.stderr.write(
2805
- `baton: tool ${JSON.stringify(name)} declares its own overall_task, so the subagent sentence was removed from the server instructions; a session that already started keeps it
2909
+ const current2 = internals.server._instructions;
2910
+ if (current2 === INTENT_INSTRUCTIONS) {
2911
+ internals.server._instructions = "";
2912
+ } else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
2913
+ internals.server._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
2914
+ } else {
2915
+ return;
2916
+ }
2917
+ warnOnce(
2918
+ "native-user-goal",
2919
+ `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
2806
2920
  `
2807
2921
  );
2808
2922
  };
@@ -2844,15 +2958,16 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2844
2958
  vendorToolJsonSchema,
2845
2959
  bustSchemaMemo,
2846
2960
  dropSubagentClause,
2961
+ servedInstructions: () => internals.server._instructions,
2847
2962
  surfaceState,
2848
2963
  emitSurface
2849
2964
  };
2850
- const instructions = buildServerInstructions({
2851
- vendorDisplayName: config.vendorDisplayName,
2852
- annotationToolName,
2853
- intentParamMode
2854
- });
2855
- internals.server._instructions = instructions;
2965
+ const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
2966
+ internals.server._instructions = withVendorInstructions(
2967
+ internals.server,
2968
+ ours,
2969
+ (message) => warnOnce("instructions-length", message)
2970
+ );
2856
2971
  installToolsListSeam(internals.server, ctx);
2857
2972
  installToolsCallSeam(
2858
2973
  internals.server,
@@ -2870,12 +2985,12 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2870
2985
  ctx
2871
2986
  );
2872
2987
  installLifecycleSeams(internals.server, ctx);
2873
- const resolvedAnnotationToolName = registerAnnotationTool(server, {
2988
+ const resolvedAnnotationToolName = !reports ? "" : registerAnnotationTool(server, {
2874
2989
  sink,
2875
2990
  counter: ctx.counter,
2876
2991
  tenantId: ctx.tenantId,
2877
2992
  vendorId: ctx.vendorId,
2878
- vendorDisplayName: config.vendorDisplayName,
2993
+ vendorDisplayName: reports.vendorDisplayName,
2879
2994
  consentToken: ctx.consentToken,
2880
2995
  resolvePrincipal: ctx.resolvePrincipal,
2881
2996
  fallbackSessionId: ctx.fallbackSessionId,
@@ -2904,6 +3019,18 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2904
3019
  annotationToolName: resolvedAnnotationToolName
2905
3020
  });
2906
3021
  }
3022
+ function reportsFor(config) {
3023
+ if (config.reportMode !== "on") return void 0;
3024
+ return { vendorDisplayName: config.vendorDisplayName ?? "" };
3025
+ }
3026
+ function warnUnusedReportSettings(config) {
3027
+ if (config.reportMode !== "on" && config.annotationToolName !== void 0) {
3028
+ process.stderr.write(
3029
+ `baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered
3030
+ `
3031
+ );
3032
+ }
3033
+ }
2907
3034
 
2908
3035
  // src/integrations/mcp/oauthHooks.ts
2909
3036
  function claimsOf(context) {
@@ -2935,16 +3062,497 @@ function principalFromOAuthEmail(context) {
2935
3062
  displayName: at > 0 ? email.slice(0, at) : null
2936
3063
  };
2937
3064
  }
3065
+
3066
+ // src/library/session.ts
3067
+ var import_node_async_hooks2 = require("async_hooks");
3068
+ var TRANSPORT_LIBRARY = "library";
3069
+ var TURN_ID_META_KEY = "baton/turn_id";
3070
+ function sessionEnvelope(session) {
3071
+ return {
3072
+ session_id: session.sessionId,
3073
+ session_id_origin: session.origin,
3074
+ transport_observed: TRANSPORT_LIBRARY,
3075
+ principal: session.principal,
3076
+ client_observed: session.clientObserved,
3077
+ runtime_meta: session.turnId !== null ? { [TURN_ID_META_KEY]: session.turnId } : null
3078
+ };
3079
+ }
3080
+ function warn3(message) {
3081
+ process.stderr.write(`baton: ${message}
3082
+ `);
3083
+ }
3084
+ function vendorId(name, value) {
3085
+ const cleaned = typeof value === "string" ? pythonStrip(value) : "";
3086
+ if (cleaned !== "") return cleaned;
3087
+ if (value !== void 0 && value !== null) {
3088
+ warn3(`${name} is not a non-blank string \u2014 ignoring it.`);
3089
+ }
3090
+ return null;
3091
+ }
3092
+ function minted() {
3093
+ return { sessionId: uuid7(), origin: "minted", principal: null, clientObserved: null, turnId: null };
3094
+ }
3095
+ function wirePrincipal(value) {
3096
+ if (value === void 0 || value === null) return null;
3097
+ const principal = normalizePrincipal(value);
3098
+ if (principal === null) {
3099
+ warn3("principal was given but has no usable principalId \u2014 sending none.");
3100
+ return null;
3101
+ }
3102
+ return principalFor(
3103
+ principal,
3104
+ (form) => warn3(`principal form ${JSON.stringify(form)} is not registered \u2014 sending "raw".`)
3105
+ );
3106
+ }
3107
+ function newSession(values, scrubber, disabled) {
3108
+ const id = vendorId("sessionId", values.sessionId);
3109
+ const base = id !== null ? { sessionId: id, origin: "observed", principal: null, clientObserved: null, turnId: null } : minted();
3110
+ if (disabled) return base;
3111
+ return {
3112
+ ...base,
3113
+ principal: wirePrincipal(values.principal),
3114
+ clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber),
3115
+ turnId: vendorId("turnId", values.turnId)
3116
+ };
3117
+ }
3118
+ var current = new import_node_async_hooks2.AsyncLocalStorage();
3119
+ function runInSession(owner, session, fn) {
3120
+ return current.run({ owner, session }, fn);
3121
+ }
3122
+ function sessionForCall(owner) {
3123
+ const entry = current.getStore();
3124
+ return entry !== void 0 && entry.owner === owner ? entry.session : minted();
3125
+ }
3126
+ var lastSequence = 0;
3127
+ function nextSequence() {
3128
+ const nowMicros = Math.floor((performance.timeOrigin + performance.now()) * 1e3);
3129
+ lastSequence = Math.max(lastSequence + 1, nowMicros);
3130
+ return lastSequence;
3131
+ }
3132
+
3133
+ // src/library/client.ts
3134
+ function fromEnv(name) {
3135
+ const value = typeof process !== "undefined" ? process.env?.[name] : void 0;
3136
+ return value ? value : void 0;
3137
+ }
3138
+ function resolveConsentToken(explicit) {
3139
+ if (explicit !== void 0 && !explicit) {
3140
+ throw new Error(
3141
+ "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."
3142
+ );
3143
+ }
3144
+ return explicit ?? fromEnv("BATON_CONSENT_TOKEN") ?? DEFAULT_CONSENT_TOKEN;
3145
+ }
3146
+ function resolveClientOptions(options) {
3147
+ const resultCaptureMode = options.resultCaptureMode ?? "full";
3148
+ if (!RESULT_CAPTURE_MODES.includes(resultCaptureMode)) {
3149
+ throw new Error(
3150
+ `Client resultCaptureMode ${JSON.stringify(resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
3151
+ );
3152
+ }
3153
+ if (options.scrubber !== void 0 && typeof options.scrubber !== "function") {
3154
+ throw new Error("Client scrubber must be a function.");
3155
+ }
3156
+ const dsnString = selectDsn(
3157
+ options.dsn,
3158
+ {
3159
+ vendorId: Boolean(options.vendorId),
3160
+ tenantId: Boolean(options.tenantId),
3161
+ sink: options.sink !== void 0
3162
+ },
3163
+ "Client"
3164
+ );
3165
+ const consentToken = resolveConsentToken(options.consentToken);
3166
+ if (dsnString !== void 0) {
3167
+ const dsn = parseDsn(dsnString);
3168
+ return {
3169
+ sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
3170
+ vendorId: dsn.vendorId,
3171
+ tenantId: dsn.tenantId,
3172
+ consentToken,
3173
+ resultCaptureMode
3174
+ };
3175
+ }
3176
+ if (options.sink === void 0) {
3177
+ throw new Error(
3178
+ "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."
3179
+ );
3180
+ }
3181
+ const vendorId2 = options.vendorId || fromEnv("BATON_VENDOR_ID");
3182
+ if (!vendorId2) {
3183
+ throw new Error("Client needs a vendorId, or the BATON_VENDOR_ID environment variable.");
3184
+ }
3185
+ return {
3186
+ sink: options.sink,
3187
+ vendorId: vendorId2,
3188
+ tenantId: resolveTenantId(options.tenantId || void 0, vendorId2),
3189
+ consentToken,
3190
+ resultCaptureMode
3191
+ };
3192
+ }
3193
+ var hasText2 = (value) => typeof value === "string" && pythonStrip(value) !== "";
3194
+ function describeError(err) {
3195
+ let type = "Error";
3196
+ let body = "";
3197
+ try {
3198
+ type = errorTypeOf(err);
3199
+ } catch {
3200
+ }
3201
+ try {
3202
+ body = messageOf(err) || (err instanceof Error && typeof err.stack === "string" ? err.stack : "");
3203
+ } catch {
3204
+ }
3205
+ return [type, body];
3206
+ }
3207
+ function isPlainObject3(value) {
3208
+ if (typeof value !== "object" || value === null) return false;
3209
+ const proto = Object.getPrototypeOf(value);
3210
+ return proto === Object.prototype || proto === null;
3211
+ }
3212
+ function paramsOf(args) {
3213
+ if (args.length === 1 && isPlainObject3(args[0])) return args[0];
3214
+ return args.length === 0 ? {} : { args };
3215
+ }
3216
+ var Core = class {
3217
+ closed = false;
3218
+ pending = /* @__PURE__ */ new Set();
3219
+ closedWarned = false;
3220
+ sink;
3221
+ vendorId;
3222
+ tenantId;
3223
+ consentToken;
3224
+ resultCaptureMode;
3225
+ scrubber;
3226
+ disabled;
3227
+ constructor(resolved) {
3228
+ this.sink = resolved.sink;
3229
+ this.vendorId = resolved.vendorId;
3230
+ this.tenantId = resolved.tenantId;
3231
+ this.consentToken = resolved.consentToken;
3232
+ this.resultCaptureMode = resolved.resultCaptureMode;
3233
+ this.scrubber = resolved.scrubber;
3234
+ this.disabled = resolved.disabled;
3235
+ }
3236
+ /** The envelope members every event of `session` shares. Call inside a
3237
+ * build thunk, so `captured_at` is the build time. */
3238
+ envelope(session, consentToken, sequence) {
3239
+ return {
3240
+ tenant_id: this.tenantId,
3241
+ vendor_id: this.vendorId,
3242
+ ...sessionEnvelope(session),
3243
+ sequence_number: sequence,
3244
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
3245
+ consent_token: consentToken
3246
+ };
3247
+ }
3248
+ /** False when nothing may be emitted: the off switch, or a closed client. */
3249
+ live() {
3250
+ if (this.disabled) return false;
3251
+ if (!this.closed) return true;
3252
+ if (!this.closedWarned) {
3253
+ this.closedWarned = true;
3254
+ process.stderr.write("baton: Client is closed; further events are dropped.\n");
3255
+ }
3256
+ return false;
3257
+ }
3258
+ /** Never rejects. Tracked so `flush()` can wait for it. */
3259
+ emit(build) {
3260
+ const write = emit(this.sink, build).finally(() => this.pending.delete(write));
3261
+ this.pending.add(write);
3262
+ return write;
3263
+ }
3264
+ async settle() {
3265
+ while (this.pending.size > 0) await Promise.all([...this.pending]);
3266
+ }
3267
+ scrub(value, field) {
3268
+ return scrubOrNull(this.scrubber, value, field);
3269
+ }
3270
+ annotate(session, consentToken, options) {
3271
+ if (!this.live()) return Promise.resolve();
3272
+ const sequence = nextSequence();
3273
+ const text = (value) => value === void 0 ? null : this.scrubber(value);
3274
+ return this.emit(
3275
+ () => AnnotationEventSchema.parse({
3276
+ ...this.envelope(session, consentToken, sequence),
3277
+ payload: {
3278
+ intent: text(options.intent),
3279
+ expected_outcome: text(options.expectedOutcome),
3280
+ what_happened: hasText2(options.whatHappened) ? text(options.whatHappened) : null,
3281
+ tool_name: options.toolName ? text(options.toolName) : options.toolName ?? null,
3282
+ workflow: text(options.workflow),
3283
+ suggested_improvement: text(options.suggestedImprovement),
3284
+ context: options.context && Object.keys(options.context).length > 0 ? this.scrub(options.context, "context") : null
3285
+ }
3286
+ })
3287
+ );
3288
+ }
3289
+ };
3290
+ var UNSET = /* @__PURE__ */ Symbol("unset");
3291
+ var WITHHELD_RESULT = /* @__PURE__ */ Symbol("withheld");
3292
+ var SCRUB_FAILED = /* @__PURE__ */ Symbol("scrubFailed");
3293
+ var runTrace;
3294
+ var Trace = class _Trace {
3295
+ #core;
3296
+ #session;
3297
+ #options;
3298
+ #consentToken;
3299
+ #callId = uuid7();
3300
+ #startedAt = 0;
3301
+ #result = UNSET;
3302
+ #error = null;
3303
+ #observedWarned = false;
3304
+ constructor(core, session, options) {
3305
+ this.#core = core;
3306
+ this.#session = session;
3307
+ this.#options = options;
3308
+ this.#consentToken = options.consentToken || core.consentToken;
3309
+ }
3310
+ /** The session this call's events carry. */
3311
+ get sessionId() {
3312
+ return this.#session.sessionId;
3313
+ }
3314
+ /** Record the outcome. Without a call, the callback's return value is the
3315
+ * result. `observed(undefined, { error })` records a failure the callback
3316
+ * caught and did not rethrow. The last call wins. */
3317
+ observed(result, failure) {
3318
+ if ((this.#result !== UNSET || this.#error !== null) && !this.#observedWarned) {
3319
+ this.#observedWarned = true;
3320
+ process.stderr.write("baton: Trace.observed() called more than once; the last call wins.\n");
3321
+ }
3322
+ this.#result = UNSET;
3323
+ this.#error = null;
3324
+ if (this.#core.disabled) return this;
3325
+ let errorType = failure?.errorType;
3326
+ let errorBody2 = failure?.errorBody;
3327
+ if (failure?.error !== void 0) {
3328
+ const [derivedType, derivedBody] = describeError(failure.error);
3329
+ errorType ||= derivedType;
3330
+ errorBody2 ||= derivedBody;
3331
+ }
3332
+ if (errorType !== void 0 || errorBody2 !== void 0) {
3333
+ this.#error = { type: errorType || "Error", body: errorBody2 ?? "" };
3334
+ } else if (this.#core.resultCaptureMode === WITHHELD) {
3335
+ this.#result = WITHHELD_RESULT;
3336
+ } else {
3337
+ try {
3338
+ this.#result = this.#core.scrubber(result);
3339
+ } catch (err) {
3340
+ process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${String(err)}
3341
+ `);
3342
+ this.#result = SCRUB_FAILED;
3343
+ }
3344
+ }
3345
+ return this;
3346
+ }
3347
+ /** Report on this call, in its session. */
3348
+ annotate(options) {
3349
+ return this.#core.annotate(this.#session, this.#consentToken, options);
3350
+ }
3351
+ #envelope(sequence) {
3352
+ return { ...this.#core.envelope(this.#session, this.#consentToken, sequence), call_id: this.#callId };
3353
+ }
3354
+ #durationMs() {
3355
+ return Math.trunc(performance.now() - this.#startedAt);
3356
+ }
3357
+ #start() {
3358
+ this.#startedAt = performance.now();
3359
+ if (!this.#core.live()) return;
3360
+ const sequence = nextSequence();
3361
+ const o = this.#options;
3362
+ const params = o.params === void 0 ? {} : this.#core.scrub(o.params, "params") ?? {};
3363
+ const textOf = (value, field) => {
3364
+ const scrubbed = value === void 0 ? null : this.#core.scrub(value, field);
3365
+ return typeof scrubbed === "string" ? scrubbed : null;
3366
+ };
3367
+ const intent = textOf(o.intent, "intent");
3368
+ const expected = textOf(o.expectedOutcome, "expected_outcome");
3369
+ const workflow = textOf(o.workflow, "workflow");
3370
+ const stated = [intent, expected, workflow].some(hasText2);
3371
+ void this.#core.emit(
3372
+ () => ToolCallStartEventSchema.parse({
3373
+ ...this.#envelope(sequence),
3374
+ payload: {
3375
+ tool_name: o.toolName,
3376
+ params,
3377
+ call_intent: intent,
3378
+ call_expected: expected,
3379
+ call_workflow: workflow,
3380
+ intent_source: stated ? INTENT_SOURCE_LIBRARY : null
3381
+ }
3382
+ })
3383
+ );
3384
+ }
3385
+ #end(value) {
3386
+ const durationMs = this.#durationMs();
3387
+ if (!this.#core.live()) return;
3388
+ if (this.#result === UNSET && this.#error === null) this.observed(value);
3389
+ const sequence = nextSequence();
3390
+ const error = this.#error;
3391
+ if (error !== null) {
3392
+ this.#emitError(sequence, error.type, error.body, durationMs);
3393
+ return;
3394
+ }
3395
+ const result = this.#result;
3396
+ void this.#core.emit(() => {
3397
+ if (result === SCRUB_FAILED) throw new Error("the scrubber threw on this result");
3398
+ return ToolCallEndEventSchema.parse({
3399
+ ...this.#envelope(sequence),
3400
+ payload: {
3401
+ tool_name: this.#options.toolName,
3402
+ duration_ms: durationMs,
3403
+ ...result === WITHHELD_RESULT ? { result: null, result_capture: WITHHELD } : { result }
3404
+ }
3405
+ });
3406
+ });
3407
+ }
3408
+ #fail(err) {
3409
+ const durationMs = this.#durationMs();
3410
+ if (!this.#core.live()) return;
3411
+ this.#emitError(nextSequence(), ...describeError(err), durationMs);
3412
+ }
3413
+ #emitError(sequence, type, body, durationMs) {
3414
+ void this.#core.emit(
3415
+ () => ToolCallErrorEventSchema.parse({
3416
+ ...this.#envelope(sequence),
3417
+ payload: {
3418
+ tool_name: this.#options.toolName,
3419
+ error_type: type,
3420
+ error_body: scrubbedErrorBody(this.#core.scrubber, body),
3421
+ duration_ms: durationMs,
3422
+ result: null
3423
+ }
3424
+ })
3425
+ );
3426
+ }
3427
+ static {
3428
+ runTrace = (core, session, options, fn) => {
3429
+ const trace = new _Trace(core, session, options);
3430
+ trace.#start();
3431
+ let value;
3432
+ try {
3433
+ value = fn(trace);
3434
+ } catch (err) {
3435
+ trace.#fail(err);
3436
+ throw err;
3437
+ }
3438
+ if (!isThenable(value)) {
3439
+ trace.#end(value);
3440
+ return value;
3441
+ }
3442
+ return Promise.resolve(value).then(
3443
+ (resolved) => {
3444
+ trace.#end(resolved);
3445
+ return resolved;
3446
+ },
3447
+ (err) => {
3448
+ trace.#fail(err);
3449
+ throw err;
3450
+ }
3451
+ );
3452
+ };
3453
+ }
3454
+ };
3455
+ var Client = class {
3456
+ #core;
3457
+ #closing;
3458
+ constructor(options = {}) {
3459
+ const switchName = captureDisabled();
3460
+ let resolved;
3461
+ if (switchName !== null) {
3462
+ logDisabled(switchName, "Client");
3463
+ resolved = {
3464
+ sink: options.sink ?? new DisabledSink(),
3465
+ vendorId: "",
3466
+ tenantId: "",
3467
+ consentToken: DEFAULT_CONSENT_TOKEN,
3468
+ resultCaptureMode: "full"
3469
+ };
3470
+ } else {
3471
+ resolved = resolveClientOptions(options);
3472
+ }
3473
+ this.#core = new Core({
3474
+ ...resolved,
3475
+ scrubber: options.scrubber ?? new Scrubber().scrub,
3476
+ disabled: switchName !== null
3477
+ });
3478
+ }
3479
+ /** Run `fn` with one session, principal, client and turn for every
3480
+ * `trace()` and `annotate()` inside it, including after its awaits. Open
3481
+ * one per request or conversation. Returns what `fn` returns. */
3482
+ session(options, fn) {
3483
+ let block;
3484
+ try {
3485
+ block = newSession(options, this.#core.scrubber, this.#core.disabled);
3486
+ } catch (err) {
3487
+ process.stderr.write(`baton: session values could not be read; using a minted session: ${String(err)}
3488
+ `);
3489
+ block = newSession({}, this.#core.scrubber, this.#core.disabled);
3490
+ }
3491
+ return runInSession(this, block, fn);
3492
+ }
3493
+ /** Run `fn` as one traced tool call and return what it returns. When `fn`
3494
+ * returns a promise or other thenable, the call ends when it settles, and
3495
+ * what comes back is a new native Promise of the same value: `then` is
3496
+ * called exactly once, so a lazy query builder is not run twice. A throw or
3497
+ * rejection is recorded and passed on unchanged. */
3498
+ trace(options, fn) {
3499
+ return runTrace(this.#core, sessionForCall(this), options ?? {}, fn);
3500
+ }
3501
+ /** `fn`, traced on every call. A single plain-object argument is sent as
3502
+ * `params`, as an MCP tool's arguments are; other arguments as
3503
+ * `{ args: [...] }`, unless `options.params` is given. */
3504
+ wrap(options, fn) {
3505
+ const base = typeof options === "string" ? { toolName: options } : options ?? {};
3506
+ const client = this;
3507
+ return function(...args) {
3508
+ return client.trace({ ...base, params: base.params ?? paramsOf(args) }, () => fn.apply(this, args));
3509
+ };
3510
+ }
3511
+ /** Emit an annotation in the open `session()` block, or in a session of its
3512
+ * own outside one. To report on a traced call, use `trace.annotate()`. */
3513
+ annotate(options) {
3514
+ const given = options ?? {};
3515
+ return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);
3516
+ }
3517
+ /** Wait until every event so far has reached the sink and the sink has flushed. */
3518
+ async flush() {
3519
+ await this.#core.settle();
3520
+ try {
3521
+ await this.#core.sink.flush();
3522
+ } catch (err) {
3523
+ process.stderr.write(`baton: sink.flush failed: ${String(err)}
3524
+ `);
3525
+ }
3526
+ }
3527
+ /** Flush, then close the sink. Later events are dropped. */
3528
+ aclose() {
3529
+ this.#closing ??= this.#close();
3530
+ return this.#closing;
3531
+ }
3532
+ async #close() {
3533
+ await this.#core.settle();
3534
+ this.#core.closed = true;
3535
+ try {
3536
+ await this.#core.sink.aclose();
3537
+ } catch (err) {
3538
+ process.stderr.write(`baton: sink.aclose failed: ${String(err)}
3539
+ `);
3540
+ }
3541
+ }
3542
+ };
2938
3543
  // Annotate the CommonJS export names for ESM import in node:
2939
3544
  0 && (module.exports = {
2940
3545
  AnnotationEventSchema,
2941
3546
  AnnotationPayloadSchema,
2942
3547
  BatonHandle,
3548
+ Client,
2943
3549
  DEFAULT_CONSENT_TOKEN,
2944
3550
  DEPTH_LIMIT,
2945
3551
  EventSchema,
2946
3552
  EventTypeSchema,
2947
3553
  HttpSink,
3554
+ INTENT_INSTRUCTIONS,
3555
+ INTENT_PARAMS,
2948
3556
  PRINCIPAL_FORM_HASHED,
2949
3557
  PRINCIPAL_FORM_RAW,
2950
3558
  PRINCIPAL_SOURCE_ASSERTED,
@@ -2990,6 +3598,7 @@ function principalFromOAuthEmail(context) {
2990
3598
  ToolListErrorPayloadSchema,
2991
3599
  ToolListStartEventSchema,
2992
3600
  ToolListStartPayloadSchema,
3601
+ Trace,
2993
3602
  createBaton,
2994
3603
  identityScrub,
2995
3604
  principalFromOAuthEmail,