@goodtiming/baton-sdk 0.3.3 → 0.3.5

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../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/identity.ts","../src/_text.ts","../src/integrations/mcp/mcpTypes.ts","../src/integrations/mcp/userResolution.ts","../src/integrations/mcp/llmText.ts","../src/integrations/mcp/runtimeAdapter.ts","../src/integrations/mcp/sessionResolution.ts","../src/dsn.ts","../src/integrations/mcp/config.ts","../src/optout.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":["/**\n * Baton SDK — structured signal capture for agent-mediated tool use.\n *\n * TypeScript counterpart to `baton-sdk` (Python) — see that repo's\n * `docs/CHARTER.md` (load-bearing decisions) and `docs/SPEC.md` (the wire\n * protocol) for the canonical spec; this repo has none of its own.\n *\n * `withBaton(server, config)` is the entry point: it instruments a high-level\n * `McpServer` in one call — wrapping tool calls,\n * injecting server instructions and intent params, registering the\n * `<vendor>_annotate` tool, and capturing a `surface_snapshot`. Payloads are\n * PII-scrubbed by the default ruleset before they reach any sink; pass\n * `identityScrub` to opt out.\n *\n * Both majors of the official SDK are supported — 1.x\n * (`@modelcontextprotocol/sdk`) and v2 (`@modelcontextprotocol/server`) — and\n * both are OPTIONAL peerDependencies: install whichever your server is built\n * on. Nothing here imports either package, at runtime or as a type, so the\n * one you do not have is never resolved. `withBaton` takes the structural\n * `SupportedMcpServer` that both classes satisfy.\n *\n * Pre-1.0 — public API not yet stable.\n */\n\nexport { SDK_VERSION } from \"./version.js\";\n\nexport type {\n Event,\n EventType,\n ToolCallStartEvent,\n ToolCallStartPayload,\n ToolCallEndEvent,\n ToolCallEndPayload,\n ToolCallErrorEvent,\n ToolCallErrorPayload,\n AnnotationEvent,\n AnnotationPayload,\n SurfaceSnapshotEvent,\n SurfaceSnapshotPayload,\n} from \"./events.js\";\n\nexport { DEFAULT_CONSENT_TOKEN } from \"./events.js\";\n\nexport {\n EventSchema,\n EventTypeSchema,\n ToolCallStartEventSchema,\n ToolCallStartPayloadSchema,\n ToolCallEndEventSchema,\n ToolCallEndPayloadSchema,\n ToolCallErrorEventSchema,\n ToolCallErrorPayloadSchema,\n AnnotationEventSchema,\n AnnotationPayloadSchema,\n SurfaceSnapshotEventSchema,\n SurfaceSnapshotPayloadSchema,\n} from \"./events.js\";\n\nexport { Scrubber, identityScrub, DEPTH_LIMIT } from \"./scrub.js\";\n\nexport type { Sink, StdoutSinkOptions, HttpSinkOptions } from \"./sinks.js\";\nexport { StdoutSink, HttpSink, safeWrite } from \"./sinks.js\";\n\nexport type { BatonConfig } from \"./integrations/mcp/index.js\";\nexport { withBaton, BatonHandle } from \"./integrations/mcp/index.js\";\n// The only way a consumer can name `withBaton`'s parameter now that neither\n// SDK major's `McpServer` is imported.\nexport type { SupportedMcpServer } from \"./integrations/mcp/index.js\";\n\n// End-user identity. `Principal` and `UserResolutionContext` are what a\n// vendor's `resolveUser` hook signs its function against, so they are part of\n// the public contract the moment the hook is — a vendor cannot write a typed\n// hook without naming them. `hashUserId` is exported for the same reason\n// `Scrubber` is: a vendor recomputing a pseudonym outside the SDK (to join\n// their own records against Console data) must get the identical value, and\n// re-implementing the HMAC message layout by hand is how that silently\n// diverges.\nexport type { Principal, UserIdMode } from \"./identity.js\";\n// ⚠ `HASH_SCHEME` (\"h1\") is deliberately NOT exported. This arm has no\n// attested rung and never emits it, which is the same reason `hashUserId`'s\n// `scheme` is required rather than defaulted — exporting the tag as a named,\n// inviting constant would put the identical zero-row-join trap one door over.\n// It stays defined in `identity.ts` for parity with Python.\nexport { VENDOR_HASH_SCHEME, hashUserId } from \"./identity.js\";\nexport type {\n ResolveUserHook,\n UserResolutionContext,\n} from \"./integrations/mcp/index.js\";\n","// 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.3\";\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/**\n * What the SDK puts in `consent_token` when the vendor names no other value.\n * Byte-for-byte Python's `baton.events.DEFAULT_CONSENT_TOKEN`, and the two\n * must not drift: a collector comparing the field across arms would see two\n * populations where there is one.\n *\n * **The field stays on the wire and the customer stops carrying it.** SPEC\n * §2.3 governs the envelope, not the config, so defaulting here changes\n * nothing a consumer sees — this is the value the onboarding recipe has been\n * minting into `BATON_CONSENT_TOKEN` all along, now stated once instead of\n * threaded through an environment variable that reads to nobody.\n */\nexport const DEFAULT_CONSENT_TOKEN = \"customer-consented\";\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.\n *\n * `call_id` is the minted per-call correlation key: the SAME value on a tool\n * call's `tool_call_start` and its `tool_call_end` / `tool_call_error`, so a\n * worker pairs the two legs on an identifier this producer controls rather\n * than inferring the pairing from session + arrival order. Consumers key\n * SPEC §11.5.4's tier 1 on `(call_id, tool_name)`, not on the id alone —\n * which is why a TS server without it is unreachable from that tier and\n * falls back to the FIFO floor the mint exists to leave.\n *\n * It is an ENVELOPE field, present on all five event types, and null on\n * `annotation` and `surface_snapshot` — SPEC defines a `call_id` for a tool\n * call's legs and putting one on the other two would invent semantics no\n * spec text defines. Null is never an error; it is also what every event\n * emitted before this field existed carries.\n *\n * Minted as a bare opaque UUIDv7 in a local inside the scope that emits both\n * legs — per-call by construction and correct across processes. Never\n * derived from the JSON-RPC request id, which restarts at 1 per connection.\n * It says WHICH CALL, never WHO; the principal is `user_id`. */\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 call_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 /**\n * What this sink shows when something prints it — never the bearer.\n *\n * ⚠ **A sink built from a DSN holds a key the vendor never typed**, and it\n * hangs off `BatonHandle.sink` and off the resolved config, so\n * `console.log(handle.sink)` or a structured logger serialising either one\n * wrote a publishable key into the vendor's logs. Found by the S2 test that\n * asserts the DSN's own string does not survive resolution: it does not, and\n * the key was one field further down. Same treatment as the parsed DSN —\n * `toJSON` for serialisers, the inspect symbol for `console.log`, and\n * `Symbol.for` rather than importing `node:util`, since this package runs on\n * runtimes that have no such module.\n */\n toJSON(): Record<string, unknown> {\n return { url: this.url, apiKey: \"<key>\" };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")](): Record<string, unknown> {\n return this.toJSON();\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 {\n resolveBatonConfig,\n resolveTenantId,\n resolveUserIdHmacKey,\n type BatonConfig,\n} from \"./config.js\";\nimport { captureDisabled, DisabledSink, logDisabled } from \"../../optout.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 { extraEnvelope, extraMeta, type Extra } from \"./mcpTypes.js\";\nimport { ProactiveTracker } from \"./proactiveTracker.js\";\nimport { detectAgentRuntime, UNKNOWN_AGENT_RUNTIME } from \"./runtimeAdapter.js\";\nimport { resolveSessionId } from \"./sessionResolution.js\";\nimport {\n type ResolveUserHook,\n resolveCallUserId,\n warnIfIdentityCannotResolve,\n} from \"./userResolution.js\";\nimport type { UserIdMode } from \"../../identity.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 /** The wrapped MCP server, kept for one read: the `initialize` handshake\n * it cached, which is where every client shipping today declares its name\n * and the only place either peer exposes it. Read lazily per call — the\n * handshake has not happened yet when `withBaton` runs. */\n server: SupportedMcpServer;\n scrubber: (value: unknown) => unknown;\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 /** The vendor's per-request identity resolver, or `undefined`. Resolved\n * ONCE at install and shared by the tool-call and annotation paths — two\n * resolutions could disagree, and an annotation naming a different actor\n * than the call it describes is worse than one naming nobody. */\n resolveUser: ResolveUserHook | undefined;\n userIdMode: UserIdMode;\n userIdHmacKey: string | Uint8Array | undefined;\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 =\n detectAgentRuntime(meta, {\n // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of\n // `_meta`; 1.x leaves them in. Both are handed over — see\n // `mcpTypes.extraEnvelope`.\n envelope: extraEnvelope(extra),\n // Tier 2's carrier: neither peer puts client identity on the\n // handler context, both expose the cached handshake on the server.\n server: ctx.server,\n scrubber: ctx.scrubber,\n }) ?? UNKNOWN_AGENT_RUNTIME;\n const scrubbedMeta = meta ? (ctx.scrubber(meta) as Record<string, unknown>) : null;\n const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);\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 // The per-call correlation key, minted HERE — in the one scope that emits\n // both legs — so start and end carry the same value by construction. It\n // is deliberately NOT part of `common`: `common` is also spread into the\n // proactive annotation below, and SPEC defines no `call_id` for an\n // annotation. Stamped onto the three tool-call events individually.\n const callId = uuidv7();\n\n // Resolved AFTER the intent-param strip, so the hook's `arguments` are\n // exactly what the vendor's own handler receives — Baton's injected\n // params are never a caller's input and must not look like one.\n const userId = await resolveCallUserId(\n ctx.resolveUser,\n { extra, toolName, arguments: params },\n { mode: ctx.userIdMode, tenantId: ctx.tenantId, key: ctx.userIdHmacKey },\n );\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 // The four `...common` sites below are the tool-call legs and the\n // proactive annotation — the same four Python stamps\n // (`middleware.py` 481/524/562/606). `surface_snapshot` is deliberately\n // NOT among them: it describes the SERVER and is captured outside any\n // call, so there is no caller to name (register D5).\n user_id: userId,\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 call_id: callId,\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 call_id: callId,\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 call_id: callId,\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, supplied: BatonConfig = {}): BatonHandle {\n // ⚠ **FIRST — ahead of config resolution, every validation, and every\n // mutation of the vendor's server.** Off means install nothing and never\n // throw, so this cannot sit after a check that raises: a switch that can\n // still abort a vendor's boot is worse than no switch. It also has to\n // precede `resolveBatonConfig`, which would otherwise parse a DSN and\n // construct an `HttpSink` for capture that is not going to happen.\n const disabledBy = captureDisabled();\n if (disabledBy !== null) {\n logDisabled(disabledBy, \"withBaton\");\n return new BatonHandle({\n // A sink the VENDOR constructed is held rather than dropped, so their\n // `handle.aclose()` still releases it — we took ownership of that object\n // the moment they passed it, and the switch does not undo that. Nothing\n // writes to it: nothing is wrapped.\n sink: supplied.sink ?? new DisabledSink(),\n // Empty, and a constant, because when the switch is on nothing was\n // resolved: inventing a session id would put a real identifier on a\n // handle whose whole meaning is that no events exist under it.\n vendorId: \"\",\n sessionId: \"baton-disabled\",\n annotationToolName: \"\",\n });\n }\n\n // Shadowed deliberately: every path below — the tool wrappers, the\n // annotation tool, the surface snapshot — closes over `config`, and one of\n // them reading the caller's raw object would emit its events under a\n // different identity than the rest. `ResolvedBatonConfig`'s required fields\n // are what make that a compile error rather than a review question.\n //\n // The parameter defaults to `{}` so `withBaton(server)` works when\n // `BATON_DSN` is exported — the hosted-vendor shape, and Python's\n // `install_baton(mcp)` with nothing but the environment.\n const config = resolveBatonConfig(supplied);\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 // Deliberately the literal, NOT the ladder — and an earlier comment\n // here justified that by saying no call is in scope, which is false:\n // `maybeEmitSurfaceSnapshot` is the first line of `batonWrap`, so the\n // handshake has happened and tier 2's carrier is live in this closure.\n // The real reason is that the snapshot describes the VENDOR'S SURFACE,\n // which is the same whoever is calling. It is hashed and emitted at\n // most once per process per surface, so the client that happens to\n // trigger it is whichever one called first — attributing the surface to\n // that client would read as a fact about the surface and be an accident\n // of timing. Python hardcodes it from the same in-call position\n // (`_tool_wrap.py`), so this is parity, not a gap.\n //\n // ⚠ Consequence worth knowing: one session emits `surface_snapshot`\n // with `unknown` and everything else with the client's name, so a\n // consumer grouping on `agent_runtime` alone sees two runtimes for one\n // client. Intended; group surfaces on `(tenant_id, vendor_id,\n // surface_hash)`, which is what the Console's table is keyed on.\n agent_runtime: UNKNOWN_AGENT_RUNTIME,\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 server,\n scrubber,\n annotationToolName,\n intentParamMode,\n paramRegistry: new Map(),\n resolveUser: config.resolveUser,\n userIdMode: config.userIdMode ?? \"hashed\",\n userIdHmacKey: resolveUserIdHmacKey(config.userIdHmacKey),\n vendorToolJsonSchema,\n bustSchemaMemo,\n tracker,\n surfaceState,\n emitSurface,\n };\n\n // Install-time, not per-call: all three inputs are resolved above and cannot\n // change for the life of this server. See `warnIfIdentityCannotResolve` for\n // why the silent-success case is the one that needs saying out loud.\n warnIfIdentityCannotResolve(ctx);\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 // Read off `ctx`, never re-resolved from `config`: the two paths must\n // agree on the actor, and `userIdMode`/`userIdHmacKey` each have a\n // default and an env fallback that a second resolution could take\n // differently. Required (not optional) on the options type ON PURPOSE —\n // the compiler then refuses a registration that forgets them, which is\n // the mechanical version of \"wiring two of four call sites\".\n resolveUser: ctx.resolveUser,\n userIdMode: ctx.userIdMode,\n userIdHmacKey: ctx.userIdHmacKey,\n fallbackSessionId: ctx.fallbackSessionId,\n scrubber: ctx.scrubber,\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 { emit } from \"./emit.js\";\nimport { type ResolveUserHook, resolveCallUserId } from \"./userResolution.js\";\nimport type { UserIdMode } from \"../../identity.js\";\nimport { buildAnnotationToolDescription, SIGNAL_TYPES } from \"./llmText.js\";\nimport { extraEnvelope, extraMeta, type Extra } from \"./mcpTypes.js\";\nimport type { SupportedMcpServer } from \"./withBaton.js\";\nimport type { ProactiveTracker } from \"./proactiveTracker.js\";\nimport { detectAgentRuntime, UNKNOWN_AGENT_RUNTIME } 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 scrubber: (value: unknown) => unknown;\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 /** The vendor's identity resolver and its hashing settings — the SAME\n * values the tool-call wrapper holds, resolved once at install. */\n resolveUser?: ResolveUserHook | undefined;\n userIdMode: UserIdMode;\n userIdHmacKey: string | Uint8Array | 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 // Same ladder, same inputs as the tool-call wrapper. Wiring only one\n // of the two would give a single session two runtimes for one client\n // — tool events naming the client, annotations saying `unknown` —\n // which is the split N11 hit by wiring two of its four call sites.\n const runtime =\n detectAgentRuntime(meta, {\n envelope: extraEnvelope(extra),\n server,\n scrubber: options.scrubber,\n }) ?? UNKNOWN_AGENT_RUNTIME;\n const scrubbedMeta = meta ? (options.scrubber(meta) as Record<string, unknown>) : null;\n const sessionId = await resolveSessionId(options.fallbackSessionId, extra);\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 // Same hook, same context factory as the tool wrapper — and the\n // `toolName` handed over is THIS tool's own name, so a hook keyed on it\n // answers per call rather than per install. Wiring one path and not the\n // other would put an annotation and the calls it describes under two\n // different actors, which is unjoinable downstream: the identical split\n // the runtime ladder above already carries a comment about.\n const userId = await resolveCallUserId(\n options.resolveUser,\n { extra, toolName: name, arguments: args },\n {\n mode: options.userIdMode,\n tenantId: options.tenantId,\n key: options.userIdHmacKey,\n },\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 user_id: userId,\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","/** End-user identity — resolve a raw principal, hash it at the edge.\n *\n * The TypeScript half of Python's `baton/identity.py`. Baton attaches an\n * end-user actor (`user_id`) to every event so the Console can answer \"which\n * *customer* hit this\" and group by `(tenant_id, vendor_id, user_id)`.\n *\n * Residency contract: the Console DB is metadata-only and may only ever see\n * the HASH — raw identity must never leave the capture edge. So hashing\n * happens HERE, before an event reaches any console-bound sink.\n *\n * ⚠ **This file and Python's must produce byte-identical digests**, and that\n * is asserted rather than believed: `test/identity.test.ts` runs a corpus\n * GENERATED from Python (`test/identityVectors.json`, regenerated by\n * `scripts/gen_identity_vectors.py`) and compares strings. Same discipline as\n * `scrub.ts` — though NOT its method, which was a hand-mirrored matrix, not a\n * generated corpus — for the same reason: one person reaching two SDKs must be one\n * actor downstream, and nothing but a differential corpus can prove it.\n */\n\nimport { createHmac } from \"node:crypto\";\n\nimport { capCodePoints } from \"./_text.js\";\n\n/** The ATTESTED derivation tag — a principal read off a verified token. */\nexport const HASH_SCHEME = \"h1\";\n\n/** The ASSERTED derivation tag — a principal a vendor's own hook supplied.\n *\n * Deliberately outside the `h*` family: `h2:` is reserved for HMAC key\n * rotation, so a vendor assertion must never be mistakable for an\n * attestation (SPEC §11.4's registered-set rule). */\nexport const VENDOR_HASH_SCHEME = \"v1\";\n\n/** Ceiling on a RAW `user_id`, mirroring Python's `RAW_USER_ID_MAX_LEN`.\n *\n * Raw mode copies vendor-supplied text onto EVERY event of a call — three\n * tool-call legs plus any annotation — so an unbounded value is unbounded\n * several times over. A hook returning a JWT or a concatenated gateway header\n * is the realistic shape, not a hostile one. */\nexport const RAW_USER_ID_MAX_LEN = 128;\n\nexport const USER_ID_MODE_HASHED = \"hashed\";\nexport const USER_ID_MODE_RAW = \"raw\";\nexport type UserIdMode = typeof USER_ID_MODE_HASHED | typeof USER_ID_MODE_RAW;\n\n/** Codepoints Python's `str.strip()` removes, measured against CPython rather\n * than assumed — `\\s` in JavaScript is the WRONG set in BOTH directions.\n *\n * JS `\\s` omits `\\x1c`-`\\x1f` and `\\x85`, which Python strips; and JS `\\s`\n * INCLUDES `U+FEFF`, which Python does not. So a BOM-prefixed subject is\n * trimmed by one language and kept by the other, and that subject\n * subject — the shape a value pasted out of a spreadsheet or read from a\n * BOM'd file arrives in — would hash to two different actors across the two\n * SDKs. `.trim()` is therefore never correct here; the corpus carries that\n * exact vector. */\nconst PYTHON_WHITESPACE = \"\\\\t\\\\n\\\\v\\\\f\\\\r\\\\x1c-\\\\x1f \\\\x85\\\\xa0\\\\u1680\\\\u2000-\\\\u200a\\\\u2028\\\\u2029\\\\u202f\\\\u205f\\\\u3000\";\nconst PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, \"gu\");\n\n/** Matches a string containing an UNPAIRED surrogate.\n *\n * `String.prototype.isWellFormed()` says the same thing more plainly, but it\n * needs `lib: ES2024` and this package declares `ES2022` — a lib bump is a\n * statement about what every consumer must support, which is too broad a\n * change to make for one predicate. Under the `u` flag a valid pair is a\n * single code point and does NOT match, while a lone half does; verified to\n * agree with `isWellFormed()` on both. */\nconst LONE_SURROGATE = /\\p{Surrogate}/u;\n\n/** Pin the principal string once, centrally, so every modality hashes an\n * identical value: NFC-normalize, strip, lowercase — in that order, which is\n * Python's order and is load-bearing (normalizing after stripping can expose\n * new strippable codepoints). */\nfunction canonicalize(rawPrincipal: string): string {\n return rawPrincipal.normalize(\"NFC\").replace(PYTHON_STRIP, \"\").toLowerCase();\n}\n\n/** A raw, UNHASHED end-user principal, as a resolver produced it. */\nexport interface Principal {\n /** The subject — a stable per-person identifier from the vendor's own\n * system. Never an application id: that names the app and is identical for\n * every one of its users, which merges them into one actor. */\n userId: string;\n /** The issuing authority, where one exists (the OIDC `iss`). Folded into\n * the hash because a subject is unique only within the provider that minted\n * it, so two identity providers behind one vendor can hand the same subject\n * to different people. */\n issuer?: string | null | undefined;\n}\n\n/** HMAC-SHA256 a raw principal into a console-safe, per-tenant `user_id`.\n *\n * `tenantId` is folded into the HMAC MESSAGE (not just the key) so the same\n * principal under two tenants can never collide or be cross-tenant-correlated.\n * Returns `\"<scheme>:<hex>\"`.\n *\n * `scheme` tags the DERIVATION and only the tag changes — the digest for a\n * given `(tenantId, principal, issuer)` is identical under every scheme,\n * because the tag is not part of the message. That is deliberate: the same\n * person reached by two provenances is meant to be recognisably the same hex\n * under two tags, not two unrelated values.\n *\n * ⚠ **`issuer` null/undefined MUST hash byte-identically to the pre-issuer\n * form** — the append-only message layout is what guarantees it, and every\n * hash baton-proxy and baton-extmcp have produced since 0.5.0 was issuer-less.\n */\nexport function hashUserId(\n rawPrincipal: string,\n options: {\n tenantId: string;\n key: Uint8Array | string;\n // `| undefined` explicitly, because this repo runs\n // `exactOptionalPropertyTypes`: an optional property there does NOT admit\n // an explicitly-passed `undefined`, and callers forward an absent issuer\n // as one. Both spellings must mean \"no issuer\" or the two arms of that\n // caller hash differently.\n issuer?: string | null | undefined;\n /** ⚠ **REQUIRED, and deliberately NOT defaulted the way Python's is.**\n * Python defaults to `HASH_SCHEME` (`h1:`), which is right there because\n * that arm emits both provenances. This arm emits ONLY `v1:` — it has no\n * attested rung — so an `h1:` default would hand the documented\n * \"recompute the pseudonym to join your own records against Console data\"\n * use a value matching nothing we ever wrote, forever, with an equality\n * join silently returning zero rows. The hex halves are identical under\n * both tags, so it fails in the most confusing way available. Naming the\n * provenance is one word and removes the whole failure. */\n scheme: string;\n },\n): string {\n const { tenantId, key, issuer = null, scheme } = options;\n let message = `${tenantId}\\x00${canonicalize(rawPrincipal)}`;\n // `!== null` alone: the destructure above defaults an explicitly-passed\n // `undefined` to `null`, so only one of the two states survives it. The\n // `| undefined` in the option TYPE stays — that is what\n // `exactOptionalPropertyTypes` needs at the call boundary.\n if (issuer !== null) {\n message += `\\x00${canonicalize(issuer)}`;\n }\n // A string key is UTF-8 encoded, matching Python's env-var path\n // (`BATON_USER_ID_HMAC_KEY` arrives as text and is `.encode()`d there).\n const keyBytes = typeof key === \"string\" ? Buffer.from(key, \"utf8\") : key;\n const digest = createHmac(\"sha256\", keyBytes).update(message, \"utf8\").digest(\"hex\");\n return `${scheme}:${digest}`;\n}\n\n/** Normalize whatever a vendor's hook returned into a usable `Principal`, or\n * `null` if it gave us nothing usable.\n *\n * ⚠ **The shape check is load-bearing, not defensive typing.** TypeScript\n * types vanish at runtime and a hook is vendor code, so a plain string, a\n * dict, or a half-built object is exactly what arrives first — AgentCat's\n * `identify()`, the prior art this is modelled on, returns a bare object. The\n * very next thing that happens to this value is an HMAC over `userId`, so a\n * wrong return is a MISS, never a partially-built principal.\n *\n * ⚠ **An empty or whitespace-only `userId` is REJECTED**, and this is a\n * measured divergence from the prior art rather than a stylistic one: their\n * guard is falsy-only, so `{userId: \"\"}` reaches their wire. An empty\n * principal canonicalizes to `\"\"` and hashes to one stable digest naming\n * nobody — so every such caller merges into a single phantom actor, which is\n * the exact failure this field exists to prevent.\n */\nexport function normalizePrincipal(result: unknown): Principal | null {\n if (result === null || typeof result !== \"object\") return null;\n const candidate = result as { userId?: unknown; issuer?: unknown };\n if (typeof candidate.userId !== \"string\") return null;\n // ⚠ **A lone surrogate MERGES distinct people, so it is a miss.** Node's\n // `update(…, \"utf8\")` does not throw on an unpaired surrogate — it replaces\n // it with U+FFFD — so `\"a\\uD800\"`, `\"a\\uDC00\"` and `\"a\\uFFFD\"` all hash to\n // ONE digest (measured). That is the actor merge this module exists to\n // prevent, arriving through the quietest possible door. Python raises\n // `UnicodeEncodeError` on `.encode()` and drops the field, so refusing here\n // is also what keeps the two arms agreeing: same input, same answer (none).\n // Reachable from a subject sliced out of a JSON payload or a header.\n if (LONE_SURROGATE.test(candidate.userId)) return null;\n // `.strip()`-equivalent, because the canonicalizer strips: a whitespace-only\n // subject is a phantom actor every such caller merges into.\n if (canonicalize(candidate.userId) === \"\") return null;\n\n // ⚠ **This guard is falsy-not-stripped, and that is a KNOWN PAIRED DEFECT\n // carried deliberately rather than fixed here.** Python's\n // `identity_adapter.py` uses the same truthiness test, so a whitespace-only\n // issuer passes BOTH and then canonicalizes to `\"\"` — producing a digest\n // distinct from both a null issuer and an empty one, i.e. one person as two\n // actors. Fixing it on this arm alone would split every issuer-bearing hash\n // across the two SDKs, which is a worse bug than the one being fixed. The\n // corpus pins the shared behaviour (`issuer WHITESPACE-ONLY`), so whichever\n // arm is corrected first reddens the other and forces the paired change.\n const issuerRaw = typeof candidate.issuer === \"string\" && candidate.issuer ? candidate.issuer : null;\n // A malformed ISSUER costs the issuer, not the identity — the subject still\n // resolves, which is the difference between a degraded actor and no actor.\n //\n // ⚠ **This DIVERGES from Python and the corpus structurally cannot pin it.**\n // There, `hash_user_id` raises `UnicodeEncodeError` on the issuer and\n // `_finish_principal` drops `user_id` entirely; here the subject still\n // hashes, issuer-less — so the same input yields no field on one arm and a\n // digest on the other, one that collides with the same `sub` from a\n // different IdP. Recorded rather than aligned, because dropping a resolvable\n // identity over a malformed issuer is the worse behaviour. The generated\n // corpus cannot carry this case: Python's generator cannot produce a vector\n // for an input that raises.\n const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;\n return { userId: candidate.userId, issuer };\n}\n\n/** The envelope's `user_id` for one principal, or `null` to omit the field.\n *\n * `raw` mode is UNTAGGED and puts real end-user identity in the collector's\n * database — the vendor's deliberate choice, and why SPEC §11.4 tells a\n * consumer never to treat this field as anonymous.\n *\n * ⚠ **Hashed mode with no key DROPS the field rather than falling back to\n * raw.** The fallback would be a residency breach that looks like success:\n * `user_id` present, populated, and carrying the subject verbatim. Absent is\n * the safe direction — this is additive analytics and never a consent gate.\n */\nexport function userIdForPrincipal(\n principal: Principal,\n options: {\n mode: UserIdMode;\n tenantId: string;\n key?: Uint8Array | string | null | undefined;\n },\n): string | null {\n // `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so an\n // astral subject cut at the boundary ships a LONE SURROGATE — the very thing\n // `normalizePrincipal` refuses on the way IN — and disagrees with Python's\n // `user_id[:128]`, which counts code points.\n if (options.mode === USER_ID_MODE_RAW) {\n return capCodePoints(principal.userId, RAW_USER_ID_MAX_LEN);\n }\n if (options.key === null || options.key === undefined) return null;\n return hashUserId(principal.userId, {\n tenantId: options.tenantId,\n key: options.key,\n issuer: principal.issuer ?? null,\n // Unconditional: this arm has no attested rung, so every principal it\n // hashes is vendor-ASSERTED. A `scheme` option here would be an argument\n // no caller can vary — configurability for a rung the design says is not\n // coming to this SDK.\n scheme: VENDOR_HASH_SCHEME,\n });\n}\n","/** String helpers shared by the capture paths.\n *\n * Small on purpose: this exists so the ONE rule below is written down once.\n */\n\n/** Truncate to `max` CODE POINTS, never splitting a surrogate pair.\n *\n * ⚠ **Cut by code point, not by UTF-16 code unit, and the reason is a\n * downstream crash rather than tidiness.** Python's `value[:max]` counts code\n * points; `String.prototype.slice` counts units, so a value whose boundary\n * falls inside a surrogate pair ships a LONE SURROGATE. That survives\n * `JSON.stringify` (as a `\\udXXX` escape) and `json.loads`, then raises\n * `UnicodeEncodeError` in the first Python consumer that re-encodes it — a\n * capture-side value breaking a reader far from here. Cutting by code point\n * also keeps the two SDKs agreeing on what \"128 characters\" means.\n *\n * Extracted from `runtimeAdapter.clean()`, which had it first and carried this\n * reasoning alone. `identity.userIdForPrincipal` then capped a raw `user_id`\n * with a plain `.slice()` and reintroduced exactly the defect — in a module\n * whose own `normalizePrincipal` REJECTS lone surrogates on the way in. One\n * home, so the next capped field inherits the rule instead of rediscovering\n * it.\n */\nexport function capCodePoints(value: string, max: number): string {\n // Fast path: `[...value]` allocates an array of every code point, and the\n // overwhelming majority of values are already under the cap.\n if (value.length <= max) return value;\n return [...value].slice(0, max).join(\"\");\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 the fields declared below are\n * ever read — three for `_meta`/session, two more for headers.\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 *\n * The SECOND divergence, same shape, measured 2026-09-11: v2 LIFTS every\n * reserved `io.modelcontextprotocol/*` key OUT of the `_meta` a handler sees\n * and re-exposes them under `mcpReq.envelope`. Sending one identical\n * hand-crafted `_meta` to both majors, `io.modelcontextprotocol/clientInfo`\n * arrived in `extra._meta` on sdk 1.30.0 and in `ctx.mcpReq.envelope` on\n * server 2.0.0, whose `_meta` retained only the unreserved\n * `claudecode/toolUseId`. So a reserved key read at the 1.x location alone\n * is a silent `unknown` across the whole v2 major. Use {@link extraEnvelope}.\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 — reserved keys INCLUDED. */\n _meta?: unknown;\n /** v2's `ServerContext.mcpReq` — the in-flight JSON-RPC request.\n * `envelope` holds the reserved `io.modelcontextprotocol/*` keys this\n * major lifts out of `_meta`; absent entirely when the request carried\n * none, which is the common case on a 2025-11-25 connection. */\n mcpReq?: { _meta?: unknown; envelope?: unknown } | undefined;\n /** 1.x: the transport request's headers, as a plain object whose values may\n * be a STRING, an ARRAY of strings (a repeated header line), or undefined. */\n requestInfo?: { headers?: unknown } | undefined;\n /** v2: HTTP transport info. `req` is the transport request and its\n * `headers` is a Web `Headers`.\n *\n * ⚠ **`req` is MEASURED on `@modelcontextprotocol/server` 2.0.0, not\n * declared.** That package's own `.d.ts` types `http` as `{ authInfo? }`\n * only, while the runtime builds\n * `http: { ...ctx.http, req: transportInfo?.request, closeSSE, ... }`. So\n * reading the published type alone says v2 exposes no headers at all, which\n * is what an earlier pass of this work concluded and it was wrong — the type\n * is one layer above the answer. Do not \"correct\" this back on the strength\n * of the `.d.ts`. */\n http?: { req?: { headers?: unknown } | undefined } | undefined;\n}\n\n/** The call's `_meta`, from wherever this SDK major keeps it.\n *\n * ⚠ On v2 this is `_meta` MINUS the reserved keys — see {@link extraEnvelope}\n * for those. It is the right input for the `claudecode/*` heuristic and for\n * `runtime_meta`, and the wrong one for anything `io.modelcontextprotocol/*`. */\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/** The reserved `io.modelcontextprotocol/*` keys v2 lifts out of `_meta`.\n *\n * Null on 1.x, where nothing is lifted and the keys stay in `extraMeta`'s\n * result — so a reader wanting a reserved key must consult BOTH, and finding\n * nothing here is the normal 1.x answer rather than an absent client. */\nexport function extraEnvelope(extra: Extra): Record<string, unknown> | null {\n const envelope = extra.mcpReq?.envelope as Record<string, unknown> | undefined;\n return envelope ?? null;\n}\n\n/** The call's HTTP headers as ONE shape, whichever major delivered them.\n *\n * ⚠ **This exists because the two majors disagree twice over**, and a vendor\n * hook must not have to know which one it is running under:\n *\n * | | where | shape |\n * |---|---|---|\n * | 1.x | `extra.requestInfo.headers` | plain object; a repeated header is an ARRAY |\n * | v2 | `extra.http.req.headers` | Web `Headers`, case-insensitive |\n *\n * Left unnormalized, `headers[\"X-Forwarded-User\"]` returns a string on one\n * major, an array when the header repeats, and `undefined` on the other — and\n * because the SDK peers type this position loosely, nothing warns the vendor.\n * That is register A8 (fixed in the Python SDK 2026-09-13, where one adapter\n * delivered a case-insensitive mapping and the other a lowercased dict) about\n * to happen again in TypeScript, so it is absorbed HERE rather than shipped.\n *\n * Web `Headers` is the normalized shape because it is the platform's own\n * answer to this question: lookups fold case, and repeated values join with\n * `\", \"` by a rule the standard defines — unlike the Python side, where the\n * two upstreams disagree on first-wins vs last-wins and neither joins.\n *\n * Returns `null` when no HTTP request is in flight, which is every stdio call\n * and the normal case. `null` means \"no HTTP request\", never \"the client sent\n * no headers\".\n */\nexport function extraHeaders(extra: Extra): Headers | null {\n const fromV2 = extra.http?.req?.headers as Headers | undefined;\n // Duck-typed rather than `instanceof Headers`. A `Headers` built in another\n // realm — a `vm` context, a framework's fetch shim, a bundled polyfill —\n // fails `instanceof`, and the fallthrough would then return `null`, which\n // this function's contract defines as \"no HTTP request is in flight\". That\n // statement would be FALSE: the hook would see stdio semantics on an\n // authenticated HTTP call and identity would silently disappear.\n if (fromV2 && typeof fromV2.get === \"function\") return fromV2;\n\n const fromV1 = extra.requestInfo?.headers;\n if (fromV1 && typeof fromV1 === \"object\") {\n const headers = new Headers();\n for (const [name, value] of Object.entries(fromV1 as Record<string, unknown>)) {\n // `undefined` is a declared value of 1.x's header record, and passing it\n // to `append` would stringify it into the literal text \"undefined\" —\n // a header that exists and holds a lie, which reads downstream as a\n // client that sent something.\n // An array is a repeated header line. Appending each lets `Headers`\n // apply the platform's join rule rather than inventing one here.\n //\n // Anything that is not a string is SKIPPED rather than coerced. The 1.x\n // type says `string | string[] | undefined`, but this value arrives as\n // `unknown` from a peer we do not control, and `String({})` yields the\n // literal text \"[object Object]\" — a header that exists and holds a\n // lie, which downstream reads as a client that sent something. Refusing\n // to invent a value is the same rule the null-vs-absent distinction on\n // `headers` itself follows.\n for (const item of Array.isArray(value) ? value : [value]) {\n if (typeof item !== \"string\") continue;\n try {\n headers.append(name, item);\n } catch {\n // ⚠ **`Headers.append` REJECTS names and values the 1.x peer will\n // really hand us, and an identity read may not fail a tool call.**\n // `SSEServerTransport` passes Node's `req.headers` through verbatim,\n // and under Node's HTTP/2 compatibility API that object carries the\n // pseudo-headers `:path` / `:method` / `:authority` / `:scheme` —\n // `append(\":path\", …)` throws `TypeError: invalid header name`, and\n // a CR/LF-bearing value from a custom transport throws the same way.\n // Unguarded, that escapes this function, escapes the context builder,\n // and 500s EVERY tool call on an HTTP/2 deployment before the\n // vendor's own handler runs. Skipping the offending header degrades\n // identity for that one header; letting it propagate takes down the\n // server.\n }\n }\n }\n return headers;\n }\n return null;\n}\n","/** `BatonConfig.resolveUser` — the ASSERTED identity provenance.\n *\n * The TypeScript half of Python's `integrations/identity_adapter.py`, built to\n * close register D6: `user_id` has been on this SDK's envelope since 0.3.0 and\n * NOTHING could populate it, so a partition that works on one of two SDKs is\n * not a partition.\n *\n * **Hook only — there is deliberately no attested (`h1:`) rung here yet.**\n * Python reads `claims[\"sub\"]` off a verified access token; TypeScript's\n * `AuthInfo` has no `claims` field at all (it is\n * `{token, clientId, scopes, expiresAt?, resource?, extra?}`), so the nearest\n * carrier is the untyped `extra` bag and nothing specifies that `sub` lives\n * there. Reading it would mean guessing where a subject lives, vendor by\n * vendor — and a wrong guess is how two people end up as one actor. Recorded\n * as a divergence rather than filled with a guess.\n */\n\nimport {\n type Principal,\n type UserIdMode,\n USER_ID_MODE_HASHED,\n normalizePrincipal,\n userIdForPrincipal,\n} from \"../../identity.js\";\nimport { type Extra, extraHeaders, extraMeta } from \"./mcpTypes.js\";\n\n/** What a vendor's `resolveUser` hook is handed.\n *\n * Adapter-neutral BY CONSTRUCTION rather than by convention — the peers' own\n * handler-context objects differ in shape between the two majors, and this\n * type is what makes one hook portable across them. The prior art takes the\n * opposite approach: AgentCat's `identify()` receives the raw per-major object\n * behind `{ sessionId?: string; [key: string]: any }`, documented as \"only\n * `sessionId` is common to both; everything else is SDK-version-specific\".\n * That is the divergence handed to the vendor as `any`; this is the divergence\n * absorbed by us.\n */\nexport interface UserResolutionContext {\n /** The call's HTTP headers, case-insensitive on BOTH majors — see\n * `extraHeaders` for the two shapes it reconciles.\n *\n * `null` means NO HTTP REQUEST (every stdio call, the common case), never\n * \"the client sent no headers\". The distinction matters: the first is us\n * telling you the question does not apply, the second would be a claim about\n * the caller that we are not in a position to make. */\n headers: Headers | null;\n /** The call's `_meta`, from wherever this major keeps it. */\n meta: Record<string, unknown> | null;\n /** The tool being called — the annotation tool's own name on that path, so a\n * hook can answer differently per call rather than per install. */\n toolName: string;\n /** The call's arguments, AFTER Baton's injected intent params are stripped,\n * so a hook sees exactly what the vendor's own handler will. */\n arguments: Record<string, unknown>;\n}\n\n/** A vendor's per-request identity resolver. Sync or async; returning `null`\n * means \"no opinion about this caller\", which is not an error. */\nexport type ResolveUserHook = (\n context: UserResolutionContext,\n) => Principal | null | Promise<Principal | null>;\n\n/** Build the hook's input from whichever major's context arrived.\n *\n * ⚠ **ONE factory, called by every emit path.** Both consumers (the tool-call\n * wrapper and the annotation tool) go through here rather than each assembling\n * a context, because per-site assembly is exactly how the Python SDK ended up\n * with two adapters delivering different header shapes behind one declared\n * type — and no test could see it, because each path only ever tested itself.\n */\nfunction buildUserResolutionContext(\n extra: Extra,\n toolName: string,\n args: Record<string, unknown>,\n): UserResolutionContext {\n return {\n headers: extraHeaders(extra),\n meta: extraMeta(extra),\n toolName,\n arguments: args,\n };\n}\n\n/** Run a vendor's hook and turn its answer into the envelope's `user_id`.\n *\n * ⚠ **Never throws.** A hook that raises, returns the wrong shape, or returns\n * `null` yields an anonymous call, not a failed one — `user_id` is additive\n * analytics and a vendor's own bug in their resolver may not fail their tool\n * call (SPEC §11.2 fail-open). The prior art converged on the identical rule.\n *\n * ⚠ **No timeout, and that is a DIVERGENCE from Python recorded rather than\n * an omission.** Python runs vendor hooks off the event loop under a 5s\n * budget (`integrations/_hooks.py`); this arm awaits the hook inline. ⚠ An\n * earlier draft justified that by \"matching `resolveSessionId`, the convention\n * already shipped here\" — but `BatonConfig.resolveSessionId` was REMOVED\n * 2026-09-12 and the surviving function takes no vendor callable at all. The\n * real precedent is `scrubber`, the only other vendor code this SDK runs\n * inline; `resolveUser` is the first vendor hook on its per-call path. So the\n * gap is real and deserves its true weight rather than an argument from a\n * convention that no longer exists. A hook that blocks stalls this request.\n * Containment is a separate, larger change on this arm.\n */\n/** Warn ONCE at install when identity is configured but cannot produce a value.\n *\n * ⚠ **The silent-success case is the one that needs a voice.** A vendor sets\n * `resolveUser`, ships, and sees `user_id: null` on every event forever —\n * hashed mode with no key DROPS the field by design, and without this there is\n * no string anywhere in the process to grep for. Python spends a `warned` set\n * threaded through five call sites to say this; here all three inputs are\n * install-resolved constants, so it costs one check at startup and nothing per\n * call.\n *\n * ⚠ **The message must never contain the principal.** Identity was configured\n * and produced nothing, and printing the value to explain that would put raw\n * end-user identity in the vendor's log files — the residency leak one layer\n * sideways. Python's equivalent carries the same warning.\n *\n * `process.emitWarning` because `console` is banned in this package (stdout is\n * the MCP JSON-RPC frame) and this is the channel `optout.ts` and `HttpSink`\n * already use. Guarded like every `process` read here: absent on edge and\n * worker runtimes, where a missing warning channel must not crash startup.\n */\nexport function warnIfIdentityCannotResolve(config: {\n resolveUser?: ResolveUserHook | undefined;\n userIdMode: UserIdMode;\n userIdHmacKey: string | Uint8Array | undefined;\n}): void {\n if (config.resolveUser === undefined) return;\n if (config.userIdMode !== USER_ID_MODE_HASHED) return;\n if (config.userIdHmacKey !== undefined) return;\n if (typeof process === \"undefined\" || typeof process.emitWarning !== \"function\") return;\n process.emitWarning(\n \"baton: resolveUser is configured but no user_id HMAC key is set, so \" +\n \"user_id is dropped from every event (events still emit). Set \" +\n \"BATON_USER_ID_HMAC_KEY or BatonConfig.userIdHmacKey, or pass \" +\n 'userIdMode: \"raw\" if you intend to emit the subject verbatim.',\n );\n}\n\nexport async function resolveCallUserId(\n hook: ResolveUserHook | undefined,\n call: { extra: Extra; toolName: string; arguments: Record<string, unknown> },\n options: {\n mode: UserIdMode;\n tenantId: string;\n key?: Uint8Array | string | null | undefined;\n },\n): Promise<string | null> {\n // ⚠ **The context is built HERE — after the hook check, inside the try —\n // and the signature takes the raw call rather than a built context so a\n // caller CANNOT do it the other way.** Passing a context as an argument\n // meant it was constructed on every tool call of every server that never\n // configured identity, and constructed OUTSIDE this guard, so a throw from\n // the header read escaped into the vendor's tool call. Python states the\n // same rule (`standalone/middleware.py`: \"the context is built only when a\n // hook exists\"), and having it as a convention rather than a shape is how\n // this arm got it wrong.\n if (hook === undefined) return null;\n let result: unknown;\n try {\n const context = buildUserResolutionContext(call.extra, call.toolName, call.arguments);\n result = await hook(context);\n } catch {\n // Broad on purpose, and for the reason the sibling guards are: this calls\n // code a VENDOR wrote, and an identity read may not be able to fail a\n // tool call. Nothing is logged to stdout — that stream is the MCP\n // JSON-RPC frame (AGENTS.md boundary rule 2).\n return null;\n }\n const principal = normalizePrincipal(result);\n if (principal === null) return null;\n try {\n return userIdForPrincipal(principal, {\n mode: options.mode,\n tenantId: options.tenantId,\n key: options.key,\n });\n } catch {\n // The hashing step, which the guard above did NOT cover. `createHmac`\n // rejects a key that is not a string/TypedArray, and a JavaScript vendor\n // — or a TypeScript one whose config came from parsed settings and is\n // typed `any` — reaches this with `userIdHmacKey: 12345`. Install-time\n // validation refuses that now, but this function's docstring promises it\n // cannot raise, and a promise like that needs the guard rather than an\n // argument about who calls it. Python guards the same call for the same\n // reason (`identity_adapter.py:324`).\n return null;\n }\n}\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 * Which agent runtime is calling the vendor's MCP server.\n *\n * A behaviour port of `baton` (Python)'s\n * `integrations/runtime_adapter.py::detect_agent_runtime`, not a\n * transcription of it: the ladder, the precedence argument and the\n * scrub/cap rule are Python's, while two of the three carriers are\n * different objects on this side and were measured before being used.\n *\n * **Prefer what the client DECLARED over what we can infer.** A client\n * names itself in its `initialize` handshake (`clientInfo`), and that is a\n * declaration; the key-prefix heuristic below is an inference drawn from an\n * artifact built for another purpose — `claudecode/toolUseId` is a per-CALL\n * tool-use id, and reading a caller's identity off its namespace prefix\n * works for one vendor by accident of naming and yields nothing for anyone\n * else. That is why Claude Desktop, Cursor and everything else reported\n * `unknown`, on this SDK as on Python's before the ladder landed.\n *\n * ⚠ **A caller cannot assert its own runtime.** This used to read an\n * `_meta.baton.agent_runtime` override; Python removed both spellings (the\n * nested form at B5, the reverse-DNS `io.baton/*` form on 2026-09-09) and\n * so did this module. Two sensors watching one client must not disagree\n * about what it is, and the value here is self-reported — never attested —\n * so an override would let the thing being measured choose its own label.\n *\n * ## The carriers, measured 2026-09-11 on both supported peers\n *\n * Against `@modelcontextprotocol/sdk` 1.30.0 and\n * `@modelcontextprotocol/server` 2.0.0, over real `InMemoryTransport` round\n * trips, reading what a tool handler actually receives.\n *\n * **Tier 1 has two locations, and reading one is a silent `unknown` across\n * a whole major.** One identical hand-crafted `_meta` carrying\n * `io.modelcontextprotocol/clientInfo` arrived in `extra._meta` on 1.x and\n * in `ctx.mcpReq.envelope` on v2 — which lifts every reserved\n * `io.modelcontextprotocol/*` key out of the `_meta` the handler sees. That\n * is the same shape of bug as Python's `clientInfo`/`client_info`, in a\n * different place, and it is why `envelope` is read here at all.\n *\n * **Tier 2 is not on the context.** Python reads\n * `ctx.session.client_params`; neither TS peer puts client identity on the\n * handler's context at all. Both DO expose the cached handshake on the\n * server object, under the same name: `McpServer.server.getClientVersion()`\n * returned the live `{name, version}` in-handler on 1.30.0 and on 2.0.0.\n * So tier 2's carrier is the server `withBaton` already holds, read lazily\n * per call. Duck-typed, never imported — importing either peer's type pins\n * this package to that major.\n *\n * **Tier 1 is not live traffic on these peers, unlike Python's.**\n * `@modelcontextprotocol/client` 2.0.0 negotiates `2025-11-25` by default\n * and sends `clientInfo` in the handshake only, nothing per-request. The\n * Python module's note that fastmcp 4's own `Client` writes the key on\n * every request does NOT transfer. Tier 1 is built anyway: it is free, it\n * is above tier 2 by the same freshest-declaration argument, and it starts\n * working the day a client moves with no further change here.\n */\n\n/**\n * The per-request carrier for the client's declared identity, reserved by\n * MCP 2026-07-28. `@modelcontextprotocol/server` exports this as\n * `CLIENT_INFO_META_KEY`; the literal is written out instead because the\n * 1.x peer exports no such constant and importing v2's would pin a major\n * for a string.\n */\nexport const CLIENT_INFO_META_KEY = \"io.modelcontextprotocol/clientInfo\";\n\n/*\n * ⚠ **Tier 1 is forgeable on 1.x and not on v2, and the module heading above\n * is too absolute about it.** \"A caller cannot assert its own runtime\" is\n * true of the removed `io.baton/*` override and true on a new-spec\n * connection, where the client LIBRARY writes the reserved key and overwrites\n * anything whoever composed the call planted there. It is NOT true on the\n * 1.x peer: measured, a hand-written\n * `_meta[\"io.modelcontextprotocol/clientInfo\"]` arrives verbatim and\n * outranks the handshake — which is exactly what this package's own\n * \"a request-borne declaration outranks the handshake\" test demonstrates.\n * So on a 2025-11-25 connection anything composing the tool call can set\n * `agent_runtime` to any string up to the cap, and change it per request.\n *\n * That is not a hole to close here — the value is self-reported at every\n * tier, which is why `agent_runtime` is never attested and `user_id` is a\n * different field on a different condition. It is a limit to state, because\n * the sentence above reads stronger than the tier delivers.\n */\n\n/**\n * Cap on any name the CLIENT supplied. Both declared tiers read arbitrary\n * client text and copy it onto every event of the call, so an unbounded\n * value reaches every HTTP sink payload too. 128 is far above any real\n * client name (`claude-code` is 11) and far below anything worth shipping.\n *\n * The heuristic's own answer is NOT capped or scrubbed — it is a constant\n * this module owns, and mangling it would be the opposite mistake.\n */\nimport { capCodePoints } from \"../../_text.js\";\n\nexport const CLIENT_NAME_MAX_LEN = 128;\n\n/** What an event reports when no tier answered. A LITERAL, not a knob. */\nexport const UNKNOWN_AGENT_RUNTIME = \"unknown\";\n\n/** What `detectAgentRuntime` needs beyond `_meta`, all optional: omitting\n * any one costs that tier and nothing else. */\nexport interface RuntimeDetectionOptions {\n /** v2's lifted reserved keys (`extraEnvelope`). Null/omitted on 1.x,\n * where the same keys are in `meta` instead. */\n envelope?: Record<string, unknown> | null;\n /** The MCP server object `withBaton` wrapped — tier 2's only carrier on\n * either major. Duck-typed; anything else simply loses the tier. */\n server?: unknown;\n /** The vendor's scrubber, applied to the two CLIENT-SUPPLIED tiers. */\n scrubber?: ((value: unknown) => unknown) | undefined;\n}\n\n/**\n * Scrub and cap a CLIENT-SUPPLIED name, or null if it is unusable.\n *\n * Null rather than a sentinel so an empty or scrubbed-away value falls\n * through to the NEXT tier instead of becoming the reported runtime — a\n * vendor scrubber that redacts a name must lose that tier, not the ladder.\n */\nfunction clean(\n name: unknown,\n scrubber: ((value: unknown) => unknown) | undefined,\n): string | null {\n if (typeof name !== \"string\" || !name) return null;\n let cleaned: string = name;\n if (scrubber) {\n const scrubbed = scrubber(cleaned);\n // A scrubber that redacts by returning null — or anything else that is\n // not a string — loses this TIER; it does not get stringified onto the\n // wire. `String(null)` is `\"null\"`, which is truthy and would ship as\n // the reported runtime on every event of every call; an arbitrary\n // object would ship `\"[object Object]\"`.\n if (typeof scrubbed !== \"string\") return null;\n cleaned = scrubbed;\n }\n if (!cleaned) return null;\n // Code points, not UTF-16 units — `capCodePoints` carries the reasoning,\n // which moved there when a second capped field turned out to need it and\n // reintroduced the defect by slicing.\n return capCodePoints(cleaned, CLIENT_NAME_MAX_LEN);\n}\n\n/** The declared name off the reserved per-request key, wherever this major\n * keeps it. The value is an object with `name`/`version`. */\nfunction declaredOnRequest(\n meta: Record<string, unknown> | null,\n envelope: Record<string, unknown> | null | undefined,\n): unknown {\n for (const source of [envelope, meta]) {\n if (!source) continue;\n const info = source[CLIENT_INFO_META_KEY];\n if (info && typeof info === \"object\") {\n const name = (info as { name?: unknown }).name;\n if (name !== undefined) return name;\n }\n }\n return undefined;\n}\n\n/**\n * The declared name off the server's cached `initialize` handshake.\n *\n * ⚠ **Catches everything, on purpose.** This walks two properties of a\n * third-party object across two majors and seven versions, and they are\n * free to throw whatever they like — a getter that raises outside a live\n * connection is exactly the shape that already escaped into Python's\n * middleware once and failed a vendor's tool call, the one thing SPEC\n * §11.2 says capture may never do. An enumerated catch is a guess about a\n * library; this is a fail-open boundary.\n *\n * ⚠ **Per SERVER INSTANCE, where Python's carrier is per SESSION.**\n * `ctx.session.client_params` is scoped to one session by construction;\n * `getClientVersion()` returns whatever the last `initialize` on THIS object\n * cached. The two agree only while server:session is 1:1, which both peers'\n * documented patterns give (1.x `Protocol.connect` replaces the transport,\n * v2's `createMcpHandler` takes a per-session factory). A vendor wiring one\n * `McpServer` across concurrent sessions would get client A's calls\n * attributed to client B's declared name. Not measured either way — recorded\n * as the honest limit of this carrier rather than implied away.\n */\nfunction declaredOnConnection(options: RuntimeDetectionOptions): unknown {\n try {\n // `options.server` is READ INSIDE the try, never destructured by the\n // caller. Reading a property can itself throw — v2's `McpServer` reaches\n // `.server` through an accessor — and a read hoisted out of here escapes\n // the guard entirely while looking perfectly safe at the call site.\n const server = options.server;\n if (!server) return undefined;\n const inner = (server as { server?: unknown }).server;\n const holder = (inner ?? server) as {\n getClientVersion?: () => { name?: unknown } | undefined;\n };\n if (typeof holder.getClientVersion !== \"function\") return undefined;\n return holder.getClientVersion()?.name;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Return the detected agent runtime, or null if no signal — in which case\n * the caller substitutes {@link UNKNOWN_AGENT_RUNTIME}.\n *\n * Precedence — **declared before inferred**, freshest declaration first.\n * First hit wins:\n *\n * 1. The reserved `io.modelcontextprotocol/clientInfo`, riding the request\n * itself — read from v2's lifted `envelope` and from 1.x's `_meta`.\n * 2. The same declaration from the `initialize` handshake, cached on the\n * server. **This is the tier that does the work today**: every shipping\n * client declares here and nowhere else.\n * 3. Heuristic on key prefixes (`claudecode/*` → `claude-code`). Kept BELOW\n * both declarations rather than dropped: it is proven coverage, and\n * discarding proven coverage needs evidence nobody relies on it.\n * 4. null.\n *\n * **The heuristic is LAST on purpose.** A proxy forwards `_meta` verbatim,\n * so `claudecode/*` means \"this metadata ORIGINATED from Claude Code\", not\n * \"the caller IS Claude Code\" — while `clientInfo` is the client saying\n * what it is. And the heuristic is a one-vendor hardcode: on top it\n * special-cases Claude Code permanently and makes every new client a code\n * change. Where the two agree (Claude Code direct: declares `claude-code`,\n * sends `claudecode/*`) the order is unobservable either way.\n *\n * Tiers 1-2 return CLIENT-SUPPLIED text, so both are scrubbed and capped;\n * tier 3 returns a constant this module owns and is neither. A tier whose\n * value scrubs away to nothing falls through to the next one.\n *\n * ⚠ **Two things this does NOT claim.** The declared name identifies the\n * IMMEDIATE MCP client, which behind a gateway is the gateway rather than\n * the agent. And it is self-asserted, never attested: a client picks its\n * own `clientInfo`. Attested identity is `user_id`, a different field on a\n * different condition; keep the two claims apart.\n */\nexport function detectAgentRuntime(\n meta: Record<string, unknown> | null,\n options: RuntimeDetectionOptions = {},\n): string | null {\n const { envelope, scrubber } = options;\n\n // Tier 1 — declared, on the request.\n const onRequest = clean(declaredOnRequest(meta, envelope), scrubber);\n if (onRequest !== null) return onRequest;\n\n // Tier 2 — declared, on the connection. The tier that answers for every\n // client shipping today, including the ones that were unattributable\n // before it existed. `options` goes in whole, deliberately: see the\n // property-read note in `declaredOnConnection`.\n const onConnection = clean(declaredOnConnection(options), scrubber);\n if (onConnection !== null) return onConnection;\n\n // Tier 3 — inferred, and last: a key prefix says where the METADATA came\n // from, not who the caller is. Only reached when nobody declared anything.\n if (meta) {\n for (const key of Object.keys(meta)) {\n if (key.startsWith(\"claudecode/\")) return \"claude-code\";\n }\n }\n\n return null;\n}\n","import 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. Falls back to the\n * transport-supplied `extra.sessionId`, then the process-wide fallback.\n *\n * ⚠ **Rung 0 — `BatonConfig.resolveSessionId` — was REMOVED 2026-09-12**,\n * mirroring Python. It keyed the session on an identifier the SDK did not\n * mint, which is what retired the `_meta` rungs on the Python side: a\n * vendor's handle differs from a client's only in who supplied it, and the\n * join rule does not draw that line. What a vendor knows about a caller\n * belongs in `user_id`, which `BatonConfig.resolveUser` now populates on this\n * SDK (see `userResolution.ts`). That sentence read \"cannot yet populate at\n * all\" until the hook landed. */\nexport async function resolveSessionId(\n fallbackSessionId: string,\n extra: Extra,\n): Promise<string> {\n if (typeof extra.sessionId === \"string\" && extra.sessionId) return extra.sessionId;\n return fallbackSessionId;\n}\n","/**\n * The packed connection string a wrapped server ships with — parse only.\n *\n * A **DSN** carries the four values an install needs in one string:\n *\n * ```text\n * https://baton_pk_<random>@ingest.goodtiming.ai/ten_<8 hex>/echo-server\n * │ │ │ │ │\n * scheme key (the bearer) authority workspace server\n *\n * dsn = scheme \"://\" key \"@\" authority \"/\" workspace \"/\" server\n * scheme = \"https\" | \"http\"\n * key = \"baton_pk_\" tail ; \"baton_sk_\" warns and still works\n * authority = host [ \":\" port ]\n * workspace = \"ten_\" ( 8(hexdigit) | 32(hexdigit) )\n * server = the vendor_id pattern below\n * ```\n *\n * It replaces five environment variables with one value that can sit inline in\n * a distributable server's source, which is the whole point: a stdio server\n * runs on every user's machine, so a key that cannot ship means events that\n * never arrive.\n *\n * **Nothing here reaches the wire.** The envelope still carries `tenant_id`,\n * `vendor_id` and `consent_token` as separate fields — the SDK unpacks the\n * string and fills them in. This is config ergonomics; ingest, SPEC and the\n * `baton-spec` vectors are untouched.\n *\n * **The path segments are DATA, not a route.** Nobody can `GET` that URL. The\n * ingest origin is scheme + authority and *nothing else*; `HttpSink` appends\n * `/v0/events` itself, exactly as it does for an explicitly-constructed sink.\n * A parser that appends anything here reproduces a double-append this project\n * has already shipped once.\n *\n * Line-for-line port of `baton` (Python)'s `baton/_dsn.py`. The grammar is the\n * contract between the console's mint and both SDKs, so the two parsers are\n * kept the same shape deliberately — including the two deliberate\n * permissivenesses, because a parser STRICTER than the mint is what breaks a\n * customer, while one that is looser only fails to catch a typo the collector\n * will reject readably anyway:\n *\n * - **The key's tail is not length-checked.** The grammar says 43 characters\n * and the mint says so today; that number belongs to the console, and\n * pinning it here means the day the mint changes, every shipped SDK refuses\n * every new key. The prefix carries the meaning — length does not.\n * - **The server segment is checked with `VENDOR_ID_PATTERN`**, the same\n * object `validateBatonConfig` uses, rather than a second regex restating\n * its ceiling. That ceiling has already been costed wrong twice.\n *\n * **Never put a parsed DSN in an error message.** It holds a bearer token, and\n * an exception carrying one lands in stack traces, logs and issue reports.\n * Every throw below goes through `redact`.\n */\n\n/**\n * Vendor IDs become annotation tool name prefixes; same client-pattern as\n * annotation tool names. Rejects dots so the default tool name is valid.\n *\n * It lives HERE rather than in `integrations/mcp/config.ts` — which is where\n * it was defined and where `validateBatonConfig` still applies it — for the\n * same structural reason the Python copy moved: the DSN's server segment IS a\n * vendorId, and a top-level module must not import from `integrations/`. One\n * object, imported both places, so the two rules cannot drift apart the way a\n * copied regex would.\n */\nexport const VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;\n\n// The console mints lowercase, but hex case is not meaningful and refusing an\n// uppercase digit would be a rule stricter than the mint. Matched loosely,\n// passed through VERBATIM — the value is compared as a string server-side, so\n// this parser must never normalise it.\n//\n// **Two lengths.** `new_tenant_id` moved 32 -> 8 hex on 2026-09-12; 32 is the\n// shape it replaced, and every workspace minted before that date still carries\n// it. Both are accepted because a DSN ships inline in a distributable server's\n// source — refusing the old length breaks installs already out there, on an\n// upgrade meant to be safe. It collapses to `{8}` the day no `ten_<32 hex>`\n// workspace exists — a console question, and a CHECK rather than a note,\n// because a note drifts and nobody re-reads a comment to find out it expired:\n//\n// SELECT count(*) FROM tenants WHERE vendor_id ~ '^ten_[0-9a-f]{32}$';\n//\n// Zero means the 32-branch and its tests can go in one commit.\nconst WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;\n\n// A host contains none of these. Character for character `baton`'s\n// `_NOT_IN_A_HOST` (`_dsn.py:345`), because the two parsers answering one\n// question differently is how a DSN that works in Python fails in TypeScript.\n// The control characters ARE the subject here: this class exists to reject\n// them, which is the opposite of the accidental-escape case `no-control-regex`\n// guards against.\n// eslint-disable-next-line no-control-regex\nconst NOT_IN_A_HOST = /[\\\\\\s\\x00-\\x1f\\x7f]/;\n\n// What a BEARER can never carry, measured rather than assumed: `new Headers`\n// rejects exactly NUL, LF and CR, and accepts every other control character\n// and the space. Narrow on purpose — the tail's alphabet belongs to the\n// console's mint, and a parser stricter than the mint refuses valid keys in\n// the field. These three cannot be sent at all, so they are catchable here\n// instead of surfacing as a fetch that throws on every write.\n// eslint-disable-next-line no-control-regex\nconst NOT_IN_A_KEY = /[\\x00\\n\\r]/;\n\nconst PUBLISHABLE_PREFIX = \"baton_pk_\";\nconst SECRET_PREFIX = \"baton_sk_\";\n\n/**\n * A credential-shaped run: a prefix followed by enough tail to BE one.\n *\n * ⚠ **The floor on the tail is what lets this same pattern run over finished\n * sentences.** This module's own help text says \"as in\n * `https://baton_pk_...@host/ten_.../server`\" and its secret-key warning names\n * `baton_sk_` out loud; a pattern matching a bare prefix would eat both and\n * leave the reader with `<key>` where the example belongs. A real key's tail\n * is 43 URL-safe base64 characters — `%` is admitted too, since the tail is\n * deliberately unvalidated and one may contain it — so eight is far below any\n * credential and far above an ellipsis.\n */\nconst KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;\n\nfunction looksLikeAKey(value: string): boolean {\n return (\n value.startsWith(PUBLISHABLE_PREFIX) || value.startsWith(SECRET_PREFIX)\n );\n}\n\n/**\n * Whether a credential is anywhere INSIDE this value, not merely at its start.\n *\n * ⚠ **`startsWith` was the blind spot, and it was load-bearing in two\n * places.** A segment with a key glued to it — `srv-baton_pk_…`, the shape a\n * paste into a half-filled field makes — starts with neither prefix, so it\n * slipped past the key-in-slot refusal that names the slot and past the \"the\n * key is in the PATH\" hint, landing on a pattern-mismatch message that\n * interpolates the segment instead. Expressed through the scan rather than a\n * second regex, so there is ONE notion of \"looks like a credential\" and it\n * cannot drift from the one that redacts.\n */\nfunction containsKey(value: string): boolean {\n return sweep(value) !== value;\n}\n\n// What a bare key gets told. It is the single most likely paste error — the\n// /account page labels the key type \"Publishable key\" and the string you copy\n// \"DSN\" — so it earns a real sentence rather than a parse error.\nconst BARE_KEY_HINT =\n \"this looks like a bare key, not a DSN — copy the full value from \" +\n \"/account, which starts with https:// and ends with your server's name\";\n\n/**\n * Warn on stderr, never stdout: stdout is the JSON-RPC stream under stdio\n * transport, which is exactly the deployment this feature exists for.\n *\n * `process.emitWarning` is this repo's existing convention (`HttpSink`'s\n * buffer overflow), guarded here the way `resolveTenantId` guards its\n * environment read — `process` is absent on edge and worker runtimes, and a\n * missing warning channel must not crash a vendor's server startup.\n */\nfunction warn(message: string): void {\n if (\n typeof process !== \"undefined\" &&\n typeof process.emitWarning === \"function\"\n ) {\n process.emitWarning(message);\n }\n}\n\n/** The four values unpacked from one string. See the module docstring. */\nexport interface Dsn {\n /**\n * Scheme + authority, no path and no trailing slash — what `HttpSink` takes\n * as its base URL and appends `/v0/events` to.\n */\n readonly origin: string;\n /**\n * The workspace segment, `ten_` prefix included and case as minted. The\n * prefix is part of the id, not a marker to strip.\n */\n readonly tenantId: string;\n /**\n * The server segment. This is the server the key is BOUND to: a mismatch\n * between it and the events' `vendor_id` is refused at ingest.\n */\n readonly vendorId: string;\n /**\n * The bearer, whole and unmodified — the auth layer hashes the entire string\n * including its prefix, so nothing here may trim it.\n */\n readonly key: string;\n}\n\ninterface SplitDsn {\n scheme: string;\n netloc: string;\n /** Whether an authority-terminating `/` was present, so `redact` can render\n * the original shape rather than inventing or dropping a separator. */\n slash: string;\n path: string;\n}\n\n/**\n * The ONE split, shared by `redact` and `parseDsn`.\n *\n * ⚠ **Two functions splitting one string two ways is the defect this shape\n * exists to prevent**, and the Python original records it as shipped: its\n * `redact` partitioned on the first `@` while its parser used `rpartition` on\n * the netloc, so a string with two `@`s put the credential on the\n * \"redacted\" side of the split and the safe message carried the whole key.\n *\n * ⚠ **Hand-rolled rather than `new URL()`, and that is a measurement, not a\n * preference.** WHATWG parsing percent-encodes userinfo: `new URL(\n * \"https://a@b@host/…\").username` is `\"a%40b\"`, an ALTERED key — and\n * `decodeURIComponent` cannot round-trip it back, because the parser is\n * deliberately loose about the tail and a tail containing a literal `%` is\n * legal. Python's `rpartition(\"@\")` hands back the key verbatim; the bearer is\n * hashed whole server-side, so a parser that rewrites one byte of it produces\n * a key that matches no row. `new URL` is still used below, but only as a\n * VALIDATOR of the authority, after the credential is already split off.\n */\nfunction splitDsn(raw: string): SplitDsn | null {\n const schemeEnd = raw.indexOf(\"://\");\n if (schemeEnd === -1) return null;\n const scheme = raw.slice(0, schemeEnd).toLowerCase();\n const rest = raw.slice(schemeEnd + 3);\n\n // The authority ends at the first `/`, `?` or `#` — what `urlsplit` does,\n // and skipping the last two would let `https://key@host?a=b/ten_.../srv`\n // parse with a QUERY STRING inside the origin, which `HttpSink` would then\n // append `/v0/events` to.\n const end = rest.search(/[/?#]/);\n if (end === -1) return { scheme, netloc: rest, slash: \"\", path: \"\" };\n\n const netloc = rest.slice(0, end);\n if (rest[end] !== \"/\") {\n // A query or fragment where the path belongs: no segments at all, which is\n // the \"exactly two path segments\" refusal.\n return { scheme, netloc, slash: \"\", path: \"\" };\n }\n const afterSlash = rest.slice(end + 1);\n const pathEnd = afterSlash.search(/[?#]/);\n return {\n scheme,\n netloc,\n slash: \"/\",\n path: pathEnd === -1 ? afterSlash : afterSlash.slice(0, pathEnd),\n };\n}\n\n/** `netloc.rpartition(\"@\")` — the LAST `@`, so a key containing one survives. */\nfunction splitKeyFromAuthority(netloc: string): {\n key: string;\n at: boolean;\n authority: string;\n} {\n const index = netloc.lastIndexOf(\"@\");\n if (index === -1) return { key: \"\", at: false, authority: netloc };\n return {\n key: netloc.slice(0, index),\n at: true,\n authority: netloc.slice(index + 1),\n };\n}\n\n/**\n * A DSN with its credential removed, safe for an error message or a log.\n *\n * Keeps everything that helps someone fix the problem (scheme, host,\n * workspace, server) and drops the one part that must not be repeated. Falls\n * back to a bare marker if the string is too malformed to split, since \"I\n * could not parse it\" must never become \"here is your token\".\n *\n * ⚠ **The PATH is redacted too, and skipping it was the third leak of this\n * kind.** A key pasted into the workspace or server slot is a plausible\n * mistake — the two halves of a DSN look alike to someone copying by eye —\n * and such a string has no `@` at all, so every earlier version of this\n * function reported \"no key\" and then printed the path with the key in it.\n */\nexport function redact(raw: string): string {\n const parts = splitDsn(raw);\n if (parts === null) return \"<dsn>\";\n const { at, authority } = splitKeyFromAuthority(parts.netloc);\n // The path is assembled RAW and swept whole below, rather than elided\n // segment by segment. A per-segment pass is what this function used to do,\n // and it is the shape the leaks kept coming through: it can only cover the\n // slots someone remembered to route through it.\n const assembled = at\n ? `${parts.scheme}://***@${authority}${parts.slash}${parts.path}`\n : `${parts.scheme}://<no key>@${parts.netloc}${parts.slash}${parts.path}`;\n return sweep(assembled);\n}\n\n/**\n * The last line: anything still shaped like a credential is elided, wherever\n * it sits.\n *\n * ⚠ **The fourth leak of this kind, and the one per-slot handling could not\n * see.** The elision ran on PATH segments; a key pasted into the\n * AUTHORITY slot — `https://baton_pk_…` with nothing after it — was\n * interpolated verbatim, so the refusal printed the whole bearer. That case is\n * not exotic, it is the one this parser STEERS people into: a vendor who\n * pastes a bare key is told \"copy the full value from /account, which starts\n * with `https://`\", and the obvious next move is to prepend `https://` to the\n * key already in hand and run it again — putting the credential into the boot\n * log on the retry.\n *\n * So the guarantee stops being a list of slots that each remember to elide,\n * and becomes one scan of the finished string: a slot added later cannot\n * forget. Prefix-anchored, so the host, workspace and server around it stay\n * readable — the whole point of redacting rather than refusing to say\n * anything.\n */\nfunction sweep(message: string): string {\n return message.replace(KEY_RUN, \"<key>\");\n}\n\n/**\n * The only way this module throws, so the scan cannot be skipped.\n *\n * ⚠ **Review found two throws that skipped it, under a docstring already\n * claiming they could not.** The two pattern-mismatch refusals interpolate the\n * offending segment, which was elided by a prefix-anchored check that a\n * glued-on key — `srv-baton_pk_…`, what a paste into a half-filled field makes\n * — walks straight past. The bearer printed in plaintext, in the same sentence\n * as its own redaction.\n *\n * ⚠ **This sweep and `containsKey`'s key-in-slot refusal cover that input\n * jointly, and NEITHER is load-bearing alone** — measured by mutation:\n * removing either one reds no leak test, removing both reds three. That is\n * worth stating rather than leaving to be rediscovered, because it means a\n * reader who deletes one of them sees a green suite and concludes it was dead.\n * They are kept as a pair on purpose, and they answer different questions: the\n * refusal decides which SENTENCE a vendor reads, and is pinned by its own\n * test; this decides what no sentence may contain.\n *\n * The exit is the right home for the second job. A guarantee that lives at the\n * call sites is one the next message added does not know about.\n */\nfunction fail(message: string): never {\n throw new Error(sweep(message));\n}\n\n/** `BATON_DSN`, or undefined — guarded, since `process` is absent on edge and\n * worker runtimes and this module must not crash a server's startup there. */\nfunction dsnFromEnvironment(): string | undefined {\n const fromEnv =\n typeof process !== \"undefined\" ? process.env?.BATON_DSN : undefined;\n // Set-but-empty is how a shell exports a variable it failed to fill.\n // Treating it as a value would raise a parse error naming a string the\n // vendor never wrote.\n return fromEnv ? fromEnv : undefined;\n}\n\n/**\n * Which DSN applies, given what the caller ALSO configured by hand.\n *\n * ⚠ **An environment variable is not something the caller passed, and the\n * first cut of the Python original treated the two as one value.** Folding\n * `BATON_DSN` in before the conflict check meant a vendor who exported it for\n * one server could not install a SECOND server the old explicit way in the\n * same process: the install died accusing them of passing a `dsn` that appears\n * nowhere in their code. It also contradicted the precedence rule this SDK\n * states everywhere else — explicit wins, the environment is the fallback — by\n * letting an ambient value beat an explicit one and then blaming the caller\n * for the collision.\n *\n * So the two sources are separated:\n *\n * - **An explicit DSN beside an explicit `vendorId` / `tenantId` / `sink`\n * still throws.** Both are in the vendor's own source; picking one would be\n * a guess, and a wrong guess routes a server's traffic under someone else's\n * identity.\n * - **An ambient `BATON_DSN` loses to explicit configuration and is\n * ignored**, which is just \"explicit wins\" applied to a value the caller did\n * not write. It still outranks `BATON_TENANT_ID` and friends, which is the\n * re-install case the DSN exists for: environment against environment, the\n * packed one is the one someone chose today.\n * - **Being ignored is announced.** A vendor who exported `BATON_DSN`\n * expecting it to configure this server would otherwise get a healthy\n * install that ships events nowhere near the collector — broken and unbuilt\n * looking alike, at the one boundary where nobody is watching.\n */\nexport function selectDsn(\n explicit: string | undefined,\n supplied: Record<string, boolean>,\n door: string,\n): string | undefined {\n const conflicts = Object.keys(supplied)\n .filter((name) => supplied[name])\n .sort();\n\n // ⚠ **Falsy means unset, matching `dsnFromEnvironment` above and\n // `resolveTenantId`** — `!== undefined` was the first cut and the two rules\n // disagreed. A vendor writing `dsn: process.env.MY_DSN ?? \"\"`, or a config\n // loader that fills unset keys with `\"\"`, got an install that died naming a\n // dsn they never filled and pointed them at the wrong value to delete.\n //\n // ⚠ Python uses `is not None` here and therefore still has that behaviour;\n // this is a deliberate divergence, recorded for the back-port rather than\n // left to be found twice.\n if (explicit) {\n if (conflicts.length > 0) {\n fail(\n `${door} got both a dsn and an explicit ${conflicts[0]} — the dsn ` +\n `already supplies it. Drop one: the dsn is the single value from ` +\n `/account, and ${conflicts[0]} is what it unpacks to.`,\n );\n }\n return explicit;\n }\n\n const ambient = dsnFromEnvironment();\n if (ambient === undefined) return undefined;\n if (conflicts.length > 0) {\n warn(\n `baton: BATON_DSN is set, but this ${door} supplies ${conflicts.join(\", \")} ` +\n `directly, so BATON_DSN is being IGNORED and these events are NOT going ` +\n `to the collector it names. Remove the explicit value to use it, or ` +\n `unset BATON_DSN if it was meant for a different server.`,\n );\n return undefined;\n }\n return ambient;\n}\n\n/**\n * Unpack a DSN, throwing on anything that is not one.\n *\n * Loud at install, which is the behaviour a missing required environment\n * variable already has and the reason the TypeScript recipe grew an `env()`\n * helper: a config value that arrives wrong must fail where the vendor is\n * looking, not at the first tool call in production.\n */\nexport function parseDsn(raw: string): Dsn {\n if (typeof raw !== \"string\" || raw.trim() === \"\") {\n fail(\"dsn must be a non-empty string\");\n }\n\n const dsn = raw.trim();\n\n if (looksLikeAKey(dsn)) {\n // No redact() — a bare key has no structure to show, and echoing it is the\n // thing redact() exists to prevent.\n fail(`dsn is not a URL: ${BARE_KEY_HINT}`);\n }\n\n const safe = redact(dsn);\n const parts = splitDsn(dsn);\n\n if (parts === null || (parts.scheme !== \"https\" && parts.scheme !== \"http\")) {\n fail(\n `dsn ${safe} must start with https:// (or http:// for local ` +\n `development) — ${BARE_KEY_HINT}`,\n );\n }\n\n const { key, at, authority } = splitKeyFromAuthority(parts.netloc);\n if (!at || !key) {\n // The likeliest way to arrive here is not a missing key but a MISPLACED\n // one: the two path segments and the userinfo all look alike to someone\n // copying by eye. Saying which mistake it is costs one scan and saves the\n // reader the guess.\n // A key sitting where the HOST belongs is the retry of the bare-key\n // mistake: that refusal says \"copy the full value, which starts with\n // https://\", so the next thing a vendor tries is their bare key with a\n // scheme in front of it. Landing them on the generic sentence would leave\n // them exactly as stuck as before, having done what they were told.\n if (looksLikeAKey(parts.netloc)) {\n fail(\n `dsn ${safe} is a bare key with a scheme in front of it: ${BARE_KEY_HINT}. ` +\n `The full value also carries a host, your workspace and your server — ` +\n `https://baton_pk_...@host/ten_.../server`,\n );\n }\n const misplaced = parts.path\n .split(\"/\")\n .some((segment) => containsKey(segment));\n const detail = misplaced\n ? \"the key is in the PATH — it goes before an @\"\n : \"the value from /account has the key before an @\";\n fail(\n `dsn ${safe} carries no key: ${detail}, as in https://baton_pk_...@host/ten_.../server`,\n );\n }\n if (NOT_IN_A_KEY.test(key)) {\n // The key is the longest part of a DSN — a 9-character prefix and a\n // 43-character tail out of about a hundred — so it is the likeliest place\n // a line wrap lands, and the host message below would never have mentioned\n // it. `HttpSink` builds `Authorization: Bearer <key>`, which throws inside\n // the sink's bare catch and retries forever.\n fail(\n `dsn ${safe} has a line break or a null inside its key — those can ` +\n `never be sent in an Authorization header, so this DSN could not ` +\n `have worked. Check for a line wrap where the value was copied.`,\n );\n }\n if (key.includes(\":\")) {\n fail(\n `dsn ${safe} has a ':' in its key — a DSN carries one credential and no password field`,\n );\n }\n if (!authority) {\n fail(`dsn ${safe} has no host`);\n }\n\n // ⚠ **The first version of this guard listed `\\t`, `\\n`, `\\r` and called\n // the set CLOSED — \"every other control character makes `new URL` throw\".\n // That was measured in ONE POSITION and generalised.** WHATWG strips those\n // three anywhere, and additionally strips leading and trailing C0 controls\n // AND the space, so `https://key@host.example.com<SP>/ten_…/srv` parsed\n // clean with `pathname` still `/`. The origin then kept the character,\n // `HttpSink` appended `/v0/events` to put it mid-string, and `fetch` threw\n // on every send into `sendWithRetry`'s bare catch — retried, dropped,\n // forever, from an install that raised nothing.\n //\n // So the rule is now a CHARACTER CLASS over the authority, and it is\n // `baton`'s `_NOT_IN_A_HOST` (`_dsn.py:345`) character for character rather\n // than a second guess at the same question. A host contains no whitespace,\n // no control character and no backslash; what a URL parser then does with\n // one does not have to be enumerated.\n // ⚠ **A key in the HOST slot PARSES, and that is worse than printing one.**\n // Ported from `baton` (`_dsn.py:395`), which has had this refusal since its\n // own review found it; this parser went without and the twins diverged on\n // the one question this file says twice they must not diverge on.\n //\n // `https://x@<key>/ten_.../srv` splits on the LAST `@`, so the key lands in\n // the authority and any userinfo at all — one character will do — keeps it\n // out of the no-`@` branch that has the sentence for this. Nothing\n // downstream objects: the segments validate, `origin` becomes\n // `https://baton_pk_...` and rides on the config, and `HttpSink` appends\n // `/v0/events` and hands the result to `fetch` as a HOSTNAME — which puts\n // the bearer in a DNS query and a TLS SNI field on every send, to every\n // resolver in path. The bearer also silently becomes the one-character\n // userinfo, so nothing downstream even authenticates.\n //\n // Checked BEFORE `NOT_IN_A_HOST`, as in Python: a key contains none of those\n // characters, so the order only matters for WHICH sentence a paste error\n // gets, and this one names the mistake.\n if (containsKey(authority)) {\n fail(\n `dsn ${safe} has the KEY where the host belongs. The order is key, ` +\n `@, host — check whether the two are the wrong way round: ` +\n `https://baton_pk_...@host/ten_.../<server>`,\n );\n }\n if (NOT_IN_A_HOST.test(authority)) {\n fail(\n `dsn ${safe} has whitespace, a control character or a backslash inside ` +\n `its host. Those are silently REMOVED or reinterpreted when a URL is ` +\n `parsed, so the address dialled would not be the one you wrote — ` +\n `check for a line wrap or a stray space where the value was copied.`,\n );\n }\n\n // ⚠ **`new URL` is the host validator, and it runs only AFTER the credential\n // is split off.** Node's `ERR_INVALID_URL` carries the string it was handed\n // on `error.input`, so validating the whole DSN would put the bearer into an\n // exception — the single thing this module exists to prevent. Handed the\n // authority alone, the worst that error can hold is a hostname.\n //\n // ⚠ **Nothing from the caught error crosses over — not the object, not\n // `{ cause }`, not its message.** `cause` is the TypeScript twin of Python's\n // `__context__` trap: it survives on the thrown error and is reachable by\n // anything that walks the chain — an error reporter, a structured logger,\n // vitest's own diff. Only the constructor NAME is carried, and it carries no\n // input.\n //\n // Python reaches this check earlier (its `urlsplit` runs before the key\n // checks above), so a string that is BOTH keyless and unparseable gets the\n // \"carries no key\" sentence here and \"not a parseable URL\" there. Both\n // refuse, neither leaks; the order is what the leak-safe placement costs.\n let hostReason: string | null = null;\n let parsedAuthority: URL | null = null;\n try {\n parsedAuthority = new URL(`${parts.scheme}://${authority}`);\n } catch (error) {\n hostReason = error instanceof Error ? error.constructor.name : \"Error\";\n }\n if (parsedAuthority === null) {\n fail(`dsn ${safe} is not a parseable URL (${hostReason ?? \"Error\"})`);\n }\n\n // ⚠ **An assertion on `parsedAuthority.pathname`/`search`/`hash` stood here\n // and has been DELETED.** It was the first answer to the backslash smuggle,\n // and `NOT_IN_A_HOST` above is the second and better one — so it became a\n // guard no input could reach, which mutation testing showed by reddening\n // nothing when removed. Two rules answering for one input is what the\n // character class exists to stop being; the parsed object is still used, as\n // the validator that a host is a host at all.\n\n // ⚠ **A BACKSLASH smuggles a path into the authority, and the validator said\n // yes.** WHATWG folds `\\` to `/` for special schemes, so\n // `new URL(\"https://ingest.example.com\\evil\")` parses happily with host\n // `ingest.example.com` and path `/evil` — while the split above, which ends\n // the authority at `/`, `?` or `#`, keeps the whole thing as the authority.\n // The origin became `https://ingest.example.com\\evil`, `HttpSink` appended\n // `/v0/events`, and `fetch` resolved that to\n // `https://ingest.example.com/evil/v0/events`: a 404 at the first tool call,\n // in production, from an install that raised nothing — the exact failure the\n // \"loud at install\" promise exists to prevent.\n //\n // Asserted on what the URL parser MADE of the authority rather than by\n // adding `\\` to the terminator set, because the question is not which\n // characters WHATWG folds — it is whether anything but a host survived.\n const segments = parts.path.split(\"/\").filter((segment) => segment !== \"\");\n // Destructured with a rest element rather than length-checked, so the two\n // names narrow to `string` from the same test that refuses the wrong count.\n // `segments.length !== 2` would read more directly and `noUncheckedIndexedAccess`\n // cannot see through it — leaving a choice between an assertion that lies\n // the day someone edits the check, and an unreachable branch no test covers.\n const [workspace, server, ...extra] = segments;\n if (workspace === undefined || server === undefined || extra.length > 0) {\n fail(\n `dsn ${safe} must carry exactly two path segments — the workspace and ` +\n `the server, as in /ten_.../<server>. A missing server is never ` +\n `defaulted: it is what the key is bound to.`,\n );\n }\n\n for (const [slot, segment] of [\n [\"workspace\", workspace],\n [\"server\", server],\n ] as const) {\n if (containsKey(segment)) {\n // Checked BEFORE the pattern tests below, which would otherwise\n // interpolate the segment — and a key is far more useful to name by its\n // slot than to print back.\n fail(\n `dsn ${safe} has a KEY in the ${slot} slot. The key goes before the @, ` +\n `and the path carries the workspace and the server: ` +\n `https://baton_pk_...@host/ten_.../<server>`,\n );\n }\n }\n\n if (!WORKSPACE_PATTERN.test(workspace)) {\n fail(\n `dsn ${safe} has ${JSON.stringify(workspace)} where the workspace ` +\n `belongs — expected ten_ followed by 8 or 32 hex characters. If the two ` +\n `path segments are the right way round, this is not a Baton DSN.`,\n );\n }\n if (!VENDOR_ID_PATTERN.test(server)) {\n fail(\n `dsn ${safe} has ${JSON.stringify(server)} where the server belongs ` +\n `— it must match ${VENDOR_ID_PATTERN.source}, because this value becomes ` +\n `the annotation tool name prefix as well as the envelope's vendor_id.`,\n );\n }\n\n if (key.startsWith(SECRET_PREFIX)) {\n // A warning, never a refusal. The KEY ROW is the authority on what a key\n // may do, not its prefix — an SDK enforcing a console policy turns a typo\n // at the mint site into a confusing client-side error. But a secret key\n // inside a server that ships to strangers is worth saying out loud, and\n // this is the only place that can say it. The prefix only — the point is\n // not to repeat the secret.\n warn(\n `baton: this DSN carries a ${SECRET_PREFIX} key (a workspace SECRET) where ` +\n `a ${PUBLISHABLE_PREFIX} key belongs. It will work. But if this server ` +\n `ships to anyone else, that key reads and writes everything the ` +\n `workspace holds — mint a publishable key at /account instead.`,\n );\n }\n\n return sealKey({\n origin: `${parts.scheme}://${authority}`,\n tenantId: workspace,\n vendorId: server,\n key,\n });\n}\n\n/**\n * The parsed DSN, with its bearer kept out of anything that prints the object.\n *\n * `dsn.key` still reads the key — the sink needs it. What changes is the\n * INCIDENTAL paths: `console.log(dsn)`, `util.inspect`, and the\n * `JSON.stringify` inside every structured logger, each of which would\n * otherwise write a publishable key into a vendor's log the moment anyone\n * debugs their install. Python's copy takes the same precaution one field at a\n * time (`field(repr=False)`); a JS object has no repr, so the two hooks that\n * stand in for one are both defined.\n *\n * Both are non-enumerable, so `{...dsn}` and `Object.keys` are unchanged — a\n * spread that silently dropped the bearer would be a far worse trap than the\n * one being closed.\n */\nfunction sealKey(dsn: Dsn): Dsn {\n const shown = {\n origin: dsn.origin,\n tenantId: dsn.tenantId,\n vendorId: dsn.vendorId,\n key: \"<key>\",\n };\n Object.defineProperty(dsn, \"toJSON\", {\n value: () => shown,\n enumerable: false,\n });\n // `Symbol.for`, not an import of `node:util`: this package runs on edge and\n // worker runtimes too, and a registry symbol is inert where nothing reads it.\n Object.defineProperty(dsn, Symbol.for(\"nodejs.util.inspect.custom\"), {\n value: () => shown,\n enumerable: false,\n });\n return dsn;\n}\n","/**\n * `BatonConfig` — vendor-side configuration for `withBaton`. A trimmed\n * mirror of `baton` (Python)'s `integrations/_config.py::VendorConfig`.\n */\n\nimport { parseDsn, selectDsn, VENDOR_ID_PATTERN } from \"../../dsn.js\";\nimport type { ResolveUserHook } from \"./userResolution.js\";\nimport { DEFAULT_CONSENT_TOKEN } from \"../../events.js\";\nimport { HttpSink, 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.\n//\n// Imported from `dsn.ts` rather than defined here, and re-exported so this\n// stays the name the rest of the integration reads: a DSN's server segment IS\n// a vendorId, so the parser applies this very rule, and a second copy of the\n// regex is how the two drift apart. This recipe has already costed that 48\n// wrong twice by writing the number down somewhere else. Python makes the\n// same move, for the same reason.\nexport { VENDOR_ID_PATTERN } from \"../../dsn.js\";\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\"]);\nconst USER_ID_MODES = new Set([\"hashed\", \"raw\"]);\n\nexport interface BatonConfig {\n /** The packed connection string from /account — one value carrying the\n * ingest host, the workspace, the server and the key that binds them.\n *\n * `withBaton(server, { dsn })` is the whole wrap block a DISTRIBUTABLE\n * server ships with, and that is the case it exists for: a stdio server\n * runs on every user's machine, so five `BATON_*` variables are five values\n * that never arrive. Resolved explicit → `BATON_DSN` → unset.\n *\n * **Environment variables do not override it.** A server being re-onboarded\n * has last install's `.env` beside the new inline DSN, and if these values\n * fell through to `BATON_TENANT_ID` the way an unset field does, the stale\n * file would win silently and the events would arrive under the previous\n * server's name.\n *\n * Passing a dsn AND an explicit `vendorId`, `tenantId` or `sink` throws:\n * two sources for one value cannot be reconciled without guessing, and a\n * wrong guess routes a server's traffic under someone else's identity.\n * Everything else — the display name, the scrubber, the injection modes,\n * every identity option — is unaffected; set them alongside a dsn freely. */\n dsn?: string;\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 *\n * Required unless a `dsn` supplies it — the DSN's last path segment IS this\n * value, and it is what the key is BOUND to. */\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 *\n * Defaults to the DSN's server segment VERBATIM when a `dsn` is given and\n * this is not. Verbatim rather than prettified: this string reaches the\n * calling agent, so inventing a capitalisation the vendor never chose would\n * put a fabricated name in front of their users. */\n vendorDisplayName?: string;\n /** End-user consent token attached to every emitted event per SPEC §2.3 —\n * the Console MUST reject events missing it.\n *\n * **Defaulted, so the customer never has to carry it** — see\n * `DEFAULT_CONSENT_TOKEN` for why the field stays on the wire regardless.\n * Passing `\"\"` explicitly still throws: a value the vendor deliberately\n * emptied is a mistake, not a request for the default.\n *\n * ⚠ **No environment variable is read for this, and that is parity rather\n * than a gap.** Python reads `BATON_CONSENT_TOKEN` on its `Client` door\n * only; its `VendorConfig` — the door this package mirrors — takes a plain\n * default, and the `os.environ[\"BATON_CONSENT_TOKEN\"]` in its install\n * examples is the RECIPE passing a value explicitly, not the SDK reading\n * one. Adding the read here would make this arm honour a variable the\n * equivalent Python door ignores. */\n consentToken?: string;\n /** Where events go. Defaults to `new StdoutSink()` — zero-config dev mode. */\n sink?: Sink;\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 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 /** Per-request end-user identity — the ASSERTED provenance behind the\n * envelope's `user_id` (SPEC §11.4 rung 0), tagged `v1:`.\n *\n * Called on every captured tool call and on the annotation tool, with an\n * adapter-neutral {@link UserResolutionContext}: headers folded to ONE\n * case-insensitive shape across both SDK majors, the call's `_meta`, the\n * tool name, and the arguments the vendor's own handler will see. Return a\n * `Principal`, or `null` for \"no opinion about this caller\".\n *\n * **This is the only identity mechanism on this arm.** MCP auth is HTTP\n * middleware, so a stdio server has no token at all; and unlike Python, no\n * attested rung is implemented here — see `userResolution.ts` for why\n * (TypeScript's `AuthInfo` carries no `claims`).\n *\n * Never fails a tool call: a hook that throws or returns junk yields an\n * anonymous call. ⚠ It is awaited INLINE with no timeout — a blocking hook\n * stalls its own request. */\n resolveUser?: ResolveUserHook;\n /** `\"hashed\"` (default) emits a `v1:` per-tenant HMAC pseudonym; `\"raw\"`\n * emits the subject VERBATIM.\n *\n * `\"raw\"` puts real end-user identity in the collector's database and is the\n * vendor's deliberate choice — which is why SPEC §11.4 tells a consumer\n * never to treat this field as anonymous. */\n userIdMode?: \"hashed\" | \"raw\";\n /** The HMAC secret for hashed mode. Resolved explicit →\n * `BATON_USER_ID_HMAC_KEY` → unset.\n *\n * ⚠ **With none set, hashed mode DROPS `user_id` rather than falling back to\n * raw.** The fallback would be a residency breach that looks like success:\n * the field present, populated, and carrying the subject verbatim. */\n userIdHmacKey?: string | Uint8Array;\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 a missing one is\n // a miss, not a crash inside the vendor's server startup. (This said \"this\n // package reads no other environment variable\" until `resolveUserIdHmacKey`\n // below added a second one; `dsn.ts` and `optout.ts` read theirs too.)\n const fromEnv = typeof process !== \"undefined\" ? process.env?.BATON_TENANT_ID : undefined;\n if (fromEnv) return fromEnv;\n return vendorId;\n}\n\n/**\n * The HMAC secret for hashed `user_id`: explicit → `BATON_USER_ID_HMAC_KEY` →\n * unset. Mirrors Python's `_resolve_user_id_hmac_key`.\n *\n * `undefined` is a SUPPORTED state, not an error: it means hashed-mode\n * identity is off and events emit without `user_id`. A string is kept as a\n * string and UTF-8 encoded at the HMAC, which is the same byte sequence\n * Python's env path produces — the env var has always carried text.\n *\n * Resolved ONCE per install, for the same reason `resolveTenantId` is: two\n * resolutions could disagree, and one person would hash two ways within a\n * single server.\n */\nexport function resolveUserIdHmacKey(\n explicit: string | Uint8Array | undefined,\n): string | Uint8Array | undefined {\n if (explicit !== undefined) return explicit;\n // Guarded exactly like the tenant read — `process` is absent on edge and\n // worker runtimes, and a missing one is a miss rather than a crash inside\n // the vendor's server startup.\n const fromEnv =\n typeof process !== \"undefined\" ? process.env?.BATON_USER_ID_HMAC_KEY : undefined;\n return fromEnv ? fromEnv : undefined;\n}\n\n/**\n * A config with everything the DSN can supply already filled in.\n *\n * The three fields are required HERE and optional on `BatonConfig`, so the\n * compiler enforces that `withBaton` reads the resolved value: the wrap paths,\n * the annotation tool and the surface snapshot all close over this object, and\n * one of them reading the caller's raw config would emit events under a\n * different identity than the rest.\n */\nexport interface ResolvedBatonConfig extends BatonConfig {\n vendorId: string;\n vendorDisplayName: string;\n consentToken: string;\n}\n\n/**\n * Fill in whatever the DSN carries, returning a config nothing downstream has\n * to know about. Mirrors Python's `integrations/_config.py::resolve_config`.\n *\n * **Everything a DSN supplies lands at the EXPLICIT tier, above the\n * environment** — see `BatonConfig.dsn` for why that matters more than it\n * sounds. A NEW object is returned rather than the caller's mutated: a vendor\n * may hold one config and hand it to two servers, and an install that rewrote\n * its argument would make the second inherit the first's resolution.\n *\n * ⚠ **The parsed key is NOT kept on the returned config.** It reaches the sink\n * and stops there. Python retains its `dsn` string on the config and pays for\n * it — `repr(VendorConfig)` prints the bearer, which is one of the leaks\n * parked for that repo — and nothing here reads the string after parsing, so\n * this arm simply does not import the problem.\n */\nexport function resolveBatonConfig(config: BatonConfig): ResolvedBatonConfig {\n const dsnString = selectDsn(\n config.dsn,\n {\n // Truthiness per field, mirroring Python's `bool()` / `is not None`\n // split: an empty `vendorId` is an unset one, while an explicitly\n // supplied `tenantId` or `sink` is a conflict whatever it holds.\n vendorId: Boolean(config.vendorId),\n tenantId: config.tenantId !== undefined,\n sink: config.sink !== undefined,\n },\n \"BatonConfig\",\n );\n\n if (dsnString === undefined) {\n const defaulted: BatonConfig = {\n ...config,\n consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN,\n };\n validateBatonConfig(defaulted);\n return defaulted;\n }\n\n const dsn = parseDsn(dsnString);\n // The packed string is DELETED rather than overwritten with `undefined`:\n // `exactOptionalPropertyTypes` refuses the latter, and dropping the property\n // is what is wanted anyway — see the note above about not keeping the\n // bearer on an object that outlives this call.\n const rest: BatonConfig = { ...config };\n delete rest.dsn;\n const identity: BatonConfig = {\n ...rest,\n vendorId: dsn.vendorId,\n tenantId: dsn.tenantId,\n // `??`, for the same reason as `consentToken` directly below, and the\n // inconsistency was worth fixing rather than mirroring: with no dsn,\n // `vendorDisplayName: \"\"` is REFUSED by validation; with one, `||` quietly\n // substituted the server slug. One input, two answers, decided by whether\n // a dsn happens to be present — and this string reaches the calling agent\n // in the server instructions and the annotation tool description, which is\n // the whitelabel obligation the validator cites when it refuses the empty\n // one. ⚠ Python uses `or` here and still has the inconsistency.\n vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,\n // `??`, not `||`: an explicit empty string must survive to the validation\n // below and be REFUSED there, rather than be quietly replaced by the\n // default it was deliberately not left as.\n consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN,\n };\n\n // Validated BEFORE the sink is built. The ordering is parity with Python,\n // where `HttpSink.__init__` eagerly constructs an httpx client that a later\n // validation failure would leave unclosed; this `HttpSink` holds no resource\n // until its first write, so here the order protects nothing and is kept so\n // the two arms cannot answer \"what happens on a bad config\" differently.\n validateBatonConfig(identity);\n\n // `identity` is a ResolvedBatonConfig from here — `validateBatonConfig` is\n // an assertion signature, so the three required fields are proven by the\n // same call that refuses a config missing them, rather than re-asserted with\n // a cast that would go on compiling if a check were ever deleted.\n return {\n ...identity,\n // The origin is scheme + authority; `HttpSink` appends `/v0/events`\n // itself, exactly as it does for an explicitly-constructed sink.\n sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),\n };\n}\n\nexport function validateBatonConfig(config: BatonConfig): asserts config is ResolvedBatonConfig {\n if (!config.vendorId) {\n throw new Error(\n \"BatonConfig needs a vendorId — either directly, or via a dsn whose \" +\n \"last path segment names the server (see /account).\",\n );\n }\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 !== undefined && !config.consentToken) {\n throw new Error(\n \"BatonConfig.consentToken was set to an empty string, and events \" +\n \"without a valid consent_token MUST be rejected by the consumer per \" +\n \"SPEC §2.3. Omit it to take the SDK's default.\",\n );\n }\n if (!config.consentToken) {\n // Reached only by a direct call: `resolveBatonConfig` fills the default in\n // before validating. Kept because this function is exported and asserts\n // the field is present — an assertion signature that can be true while the\n // field is missing is worse than no signature.\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 if (config.resolveUser !== undefined && typeof config.resolveUser !== \"function\") {\n // Refused AT INSTALL rather than at the first call. Unvalidated it would\n // fail inside the hook's own fail-open guard — logged nowhere, identity\n // silently absent for the life of the process, in the one deployment shape\n // (stdio, where no token can exist) that this field is the only mechanism\n // for. Mirrors Python's `resolve_user must be callable`.\n throw new Error(\"BatonConfig.resolveUser must be a function.\");\n }\n if (\n config.userIdHmacKey !== undefined &&\n typeof config.userIdHmacKey !== \"string\" &&\n !(config.userIdHmacKey instanceof Uint8Array)\n ) {\n // The one new field with no install-time check until now, and the shape\n // that reaches it is ordinary: a config built from parsed settings is\n // typed `any`, so `userIdHmacKey: 12345` compiles. Unvalidated, `createHmac`\n // rejects it INSIDE the per-call identity path — once per tool call, for\n // the life of the process. Mirrors Python, which guards this at install\n // AND around the hash itself; both, because a promise that a function\n // cannot raise should not rest on an argument about who calls it.\n throw new Error(\"BatonConfig.userIdHmacKey must be a string or a Uint8Array.\");\n }\n if (config.userIdMode !== undefined && !USER_ID_MODES.has(config.userIdMode)) {\n throw new Error(\n `BatonConfig.userIdMode ${JSON.stringify(config.userIdMode)} must be one of ` +\n `${JSON.stringify([...USER_ID_MODES].sort())}.`,\n );\n }\n}\n","/**\n * The off switch — one environment variable that stops Baton doing anything.\n *\n * `BATON_DISABLED=1`, and deliberately nothing else. Port of Python's\n * `baton/_optout.py`; `DO_NOT_TRACK` was built there and taken back OUT the\n * same day, on a measurement rather than an argument, so it is not here\n * either: **an MCP client does not hand its environment to the server it\n * spawns.** Both SDKs' clients pass a fixed allowlist — `HOME`, `LOGNAME`,\n * `PATH`, `SHELL`, `TERM`, `USER` — and `DO_NOT_TRACK` is not on it, so a\n * global export never reaches a wrapped stdio server, while a user editing\n * their client config's `env` block could have typed `BATON_DISABLED=1` there\n * instead. The cost was concrete where the benefit was not: a contributor with\n * it exported got a silently disabled SDK and 203 failing tests.\n *\n * **Off means INSTALL NOTHING, and it means NEVER THROW.** Not\n * capture-and-discard: no tool wrapping, no annotation tool on the surface, no\n * instructions rewrite, no sink, no buffer. The vendor's server starts and\n * behaves exactly as it would if `withBaton` were not in the file at all. Both\n * halves are load-bearing:\n *\n * - **Nothing on stdout, ever.** A stdio MCP server speaks JSON-RPC on stdout,\n * so a courteous \"Baton is disabled\" line printed there corrupts the stream\n * and breaks the server — in precisely the deployment shape this switch\n * exists for.\n * - **The switch cannot break a server.** Every guard the SDK would otherwise\n * throw from — a config missing its `vendorId`, an unparseable DSN — is\n * skipped along with everything else, because a promise of \"set this and\n * Baton stops\" that can still abort a boot is worse than no switch at all.\n *\n * ⚠ **The consequence of never-throw, recorded rather than argued away:** a\n * vendor whose CI exports `BATON_DISABLED` globally will not learn that their\n * `withBaton` call is malformed, because the call cannot fail while the switch\n * is on. It surfaces the first time capture is enabled.\n *\n * ⚠ **Read at install time, once, and never re-read.** A process that starts\n * with capture on keeps it on: this is a boot-time switch, not a live one. A\n * re-read per event would let a mid-flight environment change split one\n * session's events across two answers.\n *\n * ⚠ **Whose switch this is.** It belongs to whoever RUNS the server. For a\n * distributed stdio server that is the end user, and it works. For a HOSTED\n * server it is the vendor, and the end user has no switch at all — they cannot\n * set an environment variable on someone else's machine. A per-end-user\n * opt-out is the consent token (CHARTER ADR-1) and remains unbuilt, so no\n * vendor-facing wording may imply otherwise.\n */\n\nimport type { Sink } from \"./sinks.js\";\n\nconst SWITCH = \"BATON_DISABLED\";\n\n// ⚠ **Permissive toward the opt-out, on purpose.** The documented form is\n// `=1`, but someone who writes `BATON_DISABLED=true` has said what they want\n// as plainly as someone who writes `1`, and the two failure directions are not\n// symmetric: honouring an unintended opt-out costs some telemetry, while\n// ignoring an intended one collects data from a person who asked us not to.\n// So anything that is not an explicit \"off\" counts as on.\nconst OFF_VALUES = new Set([\"\", \"0\", \"false\", \"no\", \"off\"]);\n\n/**\n * The NAME of the variable switching capture off, or `null`.\n *\n * The name rather than a boolean, so the log line and the disabled handle can\n * say what did it without every entry point repeating the string.\n *\n * The `process` read is guarded, like every other one in this package: it is\n * absent on edge and worker runtimes, and a missing `process` is \"no switch\n * set\", never a crash inside a vendor's server startup.\n */\nexport function captureDisabled(): string | null {\n const value = typeof process !== \"undefined\" ? process.env?.[SWITCH] : undefined;\n if (value !== undefined && !OFF_VALUES.has(value.trim().toLowerCase())) {\n return SWITCH;\n }\n return null;\n}\n\n/**\n * Say so once, on stderr, never on stdout.\n *\n * ⚠ **`process.emitWarning`, because `console` is BANNED in this package** —\n * `no-console` is an eslint error here, the coarse guard against the fatal\n * case: `console.log` writes to stdout, which is the JSON-RPC stream under\n * stdio transport. `console.error` would have been safe and was the first\n * cut, but carving an exception into a repo-wide rule for one line is worse\n * than using the channel the package already speaks on — `HttpSink`'s buffer\n * warning is the same call.\n *\n * ⚠ **Louder than the Python copy, and that is a divergence rather than an\n * oversight.** Python logs this at INFO, which its default handler drops, so a\n * server that configures no logging prints nothing; it argues explicitly\n * against WARNING, on the grounds that a line emitted every process start for\n * a switch somebody set deliberately teaches people to ignore warnings. That\n * argument is about a logger with levels to be quiet at, and this package has\n * none. The alternative was saying nothing at all, which loses the answer for\n * the vendor asking why no events arrive.\n *\n * ⚠ **Not a discoverability guarantee, and it must not be sold as one.** It is\n * for the vendor who goes looking. The answer for one who has not thought to\n * look is vendor-facing documentation, which is a different piece of work.\n */\nexport function logDisabled(switchName: string, surface: string): void {\n // Guarded like every `process` read in this package — absent on edge and\n // worker runtimes, where a missing warning channel must not crash a server's\n // startup. Deliberately NOT shared with `dsn.ts`'s `warn`: that one sweeps\n // credentials out of its message first, and this one has none to sweep.\n if (typeof process !== \"undefined\" && typeof process.emitWarning === \"function\") {\n process.emitWarning(\n `baton: ${switchName} is set, so capture is OFF — ${surface} installed ` +\n `nothing and will emit no events. Unset it to re-enable.`,\n );\n }\n}\n\nexport class DisabledSink implements Sink {\n // The parameter is omitted rather than named-and-ignored: a narrower\n // signature satisfies `Sink` in TypeScript, and there is nothing to do with\n // an event that cannot arrive.\n async write(): Promise<void> {\n return;\n }\n\n async flush(): Promise<void> {\n return;\n }\n\n async aclose(): Promise<void> {\n return;\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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;AAAA,IACX,oBAAoB;AAAA,EACtB,CAAC;AACH;","names":["uuidv7","import_uuid","import_zod","import_zod","zV4","zV3","import_node_crypto","uuidv7","durationMs","wrapper"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/version.ts","../src/events.ts","../src/scrub.ts","../src/sinks.ts","../src/integrations/mcp/withBaton.ts","../src/integrations/mcp/annotation.ts","../src/identity.ts","../src/_text.ts","../src/integrations/mcp/llmText.ts","../src/integrations/mcp/annotationName.ts","../src/integrations/mcp/emit.ts","../src/integrations/mcp/mcpTypes.ts","../src/integrations/mcp/principalResolution.ts","../src/integrations/mcp/runtimeAdapter.ts","../src/integrations/mcp/sessionResolution.ts","../src/dsn.ts","../src/integrations/mcp/config.ts","../src/optout.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":["/**\n * Baton SDK — structured signal capture for agent-mediated tool use.\n *\n * TypeScript counterpart to `baton-sdk` (Python) — see that repo's\n * `docs/CHARTER.md` (load-bearing decisions) and `docs/SPEC.md` (the wire\n * protocol) for the canonical spec; this repo has none of its own.\n *\n * `withBaton(server, config)` is the entry point: it instruments a high-level\n * `McpServer` in one call — wrapping tool calls,\n * injecting server instructions and intent params, registering the\n * `<vendor>_annotate` tool, and capturing a `surface_snapshot`. Payloads are\n * PII-scrubbed by the default ruleset before they reach any sink; pass\n * `identityScrub` to opt out.\n *\n * Both majors of the official SDK are supported — 1.x\n * (`@modelcontextprotocol/sdk`) and v2 (`@modelcontextprotocol/server`) — and\n * both are OPTIONAL peerDependencies: install whichever your server is built\n * on. Nothing here imports either package, at runtime or as a type, so the\n * one you do not have is never resolved. `withBaton` takes the structural\n * `SupportedMcpServer` that both classes satisfy.\n *\n * Pre-1.0 — public API not yet stable.\n */\n\nexport { SDK_VERSION } from \"./version.js\";\n\nexport type {\n Event,\n EventType,\n ToolCallStartEvent,\n ToolCallStartPayload,\n ToolCallEndEvent,\n ToolCallEndPayload,\n ToolCallErrorEvent,\n ToolCallErrorPayload,\n AnnotationEvent,\n AnnotationPayload,\n SurfaceSnapshotEvent,\n SurfaceSnapshotPayload,\n} from \"./events.js\";\n\nexport { DEFAULT_CONSENT_TOKEN } from \"./events.js\";\n\nexport {\n EventSchema,\n EventTypeSchema,\n ToolCallStartEventSchema,\n ToolCallStartPayloadSchema,\n ToolCallEndEventSchema,\n ToolCallEndPayloadSchema,\n ToolCallErrorEventSchema,\n ToolCallErrorPayloadSchema,\n AnnotationEventSchema,\n AnnotationPayloadSchema,\n SurfaceSnapshotEventSchema,\n SurfaceSnapshotPayloadSchema,\n} from \"./events.js\";\n\nexport { Scrubber, identityScrub, DEPTH_LIMIT } from \"./scrub.js\";\n\nexport type { Sink, StdoutSinkOptions, HttpSinkOptions } from \"./sinks.js\";\nexport { StdoutSink, HttpSink, safeWrite } from \"./sinks.js\";\n\nexport type { BatonConfig } from \"./integrations/mcp/index.js\";\nexport { withBaton, BatonHandle } from \"./integrations/mcp/index.js\";\n// The only way a consumer can name `withBaton`'s parameter now that neither\n// SDK major's `McpServer` is imported.\nexport type { SupportedMcpServer } from \"./integrations/mcp/index.js\";\n\n// Principal identity. `Principal` and `PrincipalResolutionContext` are what a\n// vendor's `resolvePrincipal` hook signs its function against, so they are part of\n// the public contract the moment the hook is — a vendor cannot write a typed\n// hook without naming them. `hashPrincipalId` is exported for the same reason\n// `Scrubber` is: a vendor recomputing a pseudonym outside the SDK (to join\n// their own records against Console data) must get the identical value, and\n// re-implementing the HMAC message layout by hand is how that silently\n// diverges.\nexport type { Principal, PrincipalIdMode } from \"./identity.js\";\n// ⚠ `HASH_SCHEME` (\"h1\") is deliberately NOT exported. This arm has no\n// attested rung and never emits it, which is the same reason `hashPrincipalId`'s\n// `scheme` is required rather than defaulted — exporting the tag as a named,\n// inviting constant would put the identical zero-row-join trap one door over.\n// It stays defined in `identity.ts` for parity with Python.\nexport { VENDOR_HASH_SCHEME, hashPrincipalId } from \"./identity.js\";\nexport type {\n ResolvePrincipalHook,\n PrincipalResolutionContext,\n} from \"./integrations/mcp/index.js\";\n","// 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.5\";\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/**\n * What the SDK puts in `consent_token` when the vendor names no other value.\n * Byte-for-byte Python's `baton.events.DEFAULT_CONSENT_TOKEN`, and the two\n * must not drift: a collector comparing the field across arms would see two\n * populations where there is one.\n *\n * **The field stays on the wire and the customer stops carrying it.** SPEC\n * §2.3 governs the envelope, not the config, so defaulting here changes\n * nothing a consumer sees — this is the value the onboarding recipe has been\n * minting into `BATON_CONSENT_TOKEN` all along, now stated once instead of\n * threaded through an environment variable that reads to nobody.\n */\nexport const DEFAULT_CONSENT_TOKEN = \"customer-consented\";\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 * `principalId` is the hashed resolved principal (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.\n *\n * `call_id` is the minted per-call correlation key: the SAME value on a tool\n * call's `tool_call_start` and its `tool_call_end` / `tool_call_error`, so a\n * worker pairs the two legs on an identifier this producer controls rather\n * than inferring the pairing from session + arrival order. Consumers key\n * SPEC §11.5.4's tier 1 on `(call_id, tool_name)`, not on the id alone —\n * which is why a TS server without it is unreachable from that tier and\n * falls back to the FIFO floor the mint exists to leave.\n *\n * It is an ENVELOPE field, present on all five event types, and null on\n * `annotation` and `surface_snapshot` — SPEC defines a `call_id` for a tool\n * call's legs and putting one on the other two would invent semantics no\n * spec text defines. Null is never an error; it is also what every event\n * emitted before this field existed carries.\n *\n * Minted as a bare opaque UUIDv7 in a local inside the scope that emits both\n * legs — per-call by construction and correct across processes. Never\n * derived from the JSON-RPC request id, which restarts at 1 per connection.\n * It says WHICH CALL, never WHO; the principal is `principal_id`. */\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 principal_id: z.string().nullable().default(null),\n call_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 /**\n * What this sink shows when something prints it — never the bearer.\n *\n * ⚠ **A sink built from a DSN holds a key the vendor never typed**, and it\n * hangs off `BatonHandle.sink` and off the resolved config, so\n * `console.log(handle.sink)` or a structured logger serialising either one\n * wrote a publishable key into the vendor's logs. Found by the S2 test that\n * asserts the DSN's own string does not survive resolution: it does not, and\n * the key was one field further down. Same treatment as the parsed DSN —\n * `toJSON` for serialisers, the inspect symbol for `console.log`, and\n * `Symbol.for` rather than importing `node:util`, since this package runs on\n * runtimes that have no such module.\n */\n toJSON(): Record<string, unknown> {\n return { url: this.url, apiKey: \"<key>\" };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")](): Record<string, unknown> {\n return this.toJSON();\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 {\n resolveBatonConfig,\n resolveTenantId,\n resolvePrincipalIdHmacKey,\n type BatonConfig,\n} from \"./config.js\";\nimport { captureDisabled, DisabledSink, logDisabled } from \"../../optout.js\";\nimport { emit } from \"./emit.js\";\nimport { BatonHandle } from \"./handle.js\";\nimport { resolveAnnotationToolName, usableServerName } from \"./annotationName.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 { extraEnvelope, extraMeta, type Extra } from \"./mcpTypes.js\";\nimport { ProactiveTracker } from \"./proactiveTracker.js\";\nimport { detectAgentRuntime, UNKNOWN_AGENT_RUNTIME } from \"./runtimeAdapter.js\";\nimport { resolveSessionId } from \"./sessionResolution.js\";\nimport {\n type ResolvePrincipalHook,\n resolveCallPrincipalId,\n warnIfIdentityCannotResolve,\n} from \"./principalResolution.js\";\nimport type { PrincipalIdMode } from \"../../identity.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 /** The wrapped MCP server, kept for one read: the `initialize` handshake\n * it cached, which is where every client shipping today declares its name\n * and the only place either peer exposes it. Read lazily per call — the\n * handshake has not happened yet when `withBaton` runs. */\n server: SupportedMcpServer;\n scrubber: (value: unknown) => unknown;\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 /** The vendor's per-request identity resolver, or `undefined`. Resolved\n * ONCE at install and shared by the tool-call and annotation paths — two\n * resolutions could disagree, and an annotation naming a different actor\n * than the call it describes is worse than one naming nobody. */\n resolvePrincipal: ResolvePrincipalHook | undefined;\n principalIdMode: PrincipalIdMode;\n principalIdHmacKey: string | Uint8Array | undefined;\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 =\n detectAgentRuntime(meta, {\n // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of\n // `_meta`; 1.x leaves them in. Both are handed over — see\n // `mcpTypes.extraEnvelope`.\n envelope: extraEnvelope(extra),\n // Tier 2's carrier: neither peer puts client identity on the\n // handler context, both expose the cached handshake on the server.\n server: ctx.server,\n scrubber: ctx.scrubber,\n }) ?? UNKNOWN_AGENT_RUNTIME;\n const scrubbedMeta = meta ? (ctx.scrubber(meta) as Record<string, unknown>) : null;\n const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);\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 // The per-call correlation key, minted HERE — in the one scope that emits\n // both legs — so start and end carry the same value by construction. It\n // is deliberately NOT part of `common`: `common` is also spread into the\n // proactive annotation below, and SPEC defines no `call_id` for an\n // annotation. Stamped onto the three tool-call events individually.\n const callId = uuidv7();\n\n // Resolved AFTER the intent-param strip, so the hook's `arguments` are\n // exactly what the vendor's own handler receives — Baton's injected\n // params are never a caller's input and must not look like one.\n const principalId = await resolveCallPrincipalId(\n ctx.resolvePrincipal,\n { extra, toolName, arguments: params },\n { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey },\n );\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 // The four `...common` sites below are the tool-call legs and the\n // proactive annotation — the same four Python stamps\n // (`middleware.py` 481/524/562/606). `surface_snapshot` is deliberately\n // NOT among them: it describes the SERVER and is captured outside any\n // call, so there is no caller to name (register D5).\n principal_id: principalId,\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 call_id: callId,\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 call_id: callId,\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 call_id: callId,\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, supplied: BatonConfig = {}): BatonHandle {\n // ⚠ **FIRST — ahead of config resolution, every validation, and every\n // mutation of the vendor's server.** Off means install nothing and never\n // throw, so this cannot sit after a check that raises: a switch that can\n // still abort a vendor's boot is worse than no switch. It also has to\n // precede `resolveBatonConfig`, which would otherwise parse a DSN and\n // construct an `HttpSink` for capture that is not going to happen.\n const disabledBy = captureDisabled();\n if (disabledBy !== null) {\n logDisabled(disabledBy, \"withBaton\");\n return new BatonHandle({\n // A sink the VENDOR constructed is held rather than dropped, so their\n // `handle.aclose()` still releases it — we took ownership of that object\n // the moment they passed it, and the switch does not undo that. Nothing\n // writes to it: nothing is wrapped.\n sink: supplied.sink ?? new DisabledSink(),\n // Empty, and a constant, because when the switch is on nothing was\n // resolved: inventing a session id would put a real identifier on a\n // handle whose whole meaning is that no events exist under it.\n vendorId: \"\",\n sessionId: \"baton-disabled\",\n annotationToolName: \"\",\n });\n }\n\n // The internals both majors keep off their public `.d.ts`, on 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; _serverInfo?: { name?: unknown } };\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\n // The name the vendor gave this server, read once for both cosmetic labels:\n // the display name (only when a DSN is given) and the annotation tool name.\n // `_serverInfo` is where both majors keep what the constructor was handed;\n // the guards live in `annotationName.ts`.\n const serverName = usableServerName(() => ({\n name: internals.server._serverInfo?.name,\n className: internals.constructor.name,\n }));\n\n // Shadowed deliberately: every path below — the tool wrappers, the\n // annotation tool, the surface snapshot — closes over `config`, and one of\n // them reading the caller's raw object would emit its events under a\n // different identity than the rest. `ResolvedBatonConfig`'s required fields\n // are what make that a compile error rather than a review question.\n //\n // The parameter defaults to `{}` so `withBaton(server)` works when\n // `BATON_DSN` is exported — the hosted-vendor shape, and Python's\n // `install_baton(mcp)` with nothing but the environment.\n const config = resolveBatonConfig(supplied, serverName);\n const sink = config.sink ?? new StdoutSink();\n // Resolved ONCE and threaded to every consumer below: the wrapper's skip of\n // the annotate tool, the instructions, the registration and the handle. With\n // the server's name as an input, two resolutions could register one name\n // while the wrapper skips another and the instructions cite a third.\n const annotationToolName = resolveAnnotationToolName(serverName, config);\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 // Deliberately the literal, NOT the ladder — and an earlier comment\n // here justified that by saying no call is in scope, which is false:\n // `maybeEmitSurfaceSnapshot` is the first line of `batonWrap`, so the\n // handshake has happened and tier 2's carrier is live in this closure.\n // The real reason is that the snapshot describes the VENDOR'S SURFACE,\n // which is the same whoever is calling. It is hashed and emitted at\n // most once per process per surface, so the client that happens to\n // trigger it is whichever one called first — attributing the surface to\n // that client would read as a fact about the surface and be an accident\n // of timing. Python hardcodes it from the same in-call position\n // (`_tool_wrap.py`), so this is parity, not a gap.\n //\n // ⚠ Consequence worth knowing: one session emits `surface_snapshot`\n // with `unknown` and everything else with the client's name, so a\n // consumer grouping on `agent_runtime` alone sees two runtimes for one\n // client. Intended; group surfaces on `(tenant_id, vendor_id,\n // surface_hash)`, which is what the Console's table is keyed on.\n agent_runtime: UNKNOWN_AGENT_RUNTIME,\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 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 server,\n scrubber,\n annotationToolName,\n intentParamMode,\n paramRegistry: new Map(),\n resolvePrincipal: config.resolvePrincipal,\n principalIdMode: config.principalIdMode ?? \"hashed\",\n principalIdHmacKey: resolvePrincipalIdHmacKey(config.principalIdHmacKey),\n vendorToolJsonSchema,\n bustSchemaMemo,\n tracker,\n surfaceState,\n emitSurface,\n };\n\n // Install-time, not per-call: all three inputs are resolved above and cannot\n // change for the life of this server. See `warnIfIdentityCannotResolve` for\n // why the silent-success case is the one that needs saying out loud.\n warnIfIdentityCannotResolve(ctx);\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 // Read off `ctx`, never re-resolved from `config`: the two paths must\n // agree on the actor, and `principalIdMode`/`principalIdHmacKey` each have a\n // default and an env fallback that a second resolution could take\n // differently. Required (not optional) on the options type ON PURPOSE —\n // the compiler then refuses a registration that forgets them, which is\n // the mechanical version of \"wiring two of four call sites\".\n resolvePrincipal: ctx.resolvePrincipal,\n principalIdMode: ctx.principalIdMode,\n principalIdHmacKey: ctx.principalIdHmacKey,\n fallbackSessionId: ctx.fallbackSessionId,\n scrubber: ctx.scrubber,\n // The RESOLVED name, never `config.annotationToolName`: handing over the\n // raw override and letting the registration re-derive would register\n // `srv-..._annotate` while the instructions name the server-derived one.\n 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 (named by `annotationName.ts`: explicit, else the server's own name\n * slugged, else `{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 { deriveAnnotationToolName } from \"./annotationName.js\";\nimport { emit } from \"./emit.js\";\nimport { type ResolvePrincipalHook, resolveCallPrincipalId } from \"./principalResolution.js\";\nimport type { PrincipalIdMode } from \"../../identity.js\";\nimport { buildAnnotationToolDescription, SIGNAL_TYPES } from \"./llmText.js\";\nimport { extraEnvelope, extraMeta, type Extra } from \"./mcpTypes.js\";\nimport type { SupportedMcpServer } from \"./withBaton.js\";\nimport type { ProactiveTracker } from \"./proactiveTracker.js\";\nimport { detectAgentRuntime, UNKNOWN_AGENT_RUNTIME } from \"./runtimeAdapter.js\";\nimport { resolveSessionId } from \"./sessionResolution.js\";\nimport type { SessionCounter } from \"./sessionCounter.js\";\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 interface RegisterAnnotationToolOptions {\n sink: Sink;\n counter: SessionCounter;\n tenantId: string;\n vendorId: string;\n vendorDisplayName: string;\n consentToken: string;\n fallbackSessionId: string;\n scrubber: (value: unknown) => unknown;\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 /** The vendor's identity resolver and its hashing settings — the SAME\n * values the tool-call wrapper holds, resolved once at install. */\n resolvePrincipal?: ResolvePrincipalHook | undefined;\n principalIdMode: PrincipalIdMode;\n principalIdHmacKey: string | Uint8Array | 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 // Same ladder, same inputs as the tool-call wrapper. Wiring only one\n // of the two would give a single session two runtimes for one client\n // — tool events naming the client, annotations saying `unknown` —\n // which is the split N11 hit by wiring two of its four call sites.\n const runtime =\n detectAgentRuntime(meta, {\n envelope: extraEnvelope(extra),\n server,\n scrubber: options.scrubber,\n }) ?? UNKNOWN_AGENT_RUNTIME;\n const scrubbedMeta = meta ? (options.scrubber(meta) as Record<string, unknown>) : null;\n const sessionId = await resolveSessionId(options.fallbackSessionId, extra);\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 // Same hook, same context factory as the tool wrapper — and the\n // `toolName` handed over is THIS tool's own name, so a hook keyed on it\n // answers per call rather than per install. Wiring one path and not the\n // other would put an annotation and the calls it describes under two\n // different actors, which is unjoinable downstream: the identical split\n // the runtime ladder above already carries a comment about.\n const principalId = await resolveCallPrincipalId(\n options.resolvePrincipal,\n { extra, toolName: name, arguments: args },\n {\n mode: options.principalIdMode,\n tenantId: options.tenantId,\n key: options.principalIdHmacKey,\n },\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 principal_id: principalId,\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","/** Principal identity — resolve a raw principal, hash it at the edge.\n *\n * The TypeScript half of Python's `baton/identity.py`. Baton attaches the\n * resolved principal (`principal_id`) to every event so the Console can group\n * by `(tenant_id, vendor_id, principal_id)`, at whatever grain the vendor\n * resolved (SPEC §11.4).\n *\n * Residency contract: the Console DB is metadata-only and may only ever see\n * the HASH — raw identity must never leave the capture edge. So hashing\n * happens HERE, before an event reaches any console-bound sink.\n *\n * ⚠ **This file and Python's must produce byte-identical digests**, and that\n * is asserted rather than believed: `test/identity.test.ts` runs a corpus\n * GENERATED from Python (`test/identityVectors.json`, regenerated by\n * `scripts/gen_identity_vectors.py`) and compares strings. Same discipline as\n * `scrub.ts` — though NOT its method, which was a hand-mirrored matrix, not a\n * generated corpus — for the same reason: one person reaching two SDKs must be one\n * actor downstream, and nothing but a differential corpus can prove it.\n */\n\nimport { createHmac } from \"node:crypto\";\n\nimport { capCodePoints } from \"./_text.js\";\n\n/** The ATTESTED derivation tag — a principal read off a verified token. */\nexport const HASH_SCHEME = \"h1\";\n\n/** The ASSERTED derivation tag — a principal a vendor's own hook supplied.\n *\n * Deliberately outside the `h*` family: `h2:` is reserved for HMAC key\n * rotation, so a vendor assertion must never be mistakable for an\n * attestation (SPEC §11.4's registered-set rule). */\nexport const VENDOR_HASH_SCHEME = \"v1\";\n\n/** Ceiling on a RAW `principal_id`, mirroring Python's `RAW_PRINCIPAL_ID_MAX_LEN`.\n *\n * Raw mode copies vendor-supplied text onto EVERY event of a call — three\n * tool-call legs plus any annotation — so an unbounded value is unbounded\n * several times over. A hook returning a JWT or a concatenated gateway header\n * is the realistic shape, not a hostile one. */\nexport const RAW_PRINCIPAL_ID_MAX_LEN = 128;\n\nexport const PRINCIPAL_ID_MODE_HASHED = \"hashed\";\nexport const PRINCIPAL_ID_MODE_RAW = \"raw\";\nexport type PrincipalIdMode = typeof PRINCIPAL_ID_MODE_HASHED | typeof PRINCIPAL_ID_MODE_RAW;\n\n/** Codepoints Python's `str.strip()` removes, measured against CPython rather\n * than assumed — `\\s` in JavaScript is the WRONG set in BOTH directions.\n *\n * JS `\\s` omits `\\x1c`-`\\x1f` and `\\x85`, which Python strips; and JS `\\s`\n * INCLUDES `U+FEFF`, which Python does not. So a BOM-prefixed subject is\n * trimmed by one language and kept by the other, and that subject\n * subject — the shape a value pasted out of a spreadsheet or read from a\n * BOM'd file arrives in — would hash to two different actors across the two\n * SDKs. `.trim()` is therefore never correct here; the corpus carries that\n * exact vector. */\nconst PYTHON_WHITESPACE = \"\\\\t\\\\n\\\\v\\\\f\\\\r\\\\x1c-\\\\x1f \\\\x85\\\\xa0\\\\u1680\\\\u2000-\\\\u200a\\\\u2028\\\\u2029\\\\u202f\\\\u205f\\\\u3000\";\nconst PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, \"gu\");\n\n/** Matches a string containing an UNPAIRED surrogate.\n *\n * `String.prototype.isWellFormed()` says the same thing more plainly, but it\n * needs `lib: ES2024` and this package declares `ES2022` — a lib bump is a\n * statement about what every consumer must support, which is too broad a\n * change to make for one predicate. Under the `u` flag a valid pair is a\n * single code point and does NOT match, while a lone half does; verified to\n * agree with `isWellFormed()` on both. */\nconst LONE_SURROGATE = /\\p{Surrogate}/u;\n\n/** Pin the principal string once, centrally, so every modality hashes an\n * identical value: NFC-normalize, strip, lowercase — in that order, which is\n * Python's order and is load-bearing (normalizing after stripping can expose\n * new strippable codepoints). */\nfunction canonicalize(rawPrincipal: string): string {\n return pythonStrip(rawPrincipal.normalize(\"NFC\")).toLowerCase();\n}\n\n/** Python's `str.strip()`, over exactly the set above. Exported for the\n * server-name rule in `integrations/mcp/annotationName.ts`, which has to agree\n * with Python's on what counts as a blank name. */\nexport function pythonStrip(value: string): string {\n return value.replace(PYTHON_STRIP, \"\");\n}\n\n/** A raw, UNHASHED principal, as a resolver produced it. */\nexport interface Principal {\n /** The subject — a stable identifier from the vendor's own\n * system. Never an application id: that names the app and is identical for\n * every one of its users, which merges them into one actor. */\n principalId: string;\n /** The issuing authority, where one exists (the OIDC `iss`). Folded into\n * the hash because a subject is unique only within the provider that minted\n * it, so two identity providers behind one vendor can hand the same subject\n * to different people. */\n issuer?: string | null | undefined;\n}\n\n/** HMAC-SHA256 a raw principal into a console-safe, per-tenant `principal_id`.\n *\n * `tenantId` is folded into the HMAC MESSAGE (not just the key) so the same\n * principal under two tenants can never collide or be cross-tenant-correlated.\n * Returns `\"<scheme>:<hex>\"`.\n *\n * `scheme` tags the DERIVATION and only the tag changes — the digest for a\n * given `(tenantId, principal, issuer)` is identical under every scheme,\n * because the tag is not part of the message. That is deliberate: the same\n * person reached by two provenances is meant to be recognisably the same hex\n * under two tags, not two unrelated values.\n *\n * ⚠ **`issuer` null/undefined MUST hash byte-identically to the pre-issuer\n * form** — the append-only message layout is what guarantees it, and every\n * hash baton-proxy and baton-extmcp have produced since 0.5.0 was issuer-less.\n */\nexport function hashPrincipalId(\n rawPrincipal: string,\n options: {\n tenantId: string;\n key: Uint8Array | string;\n // `| undefined` explicitly, because this repo runs\n // `exactOptionalPropertyTypes`: an optional property there does NOT admit\n // an explicitly-passed `undefined`, and callers forward an absent issuer\n // as one. Both spellings must mean \"no issuer\" or the two arms of that\n // caller hash differently.\n issuer?: string | null | undefined;\n /** ⚠ **REQUIRED, and deliberately NOT defaulted the way Python's is.**\n * Python defaults to `HASH_SCHEME` (`h1:`), which is right there because\n * that arm emits both provenances. This arm emits ONLY `v1:` — it has no\n * attested rung — so an `h1:` default would hand the documented\n * \"recompute the pseudonym to join your own records against Console data\"\n * use a value matching nothing we ever wrote, forever, with an equality\n * join silently returning zero rows. The hex halves are identical under\n * both tags, so it fails in the most confusing way available. Naming the\n * provenance is one word and removes the whole failure. */\n scheme: string;\n },\n): string {\n const { tenantId, key, issuer = null, scheme } = options;\n let message = `${tenantId}\\x00${canonicalize(rawPrincipal)}`;\n // `!== null` alone: the destructure above defaults an explicitly-passed\n // `undefined` to `null`, so only one of the two states survives it. The\n // `| undefined` in the option TYPE stays — that is what\n // `exactOptionalPropertyTypes` needs at the call boundary.\n if (issuer !== null) {\n message += `\\x00${canonicalize(issuer)}`;\n }\n // A string key is UTF-8 encoded, matching Python's env-var path\n // (`BATON_PRINCIPAL_ID_HMAC_KEY` arrives as text and is `.encode()`d there).\n const keyBytes = typeof key === \"string\" ? Buffer.from(key, \"utf8\") : key;\n const digest = createHmac(\"sha256\", keyBytes).update(message, \"utf8\").digest(\"hex\");\n return `${scheme}:${digest}`;\n}\n\n/** Normalize whatever a vendor's hook returned into a usable `Principal`, or\n * `null` if it gave us nothing usable.\n *\n * ⚠ **The shape check is load-bearing, not defensive typing.** TypeScript\n * types vanish at runtime and a hook is vendor code, so a plain string, a\n * dict, or a half-built object is exactly what arrives first — AgentCat's\n * `identify()`, the prior art this is modelled on, returns a bare object. The\n * very next thing that happens to this value is an HMAC over `principalId`, so a\n * wrong return is a MISS, never a partially-built principal.\n *\n * ⚠ **An empty or whitespace-only `principalId` is REJECTED**, and this is a\n * measured divergence from the prior art rather than a stylistic one: their\n * guard is falsy-only, so `{principalId: \"\"}` reaches their wire. An empty\n * principal canonicalizes to `\"\"` and hashes to one stable digest naming\n * nobody — so every such caller merges into a single phantom actor, which is\n * the exact failure this field exists to prevent.\n */\nexport function normalizePrincipal(result: unknown): Principal | null {\n if (result === null || typeof result !== \"object\") return null;\n const candidate = result as { principalId?: unknown; issuer?: unknown };\n if (typeof candidate.principalId !== \"string\") return null;\n // ⚠ **A lone surrogate MERGES distinct people, so it is a miss.** Node's\n // `update(…, \"utf8\")` does not throw on an unpaired surrogate — it replaces\n // it with U+FFFD — so `\"a\\uD800\"`, `\"a\\uDC00\"` and `\"a\\uFFFD\"` all hash to\n // ONE digest (measured). That is the actor merge this module exists to\n // prevent, arriving through the quietest possible door. Python raises\n // `UnicodeEncodeError` on `.encode()` and drops the field, so refusing here\n // is also what keeps the two arms agreeing: same input, same answer (none).\n // Reachable from a subject sliced out of a JSON payload or a header.\n if (LONE_SURROGATE.test(candidate.principalId)) return null;\n // `.strip()`-equivalent, because the canonicalizer strips: a whitespace-only\n // subject is a phantom actor every such caller merges into.\n if (canonicalize(candidate.principalId) === \"\") return null;\n\n // ⚠ **This guard is falsy-not-stripped, and that is a KNOWN PAIRED DEFECT\n // carried deliberately rather than fixed here.** Python's\n // `identity_adapter.py` uses the same truthiness test, so a whitespace-only\n // issuer passes BOTH and then canonicalizes to `\"\"` — producing a digest\n // distinct from both a null issuer and an empty one, i.e. one person as two\n // actors. Fixing it on this arm alone would split every issuer-bearing hash\n // across the two SDKs, which is a worse bug than the one being fixed. The\n // corpus pins the shared behaviour (`issuer WHITESPACE-ONLY`), so whichever\n // arm is corrected first reddens the other and forces the paired change.\n const issuerRaw = typeof candidate.issuer === \"string\" && candidate.issuer ? candidate.issuer : null;\n // A malformed ISSUER costs the issuer, not the identity — the subject still\n // resolves, which is the difference between a degraded actor and no actor.\n //\n // ⚠ **This DIVERGES from Python and the corpus structurally cannot pin it.**\n // There, `hash_principal_id` raises `UnicodeEncodeError` on the issuer and\n // `_finish_principal` drops `principal_id` entirely; here the subject still\n // hashes, issuer-less — so the same input yields no field on one arm and a\n // digest on the other, one that collides with the same `sub` from a\n // different IdP. Recorded rather than aligned, because dropping a resolvable\n // identity over a malformed issuer is the worse behaviour. The generated\n // corpus cannot carry this case: Python's generator cannot produce a vector\n // for an input that raises.\n const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;\n return { principalId: candidate.principalId, issuer };\n}\n\n/** The envelope's `principal_id` for one principal, or `null` to omit the field.\n *\n * `raw` mode is UNTAGGED and puts real identity in the collector's\n * database — the vendor's deliberate choice, and why SPEC §11.4 tells a\n * consumer never to treat this field as anonymous.\n *\n * ⚠ **Hashed mode with no key DROPS the field rather than falling back to\n * raw.** The fallback would be a residency breach that looks like success:\n * `principal_id` present, populated, and carrying the subject verbatim. Absent is\n * the safe direction — this is additive analytics and never a consent gate.\n */\nexport function principalIdFor(\n principal: Principal,\n options: {\n mode: PrincipalIdMode;\n tenantId: string;\n key?: Uint8Array | string | null | undefined;\n },\n): string | null {\n // `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so an\n // astral subject cut at the boundary ships a LONE SURROGATE — the very thing\n // `normalizePrincipal` refuses on the way IN — and disagrees with Python's\n // `principal_id[:128]`, which counts code points.\n if (options.mode === PRINCIPAL_ID_MODE_RAW) {\n return capCodePoints(principal.principalId, RAW_PRINCIPAL_ID_MAX_LEN);\n }\n if (options.key === null || options.key === undefined) return null;\n return hashPrincipalId(principal.principalId, {\n tenantId: options.tenantId,\n key: options.key,\n issuer: principal.issuer ?? null,\n // Unconditional: this arm has no attested rung, so every principal it\n // hashes is vendor-ASSERTED. A `scheme` option here would be an argument\n // no caller can vary — configurability for a rung the design says is not\n // coming to this SDK.\n scheme: VENDOR_HASH_SCHEME,\n });\n}\n","/** String helpers shared by the capture paths.\n *\n * Small on purpose: this exists so the ONE rule below is written down once.\n */\n\n/** Truncate to `max` CODE POINTS, never splitting a surrogate pair.\n *\n * ⚠ **Cut by code point, not by UTF-16 code unit, and the reason is a\n * downstream crash rather than tidiness.** Python's `value[:max]` counts code\n * points; `String.prototype.slice` counts units, so a value whose boundary\n * falls inside a surrogate pair ships a LONE SURROGATE. That survives\n * `JSON.stringify` (as a `\\udXXX` escape) and `json.loads`, then raises\n * `UnicodeEncodeError` in the first Python consumer that re-encodes it — a\n * capture-side value breaking a reader far from here. Cutting by code point\n * also keeps the two SDKs agreeing on what \"128 characters\" means.\n *\n * Extracted from `runtimeAdapter.clean()`, which had it first and carried this\n * reasoning alone. `identity.principalIdFor` then capped a raw `principal_id`\n * with a plain `.slice()` and reintroduced exactly the defect — in a module\n * whose own `normalizePrincipal` REJECTS lone surrogates on the way in. One\n * home, so the next capped field inherits the rule instead of rediscovering\n * it.\n */\nexport function capCodePoints(value: string, max: number): string {\n // Fast path: `[...value]` allocates an array of every code point, and the\n // overwhelming majority of values are already under the cap.\n if (value.length <= max) return value;\n return [...value].slice(0, max).join(\"\");\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, as there is no cross-language codegen for prose, and\n * checked: `test/integrations/mcp/llmTextVectors.json` is Python's own\n * rendering, compared string-for-string.\n *\n * **Python's DEFAULT text, `proactive_mode=\"off\"`.** This arm has no\n * `proactiveMode`, so it renders what Python renders when that is unset: the\n * reactive-only head and annotation lead, and no BEFORE clause asking for an\n * annotation ahead of every call. The injected `user_goal`/`expected_result`/\n * `overall_task` params carry intent on every call instead, without the extra\n * turn. ⚠ With `intentParamMode: \"off\"` nothing asks for intent at all.\n * Python refuses that combination at install; this arm has no second mode to\n * refuse it against.\n */\n\nconst SERVER_INSTRUCTIONS_TEMPLATE = (\n vendorDisplayName: string,\n annotationToolName: string,\n) => `This server is wrapped in the ${vendorDisplayName} usage and friction SDK. \\\nUse \\`${annotationToolName}\\` to report when a ${vendorDisplayName} tool \\\ncall goes wrong, or when a tool you needed does not exist, so \\\n${vendorDisplayName} can improve their product. See that tool's \\\ndescription for field-level detail.\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) => `Report a ${vendorDisplayName} tool call that went wrong — call this \\\nAFTER a call returns an unhelpful, empty, failed or contradictory \\\nresult, or when no tool covers what the user asked for. Do NOT call it \\\nbefore a tool call or to narrate normal successful work.\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'. REPEAT the \\\nexact same string on every call serving the same task; change it only \\\nwhen the user starts a different 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\ninterface InstructionNames {\n vendorDisplayName: string;\n annotationToolName: string;\n}\n\nfunction renderServerInstructions(options: InstructionNames): string {\n return SERVER_INSTRUCTIONS_TEMPLATE(options.vendorDisplayName, options.annotationToolName);\n}\n\n/** Would these two names render under the cap? Asked by RENDERING, not by\n * arithmetic, so the answer cannot drift from the template: the interpolation\n * count and the cap both live here, and both have moved before. Used by\n * `annotationName.ts` to keep a name derived from the server only where it\n * fits. */\nexport function fitsInstructionsCap(options: InstructionNames): boolean {\n return renderServerInstructions(options).length <= INSTRUCTIONS_LENGTH_CAP;\n}\n\nexport function buildServerInstructions(options: InstructionNames): string {\n const rendered = renderServerInstructions(options);\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 annotation tool's name and the vendor's display name, both resolved\n * from the server object `withBaton` is handed.\n *\n * `withBaton(server, { dsn })` receives the vendor's `McpServer`, and that\n * object knows its own name. Without it, both defaults come from the DSN's\n * server segment, an opaque `srv-<8 hex>` the console mints: a stranger's walk\n * of the self-serve lane on 2026-09-14 saw a tool called\n * `srv-c8eca135_annotate`, and instructions calling the vendor `srv-c8eca135`,\n * on a server its author had named `toybox-pantry`.\n *\n * The tool-name half is a port of `baton` (Python)'s\n * `integrations/_annotation_name.py` as released in 0.8.3. The display-name\n * half is new in both SDKs together, so the two implement ONE rule. Kept in\n * step by hand.\n *\n * **Cosmetic local labels, never ids.** `vendorId` and `tenantId` stay opaque\n * and console-owned. The tool name does reach the wire in one place,\n * `surface_snapshot.seam_augmentations.injected_tools`, so a consumer matches\n * that list by the `_annotate` suffix, never by an exact name.\n *\n * **Order, and why the display name goes first.** Both names enter the server\n * instructions, whose cap THROWS, so they share one budget. The display name\n * is resolved first, checked beside the tool name the install would otherwise\n * use (the explicit one, or `{vendorId}_annotate`); the tool name is then\n * checked beside the display name that won. Each step keeps a name only if it\n * renders beside the other, so neither can turn a server that booted before\n * this rule into one that throws, and where both derived names do not fit\n * together it is the tool name that gives way. The second check is Python\n * 0.8.3's own (`annotation_tool_name_from_server` already measures against the\n * resolved display name), so this order leaves that code as it is.\n *\n * ⚠ **Nothing here throws, except on a tool name the vendor passed\n * explicitly.** Both labels are cosmetic and a vendor's boot is not, so every\n * path that cannot produce a name returns `undefined` and the caller falls\n * back.\n */\n\nimport { pythonStrip } from \"../../identity.js\";\nimport { fitsInstructionsCap } from \"./llmText.js\";\n\n/** The strictest known client pattern (Claude Desktop): dots, slashes and\n * other separators are rejected. One copy, for the explicit name and the\n * derived one alike. */\nexport const TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;\n\nconst SUFFIX = \"_annotate\";\n\n/** Cap on the SLUG, and the binding constraint is not the pattern's 64: the\n * tool name shares the instructions budget with the display name, so a longer\n * one buys a shorter legal display name. Python's number, kept identical. The\n * cap is not the safety property; `fitsInstructionsCap` is. */\nexport const SLUG_CAP = 30;\n\n/** What a library calls a server nobody named. These two are Python's: its\n * official SDK defaults to `\"FastMCP\"` on mcp 1.x and `\"mcp-server\"` on 2.x.\n *\n * Neither TypeScript peer adds one. Both `McpServer` constructors store the\n * `serverInfo` they are handed with no default, and both type it as a\n * required `Implementation` (measured on `@modelcontextprotocol/sdk` 1.30.0\n * and `@modelcontextprotocol/server` 2.0.0). The Python strings stay here\n * anyway: this is one rule across both SDKs, and a TypeScript server called\n * `FastMCP` carries a name copied from somewhere, not one its vendor chose. */\nconst PLACEHOLDER_LITERALS = new Set([\"fastmcp\", \"mcp-server\"]);\n\n/** fastmcp's default is `${ClassName}-${4 hex}`, minted per construction, so a\n * name derived from it would change on every restart. Matched against the\n * server's OWN class name rather than a bare trailing `-[0-9a-f]{4}`, because\n * hex spells words: `toybox-cafe` is a real name. */\nconst RANDOM_SUFFIX = /-[0-9a-f]{4}$/;\n\nfunction isLibraryPlaceholder(serverName: string, className: string): boolean {\n const stripped = pythonStrip(serverName);\n if (PLACEHOLDER_LITERALS.has(stripped.toLowerCase())) return true;\n const stem = stripped.replace(RANDOM_SUFFIX, \"\");\n return stem !== stripped && stem === className;\n}\n\n/** `process.emitWarning`, guarded like every `process` read in this package:\n * `console` is banned (stdout is the MCP JSON-RPC frame under stdio), and edge\n * runtimes have no `process` at all. */\nexport function warn(message: string): void {\n if (typeof process !== \"undefined\" && typeof process.emitWarning === \"function\") {\n process.emitWarning(message);\n }\n}\n\n/**\n * The name the vendor gave their server, or `undefined` when there is none to\n * use: a read that throws, a value that is not a string, a blank one, or a\n * name a library made up.\n *\n * Takes a reader rather than the server, so the private-field access stays in\n * `withBaton.ts` on its named internals shape, beside the other reach-ins. The\n * reader runs inside the guard because it touches the vendor's object.\n *\n * Blank is refused although Python's rule does not name it: `validateBatonConfig`\n * refuses a blank display name, and a cosmetic default may not be the thing\n * that stops a server from starting.\n */\nexport function usableServerName(\n read: () => { name: unknown; className: unknown },\n): string | undefined {\n let name: unknown;\n let className: unknown;\n try {\n ({ name, className } = read());\n } catch {\n warn(\n \"baton: reading the server name failed; using the DSN's server segment \" +\n \"and {vendorId}_annotate instead.\",\n );\n return undefined;\n }\n if (typeof name !== \"string\" || pythonStrip(name) === \"\") return undefined;\n if (isLibraryPlaceholder(name, typeof className === \"string\" ? className : \"\")) {\n return undefined;\n }\n return name;\n}\n\n/** Slug a server name for use as a tool-name stem, or `undefined` if nothing\n * is left. Python's transform exactly: strip, lowercase, every character\n * outside `[a-z0-9-]` to a hyphen, collapse, strip hyphens, cap. */\nexport function slugServerName(serverName: string): string | undefined {\n const mapped = pythonStrip(serverName).toLowerCase().replace(/[^a-z0-9-]/gu, \"-\");\n const collapsed = mapped.replace(/-+/g, \"-\").replace(/^-+|-+$/g, \"\");\n // Cut BEFORE the final strip: slicing can leave a trailing hyphen, which\n // reads as a truncation artefact.\n return collapsed.slice(0, SLUG_CAP).replace(/^-+|-+$/g, \"\") || undefined;\n}\n\n/**\n * The display name from the server's own name, VERBATIM, or `undefined`.\n *\n * Not slugged: it is a string the vendor chose, and it reaches their users.\n * Rendered beside the tool name this install would use if nothing were\n * derived, so a name that does not fit leaves the DSN segment in place rather\n * than making the install throw.\n */\nexport function displayNameFromServer(\n serverName: string | undefined,\n tool: { vendorId: string; annotationToolName?: string | undefined },\n): string | undefined {\n if (serverName === undefined) return undefined;\n const fallbackToolName = tool.annotationToolName || `${tool.vendorId}${SUFFIX}`;\n if (!fitsInstructionsCap({ vendorDisplayName: serverName, annotationToolName: fallbackToolName })) {\n warn(\n `baton: the server name (${serverName.length} chars) does not fit the ` +\n \"server-instructions budget as the display name; keeping the DSN's \" +\n \"server segment. Pass vendorDisplayName to choose a shorter one.\",\n );\n return undefined;\n }\n return serverName;\n}\n\n/**\n * A readable `{slug}_annotate` from the server's own name, or `undefined`.\n *\n * Returns only a name it has already checked against the pattern, so the\n * caller can pass it straight in as an override without that becoming a\n * second throw site. Rendered beside the display name that won, and never\n * worse than the fallback: a name that does not fit is discarded and\n * `{vendorId}_annotate` stays.\n */\nexport function annotationToolNameFromServer(\n serverName: string | undefined,\n vendorDisplayName: string,\n): string | undefined {\n if (serverName === undefined) return undefined;\n const slug = slugServerName(serverName);\n if (slug === undefined) return undefined;\n const candidate = `${slug}${SUFFIX}`;\n // The slug's alphabet is a subset of the pattern's and the cap is well\n // inside it, so this cannot currently fail. Checked anyway, because the\n // alternative to a check here is a throw at a vendor's startup.\n if (!TOOL_NAME_PATTERN.test(candidate)) return undefined;\n if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: candidate })) {\n warn(\n `baton: the server-derived annotation tool name ${JSON.stringify(candidate)} ` +\n \"does not fit the server-instructions budget beside the display name \" +\n `(${vendorDisplayName.length} chars); keeping {vendorId}_annotate. ` +\n \"A shorter display name gets the readable one.\",\n );\n return undefined;\n }\n return candidate;\n}\n\n/** Compose and VALIDATE the final tool name: the last step of the ladder, and\n * its one throw site. Reached with a vendor's explicit name or an\n * already-validated derived one, never with a guess. */\nexport function deriveAnnotationToolName(vendorId: string, override?: string): string {\n const name = override || `${vendorId}${SUFFIX}`;\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\n/** The whole tool-name ladder in one call: explicit, then derived from the\n * server's name, then `{vendorId}_annotate`. Python's\n * `resolve_annotation_tool_name`. */\nexport function resolveAnnotationToolName(\n serverName: string | undefined,\n config: { vendorId: string; vendorDisplayName: string; annotationToolName?: string | undefined },\n): string {\n return deriveAnnotationToolName(\n config.vendorId,\n config.annotationToolName ||\n annotationToolNameFromServer(serverName, config.vendorDisplayName),\n );\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 * 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 the fields declared below are\n * ever read — three for `_meta`/session, two more for headers.\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 *\n * The SECOND divergence, same shape, measured 2026-09-11: v2 LIFTS every\n * reserved `io.modelcontextprotocol/*` key OUT of the `_meta` a handler sees\n * and re-exposes them under `mcpReq.envelope`. Sending one identical\n * hand-crafted `_meta` to both majors, `io.modelcontextprotocol/clientInfo`\n * arrived in `extra._meta` on sdk 1.30.0 and in `ctx.mcpReq.envelope` on\n * server 2.0.0, whose `_meta` retained only the unreserved\n * `claudecode/toolUseId`. So a reserved key read at the 1.x location alone\n * is a silent `unknown` across the whole v2 major. Use {@link extraEnvelope}.\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 — reserved keys INCLUDED. */\n _meta?: unknown;\n /** v2's `ServerContext.mcpReq` — the in-flight JSON-RPC request.\n * `envelope` holds the reserved `io.modelcontextprotocol/*` keys this\n * major lifts out of `_meta`; absent entirely when the request carried\n * none, which is the common case on a 2025-11-25 connection. */\n mcpReq?: { _meta?: unknown; envelope?: unknown } | undefined;\n /** 1.x: the transport request's headers, as a plain object whose values may\n * be a STRING, an ARRAY of strings (a repeated header line), or undefined. */\n requestInfo?: { headers?: unknown } | undefined;\n /** v2: HTTP transport info. `req` is the transport request and its\n * `headers` is a Web `Headers`.\n *\n * ⚠ **`req` is MEASURED on `@modelcontextprotocol/server` 2.0.0, not\n * declared.** That package's own `.d.ts` types `http` as `{ authInfo? }`\n * only, while the runtime builds\n * `http: { ...ctx.http, req: transportInfo?.request, closeSSE, ... }`. So\n * reading the published type alone says v2 exposes no headers at all, which\n * is what an earlier pass of this work concluded and it was wrong — the type\n * is one layer above the answer. Do not \"correct\" this back on the strength\n * of the `.d.ts`. */\n http?: { req?: { headers?: unknown } | undefined } | undefined;\n}\n\n/** The call's `_meta`, from wherever this SDK major keeps it.\n *\n * ⚠ On v2 this is `_meta` MINUS the reserved keys — see {@link extraEnvelope}\n * for those. It is the right input for the `claudecode/*` heuristic and for\n * `runtime_meta`, and the wrong one for anything `io.modelcontextprotocol/*`. */\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/** The reserved `io.modelcontextprotocol/*` keys v2 lifts out of `_meta`.\n *\n * Null on 1.x, where nothing is lifted and the keys stay in `extraMeta`'s\n * result — so a reader wanting a reserved key must consult BOTH, and finding\n * nothing here is the normal 1.x answer rather than an absent client. */\nexport function extraEnvelope(extra: Extra): Record<string, unknown> | null {\n const envelope = extra.mcpReq?.envelope as Record<string, unknown> | undefined;\n return envelope ?? null;\n}\n\n/** The call's HTTP headers as ONE shape, whichever major delivered them.\n *\n * ⚠ **This exists because the two majors disagree twice over**, and a vendor\n * hook must not have to know which one it is running under:\n *\n * | | where | shape |\n * |---|---|---|\n * | 1.x | `extra.requestInfo.headers` | plain object; a repeated header is an ARRAY |\n * | v2 | `extra.http.req.headers` | Web `Headers`, case-insensitive |\n *\n * Left unnormalized, `headers[\"X-Forwarded-User\"]` returns a string on one\n * major, an array when the header repeats, and `undefined` on the other — and\n * because the SDK peers type this position loosely, nothing warns the vendor.\n * That is register A8 (fixed in the Python SDK 2026-09-13, where one adapter\n * delivered a case-insensitive mapping and the other a lowercased dict) about\n * to happen again in TypeScript, so it is absorbed HERE rather than shipped.\n *\n * Web `Headers` is the normalized shape because it is the platform's own\n * answer to this question: lookups fold case, and repeated values join with\n * `\", \"` by a rule the standard defines — unlike the Python side, where the\n * two upstreams disagree on first-wins vs last-wins and neither joins.\n *\n * Returns `null` when no HTTP request is in flight, which is every stdio call\n * and the normal case. `null` means \"no HTTP request\", never \"the client sent\n * no headers\".\n */\nexport function extraHeaders(extra: Extra): Headers | null {\n const fromV2 = extra.http?.req?.headers as Headers | undefined;\n // Duck-typed rather than `instanceof Headers`. A `Headers` built in another\n // realm — a `vm` context, a framework's fetch shim, a bundled polyfill —\n // fails `instanceof`, and the fallthrough would then return `null`, which\n // this function's contract defines as \"no HTTP request is in flight\". That\n // statement would be FALSE: the hook would see stdio semantics on an\n // authenticated HTTP call and identity would silently disappear.\n if (fromV2 && typeof fromV2.get === \"function\") return fromV2;\n\n const fromV1 = extra.requestInfo?.headers;\n if (fromV1 && typeof fromV1 === \"object\") {\n const headers = new Headers();\n for (const [name, value] of Object.entries(fromV1 as Record<string, unknown>)) {\n // `undefined` is a declared value of 1.x's header record, and passing it\n // to `append` would stringify it into the literal text \"undefined\" —\n // a header that exists and holds a lie, which reads downstream as a\n // client that sent something.\n // An array is a repeated header line. Appending each lets `Headers`\n // apply the platform's join rule rather than inventing one here.\n //\n // Anything that is not a string is SKIPPED rather than coerced. The 1.x\n // type says `string | string[] | undefined`, but this value arrives as\n // `unknown` from a peer we do not control, and `String({})` yields the\n // literal text \"[object Object]\" — a header that exists and holds a\n // lie, which downstream reads as a client that sent something. Refusing\n // to invent a value is the same rule the null-vs-absent distinction on\n // `headers` itself follows.\n for (const item of Array.isArray(value) ? value : [value]) {\n if (typeof item !== \"string\") continue;\n try {\n headers.append(name, item);\n } catch {\n // ⚠ **`Headers.append` REJECTS names and values the 1.x peer will\n // really hand us, and an identity read may not fail a tool call.**\n // `SSEServerTransport` passes Node's `req.headers` through verbatim,\n // and under Node's HTTP/2 compatibility API that object carries the\n // pseudo-headers `:path` / `:method` / `:authority` / `:scheme` —\n // `append(\":path\", …)` throws `TypeError: invalid header name`, and\n // a CR/LF-bearing value from a custom transport throws the same way.\n // Unguarded, that escapes this function, escapes the context builder,\n // and 500s EVERY tool call on an HTTP/2 deployment before the\n // vendor's own handler runs. Skipping the offending header degrades\n // identity for that one header; letting it propagate takes down the\n // server.\n }\n }\n }\n return headers;\n }\n return null;\n}\n","/** `BatonConfig.resolvePrincipal` — the ASSERTED identity provenance.\n *\n * The TypeScript half of Python's `integrations/identity_adapter.py`, built to\n * close register D6: the field (`user_id` until 0.3.5) had been on this SDK's\n * envelope since 0.3.0 and NOTHING could populate it, so a partition that\n * works on one of two SDKs is not a partition.\n *\n * **Hook only — there is deliberately no attested (`h1:`) rung here yet.**\n * Python reads `claims[\"sub\"]` off a verified access token; TypeScript's\n * `AuthInfo` has no `claims` field at all (it is\n * `{token, clientId, scopes, expiresAt?, resource?, extra?}`), so the nearest\n * carrier is the untyped `extra` bag and nothing specifies that `sub` lives\n * there. Reading it would mean guessing where a subject lives, vendor by\n * vendor — and a wrong guess is how two people end up as one actor. Recorded\n * as a divergence rather than filled with a guess.\n */\n\nimport {\n type Principal,\n type PrincipalIdMode,\n PRINCIPAL_ID_MODE_HASHED,\n normalizePrincipal,\n principalIdFor,\n} from \"../../identity.js\";\nimport { warn } from \"./annotationName.js\";\nimport { type Extra, extraHeaders, extraMeta } from \"./mcpTypes.js\";\n\n/** What a vendor's `resolvePrincipal` hook is handed.\n *\n * Adapter-neutral BY CONSTRUCTION rather than by convention — the peers' own\n * handler-context objects differ in shape between the two majors, and this\n * type is what makes one hook portable across them. The prior art takes the\n * opposite approach: AgentCat's `identify()` receives the raw per-major object\n * behind `{ sessionId?: string; [key: string]: any }`, documented as \"only\n * `sessionId` is common to both; everything else is SDK-version-specific\".\n * That is the divergence handed to the vendor as `any`; this is the divergence\n * absorbed by us.\n */\nexport interface PrincipalResolutionContext {\n /** The call's HTTP headers, case-insensitive on BOTH majors — see\n * `extraHeaders` for the two shapes it reconciles.\n *\n * `null` means NO HTTP REQUEST (every stdio call, the common case), never\n * \"the client sent no headers\". The distinction matters: the first is us\n * telling you the question does not apply, the second would be a claim about\n * the caller that we are not in a position to make. */\n headers: Headers | null;\n /** The call's `_meta`, from wherever this major keeps it. */\n meta: Record<string, unknown> | null;\n /** The tool being called — the annotation tool's own name on that path, so a\n * hook can answer differently per call rather than per install. */\n toolName: string;\n /** The call's arguments, AFTER Baton's injected intent params are stripped,\n * so a hook sees exactly what the vendor's own handler will. */\n arguments: Record<string, unknown>;\n}\n\n/** A vendor's per-request identity resolver. Sync or async; returning `null`\n * means \"no opinion about this caller\", which is not an error. */\nexport type ResolvePrincipalHook = (\n context: PrincipalResolutionContext,\n) => Principal | null | Promise<Principal | null>;\n\n/** Build the hook's input from whichever major's context arrived.\n *\n * ⚠ **ONE factory, called by every emit path.** Both consumers (the tool-call\n * wrapper and the annotation tool) go through here rather than each assembling\n * a context, because per-site assembly is exactly how the Python SDK ended up\n * with two adapters delivering different header shapes behind one declared\n * type — and no test could see it, because each path only ever tested itself.\n */\nfunction buildPrincipalResolutionContext(\n extra: Extra,\n toolName: string,\n args: Record<string, unknown>,\n): PrincipalResolutionContext {\n return {\n headers: extraHeaders(extra),\n meta: extraMeta(extra),\n toolName,\n arguments: args,\n };\n}\n\n/** Warn ONCE at install when identity is configured but cannot produce a value.\n *\n * ⚠ **The silent-success case is the one that needs a voice.** A vendor sets\n * `resolvePrincipal`, ships, and sees `principal_id: null` on every event forever —\n * hashed mode with no key DROPS the field by design, and without this there is\n * no string anywhere in the process to grep for. Python spends a `warned` set\n * threaded through five call sites to say this; here all three inputs are\n * install-resolved constants, so it costs one check at startup and nothing per\n * call.\n *\n * ⚠ **The message must never contain the principal.** Identity was configured\n * and produced nothing, and printing the value to explain that would put raw\n * end-user identity in the vendor's log files — the residency leak one layer\n * sideways. Python's equivalent carries the same warning.\n *\n * `process.emitWarning` because `console` is banned in this package (stdout is\n * the MCP JSON-RPC frame) and this is the channel `optout.ts` and `HttpSink`\n * already use. Guarded like every `process` read here: absent on edge and\n * worker runtimes, where a missing warning channel must not crash startup.\n */\nexport function warnIfIdentityCannotResolve(config: {\n resolvePrincipal?: ResolvePrincipalHook | undefined;\n principalIdMode: PrincipalIdMode;\n principalIdHmacKey: string | Uint8Array | undefined;\n}): void {\n if (config.resolvePrincipal === undefined) return;\n if (config.principalIdMode !== PRINCIPAL_ID_MODE_HASHED) return;\n if (config.principalIdHmacKey !== undefined) return;\n if (typeof process === \"undefined\" || typeof process.emitWarning !== \"function\") return;\n // The pre-0.3.5 variable is never read. Naming it is the only way an upgrade\n // that kept it learns why identity stopped; its value is never logged.\n const renamed = process.env?.BATON_USER_ID_HMAC_KEY\n ? \"BATON_USER_ID_HMAC_KEY is set, but it was renamed to \" +\n \"BATON_PRINCIPAL_ID_HMAC_KEY in 0.3.5 and is no longer read. \"\n : \"\";\n process.emitWarning(\n \"baton: resolvePrincipal is configured but no principal_id HMAC key is set, so \" +\n `principal_id is dropped from every event (events still emit). ${renamed}Set ` +\n \"BATON_PRINCIPAL_ID_HMAC_KEY or BatonConfig.principalIdHmacKey, or pass \" +\n 'principalIdMode: \"raw\" if you intend to emit the subject verbatim.',\n );\n}\n\nlet warnedPreRenameShape = false;\n\n/** A hook still returning the pre-0.3.5 `{ userId }` resolves nobody on every\n * call and throws nothing, unlike a renamed config key. Say so once, and never\n * with the value. */\nfunction warnIfPreRenameShape(result: unknown): void {\n const userId = (result as { userId?: unknown } | null | undefined)?.userId;\n if (warnedPreRenameShape || typeof userId !== \"string\") return;\n warnedPreRenameShape = true;\n warn(\n \"baton: resolvePrincipal returned { userId }, which was renamed to { principalId } \" +\n \"in 0.3.5, so principal_id is dropped from every event until the hook returns the new key.\",\n );\n}\n\n/** Run a vendor's hook and turn its answer into the envelope's `principal_id`.\n *\n * ⚠ **Never throws.** A hook that raises, returns the wrong shape, or returns\n * `null` yields an anonymous call, not a failed one — `principal_id` is additive\n * analytics and a vendor's own bug in their resolver may not fail their tool\n * call (SPEC §11.2 fail-open). The prior art converged on the identical rule.\n *\n * ⚠ **No timeout, and that is a DIVERGENCE from Python recorded rather than\n * an omission.** Python runs vendor hooks off the event loop under a 5s\n * budget (`integrations/_hooks.py`); this arm awaits the hook inline. ⚠ An\n * earlier draft justified that by \"matching `resolveSessionId`, the convention\n * already shipped here\" — but `BatonConfig.resolveSessionId` was REMOVED\n * 2026-09-12 and the surviving function takes no vendor callable at all. The\n * real precedent is `scrubber`, the only other vendor code this SDK runs\n * inline; `resolvePrincipal` is the first vendor hook on its per-call path. So the\n * gap is real and deserves its true weight rather than an argument from a\n * convention that no longer exists. A hook that blocks stalls this request.\n * Containment is a separate, larger change on this arm.\n */\nexport async function resolveCallPrincipalId(\n hook: ResolvePrincipalHook | undefined,\n call: { extra: Extra; toolName: string; arguments: Record<string, unknown> },\n options: {\n mode: PrincipalIdMode;\n tenantId: string;\n key?: Uint8Array | string | null | undefined;\n },\n): Promise<string | null> {\n // ⚠ **The context is built HERE — after the hook check, inside the try —\n // and the signature takes the raw call rather than a built context so a\n // caller CANNOT do it the other way.** Passing a context as an argument\n // meant it was constructed on every tool call of every server that never\n // configured identity, and constructed OUTSIDE this guard, so a throw from\n // the header read escaped into the vendor's tool call. Python states the\n // same rule (`standalone/middleware.py`: \"the context is built only when a\n // hook exists\"), and having it as a convention rather than a shape is how\n // this arm got it wrong.\n if (hook === undefined) return null;\n let result: unknown;\n try {\n const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);\n result = await hook(context);\n } catch {\n // Broad on purpose, and for the reason the sibling guards are: this calls\n // code a VENDOR wrote, and an identity read may not be able to fail a\n // tool call. Nothing is logged to stdout — that stream is the MCP\n // JSON-RPC frame (AGENTS.md boundary rule 2).\n return null;\n }\n const principal = normalizePrincipal(result);\n if (principal === null) {\n warnIfPreRenameShape(result);\n return null;\n }\n try {\n return principalIdFor(principal, {\n mode: options.mode,\n tenantId: options.tenantId,\n key: options.key,\n });\n } catch {\n // The hashing step, which the guard above did NOT cover. `createHmac`\n // rejects a key that is not a string/TypedArray, and a JavaScript vendor\n // — or a TypeScript one whose config came from parsed settings and is\n // typed `any` — reaches this with `principalIdHmacKey: 12345`. Install-time\n // validation refuses that now, but this function's docstring promises it\n // cannot raise, and a promise like that needs the guard rather than an\n // argument about who calls it. Python guards the same call for the same\n // reason (`identity_adapter.py:324`).\n return null;\n }\n}\n\n","/**\n * Which agent runtime is calling the vendor's MCP server.\n *\n * A behaviour port of `baton` (Python)'s\n * `integrations/runtime_adapter.py::detect_agent_runtime`, not a\n * transcription of it: the ladder, the precedence argument and the\n * scrub/cap rule are Python's, while two of the three carriers are\n * different objects on this side and were measured before being used.\n *\n * **Prefer what the client DECLARED over what we can infer.** A client\n * names itself in its `initialize` handshake (`clientInfo`), and that is a\n * declaration; the key-prefix heuristic below is an inference drawn from an\n * artifact built for another purpose — `claudecode/toolUseId` is a per-CALL\n * tool-use id, and reading a caller's identity off its namespace prefix\n * works for one vendor by accident of naming and yields nothing for anyone\n * else. That is why Claude Desktop, Cursor and everything else reported\n * `unknown`, on this SDK as on Python's before the ladder landed.\n *\n * ⚠ **A caller cannot assert its own runtime.** This used to read an\n * `_meta.baton.agent_runtime` override; Python removed both spellings (the\n * nested form at B5, the reverse-DNS `io.baton/*` form on 2026-09-09) and\n * so did this module. Two sensors watching one client must not disagree\n * about what it is, and the value here is self-reported — never attested —\n * so an override would let the thing being measured choose its own label.\n *\n * ## The carriers, measured 2026-09-11 on both supported peers\n *\n * Against `@modelcontextprotocol/sdk` 1.30.0 and\n * `@modelcontextprotocol/server` 2.0.0, over real `InMemoryTransport` round\n * trips, reading what a tool handler actually receives.\n *\n * **Tier 1 has two locations, and reading one is a silent `unknown` across\n * a whole major.** One identical hand-crafted `_meta` carrying\n * `io.modelcontextprotocol/clientInfo` arrived in `extra._meta` on 1.x and\n * in `ctx.mcpReq.envelope` on v2 — which lifts every reserved\n * `io.modelcontextprotocol/*` key out of the `_meta` the handler sees. That\n * is the same shape of bug as Python's `clientInfo`/`client_info`, in a\n * different place, and it is why `envelope` is read here at all.\n *\n * **Tier 2 is not on the context.** Python reads\n * `ctx.session.client_params`; neither TS peer puts client identity on the\n * handler's context at all. Both DO expose the cached handshake on the\n * server object, under the same name: `McpServer.server.getClientVersion()`\n * returned the live `{name, version}` in-handler on 1.30.0 and on 2.0.0.\n * So tier 2's carrier is the server `withBaton` already holds, read lazily\n * per call. Duck-typed, never imported — importing either peer's type pins\n * this package to that major.\n *\n * **Tier 1 is not live traffic on these peers, unlike Python's.**\n * `@modelcontextprotocol/client` 2.0.0 negotiates `2025-11-25` by default\n * and sends `clientInfo` in the handshake only, nothing per-request. The\n * Python module's note that fastmcp 4's own `Client` writes the key on\n * every request does NOT transfer. Tier 1 is built anyway: it is free, it\n * is above tier 2 by the same freshest-declaration argument, and it starts\n * working the day a client moves with no further change here.\n */\n\n/**\n * The per-request carrier for the client's declared identity, reserved by\n * MCP 2026-07-28. `@modelcontextprotocol/server` exports this as\n * `CLIENT_INFO_META_KEY`; the literal is written out instead because the\n * 1.x peer exports no such constant and importing v2's would pin a major\n * for a string.\n */\nexport const CLIENT_INFO_META_KEY = \"io.modelcontextprotocol/clientInfo\";\n\n/*\n * ⚠ **Tier 1 is forgeable on 1.x and not on v2, and the module heading above\n * is too absolute about it.** \"A caller cannot assert its own runtime\" is\n * true of the removed `io.baton/*` override and true on a new-spec\n * connection, where the client LIBRARY writes the reserved key and overwrites\n * anything whoever composed the call planted there. It is NOT true on the\n * 1.x peer: measured, a hand-written\n * `_meta[\"io.modelcontextprotocol/clientInfo\"]` arrives verbatim and\n * outranks the handshake — which is exactly what this package's own\n * \"a request-borne declaration outranks the handshake\" test demonstrates.\n * So on a 2025-11-25 connection anything composing the tool call can set\n * `agent_runtime` to any string up to the cap, and change it per request.\n *\n * That is not a hole to close here — the value is self-reported at every\n * tier, which is why `agent_runtime` is never attested and `principal_id` is a\n * different field on a different condition. It is a limit to state, because\n * the sentence above reads stronger than the tier delivers.\n */\n\n/**\n * Cap on any name the CLIENT supplied. Both declared tiers read arbitrary\n * client text and copy it onto every event of the call, so an unbounded\n * value reaches every HTTP sink payload too. 128 is far above any real\n * client name (`claude-code` is 11) and far below anything worth shipping.\n *\n * The heuristic's own answer is NOT capped or scrubbed — it is a constant\n * this module owns, and mangling it would be the opposite mistake.\n */\nimport { capCodePoints } from \"../../_text.js\";\n\nexport const CLIENT_NAME_MAX_LEN = 128;\n\n/** What an event reports when no tier answered. A LITERAL, not a knob. */\nexport const UNKNOWN_AGENT_RUNTIME = \"unknown\";\n\n/** What `detectAgentRuntime` needs beyond `_meta`, all optional: omitting\n * any one costs that tier and nothing else. */\nexport interface RuntimeDetectionOptions {\n /** v2's lifted reserved keys (`extraEnvelope`). Null/omitted on 1.x,\n * where the same keys are in `meta` instead. */\n envelope?: Record<string, unknown> | null;\n /** The MCP server object `withBaton` wrapped — tier 2's only carrier on\n * either major. Duck-typed; anything else simply loses the tier. */\n server?: unknown;\n /** The vendor's scrubber, applied to the two CLIENT-SUPPLIED tiers. */\n scrubber?: ((value: unknown) => unknown) | undefined;\n}\n\n/**\n * Scrub and cap a CLIENT-SUPPLIED name, or null if it is unusable.\n *\n * Null rather than a sentinel so an empty or scrubbed-away value falls\n * through to the NEXT tier instead of becoming the reported runtime — a\n * vendor scrubber that redacts a name must lose that tier, not the ladder.\n */\nfunction clean(\n name: unknown,\n scrubber: ((value: unknown) => unknown) | undefined,\n): string | null {\n if (typeof name !== \"string\" || !name) return null;\n let cleaned: string = name;\n if (scrubber) {\n const scrubbed = scrubber(cleaned);\n // A scrubber that redacts by returning null — or anything else that is\n // not a string — loses this TIER; it does not get stringified onto the\n // wire. `String(null)` is `\"null\"`, which is truthy and would ship as\n // the reported runtime on every event of every call; an arbitrary\n // object would ship `\"[object Object]\"`.\n if (typeof scrubbed !== \"string\") return null;\n cleaned = scrubbed;\n }\n if (!cleaned) return null;\n // Code points, not UTF-16 units — `capCodePoints` carries the reasoning,\n // which moved there when a second capped field turned out to need it and\n // reintroduced the defect by slicing.\n return capCodePoints(cleaned, CLIENT_NAME_MAX_LEN);\n}\n\n/** The declared name off the reserved per-request key, wherever this major\n * keeps it. The value is an object with `name`/`version`. */\nfunction declaredOnRequest(\n meta: Record<string, unknown> | null,\n envelope: Record<string, unknown> | null | undefined,\n): unknown {\n for (const source of [envelope, meta]) {\n if (!source) continue;\n const info = source[CLIENT_INFO_META_KEY];\n if (info && typeof info === \"object\") {\n const name = (info as { name?: unknown }).name;\n if (name !== undefined) return name;\n }\n }\n return undefined;\n}\n\n/**\n * The declared name off the server's cached `initialize` handshake.\n *\n * ⚠ **Catches everything, on purpose.** This walks two properties of a\n * third-party object across two majors and seven versions, and they are\n * free to throw whatever they like — a getter that raises outside a live\n * connection is exactly the shape that already escaped into Python's\n * middleware once and failed a vendor's tool call, the one thing SPEC\n * §11.2 says capture may never do. An enumerated catch is a guess about a\n * library; this is a fail-open boundary.\n *\n * ⚠ **Per SERVER INSTANCE, where Python's carrier is per SESSION.**\n * `ctx.session.client_params` is scoped to one session by construction;\n * `getClientVersion()` returns whatever the last `initialize` on THIS object\n * cached. The two agree only while server:session is 1:1, which both peers'\n * documented patterns give (1.x `Protocol.connect` replaces the transport,\n * v2's `createMcpHandler` takes a per-session factory). A vendor wiring one\n * `McpServer` across concurrent sessions would get client A's calls\n * attributed to client B's declared name. Not measured either way — recorded\n * as the honest limit of this carrier rather than implied away.\n */\nfunction declaredOnConnection(options: RuntimeDetectionOptions): unknown {\n try {\n // `options.server` is READ INSIDE the try, never destructured by the\n // caller. Reading a property can itself throw — v2's `McpServer` reaches\n // `.server` through an accessor — and a read hoisted out of here escapes\n // the guard entirely while looking perfectly safe at the call site.\n const server = options.server;\n if (!server) return undefined;\n const inner = (server as { server?: unknown }).server;\n const holder = (inner ?? server) as {\n getClientVersion?: () => { name?: unknown } | undefined;\n };\n if (typeof holder.getClientVersion !== \"function\") return undefined;\n return holder.getClientVersion()?.name;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Return the detected agent runtime, or null if no signal — in which case\n * the caller substitutes {@link UNKNOWN_AGENT_RUNTIME}.\n *\n * Precedence — **declared before inferred**, freshest declaration first.\n * First hit wins:\n *\n * 1. The reserved `io.modelcontextprotocol/clientInfo`, riding the request\n * itself — read from v2's lifted `envelope` and from 1.x's `_meta`.\n * 2. The same declaration from the `initialize` handshake, cached on the\n * server. **This is the tier that does the work today**: every shipping\n * client declares here and nowhere else.\n * 3. Heuristic on key prefixes (`claudecode/*` → `claude-code`). Kept BELOW\n * both declarations rather than dropped: it is proven coverage, and\n * discarding proven coverage needs evidence nobody relies on it.\n * 4. null.\n *\n * **The heuristic is LAST on purpose.** A proxy forwards `_meta` verbatim,\n * so `claudecode/*` means \"this metadata ORIGINATED from Claude Code\", not\n * \"the caller IS Claude Code\" — while `clientInfo` is the client saying\n * what it is. And the heuristic is a one-vendor hardcode: on top it\n * special-cases Claude Code permanently and makes every new client a code\n * change. Where the two agree (Claude Code direct: declares `claude-code`,\n * sends `claudecode/*`) the order is unobservable either way.\n *\n * Tiers 1-2 return CLIENT-SUPPLIED text, so both are scrubbed and capped;\n * tier 3 returns a constant this module owns and is neither. A tier whose\n * value scrubs away to nothing falls through to the next one.\n *\n * ⚠ **Two things this does NOT claim.** The declared name identifies the\n * IMMEDIATE MCP client, which behind a gateway is the gateway rather than\n * the agent. And it is self-asserted, never attested: a client picks its\n * own `clientInfo`. Attested identity is `principal_id`, a different field on a\n * different condition; keep the two claims apart.\n */\nexport function detectAgentRuntime(\n meta: Record<string, unknown> | null,\n options: RuntimeDetectionOptions = {},\n): string | null {\n const { envelope, scrubber } = options;\n\n // Tier 1 — declared, on the request.\n const onRequest = clean(declaredOnRequest(meta, envelope), scrubber);\n if (onRequest !== null) return onRequest;\n\n // Tier 2 — declared, on the connection. The tier that answers for every\n // client shipping today, including the ones that were unattributable\n // before it existed. `options` goes in whole, deliberately: see the\n // property-read note in `declaredOnConnection`.\n const onConnection = clean(declaredOnConnection(options), scrubber);\n if (onConnection !== null) return onConnection;\n\n // Tier 3 — inferred, and last: a key prefix says where the METADATA came\n // from, not who the caller is. Only reached when nobody declared anything.\n if (meta) {\n for (const key of Object.keys(meta)) {\n if (key.startsWith(\"claudecode/\")) return \"claude-code\";\n }\n }\n\n return null;\n}\n","import 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. Falls back to the\n * transport-supplied `extra.sessionId`, then the process-wide fallback.\n *\n * ⚠ **Rung 0 — `BatonConfig.resolveSessionId` — was REMOVED 2026-09-12**,\n * mirroring Python. It keyed the session on an identifier the SDK did not\n * mint, which is what retired the `_meta` rungs on the Python side: a\n * vendor's handle differs from a client's only in who supplied it, and the\n * join rule does not draw that line. What a vendor knows about a caller\n * belongs in `principal_id`, which `BatonConfig.resolvePrincipal` now populates on this\n * SDK (see `principalResolution.ts`). That sentence read \"cannot yet populate at\n * all\" until the hook landed. */\nexport async function resolveSessionId(\n fallbackSessionId: string,\n extra: Extra,\n): Promise<string> {\n if (typeof extra.sessionId === \"string\" && extra.sessionId) return extra.sessionId;\n return fallbackSessionId;\n}\n","/**\n * The packed connection string a wrapped server ships with — parse only.\n *\n * A **DSN** carries the four values an install needs in one string:\n *\n * ```text\n * https://baton_pk_<random>@ingest.goodtiming.ai/ten_<8 hex>/echo-server\n * │ │ │ │ │\n * scheme key (the bearer) authority workspace server\n *\n * dsn = scheme \"://\" key \"@\" authority \"/\" workspace \"/\" server\n * scheme = \"https\" | \"http\"\n * key = \"baton_pk_\" tail ; \"baton_sk_\" warns and still works\n * authority = host [ \":\" port ]\n * workspace = \"ten_\" ( 8(hexdigit) | 32(hexdigit) )\n * server = the vendor_id pattern below\n * ```\n *\n * It replaces five environment variables with one value that can sit inline in\n * a distributable server's source, which is the whole point: a stdio server\n * runs on every user's machine, so a key that cannot ship means events that\n * never arrive.\n *\n * **Nothing here reaches the wire.** The envelope still carries `tenant_id`,\n * `vendor_id` and `consent_token` as separate fields — the SDK unpacks the\n * string and fills them in. This is config ergonomics; ingest, SPEC and the\n * `baton-spec` vectors are untouched.\n *\n * **The path segments are DATA, not a route.** Nobody can `GET` that URL. The\n * ingest origin is scheme + authority and *nothing else*; `HttpSink` appends\n * `/v0/events` itself, exactly as it does for an explicitly-constructed sink.\n * A parser that appends anything here reproduces a double-append this project\n * has already shipped once.\n *\n * Line-for-line port of `baton` (Python)'s `baton/_dsn.py`. The grammar is the\n * contract between the console's mint and both SDKs, so the two parsers are\n * kept the same shape deliberately — including the two deliberate\n * permissivenesses, because a parser STRICTER than the mint is what breaks a\n * customer, while one that is looser only fails to catch a typo the collector\n * will reject readably anyway:\n *\n * - **The key's tail is not length-checked.** The grammar says 43 characters\n * and the mint says so today; that number belongs to the console, and\n * pinning it here means the day the mint changes, every shipped SDK refuses\n * every new key. The prefix carries the meaning — length does not.\n * - **The server segment is checked with `VENDOR_ID_PATTERN`**, the same\n * object `validateBatonConfig` uses, rather than a second regex restating\n * its ceiling. That ceiling has already been costed wrong twice.\n *\n * **Never put a parsed DSN in an error message.** It holds a bearer token, and\n * an exception carrying one lands in stack traces, logs and issue reports.\n * Every throw below goes through `redact`.\n */\n\n/**\n * Vendor IDs become annotation tool name prefixes; same client-pattern as\n * annotation tool names. Rejects dots so the default tool name is valid.\n *\n * It lives HERE rather than in `integrations/mcp/config.ts` — which is where\n * it was defined and where `validateBatonConfig` still applies it — for the\n * same structural reason the Python copy moved: the DSN's server segment IS a\n * vendorId, and a top-level module must not import from `integrations/`. One\n * object, imported both places, so the two rules cannot drift apart the way a\n * copied regex would.\n */\nexport const VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;\n\n// The console mints lowercase, but hex case is not meaningful and refusing an\n// uppercase digit would be a rule stricter than the mint. Matched loosely,\n// passed through VERBATIM — the value is compared as a string server-side, so\n// this parser must never normalise it.\n//\n// **Two lengths.** `new_tenant_id` moved 32 -> 8 hex on 2026-09-12; 32 is the\n// shape it replaced, and every workspace minted before that date still carries\n// it. Both are accepted because a DSN ships inline in a distributable server's\n// source — refusing the old length breaks installs already out there, on an\n// upgrade meant to be safe. It collapses to `{8}` the day no `ten_<32 hex>`\n// workspace exists — a console question, and a CHECK rather than a note,\n// because a note drifts and nobody re-reads a comment to find out it expired:\n//\n// SELECT count(*) FROM tenants WHERE vendor_id ~ '^ten_[0-9a-f]{32}$';\n//\n// Zero means the 32-branch and its tests can go in one commit.\nconst WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;\n\n// A host contains none of these. Character for character `baton`'s\n// `_NOT_IN_A_HOST` (`_dsn.py:345`), because the two parsers answering one\n// question differently is how a DSN that works in Python fails in TypeScript.\n// The control characters ARE the subject here: this class exists to reject\n// them, which is the opposite of the accidental-escape case `no-control-regex`\n// guards against.\n// eslint-disable-next-line no-control-regex\nconst NOT_IN_A_HOST = /[\\\\\\s\\x00-\\x1f\\x7f]/;\n\n// What a BEARER can never carry, measured rather than assumed: `new Headers`\n// rejects exactly NUL, LF and CR, and accepts every other control character\n// and the space. Narrow on purpose — the tail's alphabet belongs to the\n// console's mint, and a parser stricter than the mint refuses valid keys in\n// the field. These three cannot be sent at all, so they are catchable here\n// instead of surfacing as a fetch that throws on every write.\n// eslint-disable-next-line no-control-regex\nconst NOT_IN_A_KEY = /[\\x00\\n\\r]/;\n\nconst PUBLISHABLE_PREFIX = \"baton_pk_\";\nconst SECRET_PREFIX = \"baton_sk_\";\n\n/**\n * A credential-shaped run: a prefix followed by enough tail to BE one.\n *\n * ⚠ **The floor on the tail is what lets this same pattern run over finished\n * sentences.** This module's own help text says \"as in\n * `https://baton_pk_...@host/ten_.../server`\" and its secret-key warning names\n * `baton_sk_` out loud; a pattern matching a bare prefix would eat both and\n * leave the reader with `<key>` where the example belongs. A real key's tail\n * is 43 URL-safe base64 characters — `%` is admitted too, since the tail is\n * deliberately unvalidated and one may contain it — so eight is far below any\n * credential and far above an ellipsis.\n */\nconst KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;\n\nfunction looksLikeAKey(value: string): boolean {\n return (\n value.startsWith(PUBLISHABLE_PREFIX) || value.startsWith(SECRET_PREFIX)\n );\n}\n\n/**\n * Whether a credential is anywhere INSIDE this value, not merely at its start.\n *\n * ⚠ **`startsWith` was the blind spot, and it was load-bearing in two\n * places.** A segment with a key glued to it — `srv-baton_pk_…`, the shape a\n * paste into a half-filled field makes — starts with neither prefix, so it\n * slipped past the key-in-slot refusal that names the slot and past the \"the\n * key is in the PATH\" hint, landing on a pattern-mismatch message that\n * interpolates the segment instead. Expressed through the scan rather than a\n * second regex, so there is ONE notion of \"looks like a credential\" and it\n * cannot drift from the one that redacts.\n */\nfunction containsKey(value: string): boolean {\n return sweep(value) !== value;\n}\n\n// What a bare key gets told. It is the single most likely paste error — the\n// /account page labels the key type \"Publishable key\" and the string you copy\n// \"DSN\" — so it earns a real sentence rather than a parse error.\nconst BARE_KEY_HINT =\n \"this looks like a bare key, not a DSN — copy the full value from \" +\n \"/account, which starts with https:// and ends with your server's name\";\n\n/**\n * Warn on stderr, never stdout: stdout is the JSON-RPC stream under stdio\n * transport, which is exactly the deployment this feature exists for.\n *\n * `process.emitWarning` is this repo's existing convention (`HttpSink`'s\n * buffer overflow), guarded here the way `resolveTenantId` guards its\n * environment read — `process` is absent on edge and worker runtimes, and a\n * missing warning channel must not crash a vendor's server startup.\n */\nfunction warn(message: string): void {\n if (\n typeof process !== \"undefined\" &&\n typeof process.emitWarning === \"function\"\n ) {\n process.emitWarning(message);\n }\n}\n\n/** The four values unpacked from one string. See the module docstring. */\nexport interface Dsn {\n /**\n * Scheme + authority, no path and no trailing slash — what `HttpSink` takes\n * as its base URL and appends `/v0/events` to.\n */\n readonly origin: string;\n /**\n * The workspace segment, `ten_` prefix included and case as minted. The\n * prefix is part of the id, not a marker to strip.\n */\n readonly tenantId: string;\n /**\n * The server segment. This is the server the key is BOUND to: a mismatch\n * between it and the events' `vendor_id` is refused at ingest.\n */\n readonly vendorId: string;\n /**\n * The bearer, whole and unmodified — the auth layer hashes the entire string\n * including its prefix, so nothing here may trim it.\n */\n readonly key: string;\n}\n\ninterface SplitDsn {\n scheme: string;\n netloc: string;\n /** Whether an authority-terminating `/` was present, so `redact` can render\n * the original shape rather than inventing or dropping a separator. */\n slash: string;\n path: string;\n}\n\n/**\n * The ONE split, shared by `redact` and `parseDsn`.\n *\n * ⚠ **Two functions splitting one string two ways is the defect this shape\n * exists to prevent**, and the Python original records it as shipped: its\n * `redact` partitioned on the first `@` while its parser used `rpartition` on\n * the netloc, so a string with two `@`s put the credential on the\n * \"redacted\" side of the split and the safe message carried the whole key.\n *\n * ⚠ **Hand-rolled rather than `new URL()`, and that is a measurement, not a\n * preference.** WHATWG parsing percent-encodes userinfo: `new URL(\n * \"https://a@b@host/…\").username` is `\"a%40b\"`, an ALTERED key — and\n * `decodeURIComponent` cannot round-trip it back, because the parser is\n * deliberately loose about the tail and a tail containing a literal `%` is\n * legal. Python's `rpartition(\"@\")` hands back the key verbatim; the bearer is\n * hashed whole server-side, so a parser that rewrites one byte of it produces\n * a key that matches no row. `new URL` is still used below, but only as a\n * VALIDATOR of the authority, after the credential is already split off.\n */\nfunction splitDsn(raw: string): SplitDsn | null {\n const schemeEnd = raw.indexOf(\"://\");\n if (schemeEnd === -1) return null;\n const scheme = raw.slice(0, schemeEnd).toLowerCase();\n const rest = raw.slice(schemeEnd + 3);\n\n // The authority ends at the first `/`, `?` or `#` — what `urlsplit` does,\n // and skipping the last two would let `https://key@host?a=b/ten_.../srv`\n // parse with a QUERY STRING inside the origin, which `HttpSink` would then\n // append `/v0/events` to.\n const end = rest.search(/[/?#]/);\n if (end === -1) return { scheme, netloc: rest, slash: \"\", path: \"\" };\n\n const netloc = rest.slice(0, end);\n if (rest[end] !== \"/\") {\n // A query or fragment where the path belongs: no segments at all, which is\n // the \"exactly two path segments\" refusal.\n return { scheme, netloc, slash: \"\", path: \"\" };\n }\n const afterSlash = rest.slice(end + 1);\n const pathEnd = afterSlash.search(/[?#]/);\n return {\n scheme,\n netloc,\n slash: \"/\",\n path: pathEnd === -1 ? afterSlash : afterSlash.slice(0, pathEnd),\n };\n}\n\n/** `netloc.rpartition(\"@\")` — the LAST `@`, so a key containing one survives. */\nfunction splitKeyFromAuthority(netloc: string): {\n key: string;\n at: boolean;\n authority: string;\n} {\n const index = netloc.lastIndexOf(\"@\");\n if (index === -1) return { key: \"\", at: false, authority: netloc };\n return {\n key: netloc.slice(0, index),\n at: true,\n authority: netloc.slice(index + 1),\n };\n}\n\n/**\n * A DSN with its credential removed, safe for an error message or a log.\n *\n * Keeps everything that helps someone fix the problem (scheme, host,\n * workspace, server) and drops the one part that must not be repeated. Falls\n * back to a bare marker if the string is too malformed to split, since \"I\n * could not parse it\" must never become \"here is your token\".\n *\n * ⚠ **The PATH is redacted too, and skipping it was the third leak of this\n * kind.** A key pasted into the workspace or server slot is a plausible\n * mistake — the two halves of a DSN look alike to someone copying by eye —\n * and such a string has no `@` at all, so every earlier version of this\n * function reported \"no key\" and then printed the path with the key in it.\n */\nexport function redact(raw: string): string {\n const parts = splitDsn(raw);\n if (parts === null) return \"<dsn>\";\n const { at, authority } = splitKeyFromAuthority(parts.netloc);\n // The path is assembled RAW and swept whole below, rather than elided\n // segment by segment. A per-segment pass is what this function used to do,\n // and it is the shape the leaks kept coming through: it can only cover the\n // slots someone remembered to route through it.\n const assembled = at\n ? `${parts.scheme}://***@${authority}${parts.slash}${parts.path}`\n : `${parts.scheme}://<no key>@${parts.netloc}${parts.slash}${parts.path}`;\n return sweep(assembled);\n}\n\n/**\n * The last line: anything still shaped like a credential is elided, wherever\n * it sits.\n *\n * ⚠ **The fourth leak of this kind, and the one per-slot handling could not\n * see.** The elision ran on PATH segments; a key pasted into the\n * AUTHORITY slot — `https://baton_pk_…` with nothing after it — was\n * interpolated verbatim, so the refusal printed the whole bearer. That case is\n * not exotic, it is the one this parser STEERS people into: a vendor who\n * pastes a bare key is told \"copy the full value from /account, which starts\n * with `https://`\", and the obvious next move is to prepend `https://` to the\n * key already in hand and run it again — putting the credential into the boot\n * log on the retry.\n *\n * So the guarantee stops being a list of slots that each remember to elide,\n * and becomes one scan of the finished string: a slot added later cannot\n * forget. Prefix-anchored, so the host, workspace and server around it stay\n * readable — the whole point of redacting rather than refusing to say\n * anything.\n */\nfunction sweep(message: string): string {\n return message.replace(KEY_RUN, \"<key>\");\n}\n\n/**\n * The only way this module throws, so the scan cannot be skipped.\n *\n * ⚠ **Review found two throws that skipped it, under a docstring already\n * claiming they could not.** The two pattern-mismatch refusals interpolate the\n * offending segment, which was elided by a prefix-anchored check that a\n * glued-on key — `srv-baton_pk_…`, what a paste into a half-filled field makes\n * — walks straight past. The bearer printed in plaintext, in the same sentence\n * as its own redaction.\n *\n * ⚠ **This sweep and `containsKey`'s key-in-slot refusal cover that input\n * jointly, and NEITHER is load-bearing alone** — measured by mutation:\n * removing either one reds no leak test, removing both reds three. That is\n * worth stating rather than leaving to be rediscovered, because it means a\n * reader who deletes one of them sees a green suite and concludes it was dead.\n * They are kept as a pair on purpose, and they answer different questions: the\n * refusal decides which SENTENCE a vendor reads, and is pinned by its own\n * test; this decides what no sentence may contain.\n *\n * The exit is the right home for the second job. A guarantee that lives at the\n * call sites is one the next message added does not know about.\n */\nfunction fail(message: string): never {\n throw new Error(sweep(message));\n}\n\n/** `BATON_DSN`, or undefined — guarded, since `process` is absent on edge and\n * worker runtimes and this module must not crash a server's startup there. */\nfunction dsnFromEnvironment(): string | undefined {\n const fromEnv =\n typeof process !== \"undefined\" ? process.env?.BATON_DSN : undefined;\n // Set-but-empty is how a shell exports a variable it failed to fill.\n // Treating it as a value would raise a parse error naming a string the\n // vendor never wrote.\n return fromEnv ? fromEnv : undefined;\n}\n\n/**\n * Which DSN applies, given what the caller ALSO configured by hand.\n *\n * ⚠ **An environment variable is not something the caller passed, and the\n * first cut of the Python original treated the two as one value.** Folding\n * `BATON_DSN` in before the conflict check meant a vendor who exported it for\n * one server could not install a SECOND server the old explicit way in the\n * same process: the install died accusing them of passing a `dsn` that appears\n * nowhere in their code. It also contradicted the precedence rule this SDK\n * states everywhere else — explicit wins, the environment is the fallback — by\n * letting an ambient value beat an explicit one and then blaming the caller\n * for the collision.\n *\n * So the two sources are separated:\n *\n * - **An explicit DSN beside an explicit `vendorId` / `tenantId` / `sink`\n * still throws.** Both are in the vendor's own source; picking one would be\n * a guess, and a wrong guess routes a server's traffic under someone else's\n * identity.\n * - **An ambient `BATON_DSN` loses to explicit configuration and is\n * ignored**, which is just \"explicit wins\" applied to a value the caller did\n * not write. It still outranks `BATON_TENANT_ID` and friends, which is the\n * re-install case the DSN exists for: environment against environment, the\n * packed one is the one someone chose today.\n * - **Being ignored is announced.** A vendor who exported `BATON_DSN`\n * expecting it to configure this server would otherwise get a healthy\n * install that ships events nowhere near the collector — broken and unbuilt\n * looking alike, at the one boundary where nobody is watching.\n */\nexport function selectDsn(\n explicit: string | undefined,\n supplied: Record<string, boolean>,\n door: string,\n): string | undefined {\n const conflicts = Object.keys(supplied)\n .filter((name) => supplied[name])\n .sort();\n\n // ⚠ **Falsy means unset, matching `dsnFromEnvironment` above and\n // `resolveTenantId`** — `!== undefined` was the first cut and the two rules\n // disagreed. A vendor writing `dsn: process.env.MY_DSN ?? \"\"`, or a config\n // loader that fills unset keys with `\"\"`, got an install that died naming a\n // dsn they never filled and pointed them at the wrong value to delete.\n //\n // ⚠ Python uses `is not None` here and therefore still has that behaviour;\n // this is a deliberate divergence, recorded for the back-port rather than\n // left to be found twice.\n if (explicit) {\n if (conflicts.length > 0) {\n fail(\n `${door} got both a dsn and an explicit ${conflicts[0]} — the dsn ` +\n `already supplies it. Drop one: the dsn is the single value from ` +\n `/account, and ${conflicts[0]} is what it unpacks to.`,\n );\n }\n return explicit;\n }\n\n const ambient = dsnFromEnvironment();\n if (ambient === undefined) return undefined;\n if (conflicts.length > 0) {\n warn(\n `baton: BATON_DSN is set, but this ${door} supplies ${conflicts.join(\", \")} ` +\n `directly, so BATON_DSN is being IGNORED and these events are NOT going ` +\n `to the collector it names. Remove the explicit value to use it, or ` +\n `unset BATON_DSN if it was meant for a different server.`,\n );\n return undefined;\n }\n return ambient;\n}\n\n/**\n * Unpack a DSN, throwing on anything that is not one.\n *\n * Loud at install, which is the behaviour a missing required environment\n * variable already has and the reason the TypeScript recipe grew an `env()`\n * helper: a config value that arrives wrong must fail where the vendor is\n * looking, not at the first tool call in production.\n */\nexport function parseDsn(raw: string): Dsn {\n if (typeof raw !== \"string\" || raw.trim() === \"\") {\n fail(\"dsn must be a non-empty string\");\n }\n\n const dsn = raw.trim();\n\n if (looksLikeAKey(dsn)) {\n // No redact() — a bare key has no structure to show, and echoing it is the\n // thing redact() exists to prevent.\n fail(`dsn is not a URL: ${BARE_KEY_HINT}`);\n }\n\n const safe = redact(dsn);\n const parts = splitDsn(dsn);\n\n if (parts === null || (parts.scheme !== \"https\" && parts.scheme !== \"http\")) {\n fail(\n `dsn ${safe} must start with https:// (or http:// for local ` +\n `development) — ${BARE_KEY_HINT}`,\n );\n }\n\n const { key, at, authority } = splitKeyFromAuthority(parts.netloc);\n if (!at || !key) {\n // The likeliest way to arrive here is not a missing key but a MISPLACED\n // one: the two path segments and the userinfo all look alike to someone\n // copying by eye. Saying which mistake it is costs one scan and saves the\n // reader the guess.\n // A key sitting where the HOST belongs is the retry of the bare-key\n // mistake: that refusal says \"copy the full value, which starts with\n // https://\", so the next thing a vendor tries is their bare key with a\n // scheme in front of it. Landing them on the generic sentence would leave\n // them exactly as stuck as before, having done what they were told.\n if (looksLikeAKey(parts.netloc)) {\n fail(\n `dsn ${safe} is a bare key with a scheme in front of it: ${BARE_KEY_HINT}. ` +\n `The full value also carries a host, your workspace and your server — ` +\n `https://baton_pk_...@host/ten_.../server`,\n );\n }\n const misplaced = parts.path\n .split(\"/\")\n .some((segment) => containsKey(segment));\n const detail = misplaced\n ? \"the key is in the PATH — it goes before an @\"\n : \"the value from /account has the key before an @\";\n fail(\n `dsn ${safe} carries no key: ${detail}, as in https://baton_pk_...@host/ten_.../server`,\n );\n }\n if (NOT_IN_A_KEY.test(key)) {\n // The key is the longest part of a DSN — a 9-character prefix and a\n // 43-character tail out of about a hundred — so it is the likeliest place\n // a line wrap lands, and the host message below would never have mentioned\n // it. `HttpSink` builds `Authorization: Bearer <key>`, which throws inside\n // the sink's bare catch and retries forever.\n fail(\n `dsn ${safe} has a line break or a null inside its key — those can ` +\n `never be sent in an Authorization header, so this DSN could not ` +\n `have worked. Check for a line wrap where the value was copied.`,\n );\n }\n if (key.includes(\":\")) {\n fail(\n `dsn ${safe} has a ':' in its key — a DSN carries one credential and no password field`,\n );\n }\n if (!authority) {\n fail(`dsn ${safe} has no host`);\n }\n\n // ⚠ **The first version of this guard listed `\\t`, `\\n`, `\\r` and called\n // the set CLOSED — \"every other control character makes `new URL` throw\".\n // That was measured in ONE POSITION and generalised.** WHATWG strips those\n // three anywhere, and additionally strips leading and trailing C0 controls\n // AND the space, so `https://key@host.example.com<SP>/ten_…/srv` parsed\n // clean with `pathname` still `/`. The origin then kept the character,\n // `HttpSink` appended `/v0/events` to put it mid-string, and `fetch` threw\n // on every send into `sendWithRetry`'s bare catch — retried, dropped,\n // forever, from an install that raised nothing.\n //\n // So the rule is now a CHARACTER CLASS over the authority, and it is\n // `baton`'s `_NOT_IN_A_HOST` (`_dsn.py:345`) character for character rather\n // than a second guess at the same question. A host contains no whitespace,\n // no control character and no backslash; what a URL parser then does with\n // one does not have to be enumerated.\n // ⚠ **A key in the HOST slot PARSES, and that is worse than printing one.**\n // Ported from `baton` (`_dsn.py:395`), which has had this refusal since its\n // own review found it; this parser went without and the twins diverged on\n // the one question this file says twice they must not diverge on.\n //\n // `https://x@<key>/ten_.../srv` splits on the LAST `@`, so the key lands in\n // the authority and any userinfo at all — one character will do — keeps it\n // out of the no-`@` branch that has the sentence for this. Nothing\n // downstream objects: the segments validate, `origin` becomes\n // `https://baton_pk_...` and rides on the config, and `HttpSink` appends\n // `/v0/events` and hands the result to `fetch` as a HOSTNAME — which puts\n // the bearer in a DNS query and a TLS SNI field on every send, to every\n // resolver in path. The bearer also silently becomes the one-character\n // userinfo, so nothing downstream even authenticates.\n //\n // Checked BEFORE `NOT_IN_A_HOST`, as in Python: a key contains none of those\n // characters, so the order only matters for WHICH sentence a paste error\n // gets, and this one names the mistake.\n if (containsKey(authority)) {\n fail(\n `dsn ${safe} has the KEY where the host belongs. The order is key, ` +\n `@, host — check whether the two are the wrong way round: ` +\n `https://baton_pk_...@host/ten_.../<server>`,\n );\n }\n if (NOT_IN_A_HOST.test(authority)) {\n fail(\n `dsn ${safe} has whitespace, a control character or a backslash inside ` +\n `its host. Those are silently REMOVED or reinterpreted when a URL is ` +\n `parsed, so the address dialled would not be the one you wrote — ` +\n `check for a line wrap or a stray space where the value was copied.`,\n );\n }\n\n // ⚠ **`new URL` is the host validator, and it runs only AFTER the credential\n // is split off.** Node's `ERR_INVALID_URL` carries the string it was handed\n // on `error.input`, so validating the whole DSN would put the bearer into an\n // exception — the single thing this module exists to prevent. Handed the\n // authority alone, the worst that error can hold is a hostname.\n //\n // ⚠ **Nothing from the caught error crosses over — not the object, not\n // `{ cause }`, not its message.** `cause` is the TypeScript twin of Python's\n // `__context__` trap: it survives on the thrown error and is reachable by\n // anything that walks the chain — an error reporter, a structured logger,\n // vitest's own diff. Only the constructor NAME is carried, and it carries no\n // input.\n //\n // Python reaches this check earlier (its `urlsplit` runs before the key\n // checks above), so a string that is BOTH keyless and unparseable gets the\n // \"carries no key\" sentence here and \"not a parseable URL\" there. Both\n // refuse, neither leaks; the order is what the leak-safe placement costs.\n let hostReason: string | null = null;\n let parsedAuthority: URL | null = null;\n try {\n parsedAuthority = new URL(`${parts.scheme}://${authority}`);\n } catch (error) {\n hostReason = error instanceof Error ? error.constructor.name : \"Error\";\n }\n if (parsedAuthority === null) {\n fail(`dsn ${safe} is not a parseable URL (${hostReason ?? \"Error\"})`);\n }\n\n // ⚠ **An assertion on `parsedAuthority.pathname`/`search`/`hash` stood here\n // and has been DELETED.** It was the first answer to the backslash smuggle,\n // and `NOT_IN_A_HOST` above is the second and better one — so it became a\n // guard no input could reach, which mutation testing showed by reddening\n // nothing when removed. Two rules answering for one input is what the\n // character class exists to stop being; the parsed object is still used, as\n // the validator that a host is a host at all.\n\n // ⚠ **A BACKSLASH smuggles a path into the authority, and the validator said\n // yes.** WHATWG folds `\\` to `/` for special schemes, so\n // `new URL(\"https://ingest.example.com\\evil\")` parses happily with host\n // `ingest.example.com` and path `/evil` — while the split above, which ends\n // the authority at `/`, `?` or `#`, keeps the whole thing as the authority.\n // The origin became `https://ingest.example.com\\evil`, `HttpSink` appended\n // `/v0/events`, and `fetch` resolved that to\n // `https://ingest.example.com/evil/v0/events`: a 404 at the first tool call,\n // in production, from an install that raised nothing — the exact failure the\n // \"loud at install\" promise exists to prevent.\n //\n // Asserted on what the URL parser MADE of the authority rather than by\n // adding `\\` to the terminator set, because the question is not which\n // characters WHATWG folds — it is whether anything but a host survived.\n const segments = parts.path.split(\"/\").filter((segment) => segment !== \"\");\n // Destructured with a rest element rather than length-checked, so the two\n // names narrow to `string` from the same test that refuses the wrong count.\n // `segments.length !== 2` would read more directly and `noUncheckedIndexedAccess`\n // cannot see through it — leaving a choice between an assertion that lies\n // the day someone edits the check, and an unreachable branch no test covers.\n const [workspace, server, ...extra] = segments;\n if (workspace === undefined || server === undefined || extra.length > 0) {\n fail(\n `dsn ${safe} must carry exactly two path segments — the workspace and ` +\n `the server, as in /ten_.../<server>. A missing server is never ` +\n `defaulted: it is what the key is bound to.`,\n );\n }\n\n for (const [slot, segment] of [\n [\"workspace\", workspace],\n [\"server\", server],\n ] as const) {\n if (containsKey(segment)) {\n // Checked BEFORE the pattern tests below, which would otherwise\n // interpolate the segment — and a key is far more useful to name by its\n // slot than to print back.\n fail(\n `dsn ${safe} has a KEY in the ${slot} slot. The key goes before the @, ` +\n `and the path carries the workspace and the server: ` +\n `https://baton_pk_...@host/ten_.../<server>`,\n );\n }\n }\n\n if (!WORKSPACE_PATTERN.test(workspace)) {\n fail(\n `dsn ${safe} has ${JSON.stringify(workspace)} where the workspace ` +\n `belongs — expected ten_ followed by 8 or 32 hex characters. If the two ` +\n `path segments are the right way round, this is not a Baton DSN.`,\n );\n }\n if (!VENDOR_ID_PATTERN.test(server)) {\n fail(\n `dsn ${safe} has ${JSON.stringify(server)} where the server belongs ` +\n `— it must match ${VENDOR_ID_PATTERN.source}, because this value becomes ` +\n `the annotation tool name prefix as well as the envelope's vendor_id.`,\n );\n }\n\n if (key.startsWith(SECRET_PREFIX)) {\n // A warning, never a refusal. The KEY ROW is the authority on what a key\n // may do, not its prefix — an SDK enforcing a console policy turns a typo\n // at the mint site into a confusing client-side error. But a secret key\n // inside a server that ships to strangers is worth saying out loud, and\n // this is the only place that can say it. The prefix only — the point is\n // not to repeat the secret.\n warn(\n `baton: this DSN carries a ${SECRET_PREFIX} key (a workspace SECRET) where ` +\n `a ${PUBLISHABLE_PREFIX} key belongs. It will work. But if this server ` +\n `ships to anyone else, that key reads and writes everything the ` +\n `workspace holds — mint a publishable key at /account instead.`,\n );\n }\n\n return sealKey({\n origin: `${parts.scheme}://${authority}`,\n tenantId: workspace,\n vendorId: server,\n key,\n });\n}\n\n/**\n * The parsed DSN, with its bearer kept out of anything that prints the object.\n *\n * `dsn.key` still reads the key — the sink needs it. What changes is the\n * INCIDENTAL paths: `console.log(dsn)`, `util.inspect`, and the\n * `JSON.stringify` inside every structured logger, each of which would\n * otherwise write a publishable key into a vendor's log the moment anyone\n * debugs their install. Python's copy takes the same precaution one field at a\n * time (`field(repr=False)`); a JS object has no repr, so the two hooks that\n * stand in for one are both defined.\n *\n * Both are non-enumerable, so `{...dsn}` and `Object.keys` are unchanged — a\n * spread that silently dropped the bearer would be a far worse trap than the\n * one being closed.\n */\nfunction sealKey(dsn: Dsn): Dsn {\n const shown = {\n origin: dsn.origin,\n tenantId: dsn.tenantId,\n vendorId: dsn.vendorId,\n key: \"<key>\",\n };\n Object.defineProperty(dsn, \"toJSON\", {\n value: () => shown,\n enumerable: false,\n });\n // `Symbol.for`, not an import of `node:util`: this package runs on edge and\n // worker runtimes too, and a registry symbol is inert where nothing reads it.\n Object.defineProperty(dsn, Symbol.for(\"nodejs.util.inspect.custom\"), {\n value: () => shown,\n enumerable: false,\n });\n return dsn;\n}\n","/**\n * `BatonConfig` — vendor-side configuration for `withBaton`. A trimmed\n * mirror of `baton` (Python)'s `integrations/_config.py::VendorConfig`.\n */\n\nimport { parseDsn, selectDsn, VENDOR_ID_PATTERN } from \"../../dsn.js\";\nimport { displayNameFromServer } from \"./annotationName.js\";\nimport type { ResolvePrincipalHook } from \"./principalResolution.js\";\nimport { DEFAULT_CONSENT_TOKEN } from \"../../events.js\";\nimport { HttpSink, 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.\n//\n// Imported from `dsn.ts` rather than defined here, and re-exported so this\n// stays the name the rest of the integration reads: a DSN's server segment IS\n// a vendorId, so the parser applies this very rule, and a second copy of the\n// regex is how the two drift apart. This recipe has already costed that 48\n// wrong twice by writing the number down somewhere else. Python makes the\n// same move, for the same reason.\nexport { VENDOR_ID_PATTERN } from \"../../dsn.js\";\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\"]);\nconst PRINCIPAL_ID_MODES = new Set([\"hashed\", \"raw\"]);\n\nexport interface BatonConfig {\n /** The packed connection string from /account — one value carrying the\n * ingest host, the workspace, the server and the key that binds them.\n *\n * `withBaton(server, { dsn })` is the whole wrap block a DISTRIBUTABLE\n * server ships with, and that is the case it exists for: a stdio server\n * runs on every user's machine, so five `BATON_*` variables are five values\n * that never arrive. Resolved explicit → `BATON_DSN` → unset.\n *\n * **Environment variables do not override it.** A server being re-onboarded\n * has last install's `.env` beside the new inline DSN, and if these values\n * fell through to `BATON_TENANT_ID` the way an unset field does, the stale\n * file would win silently and the events would arrive under the previous\n * server's name.\n *\n * Passing a dsn AND an explicit `vendorId`, `tenantId` or `sink` throws:\n * two sources for one value cannot be reconciled without guessing, and a\n * wrong guess routes a server's traffic under someone else's identity.\n * Everything else — the display name, the scrubber, the injection modes,\n * every identity option — is unaffected; set them alongside a dsn freely. */\n dsn?: string;\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 *\n * Required unless a `dsn` supplies it — the DSN's last path segment IS this\n * value, and it is what the key is BOUND to. */\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 *\n * When a `dsn` is given and this is not, defaults to your server's OWN name\n * (`new McpServer({ name })`), VERBATIM: a string you chose, which makes it\n * the one to put in front of your users. Verbatim rather than prettified\n * for the same reason: a capitalisation you never chose would be a\n * fabricated name. Falls back to the DSN's server segment when the server's\n * name is one a library made up, is blank or unreadable, or would push the\n * server instructions over their cap. With no `dsn`, this is required. */\n vendorDisplayName?: string;\n /** End-user consent token attached to every emitted event per SPEC §2.3 —\n * the Console MUST reject events missing it.\n *\n * **Defaulted, so the customer never has to carry it** — see\n * `DEFAULT_CONSENT_TOKEN` for why the field stays on the wire regardless.\n * Passing `\"\"` explicitly still throws: a value the vendor deliberately\n * emptied is a mistake, not a request for the default.\n *\n * ⚠ **No environment variable is read for this, and that is parity rather\n * than a gap.** Python reads `BATON_CONSENT_TOKEN` on its `Client` door\n * only; its `VendorConfig` — the door this package mirrors — takes a plain\n * default, and the `os.environ[\"BATON_CONSENT_TOKEN\"]` in its install\n * examples is the RECIPE passing a value explicitly, not the SDK reading\n * one. Adding the read here would make this arm honour a variable the\n * equivalent Python door ignores. */\n consentToken?: string;\n /** Where events go. Defaults to `new StdoutSink()` — zero-config dev mode. */\n sink?: Sink;\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 override for the annotation tool name, and the only thing that\n * pins it. The default is derived from your server's own name, slugged: a\n * server called `\"Acme Knowledge Base\"` registers\n * `acme-knowledge-base_annotate`. It falls back to `{vendorId}_annotate`\n * when the name is one a library made up, slugs to nothing, is unreadable,\n * or would not fit the server instructions. Set this to keep a name you have\n * written into documentation, a prompt or a script. */\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 /** Per-request principal identity — the ASSERTED provenance behind the\n * envelope's `principal_id` (SPEC §11.4 rung 0), tagged `v1:`.\n *\n * Called on every captured tool call and on the annotation tool, with an\n * adapter-neutral {@link PrincipalResolutionContext}: headers folded to ONE\n * case-insensitive shape across both SDK majors, the call's `_meta`, the\n * tool name, and the arguments the vendor's own handler will see. Return a\n * `Principal`, or `null` for \"no opinion about this caller\".\n *\n * **This is the only identity mechanism on this arm.** MCP auth is HTTP\n * middleware, so a stdio server has no token at all; and unlike Python, no\n * attested rung is implemented here — see `principalResolution.ts` for why\n * (TypeScript's `AuthInfo` carries no `claims`).\n *\n * Never fails a tool call: a hook that throws or returns junk yields an\n * anonymous call. ⚠ It is awaited INLINE with no timeout — a blocking hook\n * stalls its own request. */\n resolvePrincipal?: ResolvePrincipalHook;\n /** `\"hashed\"` (default) emits a `v1:` per-tenant HMAC pseudonym; `\"raw\"`\n * emits the subject VERBATIM.\n *\n * `\"raw\"` puts real identity in the collector's database and is the\n * vendor's deliberate choice — which is why SPEC §11.4 tells a consumer\n * never to treat this field as anonymous. */\n principalIdMode?: \"hashed\" | \"raw\";\n /** The HMAC secret for hashed mode. Resolved explicit →\n * `BATON_PRINCIPAL_ID_HMAC_KEY` → unset.\n *\n * ⚠ **With none set, hashed mode DROPS `principal_id` rather than falling back to\n * raw.** The fallback would be a residency breach that looks like success:\n * the field present, populated, and carrying the subject verbatim. */\n principalIdHmacKey?: string | Uint8Array;\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 a missing one is\n // a miss, not a crash inside the vendor's server startup. (This said \"this\n // package reads no other environment variable\" until `resolvePrincipalIdHmacKey`\n // below added a second one; `dsn.ts` and `optout.ts` read theirs too.)\n const fromEnv = typeof process !== \"undefined\" ? process.env?.BATON_TENANT_ID : undefined;\n if (fromEnv) return fromEnv;\n return vendorId;\n}\n\n/**\n * The HMAC secret for hashed `principal_id`: explicit → `BATON_PRINCIPAL_ID_HMAC_KEY` →\n * unset. Mirrors Python's `_resolve_principal_id_hmac_key`.\n *\n * `undefined` is a SUPPORTED state, not an error: it means hashed-mode\n * identity is off and events emit without `principal_id`. A string is kept as a\n * string and UTF-8 encoded at the HMAC, which is the same byte sequence\n * Python's env path produces — the env var has always carried text.\n *\n * Resolved ONCE per install, for the same reason `resolveTenantId` is: two\n * resolutions could disagree, and one person would hash two ways within a\n * single server.\n */\nexport function resolvePrincipalIdHmacKey(\n explicit: string | Uint8Array | undefined,\n): string | Uint8Array | undefined {\n if (explicit !== undefined) return explicit;\n // Guarded exactly like the tenant read — `process` is absent on edge and\n // worker runtimes, and a missing one is a miss rather than a crash inside\n // the vendor's server startup.\n const fromEnv =\n typeof process !== \"undefined\" ? process.env?.BATON_PRINCIPAL_ID_HMAC_KEY : undefined;\n return fromEnv ? fromEnv : undefined;\n}\n\n/**\n * A config with everything the DSN can supply already filled in.\n *\n * The three fields are required HERE and optional on `BatonConfig`, so the\n * compiler enforces that `withBaton` reads the resolved value: the wrap paths,\n * the annotation tool and the surface snapshot all close over this object, and\n * one of them reading the caller's raw config would emit events under a\n * different identity than the rest.\n */\nexport interface ResolvedBatonConfig extends BatonConfig {\n vendorId: string;\n vendorDisplayName: string;\n consentToken: string;\n}\n\n/**\n * Fill in whatever the DSN carries, returning a config nothing downstream has\n * to know about. Mirrors Python's `integrations/_config.py::resolve_config`.\n *\n * **Everything a DSN supplies lands at the EXPLICIT tier, above the\n * environment** — see `BatonConfig.dsn` for why that matters more than it\n * sounds. A NEW object is returned rather than the caller's mutated: a vendor\n * may hold one config and hand it to two servers, and an install that rewrote\n * its argument would make the second inherit the first's resolution.\n *\n * ⚠ **The parsed key is NOT kept on the returned config.** It reaches the sink\n * and stops there. Python retains its `dsn` string on the config and pays for\n * it — `repr(VendorConfig)` prints the bearer, which is one of the leaks\n * parked for that repo — and nothing here reads the string after parsing, so\n * this arm simply does not import the problem.\n *\n * `serverName` is the server's own name as `withBaton` read it, already\n * through `usableServerName`, so `undefined` when there is none to use. It is\n * consulted for one field, the display name, and only when a DSN is given:\n * with no DSN, `vendorDisplayName` stays required.\n */\nexport function resolveBatonConfig(config: BatonConfig, serverName?: string): ResolvedBatonConfig {\n const dsnString = selectDsn(\n config.dsn,\n {\n // Truthiness per field, mirroring Python's `bool()` / `is not None`\n // split: an empty `vendorId` is an unset one, while an explicitly\n // supplied `tenantId` or `sink` is a conflict whatever it holds.\n vendorId: Boolean(config.vendorId),\n tenantId: config.tenantId !== undefined,\n sink: config.sink !== undefined,\n },\n \"BatonConfig\",\n );\n\n if (dsnString === undefined) {\n const defaulted: BatonConfig = {\n ...config,\n consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN,\n };\n validateBatonConfig(defaulted);\n return defaulted;\n }\n\n const dsn = parseDsn(dsnString);\n // The packed string is DELETED rather than overwritten with `undefined`:\n // `exactOptionalPropertyTypes` refuses the latter, and dropping the property\n // is what is wanted anyway — see the note above about not keeping the\n // bearer on an object that outlives this call.\n const rest: BatonConfig = { ...config };\n delete rest.dsn;\n const identity: BatonConfig = {\n ...rest,\n vendorId: dsn.vendorId,\n tenantId: dsn.tenantId,\n // `??`, for the same reason as `consentToken` directly below, and the\n // inconsistency was worth fixing rather than mirroring: with no dsn,\n // `vendorDisplayName: \"\"` is REFUSED by validation; with one, `||` quietly\n // substituted the server slug. One input, two answers, decided by whether\n // a dsn happens to be present — and this string reaches the calling agent\n // in the server instructions and the annotation tool description, which is\n // the whitelabel obligation the validator cites when it refuses the empty\n // one. ⚠ Python uses `or` here and still has the inconsistency.\n //\n // Between the explicit value and the segment sits the server's own name,\n // under the guards in `annotationName.ts`: the segment is an opaque\n // `srv-<8 hex>`, and it was what agents were told the vendor is called.\n vendorDisplayName:\n config.vendorDisplayName ??\n displayNameFromServer(serverName, {\n vendorId: dsn.vendorId,\n annotationToolName: config.annotationToolName,\n }) ??\n dsn.vendorId,\n // `??`, not `||`: an explicit empty string must survive to the validation\n // below and be REFUSED there, rather than be quietly replaced by the\n // default it was deliberately not left as.\n consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN,\n };\n\n // Validated BEFORE the sink is built. The ordering is parity with Python,\n // where `HttpSink.__init__` eagerly constructs an httpx client that a later\n // validation failure would leave unclosed; this `HttpSink` holds no resource\n // until its first write, so here the order protects nothing and is kept so\n // the two arms cannot answer \"what happens on a bad config\" differently.\n validateBatonConfig(identity);\n\n // `identity` is a ResolvedBatonConfig from here — `validateBatonConfig` is\n // an assertion signature, so the three required fields are proven by the\n // same call that refuses a config missing them, rather than re-asserted with\n // a cast that would go on compiling if a check were ever deleted.\n return {\n ...identity,\n // The origin is scheme + authority; `HttpSink` appends `/v0/events`\n // itself, exactly as it does for an explicitly-constructed sink.\n sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),\n };\n}\n\n/** Keys renamed in 0.3.5, REFUSED rather than ignored: a JavaScript caller gets\n * no compile error, and identity fails open, so an ignored `resolveUser` would\n * just stop producing `principal_id`. The renamed subset of what Python's\n * `TypeError` refuses, which is any unknown keyword. */\nconst RENAMED_KEYS: Record<string, string> = {\n resolveUser: \"resolvePrincipal\",\n userIdMode: \"principalIdMode\",\n userIdHmacKey: \"principalIdHmacKey\",\n};\n\nexport function validateBatonConfig(config: BatonConfig): asserts config is ResolvedBatonConfig {\n for (const [was, now] of Object.entries(RENAMED_KEYS)) {\n if (was in config) {\n throw new Error(`BatonConfig.${was} was renamed to ${now} in 0.3.5.`);\n }\n }\n if (!config.vendorId) {\n throw new Error(\n \"BatonConfig needs a vendorId — either directly, or via a dsn whose \" +\n \"last path segment names the server (see /account).\",\n );\n }\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 !== undefined && !config.consentToken) {\n throw new Error(\n \"BatonConfig.consentToken was set to an empty string, and events \" +\n \"without a valid consent_token MUST be rejected by the consumer per \" +\n \"SPEC §2.3. Omit it to take the SDK's default.\",\n );\n }\n if (!config.consentToken) {\n // Reached only by a direct call: `resolveBatonConfig` fills the default in\n // before validating. Kept because this function is exported and asserts\n // the field is present — an assertion signature that can be true while the\n // field is missing is worse than no signature.\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 if (config.resolvePrincipal !== undefined && typeof config.resolvePrincipal !== \"function\") {\n // Refused AT INSTALL rather than at the first call. Unvalidated it would\n // fail inside the hook's own fail-open guard — logged nowhere, identity\n // silently absent for the life of the process, in the one deployment shape\n // (stdio, where no token can exist) that this field is the only mechanism\n // for. Mirrors Python's `resolve_user must be callable`.\n throw new Error(\"BatonConfig.resolvePrincipal must be a function.\");\n }\n if (\n config.principalIdHmacKey !== undefined &&\n typeof config.principalIdHmacKey !== \"string\" &&\n !(config.principalIdHmacKey instanceof Uint8Array)\n ) {\n // The one new field with no install-time check until now, and the shape\n // that reaches it is ordinary: a config built from parsed settings is\n // typed `any`, so `principalIdHmacKey: 12345` compiles. Unvalidated, `createHmac`\n // rejects it INSIDE the per-call identity path — once per tool call, for\n // the life of the process. Mirrors Python, which guards this at install\n // AND around the hash itself; both, because a promise that a function\n // cannot raise should not rest on an argument about who calls it.\n throw new Error(\"BatonConfig.principalIdHmacKey must be a string or a Uint8Array.\");\n }\n if (config.principalIdMode !== undefined && !PRINCIPAL_ID_MODES.has(config.principalIdMode)) {\n throw new Error(\n `BatonConfig.principalIdMode ${JSON.stringify(config.principalIdMode)} must be one of ` +\n `${JSON.stringify([...PRINCIPAL_ID_MODES].sort())}.`,\n );\n }\n}\n","/**\n * The off switch — one environment variable that stops Baton doing anything.\n *\n * `BATON_DISABLED=1`, and deliberately nothing else. Port of Python's\n * `baton/_optout.py`; `DO_NOT_TRACK` was built there and taken back OUT the\n * same day, on a measurement rather than an argument, so it is not here\n * either: **an MCP client does not hand its environment to the server it\n * spawns.** Both SDKs' clients pass a fixed allowlist — `HOME`, `LOGNAME`,\n * `PATH`, `SHELL`, `TERM`, `USER` — and `DO_NOT_TRACK` is not on it, so a\n * global export never reaches a wrapped stdio server, while a user editing\n * their client config's `env` block could have typed `BATON_DISABLED=1` there\n * instead. The cost was concrete where the benefit was not: a contributor with\n * it exported got a silently disabled SDK and 203 failing tests.\n *\n * **Off means INSTALL NOTHING, and it means NEVER THROW.** Not\n * capture-and-discard: no tool wrapping, no annotation tool on the surface, no\n * instructions rewrite, no sink, no buffer. The vendor's server starts and\n * behaves exactly as it would if `withBaton` were not in the file at all. Both\n * halves are load-bearing:\n *\n * - **Nothing on stdout, ever.** A stdio MCP server speaks JSON-RPC on stdout,\n * so a courteous \"Baton is disabled\" line printed there corrupts the stream\n * and breaks the server — in precisely the deployment shape this switch\n * exists for.\n * - **The switch cannot break a server.** Every guard the SDK would otherwise\n * throw from — a config missing its `vendorId`, an unparseable DSN — is\n * skipped along with everything else, because a promise of \"set this and\n * Baton stops\" that can still abort a boot is worse than no switch at all.\n *\n * ⚠ **The consequence of never-throw, recorded rather than argued away:** a\n * vendor whose CI exports `BATON_DISABLED` globally will not learn that their\n * `withBaton` call is malformed, because the call cannot fail while the switch\n * is on. It surfaces the first time capture is enabled.\n *\n * ⚠ **Read at install time, once, and never re-read.** A process that starts\n * with capture on keeps it on: this is a boot-time switch, not a live one. A\n * re-read per event would let a mid-flight environment change split one\n * session's events across two answers.\n *\n * ⚠ **Whose switch this is.** It belongs to whoever RUNS the server. For a\n * distributed stdio server that is the end user, and it works. For a HOSTED\n * server it is the vendor, and the end user has no switch at all — they cannot\n * set an environment variable on someone else's machine. A per-end-user\n * opt-out is the consent token (CHARTER ADR-1) and remains unbuilt, so no\n * vendor-facing wording may imply otherwise.\n */\n\nimport type { Sink } from \"./sinks.js\";\n\nconst SWITCH = \"BATON_DISABLED\";\n\n// ⚠ **Permissive toward the opt-out, on purpose.** The documented form is\n// `=1`, but someone who writes `BATON_DISABLED=true` has said what they want\n// as plainly as someone who writes `1`, and the two failure directions are not\n// symmetric: honouring an unintended opt-out costs some telemetry, while\n// ignoring an intended one collects data from a person who asked us not to.\n// So anything that is not an explicit \"off\" counts as on.\nconst OFF_VALUES = new Set([\"\", \"0\", \"false\", \"no\", \"off\"]);\n\n/**\n * The NAME of the variable switching capture off, or `null`.\n *\n * The name rather than a boolean, so the log line and the disabled handle can\n * say what did it without every entry point repeating the string.\n *\n * The `process` read is guarded, like every other one in this package: it is\n * absent on edge and worker runtimes, and a missing `process` is \"no switch\n * set\", never a crash inside a vendor's server startup.\n */\nexport function captureDisabled(): string | null {\n const value = typeof process !== \"undefined\" ? process.env?.[SWITCH] : undefined;\n if (value !== undefined && !OFF_VALUES.has(value.trim().toLowerCase())) {\n return SWITCH;\n }\n return null;\n}\n\n/**\n * Say so once, on stderr, never on stdout.\n *\n * ⚠ **`process.emitWarning`, because `console` is BANNED in this package** —\n * `no-console` is an eslint error here, the coarse guard against the fatal\n * case: `console.log` writes to stdout, which is the JSON-RPC stream under\n * stdio transport. `console.error` would have been safe and was the first\n * cut, but carving an exception into a repo-wide rule for one line is worse\n * than using the channel the package already speaks on — `HttpSink`'s buffer\n * warning is the same call.\n *\n * ⚠ **Louder than the Python copy, and that is a divergence rather than an\n * oversight.** Python logs this at INFO, which its default handler drops, so a\n * server that configures no logging prints nothing; it argues explicitly\n * against WARNING, on the grounds that a line emitted every process start for\n * a switch somebody set deliberately teaches people to ignore warnings. That\n * argument is about a logger with levels to be quiet at, and this package has\n * none. The alternative was saying nothing at all, which loses the answer for\n * the vendor asking why no events arrive.\n *\n * ⚠ **Not a discoverability guarantee, and it must not be sold as one.** It is\n * for the vendor who goes looking. The answer for one who has not thought to\n * look is vendor-facing documentation, which is a different piece of work.\n */\nexport function logDisabled(switchName: string, surface: string): void {\n // Guarded like every `process` read in this package — absent on edge and\n // worker runtimes, where a missing warning channel must not crash a server's\n // startup. Deliberately NOT shared with `dsn.ts`'s `warn`: that one sweeps\n // credentials out of its message first, and this one has none to sweep.\n if (typeof process !== \"undefined\" && typeof process.emitWarning === \"function\") {\n process.emitWarning(\n `baton: ${switchName} is set, so capture is OFF — ${surface} installed ` +\n `nothing and will emit no events. Unset it to re-enable.`,\n );\n }\n}\n\nexport class DisabledSink implements Sink {\n // The parameter is omitted rather than named-and-ignored: a narrower\n // signature satisfies `Sink` in TypeScript, and there is nothing to do with\n // an event that cannot arrive.\n async write(): Promise<void> {\n return;\n }\n\n async flush(): Promise<void> {\n return;\n }\n\n async aclose(): Promise<void> {\n return;\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: `BatonConfig.annotationToolName` if\n * set, else derived from the server's own name (`{slug}_annotate`), else\n * `{vendorId}_annotate`. */\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,cAAc;;;ACa3B,iBAAkB;AAClB,kBAA6B;AAkBtB,IAAM,6BAA6B,aACvC,OAAO;AAAA,EACN,WAAW,aAAE,OAAO;AAAA,EACpB,QAAQ,aAAE,OAAO,aAAE,OAAO,GAAG,aAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EACpD,aAAa,aAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EAC/C,eAAe,aAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EACjD,eAAe,aAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EACjD,eAAe,aAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AACnD,CAAC,EACA,OAAO;AAIH,IAAM,2BAA2B,aACrC,OAAO;AAAA,EACN,WAAW,aAAE,OAAO;AAAA,EACpB,QAAQ,aAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EAC3C,aAAa,aAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,IAAI;AACvD,CAAC,EACA,OAAO;AAMH,IAAM,6BAA6B,aACvC,OAAO;AAAA,EACN,WAAW,aAAE,OAAO;AAAA,EACpB,YAAY,aAAE,OAAO;AAAA,EACrB,YAAY,aAAE,OAAO;AAAA,EACrB,aAAa,aAAE,OAAO,EAAE,IAAI,E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