@goodtiming/baton-sdk 0.3.1 → 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
@@ -56,7 +56,7 @@ __export(index_exports, {
56
56
  module.exports = __toCommonJS(index_exports);
57
57
 
58
58
  // src/version.ts
59
- var SDK_VERSION = "ts-0.3.1";
59
+ var SDK_VERSION = "ts-0.3.2";
60
60
 
61
61
  // src/events.ts
62
62
  var import_zod = require("zod");
@@ -110,6 +110,7 @@ var envelopeShape = {
110
110
  sdk_version: import_zod.z.string().default(SDK_VERSION),
111
111
  agent_runtime: import_zod.z.string().default("unknown"),
112
112
  user_id: import_zod.z.string().nullable().default(null),
113
+ call_id: import_zod.z.string().nullable().default(null),
113
114
  runtime_meta: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null)
114
115
  };
115
116
  var EventTypeSchema = import_zod.z.enum([
@@ -530,25 +531,65 @@ function extraMeta(extra) {
530
531
  const nested = extra.mcpReq?._meta;
531
532
  return nested ?? null;
532
533
  }
534
+ function extraEnvelope(extra) {
535
+ const envelope = extra.mcpReq?.envelope;
536
+ return envelope ?? null;
537
+ }
533
538
 
534
539
  // 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";
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
+ }
539
587
  }
540
588
  return null;
541
589
  }
542
590
 
543
591
  // 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
- }
592
+ async function resolveSessionId(fallbackSessionId, extra) {
552
593
  if (typeof extra.sessionId === "string" && extra.sessionId) return extra.sessionId;
553
594
  return fallbackSessionId;
554
595
  }
@@ -584,16 +625,13 @@ function registerAnnotationTool(server, options) {
584
625
  },
585
626
  async (args, extra) => {
586
627
  const meta = extraMeta(extra);
587
- 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;
588
633
  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
- );
634
+ const sessionId = await resolveSessionId(options.fallbackSessionId, extra);
597
635
  if (args.signal_type === void 0) {
598
636
  options.tracker?.mark(sessionId);
599
637
  }
@@ -640,7 +678,7 @@ function registerAnnotationTool(server, options) {
640
678
 
641
679
  // src/dsn.ts
642
680
  var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
643
- var WORKSPACE_PATTERN = /^ten_[0-9a-fA-F]{32}$/;
681
+ var WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;
644
682
  var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
645
683
  var NOT_IN_A_KEY = /[\x00\n\r]/;
646
684
  var PUBLISHABLE_PREFIX = "baton_pk_";
@@ -681,7 +719,11 @@ function splitDsn(raw) {
681
719
  function splitKeyFromAuthority(netloc) {
682
720
  const index = netloc.lastIndexOf("@");
683
721
  if (index === -1) return { key: "", at: false, authority: netloc };
684
- return { key: netloc.slice(0, index), at: true, authority: netloc.slice(index + 1) };
722
+ return {
723
+ key: netloc.slice(0, index),
724
+ at: true,
725
+ authority: netloc.slice(index + 1)
726
+ };
685
727
  }
686
728
  function redact(raw) {
687
729
  const parts = splitDsn(raw);
@@ -761,6 +803,11 @@ function parseDsn(raw) {
761
803
  if (!authority) {
762
804
  fail(`dsn ${safe} has no host`);
763
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
+ }
764
811
  if (NOT_IN_A_HOST.test(authority)) {
765
812
  fail(
766
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.`
@@ -780,7 +827,7 @@ function parseDsn(raw) {
780
827
  const [workspace, server, ...extra] = segments;
781
828
  if (workspace === void 0 || server === void 0 || extra.length > 0) {
782
829
  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.`
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.`
784
831
  );
785
832
  }
786
833
  for (const [slot, segment] of [
@@ -789,13 +836,13 @@ function parseDsn(raw) {
789
836
  ]) {
790
837
  if (containsKey(segment)) {
791
838
  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>`
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>`
793
840
  );
794
841
  }
795
842
  }
796
843
  if (!WORKSPACE_PATTERN.test(workspace)) {
797
844
  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.`
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.`
799
846
  );
800
847
  }
801
848
  if (!VENDOR_ID_PATTERN.test(server)) {
@@ -816,8 +863,16 @@ function parseDsn(raw) {
816
863
  });
817
864
  }
818
865
  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 });
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
+ });
821
876
  Object.defineProperty(dsn, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
822
877
  value: () => shown,
823
878
  enumerable: false
@@ -1240,16 +1295,18 @@ function batonWrap(nameRef, original, ctx) {
1240
1295
  const extra = callArgs[callArgs.length - 1];
1241
1296
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
1242
1297
  const meta = extraMeta(extra);
1243
- 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;
1244
1308
  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
- );
1309
+ const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1253
1310
  const dispositions = ctx.paramRegistry.get(toolName);
1254
1311
  const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions);
1255
1312
  const rawExpected = extractGoalParam(
@@ -1262,6 +1319,7 @@ function batonWrap(nameRef, original, ctx) {
1262
1319
  const scrubbedIntent = rawIntent !== null ? ctx.scrubber(rawIntent) : null;
1263
1320
  const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1264
1321
  const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1322
+ const callId = (0, import_uuid2.v7)();
1265
1323
  const common = {
1266
1324
  tenant_id: ctx.tenantId,
1267
1325
  vendor_id: ctx.vendorId,
@@ -1290,6 +1348,7 @@ function batonWrap(nameRef, original, ctx) {
1290
1348
  ctx.sink,
1291
1349
  () => ToolCallStartEventSchema.parse({
1292
1350
  ...common,
1351
+ call_id: callId,
1293
1352
  sequence_number: ctx.counter.next(sessionId),
1294
1353
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1295
1354
  payload: {
@@ -1313,6 +1372,7 @@ function batonWrap(nameRef, original, ctx) {
1313
1372
  ctx.sink,
1314
1373
  () => ToolCallErrorEventSchema.parse({
1315
1374
  ...common,
1375
+ call_id: callId,
1316
1376
  sequence_number: ctx.counter.next(sessionId),
1317
1377
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1318
1378
  payload: {
@@ -1330,6 +1390,7 @@ function batonWrap(nameRef, original, ctx) {
1330
1390
  ctx.sink,
1331
1391
  () => ToolCallEndEventSchema.parse({
1332
1392
  ...common,
1393
+ call_id: callId,
1333
1394
  sequence_number: ctx.counter.next(sessionId),
1334
1395
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1335
1396
  payload: { tool_name: toolName, result: ctx.scrubber(result), duration_ms: durationMs }
@@ -1499,7 +1560,24 @@ function withBaton(server, supplied = {}) {
1499
1560
  consent_token: config.consentToken,
1500
1561
  sequence_number: counter.next(sessionId),
1501
1562
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1502
- 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,
1503
1581
  payload: {
1504
1582
  surface_hash: digest,
1505
1583
  server_info: snapshot.server_info,
@@ -1545,9 +1623,8 @@ function withBaton(server, supplied = {}) {
1545
1623
  vendorId: config.vendorId,
1546
1624
  consentToken: config.consentToken,
1547
1625
  fallbackSessionId,
1548
- defaultAgentRuntime: config.defaultAgentRuntime ?? "unknown",
1626
+ server,
1549
1627
  scrubber,
1550
- resolveSessionId: config.resolveSessionId,
1551
1628
  annotationToolName,
1552
1629
  intentParamMode,
1553
1630
  paramRegistry: /* @__PURE__ */ new Map(),
@@ -1570,9 +1647,7 @@ function withBaton(server, supplied = {}) {
1570
1647
  vendorDisplayName: config.vendorDisplayName,
1571
1648
  consentToken: ctx.consentToken,
1572
1649
  fallbackSessionId: ctx.fallbackSessionId,
1573
- defaultAgentRuntime: ctx.defaultAgentRuntime,
1574
1650
  scrubber: ctx.scrubber,
1575
- resolveSessionId: ctx.resolveSessionId,
1576
1651
  annotationToolName: config.annotationToolName,
1577
1652
  tracker
1578
1653
  });