@goodtiming/baton-sdk 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -49,6 +49,8 @@ __export(index_exports, {
49
49
  ToolCallErrorPayloadSchema: () => ToolCallErrorPayloadSchema,
50
50
  ToolCallStartEventSchema: () => ToolCallStartEventSchema,
51
51
  ToolCallStartPayloadSchema: () => ToolCallStartPayloadSchema,
52
+ VENDOR_HASH_SCHEME: () => VENDOR_HASH_SCHEME,
53
+ hashUserId: () => hashUserId,
52
54
  identityScrub: () => identityScrub,
53
55
  safeWrite: () => safeWrite,
54
56
  withBaton: () => withBaton
@@ -56,7 +58,7 @@ __export(index_exports, {
56
58
  module.exports = __toCommonJS(index_exports);
57
59
 
58
60
  // src/version.ts
59
- var SDK_VERSION = "ts-0.3.1";
61
+ var SDK_VERSION = "ts-0.3.3";
60
62
 
61
63
  // src/events.ts
62
64
  var import_zod = require("zod");
@@ -110,6 +112,7 @@ var envelopeShape = {
110
112
  sdk_version: import_zod.z.string().default(SDK_VERSION),
111
113
  agent_runtime: import_zod.z.string().default("unknown"),
112
114
  user_id: import_zod.z.string().nullable().default(null),
115
+ call_id: import_zod.z.string().nullable().default(null),
113
116
  runtime_meta: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null)
114
117
  };
115
118
  var EventTypeSchema = import_zod.z.enum([
@@ -462,6 +465,134 @@ async function emit(sink, build) {
462
465
  await safeWrite(sink, event);
463
466
  }
464
467
 
468
+ // src/identity.ts
469
+ var import_node_crypto = require("crypto");
470
+
471
+ // src/_text.ts
472
+ function capCodePoints(value, max) {
473
+ if (value.length <= max) return value;
474
+ return [...value].slice(0, max).join("");
475
+ }
476
+
477
+ // src/identity.ts
478
+ var VENDOR_HASH_SCHEME = "v1";
479
+ var RAW_USER_ID_MAX_LEN = 128;
480
+ var USER_ID_MODE_HASHED = "hashed";
481
+ var USER_ID_MODE_RAW = "raw";
482
+ var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
483
+ var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
484
+ var LONE_SURROGATE = /\p{Surrogate}/u;
485
+ function canonicalize(rawPrincipal) {
486
+ return rawPrincipal.normalize("NFC").replace(PYTHON_STRIP, "").toLowerCase();
487
+ }
488
+ function hashUserId(rawPrincipal, options) {
489
+ const { tenantId, key, issuer = null, scheme } = options;
490
+ let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
491
+ if (issuer !== null) {
492
+ message += `\0${canonicalize(issuer)}`;
493
+ }
494
+ const keyBytes = typeof key === "string" ? Buffer.from(key, "utf8") : key;
495
+ const digest = (0, import_node_crypto.createHmac)("sha256", keyBytes).update(message, "utf8").digest("hex");
496
+ return `${scheme}:${digest}`;
497
+ }
498
+ function normalizePrincipal(result) {
499
+ if (result === null || typeof result !== "object") return null;
500
+ const candidate = result;
501
+ if (typeof candidate.userId !== "string") return null;
502
+ if (LONE_SURROGATE.test(candidate.userId)) return null;
503
+ if (canonicalize(candidate.userId) === "") return null;
504
+ const issuerRaw = typeof candidate.issuer === "string" && candidate.issuer ? candidate.issuer : null;
505
+ const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
506
+ return { userId: candidate.userId, issuer };
507
+ }
508
+ function userIdForPrincipal(principal, options) {
509
+ if (options.mode === USER_ID_MODE_RAW) {
510
+ return capCodePoints(principal.userId, RAW_USER_ID_MAX_LEN);
511
+ }
512
+ if (options.key === null || options.key === void 0) return null;
513
+ return hashUserId(principal.userId, {
514
+ tenantId: options.tenantId,
515
+ key: options.key,
516
+ issuer: principal.issuer ?? null,
517
+ // Unconditional: this arm has no attested rung, so every principal it
518
+ // hashes is vendor-ASSERTED. A `scheme` option here would be an argument
519
+ // no caller can vary — configurability for a rung the design says is not
520
+ // coming to this SDK.
521
+ scheme: VENDOR_HASH_SCHEME
522
+ });
523
+ }
524
+
525
+ // src/integrations/mcp/mcpTypes.ts
526
+ function extraMeta(extra) {
527
+ const direct = extra._meta;
528
+ if (direct) return direct;
529
+ const nested = extra.mcpReq?._meta;
530
+ return nested ?? null;
531
+ }
532
+ function extraEnvelope(extra) {
533
+ const envelope = extra.mcpReq?.envelope;
534
+ return envelope ?? null;
535
+ }
536
+ function extraHeaders(extra) {
537
+ const fromV2 = extra.http?.req?.headers;
538
+ if (fromV2 && typeof fromV2.get === "function") return fromV2;
539
+ const fromV1 = extra.requestInfo?.headers;
540
+ if (fromV1 && typeof fromV1 === "object") {
541
+ const headers = new Headers();
542
+ for (const [name, value] of Object.entries(fromV1)) {
543
+ for (const item of Array.isArray(value) ? value : [value]) {
544
+ if (typeof item !== "string") continue;
545
+ try {
546
+ headers.append(name, item);
547
+ } catch {
548
+ }
549
+ }
550
+ }
551
+ return headers;
552
+ }
553
+ return null;
554
+ }
555
+
556
+ // src/integrations/mcp/userResolution.ts
557
+ function buildUserResolutionContext(extra, toolName, args) {
558
+ return {
559
+ headers: extraHeaders(extra),
560
+ meta: extraMeta(extra),
561
+ toolName,
562
+ arguments: args
563
+ };
564
+ }
565
+ function warnIfIdentityCannotResolve(config) {
566
+ if (config.resolveUser === void 0) return;
567
+ if (config.userIdMode !== USER_ID_MODE_HASHED) return;
568
+ if (config.userIdHmacKey !== void 0) return;
569
+ if (typeof process === "undefined" || typeof process.emitWarning !== "function") return;
570
+ process.emitWarning(
571
+ '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.'
572
+ );
573
+ }
574
+ async function resolveCallUserId(hook, call, options) {
575
+ if (hook === void 0) return null;
576
+ let result;
577
+ try {
578
+ const context = buildUserResolutionContext(call.extra, call.toolName, call.arguments);
579
+ result = await hook(context);
580
+ } catch {
581
+ return null;
582
+ }
583
+ const principal = normalizePrincipal(result);
584
+ if (principal === null) return null;
585
+ try {
586
+ return userIdForPrincipal(principal, {
587
+ mode: options.mode,
588
+ tenantId: options.tenantId,
589
+ key: options.key
590
+ });
591
+ } catch {
592
+ return null;
593
+ }
594
+ }
595
+
465
596
  // src/integrations/mcp/llmText.ts
466
597
  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.
467
598
 
@@ -523,32 +654,60 @@ function buildExpectedResultParamDescription() {
523
654
  return EXPECTED_RESULT_PARAM_DESCRIPTION;
524
655
  }
525
656
 
526
- // src/integrations/mcp/mcpTypes.ts
527
- function extraMeta(extra) {
528
- const direct = extra._meta;
529
- if (direct) return direct;
530
- const nested = extra.mcpReq?._meta;
531
- return nested ?? null;
532
- }
533
-
534
657
  // src/integrations/mcp/runtimeAdapter.ts
535
- function detectAgentRuntime(meta) {
536
- if (!meta) return null;
537
- for (const key of Object.keys(meta)) {
538
- if (key.startsWith("claudecode/")) return "claude-code";
658
+ var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
659
+ var CLIENT_NAME_MAX_LEN = 128;
660
+ var UNKNOWN_AGENT_RUNTIME = "unknown";
661
+ function clean(name, scrubber) {
662
+ if (typeof name !== "string" || !name) return null;
663
+ let cleaned = name;
664
+ if (scrubber) {
665
+ const scrubbed = scrubber(cleaned);
666
+ if (typeof scrubbed !== "string") return null;
667
+ cleaned = scrubbed;
668
+ }
669
+ if (!cleaned) return null;
670
+ return capCodePoints(cleaned, CLIENT_NAME_MAX_LEN);
671
+ }
672
+ function declaredOnRequest(meta, envelope) {
673
+ for (const source of [envelope, meta]) {
674
+ if (!source) continue;
675
+ const info = source[CLIENT_INFO_META_KEY];
676
+ if (info && typeof info === "object") {
677
+ const name = info.name;
678
+ if (name !== void 0) return name;
679
+ }
680
+ }
681
+ return void 0;
682
+ }
683
+ function declaredOnConnection(options) {
684
+ try {
685
+ const server = options.server;
686
+ if (!server) return void 0;
687
+ const inner = server.server;
688
+ const holder = inner ?? server;
689
+ if (typeof holder.getClientVersion !== "function") return void 0;
690
+ return holder.getClientVersion()?.name;
691
+ } catch {
692
+ return void 0;
693
+ }
694
+ }
695
+ function detectAgentRuntime(meta, options = {}) {
696
+ const { envelope, scrubber } = options;
697
+ const onRequest = clean(declaredOnRequest(meta, envelope), scrubber);
698
+ if (onRequest !== null) return onRequest;
699
+ const onConnection = clean(declaredOnConnection(options), scrubber);
700
+ if (onConnection !== null) return onConnection;
701
+ if (meta) {
702
+ for (const key of Object.keys(meta)) {
703
+ if (key.startsWith("claudecode/")) return "claude-code";
704
+ }
539
705
  }
540
706
  return null;
541
707
  }
542
708
 
543
709
  // src/integrations/mcp/sessionResolution.ts
544
- async function resolveSessionId(hook, fallbackSessionId, extra, meta, toolName, args) {
545
- if (hook) {
546
- try {
547
- const hookResult = await hook({ meta, toolName, arguments: args });
548
- if (typeof hookResult === "string" && hookResult) return hookResult;
549
- } catch {
550
- }
551
- }
710
+ async function resolveSessionId(fallbackSessionId, extra) {
552
711
  if (typeof extra.sessionId === "string" && extra.sessionId) return extra.sessionId;
553
712
  return fallbackSessionId;
554
713
  }
@@ -584,19 +743,25 @@ function registerAnnotationTool(server, options) {
584
743
  },
585
744
  async (args, extra) => {
586
745
  const meta = extraMeta(extra);
587
- const runtime = detectAgentRuntime(meta) ?? options.defaultAgentRuntime;
746
+ const runtime = detectAgentRuntime(meta, {
747
+ envelope: extraEnvelope(extra),
748
+ server,
749
+ scrubber: options.scrubber
750
+ }) ?? UNKNOWN_AGENT_RUNTIME;
588
751
  const scrubbedMeta = meta ? options.scrubber(meta) : null;
589
- const sessionId = await resolveSessionId(
590
- options.resolveSessionId,
591
- options.fallbackSessionId,
592
- extra,
593
- meta,
594
- name,
595
- args
596
- );
752
+ const sessionId = await resolveSessionId(options.fallbackSessionId, extra);
597
753
  if (args.signal_type === void 0) {
598
754
  options.tracker?.mark(sessionId);
599
755
  }
756
+ const userId = await resolveCallUserId(
757
+ options.resolveUser,
758
+ { extra, toolName: name, arguments: args },
759
+ {
760
+ mode: options.userIdMode,
761
+ tenantId: options.tenantId,
762
+ key: options.userIdHmacKey
763
+ }
764
+ );
600
765
  await emit(
601
766
  options.sink,
602
767
  () => AnnotationEventSchema.parse({
@@ -607,6 +772,7 @@ function registerAnnotationTool(server, options) {
607
772
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
608
773
  consent_token: options.consentToken,
609
774
  agent_runtime: runtime,
775
+ user_id: userId,
610
776
  runtime_meta: scrubbedMeta,
611
777
  payload: {
612
778
  // Agent-facing names -> wire keys, as with `overall_task`
@@ -640,7 +806,7 @@ function registerAnnotationTool(server, options) {
640
806
 
641
807
  // src/dsn.ts
642
808
  var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
643
- var WORKSPACE_PATTERN = /^ten_[0-9a-fA-F]{32}$/;
809
+ var WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;
644
810
  var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
645
811
  var NOT_IN_A_KEY = /[\x00\n\r]/;
646
812
  var PUBLISHABLE_PREFIX = "baton_pk_";
@@ -681,7 +847,11 @@ function splitDsn(raw) {
681
847
  function splitKeyFromAuthority(netloc) {
682
848
  const index = netloc.lastIndexOf("@");
683
849
  if (index === -1) return { key: "", at: false, authority: netloc };
684
- return { key: netloc.slice(0, index), at: true, authority: netloc.slice(index + 1) };
850
+ return {
851
+ key: netloc.slice(0, index),
852
+ at: true,
853
+ authority: netloc.slice(index + 1)
854
+ };
685
855
  }
686
856
  function redact(raw) {
687
857
  const parts = splitDsn(raw);
@@ -761,6 +931,11 @@ function parseDsn(raw) {
761
931
  if (!authority) {
762
932
  fail(`dsn ${safe} has no host`);
763
933
  }
934
+ if (containsKey(authority)) {
935
+ fail(
936
+ `dsn ${safe} has the KEY where the host belongs. The order is key, @, host \u2014 check whether the two are the wrong way round: https://baton_pk_...@host/ten_.../<server>`
937
+ );
938
+ }
764
939
  if (NOT_IN_A_HOST.test(authority)) {
765
940
  fail(
766
941
  `dsn ${safe} has whitespace, a control character or a backslash inside its host. Those are silently REMOVED or reinterpreted when a URL is parsed, so the address dialled would not be the one you wrote \u2014 check for a line wrap or a stray space where the value was copied.`
@@ -780,7 +955,7 @@ function parseDsn(raw) {
780
955
  const [workspace, server, ...extra] = segments;
781
956
  if (workspace === void 0 || server === void 0 || extra.length > 0) {
782
957
  fail(
783
- `dsn ${safe} must carry exactly two path segments \u2014 the workspace and the server, as in /ten_<32 hex>/<server>. A missing server is never defaulted: it is what the key is bound to.`
958
+ `dsn ${safe} must carry exactly two path segments \u2014 the workspace and the server, as in /ten_.../<server>. A missing server is never defaulted: it is what the key is bound to.`
784
959
  );
785
960
  }
786
961
  for (const [slot, segment] of [
@@ -789,13 +964,13 @@ function parseDsn(raw) {
789
964
  ]) {
790
965
  if (containsKey(segment)) {
791
966
  fail(
792
- `dsn ${safe} has a KEY in the ${slot} slot. The key goes before the @, and the path carries the workspace and the server: https://baton_pk_...@host/ten_<32 hex>/<server>`
967
+ `dsn ${safe} has a KEY in the ${slot} slot. The key goes before the @, and the path carries the workspace and the server: https://baton_pk_...@host/ten_.../<server>`
793
968
  );
794
969
  }
795
970
  }
796
971
  if (!WORKSPACE_PATTERN.test(workspace)) {
797
972
  fail(
798
- `dsn ${safe} has ${JSON.stringify(workspace)} where the workspace belongs \u2014 expected ten_ followed by 32 hex characters. If the two path segments are the right way round, this is not a Baton DSN.`
973
+ `dsn ${safe} has ${JSON.stringify(workspace)} where the workspace belongs \u2014 expected ten_ followed by 8 or 32 hex characters. If the two path segments are the right way round, this is not a Baton DSN.`
799
974
  );
800
975
  }
801
976
  if (!VENDOR_ID_PATTERN.test(server)) {
@@ -816,8 +991,16 @@ function parseDsn(raw) {
816
991
  });
817
992
  }
818
993
  function sealKey(dsn) {
819
- const shown = { origin: dsn.origin, tenantId: dsn.tenantId, vendorId: dsn.vendorId, key: "<key>" };
820
- Object.defineProperty(dsn, "toJSON", { value: () => shown, enumerable: false });
994
+ const shown = {
995
+ origin: dsn.origin,
996
+ tenantId: dsn.tenantId,
997
+ vendorId: dsn.vendorId,
998
+ key: "<key>"
999
+ };
1000
+ Object.defineProperty(dsn, "toJSON", {
1001
+ value: () => shown,
1002
+ enumerable: false
1003
+ });
821
1004
  Object.defineProperty(dsn, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
822
1005
  value: () => shown,
823
1006
  enumerable: false
@@ -827,12 +1010,18 @@ function sealKey(dsn) {
827
1010
 
828
1011
  // src/integrations/mcp/config.ts
829
1012
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1013
+ var USER_ID_MODES = /* @__PURE__ */ new Set(["hashed", "raw"]);
830
1014
  function resolveTenantId(explicit, vendorId) {
831
1015
  if (explicit) return explicit;
832
1016
  const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
833
1017
  if (fromEnv) return fromEnv;
834
1018
  return vendorId;
835
1019
  }
1020
+ function resolveUserIdHmacKey(explicit) {
1021
+ if (explicit !== void 0) return explicit;
1022
+ const fromEnv = typeof process !== "undefined" ? process.env?.BATON_USER_ID_HMAC_KEY : void 0;
1023
+ return fromEnv ? fromEnv : void 0;
1024
+ }
836
1025
  function resolveBatonConfig(config) {
837
1026
  const dsnString = selectDsn(
838
1027
  config.dsn,
@@ -914,6 +1103,17 @@ function validateBatonConfig(config) {
914
1103
  `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
915
1104
  );
916
1105
  }
1106
+ if (config.resolveUser !== void 0 && typeof config.resolveUser !== "function") {
1107
+ throw new Error("BatonConfig.resolveUser must be a function.");
1108
+ }
1109
+ if (config.userIdHmacKey !== void 0 && typeof config.userIdHmacKey !== "string" && !(config.userIdHmacKey instanceof Uint8Array)) {
1110
+ throw new Error("BatonConfig.userIdHmacKey must be a string or a Uint8Array.");
1111
+ }
1112
+ if (config.userIdMode !== void 0 && !USER_ID_MODES.has(config.userIdMode)) {
1113
+ throw new Error(
1114
+ `BatonConfig.userIdMode ${JSON.stringify(config.userIdMode)} must be one of ${JSON.stringify([...USER_ID_MODES].sort())}.`
1115
+ );
1116
+ }
917
1117
  }
918
1118
 
919
1119
  // src/optout.ts
@@ -1139,10 +1339,10 @@ function toolInputJsonSchema(inputSchema) {
1139
1339
  }
1140
1340
 
1141
1341
  // src/integrations/mcp/surface.ts
1142
- var import_node_crypto = require("crypto");
1342
+ var import_node_crypto2 = require("crypto");
1143
1343
  function surfaceHash(surface) {
1144
1344
  const canonical = canonicalJson(surface);
1145
- const digest = (0, import_node_crypto.createHash)("sha256").update(canonical, "utf-8").digest("hex");
1345
+ const digest = (0, import_node_crypto2.createHash)("sha256").update(canonical, "utf-8").digest("hex");
1146
1346
  return `sha256:${digest}`;
1147
1347
  }
1148
1348
  function canonicalJson(value) {
@@ -1240,16 +1440,18 @@ function batonWrap(nameRef, original, ctx) {
1240
1440
  const extra = callArgs[callArgs.length - 1];
1241
1441
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
1242
1442
  const meta = extraMeta(extra);
1243
- const runtime = detectAgentRuntime(meta) ?? ctx.defaultAgentRuntime;
1443
+ const runtime = detectAgentRuntime(meta, {
1444
+ // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1445
+ // `_meta`; 1.x leaves them in. Both are handed over — see
1446
+ // `mcpTypes.extraEnvelope`.
1447
+ envelope: extraEnvelope(extra),
1448
+ // Tier 2's carrier: neither peer puts client identity on the
1449
+ // handler context, both expose the cached handshake on the server.
1450
+ server: ctx.server,
1451
+ scrubber: ctx.scrubber
1452
+ }) ?? UNKNOWN_AGENT_RUNTIME;
1244
1453
  const scrubbedMeta = meta ? ctx.scrubber(meta) : null;
1245
- const sessionId = await resolveSessionId(
1246
- ctx.resolveSessionId,
1247
- ctx.fallbackSessionId,
1248
- extra,
1249
- meta,
1250
- toolName,
1251
- params
1252
- );
1454
+ const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1253
1455
  const dispositions = ctx.paramRegistry.get(toolName);
1254
1456
  const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions);
1255
1457
  const rawExpected = extractGoalParam(
@@ -1262,12 +1464,24 @@ function batonWrap(nameRef, original, ctx) {
1262
1464
  const scrubbedIntent = rawIntent !== null ? ctx.scrubber(rawIntent) : null;
1263
1465
  const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1264
1466
  const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1467
+ const callId = (0, import_uuid2.v7)();
1468
+ const userId = await resolveCallUserId(
1469
+ ctx.resolveUser,
1470
+ { extra, toolName, arguments: params },
1471
+ { mode: ctx.userIdMode, tenantId: ctx.tenantId, key: ctx.userIdHmacKey }
1472
+ );
1265
1473
  const common = {
1266
1474
  tenant_id: ctx.tenantId,
1267
1475
  vendor_id: ctx.vendorId,
1268
1476
  session_id: sessionId,
1269
1477
  consent_token: ctx.consentToken,
1270
1478
  agent_runtime: runtime,
1479
+ // The four `...common` sites below are the tool-call legs and the
1480
+ // proactive annotation — the same four Python stamps
1481
+ // (`middleware.py` 481/524/562/606). `surface_snapshot` is deliberately
1482
+ // NOT among them: it describes the SERVER and is captured outside any
1483
+ // call, so there is no caller to name (register D5).
1484
+ user_id: userId,
1271
1485
  runtime_meta: scrubbedMeta
1272
1486
  };
1273
1487
  if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
@@ -1290,6 +1504,7 @@ function batonWrap(nameRef, original, ctx) {
1290
1504
  ctx.sink,
1291
1505
  () => ToolCallStartEventSchema.parse({
1292
1506
  ...common,
1507
+ call_id: callId,
1293
1508
  sequence_number: ctx.counter.next(sessionId),
1294
1509
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1295
1510
  payload: {
@@ -1313,6 +1528,7 @@ function batonWrap(nameRef, original, ctx) {
1313
1528
  ctx.sink,
1314
1529
  () => ToolCallErrorEventSchema.parse({
1315
1530
  ...common,
1531
+ call_id: callId,
1316
1532
  sequence_number: ctx.counter.next(sessionId),
1317
1533
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1318
1534
  payload: {
@@ -1330,6 +1546,7 @@ function batonWrap(nameRef, original, ctx) {
1330
1546
  ctx.sink,
1331
1547
  () => ToolCallEndEventSchema.parse({
1332
1548
  ...common,
1549
+ call_id: callId,
1333
1550
  sequence_number: ctx.counter.next(sessionId),
1334
1551
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1335
1552
  payload: { tool_name: toolName, result: ctx.scrubber(result), duration_ms: durationMs }
@@ -1499,7 +1716,24 @@ function withBaton(server, supplied = {}) {
1499
1716
  consent_token: config.consentToken,
1500
1717
  sequence_number: counter.next(sessionId),
1501
1718
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1502
- agent_runtime: config.defaultAgentRuntime ?? "unknown",
1719
+ // Deliberately the literal, NOT the ladder — and an earlier comment
1720
+ // here justified that by saying no call is in scope, which is false:
1721
+ // `maybeEmitSurfaceSnapshot` is the first line of `batonWrap`, so the
1722
+ // handshake has happened and tier 2's carrier is live in this closure.
1723
+ // The real reason is that the snapshot describes the VENDOR'S SURFACE,
1724
+ // which is the same whoever is calling. It is hashed and emitted at
1725
+ // most once per process per surface, so the client that happens to
1726
+ // trigger it is whichever one called first — attributing the surface to
1727
+ // that client would read as a fact about the surface and be an accident
1728
+ // of timing. Python hardcodes it from the same in-call position
1729
+ // (`_tool_wrap.py`), so this is parity, not a gap.
1730
+ //
1731
+ // ⚠ Consequence worth knowing: one session emits `surface_snapshot`
1732
+ // with `unknown` and everything else with the client's name, so a
1733
+ // consumer grouping on `agent_runtime` alone sees two runtimes for one
1734
+ // client. Intended; group surfaces on `(tenant_id, vendor_id,
1735
+ // surface_hash)`, which is what the Console's table is keyed on.
1736
+ agent_runtime: UNKNOWN_AGENT_RUNTIME,
1503
1737
  payload: {
1504
1738
  surface_hash: digest,
1505
1739
  server_info: snapshot.server_info,
@@ -1545,18 +1779,21 @@ function withBaton(server, supplied = {}) {
1545
1779
  vendorId: config.vendorId,
1546
1780
  consentToken: config.consentToken,
1547
1781
  fallbackSessionId,
1548
- defaultAgentRuntime: config.defaultAgentRuntime ?? "unknown",
1782
+ server,
1549
1783
  scrubber,
1550
- resolveSessionId: config.resolveSessionId,
1551
1784
  annotationToolName,
1552
1785
  intentParamMode,
1553
1786
  paramRegistry: /* @__PURE__ */ new Map(),
1787
+ resolveUser: config.resolveUser,
1788
+ userIdMode: config.userIdMode ?? "hashed",
1789
+ userIdHmacKey: resolveUserIdHmacKey(config.userIdHmacKey),
1554
1790
  vendorToolJsonSchema,
1555
1791
  bustSchemaMemo,
1556
1792
  tracker,
1557
1793
  surfaceState,
1558
1794
  emitSurface
1559
1795
  };
1796
+ warnIfIdentityCannotResolve(ctx);
1560
1797
  const instructions = buildServerInstructions({
1561
1798
  vendorDisplayName: config.vendorDisplayName,
1562
1799
  annotationToolName
@@ -1569,10 +1806,17 @@ function withBaton(server, supplied = {}) {
1569
1806
  vendorId: ctx.vendorId,
1570
1807
  vendorDisplayName: config.vendorDisplayName,
1571
1808
  consentToken: ctx.consentToken,
1809
+ // Read off `ctx`, never re-resolved from `config`: the two paths must
1810
+ // agree on the actor, and `userIdMode`/`userIdHmacKey` each have a
1811
+ // default and an env fallback that a second resolution could take
1812
+ // differently. Required (not optional) on the options type ON PURPOSE —
1813
+ // the compiler then refuses a registration that forgets them, which is
1814
+ // the mechanical version of "wiring two of four call sites".
1815
+ resolveUser: ctx.resolveUser,
1816
+ userIdMode: ctx.userIdMode,
1817
+ userIdHmacKey: ctx.userIdHmacKey,
1572
1818
  fallbackSessionId: ctx.fallbackSessionId,
1573
- defaultAgentRuntime: ctx.defaultAgentRuntime,
1574
1819
  scrubber: ctx.scrubber,
1575
- resolveSessionId: ctx.resolveSessionId,
1576
1820
  annotationToolName: config.annotationToolName,
1577
1821
  tracker
1578
1822
  });
@@ -1616,6 +1860,8 @@ function withBaton(server, supplied = {}) {
1616
1860
  ToolCallErrorPayloadSchema,
1617
1861
  ToolCallStartEventSchema,
1618
1862
  ToolCallStartPayloadSchema,
1863
+ VENDOR_HASH_SCHEME,
1864
+ hashUserId,
1619
1865
  identityScrub,
1620
1866
  safeWrite,
1621
1867
  withBaton