@goodtiming/baton-sdk 0.3.6 → 0.4.0

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.6";
2
+ var SDK_VERSION = "ts-0.4.0";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
@@ -21,7 +21,23 @@ var ToolCallErrorPayloadSchema = z.object({
21
21
  tool_name: z.string(),
22
22
  error_type: z.string(),
23
23
  error_body: z.string(),
24
- duration_ms: z.number().int().nullable().default(null)
24
+ duration_ms: z.number().int().nullable().default(null),
25
+ // ⚠ `.optional()`, NOT `.default(null)` like the sibling fields — and it
26
+ // stays that way now that the producer emits the field.
27
+ //
28
+ // A default makes the schema an EMITTER: parsing a payload without the key
29
+ // ADDS it. That is wrong in a schema that also READS — a stored event from
30
+ // before the field existed would come back carrying an invented key, and
31
+ // against the pre-`f1e0280` spec pin, whose `events.schema.json` is
32
+ // `additionalProperties: false`, it reddened three tests saying so: a
33
+ // byte-identical vector round-trip, an ajv validation of TS-built events,
34
+ // and a field-for-field payload comparison.
35
+ //
36
+ // `.optional()` accepts the field when a vector carries it and stays
37
+ // silent when it does not. What makes the EMITTED shape complete is the
38
+ // emitter declaring `result` on both failure legs (`withBaton.ts`),
39
+ // explicitly `null` on a throw — not the schema filling it in.
40
+ result: z.unknown().nullable().optional()
25
41
  }).strict();
26
42
  var AnnotationPayloadSchema = z.object({
27
43
  intent: z.string().nullable().default(null),
@@ -42,6 +58,11 @@ var SurfaceSnapshotPayloadSchema = z.object({
42
58
  seam_augmentations: z.record(z.string(), z.unknown()).default({})
43
59
  }).strict();
44
60
  var DEFAULT_CONSENT_TOKEN = "customer-consented";
61
+ var PrincipalWireSchema = z.object({
62
+ id: z.string(),
63
+ source: z.string(),
64
+ form: z.string()
65
+ }).strict();
45
66
  var envelopeShape = {
46
67
  event_id: z.uuid().default(() => uuidv7()),
47
68
  tenant_id: z.string(),
@@ -52,7 +73,8 @@ var envelopeShape = {
52
73
  consent_token: z.string(),
53
74
  sdk_version: z.string().default(SDK_VERSION),
54
75
  agent_runtime: z.string().default("unknown"),
55
- principal_id: z.string().nullable().default(null),
76
+ principal: PrincipalWireSchema.nullable().default(null),
77
+ transport_observed: z.string().nullable().default(null),
56
78
  call_id: z.string().nullable().default(null),
57
79
  runtime_meta: z.record(z.string(), z.unknown()).nullable().default(null)
58
80
  };
@@ -393,6 +415,51 @@ import { v7 as uuidv72 } from "uuid";
393
415
  // src/integrations/mcp/annotation.ts
394
416
  import { z as z2 } from "zod";
395
417
 
418
+ // src/metaCoordinates.ts
419
+ var COORD_FIELD_NAMES = /* @__PURE__ */ new Set(["latitude", "longitude"]);
420
+ var DECIMAL_STRING = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
421
+ function isPlainObject2(value) {
422
+ if (typeof value !== "object" || value === null) return false;
423
+ const proto = Object.getPrototypeOf(value);
424
+ return proto === Object.prototype || proto === null;
425
+ }
426
+ function toOneDecimal(value) {
427
+ const magnitude = Math.abs(value);
428
+ if (Number.isInteger(magnitude * 4) && !Number.isInteger(magnitude * 2)) {
429
+ const tenths = Math.floor(magnitude * 10);
430
+ const even = tenths % 2 === 0 ? tenths : tenths + 1;
431
+ return (Math.sign(value) * even / 10).toFixed(1);
432
+ }
433
+ return value.toFixed(1);
434
+ }
435
+ function roundCoordinate(value) {
436
+ if (typeof value === "number") {
437
+ return Number.isFinite(value) && !Number.isInteger(value) ? Number(toOneDecimal(value)) : void 0;
438
+ }
439
+ if (typeof value === "string" && DECIMAL_STRING.test(value)) {
440
+ return toOneDecimal(Number(value));
441
+ }
442
+ return void 0;
443
+ }
444
+ function walk(value, depth) {
445
+ if (depth >= DEPTH_LIMIT) return value;
446
+ if (isPlainObject2(value)) {
447
+ const out = {};
448
+ for (const [k, v] of Object.entries(value)) {
449
+ const rounded = COORD_FIELD_NAMES.has(k.toLowerCase()) && depth + 1 < DEPTH_LIMIT ? roundCoordinate(v) : void 0;
450
+ out[k] = rounded ?? walk(v, depth + 1);
451
+ }
452
+ return out;
453
+ }
454
+ if (Array.isArray(value)) {
455
+ return value.map((item) => walk(item, depth + 1));
456
+ }
457
+ return value;
458
+ }
459
+ function roundMetaCoordinates(meta) {
460
+ return walk(meta, 0);
461
+ }
462
+
396
463
  // src/identity.ts
397
464
  import { createHmac } from "crypto";
398
465
 
@@ -403,10 +470,20 @@ function capCodePoints(value, max) {
403
470
  }
404
471
 
405
472
  // src/identity.ts
406
- var VENDOR_HASH_SCHEME = "v1";
473
+ var HASH_SCHEME = "h1";
474
+ var PRINCIPAL_SOURCE_ASSERTED = "asserted";
475
+ var PRINCIPAL_FORM_HASHED = "hashed";
476
+ var PRINCIPAL_FORM_RAW = "raw";
407
477
  var RAW_PRINCIPAL_ID_MAX_LEN = 128;
408
478
  var PRINCIPAL_ID_MODE_HASHED = "hashed";
409
479
  var PRINCIPAL_ID_MODE_RAW = "raw";
480
+ var FORM_BY_MODE = {
481
+ [PRINCIPAL_ID_MODE_HASHED]: PRINCIPAL_FORM_HASHED,
482
+ [PRINCIPAL_ID_MODE_RAW]: PRINCIPAL_FORM_RAW
483
+ };
484
+ var PRINCIPAL_ID_MODES = Object.keys(
485
+ FORM_BY_MODE
486
+ );
410
487
  var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
411
488
  var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
412
489
  var LONE_SURROGATE = /\p{Surrogate}/u;
@@ -417,7 +494,7 @@ function pythonStrip(value) {
417
494
  return value.replace(PYTHON_STRIP, "");
418
495
  }
419
496
  function hashPrincipalId(rawPrincipal, options) {
420
- const { tenantId, key, issuer = null, scheme } = options;
497
+ const { tenantId, key, issuer = null, scheme = HASH_SCHEME } = options;
421
498
  let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
422
499
  if (issuer !== null) {
423
500
  message += `\0${canonicalize(issuer)}`;
@@ -436,21 +513,19 @@ function normalizePrincipal(result) {
436
513
  const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
437
514
  return { principalId: candidate.principalId, issuer };
438
515
  }
439
- function principalIdFor(principal, options) {
516
+ function principalFor(principal, options) {
517
+ let id;
440
518
  if (options.mode === PRINCIPAL_ID_MODE_RAW) {
441
- return capCodePoints(principal.principalId, RAW_PRINCIPAL_ID_MAX_LEN);
442
- }
443
- if (options.key === null || options.key === void 0) return null;
444
- return hashPrincipalId(principal.principalId, {
445
- tenantId: options.tenantId,
446
- key: options.key,
447
- issuer: principal.issuer ?? null,
448
- // Unconditional: this arm has no attested rung, so every principal it
449
- // hashes is vendor-ASSERTED. A `scheme` option here would be an argument
450
- // no caller can vary — configurability for a rung the design says is not
451
- // coming to this SDK.
452
- scheme: VENDOR_HASH_SCHEME
453
- });
519
+ id = capCodePoints(principal.principalId, RAW_PRINCIPAL_ID_MAX_LEN);
520
+ } else {
521
+ if (options.key === null || options.key === void 0) return null;
522
+ id = hashPrincipalId(principal.principalId, {
523
+ tenantId: options.tenantId,
524
+ key: options.key,
525
+ issuer: principal.issuer ?? null
526
+ });
527
+ }
528
+ return { id, source: PRINCIPAL_SOURCE_ASSERTED, form: FORM_BY_MODE[options.mode] };
454
529
  }
455
530
 
456
531
  // src/integrations/mcp/llmText.ts
@@ -621,6 +696,14 @@ function extraEnvelope(extra) {
621
696
  const envelope = extra.mcpReq?.envelope;
622
697
  return envelope ?? null;
623
698
  }
699
+ function observeTransport(extra) {
700
+ try {
701
+ const carrier = extra.http?.req ?? extra.requestInfo;
702
+ return carrier ? "http" : "no-http-request";
703
+ } catch {
704
+ return "read-failed";
705
+ }
706
+ }
624
707
  function extraHeaders(extra) {
625
708
  const fromV2 = extra.http?.req?.headers;
626
709
  if (fromV2 && typeof fromV2.get === "function") return fromV2;
@@ -657,7 +740,7 @@ function warnIfIdentityCannotResolve(config) {
657
740
  if (typeof process === "undefined" || typeof process.emitWarning !== "function") return;
658
741
  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. " : "";
659
742
  process.emitWarning(
660
- `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.`
743
+ `baton: resolvePrincipal is configured but no principal HMAC key is set, so the principal 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.`
661
744
  );
662
745
  }
663
746
  var warnedPreRenameShape = false;
@@ -666,10 +749,10 @@ function warnIfPreRenameShape(result) {
666
749
  if (warnedPreRenameShape || typeof userId !== "string") return;
667
750
  warnedPreRenameShape = true;
668
751
  warn(
669
- "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."
752
+ "baton: resolvePrincipal returned { userId }, which was renamed to { principalId } in 0.3.5, so the principal is dropped from every event until the hook returns the new key."
670
753
  );
671
754
  }
672
- async function resolveCallPrincipalId(hook, call, options) {
755
+ async function resolveCallPrincipal(hook, call, options) {
673
756
  if (hook === void 0) return null;
674
757
  let result;
675
758
  try {
@@ -684,7 +767,7 @@ async function resolveCallPrincipalId(hook, call, options) {
684
767
  return null;
685
768
  }
686
769
  try {
687
- return principalIdFor(principal, {
770
+ return principalFor(principal, {
688
771
  mode: options.mode,
689
772
  tenantId: options.tenantId,
690
773
  key: options.key
@@ -778,12 +861,12 @@ function registerAnnotationTool(server, options) {
778
861
  server,
779
862
  scrubber: options.scrubber
780
863
  }) ?? UNKNOWN_AGENT_RUNTIME;
781
- const scrubbedMeta = meta ? options.scrubber(meta) : null;
864
+ const scrubbedMeta = meta ? options.scrubber(roundMetaCoordinates(meta)) : null;
782
865
  const sessionId = await resolveSessionId(options.fallbackSessionId, extra);
783
866
  if (args.signal_type === void 0) {
784
867
  options.tracker?.mark(sessionId);
785
868
  }
786
- const principalId = await resolveCallPrincipalId(
869
+ const principal = await resolveCallPrincipal(
787
870
  options.resolvePrincipal,
788
871
  { extra, toolName: name, arguments: args },
789
872
  {
@@ -802,7 +885,8 @@ function registerAnnotationTool(server, options) {
802
885
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
803
886
  consent_token: options.consentToken,
804
887
  agent_runtime: runtime,
805
- principal_id: principalId,
888
+ principal,
889
+ transport_observed: observeTransport(extra),
806
890
  runtime_meta: scrubbedMeta,
807
891
  payload: {
808
892
  // Agent-facing names -> wire keys, as with `overall_task`
@@ -1040,7 +1124,7 @@ function sealKey(dsn) {
1040
1124
 
1041
1125
  // src/integrations/mcp/config.ts
1042
1126
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1043
- var PRINCIPAL_ID_MODES = /* @__PURE__ */ new Set(["hashed", "raw"]);
1127
+ var PRINCIPAL_ID_MODE_SET = new Set(PRINCIPAL_ID_MODES);
1044
1128
  function resolveTenantId(explicit, vendorId) {
1045
1129
  if (explicit) return explicit;
1046
1130
  const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
@@ -1156,9 +1240,9 @@ function validateBatonConfig(config) {
1156
1240
  if (config.principalIdHmacKey !== void 0 && typeof config.principalIdHmacKey !== "string" && !(config.principalIdHmacKey instanceof Uint8Array)) {
1157
1241
  throw new Error("BatonConfig.principalIdHmacKey must be a string or a Uint8Array.");
1158
1242
  }
1159
- if (config.principalIdMode !== void 0 && !PRINCIPAL_ID_MODES.has(config.principalIdMode)) {
1243
+ if (config.principalIdMode !== void 0 && !PRINCIPAL_ID_MODE_SET.has(config.principalIdMode)) {
1160
1244
  throw new Error(
1161
- `BatonConfig.principalIdMode ${JSON.stringify(config.principalIdMode)} must be one of ${JSON.stringify([...PRINCIPAL_ID_MODES].sort())}.`
1245
+ `BatonConfig.principalIdMode ${JSON.stringify(config.principalIdMode)} must be one of ${JSON.stringify([...PRINCIPAL_ID_MODE_SET].sort())}.`
1162
1246
  );
1163
1247
  }
1164
1248
  }
@@ -1195,6 +1279,34 @@ var DisabledSink = class {
1195
1279
  }
1196
1280
  };
1197
1281
 
1282
+ // src/integrations/mcp/errorResult.ts
1283
+ var TOOL_ERROR_TYPE = "tool_error";
1284
+ var ERROR_BODY_MAX_CODE_POINTS = 2e3;
1285
+ function isErrorResult(value) {
1286
+ try {
1287
+ if (typeof value !== "object" || value === null) return false;
1288
+ return Boolean(value.isError);
1289
+ } catch {
1290
+ return false;
1291
+ }
1292
+ }
1293
+ function errorText(value) {
1294
+ const parts = [];
1295
+ try {
1296
+ const content = value?.content;
1297
+ if (!Array.isArray(content)) return "";
1298
+ for (const part of content) {
1299
+ const text = part?.text;
1300
+ if (typeof text !== "string") continue;
1301
+ const trimmed = text.trim();
1302
+ if (trimmed) parts.push(trimmed);
1303
+ }
1304
+ } catch {
1305
+ return "";
1306
+ }
1307
+ return parts.join("\n");
1308
+ }
1309
+
1198
1310
  // src/integrations/mcp/handle.ts
1199
1311
  var BatonHandle = class {
1200
1312
  sink;
@@ -1499,6 +1611,9 @@ var SurfaceState = class {
1499
1611
  );
1500
1612
  }
1501
1613
  };
1614
+ function errorBody(ctx, text) {
1615
+ return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
1616
+ }
1502
1617
  function batonWrap(nameRef, original, ctx) {
1503
1618
  return async (...callArgs) => {
1504
1619
  const toolName = nameRef.current;
@@ -1516,7 +1631,7 @@ function batonWrap(nameRef, original, ctx) {
1516
1631
  server: ctx.server,
1517
1632
  scrubber: ctx.scrubber
1518
1633
  }) ?? UNKNOWN_AGENT_RUNTIME;
1519
- const scrubbedMeta = meta ? ctx.scrubber(meta) : null;
1634
+ const scrubbedMeta = meta ? ctx.scrubber(roundMetaCoordinates(meta)) : null;
1520
1635
  const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1521
1636
  const dispositions = ctx.paramRegistry.get(toolName);
1522
1637
  const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions);
@@ -1531,7 +1646,7 @@ function batonWrap(nameRef, original, ctx) {
1531
1646
  const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1532
1647
  const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1533
1648
  const callId = uuidv72();
1534
- const principalId = await resolveCallPrincipalId(
1649
+ const principal = await resolveCallPrincipal(
1535
1650
  ctx.resolvePrincipal,
1536
1651
  { extra, toolName, arguments: params },
1537
1652
  { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
@@ -1542,12 +1657,18 @@ function batonWrap(nameRef, original, ctx) {
1542
1657
  session_id: sessionId,
1543
1658
  consent_token: ctx.consentToken,
1544
1659
  agent_runtime: runtime,
1545
- // The four `...common` sites below are the tool-call legs and the
1546
- // proactive annotation — the same four Python stamps
1547
- // (`middleware.py` 481/524/562/606). `surface_snapshot` is deliberately
1548
- // NOT among them: it describes the SERVER and is captured outside any
1549
- // call, so there is no caller to name (register D5).
1550
- principal_id: principalId,
1660
+ // The five `...common` sites below are the tool-call legs — start, end,
1661
+ // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
1662
+ // annotation, the same five Python stamps (`middleware.py`
1663
+ // 503/547/586/644/674; it was four until the returned shape landed
1664
+ // there too). `surface_snapshot` is deliberately NOT among them: it
1665
+ // describes the SERVER and is captured outside any call, so there is no
1666
+ // caller to name (register D5).
1667
+ principal,
1668
+ // Same five stamps, same exclusion: a surface_snapshot describes the
1669
+ // SERVER and is captured outside any call, so it has no caller's
1670
+ // transport to name any more than it has a caller to name.
1671
+ transport_observed: observeTransport(extra),
1551
1672
  runtime_meta: scrubbedMeta
1552
1673
  };
1553
1674
  if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
@@ -1600,14 +1721,46 @@ function batonWrap(nameRef, original, ctx) {
1600
1721
  payload: {
1601
1722
  tool_name: toolName,
1602
1723
  error_type: err instanceof Error ? err.constructor.name : "Error",
1603
- error_body: String(ctx.scrubber(message)).slice(0, 2e3),
1604
- duration_ms: durationMs2
1724
+ error_body: errorBody(ctx, message),
1725
+ duration_ms: durationMs2,
1726
+ // Explicit, though the field is `.optional()` and this is its
1727
+ // absent value. The schema is deliberately not an emitter (see
1728
+ // `ToolCallErrorPayloadSchema`), so if this leg stayed silent the
1729
+ // key would be missing — and Python's `tool_call_error` vector
1730
+ // carries `result: null`, so the cross-SDK key-set check in
1731
+ // `emitterConformance.test.ts` is what would say so. Each of the
1732
+ // two failure shapes declares which it is, the same reason
1733
+ // Python's emitter made the parameter positional-without-default.
1734
+ result: null
1605
1735
  }
1606
1736
  })
1607
1737
  );
1608
1738
  throw err;
1609
1739
  }
1610
1740
  const durationMs = Math.round(performance.now() - startedAt);
1741
+ if (isErrorResult(result)) {
1742
+ await emit(
1743
+ ctx.sink,
1744
+ () => ToolCallErrorEventSchema.parse({
1745
+ ...common,
1746
+ call_id: callId,
1747
+ sequence_number: ctx.counter.next(sessionId),
1748
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1749
+ payload: {
1750
+ tool_name: toolName,
1751
+ error_type: TOOL_ERROR_TYPE,
1752
+ error_body: errorBody(ctx, errorText(result)),
1753
+ duration_ms: durationMs,
1754
+ // The whole envelope. ⚠ On this producer that is the same shape
1755
+ // `tool_call_end.result` records, which is NOT what Python's
1756
+ // contrast says — `ToolCallErrorPayloadSchema` in `events.ts`
1757
+ // holds that claim and names the test that enforces it.
1758
+ result: ctx.scrubber(result)
1759
+ }
1760
+ })
1761
+ );
1762
+ return result;
1763
+ }
1611
1764
  await emit(
1612
1765
  ctx.sink,
1613
1766
  () => ToolCallEndEventSchema.parse({
@@ -1961,7 +2114,12 @@ export {
1961
2114
  DEPTH_LIMIT,
1962
2115
  EventSchema,
1963
2116
  EventTypeSchema,
2117
+ HASH_SCHEME,
1964
2118
  HttpSink,
2119
+ PRINCIPAL_FORM_HASHED,
2120
+ PRINCIPAL_FORM_RAW,
2121
+ PRINCIPAL_SOURCE_ASSERTED,
2122
+ PrincipalWireSchema,
1965
2123
  SDK_VERSION,
1966
2124
  Scrubber,
1967
2125
  StdoutSink,
@@ -1973,7 +2131,6 @@ export {
1973
2131
  ToolCallErrorPayloadSchema,
1974
2132
  ToolCallStartEventSchema,
1975
2133
  ToolCallStartPayloadSchema,
1976
- VENDOR_HASH_SCHEME,
1977
2134
  hashPrincipalId,
1978
2135
  identityScrub,
1979
2136
  safeWrite,