@goodtiming/baton-sdk 0.5.6 → 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.6";
99
+ var SDK_VERSION = "ts-0.5.7";
97
100
 
98
101
  // src/events.ts
99
102
  var import_zod = require("zod");
@@ -902,6 +905,7 @@ var USER_GOAL_PARAM_NAME = "user_goal";
902
905
  var EXPECTED_RESULT_PARAM_NAME = "expected_result";
903
906
  var OVERALL_TASK_PARAM_NAME = "overall_task";
904
907
  var INTENT_SOURCE_PARAM = "injected_param";
908
+ var INTENT_SOURCE_LIBRARY = "library_arg";
905
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).";
906
910
  var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
907
911
  var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
@@ -924,6 +928,15 @@ function buildExpectedResultParamDescription(options = {}) {
924
928
  function requiredParamNames(intentParamMode) {
925
929
  return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME] : [];
926
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
+ ]);
927
940
 
928
941
  // src/integrations/mcp/annotationName.ts
929
942
  var TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
@@ -993,8 +1006,8 @@ function annotationToolNameFromServer(serverName, vendorDisplayName) {
993
1006
  }
994
1007
  return candidate;
995
1008
  }
996
- function deriveAnnotationToolName(vendorId, override) {
997
- const name = override || `${vendorId}${SUFFIX}`;
1009
+ function deriveAnnotationToolName(vendorId2, override) {
1010
+ const name = override || `${vendorId2}${SUFFIX}`;
998
1011
  if (!TOOL_NAME_PATTERN.test(name)) {
999
1012
  throw new Error(
1000
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).`
@@ -1174,19 +1187,20 @@ function declaredOnConnection(server) {
1174
1187
  return declared(holder.getClientVersion());
1175
1188
  }
1176
1189
  function observedInfo(extra, options) {
1177
- const sent = declaredOnRequest(extra) ?? declaredOnConnection(options.server);
1190
+ return cleanInfo(declaredOnRequest(extra) ?? declaredOnConnection(options.server), options.scrubber);
1191
+ }
1192
+ function cleanInfo(sent, scrubber) {
1178
1193
  const info = {};
1179
- const name = clean(sent?.name, options.scrubber, CLIENT_INFO_MAX_LEN);
1180
- 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);
1181
1196
  if (name !== void 0) info.name = name;
1182
1197
  if (version !== void 0) info.version = version;
1183
1198
  return Object.keys(info).length > 0 ? info : void 0;
1184
1199
  }
1185
- function observedHeaders(extra, options) {
1186
- const sent = extraHeaders(extra);
1200
+ function cleanHeaders(sent, scrubber) {
1187
1201
  const headers = {};
1188
1202
  for (const header of OBSERVED_HEADERS) {
1189
- const value = clean(sent?.get(header), options.scrubber, HEADER_VALUE_MAX_LEN);
1203
+ const value = clean(sent?.get(header), scrubber, HEADER_VALUE_MAX_LEN);
1190
1204
  if (value !== void 0) headers[header] = value;
1191
1205
  }
1192
1206
  return Object.keys(headers).length > 0 ? headers : void 0;
@@ -1204,12 +1218,46 @@ function orNothing(read) {
1204
1218
  return void 0;
1205
1219
  }
1206
1220
  }
1207
- function observeClient(extra, options) {
1208
- const info = orNothing(() => observedInfo(extra, options));
1209
- const headers = orNothing(() => observedHeaders(extra, options));
1221
+ function assemble(info, headers) {
1210
1222
  if (info === void 0 && headers === void 0) return null;
1211
1223
  return { ...info && { info }, ...headers && { headers } };
1212
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
+ }
1213
1261
 
1214
1262
  // src/integrations/mcp/sessionResolution.ts
1215
1263
  async function resolveSessionId(fallbackSessionId, extra) {
@@ -1387,8 +1435,8 @@ function fail(message) {
1387
1435
  throw new Error(sweep(message));
1388
1436
  }
1389
1437
  function dsnFromEnvironment() {
1390
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
1391
- return fromEnv ? fromEnv : void 0;
1438
+ const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
1439
+ return fromEnv2 ? fromEnv2 : void 0;
1392
1440
  }
1393
1441
  function selectDsn(explicit, supplied, door) {
1394
1442
  const conflicts = Object.keys(supplied).filter((name) => supplied[name]).sort();
@@ -1586,15 +1634,24 @@ function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
1586
1634
  function requestSideErrorFields(text, errorBody2) {
1587
1635
  return { error_body: errorBody2(text), result: null };
1588
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
+ }
1589
1646
 
1590
1647
  // src/integrations/mcp/config.ts
1591
1648
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1592
1649
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1593
- function resolveTenantId(explicit, vendorId) {
1650
+ function resolveTenantId(explicit, vendorId2) {
1594
1651
  if (explicit) return explicit;
1595
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
1596
- if (fromEnv) return fromEnv;
1597
- return vendorId;
1652
+ const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
1653
+ if (fromEnv2) return fromEnv2;
1654
+ return vendorId2;
1598
1655
  }
1599
1656
  function resolveBatonConfig(config) {
1600
1657
  const dsnString = selectDsn(
@@ -1770,8 +1827,8 @@ var BatonHandle = class {
1770
1827
  var SessionCounter = class {
1771
1828
  counters = /* @__PURE__ */ new Map();
1772
1829
  next(sessionId) {
1773
- const current = this.counters.get(sessionId) ?? 0;
1774
- const next = current + 1;
1830
+ const current2 = this.counters.get(sessionId) ?? 0;
1831
+ const next = current2 + 1;
1775
1832
  this.counters.set(sessionId, next);
1776
1833
  return next;
1777
1834
  }
@@ -2030,13 +2087,7 @@ var SurfaceState = class {
2030
2087
  }
2031
2088
  };
2032
2089
  function errorBody(ctx, text) {
2033
- return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
2034
- }
2035
- function errorTypeOf(err) {
2036
- return err instanceof Error ? err.constructor.name : "Error";
2037
- }
2038
- function messageOf(err) {
2039
- return err instanceof Error ? err.message : String(err);
2090
+ return scrubbedErrorBody(ctx.scrubber, text);
2040
2091
  }
2041
2092
  async function resolveEnvelopeParts(ctx, extra) {
2042
2093
  const meta = extraMeta(extra);
@@ -2798,9 +2849,9 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2798
2849
  if (memo && typeof memo === "object") delete memo[name];
2799
2850
  };
2800
2851
  const dropSubagentClause = (name) => {
2801
- const current = internals.server._instructions;
2802
- if (typeof current !== "string" || !current.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) return;
2803
- 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, "");
2804
2855
  process.stderr.write(
2805
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
2806
2857
  `
@@ -2935,16 +2986,496 @@ function principalFromOAuthEmail(context) {
2935
2986
  displayName: at > 0 ? email.slice(0, at) : null
2936
2987
  };
2937
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
+ };
2938
3467
  // Annotate the CommonJS export names for ESM import in node:
2939
3468
  0 && (module.exports = {
2940
3469
  AnnotationEventSchema,
2941
3470
  AnnotationPayloadSchema,
2942
3471
  BatonHandle,
3472
+ Client,
2943
3473
  DEFAULT_CONSENT_TOKEN,
2944
3474
  DEPTH_LIMIT,
2945
3475
  EventSchema,
2946
3476
  EventTypeSchema,
2947
3477
  HttpSink,
3478
+ INTENT_PARAMS,
2948
3479
  PRINCIPAL_FORM_HASHED,
2949
3480
  PRINCIPAL_FORM_RAW,
2950
3481
  PRINCIPAL_SOURCE_ASSERTED,
@@ -2990,6 +3521,7 @@ function principalFromOAuthEmail(context) {
2990
3521
  ToolListErrorPayloadSchema,
2991
3522
  ToolListStartEventSchema,
2992
3523
  ToolListStartPayloadSchema,
3524
+ Trace,
2993
3525
  createBaton,
2994
3526
  identityScrub,
2995
3527
  principalFromOAuthEmail,