@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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-0.3.7";
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,7 @@ 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),
56
77
  transport_observed: z.string().nullable().default(null),
57
78
  call_id: z.string().nullable().default(null),
58
79
  runtime_meta: z.record(z.string(), z.unknown()).nullable().default(null)
@@ -449,10 +470,20 @@ function capCodePoints(value, max) {
449
470
  }
450
471
 
451
472
  // src/identity.ts
452
- 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";
453
477
  var RAW_PRINCIPAL_ID_MAX_LEN = 128;
454
478
  var PRINCIPAL_ID_MODE_HASHED = "hashed";
455
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
+ );
456
487
  var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
457
488
  var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
458
489
  var LONE_SURROGATE = /\p{Surrogate}/u;
@@ -463,7 +494,7 @@ function pythonStrip(value) {
463
494
  return value.replace(PYTHON_STRIP, "");
464
495
  }
465
496
  function hashPrincipalId(rawPrincipal, options) {
466
- const { tenantId, key, issuer = null, scheme } = options;
497
+ const { tenantId, key, issuer = null, scheme = HASH_SCHEME } = options;
467
498
  let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
468
499
  if (issuer !== null) {
469
500
  message += `\0${canonicalize(issuer)}`;
@@ -482,21 +513,19 @@ function normalizePrincipal(result) {
482
513
  const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
483
514
  return { principalId: candidate.principalId, issuer };
484
515
  }
485
- function principalIdFor(principal, options) {
516
+ function principalFor(principal, options) {
517
+ let id;
486
518
  if (options.mode === PRINCIPAL_ID_MODE_RAW) {
487
- return capCodePoints(principal.principalId, RAW_PRINCIPAL_ID_MAX_LEN);
488
- }
489
- if (options.key === null || options.key === void 0) return null;
490
- return hashPrincipalId(principal.principalId, {
491
- tenantId: options.tenantId,
492
- key: options.key,
493
- issuer: principal.issuer ?? null,
494
- // Unconditional: this arm has no attested rung, so every principal it
495
- // hashes is vendor-ASSERTED. A `scheme` option here would be an argument
496
- // no caller can vary — configurability for a rung the design says is not
497
- // coming to this SDK.
498
- scheme: VENDOR_HASH_SCHEME
499
- });
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] };
500
529
  }
501
530
 
502
531
  // src/integrations/mcp/llmText.ts
@@ -711,7 +740,7 @@ function warnIfIdentityCannotResolve(config) {
711
740
  if (typeof process === "undefined" || typeof process.emitWarning !== "function") return;
712
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. " : "";
713
742
  process.emitWarning(
714
- `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.`
715
744
  );
716
745
  }
717
746
  var warnedPreRenameShape = false;
@@ -720,10 +749,10 @@ function warnIfPreRenameShape(result) {
720
749
  if (warnedPreRenameShape || typeof userId !== "string") return;
721
750
  warnedPreRenameShape = true;
722
751
  warn(
723
- "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."
724
753
  );
725
754
  }
726
- async function resolveCallPrincipalId(hook, call, options) {
755
+ async function resolveCallPrincipal(hook, call, options) {
727
756
  if (hook === void 0) return null;
728
757
  let result;
729
758
  try {
@@ -738,7 +767,7 @@ async function resolveCallPrincipalId(hook, call, options) {
738
767
  return null;
739
768
  }
740
769
  try {
741
- return principalIdFor(principal, {
770
+ return principalFor(principal, {
742
771
  mode: options.mode,
743
772
  tenantId: options.tenantId,
744
773
  key: options.key
@@ -837,7 +866,7 @@ function registerAnnotationTool(server, options) {
837
866
  if (args.signal_type === void 0) {
838
867
  options.tracker?.mark(sessionId);
839
868
  }
840
- const principalId = await resolveCallPrincipalId(
869
+ const principal = await resolveCallPrincipal(
841
870
  options.resolvePrincipal,
842
871
  { extra, toolName: name, arguments: args },
843
872
  {
@@ -856,7 +885,7 @@ function registerAnnotationTool(server, options) {
856
885
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
857
886
  consent_token: options.consentToken,
858
887
  agent_runtime: runtime,
859
- principal_id: principalId,
888
+ principal,
860
889
  transport_observed: observeTransport(extra),
861
890
  runtime_meta: scrubbedMeta,
862
891
  payload: {
@@ -1095,7 +1124,7 @@ function sealKey(dsn) {
1095
1124
 
1096
1125
  // src/integrations/mcp/config.ts
1097
1126
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1098
- var PRINCIPAL_ID_MODES = /* @__PURE__ */ new Set(["hashed", "raw"]);
1127
+ var PRINCIPAL_ID_MODE_SET = new Set(PRINCIPAL_ID_MODES);
1099
1128
  function resolveTenantId(explicit, vendorId) {
1100
1129
  if (explicit) return explicit;
1101
1130
  const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
@@ -1211,9 +1240,9 @@ function validateBatonConfig(config) {
1211
1240
  if (config.principalIdHmacKey !== void 0 && typeof config.principalIdHmacKey !== "string" && !(config.principalIdHmacKey instanceof Uint8Array)) {
1212
1241
  throw new Error("BatonConfig.principalIdHmacKey must be a string or a Uint8Array.");
1213
1242
  }
1214
- if (config.principalIdMode !== void 0 && !PRINCIPAL_ID_MODES.has(config.principalIdMode)) {
1243
+ if (config.principalIdMode !== void 0 && !PRINCIPAL_ID_MODE_SET.has(config.principalIdMode)) {
1215
1244
  throw new Error(
1216
- `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())}.`
1217
1246
  );
1218
1247
  }
1219
1248
  }
@@ -1250,6 +1279,34 @@ var DisabledSink = class {
1250
1279
  }
1251
1280
  };
1252
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
+
1253
1310
  // src/integrations/mcp/handle.ts
1254
1311
  var BatonHandle = class {
1255
1312
  sink;
@@ -1554,6 +1611,9 @@ var SurfaceState = class {
1554
1611
  );
1555
1612
  }
1556
1613
  };
1614
+ function errorBody(ctx, text) {
1615
+ return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
1616
+ }
1557
1617
  function batonWrap(nameRef, original, ctx) {
1558
1618
  return async (...callArgs) => {
1559
1619
  const toolName = nameRef.current;
@@ -1586,7 +1646,7 @@ function batonWrap(nameRef, original, ctx) {
1586
1646
  const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
1587
1647
  const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
1588
1648
  const callId = uuidv72();
1589
- const principalId = await resolveCallPrincipalId(
1649
+ const principal = await resolveCallPrincipal(
1590
1650
  ctx.resolvePrincipal,
1591
1651
  { extra, toolName, arguments: params },
1592
1652
  { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
@@ -1597,13 +1657,15 @@ function batonWrap(nameRef, original, ctx) {
1597
1657
  session_id: sessionId,
1598
1658
  consent_token: ctx.consentToken,
1599
1659
  agent_runtime: runtime,
1600
- // The four `...common` sites below are the tool-call legs and the
1601
- // proactive annotation — the same four Python stamps
1602
- // (`middleware.py` 481/524/562/606). `surface_snapshot` is deliberately
1603
- // NOT among them: it describes the SERVER and is captured outside any
1604
- // call, so there is no caller to name (register D5).
1605
- principal_id: principalId,
1606
- // Same four stamps, same exclusion: a surface_snapshot describes the
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
1607
1669
  // SERVER and is captured outside any call, so it has no caller's
1608
1670
  // transport to name any more than it has a caller to name.
1609
1671
  transport_observed: observeTransport(extra),
@@ -1659,14 +1721,46 @@ function batonWrap(nameRef, original, ctx) {
1659
1721
  payload: {
1660
1722
  tool_name: toolName,
1661
1723
  error_type: err instanceof Error ? err.constructor.name : "Error",
1662
- error_body: String(ctx.scrubber(message)).slice(0, 2e3),
1663
- 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
1664
1735
  }
1665
1736
  })
1666
1737
  );
1667
1738
  throw err;
1668
1739
  }
1669
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
+ }
1670
1764
  await emit(
1671
1765
  ctx.sink,
1672
1766
  () => ToolCallEndEventSchema.parse({
@@ -2020,7 +2114,12 @@ export {
2020
2114
  DEPTH_LIMIT,
2021
2115
  EventSchema,
2022
2116
  EventTypeSchema,
2117
+ HASH_SCHEME,
2023
2118
  HttpSink,
2119
+ PRINCIPAL_FORM_HASHED,
2120
+ PRINCIPAL_FORM_RAW,
2121
+ PRINCIPAL_SOURCE_ASSERTED,
2122
+ PrincipalWireSchema,
2024
2123
  SDK_VERSION,
2025
2124
  Scrubber,
2026
2125
  StdoutSink,
@@ -2032,7 +2131,6 @@ export {
2032
2131
  ToolCallErrorPayloadSchema,
2033
2132
  ToolCallStartEventSchema,
2034
2133
  ToolCallStartPayloadSchema,
2035
- VENDOR_HASH_SCHEME,
2036
2134
  hashPrincipalId,
2037
2135
  identityScrub,
2038
2136
  safeWrite,