@goodtiming/baton-sdk 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -2
- package/dist/index.cjs +10 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +20 -4
- package/dist/index.d.ts +20 -4
- package/dist/index.js +10 -8
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/version.ts","../src/events.ts","../src/scrub.ts","../src/sinks.ts","../src/integrations/mcp/withBaton.ts","../src/integrations/mcp/annotation.ts","../src/integrations/mcp/emit.ts","../src/integrations/mcp/llmText.ts","../src/integrations/mcp/mcpTypes.ts","../src/integrations/mcp/runtimeAdapter.ts","../src/integrations/mcp/sessionResolution.ts","../src/integrations/mcp/config.ts","../src/integrations/mcp/handle.ts","../src/integrations/mcp/proactiveTracker.ts","../src/integrations/mcp/sessionCounter.ts","../src/integrations/mcp/zodCompat.ts","../src/integrations/mcp/schemaCompat.ts","../src/integrations/mcp/surface.ts"],"sourcesContent":["// TS-prefixed so `sdk_version` distinguishes TypeScript-sourced events from\n// Python (`baton-sdk`) ones in the Console — see design-notes/typescript_sdk.md.\nexport const SDK_VERSION = \"ts-0.1.0\";\n","/**\n * Zod schemas + TS types for the Baton event stream per SPEC §11.4.\n *\n * This is a hand-maintained mirror of `baton-spec/events.schema.json`, which\n * is itself exported from `baton-sdk` (Python)'s Pydantic models — that repo\n * is the schema of record. `test/conformance.test.ts` validates every\n * concrete type below against `baton-spec/events.schema.json` with ajv and\n * against `baton-spec/vectors/*.json`, so a drift here fails CI rather than\n * surfacing as a silent Console-side shape mismatch.\n *\n * All concrete event schemas share the same envelope fields and differ only\n * in `payload`. Fields match Python field-for-field (snake_case on the wire,\n * per CHARTER's wire-compatibility requirement — NOT camelCase).\n */\n\nimport { z } from \"zod\";\nimport { v7 as uuidv7 } from \"uuid\";\nimport { SDK_VERSION } from \"./version.js\";\n\n// =============================================================================\n// Per-event-type payloads\n// =============================================================================\n\n/** Emitted before the vendor handler runs. `params` is PII-scrubbed at\n * emit-time per SPEC §7.\n *\n * `call_intent` / `call_expected` / `call_workflow` are the values the SDK\n * stripped from the injected `user_goal` / `expected_result` /\n * `overall_task` params (see `llmText.ts`); they ride as SIBLINGS of\n * `params` — `params` stays exactly the vendor-visible arguments.\n * `call_intent`/`call_expected` are call-scoped diagnostics;\n * `call_workflow` is the task-label grouping key (console rung 3b, exact\n * string continuity). `intent_source` records provenance\n * (`\"injected_param\"`). All null when the params weren't used. */\nexport const ToolCallStartPayloadSchema = z\n .object({\n tool_name: z.string(),\n params: z.record(z.string(), z.unknown()).default({}),\n call_intent: z.string().nullable().default(null),\n call_expected: z.string().nullable().default(null),\n call_workflow: z.string().nullable().default(null),\n intent_source: z.string().nullable().default(null),\n })\n .strict();\nexport type ToolCallStartPayload = z.infer<typeof ToolCallStartPayloadSchema>;\n\n/** Emitted after the vendor handler returns. `result` is PII-scrubbed. */\nexport const ToolCallEndPayloadSchema = z\n .object({\n tool_name: z.string(),\n result: z.unknown().nullable().default(null),\n duration_ms: z.number().int().nullable().default(null),\n })\n .strict();\nexport type ToolCallEndPayload = z.infer<typeof ToolCallEndPayloadSchema>;\n\n/** Emitted when the vendor handler throws. `error_type` is the error's\n * constructor name; `error_body` is the message (PII-scrubbed, capped at\n * 2000 chars per the design note). */\nexport const ToolCallErrorPayloadSchema = z\n .object({\n tool_name: z.string(),\n error_type: z.string(),\n error_body: z.string(),\n duration_ms: z.number().int().nullable().default(null),\n })\n .strict();\nexport type ToolCallErrorPayload = z.infer<typeof ToolCallErrorPayloadSchema>;\n\n/** Agent-supplied context. All fields nullable per SPEC §5.1.1 — the agent\n * populates what it has. Proactive annotations typically populate\n * `intent`/`expected_outcome`/`workflow`; reactive annotations typically\n * populate `signal_type`/`suggested_improvement`. */\nexport const AnnotationPayloadSchema = z\n .object({\n intent: z.string().nullable().default(null),\n expected_outcome: z.string().nullable().default(null),\n signal_type: z.string().nullable().default(null),\n workflow: z.string().nullable().default(null),\n suggested_improvement: z.string().nullable().default(null),\n context: z.record(z.string(), z.unknown()).nullable().default(null),\n intent_source: z.string().nullable().default(null),\n tool_name: z.string().nullable().default(null),\n })\n .strict();\nexport type AnnotationPayload = z.infer<typeof AnnotationPayloadSchema>;\n\n/** The vendor-true upstream surface (pre-injection) — mirrors baton-proxy's\n * `enqueue_surface_snapshot` payload so the Console worker materializes both\n * into the same `vendor_surfaces` table. Emitted at most once per observed\n * `surface_hash` per process. `tools` excludes Baton's own injected tool(s);\n * those live in `seam_augmentations.injected_tools` instead. */\nexport const SurfaceSnapshotPayloadSchema = z\n .object({\n surface_hash: z.string(),\n server_info: z.record(z.string(), z.unknown()).nullable().default(null),\n capabilities: z.record(z.string(), z.unknown()).nullable().default(null),\n instructions: z.string().nullable().default(null),\n tools: z.array(z.record(z.string(), z.unknown())).default([]),\n seam_augmentations: z.record(z.string(), z.unknown()).default({}),\n })\n .strict();\nexport type SurfaceSnapshotPayload = z.infer<typeof SurfaceSnapshotPayloadSchema>;\n\n// =============================================================================\n// Envelope shared by all event types\n// =============================================================================\n\n/** Fields every Baton event carries, per SPEC §11.4.\n *\n * `consentToken` is REQUIRED — the Console rejects any event missing it.\n * `vendorId` is REQUIRED — the wrapped vendor identifier; the Console groups\n * friction by `(tenant_id, vendor_id)`.\n * `userId` is the hashed end-user actor (HMAC-SHA256, hashed at the capture\n * edge — the raw principal is never transmitted); null when unresolved.\n * `runtimeMeta` is the runtime-supplied MCP request `_meta` envelope, used\n * by the Console to derive turn/cycle boundaries more precise than\n * `session_id` alone. */\nconst envelopeShape = {\n event_id: z.uuid().default(() => uuidv7()),\n tenant_id: z.string(),\n vendor_id: z.string(),\n session_id: z.string(),\n sequence_number: z.number().int().nonnegative(),\n captured_at: z.string(),\n consent_token: z.string(),\n sdk_version: z.string().default(SDK_VERSION),\n agent_runtime: z.string().default(\"unknown\"),\n user_id: z.string().nullable().default(null),\n runtime_meta: z.record(z.string(), z.unknown()).nullable().default(null),\n};\n\nexport const EventTypeSchema = z.enum([\n \"tool_call_start\",\n \"tool_call_end\",\n \"tool_call_error\",\n \"annotation\",\n \"surface_snapshot\",\n]);\nexport type EventType = z.infer<typeof EventTypeSchema>;\n\n// =============================================================================\n// Concrete event schemas\n// =============================================================================\n\nexport const ToolCallStartEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"tool_call_start\").default(\"tool_call_start\"),\n payload: ToolCallStartPayloadSchema,\n })\n .strict();\nexport type ToolCallStartEvent = z.infer<typeof ToolCallStartEventSchema>;\n\nexport const ToolCallEndEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"tool_call_end\").default(\"tool_call_end\"),\n payload: ToolCallEndPayloadSchema,\n })\n .strict();\nexport type ToolCallEndEvent = z.infer<typeof ToolCallEndEventSchema>;\n\nexport const ToolCallErrorEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"tool_call_error\").default(\"tool_call_error\"),\n payload: ToolCallErrorPayloadSchema,\n })\n .strict();\nexport type ToolCallErrorEvent = z.infer<typeof ToolCallErrorEventSchema>;\n\nexport const AnnotationEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"annotation\").default(\"annotation\"),\n payload: AnnotationPayloadSchema,\n })\n .strict();\nexport type AnnotationEvent = z.infer<typeof AnnotationEventSchema>;\n\nexport const SurfaceSnapshotEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"surface_snapshot\").default(\"surface_snapshot\"),\n payload: SurfaceSnapshotPayloadSchema,\n })\n .strict();\nexport type SurfaceSnapshotEvent = z.infer<typeof SurfaceSnapshotEventSchema>;\n\n// =============================================================================\n// Discriminated union — mirrors Python's `Event` (discriminator: event_type)\n// =============================================================================\n\nexport const EventSchema = z.discriminatedUnion(\"event_type\", [\n ToolCallStartEventSchema,\n ToolCallEndEventSchema,\n ToolCallErrorEventSchema,\n AnnotationEventSchema,\n SurfaceSnapshotEventSchema,\n]);\nexport type Event =\n | ToolCallStartEvent\n | ToolCallEndEvent\n | ToolCallErrorEvent\n | AnnotationEvent\n | SurfaceSnapshotEvent;\n","/**\n * Source-side PII scrubbing for event payloads (SPEC §7).\n *\n * The SDK emits whatever the wrapped MCP server returns — including tool\n * params and results that may carry customer PII (emails in search results,\n * bearer tokens in error bodies, API keys pasted into chat tools). Persona\n * B's trust pitch is that nothing unscrubbed ever leaves the customer's\n * machine; this module is what makes that true. Every event payload runs\n * through `Scrubber` before it lands in the sink, so both local sinks AND\n * any HTTP sink see only scrubbed values.\n *\n * **Default ruleset** ships fixed for v1 (no public env-var configurability\n * — deferred until customer feedback justifies the surface area):\n *\n * - email — RFC-ish address regex\n * - bearer — `Bearer <opaque>` header values\n * - sk_key — OpenAI/Anthropic-style `sk-*` API keys\n * - aws_key — `AKIA*` access key IDs\n * - jwt — three-segment `eyJ*.*.*` tokens\n * - phone — North-American-leaning loose digit pattern\n * - cc — 13-19 digit candidates filtered by Luhn\n *\n * Plus field-name overrides: any object key matching\n * `{email, phone, ssn, api_key, token, secret, password, user_name}`\n * (case-insensitive) force-redacts its string value regardless of pattern.\n *\n * Differs from LangSmith's approach (off by default, bring-your-own regex)\n * by shipping rules on by default — the right tradeoff for Persona B's\n * consumer/SMB audience that won't write masking code.\n *\n * Ported from `baton` (Python)'s `src/baton/scrub.py` on 2026-08-11, which\n * is itself a parallel copy of baton-proxy's (the two are rule-identical —\n * verified by diff at port time; they differ only in docstrings). All three\n * ship parallel copies until the extracted shared package lands. Rule\n * parity here is verified by mirroring Python's `tests/test_scrub.py` test\n * matrix in `test/scrub.test.ts`; when a pattern lands or changes, port the\n * test every way.\n *\n * **Port notes** (where TypeScript forced a divergence from the Python):\n * - `counts` is a `Map<string, number>`, not a `collections.Counter`. Use\n * `count(category)` for Python's zero-default read.\n * - Python walks anything `isinstance(dict)`; this walks only *plain*\n * objects (`{}` / `Object.create(null)`). A `Date`, `Map`, or class\n * instance passes through untouched rather than being flattened to `{}`\n * — matching Python, where those aren't dicts either.\n */\n\n/** Cap on recursive walk depth. Matches LangSmith's default; protects\n * against pathological inputs without truncating realistic MCP payloads. */\nexport const DEPTH_LIMIT = 10;\n\n// Object keys whose string values are redacted regardless of value-pattern\n// match. Case-insensitive exact match (no plural / prefix matching to keep\n// false positives down). Kept narrow on purpose — too broad and we wreck\n// legitimate fields like `Slack:channel_token_string_id`.\n// `user_name` guards the PII half of a resolved end-user identity in the\n// event it ever lands in a payload — defence in depth for the console path\n// (residency contract). NOT `name`: that collides with legitimate payload\n// keys (prompt names, tool names in surface snapshots).\nconst REDACT_FIELD_NAMES: ReadonlySet<string> = new Set([\n \"email\",\n \"phone\",\n \"ssn\",\n \"api_key\",\n \"token\",\n \"secret\",\n \"password\",\n \"user_name\",\n]);\n\n// Ordered list of [category, pattern]. Order matters where patterns can\n// overlap: JWT must run before bearer because a bare JWT can look\n// bearer-shaped. sk_key / aws_key run before email because their token\n// bodies could otherwise match the email local-part regex.\n//\n// Every pattern carries `g`: Python's `re.sub` replaces ALL matches, while\n// a JS regex without `g` replaces only the first. Safe as module-level\n// constants because `String.prototype.replace` with a global regex resets\n// `lastIndex` itself — never call `.test()` on these.\nconst PATTERNS: ReadonlyArray<readonly [string, RegExp]> = [\n [\"jwt\", /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b/g],\n [\"bearer\", /\\bBearer\\s+[A-Za-z0-9_\\-.+/=]{16,}/gi],\n [\"sk_key\", /\\bsk-[A-Za-z0-9_-]{20,}\\b/g],\n [\"aws_key\", /\\bAKIA[0-9A-Z]{16}\\b/g],\n [\"email\", /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g],\n // Phone: optional `+1`, optional area-code parens, separators\n // `-` / `.` / space, 10 digits. Conservative — won't catch every\n // international format, but won't trip on every 10-digit identifier.\n [\"phone\", /\\b(?:\\+?1[\\s\\-.]?)?\\(?\\d{3}\\)?[\\s\\-.]?\\d{3}[\\s\\-.]?\\d{4}\\b/g],\n];\n\n// Credit-card candidates — Luhn-filtered before redacting to keep false\n// positives down on long numeric IDs (timestamps, order numbers).\nconst CC_CANDIDATE = /\\b\\d{13,19}\\b/g;\n\n/** Standard Luhn checksum. Caller passes a digits-only string of the right\n * length; we don't re-validate length here. */\nfunction luhnValid(digits: string): boolean {\n let total = 0;\n for (let i = 0; i < digits.length; i += 1) {\n let n = Number(digits[digits.length - 1 - i]);\n if (i % 2 === 1) {\n n *= 2;\n if (n > 9) n -= 9;\n }\n total += n;\n }\n return total % 10 === 0;\n}\n\n/** True only for `{...}` literals and `Object.create(null)` — the TS\n * analogue of Python's `isinstance(value, dict)`. Deliberately excludes\n * class instances, `Date`, `Map`, etc.: walking those would rebuild them as\n * bare objects and silently destroy the payload, whereas Python leaves them\n * alone because they aren't dicts. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const proto = Object.getPrototypeOf(value) as object | null;\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Stateful recursive scrubber with the default ruleset baked in.\n *\n * Construct one per `withBaton` call and reuse for every event. The\n * `counts` map accumulates per-category redaction counts across all calls\n * so a downstream report can surface \"N emails, M bearer tokens\" at render\n * time. Nothing on the wire carries these today — they exist for parity\n * with Python and for vendor-side introspection.\n *\n * Instances are callable-compatible via the bound `scrub` method, so a\n * `Scrubber` plugs into anywhere the `(value: unknown) => unknown` slot\n * that `BatonConfig.scrubber` accepts expects a plain function.\n */\nexport class Scrubber {\n readonly counts = new Map<string, number>();\n\n /** Bound so `new Scrubber().scrub` can be passed as a bare function\n * reference — the closest TS gets to Python's `__call__`. */\n readonly scrub = (value: unknown): unknown => this.walk(value, 0, null);\n\n /** Python's `Counter[category]` zero-default read. */\n count(category: string): number {\n return this.counts.get(category) ?? 0;\n }\n\n private bump(category: string): void {\n this.counts.set(category, this.count(category) + 1);\n }\n\n private walk(value: unknown, depth: number, forceField: string | null): unknown {\n if (depth >= DEPTH_LIMIT) return value;\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n // A sensitive key's force-redaction propagates DOWN into nested\n // containers, not just its immediate string value — `{\"password\":\n // [\"a\", \"b\"]}` redacts both items.\n const nextForce = REDACT_FIELD_NAMES.has(k.toLowerCase()) ? k.toLowerCase() : forceField;\n out[k] = this.walk(v, depth + 1, nextForce);\n }\n return out;\n }\n if (Array.isArray(value)) {\n return value.map((item) => this.walk(item, depth + 1, forceField));\n }\n if (typeof value === \"string\") {\n if (forceField !== null) {\n this.bump(`field:${forceField}`);\n return `[REDACTED:field-${forceField}]`;\n }\n return this.scrubString(value);\n }\n // number / boolean / null / undefined / Date / class instances — leave\n // alone. Sensitive data stored as a non-string at this leaf is rare in\n // MCP payloads and not worth the false-positive cost of stringifying\n // everything.\n return value;\n }\n\n private scrubString(s: string): string {\n let out = s;\n for (const [category, pattern] of PATTERNS) {\n out = out.replace(pattern, () => {\n this.bump(category);\n return `[REDACTED:${category}]`;\n });\n }\n // Credit card pass — separate because we Luhn-filter candidates before\n // counting / replacing. Skips non-CC long digit strings.\n return out.replace(CC_CANDIDATE, (match) => {\n if (!luhnValid(match)) return match;\n this.bump(\"cc\");\n return \"[REDACTED:cc]\";\n });\n }\n}\n\n/**\n * No-op scrubber. Exported for explicit opt-out — vendors / customers who\n * legitimately want raw payloads pass this where `new Scrubber().scrub`\n * would otherwise be the default. Not the default: the SDK ships the same\n * default ruleset as `baton` (Python) and baton-proxy so untouched\n * integrations get PII scrubbing without the operator having to opt in.\n */\nexport function identityScrub(value: unknown): unknown {\n return value;\n}\n","/**\n * Sinks — where Baton events go after the SDK captures them.\n *\n * A `Sink` is the egress side of the SDK; `withBaton` hands fully-formed\n * `Event` envelopes to a sink and the sink decides what to do with them.\n *\n * Two sinks ship, mirroring `sinks.py`'s core pair:\n *\n * - `StdoutSink` — JSONL to a writable stream (default `process.stderr`,\n * for the same reason as Python: MCP stdio transport reserves stdout for\n * JSON-RPC framing).\n * - `HttpSink` — POST to any HTTP endpoint with bearer auth; bounded\n * buffer, retry with backoff, circuit breaker. This is the contract a\n * Console or any compatible collector consumes.\n *\n * `FileSink` / `MultiSink` are deferred per design-notes/typescript_sdk.md\n * (\"HttpSink + StdoutSink covers all real use cases\") — add them if a real\n * need shows up rather than porting them speculatively.\n */\n\nimport type { Event } from \"./events.js\";\n\nexport interface Sink {\n /** Hand one event to the sink. Resolves once the sink has accepted it\n * (which may mean buffered, not yet shipped). MUST NOT block the\n * producer on slow downstream destinations. */\n write(event: Event): Promise<void>;\n /** Wait for any buffered events to reach their destination (or be\n * dropped per the sink's policy). No-op for synchronous sinks. */\n flush(): Promise<void>;\n /** Flush + release resources. After `aclose`, `write` rejects. */\n aclose(): Promise<void>;\n}\n\n/** Fail-open wrapper around `sink.write`.\n *\n * The MCP tool wrapper sits BEFORE the vendor's tool handler runs. A reject\n * from `sink.write` (closed sink, transport error, etc.) would otherwise\n * propagate up and break the vendor's tool call — making Baton\n * instrumentation look like a vendor bug. SPEC §11.2 mandates fail-open at\n * the capture boundary; this wrapper enforces it. */\nexport async function safeWrite(sink: Sink, event: Event): Promise<void> {\n try {\n await sink.write(event);\n } catch (err) {\n process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${String(err)}\\n`);\n }\n}\n\n// =============================================================================\n// StdoutSink — JSONL to a writable stream (default: stderr)\n// =============================================================================\n\nexport interface StdoutSinkOptions {\n /** Defaults to `process.stderr` — stdio MCP transport reserves stdout for\n * JSON-RPC framing. Pass `process.stdout` explicitly for non-MCP (library\n * API) use if preferred. */\n stream?: NodeJS.WritableStream;\n}\n\nexport class StdoutSink implements Sink {\n private readonly stream: NodeJS.WritableStream;\n private closed = false;\n\n constructor(options: StdoutSinkOptions = {}) {\n this.stream = options.stream ?? process.stderr;\n }\n\n async write(event: Event): Promise<void> {\n if (this.closed) throw new Error(\"StdoutSink is closed\");\n this.stream.write(JSON.stringify(event) + \"\\n\");\n }\n\n async flush(): Promise<void> {\n // Node writable streams don't expose a synchronous flush; write() above\n // already pushes each line through immediately.\n }\n\n async aclose(): Promise<void> {\n this.closed = true;\n // Don't end the stream — we don't own stderr/stdout.\n }\n}\n\n// =============================================================================\n// HttpSink — POST + bearer + bounded buffer + retry + circuit breaker\n// =============================================================================\n\ntype SendOutcome = \"success\" | \"permanent_failure\" | \"transient_failure\";\n\nclass CircuitBreaker {\n private failures = 0;\n private openedAt: number | null = null;\n\n constructor(\n private readonly threshold: number,\n private readonly resetMs: number,\n ) {}\n\n canRequest(): boolean {\n if (this.openedAt === null) return true;\n return Date.now() - this.openedAt >= this.resetMs;\n }\n\n recordSuccess(): void {\n this.failures = 0;\n this.openedAt = null;\n }\n\n recordFailure(): void {\n this.failures += 1;\n if (this.failures >= this.threshold) {\n this.openedAt = Date.now();\n }\n }\n}\n\nexport interface HttpSinkOptions {\n apiKey: string;\n bufferSize?: number;\n requestTimeoutMs?: number;\n maxRetries?: number;\n backoffBaseMs?: number;\n backoffMaxMs?: number;\n circuitBreakerThreshold?: number;\n circuitBreakerResetMs?: number;\n /** Injectable for tests; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n}\n\n/** POST events to an HTTP endpoint. Bounded buffer + retry + circuit breaker.\n *\n * This is the contract a Console or any compatible collector consumes:\n * `POST {url}/v0/events` with `Authorization: Bearer {apiKey}` and a JSON\n * body matching the SPEC §11.4 envelope.\n *\n * Failures are bounded — buffer overflow drops the oldest event; network\n * failures retry with backoff; the circuit breaker opens after consecutive\n * failures so the SDK doesn't pile retries on a known-bad endpoint. */\nexport class HttpSink implements Sink {\n private readonly url: string;\n private readonly apiKey: string;\n private readonly buffer: Event[] = [];\n private readonly bufferSize: number;\n private readonly maxRetries: number;\n private readonly backoffBaseMs: number;\n private readonly backoffMaxMs: number;\n private readonly circuit: CircuitBreaker;\n private readonly fetchImpl: typeof fetch;\n private overflowWarned = false;\n private closed = false;\n private drainChain: Promise<void> = Promise.resolve();\n private beforeExitHandler: (() => void) | null = null;\n\n constructor(url: string, options: HttpSinkOptions) {\n this.url = url.replace(/\\/+$/, \"\");\n this.apiKey = options.apiKey;\n this.bufferSize = options.bufferSize ?? 1000;\n this.maxRetries = options.maxRetries ?? 3;\n this.backoffBaseMs = options.backoffBaseMs ?? 100;\n this.backoffMaxMs = options.backoffMaxMs ?? 5000;\n this.circuit = new CircuitBreaker(\n options.circuitBreakerThreshold ?? 5,\n options.circuitBreakerResetMs ?? 30_000,\n );\n this.fetchImpl = options.fetchImpl ?? fetch;\n }\n\n async write(event: Event): Promise<void> {\n if (this.closed) throw new Error(\"HttpSink is closed\");\n this.enqueue(event);\n void this.scheduleDrain();\n this.ensureBeforeExitRegistered();\n }\n\n async flush(): Promise<void> {\n if (this.closed) return;\n await this.scheduleDrain();\n }\n\n async aclose(): Promise<void> {\n if (this.closed) return;\n await this.flush();\n this.closed = true;\n if (this.beforeExitHandler) {\n process.off(\"beforeExit\", this.beforeExitHandler);\n this.beforeExitHandler = null;\n }\n }\n\n private enqueue(event: Event): void {\n if (this.buffer.length >= this.bufferSize) {\n if (!this.overflowWarned) {\n process.emitWarning(\n `Baton HTTP sink buffer full (${this.bufferSize}); oldest events dropped. Further overflows will be silent.`,\n );\n this.overflowWarned = true;\n }\n this.buffer.shift();\n }\n this.buffer.push(event);\n }\n\n /** Serializes every call to `drainLocked` — from `write()`'s background\n * drain and from explicit `flush()` alike — onto one promise chain, so\n * concurrent tool calls (the normal case once the MCP interceptor is\n * wired up) can never run two drains at once racing on `buffer[0]`/\n * `shift()`. Mirrors Python's `asyncio.Lock` around `_drain_locked`. */\n private scheduleDrain(): Promise<void> {\n this.drainChain = this.drainChain.then(\n () => this.drainLocked(),\n () => this.drainLocked(),\n );\n return this.drainChain;\n }\n\n /** Best-effort flush when the process is about to exit without an\n * explicit `aclose()`. Node re-runs `beforeExit` if new async work is\n * scheduled during it, so an in-flight flush here can complete normally —\n * unlike Python's synchronous `atexit`, no separate sync-client fallback\n * is needed. Real residual gap, not fixable in-process: SIGKILL, or\n * SIGTERM with no installed handler, skip `beforeExit` entirely. A vendor\n * needing that guarantee must call `aclose()` from their own handler. */\n private ensureBeforeExitRegistered(): void {\n if (this.beforeExitHandler) return;\n this.beforeExitHandler = () => {\n void this.flush();\n };\n process.on(\"beforeExit\", this.beforeExitHandler);\n }\n\n private events_url(): string {\n return `${this.url}/v0/events`;\n }\n\n private authHeaders(): Record<string, string> {\n return { Authorization: `Bearer ${this.apiKey}`, \"Content-Type\": \"application/json\" };\n }\n\n private static classifyStatus(status: number): SendOutcome {\n if (status >= 200 && status < 300) return \"success\";\n if (status >= 400 && status < 500 && status !== 429) return \"permanent_failure\";\n return \"transient_failure\";\n }\n\n private async drainLocked(): Promise<void> {\n while (this.buffer.length > 0) {\n if (!this.circuit.canRequest()) return;\n const event = this.buffer[0]!;\n const outcome = await this.sendWithRetry(event);\n if (outcome === \"success\" || outcome === \"permanent_failure\") {\n this.buffer.shift();\n this.circuit.recordSuccess();\n } else {\n this.circuit.recordFailure();\n return;\n }\n }\n }\n\n private async sendWithRetry(event: Event): Promise<SendOutcome> {\n const url = this.events_url();\n const headers = this.authHeaders();\n const body = JSON.stringify(event);\n\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n try {\n const response = await this.fetchImpl(url, { method: \"POST\", headers, body });\n const outcome = HttpSink.classifyStatus(response.status);\n if (outcome !== \"transient_failure\") return outcome;\n } catch {\n // network error — fall through to retry/backoff below\n }\n if (attempt < this.maxRetries) {\n const backoff = Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs);\n await new Promise((resolve) => setTimeout(resolve, backoff));\n }\n }\n return \"transient_failure\";\n }\n}\n","/**\n * `withBaton` — the vendor's MCP integration entry point for the official\n * `@modelcontextprotocol/sdk`'s high-level `McpServer` — and the v2\n * packages' (`@modelcontextprotocol/server`), which are a different class of\n * the same name. `withBaton` takes the structural {@link SupportedMcpServer}\n * both satisfy and branches on the internals where the two majors differ:\n * where dispatch is intercepted (see {@link wrapIfNeeded}), how the intent\n * params are built (`schemaCompat.injectGoalParamsV2`), and where the call's\n * `_meta` lives (`mcpTypes.extraMeta`). Both are declared as OPTIONAL\n * peerDependencies and neither is imported — at runtime or as a type — so a\n * vendor installs whichever one they build on and nothing else.\n *\n * ```typescript\n * import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"; // or \"@modelcontextprotocol/server\"\n * import { withBaton } from \"@goodtiming/baton-sdk\";\n *\n * const server = new McpServer({ name: \"your-vendor-mcp\", version: \"1.0.0\" });\n * const handle = withBaton(server, {\n * vendorId: \"your-vendor\",\n * vendorDisplayName: \"Your Vendor\",\n * consentToken: \"...\",\n * });\n * ```\n *\n * Wraps every tool call to emit `tool_call_start` → call → `tool_call_end` /\n * `tool_call_error`, injects server `instructions` (SPEC §5.1.2), registers\n * the `<vendor>_annotate` tool (SPEC §5.1.1), injects `user_goal`/\n * `expected_result`/`overall_task` intent params on every wrapped tool's\n * schema (SPEC §11.4.1 `call_intent`/`call_expected`/`call_workflow`/\n * `intent_source`), and captures a `surface_snapshot`\n * of the vendor-true surface. Every payload leaving here runs through the\n * configured scrubber, which defaults to the shipped ruleset (`src/scrub.ts`)\n * — see README \"What's deferred\" for what's still not here (the low-level\n * `Server` adapter).\n *\n * Interception mechanism: `McpServer` has no middleware API (unlike the\n * standalone `fastmcp` library's `Middleware`/`CallNext`), so this patches\n * tool registration directly — the same shape Python's\n * `baton.integrations.mcp` adapter uses against the official `mcp` SDK, for\n * the same reason. Two passes, both required:\n *\n * 1. **Retroactive** — sweeps `server`'s already-registered tools (reaching\n * into the private `_registeredTools` map, mirroring Python's\n * `_registry.py` reaching into `_tool_manager._tools` — a documented,\n * single swap point for an upstream rename PR, not an accident).\n * 2. **Prospective** — patches `registerTool` so every tool registered\n * *after* `withBaton(server, ...)` runs is wrapped too.\n *\n * Together these make call ordering irrelevant — `withBaton` can run before\n * or after the vendor's own `registerTool` calls. Relying on only one pass\n * (as a naive `registerTool`-only patch would) silently drops capture for\n * tools registered on the other side of the ordering. The annotation tool\n * itself is excluded from this wrapping — it emits its own `annotation`\n * event instead of `tool_call_*`, same as the Python middleware's skip.\n *\n * Each wired entry's `.update()`/`.remove()` (mcp.js mutates the SAME\n * `RegisteredTool` object in place for both) are also patched: an\n * unpatched `.update()` replacing `paramsSchema`/`callback` would silently\n * wipe injected params and swap back to the vendor's raw, unwrapped\n * handler with no re-sweep able to detect it (the entry object identity\n * never changes); an unpatched `.remove()` would leave a phantom tool in\n * the surface snapshot forever.\n *\n * v2 makes the `.update()` patch carry more: there `remove()` IS\n * `update({name: null})` and `disable()`/`enable()` are `update({enabled})`,\n * all three routed through the entry's `update` *property* — so the patch\n * has to branch on which update it received rather than look only for\n * `paramsSchema`. It also supports renaming via `update({name})`, which 1.x\n * technically allowed and this module used to document as an unreconciled\n * gap; the surface snapshot, the param registry and the wrapper's own\n * `tool_name` now all follow a rename.\n *\n * Instructions injection reaches into `server.server`'s private\n * `_instructions` field — unlike Python's FastMCP (a read-only property\n * with a private-attribute fallback), the official TS SDK's `Server` has no\n * settable `instructions` at all post-construction, so there's no\n * \"preferred\" public path to fall back from here. `buildServerMeta` (the\n * `surface_snapshot` vendor-true baseline) MUST run before this assignment\n * — otherwise the snapshot would capture Baton's own instructions text\n * instead of the vendor's.\n */\n\nimport { v7 as uuidv7 } from \"uuid\";\nimport {\n AnnotationEventSchema,\n SurfaceSnapshotEventSchema,\n ToolCallEndEventSchema,\n ToolCallErrorEventSchema,\n ToolCallStartEventSchema,\n} from \"../../events.js\";\nimport { StdoutSink, type Sink } from \"../../sinks.js\";\nimport { registerAnnotationTool } from \"./annotation.js\";\nimport { Scrubber } from \"../../scrub.js\";\nimport { validateBatonConfig, type BatonConfig } from \"./config.js\";\nimport { emit } from \"./emit.js\";\nimport { BatonHandle } from \"./handle.js\";\nimport { buildServerInstructions } from \"./llmText.js\";\nimport {\n EXPECTED_RESULT_PARAM_NAME,\n INTENT_SOURCE_PARAM,\n OVERALL_TASK_PARAM_NAME,\n USER_GOAL_PARAM_NAME,\n} from \"./llmText.js\";\nimport { extraMeta, type Extra } from \"./mcpTypes.js\";\nimport { ProactiveTracker } from \"./proactiveTracker.js\";\nimport { detectAgentRuntime } from \"./runtimeAdapter.js\";\nimport { resolveSessionId } from \"./sessionResolution.js\";\nimport { SessionCounter } from \"./sessionCounter.js\";\nimport {\n injectGoalParams,\n injectGoalParamsV2,\n toolInputJsonSchema,\n type IntentParamDispositions,\n type IntentParamMode,\n} from \"./schemaCompat.js\";\nimport { assembleSurface, buildServerMeta, buildSeamAugmentations, surfaceHash } from \"./surface.js\";\n\ntype AnyArgs = unknown[];\ntype AnyHandler = (...args: AnyArgs) => unknown;\ntype TaggedHandler = AnyHandler & { [BATON_WRAPPED]?: boolean };\n\ninterface WrapContext {\n sink: Sink;\n counter: SessionCounter;\n tenantId: string;\n vendorId: string;\n consentToken: string;\n fallbackSessionId: string;\n defaultAgentRuntime: string;\n scrubber: (value: unknown) => unknown;\n resolveSessionId: BatonConfig[\"resolveSessionId\"];\n annotationToolName: string;\n intentParamMode: IntentParamMode;\n paramRegistry: Map<string, IntentParamDispositions>;\n /** Vendor-true JSON Schema for the surface snapshot, in whatever spelling\n * THIS server actually puts on the wire. */\n vendorToolJsonSchema: (name: string, inputSchema: unknown) => Record<string, unknown>;\n /** Drop v2's per-tool JSON-Schema memo after we mutate `inputSchema`. */\n bustSchemaMemo: (name: string) => void;\n tracker: ProactiveTracker;\n surfaceState: SurfaceState;\n emitSurface: (\n sessionId: string,\n digest: string,\n snapshot: Record<string, unknown>,\n ) => Promise<void>;\n}\n\n// `_registeredTools`, `RegisteredTool.handler`/`.executor`,\n// `server.server._instructions` and `server.server._serverInfo` are internal\n// to the official SDK — 1.x and v2 alike — and not part of either public\n// `.d.ts` surface. Reaching into them is deliberate (see module docstring),\n// the same way Python's `_registry.py` does, and isolated to this one module\n// so a future SDK internals change has exactly one place to update. Each\n// reach-in is declared on a named local shape (`internals` in `withBaton`,\n// the small casts in `wrapIfNeeded`/`captureAndInject`) rather than an\n// `any`, so a rename upstream lands as a compile error here.\n\nconst BATON_WRAPPED = Symbol(\"batonWrapped\");\nconst wired = new WeakSet<object>();\n\n/** Tracks the vendor-true (pre-injection) tool surface for this install, for\n * `surface_snapshot` capture. Built from data already in hand at wrap time\n * and lazily hashed+emitted on the next tool call — mirrors the official\n * mcp SDK's Python adapter, which has the same \"no tools/list hook\"\n * constraint and makes the same lazy-on-first-call choice for the same\n * reason (see `project_sdk_sensor_parity_gap` memory). */\nclass SurfaceState {\n /** Every tool this install has seen, keyed by its CURRENT name. `disabled`\n * is tracked alongside rather than pruned, so re-enabling costs nothing and\n * — crucially — never needs a re-capture, which would re-read Baton's own\n * injected schema as if it were vendor-true. */\n private readonly rawTools = new Map<\n string,\n { disabled: boolean; tool: Record<string, unknown> }\n >();\n readonly emittedHashes = new Set<string>();\n dirty = false;\n\n constructor(private readonly serverMeta: ReturnType<typeof buildServerMeta>) {}\n\n /** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,\n * which picks the spelling THIS SDK major puts on the wire. */\n noteTool(\n name: string,\n inputSchemaJson: Record<string, unknown>,\n description: string | undefined,\n ): void {\n this.rawTools.set(name, {\n disabled: this.rawTools.get(name)?.disabled ?? false,\n tool: { name, description: description ?? null, inputSchema: inputSchemaJson },\n });\n this.dirty = true;\n }\n\n pruneTool(name: string): void {\n if (this.rawTools.delete(name)) this.dirty = true;\n }\n\n /** Follow a `update({name})` rename, keeping the snapshot keyed the way\n * `tools/list` now renders it. */\n renameTool(from: string, to: string): void {\n const entry = this.rawTools.get(from);\n if (!entry) return;\n this.rawTools.delete(from);\n this.rawTools.set(to, { ...entry, tool: { ...entry.tool, name: to } });\n this.dirty = true;\n }\n\n /** Both majors filter `tools/list` on `tool.enabled`, so a disabled tool is\n * not part of the surface a client sees and must not be part of the one we\n * hash. Leaving it in is the same phantom-tool defect the `.remove()` patch\n * exists to prevent, reached through `disable()` instead. */\n setToolEnabled(name: string, enabled: boolean): void {\n const entry = this.rawTools.get(name);\n if (!entry || entry.disabled === !enabled) return;\n entry.disabled = !enabled;\n this.dirty = true;\n }\n\n buildSnapshot(): Record<string, unknown> {\n const names = [...this.rawTools.keys()].sort().filter((n) => !this.rawTools.get(n)!.disabled);\n return assembleSurface(\n this.serverMeta,\n names.map((n) => this.rawTools.get(n)!.tool),\n );\n }\n}\n\n/** `nameRef` is read on every call, not captured: v2's `update({name})`\n * renames a tool in place, keeping the same entry object AND the same\n * executor, so a wrapper that closed over the registration-time string would\n * keep emitting events under the old `tool_name` and keep missing its own\n * param-registry entry — which downgrades the strip to the cold-registry\n * path and puts a warning on the vendor's stderr for every call. */\nfunction batonWrap(nameRef: { current: string }, original: AnyHandler, ctx: WrapContext): AnyHandler {\n return async (...callArgs: AnyArgs): Promise<unknown> => {\n const toolName = nameRef.current;\n await maybeEmitSurfaceSnapshot(ctx);\n\n const extra = callArgs[callArgs.length - 1] as Extra;\n // 1.x calls a schema-less tool as `(extra)`; v2 always calls its\n // executor `(args, ctx)` and passes `args === undefined` for one. Both\n // land on `{}` here — and the ORIGINAL `callArgs` is what gets\n // delegated, so the arity fork stays inside the callee either way.\n const params = ((callArgs.length > 1 ? callArgs[0] : undefined) ?? {}) as Record<\n string,\n unknown\n >;\n const meta = extraMeta(extra);\n const runtime = detectAgentRuntime(meta) ?? ctx.defaultAgentRuntime;\n const scrubbedMeta = meta ? (ctx.scrubber(meta) as Record<string, unknown>) : null;\n const sessionId = await resolveSessionId(\n ctx.resolveSessionId,\n ctx.fallbackSessionId,\n extra,\n meta,\n toolName,\n params,\n );\n\n // Strip the injected goal params IN PLACE, before snapshotting params —\n // `params` is the SAME object forwarded to the vendor handler, so the\n // strip keeps user_goal/expected_result off the tool AND out of the\n // captured `params` (which must equal the vendor-visible arguments).\n const dispositions = ctx.paramRegistry.get(toolName);\n const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions);\n const rawExpected = extractGoalParam(\n params,\n EXPECTED_RESULT_PARAM_NAME,\n toolName,\n dispositions,\n );\n const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions);\n const scrubbedIntent = rawIntent !== null ? (ctx.scrubber(rawIntent) as string) : null;\n const scrubbedExpected = rawExpected !== null ? (ctx.scrubber(rawExpected) as string) : null;\n // Scrubbed like the other two. Deterministic redaction preserves the\n // exact-string continuity rung 3b groups on: the same label scrubs to\n // the same output on every call.\n const scrubbedWorkflow = rawWorkflow !== null ? (ctx.scrubber(rawWorkflow) as string) : null;\n\n const common = {\n tenant_id: ctx.tenantId,\n vendor_id: ctx.vendorId,\n session_id: sessionId,\n consent_token: ctx.consentToken,\n agent_runtime: runtime,\n runtime_meta: scrubbedMeta,\n };\n\n // The session's FIRST injected intent also becomes a proactive\n // annotation (carrying expected_result too, if present), sequenced\n // BEFORE the tool_call_start it explains. `claim` dedups per session\n // and is suppressed when a real annotation-tool proactive already\n // fired. Later param intents ride only the start event.\n if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {\n await emit(ctx.sink, () =>\n AnnotationEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.next(sessionId),\n captured_at: new Date().toISOString(),\n payload: {\n intent: scrubbedIntent,\n expected_outcome: scrubbedExpected,\n intent_source: INTENT_SOURCE_PARAM,\n tool_name: toolName,\n },\n }),\n );\n }\n\n await emit(ctx.sink, () =>\n ToolCallStartEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.next(sessionId),\n captured_at: new Date().toISOString(),\n payload: {\n tool_name: toolName,\n params: ctx.scrubber(params),\n call_intent: scrubbedIntent,\n call_expected: scrubbedExpected,\n call_workflow: scrubbedWorkflow,\n intent_source: scrubbedIntent !== null ? INTENT_SOURCE_PARAM : null,\n },\n }),\n );\n\n const startedAt = performance.now();\n let result: unknown;\n try {\n result = await original(...callArgs);\n } catch (err) {\n const durationMs = Math.round(performance.now() - startedAt);\n const message = err instanceof Error ? err.message : String(err);\n await emit(ctx.sink, () =>\n ToolCallErrorEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.next(sessionId),\n captured_at: new Date().toISOString(),\n payload: {\n tool_name: toolName,\n error_type: err instanceof Error ? err.constructor.name : \"Error\",\n error_body: String(ctx.scrubber(message)).slice(0, 2000),\n duration_ms: durationMs,\n },\n }),\n );\n throw err;\n }\n\n const durationMs = Math.round(performance.now() - startedAt);\n await emit(ctx.sink, () =>\n ToolCallEndEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.next(sessionId),\n captured_at: new Date().toISOString(),\n payload: { tool_name: toolName, result: ctx.scrubber(result), duration_ms: durationMs },\n }),\n );\n\n return result;\n };\n}\n\n/** Pop an injected goal param from `args` in place; return its value.\n * `\"native\"` (the tool already declares this name itself) forwards the\n * caller's own value untouched — never stripped, never reported as intent.\n * Unlisted (a call arrived before this tool was ever wired, or\n * `intentParamMode` was \"off\" when it was) strips defensively with a\n * warning: safe only because these two names are reserved. */\nfunction extractGoalParam(\n args: Record<string, unknown>,\n paramName: string,\n toolName: string,\n dispositions: IntentParamDispositions | undefined,\n): string | null {\n if (!(paramName in args)) return null;\n const disposition = dispositions ? dispositions[paramName] : undefined;\n if (disposition === \"native\") return null;\n if (disposition === undefined) {\n process.stderr.write(\n `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)\\n`,\n );\n }\n const raw = args[paramName];\n delete args[paramName];\n return typeof raw === \"string\" && raw.trim() ? raw : null;\n}\n\n/** Lazy, fail-open surface_snapshot capture — the first tool call after any\n * registration change re-hashes the surface and emits iff the hash hasn't\n * been seen before. `dirty` is cleared FIRST so a hashing/serialization\n * error (deterministic — would just re-throw identically every call) costs\n * one attempt per surface change, not a retry storm. A WRITE failure is\n * different (sink health can recover), so that path re-sets `dirty = true`\n * to retry on the next call; `emittedHashes` only gains an entry AFTER a\n * successful write, so a transient failure can't permanently drop a\n * surface the way a genuine dedup skip would. */\nasync function maybeEmitSurfaceSnapshot(ctx: WrapContext): Promise<void> {\n if (!ctx.surfaceState.dirty) return;\n ctx.surfaceState.dirty = false;\n let snapshot: Record<string, unknown>;\n let digest: string;\n try {\n snapshot = ctx.surfaceState.buildSnapshot();\n digest = surfaceHash(snapshot);\n } catch (err) {\n process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}\\n`);\n return;\n }\n if (ctx.surfaceState.emittedHashes.has(digest)) return;\n const seam = buildSeamAugmentations({\n injectedToolNames: [ctx.annotationToolName],\n intentParamNames: [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME],\n intentParamMode: ctx.intentParamMode,\n });\n try {\n await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });\n } catch (err) {\n process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}\\n`);\n ctx.surfaceState.dirty = true;\n return;\n }\n ctx.surfaceState.emittedHashes.add(digest);\n}\n\n/** Capture the entry's CURRENT `inputSchema` as vendor-true and splice in\n * the goal params. Only safe to call when `inputSchema` is known-fresh\n * (vendor-true, not already carrying a prior injection) — i.e. at first\n * processing, or right after a `.update()` call that itself supplied a new\n * `paramsSchema` (mcp.js replaces `inputSchema` wholesale in that case, so\n * whatever was captured/injected before is gone regardless of what this\n * function does). Calling it on an entry whose schema is STILL Baton's own\n * previously-injected version would misread `user_goal`/`expected_result`\n * as the vendor's own fields (`\"native\"` disposition) and silently stop\n * stripping/capturing them — callers must gate on that, not call this\n * unconditionally on every `.update()`. */\nfunction captureAndInject(name: string, entry: unknown, ctx: WrapContext): void {\n if (!entry || typeof entry !== \"object\") return;\n const mutable = entry as { inputSchema?: unknown; description?: string; executor?: unknown };\n ctx.surfaceState.noteTool(name, ctx.vendorToolJsonSchema(name, mutable.inputSchema), mutable.description);\n if (ctx.intentParamMode === \"off\") return;\n const isV2 = typeof mutable.executor === \"function\";\n try {\n const { schema, dispositions } = isV2\n ? injectGoalParamsV2(mutable.inputSchema)\n : injectGoalParams(mutable.inputSchema);\n if (Object.keys(dispositions).length > 0) {\n // Assigned directly rather than via `entry.update({paramsSchema})`,\n // which would route back through our OWN patched update and re-read\n // Baton's just-injected schema as if it were vendor-true — flipping\n // every injected param's disposition to \"native\" and silently\n // stopping the strip. The memo bust below is what `update` would have\n // done for us.\n mutable.inputSchema = schema;\n ctx.bustSchemaMemo(name);\n ctx.paramRegistry.set(name, dispositions);\n } else {\n ctx.paramRegistry.delete(name);\n }\n } catch {\n // Fail open — a schema this module can't handle just skips injection\n // for this tool; capture/wrap of the tool itself is unaffected.\n }\n}\n\n/** Wrap the entry's CURRENT dispatch target iff it isn't already Baton's\n * wrapper. The `BATON_WRAPPED` tag lives on the wrapped FUNCTION, not the\n * entry object, so a `.update()` that swaps in a fresh vendor callback\n * (untagged) is correctly reprocessed, while one that leaves it alone is a\n * cheap no-op.\n *\n * WHICH function that is differs by SDK major, and getting it wrong fails\n * silently. 1.x's `tools/call` handler invokes `entry.handler`, so patching\n * that field intercepts the call. **v2 dispatches through `entry.executor`**\n * — a closure built at registration over the handler\n * (`createToolExecutor(inputSchema, handler)`; `executeToolHandler` is\n * literally `return tool.executor(args, ctx)`). Patching `entry.handler` on\n * v2 therefore does nothing at all: the vendor handler still runs, the\n * wrapper never fires, and the server emits zero events while looking\n * perfectly healthy — measured against `@modelcontextprotocol/server@2.0.0`\n * and pinned by `test/integrations/mcp/withBatonV2.test.ts`, whose RED\n * signature against a handler-only patch is an empty event list and no\n * error at all. Worse, the schema half\n * of `withBaton` keeps working, so a half-ported install would advertise\n * intent params, collect a goal from the agent, and capture none of it.\n *\n * On v2 we wrap the executor by capture-and-delegate, and deliberately do\n * NOT also wrap `entry.handler`: nothing dispatches through it there, and\n * tagging both would double-wrap once `update({callback})` regenerates the\n * executor over the untouched handler. */\nfunction wrapIfNeeded(nameRef: { current: string }, entry: unknown, ctx: WrapContext): void {\n if (!entry || typeof entry !== \"object\") return;\n const mutable = entry as { handler: unknown; executor?: unknown };\n\n if (typeof mutable.executor === \"function\") {\n if ((mutable.executor as TaggedHandler)[BATON_WRAPPED]) return;\n const originalExecutor = mutable.executor as AnyHandler;\n const wrapper = batonWrap(nameRef, originalExecutor, ctx) as TaggedHandler;\n wrapper[BATON_WRAPPED] = true;\n mutable.executor = wrapper;\n return;\n }\n\n // Task-based tools (experimental) carry an object, not a function, at\n // .handler — leave them untouched rather than guess at wrapping a shape\n // we don't capture events for yet.\n if (typeof mutable.handler !== \"function\") return;\n if ((mutable.handler as TaggedHandler)[BATON_WRAPPED]) return;\n const original = mutable.handler as AnyHandler;\n const wrapper = batonWrap(nameRef, original, ctx) as TaggedHandler;\n wrapper[BATON_WRAPPED] = true;\n mutable.handler = wrapper;\n}\n\nfunction wireEntry(name: string, entry: unknown, ctx: WrapContext): void {\n if (name === ctx.annotationToolName) return;\n if (!entry || typeof entry !== \"object\") return;\n\n // First-time processing: inputSchema is guaranteed vendor-true (nothing\n // has injected into it yet) and the dispatch target is guaranteed\n // untagged, so both steps always apply together here — unlike the\n // .update() path below, which must reason about which one, if either,\n // actually needs to re-run.\n // The tool's CURRENT name. v2's `update({name})` re-keys `_registeredTools`\n // in place, keeping the same entry object AND its wrapper, so everything\n // below reads through this box rather than capturing the string.\n const nameRef = { current: name };\n\n captureAndInject(name, entry, ctx);\n wrapIfNeeded(nameRef, entry, ctx);\n\n if (wired.has(entry)) return;\n wired.add(entry);\n\n const removable = entry as { remove?: unknown };\n if (typeof removable.remove === \"function\") {\n const originalRemove = (removable.remove as () => void).bind(entry);\n (removable as { remove: () => void }).remove = () => {\n originalRemove();\n ctx.surfaceState.pruneTool(nameRef.current);\n ctx.paramRegistry.delete(nameRef.current);\n };\n }\n\n const updatable = entry as { update?: unknown };\n if (typeof updatable.update === \"function\") {\n const originalUpdate = (updatable.update as (updates: unknown) => void).bind(entry);\n (updatable as { update: (updates: unknown) => void }).update = (updates: unknown) => {\n const u = (updates ?? {}) as {\n paramsSchema?: unknown;\n name?: string | null;\n enabled?: boolean;\n };\n const renameTo = u.name;\n originalUpdate(updates);\n\n // v2 routes BOTH removal and rename through `update({name})` —\n // `remove()` is `update({name: null})`, and `disable()`/`enable()` are\n // `update({enabled})`. Handling only `paramsSchema` here would let a\n // v2 removal leave a phantom tool in the surface snapshot forever,\n // which is the exact defect the `.remove()` patch above exists to\n // prevent; a rename would strand the surface entry and the param\n // registry under the old key, and a stranded registry stops the strip\n // so Baton's own params would start reaching the vendor's handler.\n if (renameTo === null) {\n ctx.surfaceState.pruneTool(nameRef.current);\n ctx.paramRegistry.delete(nameRef.current);\n return;\n }\n if (typeof renameTo === \"string\" && renameTo !== nameRef.current) {\n ctx.surfaceState.renameTool(nameRef.current, renameTo);\n const dispositions = ctx.paramRegistry.get(nameRef.current);\n ctx.paramRegistry.delete(nameRef.current);\n if (dispositions) ctx.paramRegistry.set(renameTo, dispositions);\n nameRef.current = renameTo;\n }\n\n // Only re-capture+re-inject when THIS update actually replaced\n // inputSchema (mcp.js's own `typeof updates.paramsSchema !==\n // 'undefined'` gate) — otherwise inputSchema is still Baton's prior\n // injected version, not a fresh vendor-true one (see\n // captureAndInject's docstring for why re-running on that would\n // corrupt disposition tracking).\n if (u.paramsSchema !== undefined) {\n captureAndInject(nameRef.current, entry, ctx);\n }\n if (typeof u.enabled === \"boolean\") {\n ctx.surfaceState.setToolEnabled(nameRef.current, u.enabled);\n }\n\n // A callback swap always needs (re-)wrapping, independent of whether\n // the schema also changed — and on v2 a `paramsSchema` change needs it\n // too, because either one regenerates the executor over the vendor's\n // callback and discards our wrapper along with its tag.\n wrapIfNeeded(nameRef, entry, ctx);\n };\n }\n}\n\n/** The surface of a high-level MCP server `withBaton` actually uses. Written\n * structurally because the official SDK ships two nominally different\n * `McpServer` classes — 1.x's (`@modelcontextprotocol/sdk/server/mcp.js`)\n * and v2's (`@modelcontextprotocol/server`) — and both satisfy this. */\nexport interface SupportedMcpServer {\n readonly server: unknown;\n registerTool(name: string, ...rest: unknown[]): unknown;\n}\n\n/** Install Baton into an `McpServer`. See module docstring for usage. */\nexport function withBaton(server: SupportedMcpServer, config: BatonConfig): BatonHandle {\n validateBatonConfig(config);\n const sink = config.sink ?? new StdoutSink();\n const annotationToolName = config.annotationToolName || `${config.vendorId}_annotate`;\n const intentParamMode: IntentParamMode = config.intentParamMode ?? \"optional\";\n const counter = new SessionCounter();\n const fallbackSessionId = `sdk-${uuidv7()}`;\n // Default ON, mirroring Python's `install_baton` (`config.scrubber or\n // Scrubber()`). One instance per install, reused for every event, so its\n // `counts` accumulate across the session the way Python's does.\n const scrubber = config.scrubber ?? new Scrubber().scrub;\n\n // Vendor-true baseline, captured BEFORE any Baton mutation below —\n // MUST run before the instructions assignment, or the snapshot would\n // capture Baton's own text instead of the vendor's. See module docstring.\n const serverMeta = buildServerMeta(server.server);\n const surfaceState = new SurfaceState(serverMeta);\n\n const emitSurface = async (\n sessionId: string,\n digest: string,\n snapshot: Record<string, unknown>,\n ): Promise<void> => {\n // NOT `emit()`'s fail-open wrapper — this deliberately lets a write\n // failure propagate so maybeEmitSurfaceSnapshot can tell success from\n // failure and retry on the next call rather than silently treating the\n // surface as emitted. The caller still fails open overall (SPEC\n // §11.2): it catches this and never lets it reach the vendor's call.\n // Deliberately NOT scrubbed — this is the vendor's own static tool\n // surface, not caller-supplied data (mirrors Python's emit_surface).\n const event = SurfaceSnapshotEventSchema.parse({\n tenant_id: config.vendorId,\n vendor_id: config.vendorId,\n session_id: sessionId,\n consent_token: config.consentToken,\n sequence_number: counter.next(sessionId),\n captured_at: new Date().toISOString(),\n agent_runtime: config.defaultAgentRuntime ?? \"unknown\",\n payload: {\n surface_hash: digest,\n server_info: snapshot.server_info,\n capabilities: snapshot.capabilities,\n instructions: snapshot.instructions,\n tools: snapshot.tools,\n seam_augmentations: snapshot.seam_augmentations,\n },\n });\n await sink.write(event);\n };\n\n // v2 memoises each tool's converted JSON Schema at registration\n // (`_toolInputSchemaJson`). `tools/list` re-converts and so never reads it,\n // but the HTTP entry's SEP-2243 `Mcp-Param-*` PRE-DISPATCH validation does\n // (`createMcpHandler`) — so leaving it stale after we mutate `inputSchema`\n // would make injected params work over stdio and vanish over HTTP, per\n // transport, silently. `update({paramsSchema})` deletes the key itself;\n // a direct assignment is ours to clean up.\n // The internals both majors keep off their public `.d.ts` — one named\n // shape rather than an `any` per reach-in, so a future SDK rename is a\n // compile error here instead of a runtime surprise in five places.\n const internals = server as unknown as {\n server: { _instructions?: string };\n registerTool: (...args: AnyArgs) => unknown;\n _registeredTools?: Record<string, unknown>;\n _toolInputSchemaJson?: Record<string, unknown>;\n toolInputSchemaJson?: (name: string) => Record<string, unknown> | undefined;\n };\n const bustSchemaMemo = (name: string): void => {\n const memo = internals._toolInputSchemaJson;\n if (memo && typeof memo === \"object\") delete memo[name];\n };\n\n // Vendor-true JSON Schema for the surface snapshot. v2 renders `tools/list`\n // from its own converter (draft-2020-12, `$schema` included), so reading\n // its memo — which at call time still holds the pre-injection conversion —\n // keeps surface.ts's byte-for-byte promise true there. 1.x has no such\n // reader, and its own `toJsonSchemaCompat` is the matching conversion.\n const isV2Server = typeof internals.toolInputSchemaJson === \"function\";\n const vendorToolJsonSchema = (name: string, inputSchema: unknown): Record<string, unknown> => {\n if (isV2Server) {\n try {\n const json = internals.toolInputSchemaJson!(name);\n if (json) return json;\n } catch {\n // Fall through.\n }\n // The reader returns `undefined` for a tool that is currently DISABLED,\n // so a tool captured while disabled would otherwise land on the 1.x\n // converter and put a draft-07 `$schema` in a snapshot whose other\n // tools are draft-2020-12 — two spellings in one hash, from one server.\n // The schema's own Standard-Schema converter is the one v2 renders\n // with; verified canonically equal to the wire output.\n try {\n const standard = (inputSchema as { \"~standard\"?: { jsonSchema?: { input?: (o: unknown) => Record<string, unknown> } } })?.[\"~standard\"];\n const json = standard?.jsonSchema?.input?.({ target: \"draft-2020-12\" });\n if (json) return json;\n } catch {\n // Fall through.\n }\n }\n try {\n return toolInputJsonSchema(inputSchema);\n } catch {\n // noteTool sits outside captureAndInject's try, and it runs inside the\n // vendor's own registerTool call — a throw here would surface as their\n // registration failing. A schema we cannot convert costs the snapshot\n // one tool's schema, nothing else — spelled the way both majors spell\n // an empty one, not as a third `{}`.\n return { type: \"object\", properties: {} };\n }\n };\n\n const tracker = new ProactiveTracker();\n const ctx: WrapContext = {\n sink,\n counter,\n tenantId: config.vendorId,\n vendorId: config.vendorId,\n consentToken: config.consentToken,\n fallbackSessionId,\n defaultAgentRuntime: config.defaultAgentRuntime ?? \"unknown\",\n scrubber,\n resolveSessionId: config.resolveSessionId,\n annotationToolName,\n intentParamMode,\n paramRegistry: new Map(),\n vendorToolJsonSchema,\n bustSchemaMemo,\n tracker,\n surfaceState,\n emitSurface,\n };\n\n // Server instructions — load-bearing on instruction-aware runtimes (SPEC\n // §5.1.2). No public setter exists post-construction; see module\n // docstring for why this reach-in has no \"preferred path\" to fall back\n // from, unlike Python's adapter.\n const instructions = buildServerInstructions({\n vendorDisplayName: config.vendorDisplayName,\n annotationToolName,\n });\n internals.server._instructions = instructions;\n\n const resolvedAnnotationToolName = registerAnnotationTool(server, {\n sink,\n counter: ctx.counter,\n tenantId: ctx.tenantId,\n vendorId: ctx.vendorId,\n vendorDisplayName: config.vendorDisplayName,\n consentToken: ctx.consentToken,\n fallbackSessionId: ctx.fallbackSessionId,\n defaultAgentRuntime: ctx.defaultAgentRuntime,\n scrubber: ctx.scrubber,\n resolveSessionId: ctx.resolveSessionId,\n annotationToolName: config.annotationToolName,\n tracker,\n });\n\n // Retroactive: sweep whatever's already registered, regardless of call order.\n const existing = internals._registeredTools;\n if (existing) {\n for (const [name, entry] of Object.entries(existing)) {\n wireEntry(name, entry, ctx);\n }\n }\n\n // Prospective: every future registration goes through here too. Patched\n // AFTER registerAnnotationTool runs above (deliberately) — the annotate\n // tool registration hits the original, unpatched registerTool, lands in\n // _registeredTools, and gets excluded by name in the retroactive sweep\n // just above instead. Patching registerTool before registering the\n // annotate tool would work too (wireEntry's name check guards either\n // order), but this ordering means the annotate tool only ever needs to\n // be excluded in the one place, not reasoned about twice.\n const originalRegisterTool = internals.registerTool.bind(server);\n internals.registerTool = (...args: AnyArgs) => {\n const registered = originalRegisterTool(...args);\n wireEntry(String(args[0]), registered, ctx);\n return registered;\n };\n\n return new BatonHandle({\n sink,\n vendorId: config.vendorId,\n sessionId: fallbackSessionId,\n annotationToolName: resolvedAnnotationToolName,\n });\n}\n","/**\n * Annotation tool registration — SPEC §5.1.1. Registers a vendor-namespaced\n * tool (default `{vendorId}_annotate`) that accepts the annotation\n * signature (user_goal / expected_result / signal_type / overall_task /\n * suggested_improvement / context) and emits an `annotation` event.\n * Faithful port of `baton` (Python)'s `integrations/fastmcp/annotation.py`\n * (`user_goal` required, everything else optional — same as the Python tool's\n * signature, not a TS-specific choice).\n *\n * Tool-name pattern (`^[a-zA-Z0-9_-]{1,64}$`) is the strictest known client\n * pattern (Claude Desktop) — dots, slashes, and other separators rejected.\n */\n\nimport { z } from \"zod\";\nimport { AnnotationEventSchema } from \"../../events.js\";\nimport type { Sink } from \"../../sinks.js\";\nimport type { ResolveSessionIdHook } from \"./config.js\";\nimport { emit } from \"./emit.js\";\nimport { buildAnnotationToolDescription, SIGNAL_TYPES } from \"./llmText.js\";\nimport { extraMeta, type Extra } from \"./mcpTypes.js\";\nimport type { SupportedMcpServer } from \"./withBaton.js\";\nimport type { ProactiveTracker } from \"./proactiveTracker.js\";\nimport { detectAgentRuntime } from \"./runtimeAdapter.js\";\nimport { resolveSessionId } from \"./sessionResolution.js\";\nimport type { SessionCounter } from \"./sessionCounter.js\";\n\nconst TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;\n\n/** The annotate tool's arguments. Spelled out because `SupportedMcpServer`\n * types `registerTool`'s config as `unknown` — the price of accepting both\n * SDK majors' nominally distinct servers — so nothing infers this from the\n * Zod shape below. The two must be kept in step; the round-trip tests call\n * the tool through a real client, so a drift shows up as a runtime failure\n * rather than passing silently. */\ninterface AnnotationArgs extends Record<string, unknown> {\n user_goal: string;\n expected_result?: string | undefined;\n signal_type?: (typeof SIGNAL_TYPES)[number] | undefined;\n overall_task?: string | undefined;\n suggested_improvement?: string | undefined;\n context?: Record<string, unknown> | undefined;\n}\n\nexport function deriveAnnotationToolName(vendorId: string, override?: string): string {\n const name = override || `${vendorId}_annotate`;\n if (!TOOL_NAME_PATTERN.test(name)) {\n throw new Error(\n `Annotation tool name ${JSON.stringify(name)} violates the cross-runtime ` +\n `pattern ${TOOL_NAME_PATTERN.source} (Claude Desktop and others reject ` +\n \"names with dots or other separators).\",\n );\n }\n return name;\n}\n\nexport interface RegisterAnnotationToolOptions {\n sink: Sink;\n counter: SessionCounter;\n tenantId: string;\n vendorId: string;\n vendorDisplayName: string;\n consentToken: string;\n fallbackSessionId: string;\n defaultAgentRuntime: string;\n scrubber: (value: unknown) => unknown;\n resolveSessionId?: ResolveSessionIdHook | undefined;\n annotationToolName?: string | undefined;\n /** Shared with the tool-call wrapper so a session opens at most one\n * proactive annotation regardless of which path fires first. */\n tracker?: ProactiveTracker | undefined;\n}\n\n/** Register the annotation tool on `server`. Returns the resolved tool name. */\nexport function registerAnnotationTool(\n server: SupportedMcpServer,\n options: RegisterAnnotationToolOptions,\n): string {\n const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);\n const description = buildAnnotationToolDescription({\n vendorDisplayName: options.vendorDisplayName,\n });\n\n server.registerTool(\n name,\n {\n description,\n inputSchema: {\n user_goal: z.string(),\n expected_result: z.string().optional(),\n signal_type: z.enum(SIGNAL_TYPES).optional(),\n overall_task: z.string().optional(),\n suggested_improvement: z.string().optional(),\n context: z.record(z.string(), z.unknown()).optional(),\n },\n },\n async (args: AnnotationArgs, extra: Extra) => {\n const meta = extraMeta(extra);\n const runtime = detectAgentRuntime(meta) ?? options.defaultAgentRuntime;\n const scrubbedMeta = meta ? (options.scrubber(meta) as Record<string, unknown>) : null;\n const sessionId = await resolveSessionId(\n options.resolveSessionId,\n options.fallbackSessionId,\n extra,\n meta,\n name,\n args,\n );\n // A proactive annotation (no signal_type) claims the session's\n // proactive slot so the tool wrapper won't also synthesise one from\n // an injected `user_goal` param.\n if (args.signal_type === undefined) {\n options.tracker?.mark(sessionId);\n }\n\n await emit(options.sink, () =>\n AnnotationEventSchema.parse({\n tenant_id: options.tenantId,\n vendor_id: options.vendorId,\n session_id: sessionId,\n sequence_number: options.counter.next(sessionId),\n captured_at: new Date().toISOString(),\n consent_token: options.consentToken,\n agent_runtime: runtime,\n runtime_meta: scrubbedMeta,\n payload: {\n // Agent-facing names -> wire keys, as with `overall_task`\n // below: `user_goal` is stored as `intent`, `expected_result` as\n // `expected_outcome`.\n intent: options.scrubber(args.user_goal),\n expected_outcome: args.expected_result\n ? options.scrubber(args.expected_result)\n : null,\n // `signal_type` is a closed enum — nothing to scrub. The task label\n // is agent-authored free text (\"processing invoice for\n // bob@example.com\" is a realistic value), so it IS scrubbed.\n // Python's annotation.py does NOT scrub this field — a shared\n // gap found 2026-08-11, fixed here and flagged for the sibling\n // rather than mirrored. Not a wire divergence: scrubbing changes\n // content, not shape, and it's deterministic, so the\n // exact-string continuity rung 3b groups on survives.\n signal_type: args.signal_type ?? null,\n // Agent-facing param `overall_task` -> wire key `workflow`, the same\n // split the injected params use (`overall_task` -> `call_workflow`):\n // renaming the param must not move the key the console groups on.\n workflow: args.overall_task ? options.scrubber(args.overall_task) : null,\n suggested_improvement: args.suggested_improvement\n ? options.scrubber(args.suggested_improvement)\n : null,\n context: args.context ? options.scrubber(args.context) : null,\n },\n }),\n );\n\n return { content: [{ type: \"text\" as const, text: JSON.stringify({ ok: true }) }] };\n },\n );\n\n return name;\n}\n","import type { Event } from \"../../events.js\";\nimport { safeWrite, type Sink } from \"../../sinks.js\";\n\n/** Fail-open event construction + write. `build()` runs Zod validation —\n * a scrubber that breaks a payload's wire shape (e.g. replaces a record\n * wholesale) must not break the vendor's tool call any more than a sink\n * failure would; SPEC §11.2 fail-open applies to the whole capture step,\n * not just `sink.write`. */\nexport async function emit(sink: Sink, build: () => Event): Promise<void> {\n let event: Event;\n try {\n event = build();\n } catch (err) {\n process.stderr.write(`baton: event construction failed; event dropped: ${String(err)}\\n`);\n return;\n }\n await safeWrite(sink, event);\n}\n","/**\n * Shared LLM-facing text — server instructions + annotation tool\n * description. Byte-for-byte port of `baton` (Python)'s\n * `integrations/_llm_text.py` template strings; see that module's\n * docstring for the full rationale (split of responsibility under Claude\n * Code's instructions-truncation cap, the mechanical-trigger design). Kept\n * in sync by hand — there is no cross-language codegen for prose.\n */\n\nconst SERVER_INSTRUCTIONS_TEMPLATE = (\n vendorDisplayName: string,\n annotationToolName: string,\n) => `This server is wrapped in the ${vendorDisplayName} support-signal SDK. \\\nUse \\`${annotationToolName}\\` to record what the user is trying to do and \\\nhow each ${vendorDisplayName} tool call went. See that tool's \\\ndescription for field-level detail.\n\nBEFORE invoking any ${vendorDisplayName} tool, you MUST call \\\n\\`${annotationToolName}\\` with user_goal (REQUIRED), expected_result \\\n(REQUIRED), and overall_task (REQUIRED when the request fits a \\\nrecognizable \\\nbroader task, e.g., 'morning meeting prep', 'pre-outreach research').\n\nAFTER any ${vendorDisplayName} tool errors, times out, returns an \\\nunhelpful or contradictory result, or the user shows signs of giving \\\nup, you MUST call \\`${annotationToolName}\\` again with signal_type \\\n(REQUIRED) — one of failure, retry_loop, dead_end, parameter_confusion, \\\nslow_performance, abandonment, feature_gap, other — and \\\nsuggested_improvement (REQUIRED whenever you can articulate one).\n\nIF a ${vendorDisplayName} tool response lacks a structured field for \\\nwhat the user asked about, OR you satisfied the user's intent via a \\\nworkaround because no tool matched what they asked for, OR the user \\\nasked for something this server can't do — you MUST call \\\n\\`${annotationToolName}\\` with signal_type='feature_gap' AND still \\\nanswer the user with your best inference. Filing the annotation does \\\nNOT replace answering.`;\n\nconst ANNOTATION_TOOL_DESCRIPTION_TEMPLATE = (\n vendorDisplayName: string,\n) => `Record structured signal about a ${vendorDisplayName} tool call — \\\nwhat the user is trying to do, and how it went. Populate proactively \\\nbefore the call (user_goal + expected_result + overall_task) and reactively \\\nafter if the result was unhelpful (signal_type + suggested_improvement).\n\nFields:\n - user_goal: one sentence on what the user is trying to accomplish.\n - expected_result: what a successful result should look like, so a \\\nsilent/thin failure can be told apart from success.\n - overall_task: short stable label for the broader task this call \\\nserves, e.g., 'morning meeting prep', 'pre-outreach research', 'personal \\\nscheduling'. REPEAT the exact same string on every call serving the same \\\ntask; change it only when the user starts a different task. Skip when the \\\ncall doesn't fit a recognizable broader task.\n - signal_type: reactive-only — omit on a proactive annotation. \\\nSet only once a tool call has returned an unhelpful result. One of \\\nfailure, retry_loop, dead_end, parameter_confusion, \\\nslow_performance, abandonment, feature_gap, other.\n - suggested_improvement: reactive-only — omit on a proactive. \\\nA concrete sentence about what product change would have helped.\n - context: supplementary info not covered above. Common keys: plan, \\\nalternatives_considered, likely_cause, user_impact, error_class, \\\ndownstream_blocked, confidence_in_intent. For signal_type='feature_gap' \\\nalso missing_capability_field and requested_capability.`;\n\n// Empirically measured Claude Code truncation cap for\n// InitializeResult.instructions. Reserve headroom for vendor extensions\n// composed on top.\nconst CLAUDE_CODE_TRUNCATION_CAP = 2087;\nconst INSTRUCTIONS_LENGTH_CAP = 1500;\n\n// Canonical signal_type values per SPEC §3.1. Stable and additive-only\n// until v1.0 (SPEC §13). The annotation tool's inputSchema enum and the\n// instructions text reference the same eight values.\nexport const SIGNAL_TYPES = [\n \"failure\",\n \"retry_loop\",\n \"dead_end\",\n \"parameter_confusion\",\n \"slow_performance\",\n \"abandonment\",\n \"feature_gap\",\n \"other\",\n] as const;\n\nexport function buildServerInstructions(options: {\n vendorDisplayName: string;\n annotationToolName: string;\n}): string {\n const rendered = SERVER_INSTRUCTIONS_TEMPLATE(\n options.vendorDisplayName,\n options.annotationToolName,\n );\n if (rendered.length > INSTRUCTIONS_LENGTH_CAP) {\n throw new Error(\n `Rendered server instructions are ${rendered.length} chars, which exceeds ` +\n `the ${INSTRUCTIONS_LENGTH_CAP}-char safety cap (Claude Code truncates at ` +\n `~${CLAUDE_CODE_TRUNCATION_CAP}). Shorten vendorDisplayName or annotationToolName.`,\n );\n }\n return rendered;\n}\n\nexport function buildAnnotationToolDescription(options: { vendorDisplayName: string }): string {\n return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);\n}\n\n// =============================================================================\n// Intent-param injection text — mirrors `baton` (Python)'s\n// `integrations/_llm_text.py` USER_GOAL_PARAM_NAME/EXPECTED_RESULT_PARAM_NAME\n// section byte-for-byte (see that module's docstring for rationale: this is\n// the capture path that survives runtimes which drop `instructions`,\n// notably Claude Desktop).\n// =============================================================================\n\nexport const USER_GOAL_PARAM_NAME = \"user_goal\";\nexport const EXPECTED_RESULT_PARAM_NAME = \"expected_result\";\n/** The task-label grouping key (wire field `call_workflow`; console rung 3b).\n * Deliberately NOT named `workflow`: injected params live inside vendor tool\n * schemas, where `workflow` is a plausible real vendor param (Workfront\n * approvals, CI pipelines, Notion automations) — a collision would make the\n * strip swallow the vendor's own argument, and the name would invite the LLM\n * to fill in the vendor object it is touching instead of the meta task\n * label. */\nexport const OVERALL_TASK_PARAM_NAME = \"overall_task\";\n\n/** Provenance value stamped on `tool_call_start.payload.intent_source` and\n * on the synthesised proactive annotation when intent came from an injected\n * param (vs a real annotation-tool call). The Console reads this string. */\nexport const INTENT_SOURCE_PARAM = \"injected_param\";\n\nconst USER_GOAL_PARAM_DESCRIPTION =\n \"OPTIONAL. One sentence: what the user is actually trying to accomplish \" +\n \"with this call (their goal, not a restatement of the arguments).\";\n\nconst EXPECTED_RESULT_PARAM_DESCRIPTION =\n \"OPTIONAL. One sentence: what a successful result should look like, so a \" +\n \"silent/thin failure can be told apart from success.\";\n\n// The stability contract is the load-bearing design element: user_goal/\n// expected_result are call-scoped diagnostics that reword freely, so they\n// cannot key grouping; this param works ONLY if the model repeats the label\n// verbatim while the task is unchanged (measured 2026-08-10: without the\n// contract, 80% of adjacent same-task calls reword their goal text).\n//\n// Granularity is a KNOWN, MEASURED weakness of this text, kept anyway because\n// the obvious fix is worse. Do not reword without scoring against both corpora\n// in baton-internal `spikes/overall_task_a5/` (40 paired live-agent sessions,\n// 2026-08-11, one build per run).\n//\n// What this text gets wrong: when the user switches topic WITHOUT announcing\n// it, agents carry the first task's label onto everything after it — one\n// session labelled a rice lookup, a chickpea restock and a waste check all\n// \"cook dal tonight\". Boundary detection 0.700 on cue-free multi-task scripts\n// (1.000 when the user says \"Different thing:\", which is why an earlier run\n// missed this entirely).\n//\n// What it gets right, and why it stays: it never splits a task that should\n// stay whole — 20/20 same-task pairs held the label verbatim across both\n// corpora. The candidate rewording (\"the specific task the user is working on\n// right now — not the overall theme of the conversation\") fixes the boundary\n// problem completely (1.000) but relabels *within* a single task, describing\n// successive steps of one goal as different tasks; it scored 0.200 then 0.400\n// over-split on identical scripts, and produced an A → B → A label that a\n// merge-only, adjacency-based consumer resolves as three tasks instead of one.\n// The gain (+0.300 boundary) is smaller than the cost (0.400 over-split), and\n// shattering is the failure mode that destroys downstream trust, so the trade\n// goes this way.\n//\n// The open target for any v3 is therefore specific: the candidate's boundary\n// behaviour with this text's within-task stability. The two failure modes are\n// independent, so it is not a granularity dial to be tuned — it needs the\n// repeat-verbatim contract hardened against step-level rewording.\nconst OVERALL_TASK_PARAM_DESCRIPTION =\n \"OPTIONAL. Short stable label for the broader task this call serves \" +\n \"(e.g. 'prepare campaign approval'). REPEAT the exact same string on \" +\n \"every call serving the same task; change it only when the user starts \" +\n \"a different task.\";\n\nexport function buildUserGoalParamDescription(): string {\n return USER_GOAL_PARAM_DESCRIPTION;\n}\n\nexport function buildOverallTaskParamDescription(): string {\n return OVERALL_TASK_PARAM_DESCRIPTION;\n}\n\nexport function buildExpectedResultParamDescription(): string {\n return EXPECTED_RESULT_PARAM_DESCRIPTION;\n}\n","/**\n * The context object every `McpServer` tool callback receives, whether\n * registered via `registerTool` or the annotation tool.\n *\n * Declared structurally rather than imported, for two reasons. Two shapes\n * wear this name — the official SDK 1.x passes `RequestHandlerExtra`, the v2\n * packages pass their own `ServerContext` — and importing either one would\n * pin this package to that major even for a type, which `tsup`'s `.d.ts`\n * rollup then re-exports into `dist/index.d.ts` and a consumer without that\n * package fails to typecheck against. Only these three fields are ever read.\n *\n * The divergence that matters: v2's `ServerContext` is\n * `{ sessionId, mcpReq, http }` (measured 2026-08-28) — it keeps `sessionId`\n * but moves the request `_meta` down under `mcpReq`. Read only at the 1.x\n * location and every v2 session silently degrades to\n * `agent_runtime: \"unknown\"` with no `runtime_meta`: no error, just worse\n * data. Use {@link extraMeta}, never `extra._meta`.\n */\nexport interface Extra {\n /** Transport-supplied session id; present on both majors. */\n sessionId?: string | undefined;\n /** 1.x: the request's `_meta`, at the top level. */\n _meta?: unknown;\n /** v2's `ServerContext.mcpReq` — the in-flight JSON-RPC request. */\n mcpReq?: { _meta?: unknown } | undefined;\n}\n\n/** The call's `_meta`, from wherever this SDK major keeps it. */\nexport function extraMeta(extra: Extra): Record<string, unknown> | null {\n const direct = extra._meta as Record<string, unknown> | undefined;\n if (direct) return direct;\n const nested = extra.mcpReq?._meta as Record<string, unknown> | undefined;\n return nested ?? null;\n}\n","/**\n * Per-runtime `_meta` heuristics — detect which agent runtime is calling\n * the vendor's MCP server. Mirrors `baton` (Python)'s\n * `integrations/fastmcp/runtime_adapter.py::detect_agent_runtime`.\n *\n * Per SPEC §5.2: different runtimes populate MCP's `_meta` differently\n * (Claude Code adds `claudecode/toolUseId`; Cursor only sets\n * `progressToken`; Claude Desktop sets nothing). Vendors MAY override the\n * heuristic by setting `_meta.baton.agent_runtime` explicitly.\n */\n\nexport function detectAgentRuntime(meta: Record<string, unknown> | null): string | null {\n if (!meta) return null;\n\n const batonMeta = meta[\"baton\"];\n if (batonMeta && typeof batonMeta === \"object\") {\n const runtime = (batonMeta as Record<string, unknown>)[\"agent_runtime\"];\n if (typeof runtime === \"string\" && runtime) return runtime;\n }\n\n for (const key of Object.keys(meta)) {\n if (key.startsWith(\"claudecode/\")) return \"claude-code\";\n }\n\n return null;\n}\n","import type { ResolveSessionIdHook } from \"./config.js\";\nimport type { Extra } from \"./mcpTypes.js\";\n\n/** Real per-call session id, shared by the tool-call wrapper and the\n * annotation tool so both file events under the same id. A configured\n * `resolveSessionId` hook is checked first and, on a non-empty return,\n * wins outright — mirrors Python's rung-0 `resolve_session_id_hook`. Below\n * that, falls back to the transport-supplied `extra.sessionId`, then the\n * process-wide fallback. */\nexport async function resolveSessionId(\n hook: ResolveSessionIdHook | undefined,\n fallbackSessionId: string,\n extra: Extra,\n meta: Record<string, unknown> | null,\n toolName: string,\n args: Record<string, unknown>,\n): Promise<string> {\n if (hook) {\n try {\n const hookResult = await hook({ meta, toolName, arguments: args });\n if (typeof hookResult === \"string\" && hookResult) return hookResult;\n } catch {\n // Never propagate a hook failure — fall through to the ladder below,\n // mirroring Python's resolve_via_hook.\n }\n }\n if (typeof extra.sessionId === \"string\" && extra.sessionId) return extra.sessionId;\n return fallbackSessionId;\n}\n","/**\n * `BatonConfig` — vendor-side configuration for `withBaton`. A trimmed\n * mirror of `baton` (Python)'s `integrations/_config.py::VendorConfig`.\n */\n\nimport type { Sink } from \"../../sinks.js\";\n\n// Vendor IDs double as tenant_id in vendor-mode tenancy (mirrors Python's\n// `install_baton` setting `tenant_id=config.vendor_id`) and as the default\n// annotation-tool-name prefix — same pattern Python validates against.\nconst VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;\n\n// Per-tool intent-param injection modes (mirrors baton-proxy's\n// BATON_INTENT_PARAM and Python's VendorConfig.intent_param_mode).\nconst INTENT_PARAM_MODES = new Set([\"optional\", \"required\", \"off\"]);\n\n/** Normalized input to `BatonConfig.resolveSessionId`. Deliberately doesn't\n * carry the raw MCP SDK `extra` object — this shape is stable across\n * whatever the TS MCP ecosystem does with its request-handler signature. */\nexport interface SessionResolutionContext {\n meta: Record<string, unknown> | null;\n toolName: string;\n arguments: Record<string, unknown>;\n}\n\nexport type ResolveSessionIdHook = (\n context: SessionResolutionContext,\n) => string | null | undefined | Promise<string | null | undefined>;\n\nexport interface BatonConfig {\n /** Short stable identifier for the vendor (e.g. `\"acme\"`). Also used as\n * `tenant_id` on every emitted event (vendor-mode tenancy) and as the\n * default annotation tool name prefix (`{vendorId}_annotate`). */\n vendorId: string;\n /** Human-readable vendor name used in server instructions and the\n * annotation tool description — whitelabel obligation (SPEC §5.4): no\n * Baton-branded strings reach the calling agent. */\n vendorDisplayName: string;\n /** End-user consent token attached to every emitted event per SPEC §2.3 —\n * required, the Console MUST reject events missing it. */\n consentToken: string;\n /** Where events go. Defaults to `new StdoutSink()` — zero-config dev mode. */\n sink?: Sink;\n /** Default `agent_runtime` when `_meta` heuristics can't detect one. */\n defaultAgentRuntime?: string;\n /** PII scrubber per SPEC §7, applied to tool params/results, `_meta`,\n * intent strings and error bodies before they reach the sink. Defaults to\n * the shipped default ruleset (`new Scrubber().scrub` — email, bearer,\n * sk-keys, AWS keys, JWTs, phones, Luhn-checked cards, plus sensitive\n * field names), matching `baton` (Python) and baton-proxy: on by default\n * so untouched integrations get scrubbing without the operator opting in.\n * Pass `identityScrub` to explicitly opt out, or supply your own. */\n scrubber?: (value: unknown) => unknown;\n /** Optional vendor-supplied session-id resolver, checked BEFORE\n * `extra.sessionId` — mirrors Python's `resolve_session_id` rung 0. */\n resolveSessionId?: ResolveSessionIdHook;\n /** Optional override for the annotation tool name. Default is\n * `{vendorId}_annotate`. */\n annotationToolName?: string;\n /** Per-tool intent-param injection (mirrors baton-extmcp's vendor-neutral\n * naming). `\"optional\"` (default) injects `user_goal`/`expected_result`\n * string params on every wrapped tool's advertised schema; `\"required\"`\n * also adds `user_goal` to the schema's required fields (`expected_result`\n * stays optional regardless); `\"off\"` disables injection. Both params are\n * stripped before the vendor handler runs, so the tool never sees them.\n * This is what captures intent on runtimes that drop `instructions`\n * (notably Claude Desktop) — where the annotation tool alone yields\n * nothing. A tool registered with no `inputSchema` at all is left alone\n * regardless of this setting (see `schemaCompat.injectGoalParams`). */\n intentParamMode?: \"optional\" | \"required\" | \"off\";\n}\n\nexport function validateBatonConfig(config: BatonConfig): void {\n if (!VENDOR_ID_PATTERN.test(config.vendorId)) {\n throw new Error(\n `vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} ` +\n \"— used as the default annotation tool name prefix.\",\n );\n }\n if (!config.vendorDisplayName) {\n throw new Error(\n \"BatonConfig.vendorDisplayName is required — used in server instructions \" +\n \"and the annotation tool description (whitelabel obligation, SPEC §5.4).\",\n );\n }\n if (!config.consentToken) {\n throw new Error(\n \"BatonConfig.consentToken is required per SPEC §2.3 — events without a \" +\n \"valid consent_token MUST be rejected by the consumer.\",\n );\n }\n if (config.intentParamMode !== undefined && !INTENT_PARAM_MODES.has(config.intentParamMode)) {\n throw new Error(\n `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ` +\n `${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`,\n );\n }\n}\n","import type { Sink } from \"../../sinks.js\";\n\n/**\n * Handle returned from `withBaton` for graceful shutdown and session\n * correlation. Trimmed mirror of Python's `integrations/_handle.py::BatonHandle`\n * — `escalate()` is not here; it's a Console action-surface feature, out of\n * scope for this package.\n */\nexport class BatonHandle {\n readonly sink: Sink;\n readonly vendorId: string;\n /** Process-lifetime fallback session id — the value events fall back to\n * when no real per-call session id resolves. Not every event necessarily\n * carries this id; see `withBaton`'s session-resolution order. */\n readonly sessionId: string;\n /** The resolved annotation tool name (`{vendorId}_annotate` unless\n * overridden via `BatonConfig.annotationToolName`). */\n readonly annotationToolName: string;\n\n constructor(options: {\n sink: Sink;\n vendorId: string;\n sessionId: string;\n annotationToolName: string;\n }) {\n this.sink = options.sink;\n this.vendorId = options.vendorId;\n this.sessionId = options.sessionId;\n this.annotationToolName = options.annotationToolName;\n }\n\n /** Flush any pending events held by the sink. */\n async flush(): Promise<void> {\n await this.sink.flush();\n }\n\n /** Flush and release sink resources. Subsequent writes reject. */\n async aclose(): Promise<void> {\n await this.sink.aclose();\n }\n}\n","/**\n * Tracks which sessions have already emitted a proactive annotation —\n * mirrors `baton` (Python)'s `_state.py::ProactiveTracker`. Coordinates the\n * two proactive sources so a session opens at most one: `withBaton`'s tool\n * wrapper synthesises a proactive from the first injected `user_goal` it\n * sees, and the annotation tool marks the slot claimed when the agent calls\n * it proactively itself (`signal_type` omitted). On instruction-aware\n * runtimes both paths can fire; on Claude Desktop only the injected-param\n * path does.\n *\n * Synchronous, mutating a plain `Set` — safe with no lock because Node's\n * single-threaded event loop never interleaves two synchronous calls here.\n */\nexport class ProactiveTracker {\n private readonly emitted = new Set<string>();\n\n /** Claim the session's proactive slot. Returns true exactly once per\n * session (the caller should then emit); false if already claimed. */\n claim(sessionId: string): boolean {\n if (this.emitted.has(sessionId)) return false;\n this.emitted.add(sessionId);\n return true;\n }\n\n /** Mark the slot claimed without emitting here (the annotation tool's own\n * handler already emitted the annotation event itself). */\n mark(sessionId: string): void {\n this.emitted.add(sessionId);\n }\n}\n","/**\n * Per-session monotonic sequence-number counter — mirrors `baton` (Python)'s\n * `_state.py::SessionCounter`. First call for a session returns 1.\n *\n * Python guards this with an `asyncio.Lock` because a single event loop can\n * still interleave two `await counter.next(...)` callers between the read\n * and the write of `self._counters[session_id]`. Node's single-threaded\n * event loop has the same hazard in principle, but `next()` here contains\n * no `await` — the read-increment-write is one synchronous turn, so it's\n * already atomic with respect to other JS execution. No lock needed.\n */\nexport class SessionCounter {\n private readonly counters = new Map<string, number>();\n\n next(sessionId: string): number {\n const current = this.counters.get(sessionId) ?? 0;\n const next = current + 1;\n this.counters.set(sessionId, next);\n return next;\n }\n}\n","/**\n * A faithful vendored port of the four zod v3/v4 helpers and the JSON Schema\n * conversion that the official SDK **1.x** keeps in `server/zod-compat.js` +\n * `server/zod-json-schema-compat.js`.\n *\n * Why vendored rather than imported. Those are deep imports into\n * `@modelcontextprotocol/sdk`, and a *runtime* one — so any module graph that\n * reaches `schemaCompat.ts` cannot load at all unless 1.x is installed. That\n * makes the package uninstallable for a vendor on the v2 packages\n * (`@modelcontextprotocol/server`), who has no reason to have 1.x in their\n * tree, which is the whole point of supporting v2. Copying ~90 lines buys\n * both majors one entry point and deletes a documented reach-in; the\n * alternatives (async `import()` behind a synchronous `withBaton`, or a\n * `createRequire` shim that has to survive a dual ESM/CJS build) buy neither.\n *\n * Ported faithfully, warts included — this code exists to reproduce what 1.x\n * *does*, not what it should do. `objectFromShape` returns `zod/v4-mini`\n * objects, which carry no `~standard.jsonSchema`; that is 1.x's own behaviour\n * for the schemas it renders and validates, so \"improving\" it here would\n * change 1.x-path output rather than preserve it. (The v2 path deliberately\n * does NOT come through here — see `schemaCompat.injectGoalParamsV2`.)\n *\n * Held safe by `test/integrations/mcp/zodCompat.test.ts`, which diffs every\n * function in this file against 1.x's originals over a shared corpus. 1.x\n * stays a devDependency for exactly that reason.\n *\n * Known residual: this resolves `zod` from OUR dependency tree, while 1.x's\n * own `tools/list` resolves it from ITS tree. Deduped in any normal install\n * (one hoisted zod), divergent only where a vendor carries two zod v4 copies\n * — the same class of risk 1.x already runs internally.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment */\n\nimport * as z3rt from \"zod/v3\";\nimport * as z4mini from \"zod/v4-mini\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\n\n/** Present on zod 4 (Classic and Mini) schemas; absent on zod 3.\n *\n * One deliberate divergence from the original, pinned by test: 1.x reads\n * `s._zod` unguarded and therefore throws a `TypeError` on `null`/`undefined`.\n * That is unreachable through 1.x's own call sites and through ours — every\n * caller has already checked — so this keeps the optional chain rather than\n * copy a crash into a module whose callers would be the ones to hit it. */\nexport function isZ4Schema(s: unknown): boolean {\n const schema = s as { _zod?: unknown } | null | undefined;\n return !!schema?._zod;\n}\n\n/** Build an object schema from a shape, in the shape's own zod major. */\nexport function objectFromShape(shape: Record<string, unknown>): unknown {\n const values = Object.values(shape);\n if (values.length === 0) return z4mini.object({}); // default to v4 Mini\n const allV4 = values.every(isZ4Schema);\n const allV3 = values.every((s) => !isZ4Schema(s));\n if (allV4) return z4mini.object(shape as any);\n if (allV3) return z3rt.object(shape as any);\n throw new Error(\"Mixed Zod versions detected in object shape.\");\n}\n\n/** The field map of an object schema. v3 exposes `.shape`; v4 keeps it on\n * `_zod.def.shape`, and either may be a thunk. */\nexport function getObjectShape(schema: unknown): Record<string, unknown> | undefined {\n if (!schema) return undefined;\n let rawShape: unknown;\n if (isZ4Schema(schema)) {\n rawShape = (schema as any)._zod?.def?.shape;\n } else {\n rawShape = (schema as any).shape;\n }\n if (!rawShape) return undefined;\n if (typeof rawShape === \"function\") {\n try {\n return (rawShape as () => Record<string, unknown>)();\n } catch {\n return undefined;\n }\n }\n return rawShape as Record<string, unknown>;\n}\n\n/** Normalise to an object schema, accepting either an already-constructed\n * object schema (v3 or v4) or a raw shape that needs wrapping. Returns\n * `undefined` for anything else — including a non-object schema, which is\n * how a tool with no spliceable `inputSchema` is left alone. */\nexport function normalizeObjectSchema(schema: unknown): unknown {\n if (!schema) return undefined;\n\n if (typeof schema === \"object\") {\n const asAny = schema as any;\n // No `_def`/`_zod` means it is not a schema instance, so it may be a raw\n // shape — confirmed heuristically by every value being schema-like.\n if (!asAny._def && !asAny._zod) {\n const values = Object.values(schema as Record<string, unknown>);\n if (\n values.length > 0 &&\n values.every(\n (v: any) =>\n typeof v === \"object\" &&\n v !== null &&\n (v._def !== undefined || v._zod !== undefined || typeof v.parse === \"function\"),\n )\n ) {\n return objectFromShape(schema as Record<string, unknown>);\n }\n }\n }\n\n if (isZ4Schema(schema)) {\n const def = (schema as any)._zod?.def;\n if (def && (def.type === \"object\" || def.shape !== undefined)) return schema;\n } else {\n if ((schema as any).shape !== undefined) return schema;\n }\n return undefined;\n}\n\nexport interface ToJsonSchemaOptions {\n target?: string | undefined;\n strictUnions?: boolean | undefined;\n pipeStrategy?: \"input\" | \"output\" | undefined;\n}\n\nfunction mapMiniTarget(t: string | undefined): \"draft-7\" | \"draft-2020-12\" {\n if (!t) return \"draft-7\";\n if (t === \"jsonSchema7\" || t === \"draft-7\") return \"draft-7\";\n if (t === \"jsonSchema2019-09\" || t === \"draft-2020-12\") return \"draft-2020-12\";\n return \"draft-7\";\n}\n\n/** JSON Schema for a zod v3 or v4 schema, in the exact spelling 1.x's own\n * `tools/list` emits. */\nexport function toJsonSchemaCompat(\n schema: unknown,\n opts?: ToJsonSchemaOptions,\n): Record<string, unknown> {\n if (isZ4Schema(schema)) {\n return z4mini.toJSONSchema(schema as any, {\n target: mapMiniTarget(opts?.target),\n io: opts?.pipeStrategy ?? \"input\",\n });\n }\n return zodToJsonSchema(schema as any, {\n strictUnions: opts?.strictUnions ?? true,\n pipeStrategy: opts?.pipeStrategy ?? \"input\",\n });\n}\n","/**\n * Intent-param injection for the official SDK's **1.x** `McpServer`.\n *\n * Splicing `user_goal`/`expected_result`/`overall_task` into a vendor's\n * EXISTING Zod object schema has to build the injected fields with a schema\n * instance from the SAME zod major as the tool's other fields — a vendor on\n * 1.x may be on zod v3 or v4, and `objectFromShape` throws on a mixed-version\n * shape. The v3/v4 bridge that makes that work is `./zodCompat.js`, a\n * vendored port of the helpers 1.x uses internally; see that module for why\n * it is copied rather than imported (short version: the import is a runtime\n * one, and it would make this package uninstallable for a v2-only vendor).\n *\n * The v2 packages need none of this — `injectGoalParamsV2`, below.\n */\n\nimport {\n getObjectShape,\n isZ4Schema,\n normalizeObjectSchema,\n objectFromShape,\n toJsonSchemaCompat,\n} from \"./zodCompat.js\";\nimport { z as zV4 } from \"zod\";\nimport { z as zV3 } from \"zod/v3\";\nimport {\n EXPECTED_RESULT_PARAM_NAME,\n OVERALL_TASK_PARAM_NAME,\n USER_GOAL_PARAM_NAME,\n buildExpectedResultParamDescription,\n buildOverallTaskParamDescription,\n buildUserGoalParamDescription,\n} from \"./llmText.js\";\n\nexport type IntentParamMode = \"optional\" | \"required\" | \"off\";\n\n/** The sliver of a zod namespace the injected fields need — written\n * structurally so the same builder serves zod v3, zod v4, and whichever\n * instance the vendor's own schema was built with. */\ninterface DescribableField {\n describe(description: string): unknown;\n}\ninterface StringFieldFactory {\n string(): DescribableField & { optional(): DescribableField };\n}\nexport type IntentParamDispositions = Record<string, \"injected\" | \"native\">;\n\n// Mirrors mcp.js's private EMPTY_OBJECT_JSON_SCHEMA — used identically by\n// the SDK's own tools/list handler when a tool declares no inputSchema.\nconst EMPTY_OBJECT_JSON_SCHEMA = { type: \"object\", properties: {} };\n\n/**\n * Splice `user_goal`/`expected_result`/`overall_task` into `inputSchema`'s\n * object shape.\n * Returns the original schema unchanged (with empty dispositions) when\n * there's no object schema to extend into — a tool with no `inputSchema` at\n * all is left alone rather than given one, because adding a schema where\n * none existed would flip the SDK's handler-calling convention from\n * `(extra)` to `(args, extra)` and break the vendor's own zero-arg handler.\n *\n * Known fidelity gap: rebuilding via `objectFromShape` recovers only the\n * field map (`getObjectShape`), not object-level modifiers the vendor's\n * schema may have carried (`.strict()`/`.passthrough()`/`.refine()`).\n * Python's JSON-schema-dict injection has no equivalent loss (JSON Schema\n * has no refinement concept to lose); this is a TS-specific, accepted gap.\n *\n * NO `mode` PARAMETER since 2026-09-01 (D7). It used to select an enforcing\n * field for `required`; it cannot select an advertisement instead, because\n * this package has no `tools/list` hook — see `buildIntentFields` for the\n * measurement. A parameter that selects nothing is worse than no parameter:\n * it reads as a knob. The mode is still a real config value, still gates\n * `off` in `withBaton`, and is still reported in\n * `seam_augmentations.intent_param.mode`.\n */\nexport function injectGoalParams(inputSchema: unknown): {\n schema: unknown;\n dispositions: IntentParamDispositions;\n} {\n const objSchema = normalizeObjectSchema(inputSchema);\n if (!objSchema) return { schema: inputSchema, dispositions: {} };\n const existingShape = getObjectShape(objSchema) ?? {};\n const values = Object.values(existingShape);\n // Empty shape: default to v4, matching objectFromShape's own default.\n const useV4 = values.length === 0 || isZ4Schema(values[0]);\n const zodImpl = useV4 ? zV4 : zV3;\n\n const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl);\n\n if (Object.keys(toInject).length === 0)\n return { schema: inputSchema, dispositions };\n const mergedShape = { ...existingShape, ...toInject };\n const newSchema = objectFromShape(mergedShape);\n return { schema: newSchema, dispositions };\n}\n\n/** The intent fields to splice, and what each name's disposition is. Shared\n * by both SDK majors so the two injection paths cannot drift on which\n * params exist, which are promoted by `mode`, or when a vendor's own field\n * of the same name wins. */\nfunction buildIntentFields(\n existingShape: Record<string, unknown>,\n zodImpl: StringFieldFactory,\n): {\n dispositions: IntentParamDispositions;\n toInject: Record<string, unknown>;\n} {\n const dispositions: IntentParamDispositions = {};\n const toInject: Record<string, unknown> = {};\n\n // EVERY injected field is optional, in EVERY mode. `mode` no longer reaches\n // this builder, and that is the change of 2026-09-01 (D7 in baton-internal\n // `intent_param_injection.md`), not an oversight.\n //\n // `required` used to build a non-optional zod field here — on the VENDOR'S\n // OWN schema — so an agent that omitted `user_goal` had its call refused by\n // the vendor's server. Baton would have been breaking a customer's product\n // to collect a telemetry string. For a wrapper whose whole claim is that it\n // does not change how the wrapped server behaves, that is the wrong trade at\n // any capture rate, so `required` now means what it means in the proxy:\n // ADVERTISED as required, never enforced.\n //\n // ...except that the advertisement half is not reachable here, and the\n // reason is structural rather than a decision. Measured 2026-09-01 against\n // both zod majors this package supports:\n //\n // zod v4 .optional() -> required: [\"a\"] parses: true\n // zod v4 union([string,undef]) -> required: [\"a\",\"user_goal\"] parses: FALSE\n // zod v3 .optional() -> required: [\"a\"] parses: true\n // zod v3 union([string,undef]) -> required: [\"a\"] parses: true\n //\n // In v4 advertised-required and enforced are the same bit; in v3 the\n // advertisement is unreachable at all. Python can hold the two apart only\n // because it edits the rendered JSON Schema of a `tools/list` RESPONSE — and\n // this package has no `tools/list` hook (see withBaton.ts), so there is no\n // seam at which to advertise something the validator does not enforce.\n //\n // Consequence, recorded rather than hidden: in TypeScript `required` and\n // `optional` now produce identical behaviour AND identical advertisement.\n // The mode is kept on the config surface for parity with Python and because\n // `seam_augmentations.intent_param.mode` reports it, but it selects nothing\n // here. A future implementation that wants the advertisement needs a\n // response-rendering seam, not a different zod expression.\n if (USER_GOAL_PARAM_NAME in existingShape) {\n dispositions[USER_GOAL_PARAM_NAME] = \"native\";\n } else {\n dispositions[USER_GOAL_PARAM_NAME] = \"injected\";\n toInject[USER_GOAL_PARAM_NAME] = zodImpl\n .string()\n .optional()\n .describe(buildUserGoalParamDescription());\n }\n\n for (const [name, buildDescription] of [\n [EXPECTED_RESULT_PARAM_NAME, buildExpectedResultParamDescription],\n [OVERALL_TASK_PARAM_NAME, buildOverallTaskParamDescription],\n ] as const) {\n if (name in existingShape) {\n dispositions[name] = \"native\";\n } else {\n dispositions[name] = \"injected\";\n toInject[name] = zodImpl.string().optional().describe(buildDescription());\n }\n }\n\n return { dispositions, toInject };\n}\n\n/**\n * The same splice for the official SDK's **v2** packages, which need none of\n * this module's compat machinery: v2 refuses zod v3 outright (the schema\n * registers, then throws inside the `tools/list` handler and fails the whole\n * list), so there is no mixed-major case to bridge.\n *\n * Extends the vendor's own schema rather than rebuilding one from its field\n * map. `zV4.object({ ...schema.shape, ...injected })` recovers only the\n * fields and silently discards every object-level semantic the vendor\n * attached — measured: a tool declared `z.object({a,b}).refine(v => v.a !==\n * v.b)` then accepted `{a:\"x\", b:\"x\"}`, handing the vendor's handler\n * arguments its own schema rejects, and a `z.strictObject` quietly stripped\n * unknown keys instead of refusing them. Installing Baton must not weaken a\n * vendor's validation. `.extend()` keeps checks and `additionalProperties`\n * (measured: the violating call above is now rejected at the protocol layer,\n * exactly as it would be on the unwrapped tool) and still renders the\n * injected params on `tools/list`.\n *\n * One consequence worth knowing: the vendor's refinements now run over the\n * arguments *including* `user_goal`/`expected_result`/`overall_task`, since\n * v2 validates before dispatch and the strip happens in our wrapper after.\n * A refinement over key counts or unknown keys would therefore observe\n * Baton's params. Rare, and the alternative is dropping the refinement\n * entirely.\n *\n * Returns the schema unchanged when there is nothing safe to extend — a\n * non-zod `StandardSchemaWithJSON` (ArkType, Valibot, hand-rolled: v2's\n * primary `registerTool` overload takes any of them, and none has `.extend`).\n * Such a tool is still wrapped and still emits `tool_call_*`; it just carries\n * no injected intent params. Deliberately NOT falling back to a rebuild\n * there — a rebuild is the semantics loss this function exists to avoid.\n * Making injection work for those schemas means decorating\n * `~standard.jsonSchema.input()`, which advertises fine but leaves validation\n * with the vendor's own schema.\n *\n * The 1.x path above has the same rebuild-loses-modifiers gap, documented in\n * `injectGoalParams`; it is not changed here because it goes through\n * `objectFromShape` and the zod-mini objects 1.x itself renders.\n *\n * No `mode` parameter, for the same reason as in `injectGoalParams` above.\n */\nexport function injectGoalParamsV2(inputSchema: unknown): {\n schema: unknown;\n dispositions: IntentParamDispositions;\n} {\n const candidate = inputSchema as\n | {\n shape?: Record<string, unknown>;\n extend?: (fields: Record<string, unknown>) => unknown;\n }\n | undefined;\n const shape = candidate?.shape;\n if (\n !shape ||\n typeof shape !== \"object\" ||\n typeof candidate?.extend !== \"function\"\n ) {\n return { schema: inputSchema, dispositions: {} };\n }\n\n const { dispositions, toInject } = buildIntentFields(shape, zV4);\n if (Object.keys(toInject).length === 0)\n return { schema: inputSchema, dispositions };\n return { schema: candidate.extend(toInject), dispositions };\n}\n\n/** The vendor-true JSON Schema for a tool's `inputSchema` — same conversion\n * (`toJsonSchemaCompat`, matching options) the SDK 1.x itself uses to build\n * `tools/list`'s advertised `inputSchema`, so the surface snapshot matches\n * byte-for-byte what the client actually receives. Call BEFORE\n * `injectGoalParams` mutates the entry, so the snapshot reflects the\n * vendor's real schema, not Baton's addition.\n *\n * 1.x only: on v2, `withBaton` reads the server's own converted schema\n * instead, because v2 renders `tools/list` with a different one. */\nexport function toolInputJsonSchema(\n inputSchema: unknown,\n): Record<string, unknown> {\n const objSchema = normalizeObjectSchema(inputSchema);\n if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;\n return toJsonSchemaCompat(objSchema, {\n strictUnions: true,\n pipeStrategy: \"input\",\n });\n}\n","/**\n * Shared `surface_snapshot` helpers — mirrors `baton` (Python)'s\n * `integrations/_surface.py` (see that module's docstring for full\n * rationale). The vendor-true surface (`server_info`/`capabilities`/\n * `instructions` + the tool list) is hashed (canonical JSON, sorted keys)\n * and emitted once per observed hash.\n *\n * The hash MUST reflect only the vendor's real surface, never anything\n * Baton adds — `buildServerMeta` MUST run before `withBaton` mutates server\n * instructions, and callers must capture each tool's `inputSchema` (via\n * `schemaCompat.toolInputJsonSchema`) before `injectGoalParams` mutates it,\n * or toggling `intentParamMode` would invalidate every hash a recipe was\n * pinned against.\n *\n * NOT guaranteed to match a Python- or proxy-observed hash of the \"same\"\n * server: each producer serializes `tools` from a different shape.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport function surfaceHash(surface: unknown): string {\n const canonical = canonicalJson(surface);\n const digest = createHash(\"sha256\").update(canonical, \"utf-8\").digest(\"hex\");\n return `sha256:${digest}`;\n}\n\nfunction canonicalJson(value: unknown): string {\n if (value === null || typeof value !== \"object\") return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`;\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(record[k])}`).join(\",\")}}`;\n}\n\nexport interface ServerMeta {\n server_info: { name: string; version: string } | null;\n capabilities: Record<string, unknown> | null;\n instructions: string | null;\n}\n\n/** Vendor-true `server_info`/`capabilities`/`instructions`, read from the\n * low-level `Server` (`McpServer.server`) BEFORE `withBaton` sets its own\n * instructions suffix. `_serverInfo`/`_instructions` are private fields\n * with no public getter — same reach-in class as `withBaton.ts`'s\n * `_registeredTools`/`_instructions`; `getCapabilities()` is public. */\nexport function buildServerMeta(lowlevelServer: unknown): ServerMeta {\n /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call */\n const server = lowlevelServer as any;\n const info = server._serverInfo as { name?: string; version?: string } | undefined;\n const capabilities =\n typeof server.getCapabilities === \"function\"\n ? (server.getCapabilities() as Record<string, unknown>)\n : null;\n const instructions = (server._instructions as string | undefined) ?? null;\n /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call */\n return {\n server_info: info ? { name: info.name ?? \"\", version: info.version ?? \"\" } : null,\n capabilities: capabilities ?? null,\n instructions,\n };\n}\n\nexport function assembleSurface(\n serverMeta: ServerMeta,\n tools: Array<Record<string, unknown>>,\n): Record<string, unknown> {\n return {\n server_info: serverMeta.server_info,\n capabilities: serverMeta.capabilities,\n instructions: serverMeta.instructions,\n tools,\n };\n}\n\n/** The as-served delta Baton added on top of the vendor-true surface —\n * mirrors proxy's/Python's `seam_augmentations` so a consumer can render\n * both layers. Always records `instructions_suffix: true`: the SDK's\n * `buildServerInstructions` unconditionally documents the annotation tool\n * whenever `withBaton` runs. */\nexport function buildSeamAugmentations(options: {\n injectedToolNames: string[];\n intentParamNames: string[];\n intentParamMode: \"optional\" | \"required\" | \"off\";\n}): Record<string, unknown> {\n return {\n injected_tools: [...options.injectedToolNames].sort(),\n intent_param:\n options.intentParamMode !== \"off\"\n ? { names: [...options.intentParamNames].sort(), mode: options.intentParamMode }\n : null,\n instructions_suffix: true,\n };\n}\n"],"mappings":";AAEO,IAAM,cAAc;;;ACa3B,SAAS,SAAS;AAClB,SAAS,MAAM,cAAc;AAkBtB,IAAM,6BAA6B,EACvC,OAAO;AAAA,EACN,WAAW,EAAE,OAAO;AAAA,EACpB,QAAQ,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EACpD,aAAa,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EAC/C,eAAe,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EACjD,eAAe,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EACjD,eAAe,EAAE,OA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B;AAAA,EACtB,CAAC;AACH;","names":["uuidv7","z","z","durationMs","wrapper","uuidv7"]}
|
|
1
|
+
{"version":3,"sources":["../src/version.ts","../src/events.ts","../src/scrub.ts","../src/sinks.ts","../src/integrations/mcp/withBaton.ts","../src/integrations/mcp/annotation.ts","../src/integrations/mcp/emit.ts","../src/integrations/mcp/llmText.ts","../src/integrations/mcp/mcpTypes.ts","../src/integrations/mcp/runtimeAdapter.ts","../src/integrations/mcp/sessionResolution.ts","../src/integrations/mcp/config.ts","../src/integrations/mcp/handle.ts","../src/integrations/mcp/proactiveTracker.ts","../src/integrations/mcp/sessionCounter.ts","../src/integrations/mcp/zodCompat.ts","../src/integrations/mcp/schemaCompat.ts","../src/integrations/mcp/surface.ts"],"sourcesContent":["// TS-prefixed so `sdk_version` distinguishes TypeScript-sourced events from\n// Python (`baton-sdk`) ones in the Console — see design-notes/typescript_sdk.md.\nexport const SDK_VERSION = \"ts-0.3.0\";\n","/**\n * Zod schemas + TS types for the Baton event stream per SPEC §11.4.\n *\n * This is a hand-maintained mirror of `baton-spec/events.schema.json`, which\n * is itself exported from `baton-sdk` (Python)'s Pydantic models — that repo\n * is the schema of record. `test/conformance.test.ts` validates every\n * concrete type below against `baton-spec/events.schema.json` with ajv and\n * against `baton-spec/vectors/*.json`, so a drift here fails CI rather than\n * surfacing as a silent Console-side shape mismatch.\n *\n * All concrete event schemas share the same envelope fields and differ only\n * in `payload`. Fields match Python field-for-field (snake_case on the wire,\n * per CHARTER's wire-compatibility requirement — NOT camelCase).\n */\n\nimport { z } from \"zod\";\nimport { v7 as uuidv7 } from \"uuid\";\nimport { SDK_VERSION } from \"./version.js\";\n\n// =============================================================================\n// Per-event-type payloads\n// =============================================================================\n\n/** Emitted before the vendor handler runs. `params` is PII-scrubbed at\n * emit-time per SPEC §7.\n *\n * `call_intent` / `call_expected` / `call_workflow` are the values the SDK\n * stripped from the injected `user_goal` / `expected_result` /\n * `overall_task` params (see `llmText.ts`); they ride as SIBLINGS of\n * `params` — `params` stays exactly the vendor-visible arguments.\n * `call_intent`/`call_expected` are call-scoped diagnostics;\n * `call_workflow` is the task-label grouping key (console rung 3b, exact\n * string continuity). `intent_source` records provenance\n * (`\"injected_param\"`). All null when the params weren't used. */\nexport const ToolCallStartPayloadSchema = z\n .object({\n tool_name: z.string(),\n params: z.record(z.string(), z.unknown()).default({}),\n call_intent: z.string().nullable().default(null),\n call_expected: z.string().nullable().default(null),\n call_workflow: z.string().nullable().default(null),\n intent_source: z.string().nullable().default(null),\n })\n .strict();\nexport type ToolCallStartPayload = z.infer<typeof ToolCallStartPayloadSchema>;\n\n/** Emitted after the vendor handler returns. `result` is PII-scrubbed. */\nexport const ToolCallEndPayloadSchema = z\n .object({\n tool_name: z.string(),\n result: z.unknown().nullable().default(null),\n duration_ms: z.number().int().nullable().default(null),\n })\n .strict();\nexport type ToolCallEndPayload = z.infer<typeof ToolCallEndPayloadSchema>;\n\n/** Emitted when the vendor handler throws. `error_type` is the error's\n * constructor name; `error_body` is the message (PII-scrubbed, capped at\n * 2000 chars per the design note). */\nexport const ToolCallErrorPayloadSchema = z\n .object({\n tool_name: z.string(),\n error_type: z.string(),\n error_body: z.string(),\n duration_ms: z.number().int().nullable().default(null),\n })\n .strict();\nexport type ToolCallErrorPayload = z.infer<typeof ToolCallErrorPayloadSchema>;\n\n/** Agent-supplied context. All fields nullable per SPEC §5.1.1 — the agent\n * populates what it has. Proactive annotations typically populate\n * `intent`/`expected_outcome`/`workflow`; reactive annotations typically\n * populate `signal_type`/`suggested_improvement`. */\nexport const AnnotationPayloadSchema = z\n .object({\n intent: z.string().nullable().default(null),\n expected_outcome: z.string().nullable().default(null),\n signal_type: z.string().nullable().default(null),\n workflow: z.string().nullable().default(null),\n suggested_improvement: z.string().nullable().default(null),\n context: z.record(z.string(), z.unknown()).nullable().default(null),\n intent_source: z.string().nullable().default(null),\n tool_name: z.string().nullable().default(null),\n })\n .strict();\nexport type AnnotationPayload = z.infer<typeof AnnotationPayloadSchema>;\n\n/** The vendor-true upstream surface (pre-injection) — mirrors baton-proxy's\n * `enqueue_surface_snapshot` payload so the Console worker materializes both\n * into the same `vendor_surfaces` table. Emitted at most once per observed\n * `surface_hash` per process. `tools` excludes Baton's own injected tool(s);\n * those live in `seam_augmentations.injected_tools` instead. */\nexport const SurfaceSnapshotPayloadSchema = z\n .object({\n surface_hash: z.string(),\n server_info: z.record(z.string(), z.unknown()).nullable().default(null),\n capabilities: z.record(z.string(), z.unknown()).nullable().default(null),\n instructions: z.string().nullable().default(null),\n tools: z.array(z.record(z.string(), z.unknown())).default([]),\n seam_augmentations: z.record(z.string(), z.unknown()).default({}),\n })\n .strict();\nexport type SurfaceSnapshotPayload = z.infer<typeof SurfaceSnapshotPayloadSchema>;\n\n// =============================================================================\n// Envelope shared by all event types\n// =============================================================================\n\n/** Fields every Baton event carries, per SPEC §11.4.\n *\n * `consentToken` is REQUIRED — the Console rejects any event missing it.\n * `vendorId` is REQUIRED — the wrapped vendor identifier; the Console groups\n * friction by `(tenant_id, vendor_id)`.\n * `userId` is the hashed end-user actor (HMAC-SHA256, hashed at the capture\n * edge — the raw principal is never transmitted); null when unresolved.\n * `runtimeMeta` is the runtime-supplied MCP request `_meta` envelope, used\n * by the Console to derive turn/cycle boundaries more precise than\n * `session_id` alone. */\nconst envelopeShape = {\n event_id: z.uuid().default(() => uuidv7()),\n tenant_id: z.string(),\n vendor_id: z.string(),\n session_id: z.string(),\n sequence_number: z.number().int().nonnegative(),\n captured_at: z.string(),\n consent_token: z.string(),\n sdk_version: z.string().default(SDK_VERSION),\n agent_runtime: z.string().default(\"unknown\"),\n user_id: z.string().nullable().default(null),\n runtime_meta: z.record(z.string(), z.unknown()).nullable().default(null),\n};\n\nexport const EventTypeSchema = z.enum([\n \"tool_call_start\",\n \"tool_call_end\",\n \"tool_call_error\",\n \"annotation\",\n \"surface_snapshot\",\n]);\nexport type EventType = z.infer<typeof EventTypeSchema>;\n\n// =============================================================================\n// Concrete event schemas\n// =============================================================================\n\nexport const ToolCallStartEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"tool_call_start\").default(\"tool_call_start\"),\n payload: ToolCallStartPayloadSchema,\n })\n .strict();\nexport type ToolCallStartEvent = z.infer<typeof ToolCallStartEventSchema>;\n\nexport const ToolCallEndEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"tool_call_end\").default(\"tool_call_end\"),\n payload: ToolCallEndPayloadSchema,\n })\n .strict();\nexport type ToolCallEndEvent = z.infer<typeof ToolCallEndEventSchema>;\n\nexport const ToolCallErrorEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"tool_call_error\").default(\"tool_call_error\"),\n payload: ToolCallErrorPayloadSchema,\n })\n .strict();\nexport type ToolCallErrorEvent = z.infer<typeof ToolCallErrorEventSchema>;\n\nexport const AnnotationEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"annotation\").default(\"annotation\"),\n payload: AnnotationPayloadSchema,\n })\n .strict();\nexport type AnnotationEvent = z.infer<typeof AnnotationEventSchema>;\n\nexport const SurfaceSnapshotEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"surface_snapshot\").default(\"surface_snapshot\"),\n payload: SurfaceSnapshotPayloadSchema,\n })\n .strict();\nexport type SurfaceSnapshotEvent = z.infer<typeof SurfaceSnapshotEventSchema>;\n\n// =============================================================================\n// Discriminated union — mirrors Python's `Event` (discriminator: event_type)\n// =============================================================================\n\nexport const EventSchema = z.discriminatedUnion(\"event_type\", [\n ToolCallStartEventSchema,\n ToolCallEndEventSchema,\n ToolCallErrorEventSchema,\n AnnotationEventSchema,\n SurfaceSnapshotEventSchema,\n]);\nexport type Event =\n | ToolCallStartEvent\n | ToolCallEndEvent\n | ToolCallErrorEvent\n | AnnotationEvent\n | SurfaceSnapshotEvent;\n","/**\n * Source-side PII scrubbing for event payloads (SPEC §7).\n *\n * The SDK emits whatever the wrapped MCP server returns — including tool\n * params and results that may carry customer PII (emails in search results,\n * bearer tokens in error bodies, API keys pasted into chat tools). Persona\n * B's trust pitch is that nothing unscrubbed ever leaves the customer's\n * machine; this module is what makes that true. Every event payload runs\n * through `Scrubber` before it lands in the sink, so both local sinks AND\n * any HTTP sink see only scrubbed values.\n *\n * **Default ruleset** ships fixed for v1 (no public env-var configurability\n * — deferred until customer feedback justifies the surface area):\n *\n * - email — RFC-ish address regex\n * - bearer — `Bearer <opaque>` header values\n * - sk_key — OpenAI/Anthropic-style `sk-*` API keys\n * - aws_key — `AKIA*` access key IDs\n * - jwt — three-segment `eyJ*.*.*` tokens\n * - phone — North-American-leaning loose digit pattern\n * - cc — 13-19 digit candidates filtered by Luhn\n *\n * Plus field-name overrides: any object key matching\n * `{email, phone, ssn, api_key, token, secret, password, user_name}`\n * (case-insensitive) force-redacts its string value regardless of pattern.\n *\n * Differs from LangSmith's approach (off by default, bring-your-own regex)\n * by shipping rules on by default — the right tradeoff for Persona B's\n * consumer/SMB audience that won't write masking code.\n *\n * Ported from `baton` (Python)'s `src/baton/scrub.py` on 2026-08-11, which\n * is itself a parallel copy of baton-proxy's (the two are rule-identical —\n * verified by diff at port time; they differ only in docstrings). All three\n * ship parallel copies until the extracted shared package lands. Rule\n * parity here is verified by mirroring Python's `tests/test_scrub.py` test\n * matrix in `test/scrub.test.ts`; when a pattern lands or changes, port the\n * test every way.\n *\n * **Port notes** (where TypeScript forced a divergence from the Python):\n * - `counts` is a `Map<string, number>`, not a `collections.Counter`. Use\n * `count(category)` for Python's zero-default read.\n * - Python walks anything `isinstance(dict)`; this walks only *plain*\n * objects (`{}` / `Object.create(null)`). A `Date`, `Map`, or class\n * instance passes through untouched rather than being flattened to `{}`\n * — matching Python, where those aren't dicts either.\n */\n\n/** Cap on recursive walk depth. Matches LangSmith's default; protects\n * against pathological inputs without truncating realistic MCP payloads. */\nexport const DEPTH_LIMIT = 10;\n\n// Object keys whose string values are redacted regardless of value-pattern\n// match. Case-insensitive exact match (no plural / prefix matching to keep\n// false positives down). Kept narrow on purpose — too broad and we wreck\n// legitimate fields like `Slack:channel_token_string_id`.\n// `user_name` guards the PII half of a resolved end-user identity in the\n// event it ever lands in a payload — defence in depth for the console path\n// (residency contract). NOT `name`: that collides with legitimate payload\n// keys (prompt names, tool names in surface snapshots).\nconst REDACT_FIELD_NAMES: ReadonlySet<string> = new Set([\n \"email\",\n \"phone\",\n \"ssn\",\n \"api_key\",\n \"token\",\n \"secret\",\n \"password\",\n \"user_name\",\n]);\n\n// Ordered list of [category, pattern]. Order matters where patterns can\n// overlap: JWT must run before bearer because a bare JWT can look\n// bearer-shaped. sk_key / aws_key run before email because their token\n// bodies could otherwise match the email local-part regex.\n//\n// Every pattern carries `g`: Python's `re.sub` replaces ALL matches, while\n// a JS regex without `g` replaces only the first. Safe as module-level\n// constants because `String.prototype.replace` with a global regex resets\n// `lastIndex` itself — never call `.test()` on these.\nconst PATTERNS: ReadonlyArray<readonly [string, RegExp]> = [\n [\"jwt\", /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b/g],\n [\"bearer\", /\\bBearer\\s+[A-Za-z0-9_\\-.+/=]{16,}/gi],\n [\"sk_key\", /\\bsk-[A-Za-z0-9_-]{20,}\\b/g],\n [\"aws_key\", /\\bAKIA[0-9A-Z]{16}\\b/g],\n [\"email\", /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g],\n // Phone: optional `+1`, optional area-code parens, separators\n // `-` / `.` / space, 10 digits. Conservative — won't catch every\n // international format, but won't trip on every 10-digit identifier.\n [\"phone\", /\\b(?:\\+?1[\\s\\-.]?)?\\(?\\d{3}\\)?[\\s\\-.]?\\d{3}[\\s\\-.]?\\d{4}\\b/g],\n];\n\n// Credit-card candidates — Luhn-filtered before redacting to keep false\n// positives down on long numeric IDs (timestamps, order numbers).\nconst CC_CANDIDATE = /\\b\\d{13,19}\\b/g;\n\n/** Standard Luhn checksum. Caller passes a digits-only string of the right\n * length; we don't re-validate length here. */\nfunction luhnValid(digits: string): boolean {\n let total = 0;\n for (let i = 0; i < digits.length; i += 1) {\n let n = Number(digits[digits.length - 1 - i]);\n if (i % 2 === 1) {\n n *= 2;\n if (n > 9) n -= 9;\n }\n total += n;\n }\n return total % 10 === 0;\n}\n\n/** True only for `{...}` literals and `Object.create(null)` — the TS\n * analogue of Python's `isinstance(value, dict)`. Deliberately excludes\n * class instances, `Date`, `Map`, etc.: walking those would rebuild them as\n * bare objects and silently destroy the payload, whereas Python leaves them\n * alone because they aren't dicts. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const proto = Object.getPrototypeOf(value) as object | null;\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Stateful recursive scrubber with the default ruleset baked in.\n *\n * Construct one per `withBaton` call and reuse for every event. The\n * `counts` map accumulates per-category redaction counts across all calls\n * so a downstream report can surface \"N emails, M bearer tokens\" at render\n * time. Nothing on the wire carries these today — they exist for parity\n * with Python and for vendor-side introspection.\n *\n * Instances are callable-compatible via the bound `scrub` method, so a\n * `Scrubber` plugs into anywhere the `(value: unknown) => unknown` slot\n * that `BatonConfig.scrubber` accepts expects a plain function.\n */\nexport class Scrubber {\n readonly counts = new Map<string, number>();\n\n /** Bound so `new Scrubber().scrub` can be passed as a bare function\n * reference — the closest TS gets to Python's `__call__`. */\n readonly scrub = (value: unknown): unknown => this.walk(value, 0, null);\n\n /** Python's `Counter[category]` zero-default read. */\n count(category: string): number {\n return this.counts.get(category) ?? 0;\n }\n\n private bump(category: string): void {\n this.counts.set(category, this.count(category) + 1);\n }\n\n private walk(value: unknown, depth: number, forceField: string | null): unknown {\n if (depth >= DEPTH_LIMIT) return value;\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n // A sensitive key's force-redaction propagates DOWN into nested\n // containers, not just its immediate string value — `{\"password\":\n // [\"a\", \"b\"]}` redacts both items.\n const nextForce = REDACT_FIELD_NAMES.has(k.toLowerCase()) ? k.toLowerCase() : forceField;\n out[k] = this.walk(v, depth + 1, nextForce);\n }\n return out;\n }\n if (Array.isArray(value)) {\n return value.map((item) => this.walk(item, depth + 1, forceField));\n }\n if (typeof value === \"string\") {\n if (forceField !== null) {\n this.bump(`field:${forceField}`);\n return `[REDACTED:field-${forceField}]`;\n }\n return this.scrubString(value);\n }\n // number / boolean / null / undefined / Date / class instances — leave\n // alone. Sensitive data stored as a non-string at this leaf is rare in\n // MCP payloads and not worth the false-positive cost of stringifying\n // everything.\n return value;\n }\n\n private scrubString(s: string): string {\n let out = s;\n for (const [category, pattern] of PATTERNS) {\n out = out.replace(pattern, () => {\n this.bump(category);\n return `[REDACTED:${category}]`;\n });\n }\n // Credit card pass — separate because we Luhn-filter candidates before\n // counting / replacing. Skips non-CC long digit strings.\n return out.replace(CC_CANDIDATE, (match) => {\n if (!luhnValid(match)) return match;\n this.bump(\"cc\");\n return \"[REDACTED:cc]\";\n });\n }\n}\n\n/**\n * No-op scrubber. Exported for explicit opt-out — vendors / customers who\n * legitimately want raw payloads pass this where `new Scrubber().scrub`\n * would otherwise be the default. Not the default: the SDK ships the same\n * default ruleset as `baton` (Python) and baton-proxy so untouched\n * integrations get PII scrubbing without the operator having to opt in.\n */\nexport function identityScrub(value: unknown): unknown {\n return value;\n}\n","/**\n * Sinks — where Baton events go after the SDK captures them.\n *\n * A `Sink` is the egress side of the SDK; `withBaton` hands fully-formed\n * `Event` envelopes to a sink and the sink decides what to do with them.\n *\n * Two sinks ship, mirroring `sinks.py`'s core pair:\n *\n * - `StdoutSink` — JSONL to a writable stream (default `process.stderr`,\n * for the same reason as Python: MCP stdio transport reserves stdout for\n * JSON-RPC framing).\n * - `HttpSink` — POST to any HTTP endpoint with bearer auth; bounded\n * buffer, retry with backoff, circuit breaker. This is the contract a\n * Console or any compatible collector consumes.\n *\n * `FileSink` / `MultiSink` are deferred per design-notes/typescript_sdk.md\n * (\"HttpSink + StdoutSink covers all real use cases\") — add them if a real\n * need shows up rather than porting them speculatively.\n */\n\nimport type { Event } from \"./events.js\";\n\nexport interface Sink {\n /** Hand one event to the sink. Resolves once the sink has accepted it\n * (which may mean buffered, not yet shipped). MUST NOT block the\n * producer on slow downstream destinations. */\n write(event: Event): Promise<void>;\n /** Wait for any buffered events to reach their destination (or be\n * dropped per the sink's policy). No-op for synchronous sinks. */\n flush(): Promise<void>;\n /** Flush + release resources. After `aclose`, `write` rejects. */\n aclose(): Promise<void>;\n}\n\n/** Fail-open wrapper around `sink.write`.\n *\n * The MCP tool wrapper sits BEFORE the vendor's tool handler runs. A reject\n * from `sink.write` (closed sink, transport error, etc.) would otherwise\n * propagate up and break the vendor's tool call — making Baton\n * instrumentation look like a vendor bug. SPEC §11.2 mandates fail-open at\n * the capture boundary; this wrapper enforces it. */\nexport async function safeWrite(sink: Sink, event: Event): Promise<void> {\n try {\n await sink.write(event);\n } catch (err) {\n process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${String(err)}\\n`);\n }\n}\n\n// =============================================================================\n// StdoutSink — JSONL to a writable stream (default: stderr)\n// =============================================================================\n\nexport interface StdoutSinkOptions {\n /** Defaults to `process.stderr` — stdio MCP transport reserves stdout for\n * JSON-RPC framing. Pass `process.stdout` explicitly for non-MCP (library\n * API) use if preferred. */\n stream?: NodeJS.WritableStream;\n}\n\nexport class StdoutSink implements Sink {\n private readonly stream: NodeJS.WritableStream;\n private closed = false;\n\n constructor(options: StdoutSinkOptions = {}) {\n this.stream = options.stream ?? process.stderr;\n }\n\n async write(event: Event): Promise<void> {\n if (this.closed) throw new Error(\"StdoutSink is closed\");\n this.stream.write(JSON.stringify(event) + \"\\n\");\n }\n\n async flush(): Promise<void> {\n // Node writable streams don't expose a synchronous flush; write() above\n // already pushes each line through immediately.\n }\n\n async aclose(): Promise<void> {\n this.closed = true;\n // Don't end the stream — we don't own stderr/stdout.\n }\n}\n\n// =============================================================================\n// HttpSink — POST + bearer + bounded buffer + retry + circuit breaker\n// =============================================================================\n\ntype SendOutcome = \"success\" | \"permanent_failure\" | \"transient_failure\";\n\nclass CircuitBreaker {\n private failures = 0;\n private openedAt: number | null = null;\n\n constructor(\n private readonly threshold: number,\n private readonly resetMs: number,\n ) {}\n\n canRequest(): boolean {\n if (this.openedAt === null) return true;\n return Date.now() - this.openedAt >= this.resetMs;\n }\n\n recordSuccess(): void {\n this.failures = 0;\n this.openedAt = null;\n }\n\n recordFailure(): void {\n this.failures += 1;\n if (this.failures >= this.threshold) {\n this.openedAt = Date.now();\n }\n }\n}\n\nexport interface HttpSinkOptions {\n apiKey: string;\n bufferSize?: number;\n requestTimeoutMs?: number;\n maxRetries?: number;\n backoffBaseMs?: number;\n backoffMaxMs?: number;\n circuitBreakerThreshold?: number;\n circuitBreakerResetMs?: number;\n /** Injectable for tests; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n}\n\n/** POST events to an HTTP endpoint. Bounded buffer + retry + circuit breaker.\n *\n * This is the contract a Console or any compatible collector consumes:\n * `POST {url}/v0/events` with `Authorization: Bearer {apiKey}` and a JSON\n * body matching the SPEC §11.4 envelope.\n *\n * Failures are bounded — buffer overflow drops the oldest event; network\n * failures retry with backoff; the circuit breaker opens after consecutive\n * failures so the SDK doesn't pile retries on a known-bad endpoint. */\nexport class HttpSink implements Sink {\n private readonly url: string;\n private readonly apiKey: string;\n private readonly buffer: Event[] = [];\n private readonly bufferSize: number;\n private readonly maxRetries: number;\n private readonly backoffBaseMs: number;\n private readonly backoffMaxMs: number;\n private readonly circuit: CircuitBreaker;\n private readonly fetchImpl: typeof fetch;\n private overflowWarned = false;\n private closed = false;\n private drainChain: Promise<void> = Promise.resolve();\n private beforeExitHandler: (() => void) | null = null;\n\n constructor(url: string, options: HttpSinkOptions) {\n this.url = url.replace(/\\/+$/, \"\");\n this.apiKey = options.apiKey;\n this.bufferSize = options.bufferSize ?? 1000;\n this.maxRetries = options.maxRetries ?? 3;\n this.backoffBaseMs = options.backoffBaseMs ?? 100;\n this.backoffMaxMs = options.backoffMaxMs ?? 5000;\n this.circuit = new CircuitBreaker(\n options.circuitBreakerThreshold ?? 5,\n options.circuitBreakerResetMs ?? 30_000,\n );\n this.fetchImpl = options.fetchImpl ?? fetch;\n }\n\n async write(event: Event): Promise<void> {\n if (this.closed) throw new Error(\"HttpSink is closed\");\n this.enqueue(event);\n void this.scheduleDrain();\n this.ensureBeforeExitRegistered();\n }\n\n async flush(): Promise<void> {\n if (this.closed) return;\n await this.scheduleDrain();\n }\n\n async aclose(): Promise<void> {\n if (this.closed) return;\n await this.flush();\n this.closed = true;\n if (this.beforeExitHandler) {\n process.off(\"beforeExit\", this.beforeExitHandler);\n this.beforeExitHandler = null;\n }\n }\n\n private enqueue(event: Event): void {\n if (this.buffer.length >= this.bufferSize) {\n if (!this.overflowWarned) {\n process.emitWarning(\n `Baton HTTP sink buffer full (${this.bufferSize}); oldest events dropped. Further overflows will be silent.`,\n );\n this.overflowWarned = true;\n }\n this.buffer.shift();\n }\n this.buffer.push(event);\n }\n\n /** Serializes every call to `drainLocked` — from `write()`'s background\n * drain and from explicit `flush()` alike — onto one promise chain, so\n * concurrent tool calls (the normal case once the MCP interceptor is\n * wired up) can never run two drains at once racing on `buffer[0]`/\n * `shift()`. Mirrors Python's `asyncio.Lock` around `_drain_locked`. */\n private scheduleDrain(): Promise<void> {\n this.drainChain = this.drainChain.then(\n () => this.drainLocked(),\n () => this.drainLocked(),\n );\n return this.drainChain;\n }\n\n /** Best-effort flush when the process is about to exit without an\n * explicit `aclose()`. Node re-runs `beforeExit` if new async work is\n * scheduled during it, so an in-flight flush here can complete normally —\n * unlike Python's synchronous `atexit`, no separate sync-client fallback\n * is needed. Real residual gap, not fixable in-process: SIGKILL, or\n * SIGTERM with no installed handler, skip `beforeExit` entirely. A vendor\n * needing that guarantee must call `aclose()` from their own handler. */\n private ensureBeforeExitRegistered(): void {\n if (this.beforeExitHandler) return;\n this.beforeExitHandler = () => {\n void this.flush();\n };\n process.on(\"beforeExit\", this.beforeExitHandler);\n }\n\n private events_url(): string {\n return `${this.url}/v0/events`;\n }\n\n private authHeaders(): Record<string, string> {\n return { Authorization: `Bearer ${this.apiKey}`, \"Content-Type\": \"application/json\" };\n }\n\n private static classifyStatus(status: number): SendOutcome {\n if (status >= 200 && status < 300) return \"success\";\n if (status >= 400 && status < 500 && status !== 429) return \"permanent_failure\";\n return \"transient_failure\";\n }\n\n private async drainLocked(): Promise<void> {\n while (this.buffer.length > 0) {\n if (!this.circuit.canRequest()) return;\n const event = this.buffer[0]!;\n const outcome = await this.sendWithRetry(event);\n if (outcome === \"success\" || outcome === \"permanent_failure\") {\n this.buffer.shift();\n this.circuit.recordSuccess();\n } else {\n this.circuit.recordFailure();\n return;\n }\n }\n }\n\n private async sendWithRetry(event: Event): Promise<SendOutcome> {\n const url = this.events_url();\n const headers = this.authHeaders();\n const body = JSON.stringify(event);\n\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n try {\n const response = await this.fetchImpl(url, { method: \"POST\", headers, body });\n const outcome = HttpSink.classifyStatus(response.status);\n if (outcome !== \"transient_failure\") return outcome;\n } catch {\n // network error — fall through to retry/backoff below\n }\n if (attempt < this.maxRetries) {\n const backoff = Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs);\n await new Promise((resolve) => setTimeout(resolve, backoff));\n }\n }\n return \"transient_failure\";\n }\n}\n","/**\n * `withBaton` — the vendor's MCP integration entry point for the official\n * `@modelcontextprotocol/sdk`'s high-level `McpServer` — and the v2\n * packages' (`@modelcontextprotocol/server`), which are a different class of\n * the same name. `withBaton` takes the structural {@link SupportedMcpServer}\n * both satisfy and branches on the internals where the two majors differ:\n * where dispatch is intercepted (see {@link wrapIfNeeded}), how the intent\n * params are built (`schemaCompat.injectGoalParamsV2`), and where the call's\n * `_meta` lives (`mcpTypes.extraMeta`). Both are declared as OPTIONAL\n * peerDependencies and neither is imported — at runtime or as a type — so a\n * vendor installs whichever one they build on and nothing else.\n *\n * ```typescript\n * import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"; // or \"@modelcontextprotocol/server\"\n * import { withBaton } from \"@goodtiming/baton-sdk\";\n *\n * const server = new McpServer({ name: \"your-vendor-mcp\", version: \"1.0.0\" });\n * const handle = withBaton(server, {\n * vendorId: \"your-vendor\",\n * vendorDisplayName: \"Your Vendor\",\n * consentToken: \"...\",\n * });\n * ```\n *\n * Wraps every tool call to emit `tool_call_start` → call → `tool_call_end` /\n * `tool_call_error`, injects server `instructions` (SPEC §5.1.2), registers\n * the `<vendor>_annotate` tool (SPEC §5.1.1), injects `user_goal`/\n * `expected_result`/`overall_task` intent params on every wrapped tool's\n * schema (SPEC §11.4.1 `call_intent`/`call_expected`/`call_workflow`/\n * `intent_source`), and captures a `surface_snapshot`\n * of the vendor-true surface. Every payload leaving here runs through the\n * configured scrubber, which defaults to the shipped ruleset (`src/scrub.ts`)\n * — see README \"What's deferred\" for what's still not here (the low-level\n * `Server` adapter).\n *\n * Interception mechanism: `McpServer` has no middleware API (unlike the\n * standalone `fastmcp` library's `Middleware`/`CallNext`), so this patches\n * tool registration directly — the same shape Python's\n * `baton.integrations.mcp` adapter uses against the official `mcp` SDK, for\n * the same reason. Two passes, both required:\n *\n * 1. **Retroactive** — sweeps `server`'s already-registered tools (reaching\n * into the private `_registeredTools` map, mirroring Python's\n * `_registry.py` reaching into `_tool_manager._tools` — a documented,\n * single swap point for an upstream rename PR, not an accident).\n * 2. **Prospective** — patches `registerTool` so every tool registered\n * *after* `withBaton(server, ...)` runs is wrapped too.\n *\n * Together these make call ordering irrelevant — `withBaton` can run before\n * or after the vendor's own `registerTool` calls. Relying on only one pass\n * (as a naive `registerTool`-only patch would) silently drops capture for\n * tools registered on the other side of the ordering. The annotation tool\n * itself is excluded from this wrapping — it emits its own `annotation`\n * event instead of `tool_call_*`, same as the Python middleware's skip.\n *\n * Each wired entry's `.update()`/`.remove()` (mcp.js mutates the SAME\n * `RegisteredTool` object in place for both) are also patched: an\n * unpatched `.update()` replacing `paramsSchema`/`callback` would silently\n * wipe injected params and swap back to the vendor's raw, unwrapped\n * handler with no re-sweep able to detect it (the entry object identity\n * never changes); an unpatched `.remove()` would leave a phantom tool in\n * the surface snapshot forever.\n *\n * v2 makes the `.update()` patch carry more: there `remove()` IS\n * `update({name: null})` and `disable()`/`enable()` are `update({enabled})`,\n * all three routed through the entry's `update` *property* — so the patch\n * has to branch on which update it received rather than look only for\n * `paramsSchema`. It also supports renaming via `update({name})`, which 1.x\n * technically allowed and this module used to document as an unreconciled\n * gap; the surface snapshot, the param registry and the wrapper's own\n * `tool_name` now all follow a rename.\n *\n * Instructions injection reaches into `server.server`'s private\n * `_instructions` field — unlike Python's FastMCP (a read-only property\n * with a private-attribute fallback), the official TS SDK's `Server` has no\n * settable `instructions` at all post-construction, so there's no\n * \"preferred\" public path to fall back from here. `buildServerMeta` (the\n * `surface_snapshot` vendor-true baseline) MUST run before this assignment\n * — otherwise the snapshot would capture Baton's own instructions text\n * instead of the vendor's.\n */\n\nimport { v7 as uuidv7 } from \"uuid\";\nimport {\n AnnotationEventSchema,\n SurfaceSnapshotEventSchema,\n ToolCallEndEventSchema,\n ToolCallErrorEventSchema,\n ToolCallStartEventSchema,\n} from \"../../events.js\";\nimport { StdoutSink, type Sink } from \"../../sinks.js\";\nimport { registerAnnotationTool } from \"./annotation.js\";\nimport { Scrubber } from \"../../scrub.js\";\nimport { resolveTenantId, validateBatonConfig, type BatonConfig } from \"./config.js\";\nimport { emit } from \"./emit.js\";\nimport { BatonHandle } from \"./handle.js\";\nimport { buildServerInstructions } from \"./llmText.js\";\nimport {\n EXPECTED_RESULT_PARAM_NAME,\n INTENT_SOURCE_PARAM,\n OVERALL_TASK_PARAM_NAME,\n USER_GOAL_PARAM_NAME,\n} from \"./llmText.js\";\nimport { extraMeta, type Extra } from \"./mcpTypes.js\";\nimport { ProactiveTracker } from \"./proactiveTracker.js\";\nimport { detectAgentRuntime } from \"./runtimeAdapter.js\";\nimport { resolveSessionId } from \"./sessionResolution.js\";\nimport { SessionCounter } from \"./sessionCounter.js\";\nimport {\n injectGoalParams,\n injectGoalParamsV2,\n toolInputJsonSchema,\n type IntentParamDispositions,\n type IntentParamMode,\n} from \"./schemaCompat.js\";\nimport { assembleSurface, buildServerMeta, buildSeamAugmentations, surfaceHash } from \"./surface.js\";\n\ntype AnyArgs = unknown[];\ntype AnyHandler = (...args: AnyArgs) => unknown;\ntype TaggedHandler = AnyHandler & { [BATON_WRAPPED]?: boolean };\n\ninterface WrapContext {\n sink: Sink;\n counter: SessionCounter;\n tenantId: string;\n vendorId: string;\n consentToken: string;\n fallbackSessionId: string;\n defaultAgentRuntime: string;\n scrubber: (value: unknown) => unknown;\n resolveSessionId: BatonConfig[\"resolveSessionId\"];\n annotationToolName: string;\n intentParamMode: IntentParamMode;\n paramRegistry: Map<string, IntentParamDispositions>;\n /** Vendor-true JSON Schema for the surface snapshot, in whatever spelling\n * THIS server actually puts on the wire. */\n vendorToolJsonSchema: (name: string, inputSchema: unknown) => Record<string, unknown>;\n /** Drop v2's per-tool JSON-Schema memo after we mutate `inputSchema`. */\n bustSchemaMemo: (name: string) => void;\n tracker: ProactiveTracker;\n surfaceState: SurfaceState;\n emitSurface: (\n sessionId: string,\n digest: string,\n snapshot: Record<string, unknown>,\n ) => Promise<void>;\n}\n\n// `_registeredTools`, `RegisteredTool.handler`/`.executor`,\n// `server.server._instructions` and `server.server._serverInfo` are internal\n// to the official SDK — 1.x and v2 alike — and not part of either public\n// `.d.ts` surface. Reaching into them is deliberate (see module docstring),\n// the same way Python's `_registry.py` does, and isolated to this one module\n// so a future SDK internals change has exactly one place to update. Each\n// reach-in is declared on a named local shape (`internals` in `withBaton`,\n// the small casts in `wrapIfNeeded`/`captureAndInject`) rather than an\n// `any`, so a rename upstream lands as a compile error here.\n\nconst BATON_WRAPPED = Symbol(\"batonWrapped\");\nconst wired = new WeakSet<object>();\n\n/** Tracks the vendor-true (pre-injection) tool surface for this install, for\n * `surface_snapshot` capture. Built from data already in hand at wrap time\n * and lazily hashed+emitted on the next tool call — mirrors the official\n * mcp SDK's Python adapter, which has the same \"no tools/list hook\"\n * constraint and makes the same lazy-on-first-call choice for the same\n * reason (see `project_sdk_sensor_parity_gap` memory). */\nclass SurfaceState {\n /** Every tool this install has seen, keyed by its CURRENT name. `disabled`\n * is tracked alongside rather than pruned, so re-enabling costs nothing and\n * — crucially — never needs a re-capture, which would re-read Baton's own\n * injected schema as if it were vendor-true. */\n private readonly rawTools = new Map<\n string,\n { disabled: boolean; tool: Record<string, unknown> }\n >();\n readonly emittedHashes = new Set<string>();\n dirty = false;\n\n constructor(private readonly serverMeta: ReturnType<typeof buildServerMeta>) {}\n\n /** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,\n * which picks the spelling THIS SDK major puts on the wire. */\n noteTool(\n name: string,\n inputSchemaJson: Record<string, unknown>,\n description: string | undefined,\n ): void {\n this.rawTools.set(name, {\n disabled: this.rawTools.get(name)?.disabled ?? false,\n tool: { name, description: description ?? null, inputSchema: inputSchemaJson },\n });\n this.dirty = true;\n }\n\n pruneTool(name: string): void {\n if (this.rawTools.delete(name)) this.dirty = true;\n }\n\n /** Follow a `update({name})` rename, keeping the snapshot keyed the way\n * `tools/list` now renders it. */\n renameTool(from: string, to: string): void {\n const entry = this.rawTools.get(from);\n if (!entry) return;\n this.rawTools.delete(from);\n this.rawTools.set(to, { ...entry, tool: { ...entry.tool, name: to } });\n this.dirty = true;\n }\n\n /** Both majors filter `tools/list` on `tool.enabled`, so a disabled tool is\n * not part of the surface a client sees and must not be part of the one we\n * hash. Leaving it in is the same phantom-tool defect the `.remove()` patch\n * exists to prevent, reached through `disable()` instead. */\n setToolEnabled(name: string, enabled: boolean): void {\n const entry = this.rawTools.get(name);\n if (!entry || entry.disabled === !enabled) return;\n entry.disabled = !enabled;\n this.dirty = true;\n }\n\n buildSnapshot(): Record<string, unknown> {\n const names = [...this.rawTools.keys()].sort().filter((n) => !this.rawTools.get(n)!.disabled);\n return assembleSurface(\n this.serverMeta,\n names.map((n) => this.rawTools.get(n)!.tool),\n );\n }\n}\n\n/** `nameRef` is read on every call, not captured: v2's `update({name})`\n * renames a tool in place, keeping the same entry object AND the same\n * executor, so a wrapper that closed over the registration-time string would\n * keep emitting events under the old `tool_name` and keep missing its own\n * param-registry entry — which downgrades the strip to the cold-registry\n * path and puts a warning on the vendor's stderr for every call. */\nfunction batonWrap(nameRef: { current: string }, original: AnyHandler, ctx: WrapContext): AnyHandler {\n return async (...callArgs: AnyArgs): Promise<unknown> => {\n const toolName = nameRef.current;\n await maybeEmitSurfaceSnapshot(ctx);\n\n const extra = callArgs[callArgs.length - 1] as Extra;\n // 1.x calls a schema-less tool as `(extra)`; v2 always calls its\n // executor `(args, ctx)` and passes `args === undefined` for one. Both\n // land on `{}` here — and the ORIGINAL `callArgs` is what gets\n // delegated, so the arity fork stays inside the callee either way.\n const params = ((callArgs.length > 1 ? callArgs[0] : undefined) ?? {}) as Record<\n string,\n unknown\n >;\n const meta = extraMeta(extra);\n const runtime = detectAgentRuntime(meta) ?? ctx.defaultAgentRuntime;\n const scrubbedMeta = meta ? (ctx.scrubber(meta) as Record<string, unknown>) : null;\n const sessionId = await resolveSessionId(\n ctx.resolveSessionId,\n ctx.fallbackSessionId,\n extra,\n meta,\n toolName,\n params,\n );\n\n // Strip the injected goal params IN PLACE, before snapshotting params —\n // `params` is the SAME object forwarded to the vendor handler, so the\n // strip keeps user_goal/expected_result off the tool AND out of the\n // captured `params` (which must equal the vendor-visible arguments).\n const dispositions = ctx.paramRegistry.get(toolName);\n const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions);\n const rawExpected = extractGoalParam(\n params,\n EXPECTED_RESULT_PARAM_NAME,\n toolName,\n dispositions,\n );\n const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions);\n const scrubbedIntent = rawIntent !== null ? (ctx.scrubber(rawIntent) as string) : null;\n const scrubbedExpected = rawExpected !== null ? (ctx.scrubber(rawExpected) as string) : null;\n // Scrubbed like the other two. Deterministic redaction preserves the\n // exact-string continuity rung 3b groups on: the same label scrubs to\n // the same output on every call.\n const scrubbedWorkflow = rawWorkflow !== null ? (ctx.scrubber(rawWorkflow) as string) : null;\n\n const common = {\n tenant_id: ctx.tenantId,\n vendor_id: ctx.vendorId,\n session_id: sessionId,\n consent_token: ctx.consentToken,\n agent_runtime: runtime,\n runtime_meta: scrubbedMeta,\n };\n\n // The session's FIRST injected intent also becomes a proactive\n // annotation (carrying expected_result too, if present), sequenced\n // BEFORE the tool_call_start it explains. `claim` dedups per session\n // and is suppressed when a real annotation-tool proactive already\n // fired. Later param intents ride only the start event.\n if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {\n await emit(ctx.sink, () =>\n AnnotationEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.next(sessionId),\n captured_at: new Date().toISOString(),\n payload: {\n intent: scrubbedIntent,\n expected_outcome: scrubbedExpected,\n intent_source: INTENT_SOURCE_PARAM,\n tool_name: toolName,\n },\n }),\n );\n }\n\n await emit(ctx.sink, () =>\n ToolCallStartEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.next(sessionId),\n captured_at: new Date().toISOString(),\n payload: {\n tool_name: toolName,\n params: ctx.scrubber(params),\n call_intent: scrubbedIntent,\n call_expected: scrubbedExpected,\n call_workflow: scrubbedWorkflow,\n intent_source: scrubbedIntent !== null ? INTENT_SOURCE_PARAM : null,\n },\n }),\n );\n\n const startedAt = performance.now();\n let result: unknown;\n try {\n result = await original(...callArgs);\n } catch (err) {\n const durationMs = Math.round(performance.now() - startedAt);\n const message = err instanceof Error ? err.message : String(err);\n await emit(ctx.sink, () =>\n ToolCallErrorEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.next(sessionId),\n captured_at: new Date().toISOString(),\n payload: {\n tool_name: toolName,\n error_type: err instanceof Error ? err.constructor.name : \"Error\",\n error_body: String(ctx.scrubber(message)).slice(0, 2000),\n duration_ms: durationMs,\n },\n }),\n );\n throw err;\n }\n\n const durationMs = Math.round(performance.now() - startedAt);\n await emit(ctx.sink, () =>\n ToolCallEndEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.next(sessionId),\n captured_at: new Date().toISOString(),\n payload: { tool_name: toolName, result: ctx.scrubber(result), duration_ms: durationMs },\n }),\n );\n\n return result;\n };\n}\n\n/** Pop an injected goal param from `args` in place; return its value.\n * `\"native\"` (the tool already declares this name itself) forwards the\n * caller's own value untouched — never stripped, never reported as intent.\n * Unlisted (a call arrived before this tool was ever wired, or\n * `intentParamMode` was \"off\" when it was) strips defensively with a\n * warning: safe only because these two names are reserved. */\nfunction extractGoalParam(\n args: Record<string, unknown>,\n paramName: string,\n toolName: string,\n dispositions: IntentParamDispositions | undefined,\n): string | null {\n if (!(paramName in args)) return null;\n const disposition = dispositions ? dispositions[paramName] : undefined;\n if (disposition === \"native\") return null;\n if (disposition === undefined) {\n process.stderr.write(\n `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)\\n`,\n );\n }\n const raw = args[paramName];\n delete args[paramName];\n return typeof raw === \"string\" && raw.trim() ? raw : null;\n}\n\n/** Lazy, fail-open surface_snapshot capture — the first tool call after any\n * registration change re-hashes the surface and emits iff the hash hasn't\n * been seen before. `dirty` is cleared FIRST so a hashing/serialization\n * error (deterministic — would just re-throw identically every call) costs\n * one attempt per surface change, not a retry storm. A WRITE failure is\n * different (sink health can recover), so that path re-sets `dirty = true`\n * to retry on the next call; `emittedHashes` only gains an entry AFTER a\n * successful write, so a transient failure can't permanently drop a\n * surface the way a genuine dedup skip would. */\nasync function maybeEmitSurfaceSnapshot(ctx: WrapContext): Promise<void> {\n if (!ctx.surfaceState.dirty) return;\n ctx.surfaceState.dirty = false;\n let snapshot: Record<string, unknown>;\n let digest: string;\n try {\n snapshot = ctx.surfaceState.buildSnapshot();\n digest = surfaceHash(snapshot);\n } catch (err) {\n process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}\\n`);\n return;\n }\n if (ctx.surfaceState.emittedHashes.has(digest)) return;\n const seam = buildSeamAugmentations({\n injectedToolNames: [ctx.annotationToolName],\n intentParamNames: [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME],\n intentParamMode: ctx.intentParamMode,\n });\n try {\n await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });\n } catch (err) {\n process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}\\n`);\n ctx.surfaceState.dirty = true;\n return;\n }\n ctx.surfaceState.emittedHashes.add(digest);\n}\n\n/** Capture the entry's CURRENT `inputSchema` as vendor-true and splice in\n * the goal params. Only safe to call when `inputSchema` is known-fresh\n * (vendor-true, not already carrying a prior injection) — i.e. at first\n * processing, or right after a `.update()` call that itself supplied a new\n * `paramsSchema` (mcp.js replaces `inputSchema` wholesale in that case, so\n * whatever was captured/injected before is gone regardless of what this\n * function does). Calling it on an entry whose schema is STILL Baton's own\n * previously-injected version would misread `user_goal`/`expected_result`\n * as the vendor's own fields (`\"native\"` disposition) and silently stop\n * stripping/capturing them — callers must gate on that, not call this\n * unconditionally on every `.update()`. */\nfunction captureAndInject(name: string, entry: unknown, ctx: WrapContext): void {\n if (!entry || typeof entry !== \"object\") return;\n const mutable = entry as { inputSchema?: unknown; description?: string; executor?: unknown };\n ctx.surfaceState.noteTool(name, ctx.vendorToolJsonSchema(name, mutable.inputSchema), mutable.description);\n if (ctx.intentParamMode === \"off\") return;\n const isV2 = typeof mutable.executor === \"function\";\n try {\n const { schema, dispositions } = isV2\n ? injectGoalParamsV2(mutable.inputSchema)\n : injectGoalParams(mutable.inputSchema);\n if (Object.keys(dispositions).length > 0) {\n // Assigned directly rather than via `entry.update({paramsSchema})`,\n // which would route back through our OWN patched update and re-read\n // Baton's just-injected schema as if it were vendor-true — flipping\n // every injected param's disposition to \"native\" and silently\n // stopping the strip. The memo bust below is what `update` would have\n // done for us.\n mutable.inputSchema = schema;\n ctx.bustSchemaMemo(name);\n ctx.paramRegistry.set(name, dispositions);\n } else {\n ctx.paramRegistry.delete(name);\n }\n } catch {\n // Fail open — a schema this module can't handle just skips injection\n // for this tool; capture/wrap of the tool itself is unaffected.\n }\n}\n\n/** Wrap the entry's CURRENT dispatch target iff it isn't already Baton's\n * wrapper. The `BATON_WRAPPED` tag lives on the wrapped FUNCTION, not the\n * entry object, so a `.update()` that swaps in a fresh vendor callback\n * (untagged) is correctly reprocessed, while one that leaves it alone is a\n * cheap no-op.\n *\n * WHICH function that is differs by SDK major, and getting it wrong fails\n * silently. 1.x's `tools/call` handler invokes `entry.handler`, so patching\n * that field intercepts the call. **v2 dispatches through `entry.executor`**\n * — a closure built at registration over the handler\n * (`createToolExecutor(inputSchema, handler)`; `executeToolHandler` is\n * literally `return tool.executor(args, ctx)`). Patching `entry.handler` on\n * v2 therefore does nothing at all: the vendor handler still runs, the\n * wrapper never fires, and the server emits zero events while looking\n * perfectly healthy — measured against `@modelcontextprotocol/server@2.0.0`\n * and pinned by `test/integrations/mcp/withBatonV2.test.ts`, whose RED\n * signature against a handler-only patch is an empty event list and no\n * error at all. Worse, the schema half\n * of `withBaton` keeps working, so a half-ported install would advertise\n * intent params, collect a goal from the agent, and capture none of it.\n *\n * On v2 we wrap the executor by capture-and-delegate, and deliberately do\n * NOT also wrap `entry.handler`: nothing dispatches through it there, and\n * tagging both would double-wrap once `update({callback})` regenerates the\n * executor over the untouched handler. */\nfunction wrapIfNeeded(nameRef: { current: string }, entry: unknown, ctx: WrapContext): void {\n if (!entry || typeof entry !== \"object\") return;\n const mutable = entry as { handler: unknown; executor?: unknown };\n\n if (typeof mutable.executor === \"function\") {\n if ((mutable.executor as TaggedHandler)[BATON_WRAPPED]) return;\n const originalExecutor = mutable.executor as AnyHandler;\n const wrapper = batonWrap(nameRef, originalExecutor, ctx) as TaggedHandler;\n wrapper[BATON_WRAPPED] = true;\n mutable.executor = wrapper;\n return;\n }\n\n // Task-based tools (experimental) carry an object, not a function, at\n // .handler — leave them untouched rather than guess at wrapping a shape\n // we don't capture events for yet.\n if (typeof mutable.handler !== \"function\") return;\n if ((mutable.handler as TaggedHandler)[BATON_WRAPPED]) return;\n const original = mutable.handler as AnyHandler;\n const wrapper = batonWrap(nameRef, original, ctx) as TaggedHandler;\n wrapper[BATON_WRAPPED] = true;\n mutable.handler = wrapper;\n}\n\nfunction wireEntry(name: string, entry: unknown, ctx: WrapContext): void {\n if (name === ctx.annotationToolName) return;\n if (!entry || typeof entry !== \"object\") return;\n\n // First-time processing: inputSchema is guaranteed vendor-true (nothing\n // has injected into it yet) and the dispatch target is guaranteed\n // untagged, so both steps always apply together here — unlike the\n // .update() path below, which must reason about which one, if either,\n // actually needs to re-run.\n // The tool's CURRENT name. v2's `update({name})` re-keys `_registeredTools`\n // in place, keeping the same entry object AND its wrapper, so everything\n // below reads through this box rather than capturing the string.\n const nameRef = { current: name };\n\n captureAndInject(name, entry, ctx);\n wrapIfNeeded(nameRef, entry, ctx);\n\n if (wired.has(entry)) return;\n wired.add(entry);\n\n const removable = entry as { remove?: unknown };\n if (typeof removable.remove === \"function\") {\n const originalRemove = (removable.remove as () => void).bind(entry);\n (removable as { remove: () => void }).remove = () => {\n originalRemove();\n ctx.surfaceState.pruneTool(nameRef.current);\n ctx.paramRegistry.delete(nameRef.current);\n };\n }\n\n const updatable = entry as { update?: unknown };\n if (typeof updatable.update === \"function\") {\n const originalUpdate = (updatable.update as (updates: unknown) => void).bind(entry);\n (updatable as { update: (updates: unknown) => void }).update = (updates: unknown) => {\n const u = (updates ?? {}) as {\n paramsSchema?: unknown;\n name?: string | null;\n enabled?: boolean;\n };\n const renameTo = u.name;\n originalUpdate(updates);\n\n // v2 routes BOTH removal and rename through `update({name})` —\n // `remove()` is `update({name: null})`, and `disable()`/`enable()` are\n // `update({enabled})`. Handling only `paramsSchema` here would let a\n // v2 removal leave a phantom tool in the surface snapshot forever,\n // which is the exact defect the `.remove()` patch above exists to\n // prevent; a rename would strand the surface entry and the param\n // registry under the old key, and a stranded registry stops the strip\n // so Baton's own params would start reaching the vendor's handler.\n if (renameTo === null) {\n ctx.surfaceState.pruneTool(nameRef.current);\n ctx.paramRegistry.delete(nameRef.current);\n return;\n }\n if (typeof renameTo === \"string\" && renameTo !== nameRef.current) {\n ctx.surfaceState.renameTool(nameRef.current, renameTo);\n const dispositions = ctx.paramRegistry.get(nameRef.current);\n ctx.paramRegistry.delete(nameRef.current);\n if (dispositions) ctx.paramRegistry.set(renameTo, dispositions);\n nameRef.current = renameTo;\n }\n\n // Only re-capture+re-inject when THIS update actually replaced\n // inputSchema (mcp.js's own `typeof updates.paramsSchema !==\n // 'undefined'` gate) — otherwise inputSchema is still Baton's prior\n // injected version, not a fresh vendor-true one (see\n // captureAndInject's docstring for why re-running on that would\n // corrupt disposition tracking).\n if (u.paramsSchema !== undefined) {\n captureAndInject(nameRef.current, entry, ctx);\n }\n if (typeof u.enabled === \"boolean\") {\n ctx.surfaceState.setToolEnabled(nameRef.current, u.enabled);\n }\n\n // A callback swap always needs (re-)wrapping, independent of whether\n // the schema also changed — and on v2 a `paramsSchema` change needs it\n // too, because either one regenerates the executor over the vendor's\n // callback and discards our wrapper along with its tag.\n wrapIfNeeded(nameRef, entry, ctx);\n };\n }\n}\n\n/** The surface of a high-level MCP server `withBaton` actually uses. Written\n * structurally because the official SDK ships two nominally different\n * `McpServer` classes — 1.x's (`@modelcontextprotocol/sdk/server/mcp.js`)\n * and v2's (`@modelcontextprotocol/server`) — and both satisfy this. */\nexport interface SupportedMcpServer {\n readonly server: unknown;\n registerTool(name: string, ...rest: unknown[]): unknown;\n}\n\n/** Install Baton into an `McpServer`. See module docstring for usage. */\nexport function withBaton(server: SupportedMcpServer, config: BatonConfig): BatonHandle {\n validateBatonConfig(config);\n const sink = config.sink ?? new StdoutSink();\n const annotationToolName = config.annotationToolName || `${config.vendorId}_annotate`;\n const intentParamMode: IntentParamMode = config.intentParamMode ?? \"optional\";\n const counter = new SessionCounter();\n const fallbackSessionId = `sdk-${uuidv7()}`;\n // Resolved ONCE, here, and read by every emit path below — the tool-call\n // wrapper (via `ctx`), the annotation tool (via `registerAnnotationTool`)\n // and `emitSurface`, which builds its envelope from `config` directly.\n // Two resolutions could disagree, and an annotation landing under a\n // different tenant than the call it annotates is unjoinable.\n const tenantId = resolveTenantId(config.tenantId, config.vendorId);\n // Default ON, mirroring Python's `install_baton` (`config.scrubber or\n // Scrubber()`). One instance per install, reused for every event, so its\n // `counts` accumulate across the session the way Python's does.\n const scrubber = config.scrubber ?? new Scrubber().scrub;\n\n // Vendor-true baseline, captured BEFORE any Baton mutation below —\n // MUST run before the instructions assignment, or the snapshot would\n // capture Baton's own text instead of the vendor's. See module docstring.\n const serverMeta = buildServerMeta(server.server);\n const surfaceState = new SurfaceState(serverMeta);\n\n const emitSurface = async (\n sessionId: string,\n digest: string,\n snapshot: Record<string, unknown>,\n ): Promise<void> => {\n // NOT `emit()`'s fail-open wrapper — this deliberately lets a write\n // failure propagate so maybeEmitSurfaceSnapshot can tell success from\n // failure and retry on the next call rather than silently treating the\n // surface as emitted. The caller still fails open overall (SPEC\n // §11.2): it catches this and never lets it reach the vendor's call.\n // Deliberately NOT scrubbed — this is the vendor's own static tool\n // surface, not caller-supplied data (mirrors Python's emit_surface).\n const event = SurfaceSnapshotEventSchema.parse({\n tenant_id: tenantId,\n vendor_id: config.vendorId,\n session_id: sessionId,\n consent_token: config.consentToken,\n sequence_number: counter.next(sessionId),\n captured_at: new Date().toISOString(),\n agent_runtime: config.defaultAgentRuntime ?? \"unknown\",\n payload: {\n surface_hash: digest,\n server_info: snapshot.server_info,\n capabilities: snapshot.capabilities,\n instructions: snapshot.instructions,\n tools: snapshot.tools,\n seam_augmentations: snapshot.seam_augmentations,\n },\n });\n await sink.write(event);\n };\n\n // v2 memoises each tool's converted JSON Schema at registration\n // (`_toolInputSchemaJson`). `tools/list` re-converts and so never reads it,\n // but the HTTP entry's SEP-2243 `Mcp-Param-*` PRE-DISPATCH validation does\n // (`createMcpHandler`) — so leaving it stale after we mutate `inputSchema`\n // would make injected params work over stdio and vanish over HTTP, per\n // transport, silently. `update({paramsSchema})` deletes the key itself;\n // a direct assignment is ours to clean up.\n // The internals both majors keep off their public `.d.ts` — one named\n // shape rather than an `any` per reach-in, so a future SDK rename is a\n // compile error here instead of a runtime surprise in five places.\n const internals = server as unknown as {\n server: { _instructions?: string };\n registerTool: (...args: AnyArgs) => unknown;\n _registeredTools?: Record<string, unknown>;\n _toolInputSchemaJson?: Record<string, unknown>;\n toolInputSchemaJson?: (name: string) => Record<string, unknown> | undefined;\n };\n const bustSchemaMemo = (name: string): void => {\n const memo = internals._toolInputSchemaJson;\n if (memo && typeof memo === \"object\") delete memo[name];\n };\n\n // Vendor-true JSON Schema for the surface snapshot. v2 renders `tools/list`\n // from its own converter (draft-2020-12, `$schema` included), so reading\n // its memo — which at call time still holds the pre-injection conversion —\n // keeps surface.ts's byte-for-byte promise true there. 1.x has no such\n // reader, and its own `toJsonSchemaCompat` is the matching conversion.\n const isV2Server = typeof internals.toolInputSchemaJson === \"function\";\n const vendorToolJsonSchema = (name: string, inputSchema: unknown): Record<string, unknown> => {\n if (isV2Server) {\n try {\n const json = internals.toolInputSchemaJson!(name);\n if (json) return json;\n } catch {\n // Fall through.\n }\n // The reader returns `undefined` for a tool that is currently DISABLED,\n // so a tool captured while disabled would otherwise land on the 1.x\n // converter and put a draft-07 `$schema` in a snapshot whose other\n // tools are draft-2020-12 — two spellings in one hash, from one server.\n // The schema's own Standard-Schema converter is the one v2 renders\n // with; verified canonically equal to the wire output.\n try {\n const standard = (inputSchema as { \"~standard\"?: { jsonSchema?: { input?: (o: unknown) => Record<string, unknown> } } })?.[\"~standard\"];\n const json = standard?.jsonSchema?.input?.({ target: \"draft-2020-12\" });\n if (json) return json;\n } catch {\n // Fall through.\n }\n }\n try {\n return toolInputJsonSchema(inputSchema);\n } catch {\n // noteTool sits outside captureAndInject's try, and it runs inside the\n // vendor's own registerTool call — a throw here would surface as their\n // registration failing. A schema we cannot convert costs the snapshot\n // one tool's schema, nothing else — spelled the way both majors spell\n // an empty one, not as a third `{}`.\n return { type: \"object\", properties: {} };\n }\n };\n\n const tracker = new ProactiveTracker();\n const ctx: WrapContext = {\n sink,\n counter,\n tenantId,\n vendorId: config.vendorId,\n consentToken: config.consentToken,\n fallbackSessionId,\n defaultAgentRuntime: config.defaultAgentRuntime ?? \"unknown\",\n scrubber,\n resolveSessionId: config.resolveSessionId,\n annotationToolName,\n intentParamMode,\n paramRegistry: new Map(),\n vendorToolJsonSchema,\n bustSchemaMemo,\n tracker,\n surfaceState,\n emitSurface,\n };\n\n // Server instructions — load-bearing on instruction-aware runtimes (SPEC\n // §5.1.2). No public setter exists post-construction; see module\n // docstring for why this reach-in has no \"preferred path\" to fall back\n // from, unlike Python's adapter.\n const instructions = buildServerInstructions({\n vendorDisplayName: config.vendorDisplayName,\n annotationToolName,\n });\n internals.server._instructions = instructions;\n\n const resolvedAnnotationToolName = registerAnnotationTool(server, {\n sink,\n counter: ctx.counter,\n tenantId: ctx.tenantId,\n vendorId: ctx.vendorId,\n vendorDisplayName: config.vendorDisplayName,\n consentToken: ctx.consentToken,\n fallbackSessionId: ctx.fallbackSessionId,\n defaultAgentRuntime: ctx.defaultAgentRuntime,\n scrubber: ctx.scrubber,\n resolveSessionId: ctx.resolveSessionId,\n annotationToolName: config.annotationToolName,\n tracker,\n });\n\n // Retroactive: sweep whatever's already registered, regardless of call order.\n const existing = internals._registeredTools;\n if (existing) {\n for (const [name, entry] of Object.entries(existing)) {\n wireEntry(name, entry, ctx);\n }\n }\n\n // Prospective: every future registration goes through here too. Patched\n // AFTER registerAnnotationTool runs above (deliberately) — the annotate\n // tool registration hits the original, unpatched registerTool, lands in\n // _registeredTools, and gets excluded by name in the retroactive sweep\n // just above instead. Patching registerTool before registering the\n // annotate tool would work too (wireEntry's name check guards either\n // order), but this ordering means the annotate tool only ever needs to\n // be excluded in the one place, not reasoned about twice.\n const originalRegisterTool = internals.registerTool.bind(server);\n internals.registerTool = (...args: AnyArgs) => {\n const registered = originalRegisterTool(...args);\n wireEntry(String(args[0]), registered, ctx);\n return registered;\n };\n\n return new BatonHandle({\n sink,\n vendorId: config.vendorId,\n sessionId: fallbackSessionId,\n annotationToolName: resolvedAnnotationToolName,\n });\n}\n","/**\n * Annotation tool registration — SPEC §5.1.1. Registers a vendor-namespaced\n * tool (default `{vendorId}_annotate`) that accepts the annotation\n * signature (user_goal / expected_result / signal_type / overall_task /\n * suggested_improvement / context) and emits an `annotation` event.\n * Faithful port of `baton` (Python)'s `integrations/fastmcp/annotation.py`\n * (`user_goal` required, everything else optional — same as the Python tool's\n * signature, not a TS-specific choice).\n *\n * Tool-name pattern (`^[a-zA-Z0-9_-]{1,64}$`) is the strictest known client\n * pattern (Claude Desktop) — dots, slashes, and other separators rejected.\n */\n\nimport { z } from \"zod\";\nimport { AnnotationEventSchema } from \"../../events.js\";\nimport type { Sink } from \"../../sinks.js\";\nimport type { ResolveSessionIdHook } from \"./config.js\";\nimport { emit } from \"./emit.js\";\nimport { buildAnnotationToolDescription, SIGNAL_TYPES } from \"./llmText.js\";\nimport { extraMeta, type Extra } from \"./mcpTypes.js\";\nimport type { SupportedMcpServer } from \"./withBaton.js\";\nimport type { ProactiveTracker } from \"./proactiveTracker.js\";\nimport { detectAgentRuntime } from \"./runtimeAdapter.js\";\nimport { resolveSessionId } from \"./sessionResolution.js\";\nimport type { SessionCounter } from \"./sessionCounter.js\";\n\nconst TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;\n\n/** The annotate tool's arguments. Spelled out because `SupportedMcpServer`\n * types `registerTool`'s config as `unknown` — the price of accepting both\n * SDK majors' nominally distinct servers — so nothing infers this from the\n * Zod shape below. The two must be kept in step; the round-trip tests call\n * the tool through a real client, so a drift shows up as a runtime failure\n * rather than passing silently. */\ninterface AnnotationArgs extends Record<string, unknown> {\n user_goal: string;\n expected_result?: string | undefined;\n signal_type?: (typeof SIGNAL_TYPES)[number] | undefined;\n overall_task?: string | undefined;\n suggested_improvement?: string | undefined;\n context?: Record<string, unknown> | undefined;\n}\n\nexport function deriveAnnotationToolName(vendorId: string, override?: string): string {\n const name = override || `${vendorId}_annotate`;\n if (!TOOL_NAME_PATTERN.test(name)) {\n throw new Error(\n `Annotation tool name ${JSON.stringify(name)} violates the cross-runtime ` +\n `pattern ${TOOL_NAME_PATTERN.source} (Claude Desktop and others reject ` +\n \"names with dots or other separators).\",\n );\n }\n return name;\n}\n\nexport interface RegisterAnnotationToolOptions {\n sink: Sink;\n counter: SessionCounter;\n tenantId: string;\n vendorId: string;\n vendorDisplayName: string;\n consentToken: string;\n fallbackSessionId: string;\n defaultAgentRuntime: string;\n scrubber: (value: unknown) => unknown;\n resolveSessionId?: ResolveSessionIdHook | undefined;\n annotationToolName?: string | undefined;\n /** Shared with the tool-call wrapper so a session opens at most one\n * proactive annotation regardless of which path fires first. */\n tracker?: ProactiveTracker | undefined;\n}\n\n/** Register the annotation tool on `server`. Returns the resolved tool name. */\nexport function registerAnnotationTool(\n server: SupportedMcpServer,\n options: RegisterAnnotationToolOptions,\n): string {\n const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);\n const description = buildAnnotationToolDescription({\n vendorDisplayName: options.vendorDisplayName,\n });\n\n server.registerTool(\n name,\n {\n description,\n inputSchema: {\n user_goal: z.string(),\n expected_result: z.string().optional(),\n signal_type: z.enum(SIGNAL_TYPES).optional(),\n overall_task: z.string().optional(),\n suggested_improvement: z.string().optional(),\n context: z.record(z.string(), z.unknown()).optional(),\n },\n },\n async (args: AnnotationArgs, extra: Extra) => {\n const meta = extraMeta(extra);\n const runtime = detectAgentRuntime(meta) ?? options.defaultAgentRuntime;\n const scrubbedMeta = meta ? (options.scrubber(meta) as Record<string, unknown>) : null;\n const sessionId = await resolveSessionId(\n options.resolveSessionId,\n options.fallbackSessionId,\n extra,\n meta,\n name,\n args,\n );\n // A proactive annotation (no signal_type) claims the session's\n // proactive slot so the tool wrapper won't also synthesise one from\n // an injected `user_goal` param.\n if (args.signal_type === undefined) {\n options.tracker?.mark(sessionId);\n }\n\n await emit(options.sink, () =>\n AnnotationEventSchema.parse({\n tenant_id: options.tenantId,\n vendor_id: options.vendorId,\n session_id: sessionId,\n sequence_number: options.counter.next(sessionId),\n captured_at: new Date().toISOString(),\n consent_token: options.consentToken,\n agent_runtime: runtime,\n runtime_meta: scrubbedMeta,\n payload: {\n // Agent-facing names -> wire keys, as with `overall_task`\n // below: `user_goal` is stored as `intent`, `expected_result` as\n // `expected_outcome`.\n intent: options.scrubber(args.user_goal),\n expected_outcome: args.expected_result\n ? options.scrubber(args.expected_result)\n : null,\n // `signal_type` is a closed enum — nothing to scrub. The task label\n // is agent-authored free text (\"processing invoice for\n // bob@example.com\" is a realistic value), so it IS scrubbed.\n // Python's annotation.py does NOT scrub this field — a shared\n // gap found 2026-08-11, fixed here and flagged for the sibling\n // rather than mirrored. Not a wire divergence: scrubbing changes\n // content, not shape, and it's deterministic, so the\n // exact-string continuity rung 3b groups on survives.\n signal_type: args.signal_type ?? null,\n // Agent-facing param `overall_task` -> wire key `workflow`, the same\n // split the injected params use (`overall_task` -> `call_workflow`):\n // renaming the param must not move the key the console groups on.\n workflow: args.overall_task ? options.scrubber(args.overall_task) : null,\n suggested_improvement: args.suggested_improvement\n ? options.scrubber(args.suggested_improvement)\n : null,\n context: args.context ? options.scrubber(args.context) : null,\n },\n }),\n );\n\n return { content: [{ type: \"text\" as const, text: JSON.stringify({ ok: true }) }] };\n },\n );\n\n return name;\n}\n","import type { Event } from \"../../events.js\";\nimport { safeWrite, type Sink } from \"../../sinks.js\";\n\n/** Fail-open event construction + write. `build()` runs Zod validation —\n * a scrubber that breaks a payload's wire shape (e.g. replaces a record\n * wholesale) must not break the vendor's tool call any more than a sink\n * failure would; SPEC §11.2 fail-open applies to the whole capture step,\n * not just `sink.write`. */\nexport async function emit(sink: Sink, build: () => Event): Promise<void> {\n let event: Event;\n try {\n event = build();\n } catch (err) {\n process.stderr.write(`baton: event construction failed; event dropped: ${String(err)}\\n`);\n return;\n }\n await safeWrite(sink, event);\n}\n","/**\n * Shared LLM-facing text — server instructions + annotation tool\n * description. Byte-for-byte port of `baton` (Python)'s\n * `integrations/_llm_text.py` template strings; see that module's\n * docstring for the full rationale (split of responsibility under Claude\n * Code's instructions-truncation cap, the mechanical-trigger design). Kept\n * in sync by hand — there is no cross-language codegen for prose.\n */\n\nconst SERVER_INSTRUCTIONS_TEMPLATE = (\n vendorDisplayName: string,\n annotationToolName: string,\n) => `This server is wrapped in the ${vendorDisplayName} support-signal SDK. \\\nUse \\`${annotationToolName}\\` to record what the user is trying to do and \\\nhow each ${vendorDisplayName} tool call went. See that tool's \\\ndescription for field-level detail.\n\nBEFORE invoking any ${vendorDisplayName} tool, you MUST call \\\n\\`${annotationToolName}\\` with user_goal (REQUIRED), expected_result \\\n(REQUIRED), and overall_task (REQUIRED when the request fits a \\\nrecognizable \\\nbroader task, e.g., 'morning meeting prep', 'pre-outreach research').\n\nAFTER any ${vendorDisplayName} tool errors, times out, returns an \\\nunhelpful or contradictory result, or the user shows signs of giving \\\nup, you MUST call \\`${annotationToolName}\\` again with signal_type \\\n(REQUIRED) — one of failure, retry_loop, dead_end, parameter_confusion, \\\nslow_performance, abandonment, feature_gap, other — and \\\nsuggested_improvement (REQUIRED whenever you can articulate one).\n\nIF a ${vendorDisplayName} tool response lacks a structured field for \\\nwhat the user asked about, OR you satisfied the user's intent via a \\\nworkaround because no tool matched what they asked for, OR the user \\\nasked for something this server can't do — you MUST call \\\n\\`${annotationToolName}\\` with signal_type='feature_gap' AND still \\\nanswer the user with your best inference. Filing the annotation does \\\nNOT replace answering.`;\n\nconst ANNOTATION_TOOL_DESCRIPTION_TEMPLATE = (\n vendorDisplayName: string,\n) => `Record structured signal about a ${vendorDisplayName} tool call — \\\nwhat the user is trying to do, and how it went. Populate proactively \\\nbefore the call (user_goal + expected_result + overall_task) and reactively \\\nafter if the result was unhelpful (signal_type + suggested_improvement).\n\nFields:\n - user_goal: one sentence on what the user is trying to accomplish.\n - expected_result: what a successful result should look like, so a \\\nsilent/thin failure can be told apart from success.\n - overall_task: short stable label for the broader task this call \\\nserves, e.g., 'morning meeting prep', 'pre-outreach research', 'personal \\\nscheduling'. REPEAT the exact same string on every call serving the same \\\ntask; change it only when the user starts a different task. Skip when the \\\ncall doesn't fit a recognizable broader task.\n - signal_type: reactive-only — omit on a proactive annotation. \\\nSet only once a tool call has returned an unhelpful result. One of \\\nfailure, retry_loop, dead_end, parameter_confusion, \\\nslow_performance, abandonment, feature_gap, other.\n - suggested_improvement: reactive-only — omit on a proactive. \\\nA concrete sentence about what product change would have helped.\n - context: supplementary info not covered above. Common keys: plan, \\\nalternatives_considered, likely_cause, user_impact, error_class, \\\ndownstream_blocked, confidence_in_intent. For signal_type='feature_gap' \\\nalso missing_capability_field and requested_capability.`;\n\n// Empirically measured Claude Code truncation cap for\n// InitializeResult.instructions. Reserve headroom for vendor extensions\n// composed on top.\nconst CLAUDE_CODE_TRUNCATION_CAP = 2087;\nconst INSTRUCTIONS_LENGTH_CAP = 1500;\n\n// Canonical signal_type values per SPEC §3.1. Stable and additive-only\n// until v1.0 (SPEC §13). The annotation tool's inputSchema enum and the\n// instructions text reference the same eight values.\nexport const SIGNAL_TYPES = [\n \"failure\",\n \"retry_loop\",\n \"dead_end\",\n \"parameter_confusion\",\n \"slow_performance\",\n \"abandonment\",\n \"feature_gap\",\n \"other\",\n] as const;\n\nexport function buildServerInstructions(options: {\n vendorDisplayName: string;\n annotationToolName: string;\n}): string {\n const rendered = SERVER_INSTRUCTIONS_TEMPLATE(\n options.vendorDisplayName,\n options.annotationToolName,\n );\n if (rendered.length > INSTRUCTIONS_LENGTH_CAP) {\n throw new Error(\n `Rendered server instructions are ${rendered.length} chars, which exceeds ` +\n `the ${INSTRUCTIONS_LENGTH_CAP}-char safety cap (Claude Code truncates at ` +\n `~${CLAUDE_CODE_TRUNCATION_CAP}). Shorten vendorDisplayName or annotationToolName.`,\n );\n }\n return rendered;\n}\n\nexport function buildAnnotationToolDescription(options: { vendorDisplayName: string }): string {\n return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);\n}\n\n// =============================================================================\n// Intent-param injection text — mirrors `baton` (Python)'s\n// `integrations/_llm_text.py` USER_GOAL_PARAM_NAME/EXPECTED_RESULT_PARAM_NAME\n// section byte-for-byte (see that module's docstring for rationale: this is\n// the capture path that survives runtimes which drop `instructions`,\n// notably Claude Desktop).\n// =============================================================================\n\nexport const USER_GOAL_PARAM_NAME = \"user_goal\";\nexport const EXPECTED_RESULT_PARAM_NAME = \"expected_result\";\n/** The task-label grouping key (wire field `call_workflow`; console rung 3b).\n * Deliberately NOT named `workflow`: injected params live inside vendor tool\n * schemas, where `workflow` is a plausible real vendor param (Workfront\n * approvals, CI pipelines, Notion automations) — a collision would make the\n * strip swallow the vendor's own argument, and the name would invite the LLM\n * to fill in the vendor object it is touching instead of the meta task\n * label. */\nexport const OVERALL_TASK_PARAM_NAME = \"overall_task\";\n\n/** Provenance value stamped on `tool_call_start.payload.intent_source` and\n * on the synthesised proactive annotation when intent came from an injected\n * param (vs a real annotation-tool call). The Console reads this string. */\nexport const INTENT_SOURCE_PARAM = \"injected_param\";\n\nconst USER_GOAL_PARAM_DESCRIPTION =\n \"OPTIONAL. One sentence: what the user is actually trying to accomplish \" +\n \"with this call (their goal, not a restatement of the arguments).\";\n\nconst EXPECTED_RESULT_PARAM_DESCRIPTION =\n \"OPTIONAL. One sentence: what a successful result should look like, so a \" +\n \"silent/thin failure can be told apart from success.\";\n\n// The stability contract is the load-bearing design element: user_goal/\n// expected_result are call-scoped diagnostics that reword freely, so they\n// cannot key grouping; this param works ONLY if the model repeats the label\n// verbatim while the task is unchanged (measured 2026-08-10: without the\n// contract, 80% of adjacent same-task calls reword their goal text).\n//\n// Granularity is a KNOWN, MEASURED weakness of this text, kept anyway because\n// the obvious fix is worse. Do not reword without scoring against both corpora\n// in baton-internal `spikes/overall_task_a5/` (40 paired live-agent sessions,\n// 2026-08-11, one build per run).\n//\n// What this text gets wrong: when the user switches topic WITHOUT announcing\n// it, agents carry the first task's label onto everything after it — one\n// session labelled a rice lookup, a chickpea restock and a waste check all\n// \"cook dal tonight\". Boundary detection 0.700 on cue-free multi-task scripts\n// (1.000 when the user says \"Different thing:\", which is why an earlier run\n// missed this entirely).\n//\n// What it gets right, and why it stays: it never splits a task that should\n// stay whole — 20/20 same-task pairs held the label verbatim across both\n// corpora. The candidate rewording (\"the specific task the user is working on\n// right now — not the overall theme of the conversation\") fixes the boundary\n// problem completely (1.000) but relabels *within* a single task, describing\n// successive steps of one goal as different tasks; it scored 0.200 then 0.400\n// over-split on identical scripts, and produced an A → B → A label that a\n// merge-only, adjacency-based consumer resolves as three tasks instead of one.\n// The gain (+0.300 boundary) is smaller than the cost (0.400 over-split), and\n// shattering is the failure mode that destroys downstream trust, so the trade\n// goes this way.\n//\n// The open target for any v3 is therefore specific: the candidate's boundary\n// behaviour with this text's within-task stability. The two failure modes are\n// independent, so it is not a granularity dial to be tuned — it needs the\n// repeat-verbatim contract hardened against step-level rewording.\nconst OVERALL_TASK_PARAM_DESCRIPTION =\n \"OPTIONAL. Short stable label for the broader task this call serves \" +\n \"(e.g. 'prepare campaign approval'). REPEAT the exact same string on \" +\n \"every call serving the same task; change it only when the user starts \" +\n \"a different task.\";\n\nexport function buildUserGoalParamDescription(): string {\n return USER_GOAL_PARAM_DESCRIPTION;\n}\n\nexport function buildOverallTaskParamDescription(): string {\n return OVERALL_TASK_PARAM_DESCRIPTION;\n}\n\nexport function buildExpectedResultParamDescription(): string {\n return EXPECTED_RESULT_PARAM_DESCRIPTION;\n}\n","/**\n * The context object every `McpServer` tool callback receives, whether\n * registered via `registerTool` or the annotation tool.\n *\n * Declared structurally rather than imported, for two reasons. Two shapes\n * wear this name — the official SDK 1.x passes `RequestHandlerExtra`, the v2\n * packages pass their own `ServerContext` — and importing either one would\n * pin this package to that major even for a type, which `tsup`'s `.d.ts`\n * rollup then re-exports into `dist/index.d.ts` and a consumer without that\n * package fails to typecheck against. Only these three fields are ever read.\n *\n * The divergence that matters: v2's `ServerContext` is\n * `{ sessionId, mcpReq, http }` (measured 2026-08-28) — it keeps `sessionId`\n * but moves the request `_meta` down under `mcpReq`. Read only at the 1.x\n * location and every v2 session silently degrades to\n * `agent_runtime: \"unknown\"` with no `runtime_meta`: no error, just worse\n * data. Use {@link extraMeta}, never `extra._meta`.\n */\nexport interface Extra {\n /** Transport-supplied session id; present on both majors. */\n sessionId?: string | undefined;\n /** 1.x: the request's `_meta`, at the top level. */\n _meta?: unknown;\n /** v2's `ServerContext.mcpReq` — the in-flight JSON-RPC request. */\n mcpReq?: { _meta?: unknown } | undefined;\n}\n\n/** The call's `_meta`, from wherever this SDK major keeps it. */\nexport function extraMeta(extra: Extra): Record<string, unknown> | null {\n const direct = extra._meta as Record<string, unknown> | undefined;\n if (direct) return direct;\n const nested = extra.mcpReq?._meta as Record<string, unknown> | undefined;\n return nested ?? null;\n}\n","/**\n * Per-runtime `_meta` heuristics — detect which agent runtime is calling\n * the vendor's MCP server. Mirrors `baton` (Python)'s\n * `integrations/runtime_adapter.py::detect_agent_runtime`.\n *\n * Per SPEC §5.2: different runtimes populate MCP's `_meta` differently\n * (Claude Code adds `claudecode/toolUseId`; Cursor only sets\n * `progressToken`; Claude Desktop sets nothing).\n *\n * ⚠ **A caller cannot assert its own runtime.** This used to read an\n * `_meta.baton.agent_runtime` override; Python removed both spellings of it\n * (the nested form at B5, the reverse-DNS `io.baton/*` form on 2026-09-09)\n * and this is the same removal, not a port of the old behaviour. Two sensors\n * watching one client must not disagree about what it is, and the value here\n * is self-reported — never attested — so an override would let the thing\n * being measured choose its own label. Detection answers only from signals\n * the SDK derives itself.\n */\n\nexport function detectAgentRuntime(meta: Record<string, unknown> | null): string | null {\n if (!meta) return null;\n\n for (const key of Object.keys(meta)) {\n if (key.startsWith(\"claudecode/\")) return \"claude-code\";\n }\n\n return null;\n}\n","import type { ResolveSessionIdHook } from \"./config.js\";\nimport type { Extra } from \"./mcpTypes.js\";\n\n/** Real per-call session id, shared by the tool-call wrapper and the\n * annotation tool so both file events under the same id. A configured\n * `resolveSessionId` hook is checked first and, on a non-empty return,\n * wins outright — mirrors Python's rung-0 `resolve_session_id_hook`. Below\n * that, falls back to the transport-supplied `extra.sessionId`, then the\n * process-wide fallback. */\nexport async function resolveSessionId(\n hook: ResolveSessionIdHook | undefined,\n fallbackSessionId: string,\n extra: Extra,\n meta: Record<string, unknown> | null,\n toolName: string,\n args: Record<string, unknown>,\n): Promise<string> {\n if (hook) {\n try {\n const hookResult = await hook({ meta, toolName, arguments: args });\n if (typeof hookResult === \"string\" && hookResult) return hookResult;\n } catch {\n // Never propagate a hook failure — fall through to the ladder below,\n // mirroring Python's resolve_via_hook.\n }\n }\n if (typeof extra.sessionId === \"string\" && extra.sessionId) return extra.sessionId;\n return fallbackSessionId;\n}\n","/**\n * `BatonConfig` — vendor-side configuration for `withBaton`. A trimmed\n * mirror of `baton` (Python)'s `integrations/_config.py::VendorConfig`.\n */\n\nimport type { Sink } from \"../../sinks.js\";\n\n// Vendor IDs are the annotation-tool-name prefix — same pattern Python\n// validates against. They are NOT the tenant id: see `BatonConfig.tenantId`,\n// which used to be a second copy of this value.\nconst VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;\n\n// Per-tool intent-param injection modes (mirrors baton-proxy's\n// BATON_INTENT_PARAM and Python's VendorConfig.intent_param_mode).\nconst INTENT_PARAM_MODES = new Set([\"optional\", \"required\", \"off\"]);\n\n/** Normalized input to `BatonConfig.resolveSessionId`. Deliberately doesn't\n * carry the raw MCP SDK `extra` object — this shape is stable across\n * whatever the TS MCP ecosystem does with its request-handler signature. */\nexport interface SessionResolutionContext {\n meta: Record<string, unknown> | null;\n toolName: string;\n arguments: Record<string, unknown>;\n}\n\nexport type ResolveSessionIdHook = (\n context: SessionResolutionContext,\n) => string | null | undefined | Promise<string | null | undefined>;\n\nexport interface BatonConfig {\n /** Short stable identifier for the SERVER whose surface is captured\n * (e.g. `\"acme\"`). Also the default annotation tool name prefix\n * (`{vendorId}_annotate`). This is not the account — see `tenantId`. */\n vendorId: string;\n /** Account identifier for the envelope's `tenant_id` (SPEC §11.4).\n *\n * **This is not `vendorId`, and conflating them is the bug this field\n * exists to fix.** `tenantId` names the ACCOUNT the collector\n * authenticates; `vendorId` names the SERVER whose surface is being\n * captured. One account wraps many servers, so sending the account id in\n * both slots collapses them: two servers in one workspace render as one,\n * whose label flips to whichever deployed last, and a server ends up\n * naming itself with its workspace's opaque id.\n *\n * Resolved explicit → `BATON_TENANT_ID` → `vendorId`. That last fallback\n * exists for our own fixtures during the change, not for anyone's install\n * — a wrap block states this value on its own line, because it is the diff\n * a customer reviews in their pull request. The environment read is\n * guarded, so this package still loads on runtimes with no `process`. */\n tenantId?: string;\n /** Human-readable vendor name used in server instructions and the\n * annotation tool description — whitelabel obligation (SPEC §5.4): no\n * Baton-branded strings reach the calling agent. */\n vendorDisplayName: string;\n /** End-user consent token attached to every emitted event per SPEC §2.3 —\n * required, the Console MUST reject events missing it. */\n consentToken: string;\n /** Where events go. Defaults to `new StdoutSink()` — zero-config dev mode. */\n sink?: Sink;\n /** Default `agent_runtime` when `_meta` heuristics can't detect one. */\n defaultAgentRuntime?: string;\n /** PII scrubber per SPEC §7, applied to tool params/results, `_meta`,\n * intent strings and error bodies before they reach the sink. Defaults to\n * the shipped default ruleset (`new Scrubber().scrub` — email, bearer,\n * sk-keys, AWS keys, JWTs, phones, Luhn-checked cards, plus sensitive\n * field names), matching `baton` (Python) and baton-proxy: on by default\n * so untouched integrations get scrubbing without the operator opting in.\n * Pass `identityScrub` to explicitly opt out, or supply your own. */\n scrubber?: (value: unknown) => unknown;\n /** Optional vendor-supplied session-id resolver, checked BEFORE\n * `extra.sessionId` — mirrors Python's `resolve_session_id` rung 0. */\n resolveSessionId?: ResolveSessionIdHook;\n /** Optional override for the annotation tool name. Default is\n * `{vendorId}_annotate`. */\n annotationToolName?: string;\n /** Per-tool intent-param injection (mirrors baton-extmcp's vendor-neutral\n * naming). `\"optional\"` (default) injects `user_goal`/`expected_result`\n * string params on every wrapped tool's advertised schema; `\"required\"`\n * also adds `user_goal` to the schema's required fields (`expected_result`\n * stays optional regardless); `\"off\"` disables injection. Both params are\n * stripped before the vendor handler runs, so the tool never sees them.\n * This is what captures intent on runtimes that drop `instructions`\n * (notably Claude Desktop) — where the annotation tool alone yields\n * nothing. A tool registered with no `inputSchema` at all is left alone\n * regardless of this setting (see `schemaCompat.injectGoalParams`). */\n intentParamMode?: \"optional\" | \"required\" | \"off\";\n}\n\n/**\n * `tenant_id` per SPEC §11.4: explicit → `BATON_TENANT_ID` → `vendorId`.\n * Mirrors Python's `integrations/_config.py::_resolve_tenant_id`, including\n * its falsy-means-unset behaviour (`if explicit:`), so an empty string falls\n * through rather than emitting a blank tenant.\n *\n * The `vendorId` tail is a migration shim for this repo's own fixtures, not a\n * supported configuration: it reproduces exactly the collapse the split exists\n * to end, so it is the branch to delete once the recipe emits the var.\n *\n * Resolved ONCE per `withBaton` install and shared by the tool-call and\n * annotation paths — two resolutions could disagree, and an annotation under a\n * different tenant than its call is unjoinable.\n */\nexport function resolveTenantId(explicit: string | undefined, vendorId: string): string {\n if (explicit) return explicit;\n // Guarded: `process` is absent on edge/worker runtimes, and this package\n // reads no other environment variable. A missing `process` is a miss, not a\n // crash inside the vendor's server startup.\n const fromEnv = typeof process !== \"undefined\" ? process.env?.BATON_TENANT_ID : undefined;\n if (fromEnv) return fromEnv;\n return vendorId;\n}\n\nexport function validateBatonConfig(config: BatonConfig): void {\n if (!VENDOR_ID_PATTERN.test(config.vendorId)) {\n throw new Error(\n `vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} ` +\n \"— used as the default annotation tool name prefix.\",\n );\n }\n if (!config.vendorDisplayName) {\n throw new Error(\n \"BatonConfig.vendorDisplayName is required — used in server instructions \" +\n \"and the annotation tool description (whitelabel obligation, SPEC §5.4).\",\n );\n }\n if (!config.consentToken) {\n throw new Error(\n \"BatonConfig.consentToken is required per SPEC §2.3 — events without a \" +\n \"valid consent_token MUST be rejected by the consumer.\",\n );\n }\n if (config.intentParamMode !== undefined && !INTENT_PARAM_MODES.has(config.intentParamMode)) {\n throw new Error(\n `BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ` +\n `${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`,\n );\n }\n}\n","import type { Sink } from \"../../sinks.js\";\n\n/**\n * Handle returned from `withBaton` for graceful shutdown and session\n * correlation. Trimmed mirror of Python's `integrations/_handle.py::BatonHandle`\n * — `escalate()` is not here; it's a Console action-surface feature, out of\n * scope for this package.\n */\nexport class BatonHandle {\n readonly sink: Sink;\n readonly vendorId: string;\n /** Process-lifetime fallback session id — the value events fall back to\n * when no real per-call session id resolves. Not every event necessarily\n * carries this id; see `withBaton`'s session-resolution order. */\n readonly sessionId: string;\n /** The resolved annotation tool name (`{vendorId}_annotate` unless\n * overridden via `BatonConfig.annotationToolName`). */\n readonly annotationToolName: string;\n\n constructor(options: {\n sink: Sink;\n vendorId: string;\n sessionId: string;\n annotationToolName: string;\n }) {\n this.sink = options.sink;\n this.vendorId = options.vendorId;\n this.sessionId = options.sessionId;\n this.annotationToolName = options.annotationToolName;\n }\n\n /** Flush any pending events held by the sink. */\n async flush(): Promise<void> {\n await this.sink.flush();\n }\n\n /** Flush and release sink resources. Subsequent writes reject. */\n async aclose(): Promise<void> {\n await this.sink.aclose();\n }\n}\n","/**\n * Tracks which sessions have already emitted a proactive annotation —\n * mirrors `baton` (Python)'s `_state.py::ProactiveTracker`. Coordinates the\n * two proactive sources so a session opens at most one: `withBaton`'s tool\n * wrapper synthesises a proactive from the first injected `user_goal` it\n * sees, and the annotation tool marks the slot claimed when the agent calls\n * it proactively itself (`signal_type` omitted). On instruction-aware\n * runtimes both paths can fire; on Claude Desktop only the injected-param\n * path does.\n *\n * Synchronous, mutating a plain `Set` — safe with no lock because Node's\n * single-threaded event loop never interleaves two synchronous calls here.\n */\nexport class ProactiveTracker {\n private readonly emitted = new Set<string>();\n\n /** Claim the session's proactive slot. Returns true exactly once per\n * session (the caller should then emit); false if already claimed. */\n claim(sessionId: string): boolean {\n if (this.emitted.has(sessionId)) return false;\n this.emitted.add(sessionId);\n return true;\n }\n\n /** Mark the slot claimed without emitting here (the annotation tool's own\n * handler already emitted the annotation event itself). */\n mark(sessionId: string): void {\n this.emitted.add(sessionId);\n }\n}\n","/**\n * Per-session monotonic sequence-number counter — mirrors `baton` (Python)'s\n * `_state.py::SessionCounter`. First call for a session returns 1.\n *\n * Python guards this with an `asyncio.Lock` because a single event loop can\n * still interleave two `await counter.next(...)` callers between the read\n * and the write of `self._counters[session_id]`. Node's single-threaded\n * event loop has the same hazard in principle, but `next()` here contains\n * no `await` — the read-increment-write is one synchronous turn, so it's\n * already atomic with respect to other JS execution. No lock needed.\n */\nexport class SessionCounter {\n private readonly counters = new Map<string, number>();\n\n next(sessionId: string): number {\n const current = this.counters.get(sessionId) ?? 0;\n const next = current + 1;\n this.counters.set(sessionId, next);\n return next;\n }\n}\n","/**\n * A faithful vendored port of the four zod v3/v4 helpers and the JSON Schema\n * conversion that the official SDK **1.x** keeps in `server/zod-compat.js` +\n * `server/zod-json-schema-compat.js`.\n *\n * Why vendored rather than imported. Those are deep imports into\n * `@modelcontextprotocol/sdk`, and a *runtime* one — so any module graph that\n * reaches `schemaCompat.ts` cannot load at all unless 1.x is installed. That\n * makes the package uninstallable for a vendor on the v2 packages\n * (`@modelcontextprotocol/server`), who has no reason to have 1.x in their\n * tree, which is the whole point of supporting v2. Copying ~90 lines buys\n * both majors one entry point and deletes a documented reach-in; the\n * alternatives (async `import()` behind a synchronous `withBaton`, or a\n * `createRequire` shim that has to survive a dual ESM/CJS build) buy neither.\n *\n * Ported faithfully, warts included — this code exists to reproduce what 1.x\n * *does*, not what it should do. `objectFromShape` returns `zod/v4-mini`\n * objects, which carry no `~standard.jsonSchema`; that is 1.x's own behaviour\n * for the schemas it renders and validates, so \"improving\" it here would\n * change 1.x-path output rather than preserve it. (The v2 path deliberately\n * does NOT come through here — see `schemaCompat.injectGoalParamsV2`.)\n *\n * Held safe by `test/integrations/mcp/zodCompat.test.ts`, which diffs every\n * function in this file against 1.x's originals over a shared corpus. 1.x\n * stays a devDependency for exactly that reason.\n *\n * Known residual: this resolves `zod` from OUR dependency tree, while 1.x's\n * own `tools/list` resolves it from ITS tree. Deduped in any normal install\n * (one hoisted zod), divergent only where a vendor carries two zod v4 copies\n * — the same class of risk 1.x already runs internally.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment */\n\nimport * as z3rt from \"zod/v3\";\nimport * as z4mini from \"zod/v4-mini\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\n\n/** Present on zod 4 (Classic and Mini) schemas; absent on zod 3.\n *\n * One deliberate divergence from the original, pinned by test: 1.x reads\n * `s._zod` unguarded and therefore throws a `TypeError` on `null`/`undefined`.\n * That is unreachable through 1.x's own call sites and through ours — every\n * caller has already checked — so this keeps the optional chain rather than\n * copy a crash into a module whose callers would be the ones to hit it. */\nexport function isZ4Schema(s: unknown): boolean {\n const schema = s as { _zod?: unknown } | null | undefined;\n return !!schema?._zod;\n}\n\n/** Build an object schema from a shape, in the shape's own zod major. */\nexport function objectFromShape(shape: Record<string, unknown>): unknown {\n const values = Object.values(shape);\n if (values.length === 0) return z4mini.object({}); // default to v4 Mini\n const allV4 = values.every(isZ4Schema);\n const allV3 = values.every((s) => !isZ4Schema(s));\n if (allV4) return z4mini.object(shape as any);\n if (allV3) return z3rt.object(shape as any);\n throw new Error(\"Mixed Zod versions detected in object shape.\");\n}\n\n/** The field map of an object schema. v3 exposes `.shape`; v4 keeps it on\n * `_zod.def.shape`, and either may be a thunk. */\nexport function getObjectShape(schema: unknown): Record<string, unknown> | undefined {\n if (!schema) return undefined;\n let rawShape: unknown;\n if (isZ4Schema(schema)) {\n rawShape = (schema as any)._zod?.def?.shape;\n } else {\n rawShape = (schema as any).shape;\n }\n if (!rawShape) return undefined;\n if (typeof rawShape === \"function\") {\n try {\n return (rawShape as () => Record<string, unknown>)();\n } catch {\n return undefined;\n }\n }\n return rawShape as Record<string, unknown>;\n}\n\n/** Normalise to an object schema, accepting either an already-constructed\n * object schema (v3 or v4) or a raw shape that needs wrapping. Returns\n * `undefined` for anything else — including a non-object schema, which is\n * how a tool with no spliceable `inputSchema` is left alone. */\nexport function normalizeObjectSchema(schema: unknown): unknown {\n if (!schema) return undefined;\n\n if (typeof schema === \"object\") {\n const asAny = schema as any;\n // No `_def`/`_zod` means it is not a schema instance, so it may be a raw\n // shape — confirmed heuristically by every value being schema-like.\n if (!asAny._def && !asAny._zod) {\n const values = Object.values(schema as Record<string, unknown>);\n if (\n values.length > 0 &&\n values.every(\n (v: any) =>\n typeof v === \"object\" &&\n v !== null &&\n (v._def !== undefined || v._zod !== undefined || typeof v.parse === \"function\"),\n )\n ) {\n return objectFromShape(schema as Record<string, unknown>);\n }\n }\n }\n\n if (isZ4Schema(schema)) {\n const def = (schema as any)._zod?.def;\n if (def && (def.type === \"object\" || def.shape !== undefined)) return schema;\n } else {\n if ((schema as any).shape !== undefined) return schema;\n }\n return undefined;\n}\n\nexport interface ToJsonSchemaOptions {\n target?: string | undefined;\n strictUnions?: boolean | undefined;\n pipeStrategy?: \"input\" | \"output\" | undefined;\n}\n\nfunction mapMiniTarget(t: string | undefined): \"draft-7\" | \"draft-2020-12\" {\n if (!t) return \"draft-7\";\n if (t === \"jsonSchema7\" || t === \"draft-7\") return \"draft-7\";\n if (t === \"jsonSchema2019-09\" || t === \"draft-2020-12\") return \"draft-2020-12\";\n return \"draft-7\";\n}\n\n/** JSON Schema for a zod v3 or v4 schema, in the exact spelling 1.x's own\n * `tools/list` emits. */\nexport function toJsonSchemaCompat(\n schema: unknown,\n opts?: ToJsonSchemaOptions,\n): Record<string, unknown> {\n if (isZ4Schema(schema)) {\n return z4mini.toJSONSchema(schema as any, {\n target: mapMiniTarget(opts?.target),\n io: opts?.pipeStrategy ?? \"input\",\n });\n }\n return zodToJsonSchema(schema as any, {\n strictUnions: opts?.strictUnions ?? true,\n pipeStrategy: opts?.pipeStrategy ?? \"input\",\n });\n}\n","/**\n * Intent-param injection for the official SDK's **1.x** `McpServer`.\n *\n * Splicing `user_goal`/`expected_result`/`overall_task` into a vendor's\n * EXISTING Zod object schema has to build the injected fields with a schema\n * instance from the SAME zod major as the tool's other fields — a vendor on\n * 1.x may be on zod v3 or v4, and `objectFromShape` throws on a mixed-version\n * shape. The v3/v4 bridge that makes that work is `./zodCompat.js`, a\n * vendored port of the helpers 1.x uses internally; see that module for why\n * it is copied rather than imported (short version: the import is a runtime\n * one, and it would make this package uninstallable for a v2-only vendor).\n *\n * The v2 packages need none of this — `injectGoalParamsV2`, below.\n */\n\nimport {\n getObjectShape,\n isZ4Schema,\n normalizeObjectSchema,\n objectFromShape,\n toJsonSchemaCompat,\n} from \"./zodCompat.js\";\nimport { z as zV4 } from \"zod\";\nimport { z as zV3 } from \"zod/v3\";\nimport {\n EXPECTED_RESULT_PARAM_NAME,\n OVERALL_TASK_PARAM_NAME,\n USER_GOAL_PARAM_NAME,\n buildExpectedResultParamDescription,\n buildOverallTaskParamDescription,\n buildUserGoalParamDescription,\n} from \"./llmText.js\";\n\nexport type IntentParamMode = \"optional\" | \"required\" | \"off\";\n\n/** The sliver of a zod namespace the injected fields need — written\n * structurally so the same builder serves zod v3, zod v4, and whichever\n * instance the vendor's own schema was built with. */\ninterface DescribableField {\n describe(description: string): unknown;\n}\ninterface StringFieldFactory {\n string(): DescribableField & { optional(): DescribableField };\n}\nexport type IntentParamDispositions = Record<string, \"injected\" | \"native\">;\n\n// Mirrors mcp.js's private EMPTY_OBJECT_JSON_SCHEMA — used identically by\n// the SDK's own tools/list handler when a tool declares no inputSchema.\nconst EMPTY_OBJECT_JSON_SCHEMA = { type: \"object\", properties: {} };\n\n/**\n * Splice `user_goal`/`expected_result`/`overall_task` into `inputSchema`'s\n * object shape.\n * Returns the original schema unchanged (with empty dispositions) when\n * there's no object schema to extend into — a tool with no `inputSchema` at\n * all is left alone rather than given one, because adding a schema where\n * none existed would flip the SDK's handler-calling convention from\n * `(extra)` to `(args, extra)` and break the vendor's own zero-arg handler.\n *\n * Known fidelity gap: rebuilding via `objectFromShape` recovers only the\n * field map (`getObjectShape`), not object-level modifiers the vendor's\n * schema may have carried (`.strict()`/`.passthrough()`/`.refine()`).\n * Python's JSON-schema-dict injection has no equivalent loss (JSON Schema\n * has no refinement concept to lose); this is a TS-specific, accepted gap.\n *\n * NO `mode` PARAMETER since 2026-09-01 (D7). It used to select an enforcing\n * field for `required`; it cannot select an advertisement instead, because\n * this package has no `tools/list` hook — see `buildIntentFields` for the\n * measurement. A parameter that selects nothing is worse than no parameter:\n * it reads as a knob. The mode is still a real config value, still gates\n * `off` in `withBaton`, and is still reported in\n * `seam_augmentations.intent_param.mode`.\n */\nexport function injectGoalParams(inputSchema: unknown): {\n schema: unknown;\n dispositions: IntentParamDispositions;\n} {\n const objSchema = normalizeObjectSchema(inputSchema);\n if (!objSchema) return { schema: inputSchema, dispositions: {} };\n const existingShape = getObjectShape(objSchema) ?? {};\n const values = Object.values(existingShape);\n // Empty shape: default to v4, matching objectFromShape's own default.\n const useV4 = values.length === 0 || isZ4Schema(values[0]);\n const zodImpl = useV4 ? zV4 : zV3;\n\n const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl);\n\n if (Object.keys(toInject).length === 0)\n return { schema: inputSchema, dispositions };\n const mergedShape = { ...existingShape, ...toInject };\n const newSchema = objectFromShape(mergedShape);\n return { schema: newSchema, dispositions };\n}\n\n/** The intent fields to splice, and what each name's disposition is. Shared\n * by both SDK majors so the two injection paths cannot drift on which\n * params exist, which are promoted by `mode`, or when a vendor's own field\n * of the same name wins. */\nfunction buildIntentFields(\n existingShape: Record<string, unknown>,\n zodImpl: StringFieldFactory,\n): {\n dispositions: IntentParamDispositions;\n toInject: Record<string, unknown>;\n} {\n const dispositions: IntentParamDispositions = {};\n const toInject: Record<string, unknown> = {};\n\n // EVERY injected field is optional, in EVERY mode. `mode` no longer reaches\n // this builder, and that is the change of 2026-09-01 (D7 in baton-internal\n // `intent_param_injection.md`), not an oversight.\n //\n // `required` used to build a non-optional zod field here — on the VENDOR'S\n // OWN schema — so an agent that omitted `user_goal` had its call refused by\n // the vendor's server. Baton would have been breaking a customer's product\n // to collect a telemetry string. For a wrapper whose whole claim is that it\n // does not change how the wrapped server behaves, that is the wrong trade at\n // any capture rate, so `required` now means what it means in the proxy:\n // ADVERTISED as required, never enforced.\n //\n // ...except that the advertisement half is not reachable here, and the\n // reason is structural rather than a decision. Measured 2026-09-01 against\n // both zod majors this package supports:\n //\n // zod v4 .optional() -> required: [\"a\"] parses: true\n // zod v4 union([string,undef]) -> required: [\"a\",\"user_goal\"] parses: FALSE\n // zod v3 .optional() -> required: [\"a\"] parses: true\n // zod v3 union([string,undef]) -> required: [\"a\"] parses: true\n //\n // In v4 advertised-required and enforced are the same bit; in v3 the\n // advertisement is unreachable at all. Python can hold the two apart only\n // because it edits the rendered JSON Schema of a `tools/list` RESPONSE — and\n // this package has no `tools/list` hook (see withBaton.ts), so there is no\n // seam at which to advertise something the validator does not enforce.\n //\n // Consequence, recorded rather than hidden: in TypeScript `required` and\n // `optional` now produce identical behaviour AND identical advertisement.\n // The mode is kept on the config surface for parity with Python and because\n // `seam_augmentations.intent_param.mode` reports it, but it selects nothing\n // here. A future implementation that wants the advertisement needs a\n // response-rendering seam, not a different zod expression.\n if (USER_GOAL_PARAM_NAME in existingShape) {\n dispositions[USER_GOAL_PARAM_NAME] = \"native\";\n } else {\n dispositions[USER_GOAL_PARAM_NAME] = \"injected\";\n toInject[USER_GOAL_PARAM_NAME] = zodImpl\n .string()\n .optional()\n .describe(buildUserGoalParamDescription());\n }\n\n for (const [name, buildDescription] of [\n [EXPECTED_RESULT_PARAM_NAME, buildExpectedResultParamDescription],\n [OVERALL_TASK_PARAM_NAME, buildOverallTaskParamDescription],\n ] as const) {\n if (name in existingShape) {\n dispositions[name] = \"native\";\n } else {\n dispositions[name] = \"injected\";\n toInject[name] = zodImpl.string().optional().describe(buildDescription());\n }\n }\n\n return { dispositions, toInject };\n}\n\n/**\n * The same splice for the official SDK's **v2** packages, which need none of\n * this module's compat machinery: v2 refuses zod v3 outright (the schema\n * registers, then throws inside the `tools/list` handler and fails the whole\n * list), so there is no mixed-major case to bridge.\n *\n * Extends the vendor's own schema rather than rebuilding one from its field\n * map. `zV4.object({ ...schema.shape, ...injected })` recovers only the\n * fields and silently discards every object-level semantic the vendor\n * attached — measured: a tool declared `z.object({a,b}).refine(v => v.a !==\n * v.b)` then accepted `{a:\"x\", b:\"x\"}`, handing the vendor's handler\n * arguments its own schema rejects, and a `z.strictObject` quietly stripped\n * unknown keys instead of refusing them. Installing Baton must not weaken a\n * vendor's validation. `.extend()` keeps checks and `additionalProperties`\n * (measured: the violating call above is now rejected at the protocol layer,\n * exactly as it would be on the unwrapped tool) and still renders the\n * injected params on `tools/list`.\n *\n * One consequence worth knowing: the vendor's refinements now run over the\n * arguments *including* `user_goal`/`expected_result`/`overall_task`, since\n * v2 validates before dispatch and the strip happens in our wrapper after.\n * A refinement over key counts or unknown keys would therefore observe\n * Baton's params. Rare, and the alternative is dropping the refinement\n * entirely.\n *\n * Returns the schema unchanged when there is nothing safe to extend — a\n * non-zod `StandardSchemaWithJSON` (ArkType, Valibot, hand-rolled: v2's\n * primary `registerTool` overload takes any of them, and none has `.extend`).\n * Such a tool is still wrapped and still emits `tool_call_*`; it just carries\n * no injected intent params. Deliberately NOT falling back to a rebuild\n * there — a rebuild is the semantics loss this function exists to avoid.\n * Making injection work for those schemas means decorating\n * `~standard.jsonSchema.input()`, which advertises fine but leaves validation\n * with the vendor's own schema.\n *\n * The 1.x path above has the same rebuild-loses-modifiers gap, documented in\n * `injectGoalParams`; it is not changed here because it goes through\n * `objectFromShape` and the zod-mini objects 1.x itself renders.\n *\n * No `mode` parameter, for the same reason as in `injectGoalParams` above.\n */\nexport function injectGoalParamsV2(inputSchema: unknown): {\n schema: unknown;\n dispositions: IntentParamDispositions;\n} {\n const candidate = inputSchema as\n | {\n shape?: Record<string, unknown>;\n extend?: (fields: Record<string, unknown>) => unknown;\n }\n | undefined;\n const shape = candidate?.shape;\n if (\n !shape ||\n typeof shape !== \"object\" ||\n typeof candidate?.extend !== \"function\"\n ) {\n return { schema: inputSchema, dispositions: {} };\n }\n\n const { dispositions, toInject } = buildIntentFields(shape, zV4);\n if (Object.keys(toInject).length === 0)\n return { schema: inputSchema, dispositions };\n return { schema: candidate.extend(toInject), dispositions };\n}\n\n/** The vendor-true JSON Schema for a tool's `inputSchema` — same conversion\n * (`toJsonSchemaCompat`, matching options) the SDK 1.x itself uses to build\n * `tools/list`'s advertised `inputSchema`, so the surface snapshot matches\n * byte-for-byte what the client actually receives. Call BEFORE\n * `injectGoalParams` mutates the entry, so the snapshot reflects the\n * vendor's real schema, not Baton's addition.\n *\n * 1.x only: on v2, `withBaton` reads the server's own converted schema\n * instead, because v2 renders `tools/list` with a different one. */\nexport function toolInputJsonSchema(\n inputSchema: unknown,\n): Record<string, unknown> {\n const objSchema = normalizeObjectSchema(inputSchema);\n if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;\n return toJsonSchemaCompat(objSchema, {\n strictUnions: true,\n pipeStrategy: \"input\",\n });\n}\n","/**\n * Shared `surface_snapshot` helpers — mirrors `baton` (Python)'s\n * `integrations/_surface.py` (see that module's docstring for full\n * rationale). The vendor-true surface (`server_info`/`capabilities`/\n * `instructions` + the tool list) is hashed (canonical JSON, sorted keys)\n * and emitted once per observed hash.\n *\n * The hash MUST reflect only the vendor's real surface, never anything\n * Baton adds — `buildServerMeta` MUST run before `withBaton` mutates server\n * instructions, and callers must capture each tool's `inputSchema` (via\n * `schemaCompat.toolInputJsonSchema`) before `injectGoalParams` mutates it,\n * or toggling `intentParamMode` would invalidate every hash a recipe was\n * pinned against.\n *\n * NOT guaranteed to match a Python- or proxy-observed hash of the \"same\"\n * server: each producer serializes `tools` from a different shape.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport function surfaceHash(surface: unknown): string {\n const canonical = canonicalJson(surface);\n const digest = createHash(\"sha256\").update(canonical, \"utf-8\").digest(\"hex\");\n return `sha256:${digest}`;\n}\n\nfunction canonicalJson(value: unknown): string {\n if (value === null || typeof value !== \"object\") return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`;\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(record[k])}`).join(\",\")}}`;\n}\n\nexport interface ServerMeta {\n server_info: { name: string; version: string } | null;\n capabilities: Record<string, unknown> | null;\n instructions: string | null;\n}\n\n/** Vendor-true `server_info`/`capabilities`/`instructions`, read from the\n * low-level `Server` (`McpServer.server`) BEFORE `withBaton` sets its own\n * instructions suffix. `_serverInfo`/`_instructions` are private fields\n * with no public getter — same reach-in class as `withBaton.ts`'s\n * `_registeredTools`/`_instructions`; `getCapabilities()` is public. */\nexport function buildServerMeta(lowlevelServer: unknown): ServerMeta {\n /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call */\n const server = lowlevelServer as any;\n const info = server._serverInfo as { name?: string; version?: string } | undefined;\n const capabilities =\n typeof server.getCapabilities === \"function\"\n ? (server.getCapabilities() as Record<string, unknown>)\n : null;\n const instructions = (server._instructions as string | undefined) ?? null;\n /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call */\n return {\n server_info: info ? { name: info.name ?? \"\", version: info.version ?? \"\" } : null,\n capabilities: capabilities ?? null,\n instructions,\n };\n}\n\nexport function assembleSurface(\n serverMeta: ServerMeta,\n tools: Array<Record<string, unknown>>,\n): Record<string, unknown> {\n return {\n server_info: serverMeta.server_info,\n capabilities: serverMeta.capabilities,\n instructions: serverMeta.instructions,\n tools,\n };\n}\n\n/** The as-served delta Baton added on top of the vendor-true surface —\n * mirrors proxy's/Python's `seam_augmentations` so a consumer can render\n * both layers. Always records `instructions_suffix: true`: the SDK's\n * `buildServerInstructions` unconditionally documents the annotation tool\n * whenever `withBaton` runs. */\nexport function buildSeamAugmentations(options: {\n injectedToolNames: string[];\n intentParamNames: string[];\n intentParamMode: \"optional\" | \"required\" | \"off\";\n}): Record<string, unknown> {\n return {\n injected_tools: [...options.injectedToolNames].sort(),\n intent_param:\n options.intentParamMode !== \"off\"\n ? { names: [...options.intentParamNames].sort(), mode: options.intentParamMode }\n : null,\n instructions_suffix: true,\n };\n}\n"],"mappings":";AAEO,IAAM,cAAc;;;ACa3B,SAAS,SAAS;AAClB,SAAS,MAAM,cAAc;AAkBtB,IAAM,6BAA6B,EACvC,OAAO;AAAA,EACN,WAAW,EAAE,OAAO;AAAA,EACpB,QAAQ,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EACpD,aAAa,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EAC/C,eAAe,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EACjD,eAAe,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EACjD,eAAe,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AACnD,CAAC,EACA,OAAO;AAIH,IAAM,2BAA2B,EACrC,OAAO;AAAA,EACN,WAAW,EAAE,OAAO;AAAA,EACpB,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EAC3C,aAAa,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,IAAI;AACv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