@goodtiming/baton-sdk 0.3.7 → 0.4.1

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
@@ -38,6 +38,10 @@ __export(index_exports, {
38
38
  EventSchema: () => EventSchema,
39
39
  EventTypeSchema: () => EventTypeSchema,
40
40
  HttpSink: () => HttpSink,
41
+ PRINCIPAL_FORM_HASHED: () => PRINCIPAL_FORM_HASHED,
42
+ PRINCIPAL_FORM_RAW: () => PRINCIPAL_FORM_RAW,
43
+ PRINCIPAL_SOURCE_ASSERTED: () => PRINCIPAL_SOURCE_ASSERTED,
44
+ PrincipalWireSchema: () => PrincipalWireSchema,
41
45
  SDK_VERSION: () => SDK_VERSION,
42
46
  Scrubber: () => Scrubber,
43
47
  StdoutSink: () => StdoutSink,
@@ -49,7 +53,6 @@ __export(index_exports, {
49
53
  ToolCallErrorPayloadSchema: () => ToolCallErrorPayloadSchema,
50
54
  ToolCallStartEventSchema: () => ToolCallStartEventSchema,
51
55
  ToolCallStartPayloadSchema: () => ToolCallStartPayloadSchema,
52
- VENDOR_HASH_SCHEME: () => VENDOR_HASH_SCHEME,
53
56
  hashPrincipalId: () => hashPrincipalId,
54
57
  identityScrub: () => identityScrub,
55
58
  safeWrite: () => safeWrite,
@@ -58,7 +61,7 @@ __export(index_exports, {
58
61
  module.exports = __toCommonJS(index_exports);
59
62
 
60
63
  // src/version.ts
61
- var SDK_VERSION = "ts-0.3.7";
64
+ var SDK_VERSION = "ts-0.4.1";
62
65
 
63
66
  // src/events.ts
64
67
  var import_zod = require("zod");
@@ -80,7 +83,23 @@ var ToolCallErrorPayloadSchema = import_zod.z.object({
80
83
  tool_name: import_zod.z.string(),
81
84
  error_type: import_zod.z.string(),
82
85
  error_body: import_zod.z.string(),
83
- duration_ms: import_zod.z.number().int().nullable().default(null)
86
+ duration_ms: import_zod.z.number().int().nullable().default(null),
87
+ // ⚠ `.optional()`, NOT `.default(null)` like the sibling fields — and it
88
+ // stays that way now that the producer emits the field.
89
+ //
90
+ // A default makes the schema an EMITTER: parsing a payload without the key
91
+ // ADDS it. That is wrong in a schema that also READS — a stored event from
92
+ // before the field existed would come back carrying an invented key, and
93
+ // against the pre-`f1e0280` spec pin, whose `events.schema.json` is
94
+ // `additionalProperties: false`, it reddened three tests saying so: a
95
+ // byte-identical vector round-trip, an ajv validation of TS-built events,
96
+ // and a field-for-field payload comparison.
97
+ //
98
+ // `.optional()` accepts the field when a vector carries it and stays
99
+ // silent when it does not. What makes the EMITTED shape complete is the
100
+ // emitter declaring `result` on both failure legs (`withBaton.ts`),
101
+ // explicitly `null` on a throw — not the schema filling it in.
102
+ result: import_zod.z.unknown().nullable().optional()
84
103
  }).strict();
85
104
  var AnnotationPayloadSchema = import_zod.z.object({
86
105
  intent: import_zod.z.string().nullable().default(null),
@@ -101,6 +120,11 @@ var SurfaceSnapshotPayloadSchema = import_zod.z.object({
101
120
  seam_augmentations: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).default({})
102
121
  }).strict();
103
122
  var DEFAULT_CONSENT_TOKEN = "customer-consented";
123
+ var PrincipalWireSchema = import_zod.z.object({
124
+ id: import_zod.z.string(),
125
+ source: import_zod.z.string(),
126
+ form: import_zod.z.string()
127
+ }).strict();
104
128
  var envelopeShape = {
105
129
  event_id: import_zod.z.uuid().default(() => (0, import_uuid.v7)()),
106
130
  tenant_id: import_zod.z.string(),
@@ -111,7 +135,7 @@ var envelopeShape = {
111
135
  consent_token: import_zod.z.string(),
112
136
  sdk_version: import_zod.z.string().default(SDK_VERSION),
113
137
  agent_runtime: import_zod.z.string().default("unknown"),
114
- principal_id: import_zod.z.string().nullable().default(null),
138
+ principal: PrincipalWireSchema.nullable().default(null),
115
139
  transport_observed: import_zod.z.string().nullable().default(null),
116
140
  call_id: import_zod.z.string().nullable().default(null),
117
141
  runtime_meta: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null)
@@ -508,10 +532,19 @@ function capCodePoints(value, max) {
508
532
  }
509
533
 
510
534
  // src/identity.ts
511
- var VENDOR_HASH_SCHEME = "v1";
535
+ var PRINCIPAL_SOURCE_ASSERTED = "asserted";
536
+ var PRINCIPAL_FORM_HASHED = "hashed";
537
+ var PRINCIPAL_FORM_RAW = "raw";
512
538
  var RAW_PRINCIPAL_ID_MAX_LEN = 128;
513
539
  var PRINCIPAL_ID_MODE_HASHED = "hashed";
514
540
  var PRINCIPAL_ID_MODE_RAW = "raw";
541
+ var FORM_BY_MODE = {
542
+ [PRINCIPAL_ID_MODE_HASHED]: PRINCIPAL_FORM_HASHED,
543
+ [PRINCIPAL_ID_MODE_RAW]: PRINCIPAL_FORM_RAW
544
+ };
545
+ var PRINCIPAL_ID_MODES = Object.keys(
546
+ FORM_BY_MODE
547
+ );
515
548
  var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
516
549
  var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
517
550
  var LONE_SURROGATE = /\p{Surrogate}/u;
@@ -522,14 +555,13 @@ function pythonStrip(value) {
522
555
  return value.replace(PYTHON_STRIP, "");
523
556
  }
524
557
  function hashPrincipalId(rawPrincipal, options) {
525
- const { tenantId, key, issuer = null, scheme } = options;
558
+ const { tenantId, key, issuer = null } = options;
526
559
  let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
527
560
  if (issuer !== null) {
528
561
  message += `\0${canonicalize(issuer)}`;
529
562
  }
530
563
  const keyBytes = typeof key === "string" ? Buffer.from(key, "utf8") : key;
531
- const digest = (0, import_node_crypto.createHmac)("sha256", keyBytes).update(message, "utf8").digest("hex");
532
- return `${scheme}:${digest}`;
564
+ return (0, import_node_crypto.createHmac)("sha256", keyBytes).update(message, "utf8").digest("hex");
533
565
  }
534
566
  function normalizePrincipal(result) {
535
567
  if (result === null || typeof result !== "object") return null;
@@ -541,21 +573,19 @@ function normalizePrincipal(result) {
541
573
  const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
542
574
  return { principalId: candidate.principalId, issuer };
543
575
  }
544
- function principalIdFor(principal, options) {
576
+ function principalFor(principal, options) {
577
+ let id;
545
578
  if (options.mode === PRINCIPAL_ID_MODE_RAW) {
546
- return capCodePoints(principal.principalId, RAW_PRINCIPAL_ID_MAX_LEN);
547
- }
548
- if (options.key === null || options.key === void 0) return null;
549
- return hashPrincipalId(principal.principalId, {
550
- tenantId: options.tenantId,
551
- key: options.key,
552
- issuer: principal.issuer ?? null,
553
- // Unconditional: this arm has no attested rung, so every principal it
554
- // hashes is vendor-ASSERTED. A `scheme` option here would be an argument
555
- // no caller can vary — configurability for a rung the design says is not
556
- // coming to this SDK.
557
- scheme: VENDOR_HASH_SCHEME
558
- });
579
+ id = capCodePoints(principal.principalId, RAW_PRINCIPAL_ID_MAX_LEN);
580
+ } else {
581
+ if (options.key === null || options.key === void 0) return null;
582
+ id = hashPrincipalId(principal.principalId, {
583
+ tenantId: options.tenantId,
584
+ key: options.key,
585
+ issuer: principal.issuer ?? null
586
+ });
587
+ }
588
+ return { id, source: PRINCIPAL_SOURCE_ASSERTED, form: FORM_BY_MODE[options.mode] };
559
589
  }
560
590
 
561
591
  // src/integrations/mcp/llmText.ts
@@ -770,7 +800,7 @@ function warnIfIdentityCannotResolve(config) {
770
800
  if (typeof process === "undefined" || typeof process.emitWarning !== "function") return;
771
801
  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. " : "";
772
802
  process.emitWarning(
773
- `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.`
803
+ `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.`
774
804
  );
775
805
  }
776
806
  var warnedPreRenameShape = false;
@@ -779,10 +809,10 @@ function warnIfPreRenameShape(result) {
779
809
  if (warnedPreRenameShape || typeof userId !== "string") return;
780
810
  warnedPreRenameShape = true;
781
811
  warn(
782
- "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."
812
+ "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."
783
813
  );
784
814
  }
785
- async function resolveCallPrincipalId(hook, call, options) {
815
+ async function resolveCallPrincipal(hook, call, options) {
786
816
  if (hook === void 0) return null;
787
817
  let result;
788
818
  try {
@@ -797,7 +827,7 @@ async function resolveCallPrincipalId(hook, call, options) {
797
827
  return null;
798
828
  }
799
829
  try {
800
- return principalIdFor(principal, {
830
+ return principalFor(principal, {
801
831
  mode: options.mode,
802
832
  tenantId: options.tenantId,
803
833
  key: options.key
@@ -896,7 +926,7 @@ function registerAnnotationTool(server, options) {
896
926
  if (args.signal_type === void 0) {
897
927
  options.tracker?.mark(sessionId);
898
928
  }
899
- const principalId = await resolveCallPrincipalId(
929
+ const principal = await resolveCallPrincipal(
900
930
  options.resolvePrincipal,
901
931
  { extra, toolName: name, arguments: args },
902
932
  {
@@ -915,7 +945,7 @@ function registerAnnotationTool(server, options) {
915
945
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
916
946
  consent_token: options.consentToken,
917
947
  agent_runtime: runtime,
918
- principal_id: principalId,
948
+ principal,
919
949
  transport_observed: observeTransport(extra),
920
950
  runtime_meta: scrubbedMeta,
921
951
  payload: {
@@ -1154,7 +1184,7 @@ function sealKey(dsn) {
1154
1184
 
1155
1185
  // src/integrations/mcp/config.ts
1156
1186
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1157
- var PRINCIPAL_ID_MODES = /* @__PURE__ */ new Set(["hashed", "raw"]);
1187
+ var PRINCIPAL_ID_MODE_SET = new Set(PRINCIPAL_ID_MODES);
1158
1188
  function resolveTenantId(explicit, vendorId) {
1159
1189
  if (explicit) return explicit;
1160
1190
  const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
@@ -1270,9 +1300,9 @@ function validateBatonConfig(config) {
1270
1300
  if (config.principalIdHmacKey !== void 0 && typeof config.principalIdHmacKey !== "string" && !(config.principalIdHmacKey instanceof Uint8Array)) {
1271
1301
  throw new Error("BatonConfig.principalIdHmacKey must be a string or a Uint8Array.");
1272
1302
  }
1273
- if (config.principalIdMode !== void 0 && !PRINCIPAL_ID_MODES.has(config.principalIdMode)) {
1303
+ if (config.principalIdMode !== void 0 && !PRINCIPAL_ID_MODE_SET.has(config.principalIdMode)) {
1274
1304
  throw new Error(
1275
- `BatonConfig.principalIdMode ${JSON.stringify(config.principalIdMode)} must be one of ${JSON.stringify([...PRINCIPAL_ID_MODES].sort())}.`
1305
+ `BatonConfig.principalIdMode ${JSON.stringify(config.principalIdMode)} must be one of ${JSON.stringify([...PRINCIPAL_ID_MODE_SET].sort())}.`
1276
1306
  );
1277
1307
  }
1278
1308
  }
@@ -1309,6 +1339,34 @@ var DisabledSink = class {
1309
1339
  }
1310
1340
  };
1311
1341
 
1342
+ // src/integrations/mcp/errorResult.ts
1343
+ var TOOL_ERROR_TYPE = "tool_error";
1344
+ var ERROR_BODY_MAX_CODE_POINTS = 2e3;
1345
+ function isErrorResult(value) {
1346
+ try {
1347
+ if (typeof value !== "object" || value === null) return false;
1348
+ return Boolean(value.isError);
1349
+ } catch {
1350
+ return false;
1351
+ }
1352
+ }
1353
+ function errorText(value) {
1354
+ const parts = [];
1355
+ try {
1356
+ const content = value?.content;
1357
+ if (!Array.isArray(content)) return "";
1358
+ for (const part of content) {
1359
+ const text = part?.text;
1360
+ if (typeof text !== "string") continue;
1361
+ const trimmed = text.trim();
1362
+ if (trimmed) parts.push(trimmed);
1363
+ }
1364
+ } catch {
1365
+ return "";
1366
+ }
1367
+ return parts.join("\n");
1368
+ }
1369
+
1312
1370
  // src/integrations/mcp/handle.ts
1313
1371
  var BatonHandle = class {
1314
1372
  sink;
@@ -1613,6 +1671,9 @@ var SurfaceState = class {
1613
1671
  );
1614
1672
  }
1615
1673
  };
1674
+ function errorBody(ctx, text) {
1675
+ return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
1676
+ }
1616
1677
  function batonWrap(nameRef, original, ctx) {
1617
1678
  return async (...callArgs) => {
1618
1679
  const toolName = nameRef.current;
@@ -1645,7 +1706,7 @@ function batonWrap(nameRef, original, ctx) {
1645
1706
  const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1646
1707
  const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1647
1708
  const callId = (0, import_uuid2.v7)();
1648
- const principalId = await resolveCallPrincipalId(
1709
+ const principal = await resolveCallPrincipal(
1649
1710
  ctx.resolvePrincipal,
1650
1711
  { extra, toolName, arguments: params },
1651
1712
  { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
@@ -1656,13 +1717,15 @@ function batonWrap(nameRef, original, ctx) {
1656
1717
  session_id: sessionId,
1657
1718
  consent_token: ctx.consentToken,
1658
1719
  agent_runtime: runtime,
1659
- // The four `...common` sites below are the tool-call legs and the
1660
- // proactive annotation — the same four Python stamps
1661
- // (`middleware.py` 481/524/562/606). `surface_snapshot` is deliberately
1662
- // NOT among them: it describes the SERVER and is captured outside any
1663
- // call, so there is no caller to name (register D5).
1664
- principal_id: principalId,
1665
- // Same four stamps, same exclusion: a surface_snapshot describes the
1720
+ // The five `...common` sites below are the tool-call legs — start, end,
1721
+ // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
1722
+ // annotation, the same five Python stamps (`middleware.py`
1723
+ // 503/547/586/644/674; it was four until the returned shape landed
1724
+ // there too). `surface_snapshot` is deliberately NOT among them: it
1725
+ // describes the SERVER and is captured outside any call, so there is no
1726
+ // caller to name (register D5).
1727
+ principal,
1728
+ // Same five stamps, same exclusion: a surface_snapshot describes the
1666
1729
  // SERVER and is captured outside any call, so it has no caller's
1667
1730
  // transport to name any more than it has a caller to name.
1668
1731
  transport_observed: observeTransport(extra),
@@ -1718,14 +1781,46 @@ function batonWrap(nameRef, original, ctx) {
1718
1781
  payload: {
1719
1782
  tool_name: toolName,
1720
1783
  error_type: err instanceof Error ? err.constructor.name : "Error",
1721
- error_body: String(ctx.scrubber(message)).slice(0, 2e3),
1722
- duration_ms: durationMs2
1784
+ error_body: errorBody(ctx, message),
1785
+ duration_ms: durationMs2,
1786
+ // Explicit, though the field is `.optional()` and this is its
1787
+ // absent value. The schema is deliberately not an emitter (see
1788
+ // `ToolCallErrorPayloadSchema`), so if this leg stayed silent the
1789
+ // key would be missing — and Python's `tool_call_error` vector
1790
+ // carries `result: null`, so the cross-SDK key-set check in
1791
+ // `emitterConformance.test.ts` is what would say so. Each of the
1792
+ // two failure shapes declares which it is, the same reason
1793
+ // Python's emitter made the parameter positional-without-default.
1794
+ result: null
1723
1795
  }
1724
1796
  })
1725
1797
  );
1726
1798
  throw err;
1727
1799
  }
1728
1800
  const durationMs = Math.round(performance.now() - startedAt);
1801
+ if (isErrorResult(result)) {
1802
+ await emit(
1803
+ ctx.sink,
1804
+ () => ToolCallErrorEventSchema.parse({
1805
+ ...common,
1806
+ call_id: callId,
1807
+ sequence_number: ctx.counter.next(sessionId),
1808
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1809
+ payload: {
1810
+ tool_name: toolName,
1811
+ error_type: TOOL_ERROR_TYPE,
1812
+ error_body: errorBody(ctx, errorText(result)),
1813
+ duration_ms: durationMs,
1814
+ // The whole envelope. ⚠ On this producer that is the same shape
1815
+ // `tool_call_end.result` records, which is NOT what Python's
1816
+ // contrast says — `ToolCallErrorPayloadSchema` in `events.ts`
1817
+ // holds that claim and names the test that enforces it.
1818
+ result: ctx.scrubber(result)
1819
+ }
1820
+ })
1821
+ );
1822
+ return result;
1823
+ }
1729
1824
  await emit(
1730
1825
  ctx.sink,
1731
1826
  () => ToolCallEndEventSchema.parse({
@@ -2081,6 +2176,10 @@ function withBaton(server, supplied = {}) {
2081
2176
  EventSchema,
2082
2177
  EventTypeSchema,
2083
2178
  HttpSink,
2179
+ PRINCIPAL_FORM_HASHED,
2180
+ PRINCIPAL_FORM_RAW,
2181
+ PRINCIPAL_SOURCE_ASSERTED,
2182
+ PrincipalWireSchema,
2084
2183
  SDK_VERSION,
2085
2184
  Scrubber,
2086
2185
  StdoutSink,
@@ -2092,7 +2191,6 @@ function withBaton(server, supplied = {}) {
2092
2191
  ToolCallErrorPayloadSchema,
2093
2192
  ToolCallStartEventSchema,
2094
2193
  ToolCallStartPayloadSchema,
2095
- VENDOR_HASH_SCHEME,
2096
2194
  hashPrincipalId,
2097
2195
  identityScrub,
2098
2196
  safeWrite,