@goodtiming/baton-sdk 0.3.2 → 0.3.4

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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-0.3.2";
2
+ var SDK_VERSION = "ts-0.3.4";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
@@ -393,33 +393,78 @@ import { v7 as uuidv72 } from "uuid";
393
393
  // src/integrations/mcp/annotation.ts
394
394
  import { z as z2 } from "zod";
395
395
 
396
- // src/integrations/mcp/emit.ts
397
- async function emit(sink, build) {
398
- let event;
399
- try {
400
- event = build();
401
- } catch (err) {
402
- process.stderr.write(`baton: event construction failed; event dropped: ${String(err)}
403
- `);
404
- return;
405
- }
406
- await safeWrite(sink, event);
396
+ // src/identity.ts
397
+ import { createHmac } from "crypto";
398
+
399
+ // src/_text.ts
400
+ function capCodePoints(value, max) {
401
+ if (value.length <= max) return value;
402
+ return [...value].slice(0, max).join("");
407
403
  }
408
404
 
409
- // src/integrations/mcp/llmText.ts
410
- var SERVER_INSTRUCTIONS_TEMPLATE = (vendorDisplayName, annotationToolName) => `This server is wrapped in the ${vendorDisplayName} support-signal SDK. Use \`${annotationToolName}\` to record what the user is trying to do and how each ${vendorDisplayName} tool call went. See that tool's description for field-level detail.
405
+ // src/identity.ts
406
+ var VENDOR_HASH_SCHEME = "v1";
407
+ var RAW_USER_ID_MAX_LEN = 128;
408
+ var USER_ID_MODE_HASHED = "hashed";
409
+ var USER_ID_MODE_RAW = "raw";
410
+ var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
411
+ var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
412
+ var LONE_SURROGATE = /\p{Surrogate}/u;
413
+ function canonicalize(rawPrincipal) {
414
+ return pythonStrip(rawPrincipal.normalize("NFC")).toLowerCase();
415
+ }
416
+ function pythonStrip(value) {
417
+ return value.replace(PYTHON_STRIP, "");
418
+ }
419
+ function hashUserId(rawPrincipal, options) {
420
+ const { tenantId, key, issuer = null, scheme } = options;
421
+ let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
422
+ if (issuer !== null) {
423
+ message += `\0${canonicalize(issuer)}`;
424
+ }
425
+ const keyBytes = typeof key === "string" ? Buffer.from(key, "utf8") : key;
426
+ const digest = createHmac("sha256", keyBytes).update(message, "utf8").digest("hex");
427
+ return `${scheme}:${digest}`;
428
+ }
429
+ function normalizePrincipal(result) {
430
+ if (result === null || typeof result !== "object") return null;
431
+ const candidate = result;
432
+ if (typeof candidate.userId !== "string") return null;
433
+ if (LONE_SURROGATE.test(candidate.userId)) return null;
434
+ if (canonicalize(candidate.userId) === "") return null;
435
+ const issuerRaw = typeof candidate.issuer === "string" && candidate.issuer ? candidate.issuer : null;
436
+ const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
437
+ return { userId: candidate.userId, issuer };
438
+ }
439
+ function userIdForPrincipal(principal, options) {
440
+ if (options.mode === USER_ID_MODE_RAW) {
441
+ return capCodePoints(principal.userId, RAW_USER_ID_MAX_LEN);
442
+ }
443
+ if (options.key === null || options.key === void 0) return null;
444
+ return hashUserId(principal.userId, {
445
+ tenantId: options.tenantId,
446
+ key: options.key,
447
+ issuer: principal.issuer ?? null,
448
+ // Unconditional: this arm has no attested rung, so every principal it
449
+ // hashes is vendor-ASSERTED. A `scheme` option here would be an argument
450
+ // no caller can vary — configurability for a rung the design says is not
451
+ // coming to this SDK.
452
+ scheme: VENDOR_HASH_SCHEME
453
+ });
454
+ }
411
455
 
412
- BEFORE invoking any ${vendorDisplayName} tool, you MUST call \`${annotationToolName}\` with user_goal (REQUIRED), expected_result (REQUIRED), and overall_task (REQUIRED when the request fits a recognizable broader task, e.g., 'morning meeting prep', 'pre-outreach research').
456
+ // src/integrations/mcp/llmText.ts
457
+ 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.
413
458
 
414
459
  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}\` again with signal_type (REQUIRED) \u2014 one of failure, retry_loop, dead_end, parameter_confusion, slow_performance, abandonment, feature_gap, other \u2014 and suggested_improvement (REQUIRED whenever you can articulate one).
415
460
 
416
461
  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}\` with signal_type='feature_gap' AND still answer the user with your best inference. Filing the annotation does NOT replace answering.`;
417
- var ANNOTATION_TOOL_DESCRIPTION_TEMPLATE = (vendorDisplayName) => `Record structured signal about a ${vendorDisplayName} tool call \u2014 what the user is trying to do, and how it went. Populate proactively before the call (user_goal + expected_result + overall_task) and reactively after if the result was unhelpful (signal_type + suggested_improvement).
462
+ 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.
418
463
 
419
464
  Fields:
420
465
  - user_goal: one sentence on what the user is trying to accomplish.
421
466
  - expected_result: what a successful result should look like, so a silent/thin failure can be told apart from success.
422
- - overall_task: short stable label for the broader task this call serves, e.g., 'morning meeting prep', 'pre-outreach research', 'personal scheduling'. REPEAT the exact same string on every call serving the same task; change it only when the user starts a different task. Skip when the call doesn't fit a recognizable broader task.
467
+ - 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.
423
468
  - signal_type: reactive-only \u2014 omit on a proactive annotation. Set only once a tool call has returned an unhelpful result. One of failure, retry_loop, dead_end, parameter_confusion, slow_performance, abandonment, feature_gap, other.
424
469
  - suggested_improvement: reactive-only \u2014 omit on a proactive. A concrete sentence about what product change would have helped.
425
470
  - context: supplementary info not covered above. Common keys: plan, alternatives_considered, likely_cause, user_impact, error_class, downstream_blocked, confidence_in_intent. For signal_type='feature_gap' also missing_capability_field and requested_capability.`;
@@ -435,11 +480,14 @@ var SIGNAL_TYPES = [
435
480
  "feature_gap",
436
481
  "other"
437
482
  ];
483
+ function renderServerInstructions(options) {
484
+ return SERVER_INSTRUCTIONS_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
485
+ }
486
+ function fitsInstructionsCap(options) {
487
+ return renderServerInstructions(options).length <= INSTRUCTIONS_LENGTH_CAP;
488
+ }
438
489
  function buildServerInstructions(options) {
439
- const rendered = SERVER_INSTRUCTIONS_TEMPLATE(
440
- options.vendorDisplayName,
441
- options.annotationToolName
442
- );
490
+ const rendered = renderServerInstructions(options);
443
491
  if (rendered.length > INSTRUCTIONS_LENGTH_CAP) {
444
492
  throw new Error(
445
493
  `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.`
@@ -467,6 +515,99 @@ function buildExpectedResultParamDescription() {
467
515
  return EXPECTED_RESULT_PARAM_DESCRIPTION;
468
516
  }
469
517
 
518
+ // src/integrations/mcp/annotationName.ts
519
+ var TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
520
+ var SUFFIX = "_annotate";
521
+ var SLUG_CAP = 30;
522
+ var PLACEHOLDER_LITERALS = /* @__PURE__ */ new Set(["fastmcp", "mcp-server"]);
523
+ var RANDOM_SUFFIX = /-[0-9a-f]{4}$/;
524
+ function isLibraryPlaceholder(serverName, className) {
525
+ const stripped = pythonStrip(serverName);
526
+ if (PLACEHOLDER_LITERALS.has(stripped.toLowerCase())) return true;
527
+ const stem = stripped.replace(RANDOM_SUFFIX, "");
528
+ return stem !== stripped && stem === className;
529
+ }
530
+ function warn(message) {
531
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
532
+ process.emitWarning(message);
533
+ }
534
+ }
535
+ function usableServerName(read) {
536
+ let name;
537
+ let className;
538
+ try {
539
+ ({ name, className } = read());
540
+ } catch {
541
+ warn(
542
+ "baton: reading the server name failed; using the DSN's server segment and {vendorId}_annotate instead."
543
+ );
544
+ return void 0;
545
+ }
546
+ if (typeof name !== "string" || pythonStrip(name) === "") return void 0;
547
+ if (isLibraryPlaceholder(name, typeof className === "string" ? className : "")) {
548
+ return void 0;
549
+ }
550
+ return name;
551
+ }
552
+ function slugServerName(serverName) {
553
+ const mapped = pythonStrip(serverName).toLowerCase().replace(/[^a-z0-9-]/gu, "-");
554
+ const collapsed = mapped.replace(/-+/g, "-").replace(/^-+|-+$/g, "");
555
+ return collapsed.slice(0, SLUG_CAP).replace(/^-+|-+$/g, "") || void 0;
556
+ }
557
+ function displayNameFromServer(serverName, tool) {
558
+ if (serverName === void 0) return void 0;
559
+ const fallbackToolName = tool.annotationToolName || `${tool.vendorId}${SUFFIX}`;
560
+ if (!fitsInstructionsCap({ vendorDisplayName: serverName, annotationToolName: fallbackToolName })) {
561
+ warn(
562
+ `baton: the server name (${serverName.length} chars) does not fit the server-instructions budget as the display name; keeping the DSN's server segment. Pass vendorDisplayName to choose a shorter one.`
563
+ );
564
+ return void 0;
565
+ }
566
+ return serverName;
567
+ }
568
+ function annotationToolNameFromServer(serverName, vendorDisplayName) {
569
+ if (serverName === void 0) return void 0;
570
+ const slug = slugServerName(serverName);
571
+ if (slug === void 0) return void 0;
572
+ const candidate = `${slug}${SUFFIX}`;
573
+ if (!TOOL_NAME_PATTERN.test(candidate)) return void 0;
574
+ if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: candidate })) {
575
+ warn(
576
+ `baton: the server-derived annotation tool name ${JSON.stringify(candidate)} does not fit the server-instructions budget beside the display name (${vendorDisplayName.length} chars); keeping {vendorId}_annotate. A shorter display name gets the readable one.`
577
+ );
578
+ return void 0;
579
+ }
580
+ return candidate;
581
+ }
582
+ function deriveAnnotationToolName(vendorId, override) {
583
+ const name = override || `${vendorId}${SUFFIX}`;
584
+ if (!TOOL_NAME_PATTERN.test(name)) {
585
+ throw new Error(
586
+ `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).`
587
+ );
588
+ }
589
+ return name;
590
+ }
591
+ function resolveAnnotationToolName(serverName, config) {
592
+ return deriveAnnotationToolName(
593
+ config.vendorId,
594
+ config.annotationToolName || annotationToolNameFromServer(serverName, config.vendorDisplayName)
595
+ );
596
+ }
597
+
598
+ // src/integrations/mcp/emit.ts
599
+ async function emit(sink, build) {
600
+ let event;
601
+ try {
602
+ event = build();
603
+ } catch (err) {
604
+ process.stderr.write(`baton: event construction failed; event dropped: ${String(err)}
605
+ `);
606
+ return;
607
+ }
608
+ await safeWrite(sink, event);
609
+ }
610
+
470
611
  // src/integrations/mcp/mcpTypes.ts
471
612
  function extraMeta(extra) {
472
613
  const direct = extra._meta;
@@ -478,6 +619,65 @@ function extraEnvelope(extra) {
478
619
  const envelope = extra.mcpReq?.envelope;
479
620
  return envelope ?? null;
480
621
  }
622
+ function extraHeaders(extra) {
623
+ const fromV2 = extra.http?.req?.headers;
624
+ if (fromV2 && typeof fromV2.get === "function") return fromV2;
625
+ const fromV1 = extra.requestInfo?.headers;
626
+ if (fromV1 && typeof fromV1 === "object") {
627
+ const headers = new Headers();
628
+ for (const [name, value] of Object.entries(fromV1)) {
629
+ for (const item of Array.isArray(value) ? value : [value]) {
630
+ if (typeof item !== "string") continue;
631
+ try {
632
+ headers.append(name, item);
633
+ } catch {
634
+ }
635
+ }
636
+ }
637
+ return headers;
638
+ }
639
+ return null;
640
+ }
641
+
642
+ // src/integrations/mcp/userResolution.ts
643
+ function buildUserResolutionContext(extra, toolName, args) {
644
+ return {
645
+ headers: extraHeaders(extra),
646
+ meta: extraMeta(extra),
647
+ toolName,
648
+ arguments: args
649
+ };
650
+ }
651
+ function warnIfIdentityCannotResolve(config) {
652
+ if (config.resolveUser === void 0) return;
653
+ if (config.userIdMode !== USER_ID_MODE_HASHED) return;
654
+ if (config.userIdHmacKey !== void 0) return;
655
+ if (typeof process === "undefined" || typeof process.emitWarning !== "function") return;
656
+ process.emitWarning(
657
+ '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.'
658
+ );
659
+ }
660
+ async function resolveCallUserId(hook, call, options) {
661
+ if (hook === void 0) return null;
662
+ let result;
663
+ try {
664
+ const context = buildUserResolutionContext(call.extra, call.toolName, call.arguments);
665
+ result = await hook(context);
666
+ } catch {
667
+ return null;
668
+ }
669
+ const principal = normalizePrincipal(result);
670
+ if (principal === null) return null;
671
+ try {
672
+ return userIdForPrincipal(principal, {
673
+ mode: options.mode,
674
+ tenantId: options.tenantId,
675
+ key: options.key
676
+ });
677
+ } catch {
678
+ return null;
679
+ }
680
+ }
481
681
 
482
682
  // src/integrations/mcp/runtimeAdapter.ts
483
683
  var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
@@ -492,7 +692,7 @@ function clean(name, scrubber) {
492
692
  cleaned = scrubbed;
493
693
  }
494
694
  if (!cleaned) return null;
495
- return [...cleaned].slice(0, CLIENT_NAME_MAX_LEN).join("");
695
+ return capCodePoints(cleaned, CLIENT_NAME_MAX_LEN);
496
696
  }
497
697
  function declaredOnRequest(meta, envelope) {
498
698
  for (const source of [envelope, meta]) {
@@ -538,16 +738,6 @@ async function resolveSessionId(fallbackSessionId, extra) {
538
738
  }
539
739
 
540
740
  // src/integrations/mcp/annotation.ts
541
- var TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
542
- function deriveAnnotationToolName(vendorId, override) {
543
- const name = override || `${vendorId}_annotate`;
544
- if (!TOOL_NAME_PATTERN.test(name)) {
545
- throw new Error(
546
- `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).`
547
- );
548
- }
549
- return name;
550
- }
551
741
  function registerAnnotationTool(server, options) {
552
742
  const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
553
743
  const description = buildAnnotationToolDescription({
@@ -578,6 +768,15 @@ function registerAnnotationTool(server, options) {
578
768
  if (args.signal_type === void 0) {
579
769
  options.tracker?.mark(sessionId);
580
770
  }
771
+ const userId = await resolveCallUserId(
772
+ options.resolveUser,
773
+ { extra, toolName: name, arguments: args },
774
+ {
775
+ mode: options.userIdMode,
776
+ tenantId: options.tenantId,
777
+ key: options.userIdHmacKey
778
+ }
779
+ );
581
780
  await emit(
582
781
  options.sink,
583
782
  () => AnnotationEventSchema.parse({
@@ -588,6 +787,7 @@ function registerAnnotationTool(server, options) {
588
787
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
589
788
  consent_token: options.consentToken,
590
789
  agent_runtime: runtime,
790
+ user_id: userId,
591
791
  runtime_meta: scrubbedMeta,
592
792
  payload: {
593
793
  // Agent-facing names -> wire keys, as with `overall_task`
@@ -634,7 +834,7 @@ function containsKey(value) {
634
834
  return sweep(value) !== value;
635
835
  }
636
836
  var BARE_KEY_HINT = "this looks like a bare key, not a DSN \u2014 copy the full value from /account, which starts with https:// and ends with your server's name";
637
- function warn(message) {
837
+ function warn2(message) {
638
838
  if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
639
839
  process.emitWarning(message);
640
840
  }
@@ -698,7 +898,7 @@ function selectDsn(explicit, supplied, door) {
698
898
  const ambient = dsnFromEnvironment();
699
899
  if (ambient === void 0) return void 0;
700
900
  if (conflicts.length > 0) {
701
- warn(
901
+ warn2(
702
902
  `baton: BATON_DSN is set, but this ${door} supplies ${conflicts.join(", ")} directly, so BATON_DSN is being IGNORED and these events are NOT going to the collector it names. Remove the explicit value to use it, or unset BATON_DSN if it was meant for a different server.`
703
903
  );
704
904
  return void 0;
@@ -794,7 +994,7 @@ function parseDsn(raw) {
794
994
  );
795
995
  }
796
996
  if (key.startsWith(SECRET_PREFIX)) {
797
- warn(
997
+ warn2(
798
998
  `baton: this DSN carries a ${SECRET_PREFIX} key (a workspace SECRET) where a ${PUBLISHABLE_PREFIX} key belongs. It will work. But if this server ships to anyone else, that key reads and writes everything the workspace holds \u2014 mint a publishable key at /account instead.`
799
999
  );
800
1000
  }
@@ -825,13 +1025,19 @@ function sealKey(dsn) {
825
1025
 
826
1026
  // src/integrations/mcp/config.ts
827
1027
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1028
+ var USER_ID_MODES = /* @__PURE__ */ new Set(["hashed", "raw"]);
828
1029
  function resolveTenantId(explicit, vendorId) {
829
1030
  if (explicit) return explicit;
830
1031
  const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
831
1032
  if (fromEnv) return fromEnv;
832
1033
  return vendorId;
833
1034
  }
834
- function resolveBatonConfig(config) {
1035
+ function resolveUserIdHmacKey(explicit) {
1036
+ if (explicit !== void 0) return explicit;
1037
+ const fromEnv = typeof process !== "undefined" ? process.env?.BATON_USER_ID_HMAC_KEY : void 0;
1038
+ return fromEnv ? fromEnv : void 0;
1039
+ }
1040
+ function resolveBatonConfig(config, serverName) {
835
1041
  const dsnString = selectDsn(
836
1042
  config.dsn,
837
1043
  {
@@ -867,7 +1073,14 @@ function resolveBatonConfig(config) {
867
1073
  // in the server instructions and the annotation tool description, which is
868
1074
  // the whitelabel obligation the validator cites when it refuses the empty
869
1075
  // one. ⚠ Python uses `or` here and still has the inconsistency.
870
- vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,
1076
+ //
1077
+ // Between the explicit value and the segment sits the server's own name,
1078
+ // under the guards in `annotationName.ts`: the segment is an opaque
1079
+ // `srv-<8 hex>`, and it was what agents were told the vendor is called.
1080
+ vendorDisplayName: config.vendorDisplayName ?? displayNameFromServer(serverName, {
1081
+ vendorId: dsn.vendorId,
1082
+ annotationToolName: config.annotationToolName
1083
+ }) ?? dsn.vendorId,
871
1084
  // `??`, not `||`: an explicit empty string must survive to the validation
872
1085
  // below and be REFUSED there, rather than be quietly replaced by the
873
1086
  // default it was deliberately not left as.
@@ -912,6 +1125,17 @@ function validateBatonConfig(config) {
912
1125
  `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
913
1126
  );
914
1127
  }
1128
+ if (config.resolveUser !== void 0 && typeof config.resolveUser !== "function") {
1129
+ throw new Error("BatonConfig.resolveUser must be a function.");
1130
+ }
1131
+ if (config.userIdHmacKey !== void 0 && typeof config.userIdHmacKey !== "string" && !(config.userIdHmacKey instanceof Uint8Array)) {
1132
+ throw new Error("BatonConfig.userIdHmacKey must be a string or a Uint8Array.");
1133
+ }
1134
+ if (config.userIdMode !== void 0 && !USER_ID_MODES.has(config.userIdMode)) {
1135
+ throw new Error(
1136
+ `BatonConfig.userIdMode ${JSON.stringify(config.userIdMode)} must be one of ${JSON.stringify([...USER_ID_MODES].sort())}.`
1137
+ );
1138
+ }
915
1139
  }
916
1140
 
917
1141
  // src/optout.ts
@@ -954,8 +1178,9 @@ var BatonHandle = class {
954
1178
  * when no real per-call session id resolves. Not every event necessarily
955
1179
  * carries this id; see `withBaton`'s session-resolution order. */
956
1180
  sessionId;
957
- /** The resolved annotation tool name (`{vendorId}_annotate` unless
958
- * overridden via `BatonConfig.annotationToolName`). */
1181
+ /** The resolved annotation tool name: `BatonConfig.annotationToolName` if
1182
+ * set, else derived from the server's own name (`{slug}_annotate`), else
1183
+ * `{vendorId}_annotate`. */
959
1184
  annotationToolName;
960
1185
  constructor(options) {
961
1186
  this.sink = options.sink;
@@ -1263,12 +1488,23 @@ function batonWrap(nameRef, original, ctx) {
1263
1488
  const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1264
1489
  const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1265
1490
  const callId = uuidv72();
1491
+ const userId = await resolveCallUserId(
1492
+ ctx.resolveUser,
1493
+ { extra, toolName, arguments: params },
1494
+ { mode: ctx.userIdMode, tenantId: ctx.tenantId, key: ctx.userIdHmacKey }
1495
+ );
1266
1496
  const common = {
1267
1497
  tenant_id: ctx.tenantId,
1268
1498
  vendor_id: ctx.vendorId,
1269
1499
  session_id: sessionId,
1270
1500
  consent_token: ctx.consentToken,
1271
1501
  agent_runtime: runtime,
1502
+ // The four `...common` sites below are the tool-call legs and the
1503
+ // proactive annotation — the same four Python stamps
1504
+ // (`middleware.py` 481/524/562/606). `surface_snapshot` is deliberately
1505
+ // NOT among them: it describes the SERVER and is captured outside any
1506
+ // call, so there is no caller to name (register D5).
1507
+ user_id: userId,
1272
1508
  runtime_meta: scrubbedMeta
1273
1509
  };
1274
1510
  if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
@@ -1485,9 +1721,14 @@ function withBaton(server, supplied = {}) {
1485
1721
  annotationToolName: ""
1486
1722
  });
1487
1723
  }
1488
- const config = resolveBatonConfig(supplied);
1724
+ const internals = server;
1725
+ const serverName = usableServerName(() => ({
1726
+ name: internals.server._serverInfo?.name,
1727
+ className: internals.constructor.name
1728
+ }));
1729
+ const config = resolveBatonConfig(supplied, serverName);
1489
1730
  const sink = config.sink ?? new StdoutSink();
1490
- const annotationToolName = config.annotationToolName || `${config.vendorId}_annotate`;
1731
+ const annotationToolName = resolveAnnotationToolName(serverName, config);
1491
1732
  const intentParamMode = config.intentParamMode ?? "optional";
1492
1733
  const counter = new SessionCounter();
1493
1734
  const fallbackSessionId = `sdk-${uuidv72()}`;
@@ -1532,7 +1773,6 @@ function withBaton(server, supplied = {}) {
1532
1773
  });
1533
1774
  await sink.write(event);
1534
1775
  };
1535
- const internals = server;
1536
1776
  const bustSchemaMemo = (name) => {
1537
1777
  const memo = internals._toolInputSchemaJson;
1538
1778
  if (memo && typeof memo === "object") delete memo[name];
@@ -1571,12 +1811,16 @@ function withBaton(server, supplied = {}) {
1571
1811
  annotationToolName,
1572
1812
  intentParamMode,
1573
1813
  paramRegistry: /* @__PURE__ */ new Map(),
1814
+ resolveUser: config.resolveUser,
1815
+ userIdMode: config.userIdMode ?? "hashed",
1816
+ userIdHmacKey: resolveUserIdHmacKey(config.userIdHmacKey),
1574
1817
  vendorToolJsonSchema,
1575
1818
  bustSchemaMemo,
1576
1819
  tracker,
1577
1820
  surfaceState,
1578
1821
  emitSurface
1579
1822
  };
1823
+ warnIfIdentityCannotResolve(ctx);
1580
1824
  const instructions = buildServerInstructions({
1581
1825
  vendorDisplayName: config.vendorDisplayName,
1582
1826
  annotationToolName
@@ -1589,9 +1833,21 @@ function withBaton(server, supplied = {}) {
1589
1833
  vendorId: ctx.vendorId,
1590
1834
  vendorDisplayName: config.vendorDisplayName,
1591
1835
  consentToken: ctx.consentToken,
1836
+ // Read off `ctx`, never re-resolved from `config`: the two paths must
1837
+ // agree on the actor, and `userIdMode`/`userIdHmacKey` each have a
1838
+ // default and an env fallback that a second resolution could take
1839
+ // differently. Required (not optional) on the options type ON PURPOSE —
1840
+ // the compiler then refuses a registration that forgets them, which is
1841
+ // the mechanical version of "wiring two of four call sites".
1842
+ resolveUser: ctx.resolveUser,
1843
+ userIdMode: ctx.userIdMode,
1844
+ userIdHmacKey: ctx.userIdHmacKey,
1592
1845
  fallbackSessionId: ctx.fallbackSessionId,
1593
1846
  scrubber: ctx.scrubber,
1594
- annotationToolName: config.annotationToolName,
1847
+ // The RESOLVED name, never `config.annotationToolName`: handing over the
1848
+ // raw override and letting the registration re-derive would register
1849
+ // `srv-..._annotate` while the instructions name the server-derived one.
1850
+ annotationToolName,
1595
1851
  tracker
1596
1852
  });
1597
1853
  const existing = internals._registeredTools;
@@ -1633,6 +1889,8 @@ export {
1633
1889
  ToolCallErrorPayloadSchema,
1634
1890
  ToolCallStartEventSchema,
1635
1891
  ToolCallStartPayloadSchema,
1892
+ VENDOR_HASH_SCHEME,
1893
+ hashUserId,
1636
1894
  identityScrub,
1637
1895
  safeWrite,
1638
1896
  withBaton