@goodtiming/baton-sdk 0.5.7 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -39,6 +39,7 @@ __export(index_exports, {
39
39
  EventSchema: () => EventSchema,
40
40
  EventTypeSchema: () => EventTypeSchema,
41
41
  HttpSink: () => HttpSink,
42
+ INTENT_INSTRUCTIONS: () => INTENT_INSTRUCTIONS,
42
43
  INTENT_PARAMS: () => INTENT_PARAMS,
43
44
  PRINCIPAL_FORM_HASHED: () => PRINCIPAL_FORM_HASHED,
44
45
  PRINCIPAL_FORM_RAW: () => PRINCIPAL_FORM_RAW,
@@ -96,7 +97,7 @@ __export(index_exports, {
96
97
  module.exports = __toCommonJS(index_exports);
97
98
 
98
99
  // src/version.ts
99
- var SDK_VERSION = "ts-0.5.7";
100
+ var SDK_VERSION = "ts-0.6.1";
100
101
 
101
102
  // src/events.ts
102
103
  var import_zod = require("zod");
@@ -241,6 +242,7 @@ var envelopeShape = {
241
242
  // consumer names the client from `client_observed`.
242
243
  agent_runtime: import_zod.z.string().default("unknown"),
243
244
  principal: PrincipalWireSchema.nullable().default(null),
245
+ organization: PrincipalWireSchema.nullable().default(null),
244
246
  transport_observed: import_zod.z.string().nullable().default(null),
245
247
  session_id_origin: import_zod.z.string().nullable().default(null),
246
248
  client_observed: ClientObservedSchema.nullable().default(null),
@@ -832,59 +834,113 @@ var LONE_SURROGATE = /\p{Surrogate}/u;
832
834
  function pythonStrip(value) {
833
835
  return value.replace(PYTHON_STRIP, "");
834
836
  }
835
- function normalizePrincipal(result) {
837
+ function usableId(id) {
838
+ if (typeof id !== "string") return false;
839
+ if (LONE_SURROGATE.test(id)) return false;
840
+ if (id.includes("\0")) return false;
841
+ return pythonStrip(id) !== "";
842
+ }
843
+ function readIdentity(result, idKey) {
836
844
  if (result === null || typeof result !== "object") return null;
837
845
  const candidate = result;
838
- if (typeof candidate.principalId !== "string") return null;
839
- if (LONE_SURROGATE.test(candidate.principalId)) return null;
840
- if (candidate.principalId.includes("\0")) return null;
841
- if (pythonStrip(candidate.principalId) === "") return null;
842
- const principal = { principalId: candidate.principalId };
843
- if (candidate.form !== void 0) principal.form = candidate.form;
844
- if (typeof candidate.displayName === "string") principal.displayName = candidate.displayName;
845
- return principal;
846
- }
847
- function principalFor(principal, onUnregisteredForm) {
846
+ const id = candidate[idKey];
847
+ if (!usableId(id)) return null;
848
+ const displayName = typeof candidate.displayName === "string" ? candidate.displayName : void 0;
849
+ return { id, form: candidate.form, displayName };
850
+ }
851
+ var NO_CALLER = Object.freeze({ principal: null, organization: null });
852
+ function callerFor(result, warn4) {
853
+ try {
854
+ return readCaller(result, warn4);
855
+ } catch {
856
+ warn4("unreadable", "could not be read \u2014 sending neither principal nor organization.");
857
+ return NO_CALLER;
858
+ }
859
+ }
860
+ function readCaller(result, warn4) {
861
+ if (result === void 0 || result === null) return NO_CALLER;
862
+ if (typeof result !== "object") {
863
+ warn4("not-object", `got a ${typeof result}, not an object \u2014 sending neither principal nor organization.`);
864
+ return NO_CALLER;
865
+ }
866
+ if (!("principalId" in result) && !("organization" in result)) {
867
+ if ("organizationId" in result) {
868
+ return { principal: null, organization: identityFor(result, "organization", warn4) };
869
+ }
870
+ if (typeof result.userId === "string") {
871
+ warn4(
872
+ "user-id",
873
+ "returned { userId }, which was renamed to { principalId } in 0.3.5, so the principal is dropped from every event until it returns the new key."
874
+ );
875
+ } else {
876
+ warn4("no-id", "got an object with neither principalId nor organizationId \u2014 sending neither.");
877
+ }
878
+ return NO_CALLER;
879
+ }
880
+ if ("organizationId" in result) {
881
+ warn4("flat-organization-id", "got principalId and organizationId side by side; put the company in `organization`.");
882
+ }
883
+ const nested = result.organization;
884
+ return {
885
+ principal: identityFor(result, "principal", warn4),
886
+ organization: nested == null ? null : identityFor(nested, "organization", warn4)
887
+ };
888
+ }
889
+ function identityFor(value, member, warn4) {
890
+ const idKey = member === "principal" ? "principalId" : "organizationId";
891
+ const identity = readIdentity(value, idKey);
892
+ if (identity === null) {
893
+ warn4(`${member}:id`, `${member} has no usable ${idKey} \u2014 sending no ${member}.`);
894
+ return null;
895
+ }
896
+ return identityWire(
897
+ identity.id,
898
+ identity.form,
899
+ identity.displayName,
900
+ (form) => warn4(`${member}:form`, `${member} form ${describeForm(form)} is not registered \u2014 sending "raw".`)
901
+ );
902
+ }
903
+ function describeForm(form) {
904
+ return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
905
+ }
906
+ function identityWire(id, stated, displayName, onUnregisteredForm) {
848
907
  let form = PRINCIPAL_FORM_RAW;
849
- if (principal.form !== void 0) {
850
- if (PRINCIPAL_FORMS.has(principal.form)) {
851
- form = principal.form;
908
+ if (stated !== void 0) {
909
+ if (PRINCIPAL_FORMS.has(stated)) {
910
+ form = stated;
852
911
  } else {
853
- onUnregisteredForm?.(principal.form);
912
+ onUnregisteredForm?.(stated);
854
913
  }
855
914
  }
856
915
  const wire = {
857
916
  // `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
858
917
  // an astral id cut at the boundary would ship a lone surrogate.
859
- id: capCodePoints(principal.principalId, PRINCIPAL_ID_MAX_LEN),
918
+ id: capCodePoints(id, PRINCIPAL_ID_MAX_LEN),
860
919
  source: PRINCIPAL_SOURCE_ASSERTED,
861
920
  form
862
921
  };
863
- const displayName = wireDisplayName(principal.displayName);
864
- if (displayName !== null) wire.display_name = displayName;
922
+ const name = wireDisplayName(displayName);
923
+ if (name !== null) wire.display_name = name;
865
924
  return wire;
866
925
  }
867
926
 
868
927
  // src/integrations/mcp/llmText.ts
869
- 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
-
871
- 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).
928
+ 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.`;
929
+ var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
930
+ 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.
872
931
 
873
- 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.`;
874
- 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.
932
+ 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.
875
933
 
876
934
  Fields:
877
- - user_goal: one sentence on what the user is trying to accomplish.
878
- - 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.
879
- - tool_name: REQUIRED on a report. The ${vendorDisplayName} tool that went wrong. Write none if no tool exists for the request.
880
- - expected_result: what a successful result should look like, so a silent/thin failure can be told apart from success.
881
- - 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.
882
- - suggested_improvement: A concrete sentence about what product change would have helped.
935
+ - user_goal: the same ${USER_GOAL_FORMAT} as on this server's other tools.
936
+ - 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.
937
+ - tool_name: REQUIRED. The ${vendorDisplayName} tool that went wrong, or none if no tool exists for the request.
938
+ - suggested_improvement: one concrete sentence on the product change that would have helped.
883
939
  - 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.`;
884
940
  var CLAUDE_CODE_TRUNCATION_CAP = 2087;
885
941
  var INSTRUCTIONS_LENGTH_CAP = 1500;
886
942
  function renderServerInstructions(options) {
887
- return SERVER_INSTRUCTIONS_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
943
+ return REPORT_POINTER_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
888
944
  }
889
945
  function fitsInstructionsCap(options) {
890
946
  return renderServerInstructions(options).length <= INSTRUCTIONS_LENGTH_CAP;
@@ -896,7 +952,7 @@ function buildServerInstructions(options) {
896
952
  `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.`
897
953
  );
898
954
  }
899
- return options.intentParamMode === "off" ? rendered : rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
955
+ return rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
900
956
  }
901
957
  function buildAnnotationToolDescription(options) {
902
958
  return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
@@ -904,39 +960,68 @@ function buildAnnotationToolDescription(options) {
904
960
  var USER_GOAL_PARAM_NAME = "user_goal";
905
961
  var EXPECTED_RESULT_PARAM_NAME = "expected_result";
906
962
  var OVERALL_TASK_PARAM_NAME = "overall_task";
963
+ var RETIRED_PARAM_NAMES = [EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME];
907
964
  var INTENT_SOURCE_PARAM = "injected_param";
908
965
  var INTENT_SOURCE_LIBRARY = "library_arg";
909
- 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).";
966
+ 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.`;
910
967
  var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
911
968
  var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
912
- 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.";
913
- var EXPECTED_RESULT_PARAM_DESCRIPTION = "OPTIONAL. " + EXPECTED_RESULT_PARAM_BODY;
914
- var EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + EXPECTED_RESULT_PARAM_BODY;
915
- 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.";
916
- var OVERALL_TASK_PARAM_DESCRIPTION = "OPTIONAL. " + OVERALL_TASK_PARAM_BODY;
917
- var OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + OVERALL_TASK_PARAM_BODY;
918
- 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.";
969
+ 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.";
970
+ var INTENT_INSTRUCTIONS = INSTRUCTIONS_SUBAGENT_CLAUSE.trim();
919
971
  function buildUserGoalParamDescription(options = {}) {
920
972
  return options.intentParamMode === "required" ? USER_GOAL_PARAM_DESCRIPTION_REQUIRED : USER_GOAL_PARAM_DESCRIPTION;
921
973
  }
922
- function buildOverallTaskParamDescription(options = {}) {
923
- return options.intentParamMode === "required" ? OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED : OVERALL_TASK_PARAM_DESCRIPTION;
974
+ function requiredParamNames(intentParamMode) {
975
+ return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME] : [];
924
976
  }
925
- function buildExpectedResultParamDescription(options = {}) {
926
- return options.intentParamMode === "required" ? EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED : EXPECTED_RESULT_PARAM_DESCRIPTION;
977
+ function declaresParam(schema, name) {
978
+ const props = schema?.properties;
979
+ return typeof props === "object" && props !== null && name in props;
927
980
  }
928
- function requiredParamNames(intentParamMode) {
929
- return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME] : [];
981
+ function instructionsSuffixServed(annotationToolName, served) {
982
+ if (annotationToolName) return true;
983
+ return typeof served === "string" && served.includes(INTENT_INSTRUCTIONS);
930
984
  }
931
985
  var INTENT_PARAMS = Object.freeze([
932
- Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: "intent" }),
933
- Object.freeze({
934
- name: EXPECTED_RESULT_PARAM_NAME,
935
- description: EXPECTED_RESULT_PARAM_BODY,
936
- traceOption: "expectedOutcome"
937
- }),
938
- Object.freeze({ name: OVERALL_TASK_PARAM_NAME, description: OVERALL_TASK_PARAM_BODY, traceOption: "workflow" })
986
+ Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: "intent" })
939
987
  ]);
988
+ var VENDOR_INSTRUCTIONS = /* @__PURE__ */ Symbol("batonVendorInstructions");
989
+ var escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
990
+ var OURS_STARTS = [
991
+ new RegExp(
992
+ "^" + REPORT_POINTER_TEMPLATE("\0", "\0").split("\0").map(escapeRegExp).join(".+?")
993
+ ),
994
+ new RegExp("^" + escapeRegExp(INTENT_INSTRUCTIONS))
995
+ ];
996
+ function endsInOurs(current2, vendor) {
997
+ if (typeof current2 !== "string") return false;
998
+ const prefix = typeof vendor === "string" && vendor.trim() ? `${vendor}
999
+
1000
+ ` : "";
1001
+ if (!current2.startsWith(prefix)) return false;
1002
+ const rest = current2.slice(prefix.length);
1003
+ return OURS_STARTS.some((start) => start.test(rest));
1004
+ }
1005
+ function withVendorInstructions(server, ours, warn4 = (message) => process.stderr.write(message)) {
1006
+ const holder = server;
1007
+ const current2 = holder._instructions;
1008
+ let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
1009
+ if (!endsInOurs(current2, vendor)) {
1010
+ vendor = current2;
1011
+ holder[VENDOR_INSTRUCTIONS] = vendor;
1012
+ }
1013
+ if (typeof vendor !== "string" || !vendor.trim()) return ours;
1014
+ const combined = `${vendor}
1015
+
1016
+ ${ours}`;
1017
+ if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
1018
+ warn4(
1019
+ `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
1020
+ `
1021
+ );
1022
+ }
1023
+ return combined;
1024
+ }
940
1025
 
941
1026
  // src/integrations/mcp/annotationName.ts
942
1027
  var TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
@@ -1111,47 +1196,32 @@ async function withinHookBudget(answer) {
1111
1196
  clearTimeout(timer);
1112
1197
  }
1113
1198
  }
1114
- var warnedPreRenameShape = false;
1115
- function warnIfPreRenameShape(result) {
1116
- const userId = result?.userId;
1117
- if (warnedPreRenameShape || typeof userId !== "string") return;
1118
- warnedPreRenameShape = true;
1119
- warn(
1120
- "baton: resolvePrincipal returned { userId }, which was renamed to { principalId } in 0.3.5, so the principal is dropped from every event until the hook returns the new key."
1121
- );
1199
+ var warned = /* @__PURE__ */ new Set();
1200
+ function warnOnce(key, message) {
1201
+ if (warned.has(key)) return;
1202
+ warned.add(key);
1203
+ warn(`baton: resolvePrincipal ${message}`);
1122
1204
  }
1123
- async function resolveCallPrincipal(hook, call) {
1124
- if (hook === void 0) return null;
1205
+ async function resolveCaller(hook, call) {
1206
+ if (hook === void 0) return NO_CALLER;
1125
1207
  try {
1126
1208
  const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
1127
1209
  const result = await withinHookBudget(hook(context));
1128
- const principal = normalizePrincipal(result);
1129
- if (principal === null) {
1130
- warnIfPreRenameShape(result);
1131
- return null;
1132
- }
1133
- return principalFor(principal, (form) => {
1134
- warn(
1135
- `baton: resolvePrincipal returned form ${describeForm(form)}, expected "raw" or "hashed" \u2014 sending it as "${PRINCIPAL_FORM_RAW}".`
1136
- );
1137
- });
1210
+ return callerFor(result, warnOnce);
1138
1211
  } catch {
1139
- return null;
1212
+ return NO_CALLER;
1140
1213
  }
1141
1214
  }
1142
- function describeForm(form) {
1143
- return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
1144
- }
1145
1215
 
1146
1216
  // src/integrations/mcp/safeScrub.ts
1147
- var warned = /* @__PURE__ */ new Set();
1217
+ var warned2 = /* @__PURE__ */ new Set();
1148
1218
  function scrubOrNull(scrubber, value, field) {
1149
1219
  if (value === null) return null;
1150
1220
  try {
1151
1221
  return scrubber(value);
1152
1222
  } catch (err) {
1153
- if (!warned.has(field)) {
1154
- warned.add(field);
1223
+ if (!warned2.has(field)) {
1224
+ warned2.add(field);
1155
1225
  process.stderr.write(
1156
1226
  `baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${String(err)}
1157
1227
  `
@@ -1293,12 +1363,10 @@ function registerAnnotationTool(server, options) {
1293
1363
  description,
1294
1364
  inputSchema: {
1295
1365
  user_goal: import_zod2.z.string(),
1296
- expected_result: import_zod2.z.string().optional(),
1297
1366
  what_happened: import_zod2.z.string().optional(),
1298
1367
  // Nullable so a report whose agent sends an explicit null is taken,
1299
1368
  // not rejected by validation.
1300
1369
  tool_name: import_zod2.z.string().nullable().optional(),
1301
- overall_task: import_zod2.z.string().optional(),
1302
1370
  suggested_improvement: import_zod2.z.string().optional(),
1303
1371
  context: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).optional()
1304
1372
  }
@@ -1326,7 +1394,7 @@ function registerAnnotationTool(server, options) {
1326
1394
  "_meta"
1327
1395
  );
1328
1396
  const { sessionId, origin } = await resolveSessionId(options.fallbackSessionId, extra);
1329
- const principal = await resolveCallPrincipal(
1397
+ const caller = await resolveCaller(
1330
1398
  options.resolvePrincipal,
1331
1399
  { extra, toolName: name, arguments: args }
1332
1400
  );
@@ -1339,27 +1407,20 @@ function registerAnnotationTool(server, options) {
1339
1407
  sequence_number: options.counter.next(sessionId),
1340
1408
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1341
1409
  consent_token: options.consentToken,
1342
- principal,
1410
+ principal: caller.principal,
1411
+ organization: caller.organization,
1343
1412
  transport_observed: observeTransport(extra),
1344
1413
  session_id_origin: origin,
1345
1414
  client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
1346
1415
  runtime_meta: scrubbedMeta,
1347
1416
  payload: {
1348
- // Agent-facing names -> wire keys, as with `overall_task`
1349
- // below: `user_goal` is stored as `intent`, `expected_result` as
1350
- // `expected_outcome`.
1417
+ // The agent-facing `user_goal` is stored as the wire key `intent`.
1351
1418
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1352
1419
  intent: options.scrubber(args.user_goal),
1353
- expected_outcome: args.expected_result ? options.scrubber(args.expected_result) : null,
1354
1420
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1355
1421
  what_happened: options.scrubber(whatHappened),
1356
1422
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1357
1423
  tool_name: reportedTool ? options.scrubber(reportedTool) : reportedTool,
1358
- // Agent-facing param `overall_task` -> wire key `workflow`, the same
1359
- // split the injected params use (`overall_task` -> `call_workflow`):
1360
- // renaming the param must not move the key the console groups on.
1361
- // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1362
- workflow: args.overall_task ? options.scrubber(args.overall_task) : null,
1363
1424
  suggested_improvement: args.suggested_improvement ? options.scrubber(args.suggested_improvement) : null,
1364
1425
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1365
1426
  context: args.context ? options.scrubber(args.context) : null
@@ -1579,11 +1640,14 @@ function sealKey(dsn) {
1579
1640
  // src/integrations/mcp/errorResult.ts
1580
1641
  var TOOL_ERROR_TYPE = "tool_error";
1581
1642
  var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
1643
+ var REFUSED = "refused";
1582
1644
  var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
1583
- function requestSideFailureKind(entry) {
1645
+ function requestSideFailureKind(entry, validation) {
1584
1646
  if (entry == null) return "unknown_tool";
1585
1647
  if (entry.enabled === false) return "tool_disabled";
1586
- return TASK_MODES.has(entry.execution?.taskSupport) ? void 0 : "invalid_argument";
1648
+ if (validation === "rejected") return "invalid_argument";
1649
+ if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
1650
+ return validation === "unprobed" ? "invalid_argument" : REFUSED;
1587
1651
  }
1588
1652
  var ERROR_BODY_MAX_CODE_POINTS = 2e3;
1589
1653
  function isErrorResult(value) {
@@ -1634,6 +1698,9 @@ function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
1634
1698
  function requestSideErrorFields(text, errorBody2) {
1635
1699
  return { error_body: errorBody2(text), result: null };
1636
1700
  }
1701
+ function requestSideFailureFields(kind, mode, text, result, errorBody2, scrubber) {
1702
+ return kind === REFUSED ? resultDerivedFields(mode, text, result ?? null, errorBody2, scrubber) : requestSideErrorFields(text(), errorBody2);
1703
+ }
1637
1704
  function errorTypeOf(err) {
1638
1705
  return err instanceof Error ? err.constructor.name : "Error";
1639
1706
  }
@@ -1645,7 +1712,8 @@ function scrubbedErrorBody(scrubber, text) {
1645
1712
  }
1646
1713
 
1647
1714
  // src/integrations/mcp/config.ts
1648
- var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1715
+ var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
1716
+ var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
1649
1717
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1650
1718
  function resolveTenantId(explicit, vendorId2) {
1651
1719
  if (explicit) return explicit;
@@ -1730,9 +1798,14 @@ function validateBatonConfig(config) {
1730
1798
  `vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
1731
1799
  );
1732
1800
  }
1733
- if (!config.vendorDisplayName) {
1801
+ if (config.reportMode !== void 0 && !REPORT_MODES.has(config.reportMode)) {
1802
+ throw new Error(
1803
+ `BatonConfig.reportMode ${JSON.stringify(config.reportMode)} must be one of ${JSON.stringify([...REPORT_MODES].sort())}.`
1804
+ );
1805
+ }
1806
+ if (!config.vendorDisplayName && config.reportMode === "on") {
1734
1807
  throw new Error(
1735
- "BatonConfig.vendorDisplayName is required \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4)."
1808
+ 'BatonConfig needs a vendorDisplayName with reportMode: "on" \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4).'
1736
1809
  );
1737
1810
  }
1738
1811
  if (config.consentToken !== void 0 && !config.consentToken) {
@@ -1745,6 +1818,11 @@ function validateBatonConfig(config) {
1745
1818
  "BatonConfig.consentToken is required per SPEC \xA72.3 \u2014 events without a valid consent_token MUST be rejected by the consumer."
1746
1819
  );
1747
1820
  }
1821
+ if (config.intentParamMode === "off") {
1822
+ throw new Error(
1823
+ 'BatonConfig.intentParamMode: "off" would leave nothing capturing what the user is trying to do. Use "required" (the default) or "optional".'
1824
+ );
1825
+ }
1748
1826
  if (config.intentParamMode !== void 0 && !INTENT_PARAM_MODES.has(config.intentParamMode)) {
1749
1827
  throw new Error(
1750
1828
  `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
@@ -1930,17 +2008,14 @@ function injectGoalParams(inputSchema, intentParamMode) {
1930
2008
  function buildIntentFields(existingShape, zodImpl, intentParamMode) {
1931
2009
  const dispositions = {};
1932
2010
  const toInject = {};
1933
- for (const [name, buildDescription] of [
1934
- [USER_GOAL_PARAM_NAME, buildUserGoalParamDescription],
1935
- [EXPECTED_RESULT_PARAM_NAME, buildExpectedResultParamDescription],
1936
- [OVERALL_TASK_PARAM_NAME, buildOverallTaskParamDescription]
1937
- ]) {
1938
- if (name in existingShape) {
1939
- dispositions[name] = "native";
1940
- } else {
1941
- dispositions[name] = "injected";
1942
- toInject[name] = zodImpl.string().optional().describe(buildDescription({ intentParamMode }));
1943
- }
2011
+ for (const name of RETIRED_PARAM_NAMES) {
2012
+ if (name in existingShape) dispositions[name] = "native";
2013
+ }
2014
+ if (USER_GOAL_PARAM_NAME in existingShape) {
2015
+ dispositions[USER_GOAL_PARAM_NAME] = "native";
2016
+ } else {
2017
+ dispositions[USER_GOAL_PARAM_NAME] = "injected";
2018
+ toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
1944
2019
  }
1945
2020
  return { dispositions, toInject };
1946
2021
  }
@@ -2020,12 +2095,12 @@ function assembleSurface(serverMeta, tools) {
2020
2095
  function buildSeamAugmentations(options) {
2021
2096
  return {
2022
2097
  injected_tools: [...options.injectedToolNames].sort(),
2023
- intent_param: options.intentParamMode !== "off" ? {
2098
+ intent_param: {
2024
2099
  names: [...options.intentParamNames].sort(),
2025
2100
  required_names: [...options.requiredParamNames].sort(),
2026
2101
  mode: options.intentParamMode
2027
- } : null,
2028
- instructions_suffix: true
2102
+ },
2103
+ instructions_suffix: options.instructionsSuffix
2029
2104
  };
2030
2105
  }
2031
2106
 
@@ -2095,23 +2170,16 @@ async function resolveEnvelopeParts(ctx, extra) {
2095
2170
  const session = await resolveSessionId(ctx.fallbackSessionId, extra);
2096
2171
  return { ...session, scrubbedMeta };
2097
2172
  }
2098
- async function openCall(ctx, toolName, extra, params, registered = true) {
2173
+ async function openCall(ctx, toolName, extra, params, retired, registered = true) {
2099
2174
  await maybeEmitSurfaceSnapshot(ctx);
2100
2175
  const { sessionId, origin, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
2101
2176
  const dispositions = ctx.paramRegistry.get(toolName);
2102
2177
  const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
2103
- const rawExpected = extractGoalParam(
2104
- params,
2105
- EXPECTED_RESULT_PARAM_NAME,
2106
- toolName,
2107
- dispositions,
2108
- registered
2109
- );
2110
- const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions, registered);
2111
2178
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
2112
- const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);
2113
- const scrubbedWorkflow = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);
2114
- const principal = await resolveCallPrincipal(
2179
+ const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
2180
+ (name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, retired[name] ?? popText(params, name), name)
2181
+ );
2182
+ const caller = await resolveCaller(
2115
2183
  ctx.resolvePrincipal,
2116
2184
  { extra, toolName, arguments: params }
2117
2185
  );
@@ -2124,7 +2192,8 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
2124
2192
  // it. `surface_snapshot` is deliberately not among them: it describes the
2125
2193
  // SERVER and is captured outside any call, so it has no caller, transport
2126
2194
  // or client to name.
2127
- principal,
2195
+ principal: caller.principal,
2196
+ organization: caller.organization,
2128
2197
  transport_observed: observeTransport(extra),
2129
2198
  session_id_origin: origin,
2130
2199
  client_observed: observeClient(extra, ctx),
@@ -2157,7 +2226,9 @@ function batonWrap(nameRef, original, ctx) {
2157
2226
  if (slot) slot.innerFired = true;
2158
2227
  const extra = callArgs[callArgs.length - 1];
2159
2228
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
2160
- const { common, sessionId } = await openCall(ctx, toolName, extra, params);
2229
+ const retired = slot?.retired ?? {};
2230
+ if (slot) slot.retired = {};
2231
+ const { common, sessionId } = await openCall(ctx, toolName, extra, params, retired);
2161
2232
  const terminate = async (build, replacement) => {
2162
2233
  if (!slot) {
2163
2234
  await emit(ctx.sink, build);
@@ -2325,10 +2396,28 @@ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
2325
2396
  `
2326
2397
  );
2327
2398
  }
2399
+ return popText(args, paramName);
2400
+ }
2401
+ function popText(args, paramName) {
2402
+ if (!(paramName in args)) return null;
2328
2403
  const raw = args[paramName];
2329
2404
  delete args[paramName];
2330
2405
  return typeof raw === "string" && raw.trim() ? raw : null;
2331
2406
  }
2407
+ function stripRetiredParams(params, ctx) {
2408
+ const toolName = params?.name;
2409
+ const args = params?.arguments;
2410
+ if (typeof toolName !== "string") return {};
2411
+ if (toolName === ctx.annotationToolName) return {};
2412
+ if (typeof args !== "object" || args === null || Array.isArray(args)) return {};
2413
+ const dispositions = ctx.paramRegistry.get(toolName);
2414
+ const retired = {};
2415
+ for (const name of RETIRED_PARAM_NAMES) {
2416
+ if (dispositions === void 0 || dispositions[name] === "native" || !(name in args)) continue;
2417
+ retired[name] = popText(args, name);
2418
+ }
2419
+ return retired;
2420
+ }
2332
2421
  var MAX_REMEMBERED_SURFACES = 1024;
2333
2422
  async function maybeEmitSurfaceSnapshot(ctx) {
2334
2423
  if (!ctx.surfaceState.dirty) return;
@@ -2348,10 +2437,11 @@ async function maybeEmitSurfaceSnapshot(ctx) {
2348
2437
  if (emitted.size >= MAX_REMEMBERED_SURFACES) emitted.clear();
2349
2438
  emitted.add(digest);
2350
2439
  const seam = buildSeamAugmentations({
2351
- injectedToolNames: [ctx.annotationToolName],
2352
- intentParamNames: [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME],
2440
+ injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
2441
+ intentParamNames: [USER_GOAL_PARAM_NAME],
2353
2442
  intentParamMode: ctx.intentParamMode,
2354
- requiredParamNames: requiredParamNames(ctx.intentParamMode)
2443
+ requiredParamNames: requiredParamNames(ctx.intentParamMode),
2444
+ instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions())
2355
2445
  });
2356
2446
  try {
2357
2447
  await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
@@ -2362,11 +2452,19 @@ async function maybeEmitSurfaceSnapshot(ctx) {
2362
2452
  ctx.surfaceState.dirty = true;
2363
2453
  }
2364
2454
  }
2455
+ function declaredIntentParams(vendorSchema) {
2456
+ const declared2 = {};
2457
+ for (const name of [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES]) {
2458
+ if (declaresParam(vendorSchema, name)) declared2[name] = "native";
2459
+ }
2460
+ return declared2;
2461
+ }
2365
2462
  function captureAndInject(name, entry, ctx) {
2366
2463
  if (!entry || typeof entry !== "object") return;
2367
2464
  const mutable = entry;
2368
- ctx.surfaceState.noteTool(name, ctx.vendorToolJsonSchema(name, mutable.inputSchema), mutable.description);
2369
- if (ctx.intentParamMode === "off") return;
2465
+ const vendorSchema = ctx.vendorToolJsonSchema(name, mutable.inputSchema);
2466
+ ctx.surfaceState.noteTool(name, vendorSchema, mutable.description);
2467
+ if (declaresParam(vendorSchema, USER_GOAL_PARAM_NAME)) ctx.dropSubagentClause(name);
2370
2468
  const isV2 = typeof mutable.executor === "function";
2371
2469
  try {
2372
2470
  const { schema, dispositions } = isV2 ? injectGoalParamsV2(mutable.inputSchema, ctx.intentParamMode) : injectGoalParams(mutable.inputSchema, ctx.intentParamMode);
@@ -2374,9 +2472,10 @@ function captureAndInject(name, entry, ctx) {
2374
2472
  mutable.inputSchema = schema;
2375
2473
  ctx.bustSchemaMemo(name);
2376
2474
  ctx.paramRegistry.set(name, dispositions);
2377
- if (dispositions[OVERALL_TASK_PARAM_NAME] === "native") ctx.dropSubagentClause(name);
2378
2475
  } else {
2379
- ctx.paramRegistry.delete(name);
2476
+ const declared2 = declaredIntentParams(vendorSchema);
2477
+ if (Object.keys(declared2).length > 0) ctx.paramRegistry.set(name, declared2);
2478
+ else ctx.paramRegistry.delete(name);
2380
2479
  }
2381
2480
  } catch {
2382
2481
  }
@@ -2477,7 +2576,7 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
2477
2576
  async function openLifecycleCall(ctx, spec, requestParams, extra) {
2478
2577
  try {
2479
2578
  const parts = await resolveEnvelopeParts(ctx, extra);
2480
- const principal = await resolveCallPrincipal(ctx.resolvePrincipal, {
2579
+ const caller = await resolveCaller(ctx.resolvePrincipal, {
2481
2580
  extra,
2482
2581
  toolName: null,
2483
2582
  arguments: {}
@@ -2490,7 +2589,8 @@ async function openLifecycleCall(ctx, spec, requestParams, extra) {
2490
2589
  vendor_id: ctx.vendorId,
2491
2590
  session_id: parts.sessionId,
2492
2591
  consent_token: ctx.consentToken,
2493
- principal,
2592
+ principal: caller.principal,
2593
+ organization: caller.organization,
2494
2594
  transport_observed: observeTransport(extra),
2495
2595
  session_id_origin: parts.origin,
2496
2596
  client_observed: observeClient(extra, ctx),
@@ -2618,7 +2718,13 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
2618
2718
  TOOLS_CALL_METHOD,
2619
2719
  TOOLS_CALL_SEAM,
2620
2720
  (handler) => async (...args) => {
2621
- const slot = { innerFired: false, flushTerminal: null };
2721
+ const request = args[0];
2722
+ const slot = {
2723
+ innerFired: false,
2724
+ flushTerminal: null,
2725
+ retired: stripRetiredParams(request?.params, ctx),
2726
+ validation: ctx.validationProbeLive() ? "unseen" : "unprobed"
2727
+ };
2622
2728
  let outcome = CLEAN_OUTCOME;
2623
2729
  try {
2624
2730
  const result = await callSlots.run(slot, () => handler(...args));
@@ -2633,6 +2739,27 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
2633
2739
  }
2634
2740
  );
2635
2741
  }
2742
+ var VALIDATION_PROBE = /* @__PURE__ */ Symbol("baton.validationProbe");
2743
+ function installValidationProbe(server) {
2744
+ const target = server;
2745
+ const original = target.validateToolInput;
2746
+ if (typeof original !== "function") return () => false;
2747
+ if (original[VALIDATION_PROBE]) return () => target.validateToolInput === original;
2748
+ const probe = async function(...args) {
2749
+ const slot = callSlots.getStore();
2750
+ try {
2751
+ const parsed = await original.apply(this, args);
2752
+ if (slot) slot.validation = "passed";
2753
+ return parsed;
2754
+ } catch (err) {
2755
+ if (slot) slot.validation = "rejected";
2756
+ throw err;
2757
+ }
2758
+ };
2759
+ Object.assign(probe, { [VALIDATION_PROBE]: true });
2760
+ target.validateToolInput = probe;
2761
+ return () => target.validateToolInput === probe;
2762
+ }
2636
2763
  async function settleCall(slot, outcome, args, toolEntry, ctx) {
2637
2764
  try {
2638
2765
  if (slot.flushTerminal !== null) {
@@ -2643,13 +2770,13 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
2643
2770
  }
2644
2771
  if (slot.innerFired) return;
2645
2772
  if (!outcome.failed) return;
2646
- await emitRequestSideFailure(outcome, args, toolEntry, ctx);
2773
+ await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
2647
2774
  } catch (err) {
2648
2775
  process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
2649
2776
  `);
2650
2777
  }
2651
2778
  }
2652
- async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2779
+ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
2653
2780
  const request = args[0];
2654
2781
  const toolName = request?.params?.name;
2655
2782
  if (typeof toolName !== "string") return;
@@ -2662,9 +2789,11 @@ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2662
2789
  toolName,
2663
2790
  args[1],
2664
2791
  params,
2792
+ slot.retired,
2665
2793
  entry != null
2666
2794
  );
2667
- const failureKind = requestSideFailureKind(entry);
2795
+ const failureKind = requestSideFailureKind(entry, slot.validation);
2796
+ const text = () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result);
2668
2797
  await emit(
2669
2798
  ctx.sink,
2670
2799
  () => ToolCallErrorEventSchema.parse({
@@ -2685,8 +2814,8 @@ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2685
2814
  error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
2686
2815
  // ⚠ `null`, not 0. The vendor's handler never ran, so there is no
2687
2816
  // handler duration to report; the time this call did spend was spent
2688
- // in the SDK's validator, which is not what any other event means by
2689
- // this member. §11.4 types it nullable for cases like this one.
2817
+ // above the handler, which is not what any other event means by this
2818
+ // member. §11.4 types it nullable for cases like this one.
2690
2819
  duration_ms: null,
2691
2820
  // ⚠ A CONDITIONAL SPREAD, not `failure_kind: failureKind`. Zod's
2692
2821
  // `.optional()` accepts `undefined` and keeps the KEY in its output,
@@ -2696,11 +2825,13 @@ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2696
2825
  // determine the kind MUST OMIT the member, and omitting is what this
2697
2826
  // spells.
2698
2827
  ...failureKind === void 0 ? {} : { failure_kind: failureKind },
2699
- // KEPT under `"off"` — see `requestSideErrorFields`, which takes no
2700
- // capture mode because nothing here is derived from a result.
2701
- ...requestSideErrorFields(
2702
- outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
2703
- (text) => errorBody(ctx, text)
2828
+ ...requestSideFailureFields(
2829
+ failureKind,
2830
+ ctx.resultCaptureMode,
2831
+ text,
2832
+ outcome.raised ? null : outcome.result,
2833
+ (value) => errorBody(ctx, value),
2834
+ ctx.scrubber
2704
2835
  )
2705
2836
  }
2706
2837
  })
@@ -2781,7 +2912,9 @@ function withBaton(server, supplied = {}) {
2781
2912
  annotationToolName: ""
2782
2913
  });
2783
2914
  }
2784
- return install(server, supplied, resolveBatonConfig(supplied), /* @__PURE__ */ new Set());
2915
+ const resolved = resolveBatonConfig(supplied);
2916
+ warnUnusedReportSettings(resolved);
2917
+ return install(server, supplied, resolved, /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set());
2785
2918
  }
2786
2919
  function createBaton(supplied = {}) {
2787
2920
  const disabledBy = captureDisabled();
@@ -2792,7 +2925,8 @@ function createBaton(supplied = {}) {
2792
2925
  }, flush: () => unused.flush(), aclose: () => unused.aclose() };
2793
2926
  }
2794
2927
  const resolved = resolveBatonConfig(supplied);
2795
- deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
2928
+ warnUnusedReportSettings(resolved);
2929
+ if (resolved.reportMode === "on") deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
2796
2930
  const sink = resolved.sink ?? new StdoutSink();
2797
2931
  const config = {
2798
2932
  ...resolved,
@@ -2800,23 +2934,25 @@ function createBaton(supplied = {}) {
2800
2934
  tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
2801
2935
  };
2802
2936
  const emittedSurfaceHashes = /* @__PURE__ */ new Set();
2937
+ const warned3 = /* @__PURE__ */ new Set();
2803
2938
  return {
2804
2939
  wrap: (server) => {
2805
- install(server, supplied, config, emittedSurfaceHashes);
2940
+ install(server, supplied, config, emittedSurfaceHashes, warned3);
2806
2941
  },
2807
2942
  flush: () => sink.flush(),
2808
2943
  aclose: () => sink.aclose()
2809
2944
  };
2810
2945
  }
2811
- function install(server, supplied, resolved, emittedSurfaceHashes) {
2946
+ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
2812
2947
  const internals = server;
2813
2948
  const serverName = usableServerName(() => ({
2814
2949
  name: internals.server._serverInfo?.name,
2815
2950
  className: internals.constructor.name
2816
2951
  }));
2817
- const config = withServerDisplayName(resolved, supplied, serverName);
2952
+ const config = resolved.reportMode === "on" ? withServerDisplayName(resolved, supplied, serverName) : resolved;
2818
2953
  const sink = config.sink ?? new StdoutSink();
2819
- const annotationToolName = resolveAnnotationToolName(serverName, config);
2954
+ const reports = reportsFor(config);
2955
+ const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
2820
2956
  const intentParamMode = config.intentParamMode ?? "required";
2821
2957
  const counter2 = new SessionCounter();
2822
2958
  const fallbackSessionId = `sdk-${uuid7()}`;
@@ -2848,12 +2984,23 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2848
2984
  const memo = internals._toolInputSchemaJson;
2849
2985
  if (memo && typeof memo === "object") delete memo[name];
2850
2986
  };
2987
+ const warnOnce2 = (key, message) => {
2988
+ if (warned3.has(key)) return;
2989
+ warned3.add(key);
2990
+ process.stderr.write(message);
2991
+ };
2851
2992
  const dropSubagentClause = (name) => {
2852
2993
  const current2 = internals.server._instructions;
2853
- if (typeof current2 !== "string" || !current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) return;
2854
- internals.server._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
2855
- process.stderr.write(
2856
- `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
2994
+ if (current2 === INTENT_INSTRUCTIONS) {
2995
+ internals.server._instructions = "";
2996
+ } else if (typeof current2 === "string" && current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {
2997
+ internals.server._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
2998
+ } else {
2999
+ return;
3000
+ }
3001
+ warnOnce2(
3002
+ "native-user-goal",
3003
+ `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
2857
3004
  `
2858
3005
  );
2859
3006
  };
@@ -2890,20 +3037,22 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2890
3037
  annotationToolName,
2891
3038
  intentParamMode,
2892
3039
  resultCaptureMode: config.resultCaptureMode ?? "full",
3040
+ validationProbeLive: installValidationProbe(server),
2893
3041
  paramRegistry: /* @__PURE__ */ new Map(),
2894
3042
  resolvePrincipal: config.resolvePrincipal,
2895
3043
  vendorToolJsonSchema,
2896
3044
  bustSchemaMemo,
2897
3045
  dropSubagentClause,
3046
+ servedInstructions: () => internals.server._instructions,
2898
3047
  surfaceState,
2899
3048
  emitSurface
2900
3049
  };
2901
- const instructions = buildServerInstructions({
2902
- vendorDisplayName: config.vendorDisplayName,
2903
- annotationToolName,
2904
- intentParamMode
2905
- });
2906
- internals.server._instructions = instructions;
3050
+ const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
3051
+ internals.server._instructions = withVendorInstructions(
3052
+ internals.server,
3053
+ ours,
3054
+ (message) => warnOnce2("instructions-length", message)
3055
+ );
2907
3056
  installToolsListSeam(internals.server, ctx);
2908
3057
  installToolsCallSeam(
2909
3058
  internals.server,
@@ -2921,12 +3070,12 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2921
3070
  ctx
2922
3071
  );
2923
3072
  installLifecycleSeams(internals.server, ctx);
2924
- const resolvedAnnotationToolName = registerAnnotationTool(server, {
3073
+ const resolvedAnnotationToolName = !reports ? "" : registerAnnotationTool(server, {
2925
3074
  sink,
2926
3075
  counter: ctx.counter,
2927
3076
  tenantId: ctx.tenantId,
2928
3077
  vendorId: ctx.vendorId,
2929
- vendorDisplayName: config.vendorDisplayName,
3078
+ vendorDisplayName: reports.vendorDisplayName,
2930
3079
  consentToken: ctx.consentToken,
2931
3080
  resolvePrincipal: ctx.resolvePrincipal,
2932
3081
  fallbackSessionId: ctx.fallbackSessionId,
@@ -2955,6 +3104,18 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2955
3104
  annotationToolName: resolvedAnnotationToolName
2956
3105
  });
2957
3106
  }
3107
+ function reportsFor(config) {
3108
+ if (config.reportMode !== "on") return void 0;
3109
+ return { vendorDisplayName: config.vendorDisplayName ?? "" };
3110
+ }
3111
+ function warnUnusedReportSettings(config) {
3112
+ if (config.reportMode !== "on" && config.annotationToolName !== void 0) {
3113
+ process.stderr.write(
3114
+ `baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect with reportMode: "off", because no annotation tool is registered
3115
+ `
3116
+ );
3117
+ }
3118
+ }
2958
3119
 
2959
3120
  // src/integrations/mcp/oauthHooks.ts
2960
3121
  function claimsOf(context) {
@@ -2997,6 +3158,7 @@ function sessionEnvelope(session) {
2997
3158
  session_id_origin: session.origin,
2998
3159
  transport_observed: TRANSPORT_LIBRARY,
2999
3160
  principal: session.principal,
3161
+ organization: session.organization,
3000
3162
  client_observed: session.clientObserved,
3001
3163
  runtime_meta: session.turnId !== null ? { [TURN_ID_META_KEY]: session.turnId } : null
3002
3164
  };
@@ -3013,28 +3175,16 @@ function vendorId(name, value) {
3013
3175
  }
3014
3176
  return null;
3015
3177
  }
3016
- function minted() {
3017
- return { sessionId: uuid7(), origin: "minted", principal: null, clientObserved: null, turnId: null };
3018
- }
3019
- function wirePrincipal(value) {
3020
- if (value === void 0 || value === null) return null;
3021
- const principal = normalizePrincipal(value);
3022
- if (principal === null) {
3023
- warn3("principal was given but has no usable principalId \u2014 sending none.");
3024
- return null;
3025
- }
3026
- return principalFor(
3027
- principal,
3028
- (form) => warn3(`principal form ${JSON.stringify(form)} is not registered \u2014 sending "raw".`)
3029
- );
3178
+ function blank(sessionId, origin) {
3179
+ return { sessionId, origin, ...NO_CALLER, clientObserved: null, turnId: null };
3030
3180
  }
3031
3181
  function newSession(values, scrubber, disabled) {
3032
3182
  const id = vendorId("sessionId", values.sessionId);
3033
- const base = id !== null ? { sessionId: id, origin: "observed", principal: null, clientObserved: null, turnId: null } : minted();
3183
+ const base = id !== null ? blank(id, "observed") : blank(uuid7(), "minted");
3034
3184
  if (disabled) return base;
3035
3185
  return {
3036
3186
  ...base,
3037
- principal: wirePrincipal(values.principal),
3187
+ ...callerFor(values.principal, (_key, message) => warn3(`principal ${message}`)),
3038
3188
  clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber),
3039
3189
  turnId: vendorId("turnId", values.turnId)
3040
3190
  };
@@ -3045,7 +3195,7 @@ function runInSession(owner, session, fn) {
3045
3195
  }
3046
3196
  function sessionForCall(owner) {
3047
3197
  const entry = current.getStore();
3048
- return entry !== void 0 && entry.owner === owner ? entry.session : minted();
3198
+ return entry !== void 0 && entry.owner === owner ? entry.session : blank(uuid7(), "minted");
3049
3199
  }
3050
3200
  var lastSequence = 0;
3051
3201
  function nextSequence() {
@@ -3475,6 +3625,7 @@ var Client = class {
3475
3625
  EventSchema,
3476
3626
  EventTypeSchema,
3477
3627
  HttpSink,
3628
+ INTENT_INSTRUCTIONS,
3478
3629
  INTENT_PARAMS,
3479
3630
  PRINCIPAL_FORM_HASHED,
3480
3631
  PRINCIPAL_FORM_RAW,