@goodtiming/baton-sdk 0.3.0 → 0.3.2

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
@@ -33,6 +33,7 @@ __export(index_exports, {
33
33
  AnnotationEventSchema: () => AnnotationEventSchema,
34
34
  AnnotationPayloadSchema: () => AnnotationPayloadSchema,
35
35
  BatonHandle: () => BatonHandle,
36
+ DEFAULT_CONSENT_TOKEN: () => DEFAULT_CONSENT_TOKEN,
36
37
  DEPTH_LIMIT: () => DEPTH_LIMIT,
37
38
  EventSchema: () => EventSchema,
38
39
  EventTypeSchema: () => EventTypeSchema,
@@ -55,7 +56,7 @@ __export(index_exports, {
55
56
  module.exports = __toCommonJS(index_exports);
56
57
 
57
58
  // src/version.ts
58
- var SDK_VERSION = "ts-0.3.0";
59
+ var SDK_VERSION = "ts-0.3.2";
59
60
 
60
61
  // src/events.ts
61
62
  var import_zod = require("zod");
@@ -97,6 +98,7 @@ var SurfaceSnapshotPayloadSchema = import_zod.z.object({
97
98
  tools: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
98
99
  seam_augmentations: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).default({})
99
100
  }).strict();
101
+ var DEFAULT_CONSENT_TOKEN = "customer-consented";
100
102
  var envelopeShape = {
101
103
  event_id: import_zod.z.uuid().default(() => (0, import_uuid.v7)()),
102
104
  tenant_id: import_zod.z.string(),
@@ -108,6 +110,7 @@ var envelopeShape = {
108
110
  sdk_version: import_zod.z.string().default(SDK_VERSION),
109
111
  agent_runtime: import_zod.z.string().default("unknown"),
110
112
  user_id: import_zod.z.string().nullable().default(null),
113
+ call_id: import_zod.z.string().nullable().default(null),
111
114
  runtime_meta: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null)
112
115
  };
113
116
  var EventTypeSchema = import_zod.z.enum([
@@ -320,6 +323,25 @@ var HttpSink = class _HttpSink {
320
323
  );
321
324
  this.fetchImpl = options.fetchImpl ?? fetch;
322
325
  }
326
+ /**
327
+ * What this sink shows when something prints it — never the bearer.
328
+ *
329
+ * ⚠ **A sink built from a DSN holds a key the vendor never typed**, and it
330
+ * hangs off `BatonHandle.sink` and off the resolved config, so
331
+ * `console.log(handle.sink)` or a structured logger serialising either one
332
+ * wrote a publishable key into the vendor's logs. Found by the S2 test that
333
+ * asserts the DSN's own string does not survive resolution: it does not, and
334
+ * the key was one field further down. Same treatment as the parsed DSN —
335
+ * `toJSON` for serialisers, the inspect symbol for `console.log`, and
336
+ * `Symbol.for` rather than importing `node:util`, since this package runs on
337
+ * runtimes that have no such module.
338
+ */
339
+ toJSON() {
340
+ return { url: this.url, apiKey: "<key>" };
341
+ }
342
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
343
+ return this.toJSON();
344
+ }
323
345
  async write(event) {
324
346
  if (this.closed) throw new Error("HttpSink is closed");
325
347
  this.enqueue(event);
@@ -509,25 +531,65 @@ function extraMeta(extra) {
509
531
  const nested = extra.mcpReq?._meta;
510
532
  return nested ?? null;
511
533
  }
534
+ function extraEnvelope(extra) {
535
+ const envelope = extra.mcpReq?.envelope;
536
+ return envelope ?? null;
537
+ }
512
538
 
513
539
  // src/integrations/mcp/runtimeAdapter.ts
514
- function detectAgentRuntime(meta) {
515
- if (!meta) return null;
516
- for (const key of Object.keys(meta)) {
517
- if (key.startsWith("claudecode/")) return "claude-code";
540
+ var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
541
+ var CLIENT_NAME_MAX_LEN = 128;
542
+ var UNKNOWN_AGENT_RUNTIME = "unknown";
543
+ function clean(name, scrubber) {
544
+ if (typeof name !== "string" || !name) return null;
545
+ let cleaned = name;
546
+ if (scrubber) {
547
+ const scrubbed = scrubber(cleaned);
548
+ if (typeof scrubbed !== "string") return null;
549
+ cleaned = scrubbed;
550
+ }
551
+ if (!cleaned) return null;
552
+ return [...cleaned].slice(0, CLIENT_NAME_MAX_LEN).join("");
553
+ }
554
+ function declaredOnRequest(meta, envelope) {
555
+ for (const source of [envelope, meta]) {
556
+ if (!source) continue;
557
+ const info = source[CLIENT_INFO_META_KEY];
558
+ if (info && typeof info === "object") {
559
+ const name = info.name;
560
+ if (name !== void 0) return name;
561
+ }
562
+ }
563
+ return void 0;
564
+ }
565
+ function declaredOnConnection(options) {
566
+ try {
567
+ const server = options.server;
568
+ if (!server) return void 0;
569
+ const inner = server.server;
570
+ const holder = inner ?? server;
571
+ if (typeof holder.getClientVersion !== "function") return void 0;
572
+ return holder.getClientVersion()?.name;
573
+ } catch {
574
+ return void 0;
575
+ }
576
+ }
577
+ function detectAgentRuntime(meta, options = {}) {
578
+ const { envelope, scrubber } = options;
579
+ const onRequest = clean(declaredOnRequest(meta, envelope), scrubber);
580
+ if (onRequest !== null) return onRequest;
581
+ const onConnection = clean(declaredOnConnection(options), scrubber);
582
+ if (onConnection !== null) return onConnection;
583
+ if (meta) {
584
+ for (const key of Object.keys(meta)) {
585
+ if (key.startsWith("claudecode/")) return "claude-code";
586
+ }
518
587
  }
519
588
  return null;
520
589
  }
521
590
 
522
591
  // src/integrations/mcp/sessionResolution.ts
523
- async function resolveSessionId(hook, fallbackSessionId, extra, meta, toolName, args) {
524
- if (hook) {
525
- try {
526
- const hookResult = await hook({ meta, toolName, arguments: args });
527
- if (typeof hookResult === "string" && hookResult) return hookResult;
528
- } catch {
529
- }
530
- }
592
+ async function resolveSessionId(fallbackSessionId, extra) {
531
593
  if (typeof extra.sessionId === "string" && extra.sessionId) return extra.sessionId;
532
594
  return fallbackSessionId;
533
595
  }
@@ -563,16 +625,13 @@ function registerAnnotationTool(server, options) {
563
625
  },
564
626
  async (args, extra) => {
565
627
  const meta = extraMeta(extra);
566
- const runtime = detectAgentRuntime(meta) ?? options.defaultAgentRuntime;
628
+ const runtime = detectAgentRuntime(meta, {
629
+ envelope: extraEnvelope(extra),
630
+ server,
631
+ scrubber: options.scrubber
632
+ }) ?? UNKNOWN_AGENT_RUNTIME;
567
633
  const scrubbedMeta = meta ? options.scrubber(meta) : null;
568
- const sessionId = await resolveSessionId(
569
- options.resolveSessionId,
570
- options.fallbackSessionId,
571
- extra,
572
- meta,
573
- name,
574
- args
575
- );
634
+ const sessionId = await resolveSessionId(options.fallbackSessionId, extra);
576
635
  if (args.signal_type === void 0) {
577
636
  options.tracker?.mark(sessionId);
578
637
  }
@@ -617,8 +676,211 @@ function registerAnnotationTool(server, options) {
617
676
  return name;
618
677
  }
619
678
 
620
- // src/integrations/mcp/config.ts
679
+ // src/dsn.ts
621
680
  var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
681
+ var WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;
682
+ var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
683
+ var NOT_IN_A_KEY = /[\x00\n\r]/;
684
+ var PUBLISHABLE_PREFIX = "baton_pk_";
685
+ var SECRET_PREFIX = "baton_sk_";
686
+ var KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;
687
+ function looksLikeAKey(value) {
688
+ return value.startsWith(PUBLISHABLE_PREFIX) || value.startsWith(SECRET_PREFIX);
689
+ }
690
+ function containsKey(value) {
691
+ return sweep(value) !== value;
692
+ }
693
+ 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";
694
+ function warn(message) {
695
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
696
+ process.emitWarning(message);
697
+ }
698
+ }
699
+ function splitDsn(raw) {
700
+ const schemeEnd = raw.indexOf("://");
701
+ if (schemeEnd === -1) return null;
702
+ const scheme = raw.slice(0, schemeEnd).toLowerCase();
703
+ const rest = raw.slice(schemeEnd + 3);
704
+ const end = rest.search(/[/?#]/);
705
+ if (end === -1) return { scheme, netloc: rest, slash: "", path: "" };
706
+ const netloc = rest.slice(0, end);
707
+ if (rest[end] !== "/") {
708
+ return { scheme, netloc, slash: "", path: "" };
709
+ }
710
+ const afterSlash = rest.slice(end + 1);
711
+ const pathEnd = afterSlash.search(/[?#]/);
712
+ return {
713
+ scheme,
714
+ netloc,
715
+ slash: "/",
716
+ path: pathEnd === -1 ? afterSlash : afterSlash.slice(0, pathEnd)
717
+ };
718
+ }
719
+ function splitKeyFromAuthority(netloc) {
720
+ const index = netloc.lastIndexOf("@");
721
+ if (index === -1) return { key: "", at: false, authority: netloc };
722
+ return {
723
+ key: netloc.slice(0, index),
724
+ at: true,
725
+ authority: netloc.slice(index + 1)
726
+ };
727
+ }
728
+ function redact(raw) {
729
+ const parts = splitDsn(raw);
730
+ if (parts === null) return "<dsn>";
731
+ const { at, authority } = splitKeyFromAuthority(parts.netloc);
732
+ const assembled = at ? `${parts.scheme}://***@${authority}${parts.slash}${parts.path}` : `${parts.scheme}://<no key>@${parts.netloc}${parts.slash}${parts.path}`;
733
+ return sweep(assembled);
734
+ }
735
+ function sweep(message) {
736
+ return message.replace(KEY_RUN, "<key>");
737
+ }
738
+ function fail(message) {
739
+ throw new Error(sweep(message));
740
+ }
741
+ function dsnFromEnvironment() {
742
+ const fromEnv = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
743
+ return fromEnv ? fromEnv : void 0;
744
+ }
745
+ function selectDsn(explicit, supplied, door) {
746
+ const conflicts = Object.keys(supplied).filter((name) => supplied[name]).sort();
747
+ if (explicit) {
748
+ if (conflicts.length > 0) {
749
+ fail(
750
+ `${door} got both a dsn and an explicit ${conflicts[0]} \u2014 the dsn already supplies it. Drop one: the dsn is the single value from /account, and ${conflicts[0]} is what it unpacks to.`
751
+ );
752
+ }
753
+ return explicit;
754
+ }
755
+ const ambient = dsnFromEnvironment();
756
+ if (ambient === void 0) return void 0;
757
+ if (conflicts.length > 0) {
758
+ warn(
759
+ `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.`
760
+ );
761
+ return void 0;
762
+ }
763
+ return ambient;
764
+ }
765
+ function parseDsn(raw) {
766
+ if (typeof raw !== "string" || raw.trim() === "") {
767
+ fail("dsn must be a non-empty string");
768
+ }
769
+ const dsn = raw.trim();
770
+ if (looksLikeAKey(dsn)) {
771
+ fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
772
+ }
773
+ const safe = redact(dsn);
774
+ const parts = splitDsn(dsn);
775
+ if (parts === null || parts.scheme !== "https" && parts.scheme !== "http") {
776
+ fail(
777
+ `dsn ${safe} must start with https:// (or http:// for local development) \u2014 ${BARE_KEY_HINT}`
778
+ );
779
+ }
780
+ const { key, at, authority } = splitKeyFromAuthority(parts.netloc);
781
+ if (!at || !key) {
782
+ if (looksLikeAKey(parts.netloc)) {
783
+ fail(
784
+ `dsn ${safe} is a bare key with a scheme in front of it: ${BARE_KEY_HINT}. The full value also carries a host, your workspace and your server \u2014 https://baton_pk_...@host/ten_.../server`
785
+ );
786
+ }
787
+ const misplaced = parts.path.split("/").some((segment) => containsKey(segment));
788
+ const detail = misplaced ? "the key is in the PATH \u2014 it goes before an @" : "the value from /account has the key before an @";
789
+ fail(
790
+ `dsn ${safe} carries no key: ${detail}, as in https://baton_pk_...@host/ten_.../server`
791
+ );
792
+ }
793
+ if (NOT_IN_A_KEY.test(key)) {
794
+ fail(
795
+ `dsn ${safe} has a line break or a null inside its key \u2014 those can never be sent in an Authorization header, so this DSN could not have worked. Check for a line wrap where the value was copied.`
796
+ );
797
+ }
798
+ if (key.includes(":")) {
799
+ fail(
800
+ `dsn ${safe} has a ':' in its key \u2014 a DSN carries one credential and no password field`
801
+ );
802
+ }
803
+ if (!authority) {
804
+ fail(`dsn ${safe} has no host`);
805
+ }
806
+ if (containsKey(authority)) {
807
+ fail(
808
+ `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>`
809
+ );
810
+ }
811
+ if (NOT_IN_A_HOST.test(authority)) {
812
+ fail(
813
+ `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.`
814
+ );
815
+ }
816
+ let hostReason = null;
817
+ let parsedAuthority = null;
818
+ try {
819
+ parsedAuthority = new URL(`${parts.scheme}://${authority}`);
820
+ } catch (error) {
821
+ hostReason = error instanceof Error ? error.constructor.name : "Error";
822
+ }
823
+ if (parsedAuthority === null) {
824
+ fail(`dsn ${safe} is not a parseable URL (${hostReason ?? "Error"})`);
825
+ }
826
+ const segments = parts.path.split("/").filter((segment) => segment !== "");
827
+ const [workspace, server, ...extra] = segments;
828
+ if (workspace === void 0 || server === void 0 || extra.length > 0) {
829
+ fail(
830
+ `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.`
831
+ );
832
+ }
833
+ for (const [slot, segment] of [
834
+ ["workspace", workspace],
835
+ ["server", server]
836
+ ]) {
837
+ if (containsKey(segment)) {
838
+ fail(
839
+ `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>`
840
+ );
841
+ }
842
+ }
843
+ if (!WORKSPACE_PATTERN.test(workspace)) {
844
+ fail(
845
+ `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.`
846
+ );
847
+ }
848
+ if (!VENDOR_ID_PATTERN.test(server)) {
849
+ fail(
850
+ `dsn ${safe} has ${JSON.stringify(server)} where the server belongs \u2014 it must match ${VENDOR_ID_PATTERN.source}, because this value becomes the annotation tool name prefix as well as the envelope's vendor_id.`
851
+ );
852
+ }
853
+ if (key.startsWith(SECRET_PREFIX)) {
854
+ warn(
855
+ `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.`
856
+ );
857
+ }
858
+ return sealKey({
859
+ origin: `${parts.scheme}://${authority}`,
860
+ tenantId: workspace,
861
+ vendorId: server,
862
+ key
863
+ });
864
+ }
865
+ function sealKey(dsn) {
866
+ const shown = {
867
+ origin: dsn.origin,
868
+ tenantId: dsn.tenantId,
869
+ vendorId: dsn.vendorId,
870
+ key: "<key>"
871
+ };
872
+ Object.defineProperty(dsn, "toJSON", {
873
+ value: () => shown,
874
+ enumerable: false
875
+ });
876
+ Object.defineProperty(dsn, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
877
+ value: () => shown,
878
+ enumerable: false
879
+ });
880
+ return dsn;
881
+ }
882
+
883
+ // src/integrations/mcp/config.ts
622
884
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
623
885
  function resolveTenantId(explicit, vendorId) {
624
886
  if (explicit) return explicit;
@@ -626,7 +888,62 @@ function resolveTenantId(explicit, vendorId) {
626
888
  if (fromEnv) return fromEnv;
627
889
  return vendorId;
628
890
  }
891
+ function resolveBatonConfig(config) {
892
+ const dsnString = selectDsn(
893
+ config.dsn,
894
+ {
895
+ // Truthiness per field, mirroring Python's `bool()` / `is not None`
896
+ // split: an empty `vendorId` is an unset one, while an explicitly
897
+ // supplied `tenantId` or `sink` is a conflict whatever it holds.
898
+ vendorId: Boolean(config.vendorId),
899
+ tenantId: config.tenantId !== void 0,
900
+ sink: config.sink !== void 0
901
+ },
902
+ "BatonConfig"
903
+ );
904
+ if (dsnString === void 0) {
905
+ const defaulted = {
906
+ ...config,
907
+ consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN
908
+ };
909
+ validateBatonConfig(defaulted);
910
+ return defaulted;
911
+ }
912
+ const dsn = parseDsn(dsnString);
913
+ const rest = { ...config };
914
+ delete rest.dsn;
915
+ const identity = {
916
+ ...rest,
917
+ vendorId: dsn.vendorId,
918
+ tenantId: dsn.tenantId,
919
+ // `??`, for the same reason as `consentToken` directly below, and the
920
+ // inconsistency was worth fixing rather than mirroring: with no dsn,
921
+ // `vendorDisplayName: ""` is REFUSED by validation; with one, `||` quietly
922
+ // substituted the server slug. One input, two answers, decided by whether
923
+ // a dsn happens to be present — and this string reaches the calling agent
924
+ // in the server instructions and the annotation tool description, which is
925
+ // the whitelabel obligation the validator cites when it refuses the empty
926
+ // one. ⚠ Python uses `or` here and still has the inconsistency.
927
+ vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,
928
+ // `??`, not `||`: an explicit empty string must survive to the validation
929
+ // below and be REFUSED there, rather than be quietly replaced by the
930
+ // default it was deliberately not left as.
931
+ consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN
932
+ };
933
+ validateBatonConfig(identity);
934
+ return {
935
+ ...identity,
936
+ // The origin is scheme + authority; `HttpSink` appends `/v0/events`
937
+ // itself, exactly as it does for an explicitly-constructed sink.
938
+ sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
939
+ };
940
+ }
629
941
  function validateBatonConfig(config) {
942
+ if (!config.vendorId) {
943
+ throw new Error(
944
+ "BatonConfig needs a vendorId \u2014 either directly, or via a dsn whose last path segment names the server (see /account)."
945
+ );
946
+ }
630
947
  if (!VENDOR_ID_PATTERN.test(config.vendorId)) {
631
948
  throw new Error(
632
949
  `vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
@@ -637,6 +954,11 @@ function validateBatonConfig(config) {
637
954
  "BatonConfig.vendorDisplayName is required \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4)."
638
955
  );
639
956
  }
957
+ if (config.consentToken !== void 0 && !config.consentToken) {
958
+ throw new Error(
959
+ "BatonConfig.consentToken was set to an empty string, and events without a valid consent_token MUST be rejected by the consumer per SPEC \xA72.3. Omit it to take the SDK's default."
960
+ );
961
+ }
640
962
  if (!config.consentToken) {
641
963
  throw new Error(
642
964
  "BatonConfig.consentToken is required per SPEC \xA72.3 \u2014 events without a valid consent_token MUST be rejected by the consumer."
@@ -649,6 +971,38 @@ function validateBatonConfig(config) {
649
971
  }
650
972
  }
651
973
 
974
+ // src/optout.ts
975
+ var SWITCH = "BATON_DISABLED";
976
+ var OFF_VALUES = /* @__PURE__ */ new Set(["", "0", "false", "no", "off"]);
977
+ function captureDisabled() {
978
+ const value = typeof process !== "undefined" ? process.env?.[SWITCH] : void 0;
979
+ if (value !== void 0 && !OFF_VALUES.has(value.trim().toLowerCase())) {
980
+ return SWITCH;
981
+ }
982
+ return null;
983
+ }
984
+ function logDisabled(switchName, surface) {
985
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
986
+ process.emitWarning(
987
+ `baton: ${switchName} is set, so capture is OFF \u2014 ${surface} installed nothing and will emit no events. Unset it to re-enable.`
988
+ );
989
+ }
990
+ }
991
+ var DisabledSink = class {
992
+ // The parameter is omitted rather than named-and-ignored: a narrower
993
+ // signature satisfies `Sink` in TypeScript, and there is nothing to do with
994
+ // an event that cannot arrive.
995
+ async write() {
996
+ return;
997
+ }
998
+ async flush() {
999
+ return;
1000
+ }
1001
+ async aclose() {
1002
+ return;
1003
+ }
1004
+ };
1005
+
652
1006
  // src/integrations/mcp/handle.ts
653
1007
  var BatonHandle = class {
654
1008
  sink;
@@ -941,16 +1295,18 @@ function batonWrap(nameRef, original, ctx) {
941
1295
  const extra = callArgs[callArgs.length - 1];
942
1296
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
943
1297
  const meta = extraMeta(extra);
944
- const runtime = detectAgentRuntime(meta) ?? ctx.defaultAgentRuntime;
1298
+ const runtime = detectAgentRuntime(meta, {
1299
+ // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1300
+ // `_meta`; 1.x leaves them in. Both are handed over — see
1301
+ // `mcpTypes.extraEnvelope`.
1302
+ envelope: extraEnvelope(extra),
1303
+ // Tier 2's carrier: neither peer puts client identity on the
1304
+ // handler context, both expose the cached handshake on the server.
1305
+ server: ctx.server,
1306
+ scrubber: ctx.scrubber
1307
+ }) ?? UNKNOWN_AGENT_RUNTIME;
945
1308
  const scrubbedMeta = meta ? ctx.scrubber(meta) : null;
946
- const sessionId = await resolveSessionId(
947
- ctx.resolveSessionId,
948
- ctx.fallbackSessionId,
949
- extra,
950
- meta,
951
- toolName,
952
- params
953
- );
1309
+ const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
954
1310
  const dispositions = ctx.paramRegistry.get(toolName);
955
1311
  const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions);
956
1312
  const rawExpected = extractGoalParam(
@@ -963,6 +1319,7 @@ function batonWrap(nameRef, original, ctx) {
963
1319
  const scrubbedIntent = rawIntent !== null ? ctx.scrubber(rawIntent) : null;
964
1320
  const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
965
1321
  const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1322
+ const callId = (0, import_uuid2.v7)();
966
1323
  const common = {
967
1324
  tenant_id: ctx.tenantId,
968
1325
  vendor_id: ctx.vendorId,
@@ -991,6 +1348,7 @@ function batonWrap(nameRef, original, ctx) {
991
1348
  ctx.sink,
992
1349
  () => ToolCallStartEventSchema.parse({
993
1350
  ...common,
1351
+ call_id: callId,
994
1352
  sequence_number: ctx.counter.next(sessionId),
995
1353
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
996
1354
  payload: {
@@ -1014,6 +1372,7 @@ function batonWrap(nameRef, original, ctx) {
1014
1372
  ctx.sink,
1015
1373
  () => ToolCallErrorEventSchema.parse({
1016
1374
  ...common,
1375
+ call_id: callId,
1017
1376
  sequence_number: ctx.counter.next(sessionId),
1018
1377
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1019
1378
  payload: {
@@ -1031,6 +1390,7 @@ function batonWrap(nameRef, original, ctx) {
1031
1390
  ctx.sink,
1032
1391
  () => ToolCallEndEventSchema.parse({
1033
1392
  ...common,
1393
+ call_id: callId,
1034
1394
  sequence_number: ctx.counter.next(sessionId),
1035
1395
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1036
1396
  payload: { tool_name: toolName, result: ctx.scrubber(result), duration_ms: durationMs }
@@ -1164,8 +1524,25 @@ function wireEntry(name, entry, ctx) {
1164
1524
  };
1165
1525
  }
1166
1526
  }
1167
- function withBaton(server, config) {
1168
- validateBatonConfig(config);
1527
+ function withBaton(server, supplied = {}) {
1528
+ const disabledBy = captureDisabled();
1529
+ if (disabledBy !== null) {
1530
+ logDisabled(disabledBy, "withBaton");
1531
+ return new BatonHandle({
1532
+ // A sink the VENDOR constructed is held rather than dropped, so their
1533
+ // `handle.aclose()` still releases it — we took ownership of that object
1534
+ // the moment they passed it, and the switch does not undo that. Nothing
1535
+ // writes to it: nothing is wrapped.
1536
+ sink: supplied.sink ?? new DisabledSink(),
1537
+ // Empty, and a constant, because when the switch is on nothing was
1538
+ // resolved: inventing a session id would put a real identifier on a
1539
+ // handle whose whole meaning is that no events exist under it.
1540
+ vendorId: "",
1541
+ sessionId: "baton-disabled",
1542
+ annotationToolName: ""
1543
+ });
1544
+ }
1545
+ const config = resolveBatonConfig(supplied);
1169
1546
  const sink = config.sink ?? new StdoutSink();
1170
1547
  const annotationToolName = config.annotationToolName || `${config.vendorId}_annotate`;
1171
1548
  const intentParamMode = config.intentParamMode ?? "optional";
@@ -1183,7 +1560,24 @@ function withBaton(server, config) {
1183
1560
  consent_token: config.consentToken,
1184
1561
  sequence_number: counter.next(sessionId),
1185
1562
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1186
- agent_runtime: config.defaultAgentRuntime ?? "unknown",
1563
+ // Deliberately the literal, NOT the ladder — and an earlier comment
1564
+ // here justified that by saying no call is in scope, which is false:
1565
+ // `maybeEmitSurfaceSnapshot` is the first line of `batonWrap`, so the
1566
+ // handshake has happened and tier 2's carrier is live in this closure.
1567
+ // The real reason is that the snapshot describes the VENDOR'S SURFACE,
1568
+ // which is the same whoever is calling. It is hashed and emitted at
1569
+ // most once per process per surface, so the client that happens to
1570
+ // trigger it is whichever one called first — attributing the surface to
1571
+ // that client would read as a fact about the surface and be an accident
1572
+ // of timing. Python hardcodes it from the same in-call position
1573
+ // (`_tool_wrap.py`), so this is parity, not a gap.
1574
+ //
1575
+ // ⚠ Consequence worth knowing: one session emits `surface_snapshot`
1576
+ // with `unknown` and everything else with the client's name, so a
1577
+ // consumer grouping on `agent_runtime` alone sees two runtimes for one
1578
+ // client. Intended; group surfaces on `(tenant_id, vendor_id,
1579
+ // surface_hash)`, which is what the Console's table is keyed on.
1580
+ agent_runtime: UNKNOWN_AGENT_RUNTIME,
1187
1581
  payload: {
1188
1582
  surface_hash: digest,
1189
1583
  server_info: snapshot.server_info,
@@ -1229,9 +1623,8 @@ function withBaton(server, config) {
1229
1623
  vendorId: config.vendorId,
1230
1624
  consentToken: config.consentToken,
1231
1625
  fallbackSessionId,
1232
- defaultAgentRuntime: config.defaultAgentRuntime ?? "unknown",
1626
+ server,
1233
1627
  scrubber,
1234
- resolveSessionId: config.resolveSessionId,
1235
1628
  annotationToolName,
1236
1629
  intentParamMode,
1237
1630
  paramRegistry: /* @__PURE__ */ new Map(),
@@ -1254,9 +1647,7 @@ function withBaton(server, config) {
1254
1647
  vendorDisplayName: config.vendorDisplayName,
1255
1648
  consentToken: ctx.consentToken,
1256
1649
  fallbackSessionId: ctx.fallbackSessionId,
1257
- defaultAgentRuntime: ctx.defaultAgentRuntime,
1258
1650
  scrubber: ctx.scrubber,
1259
- resolveSessionId: ctx.resolveSessionId,
1260
1651
  annotationToolName: config.annotationToolName,
1261
1652
  tracker
1262
1653
  });
@@ -1284,6 +1675,7 @@ function withBaton(server, config) {
1284
1675
  AnnotationEventSchema,
1285
1676
  AnnotationPayloadSchema,
1286
1677
  BatonHandle,
1678
+ DEFAULT_CONSENT_TOKEN,
1287
1679
  DEPTH_LIMIT,
1288
1680
  EventSchema,
1289
1681
  EventTypeSchema,