@goodtiming/baton-sdk 0.5.5 → 0.5.7

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
@@ -33,11 +33,13 @@ __export(index_exports, {
33
33
  AnnotationEventSchema: () => AnnotationEventSchema,
34
34
  AnnotationPayloadSchema: () => AnnotationPayloadSchema,
35
35
  BatonHandle: () => BatonHandle,
36
+ Client: () => Client,
36
37
  DEFAULT_CONSENT_TOKEN: () => DEFAULT_CONSENT_TOKEN,
37
38
  DEPTH_LIMIT: () => DEPTH_LIMIT,
38
39
  EventSchema: () => EventSchema,
39
40
  EventTypeSchema: () => EventTypeSchema,
40
41
  HttpSink: () => HttpSink,
42
+ INTENT_PARAMS: () => INTENT_PARAMS,
41
43
  PRINCIPAL_FORM_HASHED: () => PRINCIPAL_FORM_HASHED,
42
44
  PRINCIPAL_FORM_RAW: () => PRINCIPAL_FORM_RAW,
43
45
  PRINCIPAL_SOURCE_ASSERTED: () => PRINCIPAL_SOURCE_ASSERTED,
@@ -83,6 +85,7 @@ __export(index_exports, {
83
85
  ToolListErrorPayloadSchema: () => ToolListErrorPayloadSchema,
84
86
  ToolListStartEventSchema: () => ToolListStartEventSchema,
85
87
  ToolListStartPayloadSchema: () => ToolListStartPayloadSchema,
88
+ Trace: () => Trace,
86
89
  createBaton: () => createBaton,
87
90
  identityScrub: () => identityScrub,
88
91
  principalFromOAuthEmail: () => principalFromOAuthEmail,
@@ -93,7 +96,7 @@ __export(index_exports, {
93
96
  module.exports = __toCommonJS(index_exports);
94
97
 
95
98
  // src/version.ts
96
- var SDK_VERSION = "ts-0.5.5";
99
+ var SDK_VERSION = "ts-0.5.7";
97
100
 
98
101
  // src/events.ts
99
102
  var import_zod = require("zod");
@@ -204,7 +207,6 @@ var AnnotationPayloadSchema = import_zod.z.object({
204
207
  workflow: import_zod.z.string().nullable().default(null),
205
208
  suggested_improvement: import_zod.z.string().nullable().default(null),
206
209
  context: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null),
207
- intent_source: import_zod.z.string().nullable().default(null),
208
210
  tool_name: import_zod.z.string().nullable().default(null)
209
211
  }).strict();
210
212
  var SurfaceSnapshotPayloadSchema = import_zod.z.object({
@@ -903,6 +905,7 @@ var USER_GOAL_PARAM_NAME = "user_goal";
903
905
  var EXPECTED_RESULT_PARAM_NAME = "expected_result";
904
906
  var OVERALL_TASK_PARAM_NAME = "overall_task";
905
907
  var INTENT_SOURCE_PARAM = "injected_param";
908
+ var INTENT_SOURCE_LIBRARY = "library_arg";
906
909
  var USER_GOAL_PARAM_BODY = "One sentence: what the user is actually trying to accomplish with this call (their goal, not a restatement of the arguments).";
907
910
  var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
908
911
  var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
@@ -925,6 +928,15 @@ function buildExpectedResultParamDescription(options = {}) {
925
928
  function requiredParamNames(intentParamMode) {
926
929
  return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME] : [];
927
930
  }
931
+ var INTENT_PARAMS = Object.freeze([
932
+ Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: "intent" }),
933
+ Object.freeze({
934
+ name: EXPECTED_RESULT_PARAM_NAME,
935
+ description: EXPECTED_RESULT_PARAM_BODY,
936
+ traceOption: "expectedOutcome"
937
+ }),
938
+ Object.freeze({ name: OVERALL_TASK_PARAM_NAME, description: OVERALL_TASK_PARAM_BODY, traceOption: "workflow" })
939
+ ]);
928
940
 
929
941
  // src/integrations/mcp/annotationName.ts
930
942
  var TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
@@ -994,8 +1006,8 @@ function annotationToolNameFromServer(serverName, vendorDisplayName) {
994
1006
  }
995
1007
  return candidate;
996
1008
  }
997
- function deriveAnnotationToolName(vendorId, override) {
998
- const name = override || `${vendorId}${SUFFIX}`;
1009
+ function deriveAnnotationToolName(vendorId2, override) {
1010
+ const name = override || `${vendorId2}${SUFFIX}`;
999
1011
  if (!TOOL_NAME_PATTERN.test(name)) {
1000
1012
  throw new Error(
1001
1013
  `Annotation tool name ${JSON.stringify(name)} violates the cross-runtime pattern ${TOOL_NAME_PATTERN.source} (Claude Desktop and others reject names with dots or other separators).`
@@ -1175,19 +1187,20 @@ function declaredOnConnection(server) {
1175
1187
  return declared(holder.getClientVersion());
1176
1188
  }
1177
1189
  function observedInfo(extra, options) {
1178
- const sent = declaredOnRequest(extra) ?? declaredOnConnection(options.server);
1190
+ return cleanInfo(declaredOnRequest(extra) ?? declaredOnConnection(options.server), options.scrubber);
1191
+ }
1192
+ function cleanInfo(sent, scrubber) {
1179
1193
  const info = {};
1180
- const name = clean(sent?.name, options.scrubber, CLIENT_INFO_MAX_LEN);
1181
- const version = clean(sent?.version, options.scrubber, CLIENT_INFO_MAX_LEN);
1194
+ const name = clean(sent?.name, scrubber, CLIENT_INFO_MAX_LEN);
1195
+ const version = clean(sent?.version, scrubber, CLIENT_INFO_MAX_LEN);
1182
1196
  if (name !== void 0) info.name = name;
1183
1197
  if (version !== void 0) info.version = version;
1184
1198
  return Object.keys(info).length > 0 ? info : void 0;
1185
1199
  }
1186
- function observedHeaders(extra, options) {
1187
- const sent = extraHeaders(extra);
1200
+ function cleanHeaders(sent, scrubber) {
1188
1201
  const headers = {};
1189
1202
  for (const header of OBSERVED_HEADERS) {
1190
- const value = clean(sent?.get(header), options.scrubber, HEADER_VALUE_MAX_LEN);
1203
+ const value = clean(sent?.get(header), scrubber, HEADER_VALUE_MAX_LEN);
1191
1204
  if (value !== void 0) headers[header] = value;
1192
1205
  }
1193
1206
  return Object.keys(headers).length > 0 ? headers : void 0;
@@ -1205,12 +1218,46 @@ function orNothing(read) {
1205
1218
  return void 0;
1206
1219
  }
1207
1220
  }
1208
- function observeClient(extra, options) {
1209
- const info = orNothing(() => observedInfo(extra, options));
1210
- const headers = orNothing(() => observedHeaders(extra, options));
1221
+ function assemble(info, headers) {
1211
1222
  if (info === void 0 && headers === void 0) return null;
1212
1223
  return { ...info && { info }, ...headers && { headers } };
1213
1224
  }
1225
+ function observeClient(extra, options) {
1226
+ return assemble(
1227
+ orNothing(() => observedInfo(extra, options)),
1228
+ orNothing(() => cleanHeaders(extraHeaders(extra), options.scrubber))
1229
+ );
1230
+ }
1231
+ function append(headers, name, value) {
1232
+ try {
1233
+ headers.append(name, value);
1234
+ } catch {
1235
+ }
1236
+ }
1237
+ function registeredHeaders(input) {
1238
+ const out = new Headers();
1239
+ if (typeof input.get === "function") {
1240
+ for (const name of OBSERVED_HEADERS) {
1241
+ const value = input.get(name);
1242
+ if (typeof value === "string") append(out, name, value);
1243
+ }
1244
+ return out;
1245
+ }
1246
+ for (const [key, value] of Object.entries(input)) {
1247
+ const name = key.toLowerCase();
1248
+ if (!OBSERVED_HEADERS.includes(name)) continue;
1249
+ for (const line of typeof value === "string" ? [value] : Array.isArray(value) ? value : []) {
1250
+ if (typeof line === "string") append(out, name, line);
1251
+ }
1252
+ }
1253
+ return out;
1254
+ }
1255
+ function clientObservedFrom(clientInfo, headers, scrubber) {
1256
+ return assemble(
1257
+ orNothing(() => cleanInfo(declared(clientInfo), scrubber)),
1258
+ orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
1259
+ );
1260
+ }
1214
1261
 
1215
1262
  // src/integrations/mcp/sessionResolution.ts
1216
1263
  async function resolveSessionId(fallbackSessionId, extra) {
@@ -1388,8 +1435,8 @@ function fail(message) {
1388
1435
  throw new Error(sweep(message));
1389
1436
  }
1390
1437
  function dsnFromEnvironment() {
1391
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
1392
- return fromEnv ? fromEnv : void 0;
1438
+ const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
1439
+ return fromEnv2 ? fromEnv2 : void 0;
1393
1440
  }
1394
1441
  function selectDsn(explicit, supplied, door) {
1395
1442
  const conflicts = Object.keys(supplied).filter((name) => supplied[name]).sort();
@@ -1587,15 +1634,24 @@ function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
1587
1634
  function requestSideErrorFields(text, errorBody2) {
1588
1635
  return { error_body: errorBody2(text), result: null };
1589
1636
  }
1637
+ function errorTypeOf(err) {
1638
+ return err instanceof Error ? err.constructor.name : "Error";
1639
+ }
1640
+ function messageOf(err) {
1641
+ return err instanceof Error ? err.message : String(err);
1642
+ }
1643
+ function scrubbedErrorBody(scrubber, text) {
1644
+ return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
1645
+ }
1590
1646
 
1591
1647
  // src/integrations/mcp/config.ts
1592
1648
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1593
1649
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1594
- function resolveTenantId(explicit, vendorId) {
1650
+ function resolveTenantId(explicit, vendorId2) {
1595
1651
  if (explicit) return explicit;
1596
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
1597
- if (fromEnv) return fromEnv;
1598
- return vendorId;
1652
+ const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
1653
+ if (fromEnv2) return fromEnv2;
1654
+ return vendorId2;
1599
1655
  }
1600
1656
  function resolveBatonConfig(config) {
1601
1657
  const dsnString = selectDsn(
@@ -1767,24 +1823,12 @@ var BatonHandle = class {
1767
1823
  }
1768
1824
  };
1769
1825
 
1770
- // src/integrations/mcp/proactiveTracker.ts
1771
- var ProactiveTracker = class {
1772
- emitted = /* @__PURE__ */ new Set();
1773
- /** Claim the session's proactive slot. Returns true exactly once per
1774
- * session (the caller should then emit); false if already claimed. */
1775
- claim(sessionId) {
1776
- if (this.emitted.has(sessionId)) return false;
1777
- this.emitted.add(sessionId);
1778
- return true;
1779
- }
1780
- };
1781
-
1782
1826
  // src/integrations/mcp/sessionCounter.ts
1783
1827
  var SessionCounter = class {
1784
1828
  counters = /* @__PURE__ */ new Map();
1785
1829
  next(sessionId) {
1786
- const current = this.counters.get(sessionId) ?? 0;
1787
- const next = current + 1;
1830
+ const current2 = this.counters.get(sessionId) ?? 0;
1831
+ const next = current2 + 1;
1788
1832
  this.counters.set(sessionId, next);
1789
1833
  return next;
1790
1834
  }
@@ -2043,13 +2087,7 @@ var SurfaceState = class {
2043
2087
  }
2044
2088
  };
2045
2089
  function errorBody(ctx, text) {
2046
- return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
2047
- }
2048
- function errorTypeOf(err) {
2049
- return err instanceof Error ? err.constructor.name : "Error";
2050
- }
2051
- function messageOf(err) {
2052
- return err instanceof Error ? err.message : String(err);
2090
+ return scrubbedErrorBody(ctx.scrubber, text);
2053
2091
  }
2054
2092
  async function resolveEnvelopeParts(ctx, extra) {
2055
2093
  const meta = extraMeta(extra);
@@ -2073,7 +2111,6 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
2073
2111
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
2074
2112
  const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);
2075
2113
  const scrubbedWorkflow = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);
2076
- const callId = uuid7();
2077
2114
  const principal = await resolveCallPrincipal(
2078
2115
  ctx.resolvePrincipal,
2079
2116
  { extra, toolName, arguments: params }
@@ -2083,36 +2120,21 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
2083
2120
  vendor_id: ctx.vendorId,
2084
2121
  session_id: sessionId,
2085
2122
  consent_token: ctx.consentToken,
2086
- // Every `...common` site is an event with a caller. `surface_snapshot`
2087
- // is deliberately not among them: it describes the SERVER and is captured
2088
- // outside any call, so it has no caller, transport or client to name.
2123
+ // Every `...common` site is an event of this call, so `call_id` rides in
2124
+ // it. `surface_snapshot` is deliberately not among them: it describes the
2125
+ // SERVER and is captured outside any call, so it has no caller, transport
2126
+ // or client to name.
2089
2127
  principal,
2090
2128
  transport_observed: observeTransport(extra),
2091
2129
  session_id_origin: origin,
2092
2130
  client_observed: observeClient(extra, ctx),
2093
- runtime_meta: scrubbedMeta
2131
+ runtime_meta: scrubbedMeta,
2132
+ call_id: uuid7()
2094
2133
  };
2095
- if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
2096
- await emit(
2097
- ctx.sink,
2098
- () => AnnotationEventSchema.parse({
2099
- ...common,
2100
- sequence_number: ctx.counter.next(sessionId),
2101
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2102
- payload: {
2103
- intent: scrubbedIntent,
2104
- expected_outcome: scrubbedExpected,
2105
- intent_source: INTENT_SOURCE_PARAM,
2106
- tool_name: toolName
2107
- }
2108
- })
2109
- );
2110
- }
2111
2134
  await emit(
2112
2135
  ctx.sink,
2113
2136
  () => ToolCallStartEventSchema.parse({
2114
2137
  ...common,
2115
- call_id: callId,
2116
2138
  sequence_number: ctx.counter.next(sessionId),
2117
2139
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2118
2140
  payload: {
@@ -2126,7 +2148,7 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
2126
2148
  }
2127
2149
  })
2128
2150
  );
2129
- return { common, callId, sessionId };
2151
+ return { common, sessionId };
2130
2152
  }
2131
2153
  function batonWrap(nameRef, original, ctx) {
2132
2154
  return async (...callArgs) => {
@@ -2135,7 +2157,7 @@ function batonWrap(nameRef, original, ctx) {
2135
2157
  if (slot) slot.innerFired = true;
2136
2158
  const extra = callArgs[callArgs.length - 1];
2137
2159
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
2138
- const { common, callId, sessionId } = await openCall(ctx, toolName, extra, params);
2160
+ const { common, sessionId } = await openCall(ctx, toolName, extra, params);
2139
2161
  const terminate = async (build, replacement) => {
2140
2162
  if (!slot) {
2141
2163
  await emit(ctx.sink, build);
@@ -2161,7 +2183,6 @@ function batonWrap(nameRef, original, ctx) {
2161
2183
  await parkFailure(
2162
2184
  () => ToolCallErrorEventSchema.parse({
2163
2185
  ...common,
2164
- call_id: callId,
2165
2186
  sequence_number: ctx.counter.next(sessionId),
2166
2187
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2167
2188
  payload: {
@@ -2197,7 +2218,6 @@ function batonWrap(nameRef, original, ctx) {
2197
2218
  await parkFailure(
2198
2219
  () => ToolCallErrorEventSchema.parse({
2199
2220
  ...common,
2200
- call_id: callId,
2201
2221
  sequence_number: ctx.counter.next(sessionId),
2202
2222
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2203
2223
  payload: {
@@ -2228,7 +2248,6 @@ function batonWrap(nameRef, original, ctx) {
2228
2248
  await parkSuccess(
2229
2249
  () => ToolCallEndEventSchema.parse({
2230
2250
  ...common,
2231
- call_id: callId,
2232
2251
  sequence_number: ctx.counter.next(sessionId),
2233
2252
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2234
2253
  payload: {
@@ -2245,7 +2264,6 @@ function batonWrap(nameRef, original, ctx) {
2245
2264
  // CALLER saw fail, which is a success the product invented.
2246
2265
  (outcome) => ToolCallErrorEventSchema.parse({
2247
2266
  ...common,
2248
- call_id: callId,
2249
2267
  sequence_number: ctx.counter.next(sessionId),
2250
2268
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2251
2269
  payload: {
@@ -2639,7 +2657,7 @@ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2639
2657
  const entry = toolEntry(toolName);
2640
2658
  if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
2641
2659
  const params = { ...request?.params?.arguments ?? {} };
2642
- const { common, callId, sessionId } = await openCall(
2660
+ const { common, sessionId } = await openCall(
2643
2661
  ctx,
2644
2662
  toolName,
2645
2663
  args[1],
@@ -2651,7 +2669,6 @@ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2651
2669
  ctx.sink,
2652
2670
  () => ToolCallErrorEventSchema.parse({
2653
2671
  ...common,
2654
- call_id: callId,
2655
2672
  sequence_number: ctx.counter.next(sessionId),
2656
2673
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2657
2674
  payload: {
@@ -2832,9 +2849,9 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2832
2849
  if (memo && typeof memo === "object") delete memo[name];
2833
2850
  };
2834
2851
  const dropSubagentClause = (name) => {
2835
- const current = internals.server._instructions;
2836
- if (typeof current !== "string" || !current.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) return;
2837
- internals.server._instructions = current.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
2852
+ const current2 = internals.server._instructions;
2853
+ if (typeof current2 !== "string" || !current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) return;
2854
+ internals.server._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
2838
2855
  process.stderr.write(
2839
2856
  `baton: tool ${JSON.stringify(name)} declares its own overall_task, so the subagent sentence was removed from the server instructions; a session that already started keeps it
2840
2857
  `
@@ -2861,7 +2878,6 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2861
2878
  return { type: "object", properties: {} };
2862
2879
  }
2863
2880
  };
2864
- const tracker = new ProactiveTracker();
2865
2881
  const ctx = {
2866
2882
  sink,
2867
2883
  counter: counter2,
@@ -2879,7 +2895,6 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2879
2895
  vendorToolJsonSchema,
2880
2896
  bustSchemaMemo,
2881
2897
  dropSubagentClause,
2882
- tracker,
2883
2898
  surfaceState,
2884
2899
  emitSurface
2885
2900
  };
@@ -2971,16 +2986,496 @@ function principalFromOAuthEmail(context) {
2971
2986
  displayName: at > 0 ? email.slice(0, at) : null
2972
2987
  };
2973
2988
  }
2989
+
2990
+ // src/library/session.ts
2991
+ var import_node_async_hooks2 = require("async_hooks");
2992
+ var TRANSPORT_LIBRARY = "library";
2993
+ var TURN_ID_META_KEY = "baton/turn_id";
2994
+ function sessionEnvelope(session) {
2995
+ return {
2996
+ session_id: session.sessionId,
2997
+ session_id_origin: session.origin,
2998
+ transport_observed: TRANSPORT_LIBRARY,
2999
+ principal: session.principal,
3000
+ client_observed: session.clientObserved,
3001
+ runtime_meta: session.turnId !== null ? { [TURN_ID_META_KEY]: session.turnId } : null
3002
+ };
3003
+ }
3004
+ function warn3(message) {
3005
+ process.stderr.write(`baton: ${message}
3006
+ `);
3007
+ }
3008
+ function vendorId(name, value) {
3009
+ const cleaned = typeof value === "string" ? pythonStrip(value) : "";
3010
+ if (cleaned !== "") return cleaned;
3011
+ if (value !== void 0 && value !== null) {
3012
+ warn3(`${name} is not a non-blank string \u2014 ignoring it.`);
3013
+ }
3014
+ return null;
3015
+ }
3016
+ function minted() {
3017
+ return { sessionId: uuid7(), origin: "minted", principal: null, clientObserved: null, turnId: null };
3018
+ }
3019
+ function wirePrincipal(value) {
3020
+ if (value === void 0 || value === null) return null;
3021
+ const principal = normalizePrincipal(value);
3022
+ if (principal === null) {
3023
+ warn3("principal was given but has no usable principalId \u2014 sending none.");
3024
+ return null;
3025
+ }
3026
+ return principalFor(
3027
+ principal,
3028
+ (form) => warn3(`principal form ${JSON.stringify(form)} is not registered \u2014 sending "raw".`)
3029
+ );
3030
+ }
3031
+ function newSession(values, scrubber, disabled) {
3032
+ const id = vendorId("sessionId", values.sessionId);
3033
+ const base = id !== null ? { sessionId: id, origin: "observed", principal: null, clientObserved: null, turnId: null } : minted();
3034
+ if (disabled) return base;
3035
+ return {
3036
+ ...base,
3037
+ principal: wirePrincipal(values.principal),
3038
+ clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber),
3039
+ turnId: vendorId("turnId", values.turnId)
3040
+ };
3041
+ }
3042
+ var current = new import_node_async_hooks2.AsyncLocalStorage();
3043
+ function runInSession(owner, session, fn) {
3044
+ return current.run({ owner, session }, fn);
3045
+ }
3046
+ function sessionForCall(owner) {
3047
+ const entry = current.getStore();
3048
+ return entry !== void 0 && entry.owner === owner ? entry.session : minted();
3049
+ }
3050
+ var lastSequence = 0;
3051
+ function nextSequence() {
3052
+ const nowMicros = Math.floor((performance.timeOrigin + performance.now()) * 1e3);
3053
+ lastSequence = Math.max(lastSequence + 1, nowMicros);
3054
+ return lastSequence;
3055
+ }
3056
+
3057
+ // src/library/client.ts
3058
+ function fromEnv(name) {
3059
+ const value = typeof process !== "undefined" ? process.env?.[name] : void 0;
3060
+ return value ? value : void 0;
3061
+ }
3062
+ function resolveConsentToken(explicit) {
3063
+ if (explicit !== void 0 && !explicit) {
3064
+ throw new Error(
3065
+ "Client consentToken was set to an empty string, and events without one MUST be rejected by the consumer per SPEC \xA72.3. Omit it to take the SDK's default."
3066
+ );
3067
+ }
3068
+ return explicit ?? fromEnv("BATON_CONSENT_TOKEN") ?? DEFAULT_CONSENT_TOKEN;
3069
+ }
3070
+ function resolveClientOptions(options) {
3071
+ const resultCaptureMode = options.resultCaptureMode ?? "full";
3072
+ if (!RESULT_CAPTURE_MODES.includes(resultCaptureMode)) {
3073
+ throw new Error(
3074
+ `Client resultCaptureMode ${JSON.stringify(resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
3075
+ );
3076
+ }
3077
+ if (options.scrubber !== void 0 && typeof options.scrubber !== "function") {
3078
+ throw new Error("Client scrubber must be a function.");
3079
+ }
3080
+ const dsnString = selectDsn(
3081
+ options.dsn,
3082
+ {
3083
+ vendorId: Boolean(options.vendorId),
3084
+ tenantId: Boolean(options.tenantId),
3085
+ sink: options.sink !== void 0
3086
+ },
3087
+ "Client"
3088
+ );
3089
+ const consentToken = resolveConsentToken(options.consentToken);
3090
+ if (dsnString !== void 0) {
3091
+ const dsn = parseDsn(dsnString);
3092
+ return {
3093
+ sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
3094
+ vendorId: dsn.vendorId,
3095
+ tenantId: dsn.tenantId,
3096
+ consentToken,
3097
+ resultCaptureMode
3098
+ };
3099
+ }
3100
+ if (options.sink === void 0) {
3101
+ throw new Error(
3102
+ "Client needs somewhere to send events: pass sink (for example new HttpSink(url, { apiKey }) or new StdoutSink()), or dsn \u2014 the packed value from /account, which builds the sink for you."
3103
+ );
3104
+ }
3105
+ const vendorId2 = options.vendorId || fromEnv("BATON_VENDOR_ID");
3106
+ if (!vendorId2) {
3107
+ throw new Error("Client needs a vendorId, or the BATON_VENDOR_ID environment variable.");
3108
+ }
3109
+ return {
3110
+ sink: options.sink,
3111
+ vendorId: vendorId2,
3112
+ tenantId: resolveTenantId(options.tenantId || void 0, vendorId2),
3113
+ consentToken,
3114
+ resultCaptureMode
3115
+ };
3116
+ }
3117
+ var hasText2 = (value) => typeof value === "string" && pythonStrip(value) !== "";
3118
+ function describeError(err) {
3119
+ let type = "Error";
3120
+ let body = "";
3121
+ try {
3122
+ type = errorTypeOf(err);
3123
+ } catch {
3124
+ }
3125
+ try {
3126
+ body = messageOf(err) || (err instanceof Error && typeof err.stack === "string" ? err.stack : "");
3127
+ } catch {
3128
+ }
3129
+ return [type, body];
3130
+ }
3131
+ function isPlainObject3(value) {
3132
+ if (typeof value !== "object" || value === null) return false;
3133
+ const proto = Object.getPrototypeOf(value);
3134
+ return proto === Object.prototype || proto === null;
3135
+ }
3136
+ function paramsOf(args) {
3137
+ if (args.length === 1 && isPlainObject3(args[0])) return args[0];
3138
+ return args.length === 0 ? {} : { args };
3139
+ }
3140
+ var Core = class {
3141
+ closed = false;
3142
+ pending = /* @__PURE__ */ new Set();
3143
+ closedWarned = false;
3144
+ sink;
3145
+ vendorId;
3146
+ tenantId;
3147
+ consentToken;
3148
+ resultCaptureMode;
3149
+ scrubber;
3150
+ disabled;
3151
+ constructor(resolved) {
3152
+ this.sink = resolved.sink;
3153
+ this.vendorId = resolved.vendorId;
3154
+ this.tenantId = resolved.tenantId;
3155
+ this.consentToken = resolved.consentToken;
3156
+ this.resultCaptureMode = resolved.resultCaptureMode;
3157
+ this.scrubber = resolved.scrubber;
3158
+ this.disabled = resolved.disabled;
3159
+ }
3160
+ /** The envelope members every event of `session` shares. Call inside a
3161
+ * build thunk, so `captured_at` is the build time. */
3162
+ envelope(session, consentToken, sequence) {
3163
+ return {
3164
+ tenant_id: this.tenantId,
3165
+ vendor_id: this.vendorId,
3166
+ ...sessionEnvelope(session),
3167
+ sequence_number: sequence,
3168
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
3169
+ consent_token: consentToken
3170
+ };
3171
+ }
3172
+ /** False when nothing may be emitted: the off switch, or a closed client. */
3173
+ live() {
3174
+ if (this.disabled) return false;
3175
+ if (!this.closed) return true;
3176
+ if (!this.closedWarned) {
3177
+ this.closedWarned = true;
3178
+ process.stderr.write("baton: Client is closed; further events are dropped.\n");
3179
+ }
3180
+ return false;
3181
+ }
3182
+ /** Never rejects. Tracked so `flush()` can wait for it. */
3183
+ emit(build) {
3184
+ const write = emit(this.sink, build).finally(() => this.pending.delete(write));
3185
+ this.pending.add(write);
3186
+ return write;
3187
+ }
3188
+ async settle() {
3189
+ while (this.pending.size > 0) await Promise.all([...this.pending]);
3190
+ }
3191
+ scrub(value, field) {
3192
+ return scrubOrNull(this.scrubber, value, field);
3193
+ }
3194
+ annotate(session, consentToken, options) {
3195
+ if (!this.live()) return Promise.resolve();
3196
+ const sequence = nextSequence();
3197
+ const text = (value) => value === void 0 ? null : this.scrubber(value);
3198
+ return this.emit(
3199
+ () => AnnotationEventSchema.parse({
3200
+ ...this.envelope(session, consentToken, sequence),
3201
+ payload: {
3202
+ intent: text(options.intent),
3203
+ expected_outcome: text(options.expectedOutcome),
3204
+ what_happened: hasText2(options.whatHappened) ? text(options.whatHappened) : null,
3205
+ tool_name: options.toolName ? text(options.toolName) : options.toolName ?? null,
3206
+ workflow: text(options.workflow),
3207
+ suggested_improvement: text(options.suggestedImprovement),
3208
+ context: options.context && Object.keys(options.context).length > 0 ? this.scrub(options.context, "context") : null
3209
+ }
3210
+ })
3211
+ );
3212
+ }
3213
+ };
3214
+ var UNSET = /* @__PURE__ */ Symbol("unset");
3215
+ var WITHHELD_RESULT = /* @__PURE__ */ Symbol("withheld");
3216
+ var SCRUB_FAILED = /* @__PURE__ */ Symbol("scrubFailed");
3217
+ var runTrace;
3218
+ var Trace = class _Trace {
3219
+ #core;
3220
+ #session;
3221
+ #options;
3222
+ #consentToken;
3223
+ #callId = uuid7();
3224
+ #startedAt = 0;
3225
+ #result = UNSET;
3226
+ #error = null;
3227
+ #observedWarned = false;
3228
+ constructor(core, session, options) {
3229
+ this.#core = core;
3230
+ this.#session = session;
3231
+ this.#options = options;
3232
+ this.#consentToken = options.consentToken || core.consentToken;
3233
+ }
3234
+ /** The session this call's events carry. */
3235
+ get sessionId() {
3236
+ return this.#session.sessionId;
3237
+ }
3238
+ /** Record the outcome. Without a call, the callback's return value is the
3239
+ * result. `observed(undefined, { error })` records a failure the callback
3240
+ * caught and did not rethrow. The last call wins. */
3241
+ observed(result, failure) {
3242
+ if ((this.#result !== UNSET || this.#error !== null) && !this.#observedWarned) {
3243
+ this.#observedWarned = true;
3244
+ process.stderr.write("baton: Trace.observed() called more than once; the last call wins.\n");
3245
+ }
3246
+ this.#result = UNSET;
3247
+ this.#error = null;
3248
+ if (this.#core.disabled) return this;
3249
+ let errorType = failure?.errorType;
3250
+ let errorBody2 = failure?.errorBody;
3251
+ if (failure?.error !== void 0) {
3252
+ const [derivedType, derivedBody] = describeError(failure.error);
3253
+ errorType ||= derivedType;
3254
+ errorBody2 ||= derivedBody;
3255
+ }
3256
+ if (errorType !== void 0 || errorBody2 !== void 0) {
3257
+ this.#error = { type: errorType || "Error", body: errorBody2 ?? "" };
3258
+ } else if (this.#core.resultCaptureMode === WITHHELD) {
3259
+ this.#result = WITHHELD_RESULT;
3260
+ } else {
3261
+ try {
3262
+ this.#result = this.#core.scrubber(result);
3263
+ } catch (err) {
3264
+ process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${String(err)}
3265
+ `);
3266
+ this.#result = SCRUB_FAILED;
3267
+ }
3268
+ }
3269
+ return this;
3270
+ }
3271
+ /** Report on this call, in its session. */
3272
+ annotate(options) {
3273
+ return this.#core.annotate(this.#session, this.#consentToken, options);
3274
+ }
3275
+ #envelope(sequence) {
3276
+ return { ...this.#core.envelope(this.#session, this.#consentToken, sequence), call_id: this.#callId };
3277
+ }
3278
+ #durationMs() {
3279
+ return Math.trunc(performance.now() - this.#startedAt);
3280
+ }
3281
+ #start() {
3282
+ this.#startedAt = performance.now();
3283
+ if (!this.#core.live()) return;
3284
+ const sequence = nextSequence();
3285
+ const o = this.#options;
3286
+ const params = o.params === void 0 ? {} : this.#core.scrub(o.params, "params") ?? {};
3287
+ const textOf = (value, field) => {
3288
+ const scrubbed = value === void 0 ? null : this.#core.scrub(value, field);
3289
+ return typeof scrubbed === "string" ? scrubbed : null;
3290
+ };
3291
+ const intent = textOf(o.intent, "intent");
3292
+ const expected = textOf(o.expectedOutcome, "expected_outcome");
3293
+ const workflow = textOf(o.workflow, "workflow");
3294
+ const stated = [intent, expected, workflow].some(hasText2);
3295
+ void this.#core.emit(
3296
+ () => ToolCallStartEventSchema.parse({
3297
+ ...this.#envelope(sequence),
3298
+ payload: {
3299
+ tool_name: o.toolName,
3300
+ params,
3301
+ call_intent: intent,
3302
+ call_expected: expected,
3303
+ call_workflow: workflow,
3304
+ intent_source: stated ? INTENT_SOURCE_LIBRARY : null
3305
+ }
3306
+ })
3307
+ );
3308
+ }
3309
+ #end(value) {
3310
+ const durationMs = this.#durationMs();
3311
+ if (!this.#core.live()) return;
3312
+ if (this.#result === UNSET && this.#error === null) this.observed(value);
3313
+ const sequence = nextSequence();
3314
+ const error = this.#error;
3315
+ if (error !== null) {
3316
+ this.#emitError(sequence, error.type, error.body, durationMs);
3317
+ return;
3318
+ }
3319
+ const result = this.#result;
3320
+ void this.#core.emit(() => {
3321
+ if (result === SCRUB_FAILED) throw new Error("the scrubber threw on this result");
3322
+ return ToolCallEndEventSchema.parse({
3323
+ ...this.#envelope(sequence),
3324
+ payload: {
3325
+ tool_name: this.#options.toolName,
3326
+ duration_ms: durationMs,
3327
+ ...result === WITHHELD_RESULT ? { result: null, result_capture: WITHHELD } : { result }
3328
+ }
3329
+ });
3330
+ });
3331
+ }
3332
+ #fail(err) {
3333
+ const durationMs = this.#durationMs();
3334
+ if (!this.#core.live()) return;
3335
+ this.#emitError(nextSequence(), ...describeError(err), durationMs);
3336
+ }
3337
+ #emitError(sequence, type, body, durationMs) {
3338
+ void this.#core.emit(
3339
+ () => ToolCallErrorEventSchema.parse({
3340
+ ...this.#envelope(sequence),
3341
+ payload: {
3342
+ tool_name: this.#options.toolName,
3343
+ error_type: type,
3344
+ error_body: scrubbedErrorBody(this.#core.scrubber, body),
3345
+ duration_ms: durationMs,
3346
+ result: null
3347
+ }
3348
+ })
3349
+ );
3350
+ }
3351
+ static {
3352
+ runTrace = (core, session, options, fn) => {
3353
+ const trace = new _Trace(core, session, options);
3354
+ trace.#start();
3355
+ let value;
3356
+ try {
3357
+ value = fn(trace);
3358
+ } catch (err) {
3359
+ trace.#fail(err);
3360
+ throw err;
3361
+ }
3362
+ if (!isThenable(value)) {
3363
+ trace.#end(value);
3364
+ return value;
3365
+ }
3366
+ return Promise.resolve(value).then(
3367
+ (resolved) => {
3368
+ trace.#end(resolved);
3369
+ return resolved;
3370
+ },
3371
+ (err) => {
3372
+ trace.#fail(err);
3373
+ throw err;
3374
+ }
3375
+ );
3376
+ };
3377
+ }
3378
+ };
3379
+ var Client = class {
3380
+ #core;
3381
+ #closing;
3382
+ constructor(options = {}) {
3383
+ const switchName = captureDisabled();
3384
+ let resolved;
3385
+ if (switchName !== null) {
3386
+ logDisabled(switchName, "Client");
3387
+ resolved = {
3388
+ sink: options.sink ?? new DisabledSink(),
3389
+ vendorId: "",
3390
+ tenantId: "",
3391
+ consentToken: DEFAULT_CONSENT_TOKEN,
3392
+ resultCaptureMode: "full"
3393
+ };
3394
+ } else {
3395
+ resolved = resolveClientOptions(options);
3396
+ }
3397
+ this.#core = new Core({
3398
+ ...resolved,
3399
+ scrubber: options.scrubber ?? new Scrubber().scrub,
3400
+ disabled: switchName !== null
3401
+ });
3402
+ }
3403
+ /** Run `fn` with one session, principal, client and turn for every
3404
+ * `trace()` and `annotate()` inside it, including after its awaits. Open
3405
+ * one per request or conversation. Returns what `fn` returns. */
3406
+ session(options, fn) {
3407
+ let block;
3408
+ try {
3409
+ block = newSession(options, this.#core.scrubber, this.#core.disabled);
3410
+ } catch (err) {
3411
+ process.stderr.write(`baton: session values could not be read; using a minted session: ${String(err)}
3412
+ `);
3413
+ block = newSession({}, this.#core.scrubber, this.#core.disabled);
3414
+ }
3415
+ return runInSession(this, block, fn);
3416
+ }
3417
+ /** Run `fn` as one traced tool call and return what it returns. When `fn`
3418
+ * returns a promise or other thenable, the call ends when it settles, and
3419
+ * what comes back is a new native Promise of the same value: `then` is
3420
+ * called exactly once, so a lazy query builder is not run twice. A throw or
3421
+ * rejection is recorded and passed on unchanged. */
3422
+ trace(options, fn) {
3423
+ return runTrace(this.#core, sessionForCall(this), options ?? {}, fn);
3424
+ }
3425
+ /** `fn`, traced on every call. A single plain-object argument is sent as
3426
+ * `params`, as an MCP tool's arguments are; other arguments as
3427
+ * `{ args: [...] }`, unless `options.params` is given. */
3428
+ wrap(options, fn) {
3429
+ const base = typeof options === "string" ? { toolName: options } : options ?? {};
3430
+ const client = this;
3431
+ return function(...args) {
3432
+ return client.trace({ ...base, params: base.params ?? paramsOf(args) }, () => fn.apply(this, args));
3433
+ };
3434
+ }
3435
+ /** Emit an annotation in the open `session()` block, or in a session of its
3436
+ * own outside one. To report on a traced call, use `trace.annotate()`. */
3437
+ annotate(options) {
3438
+ const given = options ?? {};
3439
+ return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);
3440
+ }
3441
+ /** Wait until every event so far has reached the sink and the sink has flushed. */
3442
+ async flush() {
3443
+ await this.#core.settle();
3444
+ try {
3445
+ await this.#core.sink.flush();
3446
+ } catch (err) {
3447
+ process.stderr.write(`baton: sink.flush failed: ${String(err)}
3448
+ `);
3449
+ }
3450
+ }
3451
+ /** Flush, then close the sink. Later events are dropped. */
3452
+ aclose() {
3453
+ this.#closing ??= this.#close();
3454
+ return this.#closing;
3455
+ }
3456
+ async #close() {
3457
+ await this.#core.settle();
3458
+ this.#core.closed = true;
3459
+ try {
3460
+ await this.#core.sink.aclose();
3461
+ } catch (err) {
3462
+ process.stderr.write(`baton: sink.aclose failed: ${String(err)}
3463
+ `);
3464
+ }
3465
+ }
3466
+ };
2974
3467
  // Annotate the CommonJS export names for ESM import in node:
2975
3468
  0 && (module.exports = {
2976
3469
  AnnotationEventSchema,
2977
3470
  AnnotationPayloadSchema,
2978
3471
  BatonHandle,
3472
+ Client,
2979
3473
  DEFAULT_CONSENT_TOKEN,
2980
3474
  DEPTH_LIMIT,
2981
3475
  EventSchema,
2982
3476
  EventTypeSchema,
2983
3477
  HttpSink,
3478
+ INTENT_PARAMS,
2984
3479
  PRINCIPAL_FORM_HASHED,
2985
3480
  PRINCIPAL_FORM_RAW,
2986
3481
  PRINCIPAL_SOURCE_ASSERTED,
@@ -3026,6 +3521,7 @@ function principalFromOAuthEmail(context) {
3026
3521
  ToolListErrorPayloadSchema,
3027
3522
  ToolListStartEventSchema,
3028
3523
  ToolListStartPayloadSchema,
3524
+ Trace,
3029
3525
  createBaton,
3030
3526
  identityScrub,
3031
3527
  principalFromOAuthEmail,