@goodtiming/baton-sdk 0.3.4 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,7 +14,7 @@ Most production MCP servers are TypeScript, not Python — see the [design note]
14
14
  - `StdoutSink` — JSONL to a writable stream (default `process.stderr` — MCP stdio transport reserves stdout for JSON-RPC framing).
15
15
  - `HttpSink` — `POST {url}/v0/events` with bearer auth, bounded buffer, retry with backoff, circuit breaker. The contract any Baton-compatible collector consumes.
16
16
  - `withBaton(server, config)` — takes a packed `dsn` (the one string from /account) or the parts named individually, and wraps every tool call on a high-level `McpServer` from either SDK major (both optional peer dependencies) and emits `tool_call_start` / `tool_call_end` / `tool_call_error`. Works regardless of whether tools are registered before or after `withBaton` runs, and survives a tool's `.update()`/`.remove()` after the fact too (see the module docstring in `src/integrations/mcp/withBaton.ts` for why that ordering/mutation independence is load-bearing, not incidental). Also injects server `instructions` and registers the `<vendor>_annotate` tool so the calling agent can supply structured intent/outcome/friction signal — same behavioral contract as Python's adapters, ported byte-for-byte (verified against the Python SDK's actual rendered output, not just eyeballed).
17
- - Intent-param injection — `user_goal`/`expected_result`/`overall_task` string params are spliced onto every wrapped tool's advertised schema (`intentParamMode: "optional"` by default, `"required"` — which promotes only `user_goal` — or `"off"`), stripped before the vendor handler runs, and surfaced as `tool_call_start.payload.call_intent`/`call_expected`/`call_workflow`/`intent_source` plus a synthesised proactive `annotation` (at most one per session). `call_intent`/`call_expected` are call-scoped diagnostics that reword freely; `call_workflow` is the task-label grouping key the Console segments sessions on, which is why its injected param description carries an explicit repeat-the-exact-string contract. This is the capture path that survives runtimes which drop `instructions` entirely (notably Claude Desktop). A tool that already declares one of these names itself is left alone for that field (`"native"` disposition) — its value is forwarded to the vendor untouched, not captured as intent. A tool registered with no `inputSchema` at all is left alone regardless of mode, so a zero-arg handler's calling convention never changes underneath it.
17
+ - Intent-param injection: `user_goal`/`expected_result`/`overall_task` string params are spliced onto every wrapped tool's advertised schema (`intentParamMode: "required"` by default, which advertises only `user_goal` as required in `tools/list` and never enforces it, so a call without it is still served; `"optional"`, which advertises none as required; or `"off"`), stripped before the vendor handler runs, and surfaced as `tool_call_start.payload.call_intent`/`call_expected`/`call_workflow`/`intent_source` plus a synthesised proactive `annotation` (at most one per session). `call_intent`/`call_expected` are call-scoped diagnostics that reword freely; `call_workflow` is the task-label grouping key the Console segments sessions on, which is why its injected param description carries an explicit repeat-the-exact-string contract. This is the capture path that survives runtimes which drop `instructions` entirely (notably Claude Desktop). A tool that already declares one of these names itself is left alone for that field (`"native"` disposition): its value is forwarded to the vendor untouched, not captured as intent. A tool registered with no `inputSchema` at all is left alone regardless of mode, so a zero-arg handler's calling convention never changes underneath it.
18
18
  - `surface_snapshot` capture — the vendor-true (pre-injection) `server_info`/`capabilities`/`instructions`/tool list, hashed and emitted at most once per observed hash (lazily, on the first tool call — the high-level `McpServer` exposes no `tools/list` hook to capture on eagerly). Baton's own additions (the annotate tool, the injected params) are reported separately under `seam_augmentations`, never folded into the vendor-true snapshot.
19
19
  - PII scrubbing — every payload (tool params/results, `_meta`, intent strings, error bodies) runs through `Scrubber` before it reaches any sink, **on by default**. The ruleset is a rule-for-rule port of Python's `baton.scrub` (email, `Bearer` values, `sk-*` keys, `AKIA*` keys, JWTs, phone numbers, Luhn-checked card numbers, plus force-redaction on sensitive field names) — parity verified by mirroring Python's test matrix case-for-case *and* by diffing both implementations' output over a shared corpus. Pass `identityScrub` to opt out explicitly, or supply your own `(value: unknown) => unknown`.
20
20
 
@@ -108,7 +108,7 @@ collected. One real line from that stream, pretty-printed:
108
108
  "consent_token": "customer-consented",
109
109
  "sdk_version": "ts-0.3.0",
110
110
  "agent_runtime": "unknown",
111
- "user_id": null,
111
+ "principal_id": null,
112
112
  "runtime_meta": null,
113
113
  "event_type": "tool_call_start",
114
114
  "payload": {
package/dist/index.cjs CHANGED
@@ -50,7 +50,7 @@ __export(index_exports, {
50
50
  ToolCallStartEventSchema: () => ToolCallStartEventSchema,
51
51
  ToolCallStartPayloadSchema: () => ToolCallStartPayloadSchema,
52
52
  VENDOR_HASH_SCHEME: () => VENDOR_HASH_SCHEME,
53
- hashUserId: () => hashUserId,
53
+ hashPrincipalId: () => hashPrincipalId,
54
54
  identityScrub: () => identityScrub,
55
55
  safeWrite: () => safeWrite,
56
56
  withBaton: () => withBaton
@@ -58,7 +58,7 @@ __export(index_exports, {
58
58
  module.exports = __toCommonJS(index_exports);
59
59
 
60
60
  // src/version.ts
61
- var SDK_VERSION = "ts-0.3.4";
61
+ var SDK_VERSION = "ts-0.3.6";
62
62
 
63
63
  // src/events.ts
64
64
  var import_zod = require("zod");
@@ -111,7 +111,7 @@ var envelopeShape = {
111
111
  consent_token: import_zod.z.string(),
112
112
  sdk_version: import_zod.z.string().default(SDK_VERSION),
113
113
  agent_runtime: import_zod.z.string().default("unknown"),
114
- user_id: import_zod.z.string().nullable().default(null),
114
+ principal_id: import_zod.z.string().nullable().default(null),
115
115
  call_id: import_zod.z.string().nullable().default(null),
116
116
  runtime_meta: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null)
117
117
  };
@@ -463,9 +463,9 @@ function capCodePoints(value, max) {
463
463
 
464
464
  // src/identity.ts
465
465
  var VENDOR_HASH_SCHEME = "v1";
466
- var RAW_USER_ID_MAX_LEN = 128;
467
- var USER_ID_MODE_HASHED = "hashed";
468
- var USER_ID_MODE_RAW = "raw";
466
+ var RAW_PRINCIPAL_ID_MAX_LEN = 128;
467
+ var PRINCIPAL_ID_MODE_HASHED = "hashed";
468
+ var PRINCIPAL_ID_MODE_RAW = "raw";
469
469
  var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
470
470
  var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
471
471
  var LONE_SURROGATE = /\p{Surrogate}/u;
@@ -475,7 +475,7 @@ function canonicalize(rawPrincipal) {
475
475
  function pythonStrip(value) {
476
476
  return value.replace(PYTHON_STRIP, "");
477
477
  }
478
- function hashUserId(rawPrincipal, options) {
478
+ function hashPrincipalId(rawPrincipal, options) {
479
479
  const { tenantId, key, issuer = null, scheme } = options;
480
480
  let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
481
481
  if (issuer !== null) {
@@ -488,19 +488,19 @@ function hashUserId(rawPrincipal, options) {
488
488
  function normalizePrincipal(result) {
489
489
  if (result === null || typeof result !== "object") return null;
490
490
  const candidate = result;
491
- if (typeof candidate.userId !== "string") return null;
492
- if (LONE_SURROGATE.test(candidate.userId)) return null;
493
- if (canonicalize(candidate.userId) === "") return null;
491
+ if (typeof candidate.principalId !== "string") return null;
492
+ if (LONE_SURROGATE.test(candidate.principalId)) return null;
493
+ if (canonicalize(candidate.principalId) === "") return null;
494
494
  const issuerRaw = typeof candidate.issuer === "string" && candidate.issuer ? candidate.issuer : null;
495
495
  const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
496
- return { userId: candidate.userId, issuer };
496
+ return { principalId: candidate.principalId, issuer };
497
497
  }
498
- function userIdForPrincipal(principal, options) {
499
- if (options.mode === USER_ID_MODE_RAW) {
500
- return capCodePoints(principal.userId, RAW_USER_ID_MAX_LEN);
498
+ function principalIdFor(principal, options) {
499
+ if (options.mode === PRINCIPAL_ID_MODE_RAW) {
500
+ return capCodePoints(principal.principalId, RAW_PRINCIPAL_ID_MAX_LEN);
501
501
  }
502
502
  if (options.key === null || options.key === void 0) return null;
503
- return hashUserId(principal.userId, {
503
+ return hashPrincipalId(principal.principalId, {
504
504
  tenantId: options.tenantId,
505
505
  key: options.key,
506
506
  issuer: principal.issuer ?? null,
@@ -561,11 +561,13 @@ var USER_GOAL_PARAM_NAME = "user_goal";
561
561
  var EXPECTED_RESULT_PARAM_NAME = "expected_result";
562
562
  var OVERALL_TASK_PARAM_NAME = "overall_task";
563
563
  var INTENT_SOURCE_PARAM = "injected_param";
564
- var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. One sentence: what the user is actually trying to accomplish with this call (their goal, not a restatement of the arguments).";
564
+ 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).";
565
+ var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
566
+ var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
565
567
  var EXPECTED_RESULT_PARAM_DESCRIPTION = "OPTIONAL. One sentence: what a successful result should look like, so a silent/thin failure can be told apart from success.";
566
568
  var OVERALL_TASK_PARAM_DESCRIPTION = "OPTIONAL. Short stable label for the broader task this call serves (e.g. 'prepare campaign approval'). REPEAT the exact same string on every call serving the same task; change it only when the user starts a different task.";
567
- function buildUserGoalParamDescription() {
568
- return USER_GOAL_PARAM_DESCRIPTION;
569
+ function buildUserGoalParamDescription(options = {}) {
570
+ return options.intentParamMode === "required" ? USER_GOAL_PARAM_DESCRIPTION_REQUIRED : USER_GOAL_PARAM_DESCRIPTION;
569
571
  }
570
572
  function buildOverallTaskParamDescription() {
571
573
  return OVERALL_TASK_PARAM_DESCRIPTION;
@@ -698,8 +700,8 @@ function extraHeaders(extra) {
698
700
  return null;
699
701
  }
700
702
 
701
- // src/integrations/mcp/userResolution.ts
702
- function buildUserResolutionContext(extra, toolName, args) {
703
+ // src/integrations/mcp/principalResolution.ts
704
+ function buildPrincipalResolutionContext(extra, toolName, args) {
703
705
  return {
704
706
  headers: extraHeaders(extra),
705
707
  meta: extraMeta(extra),
@@ -708,27 +710,40 @@ function buildUserResolutionContext(extra, toolName, args) {
708
710
  };
709
711
  }
710
712
  function warnIfIdentityCannotResolve(config) {
711
- if (config.resolveUser === void 0) return;
712
- if (config.userIdMode !== USER_ID_MODE_HASHED) return;
713
- if (config.userIdHmacKey !== void 0) return;
713
+ if (config.resolvePrincipal === void 0) return;
714
+ if (config.principalIdMode !== PRINCIPAL_ID_MODE_HASHED) return;
715
+ if (config.principalIdHmacKey !== void 0) return;
714
716
  if (typeof process === "undefined" || typeof process.emitWarning !== "function") return;
717
+ const renamed = process.env?.BATON_USER_ID_HMAC_KEY ? "BATON_USER_ID_HMAC_KEY is set, but it was renamed to BATON_PRINCIPAL_ID_HMAC_KEY in 0.3.5 and is no longer read. " : "";
715
718
  process.emitWarning(
716
- 'baton: resolveUser is configured but no user_id HMAC key is set, so user_id is dropped from every event (events still emit). Set BATON_USER_ID_HMAC_KEY or BatonConfig.userIdHmacKey, or pass userIdMode: "raw" if you intend to emit the subject verbatim.'
719
+ `baton: resolvePrincipal is configured but no principal_id HMAC key is set, so principal_id is dropped from every event (events still emit). ${renamed}Set BATON_PRINCIPAL_ID_HMAC_KEY or BatonConfig.principalIdHmacKey, or pass principalIdMode: "raw" if you intend to emit the subject verbatim.`
717
720
  );
718
721
  }
719
- async function resolveCallUserId(hook, call, options) {
722
+ var warnedPreRenameShape = false;
723
+ function warnIfPreRenameShape(result) {
724
+ const userId = result?.userId;
725
+ if (warnedPreRenameShape || typeof userId !== "string") return;
726
+ warnedPreRenameShape = true;
727
+ warn(
728
+ "baton: resolvePrincipal returned { userId }, which was renamed to { principalId } in 0.3.5, so principal_id is dropped from every event until the hook returns the new key."
729
+ );
730
+ }
731
+ async function resolveCallPrincipalId(hook, call, options) {
720
732
  if (hook === void 0) return null;
721
733
  let result;
722
734
  try {
723
- const context = buildUserResolutionContext(call.extra, call.toolName, call.arguments);
735
+ const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
724
736
  result = await hook(context);
725
737
  } catch {
726
738
  return null;
727
739
  }
728
740
  const principal = normalizePrincipal(result);
729
- if (principal === null) return null;
741
+ if (principal === null) {
742
+ warnIfPreRenameShape(result);
743
+ return null;
744
+ }
730
745
  try {
731
- return userIdForPrincipal(principal, {
746
+ return principalIdFor(principal, {
732
747
  mode: options.mode,
733
748
  tenantId: options.tenantId,
734
749
  key: options.key
@@ -827,13 +842,13 @@ function registerAnnotationTool(server, options) {
827
842
  if (args.signal_type === void 0) {
828
843
  options.tracker?.mark(sessionId);
829
844
  }
830
- const userId = await resolveCallUserId(
831
- options.resolveUser,
845
+ const principalId = await resolveCallPrincipalId(
846
+ options.resolvePrincipal,
832
847
  { extra, toolName: name, arguments: args },
833
848
  {
834
- mode: options.userIdMode,
849
+ mode: options.principalIdMode,
835
850
  tenantId: options.tenantId,
836
- key: options.userIdHmacKey
851
+ key: options.principalIdHmacKey
837
852
  }
838
853
  );
839
854
  await emit(
@@ -846,7 +861,7 @@ function registerAnnotationTool(server, options) {
846
861
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
847
862
  consent_token: options.consentToken,
848
863
  agent_runtime: runtime,
849
- user_id: userId,
864
+ principal_id: principalId,
850
865
  runtime_meta: scrubbedMeta,
851
866
  payload: {
852
867
  // Agent-facing names -> wire keys, as with `overall_task`
@@ -1084,16 +1099,16 @@ function sealKey(dsn) {
1084
1099
 
1085
1100
  // src/integrations/mcp/config.ts
1086
1101
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1087
- var USER_ID_MODES = /* @__PURE__ */ new Set(["hashed", "raw"]);
1102
+ var PRINCIPAL_ID_MODES = /* @__PURE__ */ new Set(["hashed", "raw"]);
1088
1103
  function resolveTenantId(explicit, vendorId) {
1089
1104
  if (explicit) return explicit;
1090
1105
  const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
1091
1106
  if (fromEnv) return fromEnv;
1092
1107
  return vendorId;
1093
1108
  }
1094
- function resolveUserIdHmacKey(explicit) {
1109
+ function resolvePrincipalIdHmacKey(explicit) {
1095
1110
  if (explicit !== void 0) return explicit;
1096
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_USER_ID_HMAC_KEY : void 0;
1111
+ const fromEnv = typeof process !== "undefined" ? process.env?.BATON_PRINCIPAL_ID_HMAC_KEY : void 0;
1097
1112
  return fromEnv ? fromEnv : void 0;
1098
1113
  }
1099
1114
  function resolveBatonConfig(config, serverName) {
@@ -1153,7 +1168,17 @@ function resolveBatonConfig(config, serverName) {
1153
1168
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
1154
1169
  };
1155
1170
  }
1171
+ var RENAMED_KEYS = {
1172
+ resolveUser: "resolvePrincipal",
1173
+ userIdMode: "principalIdMode",
1174
+ userIdHmacKey: "principalIdHmacKey"
1175
+ };
1156
1176
  function validateBatonConfig(config) {
1177
+ for (const [was, now] of Object.entries(RENAMED_KEYS)) {
1178
+ if (was in config) {
1179
+ throw new Error(`BatonConfig.${was} was renamed to ${now} in 0.3.5.`);
1180
+ }
1181
+ }
1157
1182
  if (!config.vendorId) {
1158
1183
  throw new Error(
1159
1184
  "BatonConfig needs a vendorId \u2014 either directly, or via a dsn whose last path segment names the server (see /account)."
@@ -1184,15 +1209,15 @@ function validateBatonConfig(config) {
1184
1209
  `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
1185
1210
  );
1186
1211
  }
1187
- if (config.resolveUser !== void 0 && typeof config.resolveUser !== "function") {
1188
- throw new Error("BatonConfig.resolveUser must be a function.");
1212
+ if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
1213
+ throw new Error("BatonConfig.resolvePrincipal must be a function.");
1189
1214
  }
1190
- if (config.userIdHmacKey !== void 0 && typeof config.userIdHmacKey !== "string" && !(config.userIdHmacKey instanceof Uint8Array)) {
1191
- throw new Error("BatonConfig.userIdHmacKey must be a string or a Uint8Array.");
1215
+ if (config.principalIdHmacKey !== void 0 && typeof config.principalIdHmacKey !== "string" && !(config.principalIdHmacKey instanceof Uint8Array)) {
1216
+ throw new Error("BatonConfig.principalIdHmacKey must be a string or a Uint8Array.");
1192
1217
  }
1193
- if (config.userIdMode !== void 0 && !USER_ID_MODES.has(config.userIdMode)) {
1218
+ if (config.principalIdMode !== void 0 && !PRINCIPAL_ID_MODES.has(config.principalIdMode)) {
1194
1219
  throw new Error(
1195
- `BatonConfig.userIdMode ${JSON.stringify(config.userIdMode)} must be one of ${JSON.stringify([...USER_ID_MODES].sort())}.`
1220
+ `BatonConfig.principalIdMode ${JSON.stringify(config.principalIdMode)} must be one of ${JSON.stringify([...PRINCIPAL_ID_MODES].sort())}.`
1196
1221
  );
1197
1222
  }
1198
1223
  }
@@ -1364,28 +1389,28 @@ function toJsonSchemaCompat(schema, opts) {
1364
1389
  var import_zod3 = require("zod");
1365
1390
  var import_v3 = require("zod/v3");
1366
1391
  var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
1367
- function injectGoalParams(inputSchema) {
1392
+ function injectGoalParams(inputSchema, intentParamMode) {
1368
1393
  const objSchema = normalizeObjectSchema(inputSchema);
1369
1394
  if (!objSchema) return { schema: inputSchema, dispositions: {} };
1370
1395
  const existingShape = getObjectShape(objSchema) ?? {};
1371
1396
  const values = Object.values(existingShape);
1372
1397
  const useV4 = values.length === 0 || isZ4Schema(values[0]);
1373
1398
  const zodImpl = useV4 ? import_zod3.z : import_v3.z;
1374
- const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl);
1399
+ const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
1375
1400
  if (Object.keys(toInject).length === 0)
1376
1401
  return { schema: inputSchema, dispositions };
1377
1402
  const mergedShape = { ...existingShape, ...toInject };
1378
1403
  const newSchema = objectFromShape(mergedShape);
1379
1404
  return { schema: newSchema, dispositions };
1380
1405
  }
1381
- function buildIntentFields(existingShape, zodImpl) {
1406
+ function buildIntentFields(existingShape, zodImpl, intentParamMode) {
1382
1407
  const dispositions = {};
1383
1408
  const toInject = {};
1384
1409
  if (USER_GOAL_PARAM_NAME in existingShape) {
1385
1410
  dispositions[USER_GOAL_PARAM_NAME] = "native";
1386
1411
  } else {
1387
1412
  dispositions[USER_GOAL_PARAM_NAME] = "injected";
1388
- toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription());
1413
+ toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
1389
1414
  }
1390
1415
  for (const [name, buildDescription] of [
1391
1416
  [EXPECTED_RESULT_PARAM_NAME, buildExpectedResultParamDescription],
@@ -1400,17 +1425,35 @@ function buildIntentFields(existingShape, zodImpl) {
1400
1425
  }
1401
1426
  return { dispositions, toInject };
1402
1427
  }
1403
- function injectGoalParamsV2(inputSchema) {
1428
+ function injectGoalParamsV2(inputSchema, intentParamMode) {
1404
1429
  const candidate = inputSchema;
1405
1430
  const shape = candidate?.shape;
1406
1431
  if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
1407
1432
  return { schema: inputSchema, dispositions: {} };
1408
1433
  }
1409
- const { dispositions, toInject } = buildIntentFields(shape, import_zod3.z);
1434
+ const { dispositions, toInject } = buildIntentFields(shape, import_zod3.z, intentParamMode);
1410
1435
  if (Object.keys(toInject).length === 0)
1411
1436
  return { schema: inputSchema, dispositions };
1412
1437
  return { schema: candidate.extend(toInject), dispositions };
1413
1438
  }
1439
+ function advertiseUserGoalRequired(result, isInjected) {
1440
+ const tools = result?.tools;
1441
+ if (!Array.isArray(tools)) return result;
1442
+ let changed = false;
1443
+ const advertised = tools.map((tool) => {
1444
+ const entry = tool;
1445
+ if (typeof entry?.name !== "string" || !isInjected(entry.name)) return tool;
1446
+ const schema = entry.inputSchema;
1447
+ if (!schema || typeof schema !== "object") return tool;
1448
+ const declared = schema.required ?? [];
1449
+ if (!Array.isArray(declared)) return tool;
1450
+ const required = declared;
1451
+ if (required.includes(USER_GOAL_PARAM_NAME)) return tool;
1452
+ changed = true;
1453
+ return { ...entry, inputSchema: { ...schema, required: [...required, USER_GOAL_PARAM_NAME] } };
1454
+ });
1455
+ return changed ? { ...result, tools: advertised } : result;
1456
+ }
1414
1457
  function toolInputJsonSchema(inputSchema) {
1415
1458
  const objSchema = normalizeObjectSchema(inputSchema);
1416
1459
  if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
@@ -1547,10 +1590,10 @@ function batonWrap(nameRef, original, ctx) {
1547
1590
  const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1548
1591
  const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1549
1592
  const callId = (0, import_uuid2.v7)();
1550
- const userId = await resolveCallUserId(
1551
- ctx.resolveUser,
1593
+ const principalId = await resolveCallPrincipalId(
1594
+ ctx.resolvePrincipal,
1552
1595
  { extra, toolName, arguments: params },
1553
- { mode: ctx.userIdMode, tenantId: ctx.tenantId, key: ctx.userIdHmacKey }
1596
+ { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
1554
1597
  );
1555
1598
  const common = {
1556
1599
  tenant_id: ctx.tenantId,
@@ -1563,7 +1606,7 @@ function batonWrap(nameRef, original, ctx) {
1563
1606
  // (`middleware.py` 481/524/562/606). `surface_snapshot` is deliberately
1564
1607
  // NOT among them: it describes the SERVER and is captured outside any
1565
1608
  // call, so there is no caller to name (register D5).
1566
- user_id: userId,
1609
+ principal_id: principalId,
1567
1610
  runtime_meta: scrubbedMeta
1568
1611
  };
1569
1612
  if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
@@ -1687,7 +1730,7 @@ function captureAndInject(name, entry, ctx) {
1687
1730
  if (ctx.intentParamMode === "off") return;
1688
1731
  const isV2 = typeof mutable.executor === "function";
1689
1732
  try {
1690
- const { schema, dispositions } = isV2 ? injectGoalParamsV2(mutable.inputSchema) : injectGoalParams(mutable.inputSchema);
1733
+ const { schema, dispositions } = isV2 ? injectGoalParamsV2(mutable.inputSchema, ctx.intentParamMode) : injectGoalParams(mutable.inputSchema, ctx.intentParamMode);
1691
1734
  if (Object.keys(dispositions).length > 0) {
1692
1735
  mutable.inputSchema = schema;
1693
1736
  ctx.bustSchemaMemo(name);
@@ -1698,6 +1741,46 @@ function captureAndInject(name, entry, ctx) {
1698
1741
  } catch {
1699
1742
  }
1700
1743
  }
1744
+ var TOOLS_LIST_METHOD = "tools/list";
1745
+ var TOOLS_LIST_SEAM = /* @__PURE__ */ Symbol("batonToolsListSeam");
1746
+ function installToolsListSeam(lowLevel, ctx) {
1747
+ const table = lowLevel._requestHandlers;
1748
+ const originalSet = lowLevel.setRequestHandler;
1749
+ if (!(table instanceof Map) || typeof originalSet !== "function") return;
1750
+ const handlers = table;
1751
+ const setRequestHandler = originalSet;
1752
+ const isInjected = (toolName) => ctx.paramRegistry.get(toolName)?.[USER_GOAL_PARAM_NAME] === "injected";
1753
+ const advertise = (result) => {
1754
+ try {
1755
+ return advertiseUserGoalRequired(result, isInjected);
1756
+ } catch (err) {
1757
+ process.stderr.write(
1758
+ `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}
1759
+ `
1760
+ );
1761
+ return result;
1762
+ }
1763
+ };
1764
+ const wrapCurrent = () => {
1765
+ const handler = handlers.get(TOOLS_LIST_METHOD);
1766
+ if (typeof handler !== "function" || handler[TOOLS_LIST_SEAM]) return;
1767
+ const seamed = (...args) => {
1768
+ const out = handler(...args);
1769
+ return isThenable(out) ? out.then(advertise) : advertise(out);
1770
+ };
1771
+ seamed[TOOLS_LIST_SEAM] = true;
1772
+ handlers.set(TOOLS_LIST_METHOD, seamed);
1773
+ };
1774
+ wrapCurrent();
1775
+ lowLevel.setRequestHandler = (...args) => {
1776
+ const registered = setRequestHandler.apply(lowLevel, args);
1777
+ wrapCurrent();
1778
+ return registered;
1779
+ };
1780
+ }
1781
+ function isThenable(value) {
1782
+ return typeof value?.then === "function";
1783
+ }
1701
1784
  function wrapIfNeeded(nameRef, entry, ctx) {
1702
1785
  if (!entry || typeof entry !== "object") return;
1703
1786
  const mutable = entry;
@@ -1788,7 +1871,7 @@ function withBaton(server, supplied = {}) {
1788
1871
  const config = resolveBatonConfig(supplied, serverName);
1789
1872
  const sink = config.sink ?? new StdoutSink();
1790
1873
  const annotationToolName = resolveAnnotationToolName(serverName, config);
1791
- const intentParamMode = config.intentParamMode ?? "optional";
1874
+ const intentParamMode = config.intentParamMode ?? "required";
1792
1875
  const counter = new SessionCounter();
1793
1876
  const fallbackSessionId = `sdk-${(0, import_uuid2.v7)()}`;
1794
1877
  const tenantId = resolveTenantId(config.tenantId, config.vendorId);
@@ -1870,9 +1953,9 @@ function withBaton(server, supplied = {}) {
1870
1953
  annotationToolName,
1871
1954
  intentParamMode,
1872
1955
  paramRegistry: /* @__PURE__ */ new Map(),
1873
- resolveUser: config.resolveUser,
1874
- userIdMode: config.userIdMode ?? "hashed",
1875
- userIdHmacKey: resolveUserIdHmacKey(config.userIdHmacKey),
1956
+ resolvePrincipal: config.resolvePrincipal,
1957
+ principalIdMode: config.principalIdMode ?? "hashed",
1958
+ principalIdHmacKey: resolvePrincipalIdHmacKey(config.principalIdHmacKey),
1876
1959
  vendorToolJsonSchema,
1877
1960
  bustSchemaMemo,
1878
1961
  tracker,
@@ -1885,6 +1968,7 @@ function withBaton(server, supplied = {}) {
1885
1968
  annotationToolName
1886
1969
  });
1887
1970
  internals.server._instructions = instructions;
1971
+ if (intentParamMode === "required") installToolsListSeam(internals.server, ctx);
1888
1972
  const resolvedAnnotationToolName = registerAnnotationTool(server, {
1889
1973
  sink,
1890
1974
  counter: ctx.counter,
@@ -1893,14 +1977,14 @@ function withBaton(server, supplied = {}) {
1893
1977
  vendorDisplayName: config.vendorDisplayName,
1894
1978
  consentToken: ctx.consentToken,
1895
1979
  // Read off `ctx`, never re-resolved from `config`: the two paths must
1896
- // agree on the actor, and `userIdMode`/`userIdHmacKey` each have a
1980
+ // agree on the actor, and `principalIdMode`/`principalIdHmacKey` each have a
1897
1981
  // default and an env fallback that a second resolution could take
1898
1982
  // differently. Required (not optional) on the options type ON PURPOSE —
1899
1983
  // the compiler then refuses a registration that forgets them, which is
1900
1984
  // the mechanical version of "wiring two of four call sites".
1901
- resolveUser: ctx.resolveUser,
1902
- userIdMode: ctx.userIdMode,
1903
- userIdHmacKey: ctx.userIdHmacKey,
1985
+ resolvePrincipal: ctx.resolvePrincipal,
1986
+ principalIdMode: ctx.principalIdMode,
1987
+ principalIdHmacKey: ctx.principalIdHmacKey,
1904
1988
  fallbackSessionId: ctx.fallbackSessionId,
1905
1989
  scrubber: ctx.scrubber,
1906
1990
  // The RESOLVED name, never `config.annotationToolName`: handing over the
@@ -1950,7 +2034,7 @@ function withBaton(server, supplied = {}) {
1950
2034
  ToolCallStartEventSchema,
1951
2035
  ToolCallStartPayloadSchema,
1952
2036
  VENDOR_HASH_SCHEME,
1953
- hashUserId,
2037
+ hashPrincipalId,
1954
2038
  identityScrub,
1955
2039
  safeWrite,
1956
2040
  withBaton