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