@goodtiming/baton-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,685 @@
1
+ import { z } from 'zod';
2
+
3
+ declare const SDK_VERSION = "ts-0.1.0";
4
+
5
+ /**
6
+ * Zod schemas + TS types for the Baton event stream per SPEC §11.4.
7
+ *
8
+ * This is a hand-maintained mirror of `baton-spec/events.schema.json`, which
9
+ * is itself exported from `baton-sdk` (Python)'s Pydantic models — that repo
10
+ * is the schema of record. `test/conformance.test.ts` validates every
11
+ * concrete type below against `baton-spec/events.schema.json` with ajv and
12
+ * against `baton-spec/vectors/*.json`, so a drift here fails CI rather than
13
+ * surfacing as a silent Console-side shape mismatch.
14
+ *
15
+ * All concrete event schemas share the same envelope fields and differ only
16
+ * in `payload`. Fields match Python field-for-field (snake_case on the wire,
17
+ * per CHARTER's wire-compatibility requirement — NOT camelCase).
18
+ */
19
+
20
+ /** Emitted before the vendor handler runs. `params` is PII-scrubbed at
21
+ * emit-time per SPEC §7.
22
+ *
23
+ * `call_intent` / `call_expected` / `call_workflow` are the values the SDK
24
+ * stripped from the injected `user_goal` / `expected_result` /
25
+ * `overall_task` params (see `llmText.ts`); they ride as SIBLINGS of
26
+ * `params` — `params` stays exactly the vendor-visible arguments.
27
+ * `call_intent`/`call_expected` are call-scoped diagnostics;
28
+ * `call_workflow` is the task-label grouping key (console rung 3b, exact
29
+ * string continuity). `intent_source` records provenance
30
+ * (`"injected_param"`). All null when the params weren't used. */
31
+ declare const ToolCallStartPayloadSchema: z.ZodObject<{
32
+ tool_name: z.ZodString;
33
+ params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
34
+ call_intent: z.ZodDefault<z.ZodNullable<z.ZodString>>;
35
+ call_expected: z.ZodDefault<z.ZodNullable<z.ZodString>>;
36
+ call_workflow: z.ZodDefault<z.ZodNullable<z.ZodString>>;
37
+ intent_source: z.ZodDefault<z.ZodNullable<z.ZodString>>;
38
+ }, z.core.$strict>;
39
+ type ToolCallStartPayload = z.infer<typeof ToolCallStartPayloadSchema>;
40
+ /** Emitted after the vendor handler returns. `result` is PII-scrubbed. */
41
+ declare const ToolCallEndPayloadSchema: z.ZodObject<{
42
+ tool_name: z.ZodString;
43
+ result: z.ZodDefault<z.ZodNullable<z.ZodUnknown>>;
44
+ duration_ms: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
45
+ }, z.core.$strict>;
46
+ type ToolCallEndPayload = z.infer<typeof ToolCallEndPayloadSchema>;
47
+ /** Emitted when the vendor handler throws. `error_type` is the error's
48
+ * constructor name; `error_body` is the message (PII-scrubbed, capped at
49
+ * 2000 chars per the design note). */
50
+ declare const ToolCallErrorPayloadSchema: z.ZodObject<{
51
+ tool_name: z.ZodString;
52
+ error_type: z.ZodString;
53
+ error_body: z.ZodString;
54
+ duration_ms: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
55
+ }, z.core.$strict>;
56
+ type ToolCallErrorPayload = z.infer<typeof ToolCallErrorPayloadSchema>;
57
+ /** Agent-supplied context. All fields nullable per SPEC §5.1.1 — the agent
58
+ * populates what it has. Proactive annotations typically populate
59
+ * `intent`/`expected_outcome`/`workflow`; reactive annotations typically
60
+ * populate `signal_type`/`suggested_improvement`. */
61
+ declare const AnnotationPayloadSchema: z.ZodObject<{
62
+ intent: z.ZodDefault<z.ZodNullable<z.ZodString>>;
63
+ expected_outcome: z.ZodDefault<z.ZodNullable<z.ZodString>>;
64
+ signal_type: z.ZodDefault<z.ZodNullable<z.ZodString>>;
65
+ workflow: z.ZodDefault<z.ZodNullable<z.ZodString>>;
66
+ suggested_improvement: z.ZodDefault<z.ZodNullable<z.ZodString>>;
67
+ context: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
68
+ intent_source: z.ZodDefault<z.ZodNullable<z.ZodString>>;
69
+ tool_name: z.ZodDefault<z.ZodNullable<z.ZodString>>;
70
+ }, z.core.$strict>;
71
+ type AnnotationPayload = z.infer<typeof AnnotationPayloadSchema>;
72
+ /** The vendor-true upstream surface (pre-injection) — mirrors baton-proxy's
73
+ * `enqueue_surface_snapshot` payload so the Console worker materializes both
74
+ * into the same `vendor_surfaces` table. Emitted at most once per observed
75
+ * `surface_hash` per process. `tools` excludes Baton's own injected tool(s);
76
+ * those live in `seam_augmentations.injected_tools` instead. */
77
+ declare const SurfaceSnapshotPayloadSchema: z.ZodObject<{
78
+ surface_hash: z.ZodString;
79
+ server_info: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
80
+ capabilities: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
81
+ instructions: z.ZodDefault<z.ZodNullable<z.ZodString>>;
82
+ tools: z.ZodDefault<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
83
+ seam_augmentations: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
84
+ }, z.core.$strict>;
85
+ type SurfaceSnapshotPayload = z.infer<typeof SurfaceSnapshotPayloadSchema>;
86
+ declare const EventTypeSchema: z.ZodEnum<{
87
+ tool_call_start: "tool_call_start";
88
+ tool_call_end: "tool_call_end";
89
+ tool_call_error: "tool_call_error";
90
+ annotation: "annotation";
91
+ surface_snapshot: "surface_snapshot";
92
+ }>;
93
+ type EventType = z.infer<typeof EventTypeSchema>;
94
+ declare const ToolCallStartEventSchema: z.ZodObject<{
95
+ event_type: z.ZodDefault<z.ZodLiteral<"tool_call_start">>;
96
+ payload: z.ZodObject<{
97
+ tool_name: z.ZodString;
98
+ params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
99
+ call_intent: z.ZodDefault<z.ZodNullable<z.ZodString>>;
100
+ call_expected: z.ZodDefault<z.ZodNullable<z.ZodString>>;
101
+ call_workflow: z.ZodDefault<z.ZodNullable<z.ZodString>>;
102
+ intent_source: z.ZodDefault<z.ZodNullable<z.ZodString>>;
103
+ }, z.core.$strict>;
104
+ event_id: z.ZodDefault<z.ZodUUID>;
105
+ tenant_id: z.ZodString;
106
+ vendor_id: z.ZodString;
107
+ session_id: z.ZodString;
108
+ sequence_number: z.ZodNumber;
109
+ captured_at: z.ZodString;
110
+ consent_token: z.ZodString;
111
+ sdk_version: z.ZodDefault<z.ZodString>;
112
+ agent_runtime: z.ZodDefault<z.ZodString>;
113
+ user_id: z.ZodDefault<z.ZodNullable<z.ZodString>>;
114
+ runtime_meta: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
115
+ }, z.core.$strict>;
116
+ type ToolCallStartEvent = z.infer<typeof ToolCallStartEventSchema>;
117
+ declare const ToolCallEndEventSchema: z.ZodObject<{
118
+ event_type: z.ZodDefault<z.ZodLiteral<"tool_call_end">>;
119
+ payload: z.ZodObject<{
120
+ tool_name: z.ZodString;
121
+ result: z.ZodDefault<z.ZodNullable<z.ZodUnknown>>;
122
+ duration_ms: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
123
+ }, z.core.$strict>;
124
+ event_id: z.ZodDefault<z.ZodUUID>;
125
+ tenant_id: z.ZodString;
126
+ vendor_id: z.ZodString;
127
+ session_id: z.ZodString;
128
+ sequence_number: z.ZodNumber;
129
+ captured_at: z.ZodString;
130
+ consent_token: z.ZodString;
131
+ sdk_version: z.ZodDefault<z.ZodString>;
132
+ agent_runtime: z.ZodDefault<z.ZodString>;
133
+ user_id: z.ZodDefault<z.ZodNullable<z.ZodString>>;
134
+ runtime_meta: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
135
+ }, z.core.$strict>;
136
+ type ToolCallEndEvent = z.infer<typeof ToolCallEndEventSchema>;
137
+ declare const ToolCallErrorEventSchema: z.ZodObject<{
138
+ event_type: z.ZodDefault<z.ZodLiteral<"tool_call_error">>;
139
+ payload: z.ZodObject<{
140
+ tool_name: z.ZodString;
141
+ error_type: z.ZodString;
142
+ error_body: z.ZodString;
143
+ duration_ms: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
144
+ }, z.core.$strict>;
145
+ event_id: z.ZodDefault<z.ZodUUID>;
146
+ tenant_id: z.ZodString;
147
+ vendor_id: z.ZodString;
148
+ session_id: z.ZodString;
149
+ sequence_number: z.ZodNumber;
150
+ captured_at: z.ZodString;
151
+ consent_token: z.ZodString;
152
+ sdk_version: z.ZodDefault<z.ZodString>;
153
+ agent_runtime: z.ZodDefault<z.ZodString>;
154
+ user_id: z.ZodDefault<z.ZodNullable<z.ZodString>>;
155
+ runtime_meta: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
156
+ }, z.core.$strict>;
157
+ type ToolCallErrorEvent = z.infer<typeof ToolCallErrorEventSchema>;
158
+ declare const AnnotationEventSchema: z.ZodObject<{
159
+ event_type: z.ZodDefault<z.ZodLiteral<"annotation">>;
160
+ payload: z.ZodObject<{
161
+ intent: z.ZodDefault<z.ZodNullable<z.ZodString>>;
162
+ expected_outcome: z.ZodDefault<z.ZodNullable<z.ZodString>>;
163
+ signal_type: z.ZodDefault<z.ZodNullable<z.ZodString>>;
164
+ workflow: z.ZodDefault<z.ZodNullable<z.ZodString>>;
165
+ suggested_improvement: z.ZodDefault<z.ZodNullable<z.ZodString>>;
166
+ context: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
167
+ intent_source: z.ZodDefault<z.ZodNullable<z.ZodString>>;
168
+ tool_name: z.ZodDefault<z.ZodNullable<z.ZodString>>;
169
+ }, z.core.$strict>;
170
+ event_id: z.ZodDefault<z.ZodUUID>;
171
+ tenant_id: z.ZodString;
172
+ vendor_id: z.ZodString;
173
+ session_id: z.ZodString;
174
+ sequence_number: z.ZodNumber;
175
+ captured_at: z.ZodString;
176
+ consent_token: z.ZodString;
177
+ sdk_version: z.ZodDefault<z.ZodString>;
178
+ agent_runtime: z.ZodDefault<z.ZodString>;
179
+ user_id: z.ZodDefault<z.ZodNullable<z.ZodString>>;
180
+ runtime_meta: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
181
+ }, z.core.$strict>;
182
+ type AnnotationEvent = z.infer<typeof AnnotationEventSchema>;
183
+ declare const SurfaceSnapshotEventSchema: z.ZodObject<{
184
+ event_type: z.ZodDefault<z.ZodLiteral<"surface_snapshot">>;
185
+ payload: z.ZodObject<{
186
+ surface_hash: z.ZodString;
187
+ server_info: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
188
+ capabilities: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
189
+ instructions: z.ZodDefault<z.ZodNullable<z.ZodString>>;
190
+ tools: z.ZodDefault<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
191
+ seam_augmentations: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
192
+ }, z.core.$strict>;
193
+ event_id: z.ZodDefault<z.ZodUUID>;
194
+ tenant_id: z.ZodString;
195
+ vendor_id: z.ZodString;
196
+ session_id: z.ZodString;
197
+ sequence_number: z.ZodNumber;
198
+ captured_at: z.ZodString;
199
+ consent_token: z.ZodString;
200
+ sdk_version: z.ZodDefault<z.ZodString>;
201
+ agent_runtime: z.ZodDefault<z.ZodString>;
202
+ user_id: z.ZodDefault<z.ZodNullable<z.ZodString>>;
203
+ runtime_meta: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
204
+ }, z.core.$strict>;
205
+ type SurfaceSnapshotEvent = z.infer<typeof SurfaceSnapshotEventSchema>;
206
+ declare const EventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
207
+ event_type: z.ZodDefault<z.ZodLiteral<"tool_call_start">>;
208
+ payload: z.ZodObject<{
209
+ tool_name: z.ZodString;
210
+ params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
211
+ call_intent: z.ZodDefault<z.ZodNullable<z.ZodString>>;
212
+ call_expected: z.ZodDefault<z.ZodNullable<z.ZodString>>;
213
+ call_workflow: z.ZodDefault<z.ZodNullable<z.ZodString>>;
214
+ intent_source: z.ZodDefault<z.ZodNullable<z.ZodString>>;
215
+ }, z.core.$strict>;
216
+ event_id: z.ZodDefault<z.ZodUUID>;
217
+ tenant_id: z.ZodString;
218
+ vendor_id: z.ZodString;
219
+ session_id: z.ZodString;
220
+ sequence_number: z.ZodNumber;
221
+ captured_at: z.ZodString;
222
+ consent_token: z.ZodString;
223
+ sdk_version: z.ZodDefault<z.ZodString>;
224
+ agent_runtime: z.ZodDefault<z.ZodString>;
225
+ user_id: z.ZodDefault<z.ZodNullable<z.ZodString>>;
226
+ runtime_meta: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
227
+ }, z.core.$strict>, z.ZodObject<{
228
+ event_type: z.ZodDefault<z.ZodLiteral<"tool_call_end">>;
229
+ payload: z.ZodObject<{
230
+ tool_name: z.ZodString;
231
+ result: z.ZodDefault<z.ZodNullable<z.ZodUnknown>>;
232
+ duration_ms: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
233
+ }, z.core.$strict>;
234
+ event_id: z.ZodDefault<z.ZodUUID>;
235
+ tenant_id: z.ZodString;
236
+ vendor_id: z.ZodString;
237
+ session_id: z.ZodString;
238
+ sequence_number: z.ZodNumber;
239
+ captured_at: z.ZodString;
240
+ consent_token: z.ZodString;
241
+ sdk_version: z.ZodDefault<z.ZodString>;
242
+ agent_runtime: z.ZodDefault<z.ZodString>;
243
+ user_id: z.ZodDefault<z.ZodNullable<z.ZodString>>;
244
+ runtime_meta: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
245
+ }, z.core.$strict>, z.ZodObject<{
246
+ event_type: z.ZodDefault<z.ZodLiteral<"tool_call_error">>;
247
+ payload: z.ZodObject<{
248
+ tool_name: z.ZodString;
249
+ error_type: z.ZodString;
250
+ error_body: z.ZodString;
251
+ duration_ms: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
252
+ }, z.core.$strict>;
253
+ event_id: z.ZodDefault<z.ZodUUID>;
254
+ tenant_id: z.ZodString;
255
+ vendor_id: z.ZodString;
256
+ session_id: z.ZodString;
257
+ sequence_number: z.ZodNumber;
258
+ captured_at: z.ZodString;
259
+ consent_token: z.ZodString;
260
+ sdk_version: z.ZodDefault<z.ZodString>;
261
+ agent_runtime: z.ZodDefault<z.ZodString>;
262
+ user_id: z.ZodDefault<z.ZodNullable<z.ZodString>>;
263
+ runtime_meta: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
264
+ }, z.core.$strict>, z.ZodObject<{
265
+ event_type: z.ZodDefault<z.ZodLiteral<"annotation">>;
266
+ payload: z.ZodObject<{
267
+ intent: z.ZodDefault<z.ZodNullable<z.ZodString>>;
268
+ expected_outcome: z.ZodDefault<z.ZodNullable<z.ZodString>>;
269
+ signal_type: z.ZodDefault<z.ZodNullable<z.ZodString>>;
270
+ workflow: z.ZodDefault<z.ZodNullable<z.ZodString>>;
271
+ suggested_improvement: z.ZodDefault<z.ZodNullable<z.ZodString>>;
272
+ context: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
273
+ intent_source: z.ZodDefault<z.ZodNullable<z.ZodString>>;
274
+ tool_name: z.ZodDefault<z.ZodNullable<z.ZodString>>;
275
+ }, z.core.$strict>;
276
+ event_id: z.ZodDefault<z.ZodUUID>;
277
+ tenant_id: z.ZodString;
278
+ vendor_id: z.ZodString;
279
+ session_id: z.ZodString;
280
+ sequence_number: z.ZodNumber;
281
+ captured_at: z.ZodString;
282
+ consent_token: z.ZodString;
283
+ sdk_version: z.ZodDefault<z.ZodString>;
284
+ agent_runtime: z.ZodDefault<z.ZodString>;
285
+ user_id: z.ZodDefault<z.ZodNullable<z.ZodString>>;
286
+ runtime_meta: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
287
+ }, z.core.$strict>, z.ZodObject<{
288
+ event_type: z.ZodDefault<z.ZodLiteral<"surface_snapshot">>;
289
+ payload: z.ZodObject<{
290
+ surface_hash: z.ZodString;
291
+ server_info: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
292
+ capabilities: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
293
+ instructions: z.ZodDefault<z.ZodNullable<z.ZodString>>;
294
+ tools: z.ZodDefault<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
295
+ seam_augmentations: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
296
+ }, z.core.$strict>;
297
+ event_id: z.ZodDefault<z.ZodUUID>;
298
+ tenant_id: z.ZodString;
299
+ vendor_id: z.ZodString;
300
+ session_id: z.ZodString;
301
+ sequence_number: z.ZodNumber;
302
+ captured_at: z.ZodString;
303
+ consent_token: z.ZodString;
304
+ sdk_version: z.ZodDefault<z.ZodString>;
305
+ agent_runtime: z.ZodDefault<z.ZodString>;
306
+ user_id: z.ZodDefault<z.ZodNullable<z.ZodString>>;
307
+ runtime_meta: z.ZodDefault<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
308
+ }, z.core.$strict>], "event_type">;
309
+ type Event = ToolCallStartEvent | ToolCallEndEvent | ToolCallErrorEvent | AnnotationEvent | SurfaceSnapshotEvent;
310
+
311
+ /**
312
+ * Source-side PII scrubbing for event payloads (SPEC §7).
313
+ *
314
+ * The SDK emits whatever the wrapped MCP server returns — including tool
315
+ * params and results that may carry customer PII (emails in search results,
316
+ * bearer tokens in error bodies, API keys pasted into chat tools). Persona
317
+ * B's trust pitch is that nothing unscrubbed ever leaves the customer's
318
+ * machine; this module is what makes that true. Every event payload runs
319
+ * through `Scrubber` before it lands in the sink, so both local sinks AND
320
+ * any HTTP sink see only scrubbed values.
321
+ *
322
+ * **Default ruleset** ships fixed for v1 (no public env-var configurability
323
+ * — deferred until customer feedback justifies the surface area):
324
+ *
325
+ * - email — RFC-ish address regex
326
+ * - bearer — `Bearer <opaque>` header values
327
+ * - sk_key — OpenAI/Anthropic-style `sk-*` API keys
328
+ * - aws_key — `AKIA*` access key IDs
329
+ * - jwt — three-segment `eyJ*.*.*` tokens
330
+ * - phone — North-American-leaning loose digit pattern
331
+ * - cc — 13-19 digit candidates filtered by Luhn
332
+ *
333
+ * Plus field-name overrides: any object key matching
334
+ * `{email, phone, ssn, api_key, token, secret, password, user_name}`
335
+ * (case-insensitive) force-redacts its string value regardless of pattern.
336
+ *
337
+ * Differs from LangSmith's approach (off by default, bring-your-own regex)
338
+ * by shipping rules on by default — the right tradeoff for Persona B's
339
+ * consumer/SMB audience that won't write masking code.
340
+ *
341
+ * Ported from `baton` (Python)'s `src/baton/scrub.py` on 2026-08-11, which
342
+ * is itself a parallel copy of baton-proxy's (the two are rule-identical —
343
+ * verified by diff at port time; they differ only in docstrings). All three
344
+ * ship parallel copies until the extracted shared package lands. Rule
345
+ * parity here is verified by mirroring Python's `tests/test_scrub.py` test
346
+ * matrix in `test/scrub.test.ts`; when a pattern lands or changes, port the
347
+ * test every way.
348
+ *
349
+ * **Port notes** (where TypeScript forced a divergence from the Python):
350
+ * - `counts` is a `Map<string, number>`, not a `collections.Counter`. Use
351
+ * `count(category)` for Python's zero-default read.
352
+ * - Python walks anything `isinstance(dict)`; this walks only *plain*
353
+ * objects (`{}` / `Object.create(null)`). A `Date`, `Map`, or class
354
+ * instance passes through untouched rather than being flattened to `{}`
355
+ * — matching Python, where those aren't dicts either.
356
+ */
357
+ /** Cap on recursive walk depth. Matches LangSmith's default; protects
358
+ * against pathological inputs without truncating realistic MCP payloads. */
359
+ declare const DEPTH_LIMIT = 10;
360
+ /**
361
+ * Stateful recursive scrubber with the default ruleset baked in.
362
+ *
363
+ * Construct one per `withBaton` call and reuse for every event. The
364
+ * `counts` map accumulates per-category redaction counts across all calls
365
+ * so a downstream report can surface "N emails, M bearer tokens" at render
366
+ * time. Nothing on the wire carries these today — they exist for parity
367
+ * with Python and for vendor-side introspection.
368
+ *
369
+ * Instances are callable-compatible via the bound `scrub` method, so a
370
+ * `Scrubber` plugs into anywhere the `(value: unknown) => unknown` slot
371
+ * that `BatonConfig.scrubber` accepts expects a plain function.
372
+ */
373
+ declare class Scrubber {
374
+ readonly counts: Map<string, number>;
375
+ /** Bound so `new Scrubber().scrub` can be passed as a bare function
376
+ * reference — the closest TS gets to Python's `__call__`. */
377
+ readonly scrub: (value: unknown) => unknown;
378
+ /** Python's `Counter[category]` zero-default read. */
379
+ count(category: string): number;
380
+ private bump;
381
+ private walk;
382
+ private scrubString;
383
+ }
384
+ /**
385
+ * No-op scrubber. Exported for explicit opt-out — vendors / customers who
386
+ * legitimately want raw payloads pass this where `new Scrubber().scrub`
387
+ * would otherwise be the default. Not the default: the SDK ships the same
388
+ * default ruleset as `baton` (Python) and baton-proxy so untouched
389
+ * integrations get PII scrubbing without the operator having to opt in.
390
+ */
391
+ declare function identityScrub(value: unknown): unknown;
392
+
393
+ /**
394
+ * Sinks — where Baton events go after the SDK captures them.
395
+ *
396
+ * A `Sink` is the egress side of the SDK; `withBaton` hands fully-formed
397
+ * `Event` envelopes to a sink and the sink decides what to do with them.
398
+ *
399
+ * Two sinks ship, mirroring `sinks.py`'s core pair:
400
+ *
401
+ * - `StdoutSink` — JSONL to a writable stream (default `process.stderr`,
402
+ * for the same reason as Python: MCP stdio transport reserves stdout for
403
+ * JSON-RPC framing).
404
+ * - `HttpSink` — POST to any HTTP endpoint with bearer auth; bounded
405
+ * buffer, retry with backoff, circuit breaker. This is the contract a
406
+ * Console or any compatible collector consumes.
407
+ *
408
+ * `FileSink` / `MultiSink` are deferred per design-notes/typescript_sdk.md
409
+ * ("HttpSink + StdoutSink covers all real use cases") — add them if a real
410
+ * need shows up rather than porting them speculatively.
411
+ */
412
+
413
+ interface Sink {
414
+ /** Hand one event to the sink. Resolves once the sink has accepted it
415
+ * (which may mean buffered, not yet shipped). MUST NOT block the
416
+ * producer on slow downstream destinations. */
417
+ write(event: Event): Promise<void>;
418
+ /** Wait for any buffered events to reach their destination (or be
419
+ * dropped per the sink's policy). No-op for synchronous sinks. */
420
+ flush(): Promise<void>;
421
+ /** Flush + release resources. After `aclose`, `write` rejects. */
422
+ aclose(): Promise<void>;
423
+ }
424
+ /** Fail-open wrapper around `sink.write`.
425
+ *
426
+ * The MCP tool wrapper sits BEFORE the vendor's tool handler runs. A reject
427
+ * from `sink.write` (closed sink, transport error, etc.) would otherwise
428
+ * propagate up and break the vendor's tool call — making Baton
429
+ * instrumentation look like a vendor bug. SPEC §11.2 mandates fail-open at
430
+ * the capture boundary; this wrapper enforces it. */
431
+ declare function safeWrite(sink: Sink, event: Event): Promise<void>;
432
+ interface StdoutSinkOptions {
433
+ /** Defaults to `process.stderr` — stdio MCP transport reserves stdout for
434
+ * JSON-RPC framing. Pass `process.stdout` explicitly for non-MCP (library
435
+ * API) use if preferred. */
436
+ stream?: NodeJS.WritableStream;
437
+ }
438
+ declare class StdoutSink implements Sink {
439
+ private readonly stream;
440
+ private closed;
441
+ constructor(options?: StdoutSinkOptions);
442
+ write(event: Event): Promise<void>;
443
+ flush(): Promise<void>;
444
+ aclose(): Promise<void>;
445
+ }
446
+ interface HttpSinkOptions {
447
+ apiKey: string;
448
+ bufferSize?: number;
449
+ requestTimeoutMs?: number;
450
+ maxRetries?: number;
451
+ backoffBaseMs?: number;
452
+ backoffMaxMs?: number;
453
+ circuitBreakerThreshold?: number;
454
+ circuitBreakerResetMs?: number;
455
+ /** Injectable for tests; defaults to the global `fetch`. */
456
+ fetchImpl?: typeof fetch;
457
+ }
458
+ /** POST events to an HTTP endpoint. Bounded buffer + retry + circuit breaker.
459
+ *
460
+ * This is the contract a Console or any compatible collector consumes:
461
+ * `POST {url}/v0/events` with `Authorization: Bearer {apiKey}` and a JSON
462
+ * body matching the SPEC §11.4 envelope.
463
+ *
464
+ * Failures are bounded — buffer overflow drops the oldest event; network
465
+ * failures retry with backoff; the circuit breaker opens after consecutive
466
+ * failures so the SDK doesn't pile retries on a known-bad endpoint. */
467
+ declare class HttpSink implements Sink {
468
+ private readonly url;
469
+ private readonly apiKey;
470
+ private readonly buffer;
471
+ private readonly bufferSize;
472
+ private readonly maxRetries;
473
+ private readonly backoffBaseMs;
474
+ private readonly backoffMaxMs;
475
+ private readonly circuit;
476
+ private readonly fetchImpl;
477
+ private overflowWarned;
478
+ private closed;
479
+ private drainChain;
480
+ private beforeExitHandler;
481
+ constructor(url: string, options: HttpSinkOptions);
482
+ write(event: Event): Promise<void>;
483
+ flush(): Promise<void>;
484
+ aclose(): Promise<void>;
485
+ private enqueue;
486
+ /** Serializes every call to `drainLocked` — from `write()`'s background
487
+ * drain and from explicit `flush()` alike — onto one promise chain, so
488
+ * concurrent tool calls (the normal case once the MCP interceptor is
489
+ * wired up) can never run two drains at once racing on `buffer[0]`/
490
+ * `shift()`. Mirrors Python's `asyncio.Lock` around `_drain_locked`. */
491
+ private scheduleDrain;
492
+ /** Best-effort flush when the process is about to exit without an
493
+ * explicit `aclose()`. Node re-runs `beforeExit` if new async work is
494
+ * scheduled during it, so an in-flight flush here can complete normally —
495
+ * unlike Python's synchronous `atexit`, no separate sync-client fallback
496
+ * is needed. Real residual gap, not fixable in-process: SIGKILL, or
497
+ * SIGTERM with no installed handler, skip `beforeExit` entirely. A vendor
498
+ * needing that guarantee must call `aclose()` from their own handler. */
499
+ private ensureBeforeExitRegistered;
500
+ private events_url;
501
+ private authHeaders;
502
+ private static classifyStatus;
503
+ private drainLocked;
504
+ private sendWithRetry;
505
+ }
506
+
507
+ /**
508
+ * `BatonConfig` — vendor-side configuration for `withBaton`. A trimmed
509
+ * mirror of `baton` (Python)'s `integrations/_config.py::VendorConfig`.
510
+ */
511
+
512
+ /** Normalized input to `BatonConfig.resolveSessionId`. Deliberately doesn't
513
+ * carry the raw MCP SDK `extra` object — this shape is stable across
514
+ * whatever the TS MCP ecosystem does with its request-handler signature. */
515
+ interface SessionResolutionContext {
516
+ meta: Record<string, unknown> | null;
517
+ toolName: string;
518
+ arguments: Record<string, unknown>;
519
+ }
520
+ type ResolveSessionIdHook = (context: SessionResolutionContext) => string | null | undefined | Promise<string | null | undefined>;
521
+ interface BatonConfig {
522
+ /** Short stable identifier for the vendor (e.g. `"acme"`). Also used as
523
+ * `tenant_id` on every emitted event (vendor-mode tenancy) and as the
524
+ * default annotation tool name prefix (`{vendorId}_annotate`). */
525
+ vendorId: string;
526
+ /** Human-readable vendor name used in server instructions and the
527
+ * annotation tool description — whitelabel obligation (SPEC §5.4): no
528
+ * Baton-branded strings reach the calling agent. */
529
+ vendorDisplayName: string;
530
+ /** End-user consent token attached to every emitted event per SPEC §2.3 —
531
+ * required, the Console MUST reject events missing it. */
532
+ consentToken: string;
533
+ /** Where events go. Defaults to `new StdoutSink()` — zero-config dev mode. */
534
+ sink?: Sink;
535
+ /** Default `agent_runtime` when `_meta` heuristics can't detect one. */
536
+ defaultAgentRuntime?: string;
537
+ /** PII scrubber per SPEC §7, applied to tool params/results, `_meta`,
538
+ * intent strings and error bodies before they reach the sink. Defaults to
539
+ * the shipped default ruleset (`new Scrubber().scrub` — email, bearer,
540
+ * sk-keys, AWS keys, JWTs, phones, Luhn-checked cards, plus sensitive
541
+ * field names), matching `baton` (Python) and baton-proxy: on by default
542
+ * so untouched integrations get scrubbing without the operator opting in.
543
+ * Pass `identityScrub` to explicitly opt out, or supply your own. */
544
+ scrubber?: (value: unknown) => unknown;
545
+ /** Optional vendor-supplied session-id resolver, checked BEFORE
546
+ * `extra.sessionId` — mirrors Python's `resolve_session_id` rung 0. */
547
+ resolveSessionId?: ResolveSessionIdHook;
548
+ /** Optional override for the annotation tool name. Default is
549
+ * `{vendorId}_annotate`. */
550
+ annotationToolName?: string;
551
+ /** Per-tool intent-param injection (mirrors baton-extmcp's vendor-neutral
552
+ * naming). `"optional"` (default) injects `user_goal`/`expected_result`
553
+ * string params on every wrapped tool's advertised schema; `"required"`
554
+ * also adds `user_goal` to the schema's required fields (`expected_result`
555
+ * stays optional regardless); `"off"` disables injection. Both params are
556
+ * stripped before the vendor handler runs, so the tool never sees them.
557
+ * This is what captures intent on runtimes that drop `instructions`
558
+ * (notably Claude Desktop) — where the annotation tool alone yields
559
+ * nothing. A tool registered with no `inputSchema` at all is left alone
560
+ * regardless of this setting (see `schemaCompat.injectGoalParams`). */
561
+ intentParamMode?: "optional" | "required" | "off";
562
+ }
563
+
564
+ /**
565
+ * Handle returned from `withBaton` for graceful shutdown and session
566
+ * correlation. Trimmed mirror of Python's `integrations/_handle.py::BatonHandle`
567
+ * — `escalate()` is not here; it's a Console action-surface feature, out of
568
+ * scope for this package.
569
+ */
570
+ declare class BatonHandle {
571
+ readonly sink: Sink;
572
+ readonly vendorId: string;
573
+ /** Process-lifetime fallback session id — the value events fall back to
574
+ * when no real per-call session id resolves. Not every event necessarily
575
+ * carries this id; see `withBaton`'s session-resolution order. */
576
+ readonly sessionId: string;
577
+ /** The resolved annotation tool name (`{vendorId}_annotate` unless
578
+ * overridden via `BatonConfig.annotationToolName`). */
579
+ readonly annotationToolName: string;
580
+ constructor(options: {
581
+ sink: Sink;
582
+ vendorId: string;
583
+ sessionId: string;
584
+ annotationToolName: string;
585
+ });
586
+ /** Flush any pending events held by the sink. */
587
+ flush(): Promise<void>;
588
+ /** Flush and release sink resources. Subsequent writes reject. */
589
+ aclose(): Promise<void>;
590
+ }
591
+
592
+ /**
593
+ * `withBaton` — the vendor's MCP integration entry point for the official
594
+ * `@modelcontextprotocol/sdk`'s high-level `McpServer` — and the v2
595
+ * packages' (`@modelcontextprotocol/server`), which are a different class of
596
+ * the same name. `withBaton` takes the structural {@link SupportedMcpServer}
597
+ * both satisfy and branches on the internals where the two majors differ:
598
+ * where dispatch is intercepted (see {@link wrapIfNeeded}), how the intent
599
+ * params are built (`schemaCompat.injectGoalParamsV2`), and where the call's
600
+ * `_meta` lives (`mcpTypes.extraMeta`). Both are declared as OPTIONAL
601
+ * peerDependencies and neither is imported — at runtime or as a type — so a
602
+ * vendor installs whichever one they build on and nothing else.
603
+ *
604
+ * ```typescript
605
+ * import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; // or "@modelcontextprotocol/server"
606
+ * import { withBaton } from "@goodtiming/baton-sdk";
607
+ *
608
+ * const server = new McpServer({ name: "your-vendor-mcp", version: "1.0.0" });
609
+ * const handle = withBaton(server, {
610
+ * vendorId: "your-vendor",
611
+ * vendorDisplayName: "Your Vendor",
612
+ * consentToken: "...",
613
+ * });
614
+ * ```
615
+ *
616
+ * Wraps every tool call to emit `tool_call_start` → call → `tool_call_end` /
617
+ * `tool_call_error`, injects server `instructions` (SPEC §5.1.2), registers
618
+ * the `<vendor>_annotate` tool (SPEC §5.1.1), injects `user_goal`/
619
+ * `expected_result`/`overall_task` intent params on every wrapped tool's
620
+ * schema (SPEC §11.4.1 `call_intent`/`call_expected`/`call_workflow`/
621
+ * `intent_source`), and captures a `surface_snapshot`
622
+ * of the vendor-true surface. Every payload leaving here runs through the
623
+ * configured scrubber, which defaults to the shipped ruleset (`src/scrub.ts`)
624
+ * — see README "What's deferred" for what's still not here (the low-level
625
+ * `Server` adapter).
626
+ *
627
+ * Interception mechanism: `McpServer` has no middleware API (unlike the
628
+ * standalone `fastmcp` library's `Middleware`/`CallNext`), so this patches
629
+ * tool registration directly — the same shape Python's
630
+ * `baton.integrations.mcp` adapter uses against the official `mcp` SDK, for
631
+ * the same reason. Two passes, both required:
632
+ *
633
+ * 1. **Retroactive** — sweeps `server`'s already-registered tools (reaching
634
+ * into the private `_registeredTools` map, mirroring Python's
635
+ * `_registry.py` reaching into `_tool_manager._tools` — a documented,
636
+ * single swap point for an upstream rename PR, not an accident).
637
+ * 2. **Prospective** — patches `registerTool` so every tool registered
638
+ * *after* `withBaton(server, ...)` runs is wrapped too.
639
+ *
640
+ * Together these make call ordering irrelevant — `withBaton` can run before
641
+ * or after the vendor's own `registerTool` calls. Relying on only one pass
642
+ * (as a naive `registerTool`-only patch would) silently drops capture for
643
+ * tools registered on the other side of the ordering. The annotation tool
644
+ * itself is excluded from this wrapping — it emits its own `annotation`
645
+ * event instead of `tool_call_*`, same as the Python middleware's skip.
646
+ *
647
+ * Each wired entry's `.update()`/`.remove()` (mcp.js mutates the SAME
648
+ * `RegisteredTool` object in place for both) are also patched: an
649
+ * unpatched `.update()` replacing `paramsSchema`/`callback` would silently
650
+ * wipe injected params and swap back to the vendor's raw, unwrapped
651
+ * handler with no re-sweep able to detect it (the entry object identity
652
+ * never changes); an unpatched `.remove()` would leave a phantom tool in
653
+ * the surface snapshot forever.
654
+ *
655
+ * v2 makes the `.update()` patch carry more: there `remove()` IS
656
+ * `update({name: null})` and `disable()`/`enable()` are `update({enabled})`,
657
+ * all three routed through the entry's `update` *property* — so the patch
658
+ * has to branch on which update it received rather than look only for
659
+ * `paramsSchema`. It also supports renaming via `update({name})`, which 1.x
660
+ * technically allowed and this module used to document as an unreconciled
661
+ * gap; the surface snapshot, the param registry and the wrapper's own
662
+ * `tool_name` now all follow a rename.
663
+ *
664
+ * Instructions injection reaches into `server.server`'s private
665
+ * `_instructions` field — unlike Python's FastMCP (a read-only property
666
+ * with a private-attribute fallback), the official TS SDK's `Server` has no
667
+ * settable `instructions` at all post-construction, so there's no
668
+ * "preferred" public path to fall back from here. `buildServerMeta` (the
669
+ * `surface_snapshot` vendor-true baseline) MUST run before this assignment
670
+ * — otherwise the snapshot would capture Baton's own instructions text
671
+ * instead of the vendor's.
672
+ */
673
+
674
+ /** The surface of a high-level MCP server `withBaton` actually uses. Written
675
+ * structurally because the official SDK ships two nominally different
676
+ * `McpServer` classes — 1.x's (`@modelcontextprotocol/sdk/server/mcp.js`)
677
+ * and v2's (`@modelcontextprotocol/server`) — and both satisfy this. */
678
+ interface SupportedMcpServer {
679
+ readonly server: unknown;
680
+ registerTool(name: string, ...rest: unknown[]): unknown;
681
+ }
682
+ /** Install Baton into an `McpServer`. See module docstring for usage. */
683
+ declare function withBaton(server: SupportedMcpServer, config: BatonConfig): BatonHandle;
684
+
685
+ export { type AnnotationEvent, AnnotationEventSchema, type AnnotationPayload, AnnotationPayloadSchema, type BatonConfig, BatonHandle, DEPTH_LIMIT, type Event, EventSchema, type EventType, EventTypeSchema, HttpSink, type HttpSinkOptions, type ResolveSessionIdHook, SDK_VERSION, Scrubber, type SessionResolutionContext, type Sink, StdoutSink, type StdoutSinkOptions, type SupportedMcpServer, type SurfaceSnapshotEvent, SurfaceSnapshotEventSchema, type SurfaceSnapshotPayload, SurfaceSnapshotPayloadSchema, type ToolCallEndEvent, ToolCallEndEventSchema, type ToolCallEndPayload, ToolCallEndPayloadSchema, type ToolCallErrorEvent, ToolCallErrorEventSchema, type ToolCallErrorPayload, ToolCallErrorPayloadSchema, type ToolCallStartEvent, ToolCallStartEventSchema, type ToolCallStartPayload, ToolCallStartPayloadSchema, identityScrub, safeWrite, withBaton };