@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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-0.5.6";
2
+ var SDK_VERSION = "ts-0.5.7";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
@@ -808,6 +808,7 @@ var USER_GOAL_PARAM_NAME = "user_goal";
808
808
  var EXPECTED_RESULT_PARAM_NAME = "expected_result";
809
809
  var OVERALL_TASK_PARAM_NAME = "overall_task";
810
810
  var INTENT_SOURCE_PARAM = "injected_param";
811
+ var INTENT_SOURCE_LIBRARY = "library_arg";
811
812
  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).";
812
813
  var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
813
814
  var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
@@ -830,6 +831,15 @@ function buildExpectedResultParamDescription(options = {}) {
830
831
  function requiredParamNames(intentParamMode) {
831
832
  return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME] : [];
832
833
  }
834
+ var INTENT_PARAMS = Object.freeze([
835
+ Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: "intent" }),
836
+ Object.freeze({
837
+ name: EXPECTED_RESULT_PARAM_NAME,
838
+ description: EXPECTED_RESULT_PARAM_BODY,
839
+ traceOption: "expectedOutcome"
840
+ }),
841
+ Object.freeze({ name: OVERALL_TASK_PARAM_NAME, description: OVERALL_TASK_PARAM_BODY, traceOption: "workflow" })
842
+ ]);
833
843
 
834
844
  // src/integrations/mcp/annotationName.ts
835
845
  var TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
@@ -899,8 +909,8 @@ function annotationToolNameFromServer(serverName, vendorDisplayName) {
899
909
  }
900
910
  return candidate;
901
911
  }
902
- function deriveAnnotationToolName(vendorId, override) {
903
- const name = override || `${vendorId}${SUFFIX}`;
912
+ function deriveAnnotationToolName(vendorId2, override) {
913
+ const name = override || `${vendorId2}${SUFFIX}`;
904
914
  if (!TOOL_NAME_PATTERN.test(name)) {
905
915
  throw new Error(
906
916
  `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).`
@@ -1080,19 +1090,20 @@ function declaredOnConnection(server) {
1080
1090
  return declared(holder.getClientVersion());
1081
1091
  }
1082
1092
  function observedInfo(extra, options) {
1083
- const sent = declaredOnRequest(extra) ?? declaredOnConnection(options.server);
1093
+ return cleanInfo(declaredOnRequest(extra) ?? declaredOnConnection(options.server), options.scrubber);
1094
+ }
1095
+ function cleanInfo(sent, scrubber) {
1084
1096
  const info = {};
1085
- const name = clean(sent?.name, options.scrubber, CLIENT_INFO_MAX_LEN);
1086
- const version = clean(sent?.version, options.scrubber, CLIENT_INFO_MAX_LEN);
1097
+ const name = clean(sent?.name, scrubber, CLIENT_INFO_MAX_LEN);
1098
+ const version = clean(sent?.version, scrubber, CLIENT_INFO_MAX_LEN);
1087
1099
  if (name !== void 0) info.name = name;
1088
1100
  if (version !== void 0) info.version = version;
1089
1101
  return Object.keys(info).length > 0 ? info : void 0;
1090
1102
  }
1091
- function observedHeaders(extra, options) {
1092
- const sent = extraHeaders(extra);
1103
+ function cleanHeaders(sent, scrubber) {
1093
1104
  const headers = {};
1094
1105
  for (const header of OBSERVED_HEADERS) {
1095
- const value = clean(sent?.get(header), options.scrubber, HEADER_VALUE_MAX_LEN);
1106
+ const value = clean(sent?.get(header), scrubber, HEADER_VALUE_MAX_LEN);
1096
1107
  if (value !== void 0) headers[header] = value;
1097
1108
  }
1098
1109
  return Object.keys(headers).length > 0 ? headers : void 0;
@@ -1110,12 +1121,46 @@ function orNothing(read) {
1110
1121
  return void 0;
1111
1122
  }
1112
1123
  }
1113
- function observeClient(extra, options) {
1114
- const info = orNothing(() => observedInfo(extra, options));
1115
- const headers = orNothing(() => observedHeaders(extra, options));
1124
+ function assemble(info, headers) {
1116
1125
  if (info === void 0 && headers === void 0) return null;
1117
1126
  return { ...info && { info }, ...headers && { headers } };
1118
1127
  }
1128
+ function observeClient(extra, options) {
1129
+ return assemble(
1130
+ orNothing(() => observedInfo(extra, options)),
1131
+ orNothing(() => cleanHeaders(extraHeaders(extra), options.scrubber))
1132
+ );
1133
+ }
1134
+ function append(headers, name, value) {
1135
+ try {
1136
+ headers.append(name, value);
1137
+ } catch {
1138
+ }
1139
+ }
1140
+ function registeredHeaders(input) {
1141
+ const out = new Headers();
1142
+ if (typeof input.get === "function") {
1143
+ for (const name of OBSERVED_HEADERS) {
1144
+ const value = input.get(name);
1145
+ if (typeof value === "string") append(out, name, value);
1146
+ }
1147
+ return out;
1148
+ }
1149
+ for (const [key, value] of Object.entries(input)) {
1150
+ const name = key.toLowerCase();
1151
+ if (!OBSERVED_HEADERS.includes(name)) continue;
1152
+ for (const line of typeof value === "string" ? [value] : Array.isArray(value) ? value : []) {
1153
+ if (typeof line === "string") append(out, name, line);
1154
+ }
1155
+ }
1156
+ return out;
1157
+ }
1158
+ function clientObservedFrom(clientInfo, headers, scrubber) {
1159
+ return assemble(
1160
+ orNothing(() => cleanInfo(declared(clientInfo), scrubber)),
1161
+ orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
1162
+ );
1163
+ }
1119
1164
 
1120
1165
  // src/integrations/mcp/sessionResolution.ts
1121
1166
  async function resolveSessionId(fallbackSessionId, extra) {
@@ -1293,8 +1338,8 @@ function fail(message) {
1293
1338
  throw new Error(sweep(message));
1294
1339
  }
1295
1340
  function dsnFromEnvironment() {
1296
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
1297
- return fromEnv ? fromEnv : void 0;
1341
+ const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
1342
+ return fromEnv2 ? fromEnv2 : void 0;
1298
1343
  }
1299
1344
  function selectDsn(explicit, supplied, door) {
1300
1345
  const conflicts = Object.keys(supplied).filter((name) => supplied[name]).sort();
@@ -1492,15 +1537,24 @@ function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
1492
1537
  function requestSideErrorFields(text, errorBody2) {
1493
1538
  return { error_body: errorBody2(text), result: null };
1494
1539
  }
1540
+ function errorTypeOf(err) {
1541
+ return err instanceof Error ? err.constructor.name : "Error";
1542
+ }
1543
+ function messageOf(err) {
1544
+ return err instanceof Error ? err.message : String(err);
1545
+ }
1546
+ function scrubbedErrorBody(scrubber, text) {
1547
+ return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
1548
+ }
1495
1549
 
1496
1550
  // src/integrations/mcp/config.ts
1497
1551
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1498
1552
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1499
- function resolveTenantId(explicit, vendorId) {
1553
+ function resolveTenantId(explicit, vendorId2) {
1500
1554
  if (explicit) return explicit;
1501
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
1502
- if (fromEnv) return fromEnv;
1503
- return vendorId;
1555
+ const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
1556
+ if (fromEnv2) return fromEnv2;
1557
+ return vendorId2;
1504
1558
  }
1505
1559
  function resolveBatonConfig(config) {
1506
1560
  const dsnString = selectDsn(
@@ -1676,8 +1730,8 @@ var BatonHandle = class {
1676
1730
  var SessionCounter = class {
1677
1731
  counters = /* @__PURE__ */ new Map();
1678
1732
  next(sessionId) {
1679
- const current = this.counters.get(sessionId) ?? 0;
1680
- const next = current + 1;
1733
+ const current2 = this.counters.get(sessionId) ?? 0;
1734
+ const next = current2 + 1;
1681
1735
  this.counters.set(sessionId, next);
1682
1736
  return next;
1683
1737
  }
@@ -1936,13 +1990,7 @@ var SurfaceState = class {
1936
1990
  }
1937
1991
  };
1938
1992
  function errorBody(ctx, text) {
1939
- return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
1940
- }
1941
- function errorTypeOf(err) {
1942
- return err instanceof Error ? err.constructor.name : "Error";
1943
- }
1944
- function messageOf(err) {
1945
- return err instanceof Error ? err.message : String(err);
1993
+ return scrubbedErrorBody(ctx.scrubber, text);
1946
1994
  }
1947
1995
  async function resolveEnvelopeParts(ctx, extra) {
1948
1996
  const meta = extraMeta(extra);
@@ -2704,9 +2752,9 @@ function install(server, supplied, resolved, emittedSurfaceHashes) {
2704
2752
  if (memo && typeof memo === "object") delete memo[name];
2705
2753
  };
2706
2754
  const dropSubagentClause = (name) => {
2707
- const current = internals.server._instructions;
2708
- if (typeof current !== "string" || !current.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) return;
2709
- internals.server._instructions = current.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
2755
+ const current2 = internals.server._instructions;
2756
+ if (typeof current2 !== "string" || !current2.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) return;
2757
+ internals.server._instructions = current2.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
2710
2758
  process.stderr.write(
2711
2759
  `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
2712
2760
  `
@@ -2841,15 +2889,495 @@ function principalFromOAuthEmail(context) {
2841
2889
  displayName: at > 0 ? email.slice(0, at) : null
2842
2890
  };
2843
2891
  }
2892
+
2893
+ // src/library/session.ts
2894
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2895
+ var TRANSPORT_LIBRARY = "library";
2896
+ var TURN_ID_META_KEY = "baton/turn_id";
2897
+ function sessionEnvelope(session) {
2898
+ return {
2899
+ session_id: session.sessionId,
2900
+ session_id_origin: session.origin,
2901
+ transport_observed: TRANSPORT_LIBRARY,
2902
+ principal: session.principal,
2903
+ client_observed: session.clientObserved,
2904
+ runtime_meta: session.turnId !== null ? { [TURN_ID_META_KEY]: session.turnId } : null
2905
+ };
2906
+ }
2907
+ function warn3(message) {
2908
+ process.stderr.write(`baton: ${message}
2909
+ `);
2910
+ }
2911
+ function vendorId(name, value) {
2912
+ const cleaned = typeof value === "string" ? pythonStrip(value) : "";
2913
+ if (cleaned !== "") return cleaned;
2914
+ if (value !== void 0 && value !== null) {
2915
+ warn3(`${name} is not a non-blank string \u2014 ignoring it.`);
2916
+ }
2917
+ return null;
2918
+ }
2919
+ function minted() {
2920
+ return { sessionId: uuid7(), origin: "minted", principal: null, clientObserved: null, turnId: null };
2921
+ }
2922
+ function wirePrincipal(value) {
2923
+ if (value === void 0 || value === null) return null;
2924
+ const principal = normalizePrincipal(value);
2925
+ if (principal === null) {
2926
+ warn3("principal was given but has no usable principalId \u2014 sending none.");
2927
+ return null;
2928
+ }
2929
+ return principalFor(
2930
+ principal,
2931
+ (form) => warn3(`principal form ${JSON.stringify(form)} is not registered \u2014 sending "raw".`)
2932
+ );
2933
+ }
2934
+ function newSession(values, scrubber, disabled) {
2935
+ const id = vendorId("sessionId", values.sessionId);
2936
+ const base = id !== null ? { sessionId: id, origin: "observed", principal: null, clientObserved: null, turnId: null } : minted();
2937
+ if (disabled) return base;
2938
+ return {
2939
+ ...base,
2940
+ principal: wirePrincipal(values.principal),
2941
+ clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber),
2942
+ turnId: vendorId("turnId", values.turnId)
2943
+ };
2944
+ }
2945
+ var current = new AsyncLocalStorage2();
2946
+ function runInSession(owner, session, fn) {
2947
+ return current.run({ owner, session }, fn);
2948
+ }
2949
+ function sessionForCall(owner) {
2950
+ const entry = current.getStore();
2951
+ return entry !== void 0 && entry.owner === owner ? entry.session : minted();
2952
+ }
2953
+ var lastSequence = 0;
2954
+ function nextSequence() {
2955
+ const nowMicros = Math.floor((performance.timeOrigin + performance.now()) * 1e3);
2956
+ lastSequence = Math.max(lastSequence + 1, nowMicros);
2957
+ return lastSequence;
2958
+ }
2959
+
2960
+ // src/library/client.ts
2961
+ function fromEnv(name) {
2962
+ const value = typeof process !== "undefined" ? process.env?.[name] : void 0;
2963
+ return value ? value : void 0;
2964
+ }
2965
+ function resolveConsentToken(explicit) {
2966
+ if (explicit !== void 0 && !explicit) {
2967
+ throw new Error(
2968
+ "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."
2969
+ );
2970
+ }
2971
+ return explicit ?? fromEnv("BATON_CONSENT_TOKEN") ?? DEFAULT_CONSENT_TOKEN;
2972
+ }
2973
+ function resolveClientOptions(options) {
2974
+ const resultCaptureMode = options.resultCaptureMode ?? "full";
2975
+ if (!RESULT_CAPTURE_MODES.includes(resultCaptureMode)) {
2976
+ throw new Error(
2977
+ `Client resultCaptureMode ${JSON.stringify(resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
2978
+ );
2979
+ }
2980
+ if (options.scrubber !== void 0 && typeof options.scrubber !== "function") {
2981
+ throw new Error("Client scrubber must be a function.");
2982
+ }
2983
+ const dsnString = selectDsn(
2984
+ options.dsn,
2985
+ {
2986
+ vendorId: Boolean(options.vendorId),
2987
+ tenantId: Boolean(options.tenantId),
2988
+ sink: options.sink !== void 0
2989
+ },
2990
+ "Client"
2991
+ );
2992
+ const consentToken = resolveConsentToken(options.consentToken);
2993
+ if (dsnString !== void 0) {
2994
+ const dsn = parseDsn(dsnString);
2995
+ return {
2996
+ sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
2997
+ vendorId: dsn.vendorId,
2998
+ tenantId: dsn.tenantId,
2999
+ consentToken,
3000
+ resultCaptureMode
3001
+ };
3002
+ }
3003
+ if (options.sink === void 0) {
3004
+ throw new Error(
3005
+ "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."
3006
+ );
3007
+ }
3008
+ const vendorId2 = options.vendorId || fromEnv("BATON_VENDOR_ID");
3009
+ if (!vendorId2) {
3010
+ throw new Error("Client needs a vendorId, or the BATON_VENDOR_ID environment variable.");
3011
+ }
3012
+ return {
3013
+ sink: options.sink,
3014
+ vendorId: vendorId2,
3015
+ tenantId: resolveTenantId(options.tenantId || void 0, vendorId2),
3016
+ consentToken,
3017
+ resultCaptureMode
3018
+ };
3019
+ }
3020
+ var hasText2 = (value) => typeof value === "string" && pythonStrip(value) !== "";
3021
+ function describeError(err) {
3022
+ let type = "Error";
3023
+ let body = "";
3024
+ try {
3025
+ type = errorTypeOf(err);
3026
+ } catch {
3027
+ }
3028
+ try {
3029
+ body = messageOf(err) || (err instanceof Error && typeof err.stack === "string" ? err.stack : "");
3030
+ } catch {
3031
+ }
3032
+ return [type, body];
3033
+ }
3034
+ function isPlainObject3(value) {
3035
+ if (typeof value !== "object" || value === null) return false;
3036
+ const proto = Object.getPrototypeOf(value);
3037
+ return proto === Object.prototype || proto === null;
3038
+ }
3039
+ function paramsOf(args) {
3040
+ if (args.length === 1 && isPlainObject3(args[0])) return args[0];
3041
+ return args.length === 0 ? {} : { args };
3042
+ }
3043
+ var Core = class {
3044
+ closed = false;
3045
+ pending = /* @__PURE__ */ new Set();
3046
+ closedWarned = false;
3047
+ sink;
3048
+ vendorId;
3049
+ tenantId;
3050
+ consentToken;
3051
+ resultCaptureMode;
3052
+ scrubber;
3053
+ disabled;
3054
+ constructor(resolved) {
3055
+ this.sink = resolved.sink;
3056
+ this.vendorId = resolved.vendorId;
3057
+ this.tenantId = resolved.tenantId;
3058
+ this.consentToken = resolved.consentToken;
3059
+ this.resultCaptureMode = resolved.resultCaptureMode;
3060
+ this.scrubber = resolved.scrubber;
3061
+ this.disabled = resolved.disabled;
3062
+ }
3063
+ /** The envelope members every event of `session` shares. Call inside a
3064
+ * build thunk, so `captured_at` is the build time. */
3065
+ envelope(session, consentToken, sequence) {
3066
+ return {
3067
+ tenant_id: this.tenantId,
3068
+ vendor_id: this.vendorId,
3069
+ ...sessionEnvelope(session),
3070
+ sequence_number: sequence,
3071
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
3072
+ consent_token: consentToken
3073
+ };
3074
+ }
3075
+ /** False when nothing may be emitted: the off switch, or a closed client. */
3076
+ live() {
3077
+ if (this.disabled) return false;
3078
+ if (!this.closed) return true;
3079
+ if (!this.closedWarned) {
3080
+ this.closedWarned = true;
3081
+ process.stderr.write("baton: Client is closed; further events are dropped.\n");
3082
+ }
3083
+ return false;
3084
+ }
3085
+ /** Never rejects. Tracked so `flush()` can wait for it. */
3086
+ emit(build) {
3087
+ const write = emit(this.sink, build).finally(() => this.pending.delete(write));
3088
+ this.pending.add(write);
3089
+ return write;
3090
+ }
3091
+ async settle() {
3092
+ while (this.pending.size > 0) await Promise.all([...this.pending]);
3093
+ }
3094
+ scrub(value, field) {
3095
+ return scrubOrNull(this.scrubber, value, field);
3096
+ }
3097
+ annotate(session, consentToken, options) {
3098
+ if (!this.live()) return Promise.resolve();
3099
+ const sequence = nextSequence();
3100
+ const text = (value) => value === void 0 ? null : this.scrubber(value);
3101
+ return this.emit(
3102
+ () => AnnotationEventSchema.parse({
3103
+ ...this.envelope(session, consentToken, sequence),
3104
+ payload: {
3105
+ intent: text(options.intent),
3106
+ expected_outcome: text(options.expectedOutcome),
3107
+ what_happened: hasText2(options.whatHappened) ? text(options.whatHappened) : null,
3108
+ tool_name: options.toolName ? text(options.toolName) : options.toolName ?? null,
3109
+ workflow: text(options.workflow),
3110
+ suggested_improvement: text(options.suggestedImprovement),
3111
+ context: options.context && Object.keys(options.context).length > 0 ? this.scrub(options.context, "context") : null
3112
+ }
3113
+ })
3114
+ );
3115
+ }
3116
+ };
3117
+ var UNSET = /* @__PURE__ */ Symbol("unset");
3118
+ var WITHHELD_RESULT = /* @__PURE__ */ Symbol("withheld");
3119
+ var SCRUB_FAILED = /* @__PURE__ */ Symbol("scrubFailed");
3120
+ var runTrace;
3121
+ var Trace = class _Trace {
3122
+ #core;
3123
+ #session;
3124
+ #options;
3125
+ #consentToken;
3126
+ #callId = uuid7();
3127
+ #startedAt = 0;
3128
+ #result = UNSET;
3129
+ #error = null;
3130
+ #observedWarned = false;
3131
+ constructor(core, session, options) {
3132
+ this.#core = core;
3133
+ this.#session = session;
3134
+ this.#options = options;
3135
+ this.#consentToken = options.consentToken || core.consentToken;
3136
+ }
3137
+ /** The session this call's events carry. */
3138
+ get sessionId() {
3139
+ return this.#session.sessionId;
3140
+ }
3141
+ /** Record the outcome. Without a call, the callback's return value is the
3142
+ * result. `observed(undefined, { error })` records a failure the callback
3143
+ * caught and did not rethrow. The last call wins. */
3144
+ observed(result, failure) {
3145
+ if ((this.#result !== UNSET || this.#error !== null) && !this.#observedWarned) {
3146
+ this.#observedWarned = true;
3147
+ process.stderr.write("baton: Trace.observed() called more than once; the last call wins.\n");
3148
+ }
3149
+ this.#result = UNSET;
3150
+ this.#error = null;
3151
+ if (this.#core.disabled) return this;
3152
+ let errorType = failure?.errorType;
3153
+ let errorBody2 = failure?.errorBody;
3154
+ if (failure?.error !== void 0) {
3155
+ const [derivedType, derivedBody] = describeError(failure.error);
3156
+ errorType ||= derivedType;
3157
+ errorBody2 ||= derivedBody;
3158
+ }
3159
+ if (errorType !== void 0 || errorBody2 !== void 0) {
3160
+ this.#error = { type: errorType || "Error", body: errorBody2 ?? "" };
3161
+ } else if (this.#core.resultCaptureMode === WITHHELD) {
3162
+ this.#result = WITHHELD_RESULT;
3163
+ } else {
3164
+ try {
3165
+ this.#result = this.#core.scrubber(result);
3166
+ } catch (err) {
3167
+ process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${String(err)}
3168
+ `);
3169
+ this.#result = SCRUB_FAILED;
3170
+ }
3171
+ }
3172
+ return this;
3173
+ }
3174
+ /** Report on this call, in its session. */
3175
+ annotate(options) {
3176
+ return this.#core.annotate(this.#session, this.#consentToken, options);
3177
+ }
3178
+ #envelope(sequence) {
3179
+ return { ...this.#core.envelope(this.#session, this.#consentToken, sequence), call_id: this.#callId };
3180
+ }
3181
+ #durationMs() {
3182
+ return Math.trunc(performance.now() - this.#startedAt);
3183
+ }
3184
+ #start() {
3185
+ this.#startedAt = performance.now();
3186
+ if (!this.#core.live()) return;
3187
+ const sequence = nextSequence();
3188
+ const o = this.#options;
3189
+ const params = o.params === void 0 ? {} : this.#core.scrub(o.params, "params") ?? {};
3190
+ const textOf = (value, field) => {
3191
+ const scrubbed = value === void 0 ? null : this.#core.scrub(value, field);
3192
+ return typeof scrubbed === "string" ? scrubbed : null;
3193
+ };
3194
+ const intent = textOf(o.intent, "intent");
3195
+ const expected = textOf(o.expectedOutcome, "expected_outcome");
3196
+ const workflow = textOf(o.workflow, "workflow");
3197
+ const stated = [intent, expected, workflow].some(hasText2);
3198
+ void this.#core.emit(
3199
+ () => ToolCallStartEventSchema.parse({
3200
+ ...this.#envelope(sequence),
3201
+ payload: {
3202
+ tool_name: o.toolName,
3203
+ params,
3204
+ call_intent: intent,
3205
+ call_expected: expected,
3206
+ call_workflow: workflow,
3207
+ intent_source: stated ? INTENT_SOURCE_LIBRARY : null
3208
+ }
3209
+ })
3210
+ );
3211
+ }
3212
+ #end(value) {
3213
+ const durationMs = this.#durationMs();
3214
+ if (!this.#core.live()) return;
3215
+ if (this.#result === UNSET && this.#error === null) this.observed(value);
3216
+ const sequence = nextSequence();
3217
+ const error = this.#error;
3218
+ if (error !== null) {
3219
+ this.#emitError(sequence, error.type, error.body, durationMs);
3220
+ return;
3221
+ }
3222
+ const result = this.#result;
3223
+ void this.#core.emit(() => {
3224
+ if (result === SCRUB_FAILED) throw new Error("the scrubber threw on this result");
3225
+ return ToolCallEndEventSchema.parse({
3226
+ ...this.#envelope(sequence),
3227
+ payload: {
3228
+ tool_name: this.#options.toolName,
3229
+ duration_ms: durationMs,
3230
+ ...result === WITHHELD_RESULT ? { result: null, result_capture: WITHHELD } : { result }
3231
+ }
3232
+ });
3233
+ });
3234
+ }
3235
+ #fail(err) {
3236
+ const durationMs = this.#durationMs();
3237
+ if (!this.#core.live()) return;
3238
+ this.#emitError(nextSequence(), ...describeError(err), durationMs);
3239
+ }
3240
+ #emitError(sequence, type, body, durationMs) {
3241
+ void this.#core.emit(
3242
+ () => ToolCallErrorEventSchema.parse({
3243
+ ...this.#envelope(sequence),
3244
+ payload: {
3245
+ tool_name: this.#options.toolName,
3246
+ error_type: type,
3247
+ error_body: scrubbedErrorBody(this.#core.scrubber, body),
3248
+ duration_ms: durationMs,
3249
+ result: null
3250
+ }
3251
+ })
3252
+ );
3253
+ }
3254
+ static {
3255
+ runTrace = (core, session, options, fn) => {
3256
+ const trace = new _Trace(core, session, options);
3257
+ trace.#start();
3258
+ let value;
3259
+ try {
3260
+ value = fn(trace);
3261
+ } catch (err) {
3262
+ trace.#fail(err);
3263
+ throw err;
3264
+ }
3265
+ if (!isThenable(value)) {
3266
+ trace.#end(value);
3267
+ return value;
3268
+ }
3269
+ return Promise.resolve(value).then(
3270
+ (resolved) => {
3271
+ trace.#end(resolved);
3272
+ return resolved;
3273
+ },
3274
+ (err) => {
3275
+ trace.#fail(err);
3276
+ throw err;
3277
+ }
3278
+ );
3279
+ };
3280
+ }
3281
+ };
3282
+ var Client = class {
3283
+ #core;
3284
+ #closing;
3285
+ constructor(options = {}) {
3286
+ const switchName = captureDisabled();
3287
+ let resolved;
3288
+ if (switchName !== null) {
3289
+ logDisabled(switchName, "Client");
3290
+ resolved = {
3291
+ sink: options.sink ?? new DisabledSink(),
3292
+ vendorId: "",
3293
+ tenantId: "",
3294
+ consentToken: DEFAULT_CONSENT_TOKEN,
3295
+ resultCaptureMode: "full"
3296
+ };
3297
+ } else {
3298
+ resolved = resolveClientOptions(options);
3299
+ }
3300
+ this.#core = new Core({
3301
+ ...resolved,
3302
+ scrubber: options.scrubber ?? new Scrubber().scrub,
3303
+ disabled: switchName !== null
3304
+ });
3305
+ }
3306
+ /** Run `fn` with one session, principal, client and turn for every
3307
+ * `trace()` and `annotate()` inside it, including after its awaits. Open
3308
+ * one per request or conversation. Returns what `fn` returns. */
3309
+ session(options, fn) {
3310
+ let block;
3311
+ try {
3312
+ block = newSession(options, this.#core.scrubber, this.#core.disabled);
3313
+ } catch (err) {
3314
+ process.stderr.write(`baton: session values could not be read; using a minted session: ${String(err)}
3315
+ `);
3316
+ block = newSession({}, this.#core.scrubber, this.#core.disabled);
3317
+ }
3318
+ return runInSession(this, block, fn);
3319
+ }
3320
+ /** Run `fn` as one traced tool call and return what it returns. When `fn`
3321
+ * returns a promise or other thenable, the call ends when it settles, and
3322
+ * what comes back is a new native Promise of the same value: `then` is
3323
+ * called exactly once, so a lazy query builder is not run twice. A throw or
3324
+ * rejection is recorded and passed on unchanged. */
3325
+ trace(options, fn) {
3326
+ return runTrace(this.#core, sessionForCall(this), options ?? {}, fn);
3327
+ }
3328
+ /** `fn`, traced on every call. A single plain-object argument is sent as
3329
+ * `params`, as an MCP tool's arguments are; other arguments as
3330
+ * `{ args: [...] }`, unless `options.params` is given. */
3331
+ wrap(options, fn) {
3332
+ const base = typeof options === "string" ? { toolName: options } : options ?? {};
3333
+ const client = this;
3334
+ return function(...args) {
3335
+ return client.trace({ ...base, params: base.params ?? paramsOf(args) }, () => fn.apply(this, args));
3336
+ };
3337
+ }
3338
+ /** Emit an annotation in the open `session()` block, or in a session of its
3339
+ * own outside one. To report on a traced call, use `trace.annotate()`. */
3340
+ annotate(options) {
3341
+ const given = options ?? {};
3342
+ return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);
3343
+ }
3344
+ /** Wait until every event so far has reached the sink and the sink has flushed. */
3345
+ async flush() {
3346
+ await this.#core.settle();
3347
+ try {
3348
+ await this.#core.sink.flush();
3349
+ } catch (err) {
3350
+ process.stderr.write(`baton: sink.flush failed: ${String(err)}
3351
+ `);
3352
+ }
3353
+ }
3354
+ /** Flush, then close the sink. Later events are dropped. */
3355
+ aclose() {
3356
+ this.#closing ??= this.#close();
3357
+ return this.#closing;
3358
+ }
3359
+ async #close() {
3360
+ await this.#core.settle();
3361
+ this.#core.closed = true;
3362
+ try {
3363
+ await this.#core.sink.aclose();
3364
+ } catch (err) {
3365
+ process.stderr.write(`baton: sink.aclose failed: ${String(err)}
3366
+ `);
3367
+ }
3368
+ }
3369
+ };
2844
3370
  export {
2845
3371
  AnnotationEventSchema,
2846
3372
  AnnotationPayloadSchema,
2847
3373
  BatonHandle,
3374
+ Client,
2848
3375
  DEFAULT_CONSENT_TOKEN,
2849
3376
  DEPTH_LIMIT,
2850
3377
  EventSchema,
2851
3378
  EventTypeSchema,
2852
3379
  HttpSink,
3380
+ INTENT_PARAMS,
2853
3381
  PRINCIPAL_FORM_HASHED,
2854
3382
  PRINCIPAL_FORM_RAW,
2855
3383
  PRINCIPAL_SOURCE_ASSERTED,
@@ -2895,6 +3423,7 @@ export {
2895
3423
  ToolListErrorPayloadSchema,
2896
3424
  ToolListStartEventSchema,
2897
3425
  ToolListStartPayloadSchema,
3426
+ Trace,
2898
3427
  createBaton,
2899
3428
  identityScrub,
2900
3429
  principalFromOAuthEmail,