@goodtiming/baton-sdk 0.3.3 → 0.3.5

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.3";
2
+ var SDK_VERSION = "ts-0.3.5";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
@@ -52,7 +52,7 @@ var envelopeShape = {
52
52
  consent_token: z.string(),
53
53
  sdk_version: z.string().default(SDK_VERSION),
54
54
  agent_runtime: z.string().default("unknown"),
55
- user_id: z.string().nullable().default(null),
55
+ principal_id: z.string().nullable().default(null),
56
56
  call_id: z.string().nullable().default(null),
57
57
  runtime_meta: z.record(z.string(), z.unknown()).nullable().default(null)
58
58
  };
@@ -393,19 +393,6 @@ 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);
407
- }
408
-
409
396
  // src/identity.ts
410
397
  import { createHmac } from "crypto";
411
398
 
@@ -417,16 +404,19 @@ function capCodePoints(value, max) {
417
404
 
418
405
  // src/identity.ts
419
406
  var VENDOR_HASH_SCHEME = "v1";
420
- var RAW_USER_ID_MAX_LEN = 128;
421
- var USER_ID_MODE_HASHED = "hashed";
422
- var USER_ID_MODE_RAW = "raw";
407
+ var RAW_PRINCIPAL_ID_MAX_LEN = 128;
408
+ var PRINCIPAL_ID_MODE_HASHED = "hashed";
409
+ var PRINCIPAL_ID_MODE_RAW = "raw";
423
410
  var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
424
411
  var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
425
412
  var LONE_SURROGATE = /\p{Surrogate}/u;
426
413
  function canonicalize(rawPrincipal) {
427
- return rawPrincipal.normalize("NFC").replace(PYTHON_STRIP, "").toLowerCase();
414
+ return pythonStrip(rawPrincipal.normalize("NFC")).toLowerCase();
428
415
  }
429
- function hashUserId(rawPrincipal, options) {
416
+ function pythonStrip(value) {
417
+ return value.replace(PYTHON_STRIP, "");
418
+ }
419
+ function hashPrincipalId(rawPrincipal, options) {
430
420
  const { tenantId, key, issuer = null, scheme } = options;
431
421
  let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
432
422
  if (issuer !== null) {
@@ -439,19 +429,19 @@ function hashUserId(rawPrincipal, options) {
439
429
  function normalizePrincipal(result) {
440
430
  if (result === null || typeof result !== "object") return null;
441
431
  const candidate = result;
442
- if (typeof candidate.userId !== "string") return null;
443
- if (LONE_SURROGATE.test(candidate.userId)) return null;
444
- if (canonicalize(candidate.userId) === "") return null;
432
+ if (typeof candidate.principalId !== "string") return null;
433
+ if (LONE_SURROGATE.test(candidate.principalId)) return null;
434
+ if (canonicalize(candidate.principalId) === "") return null;
445
435
  const issuerRaw = typeof candidate.issuer === "string" && candidate.issuer ? candidate.issuer : null;
446
436
  const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
447
- return { userId: candidate.userId, issuer };
437
+ return { principalId: candidate.principalId, issuer };
448
438
  }
449
- function userIdForPrincipal(principal, options) {
450
- if (options.mode === USER_ID_MODE_RAW) {
451
- return capCodePoints(principal.userId, RAW_USER_ID_MAX_LEN);
439
+ function principalIdFor(principal, options) {
440
+ if (options.mode === PRINCIPAL_ID_MODE_RAW) {
441
+ return capCodePoints(principal.principalId, RAW_PRINCIPAL_ID_MAX_LEN);
452
442
  }
453
443
  if (options.key === null || options.key === void 0) return null;
454
- return hashUserId(principal.userId, {
444
+ return hashPrincipalId(principal.principalId, {
455
445
  tenantId: options.tenantId,
456
446
  key: options.key,
457
447
  issuer: principal.issuer ?? null,
@@ -463,6 +453,161 @@ function userIdForPrincipal(principal, options) {
463
453
  });
464
454
  }
465
455
 
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.
458
+
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).
460
+
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.`;
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.
463
+
464
+ Fields:
465
+ - user_goal: one sentence on what the user is trying to accomplish.
466
+ - expected_result: what a successful result should look like, so a silent/thin failure can be told apart from success.
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.
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.
469
+ - suggested_improvement: reactive-only \u2014 omit on a proactive. A concrete sentence about what product change would have helped.
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.`;
471
+ var CLAUDE_CODE_TRUNCATION_CAP = 2087;
472
+ var INSTRUCTIONS_LENGTH_CAP = 1500;
473
+ var SIGNAL_TYPES = [
474
+ "failure",
475
+ "retry_loop",
476
+ "dead_end",
477
+ "parameter_confusion",
478
+ "slow_performance",
479
+ "abandonment",
480
+ "feature_gap",
481
+ "other"
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
+ }
489
+ function buildServerInstructions(options) {
490
+ const rendered = renderServerInstructions(options);
491
+ if (rendered.length > INSTRUCTIONS_LENGTH_CAP) {
492
+ throw new Error(
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.`
494
+ );
495
+ }
496
+ return rendered;
497
+ }
498
+ function buildAnnotationToolDescription(options) {
499
+ return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
500
+ }
501
+ var USER_GOAL_PARAM_NAME = "user_goal";
502
+ var EXPECTED_RESULT_PARAM_NAME = "expected_result";
503
+ var OVERALL_TASK_PARAM_NAME = "overall_task";
504
+ var INTENT_SOURCE_PARAM = "injected_param";
505
+ 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).";
506
+ 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.";
507
+ 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.";
508
+ function buildUserGoalParamDescription() {
509
+ return USER_GOAL_PARAM_DESCRIPTION;
510
+ }
511
+ function buildOverallTaskParamDescription() {
512
+ return OVERALL_TASK_PARAM_DESCRIPTION;
513
+ }
514
+ function buildExpectedResultParamDescription() {
515
+ return EXPECTED_RESULT_PARAM_DESCRIPTION;
516
+ }
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
+
466
611
  // src/integrations/mcp/mcpTypes.ts
467
612
  function extraMeta(extra) {
468
613
  const direct = extra._meta;
@@ -494,8 +639,8 @@ function extraHeaders(extra) {
494
639
  return null;
495
640
  }
496
641
 
497
- // src/integrations/mcp/userResolution.ts
498
- function buildUserResolutionContext(extra, toolName, args) {
642
+ // src/integrations/mcp/principalResolution.ts
643
+ function buildPrincipalResolutionContext(extra, toolName, args) {
499
644
  return {
500
645
  headers: extraHeaders(extra),
501
646
  meta: extraMeta(extra),
@@ -504,27 +649,40 @@ function buildUserResolutionContext(extra, toolName, args) {
504
649
  };
505
650
  }
506
651
  function warnIfIdentityCannotResolve(config) {
507
- if (config.resolveUser === void 0) return;
508
- if (config.userIdMode !== USER_ID_MODE_HASHED) return;
509
- if (config.userIdHmacKey !== void 0) return;
652
+ if (config.resolvePrincipal === void 0) return;
653
+ if (config.principalIdMode !== PRINCIPAL_ID_MODE_HASHED) return;
654
+ if (config.principalIdHmacKey !== void 0) return;
510
655
  if (typeof process === "undefined" || typeof process.emitWarning !== "function") return;
656
+ 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. " : "";
511
657
  process.emitWarning(
512
- '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
+ `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.`
513
659
  );
514
660
  }
515
- async function resolveCallUserId(hook, call, options) {
661
+ var warnedPreRenameShape = false;
662
+ function warnIfPreRenameShape(result) {
663
+ const userId = result?.userId;
664
+ if (warnedPreRenameShape || typeof userId !== "string") return;
665
+ warnedPreRenameShape = true;
666
+ warn(
667
+ "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."
668
+ );
669
+ }
670
+ async function resolveCallPrincipalId(hook, call, options) {
516
671
  if (hook === void 0) return null;
517
672
  let result;
518
673
  try {
519
- const context = buildUserResolutionContext(call.extra, call.toolName, call.arguments);
674
+ const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
520
675
  result = await hook(context);
521
676
  } catch {
522
677
  return null;
523
678
  }
524
679
  const principal = normalizePrincipal(result);
525
- if (principal === null) return null;
680
+ if (principal === null) {
681
+ warnIfPreRenameShape(result);
682
+ return null;
683
+ }
526
684
  try {
527
- return userIdForPrincipal(principal, {
685
+ return principalIdFor(principal, {
528
686
  mode: options.mode,
529
687
  tenantId: options.tenantId,
530
688
  key: options.key
@@ -534,67 +692,6 @@ async function resolveCallUserId(hook, call, options) {
534
692
  }
535
693
  }
536
694
 
537
- // src/integrations/mcp/llmText.ts
538
- 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.
539
-
540
- 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').
541
-
542
- 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).
543
-
544
- 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.`;
545
- 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).
546
-
547
- Fields:
548
- - user_goal: one sentence on what the user is trying to accomplish.
549
- - expected_result: what a successful result should look like, so a silent/thin failure can be told apart from success.
550
- - 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.
551
- - 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.
552
- - suggested_improvement: reactive-only \u2014 omit on a proactive. A concrete sentence about what product change would have helped.
553
- - 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.`;
554
- var CLAUDE_CODE_TRUNCATION_CAP = 2087;
555
- var INSTRUCTIONS_LENGTH_CAP = 1500;
556
- var SIGNAL_TYPES = [
557
- "failure",
558
- "retry_loop",
559
- "dead_end",
560
- "parameter_confusion",
561
- "slow_performance",
562
- "abandonment",
563
- "feature_gap",
564
- "other"
565
- ];
566
- function buildServerInstructions(options) {
567
- const rendered = SERVER_INSTRUCTIONS_TEMPLATE(
568
- options.vendorDisplayName,
569
- options.annotationToolName
570
- );
571
- if (rendered.length > INSTRUCTIONS_LENGTH_CAP) {
572
- throw new Error(
573
- `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.`
574
- );
575
- }
576
- return rendered;
577
- }
578
- function buildAnnotationToolDescription(options) {
579
- return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
580
- }
581
- var USER_GOAL_PARAM_NAME = "user_goal";
582
- var EXPECTED_RESULT_PARAM_NAME = "expected_result";
583
- var OVERALL_TASK_PARAM_NAME = "overall_task";
584
- var INTENT_SOURCE_PARAM = "injected_param";
585
- 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).";
586
- 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.";
587
- 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.";
588
- function buildUserGoalParamDescription() {
589
- return USER_GOAL_PARAM_DESCRIPTION;
590
- }
591
- function buildOverallTaskParamDescription() {
592
- return OVERALL_TASK_PARAM_DESCRIPTION;
593
- }
594
- function buildExpectedResultParamDescription() {
595
- return EXPECTED_RESULT_PARAM_DESCRIPTION;
596
- }
597
-
598
695
  // src/integrations/mcp/runtimeAdapter.ts
599
696
  var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
600
697
  var CLIENT_NAME_MAX_LEN = 128;
@@ -654,16 +751,6 @@ async function resolveSessionId(fallbackSessionId, extra) {
654
751
  }
655
752
 
656
753
  // src/integrations/mcp/annotation.ts
657
- var TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
658
- function deriveAnnotationToolName(vendorId, override) {
659
- const name = override || `${vendorId}_annotate`;
660
- if (!TOOL_NAME_PATTERN.test(name)) {
661
- throw new Error(
662
- `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).`
663
- );
664
- }
665
- return name;
666
- }
667
754
  function registerAnnotationTool(server, options) {
668
755
  const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
669
756
  const description = buildAnnotationToolDescription({
@@ -694,13 +781,13 @@ function registerAnnotationTool(server, options) {
694
781
  if (args.signal_type === void 0) {
695
782
  options.tracker?.mark(sessionId);
696
783
  }
697
- const userId = await resolveCallUserId(
698
- options.resolveUser,
784
+ const principalId = await resolveCallPrincipalId(
785
+ options.resolvePrincipal,
699
786
  { extra, toolName: name, arguments: args },
700
787
  {
701
- mode: options.userIdMode,
788
+ mode: options.principalIdMode,
702
789
  tenantId: options.tenantId,
703
- key: options.userIdHmacKey
790
+ key: options.principalIdHmacKey
704
791
  }
705
792
  );
706
793
  await emit(
@@ -713,7 +800,7 @@ function registerAnnotationTool(server, options) {
713
800
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
714
801
  consent_token: options.consentToken,
715
802
  agent_runtime: runtime,
716
- user_id: userId,
803
+ principal_id: principalId,
717
804
  runtime_meta: scrubbedMeta,
718
805
  payload: {
719
806
  // Agent-facing names -> wire keys, as with `overall_task`
@@ -760,7 +847,7 @@ function containsKey(value) {
760
847
  return sweep(value) !== value;
761
848
  }
762
849
  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";
763
- function warn(message) {
850
+ function warn2(message) {
764
851
  if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
765
852
  process.emitWarning(message);
766
853
  }
@@ -824,7 +911,7 @@ function selectDsn(explicit, supplied, door) {
824
911
  const ambient = dsnFromEnvironment();
825
912
  if (ambient === void 0) return void 0;
826
913
  if (conflicts.length > 0) {
827
- warn(
914
+ warn2(
828
915
  `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.`
829
916
  );
830
917
  return void 0;
@@ -920,7 +1007,7 @@ function parseDsn(raw) {
920
1007
  );
921
1008
  }
922
1009
  if (key.startsWith(SECRET_PREFIX)) {
923
- warn(
1010
+ warn2(
924
1011
  `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.`
925
1012
  );
926
1013
  }
@@ -951,19 +1038,19 @@ function sealKey(dsn) {
951
1038
 
952
1039
  // src/integrations/mcp/config.ts
953
1040
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
954
- var USER_ID_MODES = /* @__PURE__ */ new Set(["hashed", "raw"]);
1041
+ var PRINCIPAL_ID_MODES = /* @__PURE__ */ new Set(["hashed", "raw"]);
955
1042
  function resolveTenantId(explicit, vendorId) {
956
1043
  if (explicit) return explicit;
957
1044
  const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
958
1045
  if (fromEnv) return fromEnv;
959
1046
  return vendorId;
960
1047
  }
961
- function resolveUserIdHmacKey(explicit) {
1048
+ function resolvePrincipalIdHmacKey(explicit) {
962
1049
  if (explicit !== void 0) return explicit;
963
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_USER_ID_HMAC_KEY : void 0;
1050
+ const fromEnv = typeof process !== "undefined" ? process.env?.BATON_PRINCIPAL_ID_HMAC_KEY : void 0;
964
1051
  return fromEnv ? fromEnv : void 0;
965
1052
  }
966
- function resolveBatonConfig(config) {
1053
+ function resolveBatonConfig(config, serverName) {
967
1054
  const dsnString = selectDsn(
968
1055
  config.dsn,
969
1056
  {
@@ -999,7 +1086,14 @@ function resolveBatonConfig(config) {
999
1086
  // in the server instructions and the annotation tool description, which is
1000
1087
  // the whitelabel obligation the validator cites when it refuses the empty
1001
1088
  // one. ⚠ Python uses `or` here and still has the inconsistency.
1002
- vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,
1089
+ //
1090
+ // Between the explicit value and the segment sits the server's own name,
1091
+ // under the guards in `annotationName.ts`: the segment is an opaque
1092
+ // `srv-<8 hex>`, and it was what agents were told the vendor is called.
1093
+ vendorDisplayName: config.vendorDisplayName ?? displayNameFromServer(serverName, {
1094
+ vendorId: dsn.vendorId,
1095
+ annotationToolName: config.annotationToolName
1096
+ }) ?? dsn.vendorId,
1003
1097
  // `??`, not `||`: an explicit empty string must survive to the validation
1004
1098
  // below and be REFUSED there, rather than be quietly replaced by the
1005
1099
  // default it was deliberately not left as.
@@ -1013,7 +1107,17 @@ function resolveBatonConfig(config) {
1013
1107
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
1014
1108
  };
1015
1109
  }
1110
+ var RENAMED_KEYS = {
1111
+ resolveUser: "resolvePrincipal",
1112
+ userIdMode: "principalIdMode",
1113
+ userIdHmacKey: "principalIdHmacKey"
1114
+ };
1016
1115
  function validateBatonConfig(config) {
1116
+ for (const [was, now] of Object.entries(RENAMED_KEYS)) {
1117
+ if (was in config) {
1118
+ throw new Error(`BatonConfig.${was} was renamed to ${now} in 0.3.5.`);
1119
+ }
1120
+ }
1017
1121
  if (!config.vendorId) {
1018
1122
  throw new Error(
1019
1123
  "BatonConfig needs a vendorId \u2014 either directly, or via a dsn whose last path segment names the server (see /account)."
@@ -1044,15 +1148,15 @@ function validateBatonConfig(config) {
1044
1148
  `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
1045
1149
  );
1046
1150
  }
1047
- if (config.resolveUser !== void 0 && typeof config.resolveUser !== "function") {
1048
- throw new Error("BatonConfig.resolveUser must be a function.");
1151
+ if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
1152
+ throw new Error("BatonConfig.resolvePrincipal must be a function.");
1049
1153
  }
1050
- if (config.userIdHmacKey !== void 0 && typeof config.userIdHmacKey !== "string" && !(config.userIdHmacKey instanceof Uint8Array)) {
1051
- throw new Error("BatonConfig.userIdHmacKey must be a string or a Uint8Array.");
1154
+ if (config.principalIdHmacKey !== void 0 && typeof config.principalIdHmacKey !== "string" && !(config.principalIdHmacKey instanceof Uint8Array)) {
1155
+ throw new Error("BatonConfig.principalIdHmacKey must be a string or a Uint8Array.");
1052
1156
  }
1053
- if (config.userIdMode !== void 0 && !USER_ID_MODES.has(config.userIdMode)) {
1157
+ if (config.principalIdMode !== void 0 && !PRINCIPAL_ID_MODES.has(config.principalIdMode)) {
1054
1158
  throw new Error(
1055
- `BatonConfig.userIdMode ${JSON.stringify(config.userIdMode)} must be one of ${JSON.stringify([...USER_ID_MODES].sort())}.`
1159
+ `BatonConfig.principalIdMode ${JSON.stringify(config.principalIdMode)} must be one of ${JSON.stringify([...PRINCIPAL_ID_MODES].sort())}.`
1056
1160
  );
1057
1161
  }
1058
1162
  }
@@ -1097,8 +1201,9 @@ var BatonHandle = class {
1097
1201
  * when no real per-call session id resolves. Not every event necessarily
1098
1202
  * carries this id; see `withBaton`'s session-resolution order. */
1099
1203
  sessionId;
1100
- /** The resolved annotation tool name (`{vendorId}_annotate` unless
1101
- * overridden via `BatonConfig.annotationToolName`). */
1204
+ /** The resolved annotation tool name: `BatonConfig.annotationToolName` if
1205
+ * set, else derived from the server's own name (`{slug}_annotate`), else
1206
+ * `{vendorId}_annotate`. */
1102
1207
  annotationToolName;
1103
1208
  constructor(options) {
1104
1209
  this.sink = options.sink;
@@ -1406,10 +1511,10 @@ function batonWrap(nameRef, original, ctx) {
1406
1511
  const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1407
1512
  const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1408
1513
  const callId = uuidv72();
1409
- const userId = await resolveCallUserId(
1410
- ctx.resolveUser,
1514
+ const principalId = await resolveCallPrincipalId(
1515
+ ctx.resolvePrincipal,
1411
1516
  { extra, toolName, arguments: params },
1412
- { mode: ctx.userIdMode, tenantId: ctx.tenantId, key: ctx.userIdHmacKey }
1517
+ { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
1413
1518
  );
1414
1519
  const common = {
1415
1520
  tenant_id: ctx.tenantId,
@@ -1422,7 +1527,7 @@ function batonWrap(nameRef, original, ctx) {
1422
1527
  // (`middleware.py` 481/524/562/606). `surface_snapshot` is deliberately
1423
1528
  // NOT among them: it describes the SERVER and is captured outside any
1424
1529
  // call, so there is no caller to name (register D5).
1425
- user_id: userId,
1530
+ principal_id: principalId,
1426
1531
  runtime_meta: scrubbedMeta
1427
1532
  };
1428
1533
  if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
@@ -1639,9 +1744,14 @@ function withBaton(server, supplied = {}) {
1639
1744
  annotationToolName: ""
1640
1745
  });
1641
1746
  }
1642
- const config = resolveBatonConfig(supplied);
1747
+ const internals = server;
1748
+ const serverName = usableServerName(() => ({
1749
+ name: internals.server._serverInfo?.name,
1750
+ className: internals.constructor.name
1751
+ }));
1752
+ const config = resolveBatonConfig(supplied, serverName);
1643
1753
  const sink = config.sink ?? new StdoutSink();
1644
- const annotationToolName = config.annotationToolName || `${config.vendorId}_annotate`;
1754
+ const annotationToolName = resolveAnnotationToolName(serverName, config);
1645
1755
  const intentParamMode = config.intentParamMode ?? "optional";
1646
1756
  const counter = new SessionCounter();
1647
1757
  const fallbackSessionId = `sdk-${uuidv72()}`;
@@ -1686,7 +1796,6 @@ function withBaton(server, supplied = {}) {
1686
1796
  });
1687
1797
  await sink.write(event);
1688
1798
  };
1689
- const internals = server;
1690
1799
  const bustSchemaMemo = (name) => {
1691
1800
  const memo = internals._toolInputSchemaJson;
1692
1801
  if (memo && typeof memo === "object") delete memo[name];
@@ -1725,9 +1834,9 @@ function withBaton(server, supplied = {}) {
1725
1834
  annotationToolName,
1726
1835
  intentParamMode,
1727
1836
  paramRegistry: /* @__PURE__ */ new Map(),
1728
- resolveUser: config.resolveUser,
1729
- userIdMode: config.userIdMode ?? "hashed",
1730
- userIdHmacKey: resolveUserIdHmacKey(config.userIdHmacKey),
1837
+ resolvePrincipal: config.resolvePrincipal,
1838
+ principalIdMode: config.principalIdMode ?? "hashed",
1839
+ principalIdHmacKey: resolvePrincipalIdHmacKey(config.principalIdHmacKey),
1731
1840
  vendorToolJsonSchema,
1732
1841
  bustSchemaMemo,
1733
1842
  tracker,
@@ -1748,17 +1857,20 @@ function withBaton(server, supplied = {}) {
1748
1857
  vendorDisplayName: config.vendorDisplayName,
1749
1858
  consentToken: ctx.consentToken,
1750
1859
  // Read off `ctx`, never re-resolved from `config`: the two paths must
1751
- // agree on the actor, and `userIdMode`/`userIdHmacKey` each have a
1860
+ // agree on the actor, and `principalIdMode`/`principalIdHmacKey` each have a
1752
1861
  // default and an env fallback that a second resolution could take
1753
1862
  // differently. Required (not optional) on the options type ON PURPOSE —
1754
1863
  // the compiler then refuses a registration that forgets them, which is
1755
1864
  // the mechanical version of "wiring two of four call sites".
1756
- resolveUser: ctx.resolveUser,
1757
- userIdMode: ctx.userIdMode,
1758
- userIdHmacKey: ctx.userIdHmacKey,
1865
+ resolvePrincipal: ctx.resolvePrincipal,
1866
+ principalIdMode: ctx.principalIdMode,
1867
+ principalIdHmacKey: ctx.principalIdHmacKey,
1759
1868
  fallbackSessionId: ctx.fallbackSessionId,
1760
1869
  scrubber: ctx.scrubber,
1761
- annotationToolName: config.annotationToolName,
1870
+ // The RESOLVED name, never `config.annotationToolName`: handing over the
1871
+ // raw override and letting the registration re-derive would register
1872
+ // `srv-..._annotate` while the instructions name the server-derived one.
1873
+ annotationToolName,
1762
1874
  tracker
1763
1875
  });
1764
1876
  const existing = internals._registeredTools;
@@ -1801,7 +1913,7 @@ export {
1801
1913
  ToolCallStartEventSchema,
1802
1914
  ToolCallStartPayloadSchema,
1803
1915
  VENDOR_HASH_SCHEME,
1804
- hashUserId,
1916
+ hashPrincipalId,
1805
1917
  identityScrub,
1806
1918
  safeWrite,
1807
1919
  withBaton