@goodtiming/baton-sdk 0.5.1 → 0.5.2

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/metaCoordinates.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/safeScrub.ts","../src/integrations/mcp/runtimeAdapter.ts","../src/integrations/mcp/sessionResolution.ts","../src/dsn.ts","../src/integrations/mcp/errorResult.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","../src/integrations/mcp/oauthHooks.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 // The twelve resource/prompt lifecycle types (SPEC §11.4.4). Exported for\n // the reason `f1b7ab2` exported `ResultCaptureMode`: the rolled-up\n // `dist/index.d.ts` carries them transitively, because `Event` references\n // them, but WITHOUT `export` — so a vendor could not name one and had to\n // spell `Extract<Event, {event_type: \"resource_read_start\"}>` instead.\n ResourceListStartEvent,\n ResourceListStartPayload,\n ResourceListEndEvent,\n ResourceListEndPayload,\n ResourceListErrorEvent,\n ResourceListErrorPayload,\n ResourceReadStartEvent,\n ResourceReadStartPayload,\n ResourceReadEndEvent,\n ResourceReadEndPayload,\n ResourceReadErrorEvent,\n ResourceReadErrorPayload,\n PromptListStartEvent,\n PromptListStartPayload,\n PromptListEndEvent,\n PromptListEndPayload,\n PromptListErrorEvent,\n PromptListErrorPayload,\n PromptGetStartEvent,\n PromptGetStartPayload,\n PromptGetEndEvent,\n PromptGetEndPayload,\n PromptGetErrorEvent,\n PromptGetErrorPayload,\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 PrincipalWireSchema,\n ResourceListStartEventSchema,\n ResourceListStartPayloadSchema,\n ResourceListEndEventSchema,\n ResourceListEndPayloadSchema,\n ResourceListErrorEventSchema,\n ResourceListErrorPayloadSchema,\n ResourceReadStartEventSchema,\n ResourceReadStartPayloadSchema,\n ResourceReadEndEventSchema,\n ResourceReadEndPayloadSchema,\n ResourceReadErrorEventSchema,\n ResourceReadErrorPayloadSchema,\n PromptListStartEventSchema,\n PromptListStartPayloadSchema,\n PromptListEndEventSchema,\n PromptListEndPayloadSchema,\n PromptListErrorEventSchema,\n PromptListErrorPayloadSchema,\n PromptGetStartEventSchema,\n PromptGetStartPayloadSchema,\n PromptGetEndEventSchema,\n PromptGetEndPayloadSchema,\n PromptGetErrorEventSchema,\n PromptGetErrorPayloadSchema,\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\";\n// Exported for the reason `PrincipalIdMode` is, below: `BatonConfig\n// .resultCaptureMode` is typed with it, so a vendor cannot name the field's\n// type without it.\nexport type { ResultCaptureMode } 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// ⚠ `PrincipalWire` and `PrincipalForm` are NOT exported, for the same reason\n// `principalFor` is not: they are the PRODUCER's types, narrowed to the one\n// `source` and two `form`s this SDK emits. Nothing on the public surface can\n// produce one — `Event.principal` is inferred from `PrincipalWireSchema`,\n// whose members are deliberately open, so `event.principal` does not satisfy\n// the narrow type and a vendor naming it in a `Sink` signature gets TS2345.\n// A consumer wanting a name for the received shape uses\n// `z.infer<typeof PrincipalWireSchema>` or `Event[\"principal\"]`.\n// ⚠ **`HASH_SCHEME` was exported here until 0.4.1 and is GONE**, because there\n// is no prefix left for a vendor recomputing a pseudonym to match: a hashed\n// principal is the bare digest (SPEC §11.4, §13 entry 0.8.11). A vendor holding\n// the old constant gets a tagged value from its own copy and a bare one from\n// this SDK across the upgrade — a breaking removal, stated in the CHANGELOG.\n//\n// `principalFor` is NOT exported, and that is the deliberate half: it is the\n// single construction site for the wire object, and handing it out invites a\n// vendor to assemble a `principal` by hand, which is exactly the \"all three\n// members or nothing\" guarantee this change exists to make structural.\nexport {\n PRINCIPAL_FORM_HASHED,\n PRINCIPAL_FORM_RAW,\n PRINCIPAL_SOURCE_ASSERTED,\n hashPrincipalId,\n} from \"./identity.js\";\nexport type {\n AuthInfo,\n ResolvePrincipalHook,\n PrincipalResolutionContext,\n} from \"./integrations/mcp/index.js\";\n// The ready-made hooks — the OAuth case is common enough to ship, and a vendor\n// whose verifier keeps claims elsewhere writes their own (see `oauthHooks.ts`).\nexport { principalFromOAuthEmail, principalFromOAuthSub } 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.5.1\";\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\";\nimport type { PrincipalWire } from \"./identity.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 // SPEC §11.4: the producer declares it WITHHELD result-derived data.\n // Absent means CAPTURED, so no consumer needs a version table.\n //\n // `.optional()`, NOT `.default(null)`, for the reason recorded on\n // `ToolCallErrorPayloadSchema.result` below: a default makes this reader\n // an EMITTER, and parsing a stored event from before the member existed\n // would hand back an invented key.\n //\n // ⚠ **This package OMITS the member when capturing, where the Python SDK\n // sends `result_capture: null`.** Both are conformant and SPEC §11.4 says\n // so outright — absent and null are equivalent, and a consumer MUST read\n // the VALUE, never test for the key. It is the same axis `result` already\n // differs on between `baton-sdk` (null) and `baton-proxy` (omitted), per\n // §11.4.3. Omitting is chosen here because the alternative — matching\n // Python — would require regenerating `baton-spec`'s vectors from an\n // UNMERGED branch, pinning a key set no released producer emits.\n result_capture: z.string().nullable().optional(),\n })\n .strict();\nexport type ToolCallEndPayload = z.infer<typeof ToolCallEndPayloadSchema>;\n\n/** Emitted when the call FAILED, which MCP expresses two ways (SPEC §11.4.3):\n * the vendor handler throws, or it returns a result carrying MCP's error flag\n * on a 200. `error_type` is the error's constructor name for a throw and the\n * registered value `\"tool_error\"` for a returned flag; `error_body` is the\n * message or the unwrapped reason (PII-scrubbed, then capped — the limit and\n * its unit live on `ERROR_BODY_MAX_CODE_POINTS` in\n * `integrations/mcp/errorResult.ts`, which both failure legs cut with).\n *\n * ⚠ This schema ACCEPTED `result` one commit before this producer emitted\n * it (`67453eb`), and the split was deliberate. Unlike `baton-console`'s\n * ingest — which forbids unknown keys on the envelope only, leaving `payload`\n * an opaque dict — this schema is `.strict()` down to the payload, and\n * `test/conformance.test.ts` parses every `baton-spec` vector through it. So\n * the `baton-spec` bump carrying the field would have reddened this suite on\n * BOTH error vectors, the throw-shape one included, because it now carries\n * `result: null`. Accepting first is what made that bump safe.\n *\n * `result` carries the full result envelope on the returned shape and is null\n * on a throw, where no result object exists.\n *\n * ⚠ **THE shape claim for this field lives here; everywhere else points at\n * this paragraph.** On THIS producer `tool_call_error.result` and\n * `tool_call_end.result` are the SAME shape — the object the vendor's handler\n * returned, `{content, isError?}`, which neither major converts. The sentence\n * that stood here said `result` is \"deliberately NOT unwrapped the way\n * `tool_call_end.result` unwraps to the developer's return\"; that is Python's\n * contrast, carried over with the rest of the port, and it is FALSE here.\n * SPEC §11.4.3's requirement still binds — whatever is recorded must keep the\n * flag and the reason, which the literal does — but a consumer must not read\n * a TS-sourced `tool_call_end.result` as the bare content array Python's\n * vector shows.\n *\n * Enforced by `emitterConformance.test.ts`'s\n * `PAYLOAD_ALLOWED_TO_DIFFER[\"tool_call_error.returned\"]` and the two shape\n * assertions beside it: the claim stops being true the day that test reds. */\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 // ⚠ `.optional()`, NOT `.default(null)` like the sibling fields — and it\n // stays that way now that the producer emits the field.\n //\n // A default makes the schema an EMITTER: parsing a payload without the key\n // ADDS it. That is wrong in a schema that also READS — a stored event from\n // before the field existed would come back carrying an invented key, and\n // against the pre-`f1e0280` spec pin, whose `events.schema.json` is\n // `additionalProperties: false`, it reddened three tests saying so: a\n // byte-identical vector round-trip, an ajv validation of TS-built events,\n // and a field-for-field payload comparison.\n //\n // `.optional()` accepts the field when a vector carries it and stays\n // silent when it does not. What makes the EMITTED shape complete is the\n // emitter declaring `result` on both failure legs (`withBaton.ts`),\n // explicitly `null` on a throw — not the schema filling it in.\n result: z.unknown().nullable().optional(),\n // SPEC §11.4, on BOTH payloads because the RETURN failure shape withholds\n // `result` too. Same `.optional()` reasoning as the field above it, and\n // same omit-when-capturing posture as `ToolCallEndPayloadSchema`.\n result_capture: z.string().nullable().optional(),\n // SPEC §11.4.3: the producer NAMES a failure it made above the vendor's\n // handler. `tool_call_error` ONLY — unlike `result_capture`, which rides\n // both payloads — because the one case that files `tool_call_end` today\n // IS the false success this member exists to correct, so after the fix\n // nothing carries it on a success payload.\n //\n // A plain `z.string()` and NOT `z.enum(FAILURE_KINDS)`, which SPEC\n // requires rather than permits: a closed enum turns a later registered\n // value into a `ValidationError` on the vendor's tool-call path, which\n // §11.2 says must fail open. The registry in\n // `integrations/mcp/errorResult.ts` constrains what this producer EMITS;\n // it must not constrain what this schema READS.\n //\n // Same `.optional()`-not-`.default(null)` reasoning as the two fields\n // above: a default makes the schema an emitter, and parsing a stored\n // event from before the member existed would hand back an invented key.\n failure_kind: z.string().nullable().optional(),\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/** The principal as emitted — `{id, source, form}`, all three REQUIRED\n * together, plus an optional `display_name` (SPEC §11.4). The runtime shape\n * of `identity.PrincipalWire`.\n *\n * `.strict()` mirrors Python's `extra=\"forbid\"`: a member this producer does\n * not know about is a malformed object, not a richer one.\n *\n * ⚠ **`source` and `form` are `z.string()`, not enums, on purpose** — the same\n * decision `transport_observed` records and the collector's own columns make.\n * A fourth `source` is already foreseen (alias-derived), and an enum would\n * make this producer unable to emit a value SPEC registers later without a\n * release. Worse, it would throw at the emit boundary — `emit()` catches that\n * and DROPS the event, so the tool call survives and the capture does not,\n * which is still the wrong trade for a value SPEC may register later. The\n * safety lives in the consumer rules stated positively — trust only exactly\n * `\"attested\"`, treat anything but exactly `\"hashed\"` as personal data — so an\n * unregistered value fails safe without anything having to reject it. */\nexport const PrincipalWireSchema = z\n .object({\n id: z.string(),\n source: z.string(),\n form: z.string(),\n display_name: z.string().nullable().optional(),\n })\n .strict();\n\n// ⚠ **The producer type and this schema are two declarations of one wire\n// shape, and this is what makes them agree.** Every other wire type in this\n// file is projected with `z.infer`; this one cannot be, because the producer\n// side is deliberately NARROWER (literal `source`/`form`) than the parse side\n// (open `z.string()`) — see `identity.PrincipalWire`.\n//\n// Without the check below the drift is silent in the worst direction: add a\n// member to `PrincipalWire`, and `principalFor` compiles green while\n// `.strict()` rejects the object at the emit boundary, where `emit()` catches\n// the throw and DROPS the event. Capture loss with no error at the site of\n// the change. Asserting the KEY SETS match both ways turns that into a\n// compile error here.\ntype _PrincipalKeysMatch =\n [Exclude<keyof PrincipalWire, keyof z.infer<typeof PrincipalWireSchema>>] extends [never]\n ? [Exclude<keyof z.infer<typeof PrincipalWireSchema>, keyof PrincipalWire>] extends [never]\n ? true\n : never\n : never;\nconst _principalKeysMatch: _PrincipalKeysMatch = true;\nvoid _principalKeysMatch;\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 * `principal` is the resolved principal as emitted — `{id, source, form}`, all\n * three required together, hashed at the capture edge in the default mode so\n * the raw principal never leaves it; null when nobody was resolved.\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: PrincipalWireSchema.nullable().default(null),\n transport_observed: 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 // The RESOURCE and PROMPT lifecycles (SPEC §11.4.4). Twelve types whose\n // shapes were set by `baton-proxy`, which has been emitting all of them in\n // production — see the payload schemas below.\n \"resource_list_start\",\n \"resource_list_end\",\n \"resource_list_error\",\n \"resource_read_start\",\n \"resource_read_end\",\n \"resource_read_error\",\n \"prompt_list_start\",\n \"prompt_list_end\",\n \"prompt_list_error\",\n \"prompt_get_start\",\n \"prompt_get_end\",\n \"prompt_get_error\",\n]);\nexport type EventType = z.infer<typeof EventTypeSchema>;\n\n\n// =============================================================================\n// Resource and prompt lifecycle payloads (SPEC §11.4.4)\n// =============================================================================\n//\n// ⚠ **Transcribed from `baton_proxy.emitter`, field for field, because that\n// producer SHIPPED FIRST.** All twelve types have been reaching the Console in\n// production — whose ingest `EventType` lists every one of them — and until\n// the `baton-spec` bump that accompanies this file they had no schema anywhere.\n// So these do not design a shape, they RECORD one, and where the proxy's\n// choices look inconsistent the inconsistency is preserved and annotated: a\n// second producer must copy the shape rather than infer a rule from half of it.\n//\n// ⚠ **No `result_capture` on any of the twelve, and SPEC §11.4.4 makes that\n// normative rather than incidental.** None of these payloads carries a body —\n// a read records its URI and its timing, a list records a count — so there is\n// nothing for `\"off\"` to withhold. The `*_start` payloads DO carry caller data\n// in `params`, which is scrubbed like any other payload; §11.4 says outright\n// that the member is not a statement about request data.\n//\n// ⚠ **No `result` and no `failure_kind` on the six error payloads.** The error\n// flag is a TOOL concept: a failing resource read comes back as a JSON-RPC\n// error, so these carry only §11.4.3's RAISE analogue and that subsection's\n// RETURN discriminator has no counterpart here.\n\n/** `duration_ms`, written once. SPEC defines the member once and eight of the\n * twelve lifecycle payloads carry it, so widening it (to a float, say, or to\n * non-nullable) must not be an eight-site edit where a miss leaves two payload\n * families disagreeing about a member the spec gives one definition. Same\n * spread idiom `envelopeShape` already establishes below. */\nconst timingShape = { duration_ms: z.number().int().nullable().default(null) };\n\n/** The two members every lifecycle FAILURE payload carries, plus its timing.\n * See `ResourceReadErrorPayloadSchema` for how `error_type` is spelled across\n * producers and why `error_body` is kept under every capture mode. */\nconst failureShape = { error_type: z.string(), error_body: z.string(), ...timingShape };\n\n/** `resources/list` reached the server. Deliberately EMPTY — a list request\n * has no subject, and the envelope already names the session, the tenant and\n * the vendor. `.strict()` with no members is the claim, not an oversight. */\nexport const ResourceListStartPayloadSchema = z.object({}).strict();\nexport type ResourceListStartPayload = z.infer<typeof ResourceListStartPayloadSchema>;\n\n/** `resources/list` returned.\n *\n * ⚠ `count` counts the `resources` array ALONE. Resource TEMPLATES are a\n * separate MCP method with their own result array and are not added in, so a\n * template-only server reports `0` — correctly — and a consumer MUST NOT read\n * that as \"this server has no resources\". */\nexport const ResourceListEndPayloadSchema = z\n .object({\n count: z.number().int(),\n ...timingShape,\n })\n .strict();\nexport type ResourceListEndPayload = z.infer<typeof ResourceListEndPayloadSchema>;\n\n/** `resources/list` failed. See `ResourceReadErrorPayloadSchema` for how\n * `error_type` is spelled across producers and why `error_body` is kept. */\nexport const ResourceListErrorPayloadSchema = z\n .object({\n ...failureShape,\n })\n .strict();\nexport type ResourceListErrorPayload = z.infer<typeof ResourceListErrorPayloadSchema>;\n\n/** `resources/read` reached the server.\n *\n * ⚠ **`uri` is ALSO inside `params`.** The proxy builds `params` by removing\n * `_meta` from the request's params and nothing else, and `uri` is one of\n * them — so the subject appears twice. Recorded rather than deduplicated: the\n * dedicated member is what a consumer reads, the bag is what the caller\n * actually sent, and a producer that stripped `uri` out of it would stop being\n * able to say that. */\nexport const ResourceReadStartPayloadSchema = z\n .object({\n uri: z.string(),\n /** The caller's own request params, PII-scrubbed (SPEC §7).\n *\n * ⚠ Nullable because the SCHEMA permits it, not because this producer\n * emits it: `withBaton`'s `paramsBag` answers `{}` for an absent bag,\n * matching `baton-proxy` (`dict(params) if params else {}` — it never\n * emits null). A consumer must still read both, since the schema admits\n * both and a third producer may choose either. */\n params: z.record(z.string(), z.unknown()).nullable().default(null),\n })\n .strict();\nexport type ResourceReadStartPayload = z.infer<typeof ResourceReadStartPayloadSchema>;\n\n/** `resources/read` returned.\n *\n * ⚠ **No content member, and that is the design.** The resource BODY is\n * customer data of exactly the kind the response-capture switch exists to keep\n * off the wire, and the only producer there was never sent it. URI plus timing\n * is what makes a failing or slow read visible without it. */\nexport const ResourceReadEndPayloadSchema = z\n .object({\n uri: z.string(),\n ...timingShape,\n })\n .strict();\nexport type ResourceReadEndPayload = z.infer<typeof ResourceReadEndPayloadSchema>;\n\n/** `resources/read` failed.\n *\n * ⚠ **`error_type` is an unconstrained string and the producers do NOT agree\n * on how to spell it** — stated here for all six error payloads.\n * `baton-proxy` reads the WIRE, so it holds the upstream's JSON-RPC error and\n * files the numeric `code` as a string; this package holds a live exception\n * and files its class name, the way §11.4.3's RAISE shape already does for\n * tools. Both conform — §11.4.3 says this member separates SHAPES and is not a\n * closed set of values — and a consumer MUST NOT read one producer's spelling\n * as the vocabulary.\n *\n * ⚠ **`error_body` is KEPT under every capture mode.** It is a failed FETCH's\n * message, not anything a resource returned, so nothing here is\n * result-derived. */\nexport const ResourceReadErrorPayloadSchema = z\n .object({\n uri: z.string(),\n ...failureShape,\n })\n .strict();\nexport type ResourceReadErrorPayload = z.infer<typeof ResourceReadErrorPayloadSchema>;\n\n/** `prompts/list` reached the server. Empty, for the reason\n * `ResourceListStartPayloadSchema` carries. */\nexport const PromptListStartPayloadSchema = z.object({}).strict();\nexport type PromptListStartPayload = z.infer<typeof PromptListStartPayloadSchema>;\n\n/** `prompts/list` returned. `count` counts the `prompts` array. */\nexport const PromptListEndPayloadSchema = z\n .object({\n count: z.number().int(),\n ...timingShape,\n })\n .strict();\nexport type PromptListEndPayload = z.infer<typeof PromptListEndPayloadSchema>;\n\n/** `prompts/list` failed. See `ResourceReadErrorPayloadSchema`. */\nexport const PromptListErrorPayloadSchema = z\n .object({\n ...failureShape,\n })\n .strict();\nexport type PromptListErrorPayload = z.infer<typeof PromptListErrorPayloadSchema>;\n\n/** `prompts/get` reached the server.\n *\n * ⚠ **`params` is the request's `arguments` member ALONE, not the whole params\n * bag** — the opposite of `ResourceReadStartPayloadSchema`'s choice, measured\n * in the proxy. The two are inconsistent in the only producer that existed;\n * the inconsistency is recorded so a reader does not expect `name` inside\n * `params` the way `uri` does appear there. */\nexport const PromptGetStartPayloadSchema = z\n .object({\n name: z.string(),\n /** The prompt's arguments, PII-scrubbed (SPEC §7). `{}` from this producer\n * where the request supplied none — see `ResourceReadStartPayloadSchema`'s\n * `params` for why the schema is nullable anyway. */\n params: z.record(z.string(), z.unknown()).nullable().default(null),\n })\n .strict();\nexport type PromptGetStartPayload = z.infer<typeof PromptGetStartPayloadSchema>;\n\n/** `prompts/get` returned.\n *\n * ⚠ **No rendered messages.** A prompt's text is authored by the SERVER rather\n * than fetched by a tool, so whether it is customer content at all is a\n * decision nobody has taken — and the standing answer, from the only producer,\n * is that it does not egress. */\nexport const PromptGetEndPayloadSchema = z\n .object({\n name: z.string(),\n ...timingShape,\n })\n .strict();\nexport type PromptGetEndPayload = z.infer<typeof PromptGetEndPayloadSchema>;\n\n/** `prompts/get` failed. See `ResourceReadErrorPayloadSchema`. */\nexport const PromptGetErrorPayloadSchema = z\n .object({\n name: z.string(),\n ...failureShape,\n })\n .strict();\nexport type PromptGetErrorPayload = z.infer<typeof PromptGetErrorPayloadSchema>;\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// ⚠ The twelve lifecycle events carry the SAME `envelopeShape` as the five\n// above, which is what lets one collector endpoint accept all seventeen and\n// one worker order them on `(session_id, sequence_number)`. `call_id` stays\n// absent on them: no producer mints one for these types, so SPEC §11.5.4's\n// FIFO floor is all a consumer has for pairing — recorded rather than fixed.\n\nexport const ResourceListStartEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"resource_list_start\").default(\"resource_list_start\"),\n payload: ResourceListStartPayloadSchema,\n })\n .strict();\nexport type ResourceListStartEvent = z.infer<typeof ResourceListStartEventSchema>;\n\nexport const ResourceListEndEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"resource_list_end\").default(\"resource_list_end\"),\n payload: ResourceListEndPayloadSchema,\n })\n .strict();\nexport type ResourceListEndEvent = z.infer<typeof ResourceListEndEventSchema>;\n\nexport const ResourceListErrorEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"resource_list_error\").default(\"resource_list_error\"),\n payload: ResourceListErrorPayloadSchema,\n })\n .strict();\nexport type ResourceListErrorEvent = z.infer<typeof ResourceListErrorEventSchema>;\n\nexport const ResourceReadStartEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"resource_read_start\").default(\"resource_read_start\"),\n payload: ResourceReadStartPayloadSchema,\n })\n .strict();\nexport type ResourceReadStartEvent = z.infer<typeof ResourceReadStartEventSchema>;\n\nexport const ResourceReadEndEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"resource_read_end\").default(\"resource_read_end\"),\n payload: ResourceReadEndPayloadSchema,\n })\n .strict();\nexport type ResourceReadEndEvent = z.infer<typeof ResourceReadEndEventSchema>;\n\nexport const ResourceReadErrorEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"resource_read_error\").default(\"resource_read_error\"),\n payload: ResourceReadErrorPayloadSchema,\n })\n .strict();\nexport type ResourceReadErrorEvent = z.infer<typeof ResourceReadErrorEventSchema>;\n\nexport const PromptListStartEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"prompt_list_start\").default(\"prompt_list_start\"),\n payload: PromptListStartPayloadSchema,\n })\n .strict();\nexport type PromptListStartEvent = z.infer<typeof PromptListStartEventSchema>;\n\nexport const PromptListEndEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"prompt_list_end\").default(\"prompt_list_end\"),\n payload: PromptListEndPayloadSchema,\n })\n .strict();\nexport type PromptListEndEvent = z.infer<typeof PromptListEndEventSchema>;\n\nexport const PromptListErrorEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"prompt_list_error\").default(\"prompt_list_error\"),\n payload: PromptListErrorPayloadSchema,\n })\n .strict();\nexport type PromptListErrorEvent = z.infer<typeof PromptListErrorEventSchema>;\n\nexport const PromptGetStartEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"prompt_get_start\").default(\"prompt_get_start\"),\n payload: PromptGetStartPayloadSchema,\n })\n .strict();\nexport type PromptGetStartEvent = z.infer<typeof PromptGetStartEventSchema>;\n\nexport const PromptGetEndEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"prompt_get_end\").default(\"prompt_get_end\"),\n payload: PromptGetEndPayloadSchema,\n })\n .strict();\nexport type PromptGetEndEvent = z.infer<typeof PromptGetEndEventSchema>;\n\nexport const PromptGetErrorEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"prompt_get_error\").default(\"prompt_get_error\"),\n payload: PromptGetErrorPayloadSchema,\n })\n .strict();\nexport type PromptGetErrorEvent = z.infer<typeof PromptGetErrorEventSchema>;\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 ResourceListStartEventSchema,\n ResourceListEndEventSchema,\n ResourceListErrorEventSchema,\n ResourceReadStartEventSchema,\n ResourceReadEndEventSchema,\n ResourceReadErrorEventSchema,\n PromptListStartEventSchema,\n PromptListEndEventSchema,\n PromptListErrorEventSchema,\n PromptGetStartEventSchema,\n PromptGetEndEventSchema,\n PromptGetErrorEventSchema,\n]);\n/** ⚠ DERIVED, not hand-listed. It used to be a third list of the same\n * seventeen members, after `EventTypeSchema` and `EventSchema`'s own branches,\n * and the twelve lifecycle types made that visible: three lists to keep in\n * step. `EventSchema` is the discriminated union over exactly these schemas,\n * so its inferred output type IS this union — verified mutually assignable\n * against the hand-written version before the switch.\n *\n * `EventTypeSchema` stays hand-written on purpose: `test/packaging.test.ts`\n * derives its export guard FROM it, which makes it the source of truth rather\n * than a fourth copy. */\nexport type Event = z.infer<typeof EventSchema>;\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` — the latter on FAILURE, which MCP expresses two ways\n * (SPEC §11.4.3): the vendor handler throws, or it returns a result carrying\n * MCP's error flag on a 200. Reading only the first is what this package did,\n * and what §6.1's own wording told it to. Injects server `instructions`\n * (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 is not here yet\" 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 { AsyncLocalStorage } from \"node:async_hooks\";\nimport { v7 as uuidv7 } from \"uuid\";\nimport {\n AnnotationEventSchema,\n type Event,\n PromptGetEndEventSchema,\n PromptGetErrorEventSchema,\n PromptGetStartEventSchema,\n PromptListEndEventSchema,\n PromptListErrorEventSchema,\n PromptListStartEventSchema,\n ResourceListEndEventSchema,\n ResourceListErrorEventSchema,\n ResourceListStartEventSchema,\n ResourceReadEndEventSchema,\n ResourceReadErrorEventSchema,\n ResourceReadStartEventSchema,\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 { scrubOrNull } from \"./safeScrub.js\";\nimport { roundMetaCoordinates } from \"../../metaCoordinates.js\";\nimport {\n resolveBatonConfig,\n resolveTenantId,\n resolvePrincipalIdHmacKey,\n type BatonConfig,\n} from \"./config.js\";\nimport { captureDisabled, DisabledSink, logDisabled } from \"../../optout.js\";\nimport { capCodePoints } from \"../../_text.js\";\nimport { emit } from \"./emit.js\";\nimport {\n ERROR_BODY_MAX_CODE_POINTS,\n endResultFields,\n errorText,\n type FailureKind,\n OUTPUT_SCHEMA_MISMATCH,\n requestSideErrorFields,\n requestSideFailureKind,\n type ResultCaptureMode,\n type ToolEntryFacts,\n resultDerivedFields,\n returnedErrorFields,\n isErrorResult,\n TOOL_ERROR_TYPE,\n} from \"./errorResult.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, observeTransport, 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 resolveCallPrincipal,\n warnIfIdentityCannotResolve,\n} from \"./principalResolution.js\";\nimport type { PrincipalIdMode } from \"../../identity.js\";\nimport { SessionCounter } from \"./sessionCounter.js\";\nimport {\n advertiseUserGoalRequired,\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 /** Whether result-derived data is withheld (SPEC §11.4). Validated once at\n * the config door, like `intentParamMode`, so nothing downstream re-checks\n * it. */\n resultCaptureMode: ResultCaptureMode;\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`, `server.server._serverInfo` and\n// `server.server._requestHandlers` (with the `setRequestHandler` that fills\n// it, for the `tools/list` seam) 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/**\n * What the OUTER `tools/call` seam saw once the request handler was done with\n * it — the only thing the outer tells the inner.\n *\n * Both majors convert a thrown vendor handler into a returned `isError`\n * INSIDE their `tools/call` handler, so `raised` here is NOT the vendor's\n * raise: it is a failure the SDK threw out of the handler entirely, which on\n * v2 is how an unknown or disabled tool arrives\n * (`mcp-DXXb3Vv3.mjs:1394-1397`, both outside that handler's own `try`).\n */\ntype OuterOutcome = { failed: boolean } & (\n | {\n /** `tools/call` THREW. Its own member rather than `err !== undefined`,\n * because `throw undefined` is legal and must not read as a return. */\n raised: true;\n /** The value thrown out of `tools/call`. */\n err: unknown;\n }\n | {\n raised: false;\n /** What `tools/call` returned. On a failure this is the SDK's own error\n * envelope — `createToolError`'s on both majors — not the vendor's\n * value. */\n result: unknown;\n }\n);\n\n/** `tools/call` came back cleanly. A constant because it is the initial value\n * AND the outcome handed to a flush that is not the outer's to judge — two\n * sites, and a fifth member on `OuterOutcome` must not reach only one. */\nconst CLEAN_OUTCOME: OuterOutcome = { failed: false, raised: false, result: undefined };\n\n/**\n * The per-call hand-off between Baton's two seams (SPEC §11.4.3's\n * `failure_kind`).\n *\n * ⚠ **`innerFired` is the discriminator for REQUEST-side vs result-side, and\n * it is the one the withholding rule needs too** — which is why the slot\n * carries no second field for it. `false` means the vendor's handler never ran, so the failure is\n * REQUEST-side and nothing on the payload is derived from a result (`\"off\"`\n * withholds nothing). `true` plus a failure at the outer means the handler\n * returned and something above it rejected what came back, so the failure is\n * RESULT-side and `\"off\"` withholds it. The hand-off and the provenance rule\n * are one mechanism; measured 2026-10-01 on both majors.\n *\n * ⚠ **It is not, however, the ONLY fact the settle reads, and an earlier\n * version of this paragraph said it was.** `settleCall` reads\n * `flushTerminal !== null` FIRST, so the real state space has three members —\n * inner unreached, inner reached but parked nothing (`openCall` threw), inner\n * reached and parked — and the third is subdivided by WHICH lane parked. That\n * last fact travels as the choice between `parkFailure` and `parkSuccess`\n * rather than as a field, which is what let the claim read as true.\n *\n * ⚠ **`flushTerminal` exists because two terminal events on one `call_id`\n * would break pairing** (SPEC §11.5.4 tier 1). The inner has already decided\n * which terminal event this call deserves by the time the outer learns the\n * call failed, so it PARKS that decision as a closure instead of emitting it,\n * and the outer flushes or replaces it. Parking a closure and not a built\n * event is deliberate: `counter.next` and `captured_at` must run at FLUSH, or\n * a replaced `tool_call_end` leaves an allocated sequence number behind and\n * the session's numbering gains a hole no consumer can explain.\n */\ninterface CallSlot {\n /** Set at the TOP of `batonWrap`, before anything that can throw.\n *\n * ⚠ The placement agrees with both majors by construction, not by luck:\n * each runs `validateToolInput` OUTSIDE the executor this wraps\n * (`mcp.js:125`, `mcp-DXXb3Vv3.mjs:1399`), so a rejected argument cannot\n * reach here and mark the flag. `test/integrations/mcp/aboveTool.test.ts`\n * pins that per major — a placement one line lower would still pass the\n * happy path and silently relabel every `invalid_argument`. */\n innerFired: boolean;\n /** The inner's parked terminal event, or `null` when the inner never got\n * far enough to decide on one (its own prelude threw — nothing to flush,\n * and NOT a request-side failure). */\n flushTerminal: ((outcome: OuterOutcome) => Promise<void>) | null;\n}\n\n/** Module-scoped rather than per-install, which is safe for one reason worth\n * naming: a slot is only ever read inside the dynamic extent of the dispatch\n * that created it, and `AsyncLocalStorage` nests — a tool whose handler calls\n * a second seamed server in-process enters that server's slot first, so the\n * inner wrapper there reads its own, not ours. Nothing is shared BETWEEN\n * calls, so there is no per-install state to keep. */\nconst callSlots = new AsyncLocalStorage<CallSlot>();\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/**\n * `error_body` for either failure shape (SPEC §11.4.3), so the two legs cannot\n * drift apart on the one rule they share.\n *\n * ⚠ **Scrub, THEN cut.** A PII value straddling the boundary must reach the\n * scrubber whole; cutting first hands it a fragment no pattern matches, and\n * the surviving half ships unredacted. ⚠ **Cut by CODE POINT** —\n * `capCodePoints` carries that reasoning, and Python's `[:2000]` counts code\n * points, so this is also what makes the two producers agree on what the cap\n * means in the one payload `emitterConformance.test.ts` compares\n * field-for-field.\n */\nfunction errorBody(ctx: WrapContext, text: string): string {\n // eslint-disable-next-line no-restricted-syntax -- called only from emit() build thunks, so emit's guard already covers a throw here\n return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);\n}\n\n/** `error_type` for a THROWN value (SPEC §11.4.3's RAISE shape): the\n * exception's class name, `\"Error\"` for anything that is not one. Shared by\n * the inner wrapper's raise lane and the outer seam, which both have to spell\n * it — two spellings would let the same thrown `ProtocolError` arrive under\n * two labels depending on which seam reported it. */\nfunction errorTypeOf(err: unknown): string {\n return err instanceof Error ? err.constructor.name : \"Error\";\n}\n\n/** The human-readable text of a thrown value, by the same rule. */\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** The envelope members every event shares, resolved off one MCP request —\n * everything except `principal`, which is deliberately not in here.\n *\n * Split out of `openCall` so the resource and prompt lifecycle seams (SPEC\n * §11.4.4) can build an envelope without the parts that are specific to a tool\n * call: there is no `principal` on those (see `installLifecycleSeam`), no\n * intent-param strip, and no `call_id`.\n *\n * Returns the PARTS rather than an assembled `common` so each caller spells its\n * own literal, which keeps `openCall` reading as one object and keeps\n * `principal` out of a shape that has no business resolving it.\n *\n * ⚠ **NOT for key order, which a first version of this paragraph claimed.**\n * Zod v4 emits output keys in SHAPE order, not input order, so\n * `envelopeShape` fixes the wire order however a caller spells its literal.\n * Recorded because the wrong reason is the kind a later reader preserves. */\nasync function resolveEnvelopeParts(\n ctx: WrapContext,\n extra: Extra,\n): Promise<{ sessionId: string; runtime: string; scrubbedMeta: unknown }> {\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 // Coordinates are coarsened here: after the ladder above has read the\n // raw meta, and before the vendor's scrubber, so a vendor scrubber still\n // gets the rule (handoff D5). `_meta` only; params and results keep\n // full precision. The annotation tool does the same.\n const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, \"_meta\");\n const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);\n return { sessionId, runtime, scrubbedMeta };\n}\n\n/**\n * Open a tool call: resolve everything the envelope needs, strip Baton's\n * injected intent params out of `params` IN PLACE, and emit the opening\n * events — the session's first proactive annotation, when there is one, then\n * `tool_call_start`.\n *\n * ⚠ **Extracted so BOTH seams open a call the same way.** The inner executor\n * wrapper opens a call that reached the vendor's handler; the outer\n * `tools/call` seam opens one the SDK rejected before the handler ran (SPEC\n * §11.4.3's three request-side `failure_kind`s), and those events must carry\n * the same identity, the same `principal`, the same stripped `params` and the\n * same `call_id` discipline. Two copies of this would be two chances for one\n * of them to drift — which is the miss-mechanism this thread has already paid\n * for twice.\n *\n * Returns what the TERMINAL event needs and nothing more: the envelope, the\n * minted `call_id`, and the session the counter is keyed on.\n */\nasync function openCall(\n ctx: WrapContext,\n toolName: string,\n extra: Extra,\n params: Record<string, unknown>,\n /** Is there a registry entry for this tool? `false` only from the\n * `tools/call` seam's `unknown_tool` path, and it suppresses one warning\n * whose diagnosis would be wrong there — see `extractGoalParam`. */\n registered = true,\n): Promise<{ common: Record<string, unknown>; callId: string; sessionId: string }> {\n // ⚠ HERE, not in the callers. It was a caller obligation in both of them,\n // and this function exists precisely so the two cannot drift — a third\n // caller inheriting \"remember the snapshot first\" would silently stop\n // emitting it, which is the drift `openCall` was extracted to prevent. The\n // ordering invariant (snapshot BEFORE `tool_call_start`) is preserved and is\n // now structural.\n await maybeEmitSurfaceSnapshot(ctx);\n const { sessionId, runtime, scrubbedMeta } = await resolveEnvelopeParts(ctx, 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, registered);\n const rawExpected = extractGoalParam(\n params,\n EXPECTED_RESULT_PARAM_NAME,\n toolName,\n dispositions,\n registered,\n );\n const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions, registered);\n // Guarded because `params` is already stripped in place above.\n const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);\n const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);\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 = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);\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 principal = await resolveCallPrincipal(\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 five `...common` sites below are the tool-call legs — start, end,\n // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive\n // annotation, the same five Python stamps (`middleware.py`\n // 503/547/586/644/674; it was four until the returned shape landed\n // there too). `surface_snapshot` is deliberately NOT among them: it\n // describes the SERVER and is captured outside any call, so there is no\n // caller to name (register D5).\n principal,\n // Same five stamps, same exclusion: a surface_snapshot describes the\n // SERVER and is captured outside any call, so it has no caller's\n // transport to name any more than it has a caller to name.\n transport_observed: observeTransport(extra),\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 // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw drops the event, which is correct for params\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 return { common, callId, sessionId };\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 // ⚠ FIRST, ahead of every await below. The flag's whole job is to say the\n // vendor's handler was REACHED, and a line of this prelude that threw\n // after a later assignment would leave the outer seam reporting a\n // request-side failure about a call that got this far. See `CallSlot`.\n const slot = callSlots.getStore();\n if (slot) slot.innerFired = true;\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 // ⚠ `params` is the SAME object forwarded to the vendor's handler, and\n // `openCall` strips Baton's injected intent params out of it IN PLACE —\n // which is what keeps `user_goal`/`expected_result` off the tool AND out\n // of the captured `params`, since those must equal the vendor-visible\n // arguments. The outer seam's request-side path passes a COPY instead,\n // for the reason stated there.\n const { common, callId, sessionId } = await openCall(ctx, toolName, extra, params);\n\n /** Emit this call's terminal event, or PARK it for the outer `tools/call`\n * seam when one is running (see `CallSlot`). `replacement` is passed by\n * the SUCCESS lane alone: it is the only terminal event the outer may\n * overwrite, because a parked FAILURE is already the vendor's own code\n * speaking — it raised, or it returned the flag — and SPEC §11.4.3's two\n * shapes own it. Relabelling that as `output_schema_mismatch` would blame\n * our conversion for the vendor's failure. */\n const terminate = async (\n build: () => Event,\n replacement: ((outcome: OuterOutcome) => Event) | null,\n ): Promise<void> => {\n if (!slot) {\n // No outer seam: a direct executor call, or a server whose internals\n // this package could not reach. Emit exactly as it always has — and\n // SPEC §11.4.3 agrees that is the right degradation, since \"a\n // producer with only one seam cannot emit `failure_kind` correctly\n // and MUST omit it\".\n await emit(ctx.sink, build);\n return;\n }\n // ⚠ **A parked terminal already here belongs to an EARLIER-completING\n // call in this same dispatch, and flushing it now is what keeps it from\n // being dropped.** The slot holds one decision, and parking without\n // this would overwrite it: a `tool_call_start` with no terminal, which\n // SPEC §11.5.4 leaves permanently unpaired. Two shapes reach it, one\n // probed and one read:\n //\n // - a vendor handler that invokes a SIBLING tool's wrapped executor\n // in-process — the inner call completes first, so the outer's park\n // lands second and used to erase it;\n // - v2's legacy `inputRequired` shim, which loops\n // `await handler(request, ctxNext)` inside ONE dispatch\n // (`mcp-DXXb3Vv3.mjs:602`), so every round but the last parks and\n // is immediately superseded.\n //\n // The earlier one is flushed UNREPLACED, which is the correct reading\n // rather than a convenience: the outer's outcome describes the call\n // `tools/call` itself dispatched, and that call is always the LAST to\n // decide, because its own `await` encloses everything it called.\n // Relabelling an inner call's success `output_schema_mismatch` would\n // blame whichever round happened to finish first.\n const earlier = slot.flushTerminal;\n if (earlier !== null) await earlier(CLEAN_OUTCOME);\n slot.flushTerminal = async (outcome) => {\n // The choice is made INSIDE the thunk, so either branch allocates its\n // sequence number at flush — the property `CallSlot` exists to keep.\n await emit(ctx.sink, () =>\n replacement !== null && outcome.failed ? replacement(outcome) : build(),\n );\n };\n };\n\n /** Park a terminal event the outer seam may NOT overwrite — the vendor's\n * own code spoke, by raising or by returning the flag, and SPEC §11.4.3's\n * two shapes own it. */\n const parkFailure = (build: () => Event): Promise<void> => terminate(build, null);\n\n /** Park the SUCCESS terminal, with what to emit instead if the outer seam\n * saw the call fail anyway.\n *\n * ⚠ Two functions rather than one optional parameter, so \"only the success\n * lane is replaceable\" is a thing the type system enforces instead of a\n * paragraph a future caller can skip. The invariant used to live only in\n * `terminate`'s docstring, where adding a replacement to the `isError`\n * lane would have compiled, passed every test, and relabelled the\n * vendor's own exception as our conversion's. */\n const parkSuccess = (\n build: () => Event,\n replacement: (outcome: OuterOutcome) => Event,\n ): Promise<void> => terminate(build, replacement);\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 await parkFailure(() =>\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: errorTypeOf(err),\n // ⚠ KEPT under `resultCaptureMode: \"off\"`, and that is the rule's\n // shape rather than an exception to it: the rule is keyed on\n // PROVENANCE, and a thrown error's message is the vendor's own\n // code speaking about a call that returned nothing (SPEC\n // §11.4.3(1)). A switch written as \"drop `error_body`\" would\n // delete the highest-value diagnostic the product has.\n error_body: errorBody(ctx, messageOf(err)),\n duration_ms: durationMs,\n // Explicit, though the field is `.optional()` and this is its\n // absent value. The schema is deliberately not an emitter (see\n // `ToolCallErrorPayloadSchema`), so if this leg stayed silent the\n // key would be missing. Each of the two failure shapes declares\n // which it is, the same reason Python's emitter made the parameter\n // positional-without-default.\n //\n // ⚠ Guarded by `errorResult.test.ts`'s `toContain(\"result\")`, NOT by\n // the cross-SDK key-set check — measured by removing this line. Why,\n // at one site: `endResultFields` in `errorResult.ts`. SPEC §11.4.3\n // states the same void rationale and wants the same amendment.\n result: null,\n },\n }),\n );\n throw err;\n }\n\n const durationMs = Math.round(performance.now() - startedAt);\n\n // The OTHER failure shape (SPEC §11.4.3): the handler returned normally\n // and the result carries MCP's error flag, which rides a 200 rather than a\n // JSON-RPC error. It arrives here rather than through the catch above, and\n // filing it as `tool_call_end` is filing a failure as a success.\n if (isErrorResult(result)) {\n await parkFailure(() =>\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: TOOL_ERROR_TYPE,\n duration_ms: durationMs,\n // Both remaining members are unwrapped FROM the result on this\n // shape, so one projection decides them together and owns the\n // scrubber call. `error_type` is NOT result-derived and is passed\n // regardless: the call still failed (SPEC §11.2.6).\n //\n // ⚠ Under `\"full\"` `result` is the whole envelope, and on this\n // producer that is the same shape `tool_call_end.result` records —\n // which is NOT what Python's contrast says.\n // `ToolCallErrorPayloadSchema` in `events.ts` holds that claim and\n // names the test that enforces it.\n ...returnedErrorFields(\n ctx.resultCaptureMode,\n result,\n (text) => errorBody(ctx, text),\n ctx.scrubber,\n ),\n },\n }),\n );\n // Returned, never thrown. The vendor chose to report this failure as a\n // value, and §11.2 says a sensor does not change what the caller sees.\n return result;\n }\n\n await parkSuccess(\n () =>\n ToolCallEndEventSchema.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 duration_ms: durationMs,\n ...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber),\n },\n }),\n // The handler returned something this sensor reads as a success, and\n // then the outer seam saw the call fail anyway — so what failed is the\n // producer's own conversion of the output (SPEC §11.4.3's\n // `output_schema_mismatch`). Correcting this is the whole point of the\n // second seam: without it this is a `tool_call_end` for a call the\n // CALLER saw fail, which is a success the product invented.\n (outcome) =>\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 // The lane the OUTER came back on, not this one's: on 2.x the\n // conversion failure is converted to a returned `isError` inside\n // `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `\"tool_error\"` is\n // right there. A throw out of the handler is unreachable on\n // either major today for this lane; spelled anyway, because the\n // alternative is a crash on the day it stops being.\n error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,\n // ⚠ The INNER's measurement — the vendor's handler duration —\n // not the outer's. Every other leg means the same thing by this\n // member, and widening it here for one failure kind would make\n // `duration_ms` mean two things in one column.\n duration_ms: durationMs,\n failure_kind: OUTPUT_SCHEMA_MISMATCH,\n // ⚠ **WITHHELD under `\"off\"`, unlike the three request-side\n // kinds.** The message quotes the value the tool returned\n // (\"`'not-an-int'` is not of type `integer`\"), so it is\n // result-derived by provenance and goes — which leaves\n // `failure_kind` as the ONLY surviving signal for this failure\n // under `\"off\"`, and is the measurement that justified putting\n // the member on the wire at all.\n //\n // ⚠ `result` is what the CLIENT received — the SDK's own error\n // envelope — not the vendor's rejected return value. §11.4.3\n // asks for the envelope that holds the flag and the reason, and\n // this package's own invariant is that it agrees with the\n // caller. Recording the rejected output TOO would need a member\n // nothing on the wire has; the loss is deliberate and worth\n // knowing when debugging one of these.\n ...resultDerivedFields(\n ctx.resultCaptureMode,\n () => (outcome.raised ? messageOf(outcome.err) : errorText(outcome.result)),\n // ⚠ `null` on the `raised` lane, never `undefined`, and the\n // union is what forces the branch rather than a comment: the\n // scrubber would answer `undefined` and DROP the key, where the\n // sibling raise lane a few lines up declares `result: null`\n // explicitly, for the reason `ToolCallErrorPayloadSchema`\n // records. One shape for \"no result object existed\", not two.\n outcome.raised ? null : outcome.result ?? null,\n (text) => errorBody(ctx, text),\n ctx.scrubber,\n ),\n },\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 registered: boolean,\n): string | null {\n if (!(paramName in args)) return null;\n const disposition = dispositions ? dispositions[paramName] : undefined;\n if (disposition === \"native\") return null;\n // ⚠ The warning says \"cold registry\", which is a real and useful diagnosis\n // for a tool that EXISTS and was never wired — and a wrong one for a tool\n // that does not exist at all. The `tools/call` seam reaches here for an\n // unknown tool, where there is no entry to have been wired, so the caller\n // says which case it is rather than letting this infer it from an absent\n // disposition that means two different things.\n if (disposition === undefined && registered) {\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, ctx.intentParamMode)\n : injectGoalParams(mutable.inputSchema, ctx.intentParamMode);\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/** The two request-handler internals the request seams reach, shared by both\n * majors' `Protocol`: the per-method dispatch map, and the setter that fills\n * it. Typed `unknown` and checked at install, so a server laid out\n * differently gets no seam rather than a crash. */\ninterface RequestHandlerInternals {\n _requestHandlers?: unknown;\n setRequestHandler?: unknown;\n}\n\nconst TOOLS_LIST_METHOD = \"tools/list\";\nconst TOOLS_LIST_SEAM = Symbol(\"batonToolsListSeam\");\nconst TOOLS_CALL_METHOD = \"tools/call\";\nconst TOOLS_CALL_SEAM = Symbol(\"batonToolsCallSeam\");\ntype SeamedHandler = AnyHandler & { [tag: symbol]: boolean | undefined };\n\n/**\n * Install a seam around ONE JSON-RPC method's request handler.\n *\n * Both majors dispatch requests through `server.server._requestHandlers`, a\n * `Map` keyed by method and read per request (1.x `shared/protocol.js`\n * `_onrequest`; v2 `Protocol._onrequest`), and both `McpServer`s install\n * their tool handlers lazily, on the first `registerTool` (v2 also eagerly,\n * when constructed with a `tools` capability). So both orders are covered: a\n * handler already in the map is wrapped now, and `setRequestHandler` is\n * patched so one set later is wrapped as it lands. Keyed on the map entry\n * rather than on the setter's arguments, because the majors spell the method\n * differently (a zod schema on 1.x, a string on v2) and both land in the same\n * map.\n *\n * ⚠ **Shared by both seams, which is what makes installing two of them\n * safe.** Each one patches `setRequestHandler`, so the second install must\n * reach the first's patch rather than the pristine setter — which it does,\n * because `originalSet` is read at install time, after the earlier patch has\n * landed. That composition held when this was one hand-written function per\n * seam too; one helper makes it structural rather than a property of the call\n * order in `withBaton`.\n *\n * ⚠ A server whose internals do not have this shape gets no seam at all.\n * What that costs differs per seam and is stated at each call site.\n */\nfunction installRequestSeam(\n lowLevel: RequestHandlerInternals,\n method: string,\n seamTag: symbol,\n wrap: (handler: AnyHandler) => AnyHandler,\n): void {\n const table = lowLevel._requestHandlers;\n const originalSet = lowLevel.setRequestHandler;\n if (!(table instanceof Map) || typeof originalSet !== \"function\") return;\n const handlers = table as Map<string, unknown>;\n const setRequestHandler = originalSet as AnyHandler;\n\n const wrapCurrent = (): void => {\n const handler = handlers.get(method) as SeamedHandler | undefined;\n if (typeof handler !== \"function\" || handler[seamTag]) return;\n const seamed = wrap(handler) as SeamedHandler;\n seamed[seamTag] = true;\n handlers.set(method, seamed);\n };\n\n wrapCurrent();\n lowLevel.setRequestHandler = (...args: AnyArgs): unknown => {\n const registered = setRequestHandler.apply(lowLevel, args);\n wrapCurrent();\n return registered;\n };\n}\n\n/**\n * The `tools/list` RESPONSE seam, which is what lets `intentParamMode:\n * \"required\"` advertise `user_goal` as required without the validator\n * enforcing it (see `schemaCompat.buildIntentFields` for why zod cannot).\n *\n * ⚠ Fail-open, twice. A throw from the transform is logged and the SDK's own\n * result goes out untouched, because a vendor's `tools/list` may never break\n * on Baton's account. And a server with no reachable handler map gets no seam,\n * which costs the advertisement and nothing else.\n */\nfunction installToolsListSeam(lowLevel: RequestHandlerInternals, ctx: WrapContext): void {\n const isInjected = (toolName: string): boolean =>\n ctx.paramRegistry.get(toolName)?.[USER_GOAL_PARAM_NAME] === \"injected\";\n const advertise = (result: unknown): unknown => {\n try {\n return advertiseUserGoalRequired(result, isInjected);\n } catch (err) {\n process.stderr.write(\n `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}\\n`,\n );\n return result;\n }\n };\n\n installRequestSeam(lowLevel, TOOLS_LIST_METHOD, TOOLS_LIST_SEAM, (handler) => (...args) => {\n const out = handler(...args);\n return isThenable(out) ? out.then(advertise) : advertise(out);\n });\n}\n\nconst LIFECYCLE_SEAMS = {\n resourceList: Symbol(\"batonResourceListSeam\"),\n resourceRead: Symbol(\"batonResourceReadSeam\"),\n promptList: Symbol(\"batonPromptListSeam\"),\n promptGet: Symbol(\"batonPromptGetSeam\"),\n} as const;\n\n/** The three event schemas one lifecycle family needs, structurally rather\n * than by Zod generics: all twelve `.parse` to something assignable to\n * `Event`, and that is the only thing the seam does with them. */\ninterface LifecycleSchemas {\n start: { parse(value: unknown): Event };\n end: { parse(value: unknown): Event };\n error: { parse(value: unknown): Event };\n}\n\n/**\n * The RESOURCE and PROMPT lifecycle seams (SPEC §11.4.4) — `baton-ts`'s first\n * instrumentation of anything but a tool call.\n *\n * ⚠ **At the REQUEST handler, not at registration**, and that is the whole\n * design rather than a convenience. The vantage point the twelve shapes were\n * defined from is `baton-proxy`'s, which reads the wire: subject, timing,\n * failure, no body. The request handler is the in-process position that sees\n * the same four facts — and it needs no per-family registration patch, since\n * both majors install all four handlers through the one `_requestHandlers` map\n * `installRequestSeam` already handles, lazily and in either order.\n *\n * ⚠ **No `principal` on any of the twelve, and it is a decision.** The vendor's\n * `resolvePrincipal` hook is TOOL-shaped — it takes `{extra, toolName,\n * arguments}` — so calling it with a URI in `toolName` would stretch a contract\n * a vendor's hook cannot anticipate. The proxy stamps no principal on these\n * types either (its twelve enqueue methods take none), so omitting it is parity\n * with the producer the shapes came from rather than a gap this package\n * invented. A later release that wants identity here needs a hook shape first.\n *\n * ⚠ **No `call_id` either**, same reason: no producer mints one for these, so\n * a consumer pairing a start with its end has only SPEC §11.5.4's FIFO floor.\n * §11.4.4 records that rather than leaving it to be discovered.\n *\n * ⚠ **Fail-open throughout (SPEC §11.2).** Every event goes through `emit`,\n * the whole settle is wrapped, and the vendor's result and the vendor's\n * exception pass through untouched in both lanes. A server with no reachable\n * handler map gets no seam, which costs these twelve events and nothing else.\n *\n * ⚠ **The error leg is THROW-ONLY, which is why there is no returned-flag\n * branch here.** `isError` is a `CallToolResult` member; a failing resource\n * read or prompt get comes back as a JSON-RPC error, so `error_type` is the\n * exception's class name — §11.4.3's RAISE spelling. `baton-proxy` files the\n * JSON-RPC numeric code instead, because the wire is what it holds. §11.4.4\n * states the divergence; both conform, and the member is an open string.\n */\n/** One lifecycle family's three event schemas plus the two facts that differ\n * between families. A DATA table, so adding `resources/templates/list` or\n * `completion/complete` is a row rather than a copied block.\n *\n * ⚠ `startParams` stays a CALLBACK while the other two are keys, and the\n * asymmetry is the point: the three `*_start` shapes are genuinely different\n * (none / the whole bag minus `_meta` / the `arguments` member alone) and that\n * difference is the proxy's own inconsistency, which §11.4.4 records. Encoding\n * it as a mode string would only relocate the switch. */\ninterface LifecycleSpec {\n method: string;\n seamTag: symbol;\n schemas: LifecycleSchemas;\n /** The dedicated subject member's key — `\"uri\"` for a read, `\"name\"` for a\n * prompt get, absent for either list, which has no subject. It rides all\n * three legs, so one key decides it for the family. */\n subjectKey?: \"uri\" | \"name\";\n /** Which array of the `*_list` result `count` counts. Absent for the two\n * families that have no count. */\n countKey?: \"resources\" | \"prompts\";\n /** The `*_start` payload's `params` member, or `{}` where the family has\n * none. */\n startParams: (params: Record<string, unknown>) => Record<string, unknown>;\n}\n\nfunction installLifecycleSeam(\n lowLevel: RequestHandlerInternals,\n ctx: WrapContext,\n spec: LifecycleSpec,\n): void {\n installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {\n const request = args[0] as { params?: Record<string, unknown> } | undefined;\n const requestParams = request?.params ?? {};\n const extra = args[1] as Extra;\n\n // ⚠ ONE `const`, not three `let`s with placeholder values. `emit`'s build\n // thunks capture this, and TypeScript will not narrow a captured MUTABLE\n // binding — which is what the three `const envelope = common` aliases an\n // earlier version carried were working around. `null` means the start\n // capture failed, and there is then nothing to stamp the later legs with.\n const opened = await openLifecycleCall(ctx, spec, requestParams, extra);\n\n /** Every leg is the same envelope with a different schema and payload, so\n * one builder owns the parts that must not drift: the stamp, the clock and\n * the sequence number — which `counter.next` must allocate at EMIT time,\n * not before. */\n const fire = async (\n schema: { parse(value: unknown): Event },\n payload: Record<string, unknown>,\n ): Promise<void> => {\n if (opened === null) return;\n await emit(ctx.sink, () =>\n schema.parse({\n ...opened.common,\n sequence_number: ctx.counter.next(opened.sessionId),\n captured_at: new Date().toISOString(),\n payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload }),\n }),\n );\n };\n\n await fire(spec.schemas.start, spec.startParams(requestParams));\n\n const startedAt = performance.now();\n const elapsed = (): number => Math.round(performance.now() - startedAt);\n try {\n const result = await handler(...args);\n await fire(spec.schemas.end, {\n ...(spec.countKey === undefined ? {} : { count: countOf(result, spec.countKey) }),\n duration_ms: elapsed(),\n });\n return result;\n } catch (err) {\n await fire(spec.schemas.error, {\n error_type: errorTypeOf(err),\n // KEPT under every capture mode: a failed FETCH's message is the\n // producer's own diagnostic, not anything a resource returned, so\n // nothing here is result-derived (SPEC §11.4.4). The scrub and the cap\n // are `scrubLifecyclePayload`'s, in that order.\n error_body: messageOf(err),\n duration_ms: elapsed(),\n });\n // Rethrown unchanged — a sensor does not change what the caller sees.\n throw err;\n }\n });\n}\n\n/** Resolve the envelope and the subject for one lifecycle request, or `null`\n * when that failed.\n *\n * Separate from the seam so the three legs share ONE immutable result. Guarded\n * here rather than at each leg because the vendor's request has not run yet:\n * losing the capture costs the pairing, never the call (SPEC §11.2). */\nasync function openLifecycleCall(\n ctx: WrapContext,\n spec: LifecycleSpec,\n requestParams: Record<string, unknown>,\n extra: Extra,\n): Promise<{\n common: Record<string, unknown>;\n sessionId: string;\n subject: Record<string, unknown>;\n} | null> {\n try {\n const parts = await resolveEnvelopeParts(ctx, extra);\n return {\n sessionId: parts.sessionId,\n subject:\n spec.subjectKey === undefined\n ? {}\n : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },\n common: {\n tenant_id: ctx.tenantId,\n vendor_id: ctx.vendorId,\n session_id: parts.sessionId,\n consent_token: ctx.consentToken,\n agent_runtime: parts.runtime,\n transport_observed: observeTransport(extra),\n runtime_meta: parts.scrubbedMeta,\n },\n };\n } catch (err) {\n process.stderr.write(`baton: ${spec.method} capture failed: ${String(err)}\\n`);\n return null;\n }\n}\n\n/** Every lifecycle family, as one table.\n *\n * ⚠ The two `startParams` builders that DO something are deliberately\n * different, and §11.4.4 records why: `baton-proxy` built them differently and\n * these shapes are transcribed from it, not designed. */\nconst NO_PARAMS = (): Record<string, unknown> => EMPTY_PARAMS;\n\n/** Shared because it is only ever SPREAD, never mutated. The thunk used to\n * allocate a throwaway object on every `resources/list` and `prompts/list`\n * request to produce nothing. */\nconst EMPTY_PARAMS: Record<string, unknown> = Object.freeze({});\n\nconst LIFECYCLE_SPECS: readonly LifecycleSpec[] = [\n {\n method: \"resources/list\",\n seamTag: LIFECYCLE_SEAMS.resourceList,\n schemas: {\n start: ResourceListStartEventSchema,\n end: ResourceListEndEventSchema,\n error: ResourceListErrorEventSchema,\n },\n // ⚠ `resources` ALONE. Resource TEMPLATES are a separate MCP method with\n // their own result array and are deliberately not added in, matching the\n // proxy — so a template-only server reports 0, which §11.4.4 says a\n // consumer MUST NOT read as \"this server has no resources\".\n countKey: \"resources\",\n startParams: NO_PARAMS,\n },\n {\n method: \"resources/read\",\n seamTag: LIFECYCLE_SEAMS.resourceRead,\n schemas: {\n start: ResourceReadStartEventSchema,\n end: ResourceReadEndEventSchema,\n error: ResourceReadErrorEventSchema,\n },\n subjectKey: \"uri\",\n // ⚠ The whole params bag MINUS `_meta`, so `uri` lands here as well as in\n // its own member. That duplication is the proxy's and is reproduced on\n // purpose: the dedicated member is what a consumer reads, the bag is what\n // the caller actually sent, and a producer that stripped `uri` out could no\n // longer say the second thing. `_meta` is excluded because it rides the\n // envelope as `runtime_meta` already.\n startParams: (params) => ({ params: paramsBag(params) }),\n },\n {\n method: \"prompts/list\",\n seamTag: LIFECYCLE_SEAMS.promptList,\n schemas: {\n start: PromptListStartEventSchema,\n end: PromptListEndEventSchema,\n error: PromptListErrorEventSchema,\n },\n countKey: \"prompts\",\n startParams: NO_PARAMS,\n },\n {\n method: \"prompts/get\",\n seamTag: LIFECYCLE_SEAMS.promptGet,\n schemas: {\n start: PromptGetStartEventSchema,\n end: PromptGetEndEventSchema,\n error: PromptGetErrorEventSchema,\n },\n subjectKey: \"name\",\n // ⚠ `arguments` ALONE, NOT the whole bag — the opposite of the resource\n // read above, so `name` does NOT appear inside `params`. The two are\n // inconsistent in the producer the shapes came from; the inconsistency is\n // reproduced rather than tidied, because a consumer reading one producer\n // and a second producer reading the other must agree.\n startParams: (params) => ({\n params: paramsBag(params[\"arguments\"] as Record<string, unknown> | undefined),\n }),\n },\n];\n\n/** Install every lifecycle seam. */\nfunction installLifecycleSeams(lowLevel: RequestHandlerInternals, ctx: WrapContext): void {\n for (const spec of LIFECYCLE_SPECS) installLifecycleSeam(lowLevel, ctx, spec);\n}\n\n/** The subject member a `*_read` / `*_get` payload requires, as a string.\n *\n * ⚠ `String()` on a non-string would put `\"[object Object]\"` on the wire for a\n * malformed request — a value that reads like a real URI name and is not. The\n * empty string is what `baton-proxy` emits for an absent subject\n * (`str(params.get(\"uri\") or \"\")`), so an unreadable one takes the same\n * spelling rather than inventing a third. The member is REQUIRED on all three\n * legs, so dropping it is not an option. */\nfunction stringSubject(value: unknown): string {\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** `len(result[key])`, fail-safe. A result this seam cannot read is a count of\n * 0 rather than a dropped event: the call happened and its timing is the part\n * no other signal carries. */\nfunction countOf(result: unknown, key: string): number {\n const list = (result as Record<string, unknown> | null | undefined)?.[key];\n return Array.isArray(list) ? list.length : 0;\n}\n\n/** A `*_start` payload's `params` member: the caller's own request data.\n *\n * ⚠ **Does NOT scrub — `scrubLifecyclePayload` does, over the whole payload.**\n * A first version scrubbed only here, and the result was the worst of both: a\n * resource read of `file:///alice@corp.com/doc.txt` shipped the path REDACTED\n * inside `params` and RAW in the sibling `uri` member, in one event, so the\n * redaction was worthless for that value. Found by review, reproduced on both\n * majors. Scrubbing the whole payload is also what the producer these shapes\n * came from does (`emitter.py`: `payload = self._scrubber(payload)`), so it is\n * the parity position as well as the correct one.\n *\n * `_meta` is dropped: it rides the envelope as `runtime_meta`, where it is\n * coordinate-coarsened first (`roundMetaCoordinates`), so recording it here too\n * would put the same data on one event twice under two treatments — and the\n * coarsening would be the one a consumer could not rely on.\n *\n * ⚠ `{}` and not `null` for an absent bag, which is the proxy's spelling\n * (`dict(params) if params else {}` — it never emits null). The schema permits\n * both, so this is parity rather than conformance. */\nfunction paramsBag(bag: Record<string, unknown> | undefined): Record<string, unknown> {\n if (!bag || typeof bag !== \"object\") return {};\n // One loop rather than `Object.entries().filter().fromEntries()`, which\n // allocated a pair array per key plus two arrays and a closure to produce\n // what is usually a one-key copy — this runs on every `resources/read` and\n // every `prompts/get`.\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(bag)) {\n if (key !== \"_meta\") out[key] = bag[key];\n }\n return out;\n}\n\n/**\n * Scrub a lifecycle payload WHOLE, then cap, and nothing else.\n *\n * ⚠ **Whole, not member by member** — the one rule this family needs and the\n * one a first version got wrong. `uri` and `name` are CALLER-supplied free\n * text (file paths, query strings, account ids, emails), not vendor-registered\n * identifiers like `tool_name`, and they ride all three legs. Scrubbing only\n * `params` left them raw while the same value was redacted one key over.\n *\n * It is also exactly what `baton_proxy.emitter._enqueue` does — one scrubber\n * pass over the whole payload dict — so the Console cannot receive a redacted\n * URI from one producer and a raw one from the other.\n *\n * ⚠ **Cap AFTER the scrub**, which is why the cap lives here rather than in a\n * caller: a PII value straddling `ERROR_BODY_MAX_CODE_POINTS` must reach the\n * scrubber whole, or the surviving half ships unredacted. Same ruling, same\n * reason, as `errorBody` for the tool-call legs — and the reason this path does\n * NOT call `errorBody`, which would scrub that one member a second time.\n *\n * ⚠ PRECONDITION: call this ONLY from inside an `emit()` build thunk. The bare\n * scrubber call is correct there — a throw drops the event, which is the right\n * answer for a payload — and wrong anywhere else (SPEC §11.2: a sensor never\n * breaks the vendor's call).\n */\nfunction scrubLifecyclePayload(\n ctx: WrapContext,\n raw: Record<string, unknown>,\n): Record<string, unknown> {\n // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw drops the event, which is correct for a payload\n const scrubbed = ctx.scrubber(raw) as Record<string, unknown>;\n const body = scrubbed?.[\"error_body\"];\n if (typeof body !== \"string\") return scrubbed;\n // Spread rather than assign: the scrubber is the vendor's and may hand back\n // a frozen object. Key order does not matter — Zod emits in SHAPE order.\n return { ...scrubbed, error_body: capCodePoints(body, ERROR_BODY_MAX_CODE_POINTS) };\n}\n\n/** One tool's registry entry, in the only members either seam reads.\n *\n * The CLASSIFICATION members (`enabled`, `execution`) come from\n * `ToolEntryFacts` in `errorResult.ts`, which is where the decision that reads\n * them lives; this adds the two DISPATCH members, which only this module\n * touches. One declaration per fact, so the next flag either SDK branches on\n * cannot be added to one copy and missed in the other. */\ninterface ToolEntry extends ToolEntryFacts {\n handler?: unknown;\n executor?: unknown;\n}\n\n/**\n * The function an entry actually dispatches through, which differs by SDK\n * major — 1.x invokes `entry.handler`, v2 a closure at `entry.executor`.\n *\n * Shared by `wrapIfNeeded`, which tags it, and the `tools/call` seam, which\n * asks whether it is tagged. Two copies of this rule would let the seam\n * answer \"not ours\" about a tool `wrapIfNeeded` had in fact wrapped, and the\n * consequence is silent: the request-side `failure_kind` events for that tool\n * would simply never be emitted. See {@link wrapIfNeeded} for why getting the\n * per-major choice wrong fails quietly in the first place.\n */\nfunction dispatchSlot(entry: ToolEntry): \"executor\" | \"handler\" | undefined {\n if (typeof entry.executor === \"function\") return \"executor\";\n if (typeof entry.handler === \"function\") return \"handler\";\n return undefined;\n}\n\n/** The dispatch target itself, for a caller that only needs to inspect it. */\nfunction dispatchTarget(entry: ToolEntry): TaggedHandler | undefined {\n const slot = dispatchSlot(entry);\n return slot === undefined ? undefined : (entry[slot] as TaggedHandler);\n}\n\n/**\n * The `tools/call` REQUEST seam — the second of Baton's two tool-call\n * sensors, and the one that can see a failure the SDK manufactures ABOVE the\n * vendor's handler (SPEC §11.4.3's `failure_kind`).\n *\n * Three of those four failures emit NOTHING from the inner wrapper, because\n * the handler it wraps never runs: an unknown tool, a disabled tool and a\n * rejected argument. The fourth is worse than nothing — the handler returns\n * fine and the SDK's own output conversion rejects it, so the inner files\n * `tool_call_end` for a call the CALLER saw fail. This seam closes both: it\n * supplies the missing events itself, and it hands the inner's parked\n * terminal event the outcome so a false success can be replaced.\n *\n * ⚠ **Unconditional, unlike the `tools/list` seam** (which only installs\n * under `intentParamMode: \"required\"`): the correction it makes is not\n * configurable. A server with no reachable handler map gets no seam, and then\n * this producer has one seam again and correctly omits `failure_kind`\n * entirely — `CallSlot` and `terminate` carry that degradation.\n *\n * ⚠ **Fail-open, as the whole capture path must be (SPEC §11.2).** Both the\n * flush and the request-side emission go through `emit`, and `settleCall`'s\n * own guard is below; the vendor's result and the vendor's exception pass\n * through this seam untouched in every lane.\n */\nfunction installToolsCallSeam(\n lowLevel: RequestHandlerInternals,\n toolEntry: (name: string) => ToolEntry | undefined,\n ctx: WrapContext,\n): void {\n installRequestSeam(\n lowLevel,\n TOOLS_CALL_METHOD,\n TOOLS_CALL_SEAM,\n (handler) =>\n async (...args) => {\n const slot: CallSlot = { innerFired: false, flushTerminal: null };\n // Reassigned by both the try and the catch before `finally` reads it;\n // the initializer is for definite assignment, not a live default.\n let outcome: OuterOutcome = CLEAN_OUTCOME;\n try {\n const result = await callSlots.run(slot, () => handler(...args));\n outcome = { failed: isErrorResult(result), raised: false, result };\n return result;\n } catch (err) {\n outcome = { failed: true, raised: true, err };\n throw err;\n } finally {\n // ⚠ **`finally`, never a read after the `await`.** v2 THROWS a\n // `ProtocolError` out of this handler for an unknown or a disabled\n // tool (`mcp-DXXb3Vv3.mjs:1395-1397`), so a settle placed after the\n // await is skipped on exactly the two legs this seam exists for. A\n // probe made that mistake on 2026-10-01 and reported \"the outer\n // never ran\" as a blocker; the trap is in the production seam too,\n // which is why it is named here and not only in the design note.\n await settleCall(slot, outcome, args, toolEntry, ctx);\n }\n },\n );\n}\n\n/**\n * Decide what this call owes the event stream, now that both seams have had\n * their say.\n *\n * ⚠ Fail-open at the top level. Everything below is Baton's own bookkeeping\n * about a call that has already finished — a throw here would surface to the\n * agent as a failed tool call on work that succeeded, which SPEC §11.2\n * forbids outright. `emit` guards each individual event; this guards the\n * decision around them.\n */\nasync function settleCall(\n slot: CallSlot,\n outcome: OuterOutcome,\n args: AnyArgs,\n toolEntry: (name: string) => ToolEntry | undefined,\n ctx: WrapContext,\n): Promise<void> {\n try {\n // The inner reached a terminal decision: flush it, or let the outcome\n // replace it. This is the ONLY path that emits a terminal event for a\n // call the vendor's handler actually ran.\n if (slot.flushTerminal !== null) {\n const flush = slot.flushTerminal;\n // ⚠ **Released BEFORE the await, not after — and not left set at all.**\n // The parked thunk captures this call's `result`, `params` and `extra`,\n // and on an `async_hooks`-backed `AsyncLocalStorage` the slot is copied\n // onto every async resource created inside `run`. So a vendor handler\n // that lazily makes a LONG-LIVED resource during the call (a pool, an\n // interval, a cached promise) pins the slot — and a slot still holding\n // the thunk drags that whole scope along for the resource's lifetime.\n // Clearing it bounds the retention to the dispatch.\n slot.flushTerminal = null;\n await flush(outcome);\n return;\n }\n // The handler ran but parked nothing — `openCall` itself threw. There is\n // no terminal event to flush and this is NOT a request-side failure: the\n // call got past the SDK's own checks. Saying nothing is the honest answer.\n if (slot.innerFired) return;\n // Nothing failed and the inner never fired: a tool this package does not\n // capture (the annotate tool, a task-based tool) was called and worked.\n if (!outcome.failed) return;\n await emitRequestSideFailure(outcome, args, toolEntry, ctx);\n } catch (err) {\n process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}\\n`);\n }\n}\n\n/**\n * Emit the pair of events for a failure the SDK raised BEFORE the vendor's\n * handler ran (SPEC §11.4.3's three request-side `failure_kind`s).\n *\n * The inner wrapper emitted nothing at all for these, so this supplies both\n * legs, through the same `openCall` the inner uses — identical envelope,\n * identical `principal`, a minted `call_id` on the start so SPEC §11.5.4's\n * tier 1 pairs them.\n *\n * ⚠ **The start is not cosmetic.** `baton-console`'s pairer does build a row\n * from an orphan end (`correlate.py` emits `(None, i)`), but with no start it\n * has no `params` — and the arguments are precisely the diagnostic for\n * `invalid_argument`, the commonest of these three.\n *\n * Two callers get NO event, and both omissions are the point:\n *\n * - **Baton's own annotate tool.** It is excluded from `wrapIfNeeded` because\n * it emits `annotation`, not `tool_call_*`; a rejected argument on it would\n * otherwise file an `invalid_argument` about a tool the vendor does not own.\n * - **A registered tool this package did not wrap** — task-based tools, whose\n * `.handler` is an object rather than a function. `wrapIfNeeded` leaves them\n * alone rather than guessing at a shape we capture no events for, and this\n * has to make the same choice or it would report failures for calls whose\n * successes are invisible.\n *\n * An entry that is ABSENT is the opposite case and does get an event: that is\n * `unknown_tool`, where there is nothing to have wrapped.\n */\nasync function emitRequestSideFailure(\n outcome: OuterOutcome,\n args: AnyArgs,\n toolEntry: (name: string) => ToolEntry | undefined,\n ctx: WrapContext,\n): Promise<void> {\n const request = args[0] as { params?: { name?: unknown; arguments?: unknown } } | undefined;\n const toolName = request?.params?.name;\n // A `tools/call` with no string tool name is not a call this sensor can\n // name, and SPEC gives `tool_name` no null spelling on any payload.\n if (typeof toolName !== \"string\") return;\n if (toolName === ctx.annotationToolName) return;\n const entry = toolEntry(toolName);\n // ⚠ `!= null`, so a null entry falls THROUGH to `unknown_tool` rather than\n // into `dispatchTarget`, where reading `.executor` off it would throw. The\n // registry is reached through a cast past the SDK's `private`, so its shape\n // is a declaration and not a runtime guarantee; `requestSideFailureKind`\n // makes the same check for the same reason, and it is this line that lets\n // that one be reached at all.\n if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;\n\n // ⚠ A COPY, unlike the inner wrapper's in-place strip. `openCall` removes\n // Baton's injected intent params from whatever it is given, and here the\n // object is the vendor's live `request.params.arguments` — already consumed\n // by a validator that rejected it, so mutating it changes no outcome, but a\n // sensor that edits the request it is observing is a habit to refuse rather\n // than reason about once. The strip itself is required: these params ARE\n // still in the arguments on this path (validation runs above the executor,\n // and `captureAndInject` spliced the names into the schema), so without it\n // Baton's own params would land in `tool_call_start.params`, which SPEC\n // says equals the vendor-visible arguments.\n const params = { ...((request?.params?.arguments as Record<string, unknown>) ?? {}) };\n const { common, callId, sessionId } = await openCall(\n ctx,\n toolName,\n args[1] as Extra,\n params,\n entry != null,\n );\n\n // `undefined` where the SDK rejected the call for a reason this producer\n // cannot attribute — SPEC §11.4.3 permits omitting the member and\n // `requestSideFailureKind` says which shape that is. The event still goes:\n // the call failed, and the SDK's own message is on it.\n const failureKind: FailureKind | undefined = requestSideFailureKind(entry);\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 // The lane the SDK rejected on, which is NOT the same across majors\n // for one failure: 1.x converts all three to a returned `isError`\n // inside its own `try` (`mcp.js:101-108`), v2 THROWS the first two\n // and returns the third. So the same customer-visible failure is\n // `\"tool_error\"` on one major and `\"ProtocolError\"` on the other —\n // measured 2026-10-01, and deliberately not special-cased: this\n // member is §11.4.3's RAISE/RETURN discriminator and it is reporting\n // the shape faithfully. `failure_kind` is what makes the two\n // comparable, which is the member's whole justification.\n error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,\n // ⚠ `null`, not 0. The vendor's handler never ran, so there is no\n // handler duration to report; the time this call did spend was spent\n // in the SDK's validator, which is not what any other event means by\n // this member. §11.4 types it nullable for cases like this one.\n duration_ms: null,\n // ⚠ A CONDITIONAL SPREAD, not `failure_kind: failureKind`. Zod's\n // `.optional()` accepts `undefined` and keeps the KEY in its output,\n // so the plain form writes a present-but-undefined member — invisible\n // to a JSON-serialising sink and plainly visible to a vendor-supplied\n // one that iterates keys. SPEC §11.4.3 says a producer that cannot\n // determine the kind MUST OMIT the member, and omitting is what this\n // spells.\n ...(failureKind === undefined ? {} : { failure_kind: failureKind }),\n // KEPT under `\"off\"` — see `requestSideErrorFields`, which takes no\n // capture mode because nothing here is derived from a result.\n ...requestSideErrorFields(\n outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),\n (text) => errorBody(ctx, text),\n ),\n },\n }),\n );\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return typeof (value as { then?: unknown } | null | undefined)?.then === \"function\";\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 ToolEntry;\n\n // Task-based tools (experimental) carry an object, not a function, at\n // .handler — `dispatchTarget` answers `undefined` for them, and leaving\n // them untouched is deliberate rather than a gap: we capture no events for\n // that shape, and the `tools/call` seam makes the SAME choice off the SAME\n // predicate so it cannot report a failure for a tool whose successes are\n // invisible.\n // ⚠ The SLOT, not the target, so the rule is decided ONCE. An earlier\n // version called `dispatchTarget` and then re-tested\n // `typeof mutable.executor === \"function\"` to pick where to assign — which\n // is the rule in two spellings, in the one function whose docstring says\n // that is the failure mode.\n const slot = dispatchSlot(mutable);\n if (slot === undefined) return;\n const target = mutable[slot] as TaggedHandler;\n if (target[BATON_WRAPPED]) return;\n const wrapper = batonWrap(nameRef, target, ctx) as TaggedHandler;\n wrapper[BATON_WRAPPED] = true;\n mutable[slot] = 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 } } & RequestHandlerInternals;\n registerTool: (...args: AnyArgs) => unknown;\n // `ToolEntry` and not `unknown`: the `tools/call` seam reads `enabled` and\n // the dispatch target off these entries, so an upstream rename of either\n // lands as a compile error here the way every other reach-in does.\n _registeredTools?: Record<string, ToolEntry>;\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 // \"required\" by default since 2026-09-15 (Ujwal, #features): advertised\n // through the `tools/list` seam, never enforced, so the default asks every\n // agent for `user_goal` and refuses no call that omits it.\n const intentParamMode: IntentParamMode = config.intentParamMode ?? \"required\";\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 resultCaptureMode: config.resultCaptureMode ?? \"full\",\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 // Before the annotate tool registers: on a server with no tools yet, that\n // registration is what makes the SDK install its `tools/list` handler, and\n // the seam has to be in place to wrap it as it lands.\n if (intentParamMode === \"required\") installToolsListSeam(internals.server, ctx);\n\n // The SECOND tool-call seam (SPEC §11.4.3's `failure_kind`) — unconditional,\n // and installed here for the same reason the `tools/list` seam is: the\n // annotate tool's registration below is what makes a toolless server install\n // its tool handlers at all, so the seam has to be in place to wrap one as it\n // lands.\n //\n // ⚠ The registry is read PER CALL, not captured, so a tool removed after\n // install classifies as `unknown_tool` rather than against a stale snapshot\n // — `update({name: null})` and `remove()` both delete the entry, and the\n // whole point of this lookup is to agree with what the SDK itself just read.\n installToolsCallSeam(\n internals.server,\n // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain\n // object, so `registry[\"constructor\"]` answers `Object` and\n // `registry[\"__proto__\"]` answers `Object.prototype` — both non-undefined,\n // so the \"a tool we did not wrap\" guard would decline to report, and a\n // caller-visible `Tool constructor disabled` would reach the client with\n // this seam silent. An agent hallucinating a prototype-shaped tool name is\n // exactly the kind of failure the seam exists to make visible.\n (name) => {\n const registry = internals._registeredTools;\n return registry && Object.hasOwn(registry, name) ? registry[name] : undefined;\n },\n ctx,\n );\n\n // The four resource/prompt lifecycle seams (SPEC §11.4.4) — unconditional,\n // like the seam above, because what they capture is not configurable.\n //\n // ⚠ **Install ORDER is irrelevant for these four, unlike the two above.**\n // `resources/*` and `prompts/*` handlers are installed by the vendor's own\n // `registerResource` / `registerPrompt`, not by the annotate-tool\n // registration below — and `installRequestSeam` patches `setRequestHandler`,\n // so a primitive registered AFTER `withBaton` is seamed as its handler\n // lands. Verified on both majors. This paragraph used to claim the\n // annotate-tool ordering mattered here, which was the `tools/*` seams'\n // reason copied one function too far.\n installLifecycleSeams(internals.server, ctx);\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 { roundMetaCoordinates } from \"../../metaCoordinates.js\";\nimport type { Sink } from \"../../sinks.js\";\nimport { deriveAnnotationToolName } from \"./annotationName.js\";\nimport { emit } from \"./emit.js\";\nimport { type ResolvePrincipalHook, resolveCallPrincipal } from \"./principalResolution.js\";\nimport type { PrincipalIdMode } from \"../../identity.js\";\nimport { buildAnnotationToolDescription, SIGNAL_TYPES } from \"./llmText.js\";\nimport { extraEnvelope, extraMeta, observeTransport, 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 { scrubOrNull } from \"./safeScrub.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 // As in the tool-call wrapper: coordinates coarsened after the ladder\n // read the raw meta, before the vendor's scrubber (handoff D5).\n const scrubbedMeta = scrubOrNull(\n options.scrubber,\n meta ? roundMetaCoordinates(meta) : null,\n \"_meta\",\n );\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 principal = await resolveCallPrincipal(\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,\n transport_observed: observeTransport(extra),\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 // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape\n intent: options.scrubber(args.user_goal),\n expected_outcome: args.expected_result\n // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape\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 // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape\n workflow: args.overall_task ? options.scrubber(args.overall_task) : null,\n suggested_improvement: args.suggested_improvement\n // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape\n ? options.scrubber(args.suggested_improvement)\n : null,\n // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape\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","/**\n * Coordinate coarsening for a request's `_meta` (handoff D5, 2026-09-15).\n *\n * ChatGPT sends `openai/userLocation` in `_meta` with latitude and longitude\n * at metre precision: two prod values resolved to a storefront and a home.\n * `roundMetaCoordinates` rounds them to 1 decimal (about 11 km) before the\n * meta becomes `runtime_meta`; the city, region, country and timezone beside\n * them stay.\n *\n * `_meta` only, on purpose. This is not a Scrubber rule: a vendor's own tool\n * that takes or returns coordinates keeps them at full precision in the\n * captured params and result. It runs BEFORE the vendor's scrubber, not\n * inside it, so a vendor who supplies their own scrubber still gets it.\n *\n * Mirrors the Python SDK's `round_meta_coordinates`; the two must store the\n * same value for the same client, which is why a tie is written the way\n * Python's `f\"{x:.1f}\"` writes it.\n */\n\nimport { DEPTH_LIMIT } from \"./scrub.js\";\n\n// Case-insensitive exact match, like the Scrubber's REDACT_FIELD_NAMES, so\n// `lat` / `lng` are not matched.\nconst COORD_FIELD_NAMES: ReadonlySet<string> = new Set([\"latitude\", \"longitude\"]);\n\n// A string written as a plain decimal: sign, digits, optional fraction. Whole\n// string, no trimming, no exponent, `Infinity` or `NaN`, the same grammar as\n// the Python SDK's `_DECIMAL.fullmatch`. No `g` flag, so `.test()` is safe.\nconst DECIMAL_STRING = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$/;\n\n/** `{...}` literals and `Object.create(null)` only, as in `scrub.ts`: a\n * `Date` or class instance passes through rather than being rebuilt as a\n * bare object. */\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/** `value` to 1 decimal, written the way Python's `f\"{value:.1f}\"` writes\n * it. `toFixed` rounds from the exact binary value like Python does, with\n * one exception: an exact tie (a fraction of .25 or .75) goes away from\n * zero in `toFixed` and to the even digit in Python. `37.25` is `\"37.2\"`\n * in both SDKs only because of the branch below. */\nfunction toOneDecimal(value: number): string {\n const magnitude = Math.abs(value);\n if (Number.isInteger(magnitude * 4) && !Number.isInteger(magnitude * 2)) {\n // Exact: x.25 * 10 is x2.5, x.75 * 10 is x7.5.\n const tenths = Math.floor(magnitude * 10);\n const even = tenths % 2 === 0 ? tenths : tenths + 1;\n return ((Math.sign(value) * even) / 10).toFixed(1);\n }\n return value.toFixed(1);\n}\n\n/** The rounded coordinate, keeping the value's type, or `undefined` when\n * the rule leaves `value` alone: an integer, `NaN`, `Infinity`, a boolean,\n * null, or a string that is not a decimal. A decimal string always comes\n * back with one decimal, so `\"37\"` becomes `\"37.0\"`. */\nfunction roundCoordinate(value: unknown): number | string | undefined {\n if (typeof value === \"number\") {\n return Number.isFinite(value) && !Number.isInteger(value)\n ? Number(toOneDecimal(value))\n : undefined;\n }\n if (typeof value === \"string\" && DECIMAL_STRING.test(value)) {\n return toOneDecimal(Number(value));\n }\n return undefined;\n}\n\nfunction walk(value: unknown, depth: number): 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 // The value sits at `depth + 1`, where the walk would stop, so the cap\n // applies to a coordinate the same as to anything else. The rule is\n // the key's own value only: a list under `latitude` is walked, not\n // rounded.\n const rounded =\n COORD_FIELD_NAMES.has(k.toLowerCase()) && depth + 1 < DEPTH_LIMIT\n ? roundCoordinate(v)\n : undefined;\n out[k] = rounded ?? walk(v, depth + 1);\n }\n return out;\n }\n if (Array.isArray(value)) {\n return value.map((item) => walk(item, depth + 1));\n }\n return value;\n}\n\n/**\n * A copy of `meta` with every `latitude` / `longitude` value rounded to 1\n * decimal in its own type, at any depth within DEPTH_LIMIT. Pure: `meta`\n * itself is not touched, so the handler and the runtime ladder still see\n * what the client sent.\n */\nexport function roundMetaCoordinates(meta: Record<string, unknown>): Record<string, unknown> {\n return walk(meta, 0) as Record<string, unknown>;\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 to every event so the Console can group by\n * `(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, exceedsCodePoints } from \"./_text.js\";\n\n// ⚠ **`HASH_SCHEME = \"h1\"` lived here and is GONE at 0.4.1** (SPEC §11.4, §13\n// entry 0.8.11), together with `hashPrincipalId`'s `scheme` option. A hashed\n// principal is the BARE digest: no tag, no prefix, no scheme.\n//\n// It named the HMAC key generation, and a fact ABOUT a value must not ride\n// INSIDE the value — the rule `PrincipalWire`'s three members exist to make\n// structural. Provenance is `source`, the classification is `form`, and both\n// ride every mode including `\"raw\"`, where no tag ever existed.\n//\n// ⚠ **What went with it:** nothing now records WHICH key produced a digest, so\n// rotating the secret replaces a tenant's whole population with no marker\n// anywhere. Accepted — the generation could not have re-joined a person across\n// the boundary anyway. It was also an EXPORT, so a vendor recomputing a\n// pseudonym against its own copy gets a tagged value from the old one and a\n// bare value from this one.\n\n/** Where a principal came from. `\"asserted\"` is a vendor's own resolver,\n * which nothing in the protocol checks, and is the only value this SDK\n * emits — `integrations/mcp/principalResolution.ts` has the why, and the\n * wording trap that comes with it. */\nexport const PRINCIPAL_SOURCE_ASSERTED = \"asserted\";\n\n/** What the emitted value IS — the privacy classification, and the only thing\n * SPEC §11.4 lets a consumer classify on. */\nexport const PRINCIPAL_FORM_HASHED = \"hashed\";\nexport const PRINCIPAL_FORM_RAW = \"raw\";\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\n/** Cap on `displayName`, in CODE POINTS (Python's `len`). Over it the name is\n * DROPPED, not truncated: SPEC §11.4 forbids rewriting it, so both SDKs send\n * the same bytes for one resolver output. */\nexport const DISPLAY_NAME_MAX_LEN = 128;\n\n// Unicode `White_Space`, exactly (SPEC §11.4's blank rule). Not `.trim()`:\n// that also removes U+FEFF and keeps U+0085, which Python's `strip()` does the\n// other way round, so the two SDKs would disagree on what is blank.\nconst ALL_WHITE_SPACE = /^\\p{White_Space}*$/u;\n\n/** The resolver's `displayName` as it goes on the wire, or `null`. Verbatim\n * when usable. A non-string, a blank (only Unicode `White_Space`), an\n * over-long value or one holding a lone surrogate or U+0000 is dropped ALONE — the rest\n * of the principal still ships, because a bad label is no reason to lose a\n * good id. Mirrors Python's `wire_display_name`. */\nexport function wireDisplayName(value: unknown): string | null {\n if (typeof value !== \"string\" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;\n // U+0000: Postgres text refuses it, costing a collector the whole event.\n if (LONE_SURROGATE.test(value) || value.includes(\"\\u0000\") || ALL_WHITE_SPACE.test(value)) return null;\n return value;\n}\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\nexport type PrincipalForm = typeof PRINCIPAL_FORM_HASHED | typeof PRINCIPAL_FORM_RAW;\n\n/** `principalIdMode` names a CONFIG choice; `form` names what the emitted\n * value IS. The two vocabularies coincide today and are still two\n * vocabularies — a mode added later need not name its form the same thing,\n * and a consumer classifies on `form` alone.\n *\n * Written out rather than derived, so a third mode cannot silently become a\n * third `form`: the `Record` makes it a COMPILE ERROR until someone chooses\n * what the new mode means for a consumer's classification. That\n * exhaustiveness is the payoff — `form: options.mode` would put an unexamined\n * new mode name straight onto the wire. */\nconst FORM_BY_MODE: Record<PrincipalIdMode, PrincipalForm> = {\n [PRINCIPAL_ID_MODE_HASHED]: PRINCIPAL_FORM_HASHED,\n [PRINCIPAL_ID_MODE_RAW]: PRINCIPAL_FORM_RAW,\n};\n\n/** The registered modes, DERIVED from the map above exactly as Python derives\n * `PRINCIPAL_ID_MODES = frozenset(_FORM_BY_MODE)`.\n *\n * ⚠ **This closes the other direction, and `principalFor` depends on it.**\n * That function drops Python's unrecognised-mode branch on the grounds that\n * config validation refuses an unknown mode first. With a second hand-written\n * list the guarantee would be only \"two lists happen to agree\" — the\n * prose-shaped binding this whole change exists to replace. Derived, a mode\n * cannot be accepted by the validator without someone having chosen its\n * `form`. */\nexport const PRINCIPAL_ID_MODES: readonly PrincipalIdMode[] = Object.keys(\n FORM_BY_MODE,\n) as PrincipalIdMode[];\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 /** What a page shows for this principal — `principalFromOAuthEmail` puts\n * the part of the address before the last `@` here. **Sent verbatim, in\n * every mode, hashed included, and never through the scrubber** (SPEC\n * §11.4): the vendor chooses what is safe to show. An unusable value is\n * dropped alone — see `wireDisplayName`. */\n displayName?: 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 the BARE lowercase hex digest — no tag, no prefix, no scheme. It\n * returned `\"h1:<hex>\"` until 0.4.1; the tag was never part of the HMAC\n * message, so taking it off moved no digit of the digest.\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 // ⚠ `scheme?: string` was here until 0.4.1 and is REMOVED, not deprecated.\n // A keyword left in place is an invitation to pass one, and there is no\n // longer any tag for it to select.\n },\n): string {\n const { tenantId, key, issuer = null } = 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 return createHmac(\"sha256\", keyBytes).update(message, \"utf8\").digest(\"hex\");\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; displayName?: 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 the principal 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 // Shape only; the name's own rules run once, in `principalFor`.\n return typeof candidate.displayName === \"string\"\n ? { principalId: candidate.principalId, issuer, displayName: candidate.displayName }\n : { principalId: candidate.principalId, issuer };\n}\n\n/** The principal AS EMITTED — the finished envelope value (SPEC §11.4).\n *\n * ⚠ **Not `Principal`, and the two are easy to confuse.** That one is what a\n * vendor's `resolvePrincipal` hook HANDS US: a raw subject and an optional\n * issuer. This one is what we PUT ON THE WIRE after deriving it — the raw\n * value is gone by the time this is built, and nothing here is ever the input\n * to a hash. One is the question, this is the answer.\n *\n * **All three members are REQUIRED, and that is the guarantee the object\n * exists to give.** A producer emits the whole thing or omits `principal`\n * entirely; a partial object is malformed, not a degraded reading. So there is\n * no conformant event carrying an `id` whose `form` a consumer has to guess,\n * and none carrying a `source` for an identity nobody resolved. That binding\n * is structural here precisely because its predecessor — a scheme prefix plus\n * a paragraph of prose — was not.\n */\nexport interface PrincipalWire {\n /** The value: an HMAC pseudonym in `\"hashed\"` mode, the principal verbatim\n * in `\"raw\"` mode. Which one is `form`, and it is NEVER the value's shape —\n * a real OIDC subject (`mailto:`, `acct:`, `urn:`, `https:`) reads as a\n * scheme-tagged pseudonym to anything testing for \"letters then a colon\". */\n id: string;\n /** WHERE it came from. Always `\"asserted\"` here — `principalResolution.ts`\n * has the why and the wording trap. */\n source: typeof PRINCIPAL_SOURCE_ASSERTED;\n /** WHAT it is. */\n form: PrincipalForm;\n /** What a page shows; personal data whenever present, whatever `form`\n * says. OMITTED, never `null`, when there is none — so a nameless principal\n * is byte-identical to one from before the member existed. */\n display_name?: string;\n}\n\n// ⚠ **Literal types here, `z.string()` on `PrincipalWireSchema` — and the\n// asymmetry is deliberate.** That schema is the PARSE boundary and must\n// tolerate a value SPEC registers later; this is the PRODUCER type, and this\n// SDK emits exactly one `source` and two `form`s. Widening it would inherit\n// the schema's justification without its reason, and would let a stray\n// string through. Typed this way, adding a source is a compile error in one\n// place — here, where the registry is.\n\n/** Turn a resolved principal into the finished wire object, or `null`.\n *\n * **The edge-derivation chokepoint, and the single copy of it**, mirroring\n * Python's `_finish_principal`. `raw` mode puts real identity in the\n * collector's database — the vendor's deliberate choice, and why SPEC §11.4\n * tells a consumer never to treat a principal as anonymous unless `form` says\n * exactly `\"hashed\"`.\n *\n * ⚠ **Hashed mode with no key DROPS the principal rather than falling back to\n * raw.** The fallback would be a residency breach that looks like success: the\n * field present, populated, and carrying the subject verbatim. Absent is the\n * safe direction — this is additive analytics and never a consent gate.\n *\n * **All three members or nothing**, and structurally so: there is exactly ONE\n * object literal in this function, at the bottom, and every branch that cannot\n * produce a value returns `null` before reaching it.\n *\n * ⚠ Python carries a fourth failure branch here — an unrecognised `mode`,\n * which has no truthful `form`. It is unreachable on this arm:\n * `validateConfig` (`integrations/mcp/config.ts`) refuses an unknown\n * `principalIdMode` at install, so the mode reaching this function is always\n * one of the two. Not porting it is therefore a fact about where the check\n * lives, not a gap.\n */\nexport function principalFor(\n principal: Principal,\n options: {\n mode: PrincipalIdMode;\n tenantId: string;\n key?: Uint8Array | string | null | undefined;\n },\n): PrincipalWire | null {\n let id: string;\n if (options.mode === PRINCIPAL_ID_MODE_RAW) {\n // `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so\n // an astral subject cut at the boundary ships a LONE SURROGATE — the very\n // thing `normalizePrincipal` refuses on the way IN — and disagrees with\n // Python's `principal_id[:128]`, which counts code points.\n //\n // ⚠ What raw mode NO LONGER forfeits is the provenance: `source` is a\n // member now and rides every mode, so a consumer here is told a real\n // identity AND which mechanism named it.\n id = capCodePoints(principal.principalId, RAW_PRINCIPAL_ID_MAX_LEN);\n } else {\n if (options.key === null || options.key === undefined) return null;\n id = hashPrincipalId(principal.principalId, {\n tenantId: options.tenantId,\n key: options.key,\n issuer: principal.issuer ?? null,\n });\n }\n // Unconditional `source`: every principal comes from the vendor's hook\n // (SPEC §11.4), so an option here would be an argument no caller can vary.\n const wire: PrincipalWire = {\n id,\n source: PRINCIPAL_SOURCE_ASSERTED,\n form: FORM_BY_MODE[options.mode],\n };\n // Checked HERE, where every wire object is built (Python: `_finish_principal`).\n const displayName = wireDisplayName(principal.displayName);\n if (displayName !== null) wire.display_name = displayName;\n return wire;\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.principalFor` 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 */\n/** Whether `value` is longer than `max` CODE POINTS — the check form of\n * `capCodePoints`, for a field that is dropped rather than cut. */\nexport function exceedsCodePoints(value: string, max: number): boolean {\n // Each code point is one or two UTF-16 units, so the unit count brackets it.\n if (value.length <= max) return false;\n if (value.length > 2 * max) return true;\n return [...value].length > max;\n}\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\n// The leading label tracks `intentParamMode`: under \"required\" the\n// `tools/list` seam in withBaton.ts adds `user_goal` to the advertised\n// `required` list, so a description still opening \"OPTIONAL.\" would\n// contradict the schema it ships inside. Only the label moves; the body is\n// the measured text. Mirrors Python's `build_user_goal_param_description`.\nconst USER_GOAL_PARAM_BODY =\n \"One sentence: what the user is actually trying to accomplish \" +\n \"with this call (their goal, not a restatement of the arguments).\";\nconst USER_GOAL_PARAM_DESCRIPTION = \"OPTIONAL. \" + USER_GOAL_PARAM_BODY;\nconst USER_GOAL_PARAM_DESCRIPTION_REQUIRED = \"REQUIRED. \" + USER_GOAL_PARAM_BODY;\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\n/** `user_goal`'s description, labelled \"REQUIRED.\" under `intentParamMode:\n * \"required\"` and \"OPTIONAL.\" otherwise. */\nexport function buildUserGoalParamDescription(options: { intentParamMode?: string } = {}): string {\n return options.intentParamMode === \"required\"\n ? USER_GOAL_PARAM_DESCRIPTION_REQUIRED\n : 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: `RequestHandlerExtra.authInfo` — the validated access token, set by\n * the SDK's bearer-auth middleware on an authenticated HTTP request. */\n authInfo?: unknown;\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 declared — this comment said it was not, and that was wrong.**\n * Corrected 2026-09-16 against the installed package. `ServerContext` declares\n * `http?: { req?: globalThis.Request; closeSSE?: ... }`, documented \"The\n * original HTTP request\", at\n * `@modelcontextprotocol/server@2.0.0/dist/createMcpHandler-CLhGwQTn.d.mts:2212`.\n * The `{ authInfo? }`-only shape the old text described is real but is\n * `BaseContext.http` (`:2171`) — a DIFFERENT block, which `ServerContext`\n * intersects, so the member carries both. Two declarations of one property\n * name, and the earlier pass read the wrong one and generalised.\n *\n * The old text also warned \"do not correct this back on the strength of the\n * `.d.ts`\", which is why the exact file and line are cited above rather than\n * the claim repeated: the way past that warning is a narrower read, not a\n * louder assertion. Measurement still backs it — 10 rows, both majors, every\n * transport (v15 probe) — so this is now declared AND measured. */\n http?: { req?: { headers?: unknown } | undefined; authInfo?: unknown } | undefined;\n}\n\n/** A validated access token, as both majors declare it\n * (`@modelcontextprotocol/sdk` 1.x `server/auth/types.d.ts`,\n * `@modelcontextprotocol/server` 2.0.0 `createMcpHandler-*.d.mts:751` — the\n * same six members). Declared structurally for the reason {@link Extra} is.\n *\n * ⚠ **There is no `claims` member.** Whatever a verifier knows about the\n * subject goes in the free-form `extra` bag, and only the vendor's verifier\n * decides what is there. */\nexport interface AuthInfo {\n token: string;\n clientId: string;\n scopes: string[];\n expiresAt?: number | undefined;\n resource?: URL | undefined;\n extra?: Record<string, unknown> | undefined;\n}\n\n/** The request's validated access token, from wherever this major keeps it:\n * `extra.authInfo` on 1.x, `ctx.http.authInfo` on v2. `null` on stdio (MCP\n * auth is HTTP middleware) and on any unauthenticated request.\n *\n * Only an object is passed on; anything else is `null`, so a hook never has\n * to guard against a string or a number arriving where a token should. */\nexport function extraAuthInfo(extra: Extra): AuthInfo | null {\n const found = extra.authInfo ?? extra.http?.authInfo;\n return found !== null && typeof found === \"object\" ? (found as AuthInfo) : null;\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 */\n/** What we observed beneath this call, for the envelope's `transport_observed`.\n *\n * `\"http\"` when a transport request object is reachable — `requestInfo` on the\n * 1.x peer, `http.req` on v2. `\"no-http-request\"` when neither is, which is\n * stdio and in-memory. `\"read-failed\"` if reading the carrier throws.\n *\n * ⚠ **Keyed on the REQUEST OBJECT, never on {@link extraHeaders}.** That\n * function ends in a bare `return null` and — by its own contract above —\n * returns `null` both when no HTTP request is in flight AND when a header it\n * was handed could not be appended (the HTTP/2 pseudo-header guard). So an\n * HTTP call whose headers it declined reads there as no-HTTP. That fold is\n * harmless for identity, which only loses a lookup, and NOT harmless here:\n * `\"no-http-request\"` is a licence, not a label — SPEC §3.4 lets a consumer\n * group a process-wide fallback `session_id` on it and only on it. Handing\n * that out because a header was malformed merges two strangers.\n *\n * ⚠ The v15 probe measured ZERO folds across 10 rows, so this is not a bug we\n * have seen — it is one the shape allows, and Python's equivalent helper has\n * the same fold as a LIVE defect (register A6). Same rule on both SDKs, for the\n * same reason, before either can bite.\n *\n * There is no `null` return. `null` on the envelope means the SDK did not look,\n * which is the library path with no MCP transport at all; every caller here is\n * inside a live MCP call and did look. */\nexport function observeTransport(extra: Extra): string {\n try {\n const carrier = extra.http?.req ?? extra.requestInfo;\n return carrier ? \"http\" : \"no-http-request\";\n } catch {\n return \"read-failed\";\n }\n}\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 ONLY identity provenance (SPEC §11.4).\n *\n * **The producer never reads the token itself** (SPEC §11.4, §13 2026-10-02 —\n * Python's own token rung was removed the same day), so every principal this\n * SDK emits is `source: \"asserted\"`. The hook's context carries the validated\n * `authInfo`, and `oauthHooks.ts` ships the two ready-made OAuth hooks.\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\nimport {\n type Principal,\n type PrincipalIdMode,\n type PrincipalWire,\n PRINCIPAL_ID_MODE_HASHED,\n normalizePrincipal,\n principalFor,\n} from \"../../identity.js\";\nimport { warn } from \"./annotationName.js\";\nimport { type AuthInfo, type Extra, extraAuthInfo, 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 /** The validated access token for this request, read from wherever this\n * major keeps it — see `extraAuthInfo`. `null` on stdio and on any\n * unauthenticated request. `principalFromOAuthSub` and\n * `principalFromOAuthEmail` read it, and so can a vendor's own hook.\n *\n * Optional so a vendor hand-building a context in their own tests keeps\n * compiling, as Python's defaulted `claims` keeps theirs running. */\n authInfo?: AuthInfo | null | undefined;\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 authInfo: extraAuthInfo(extra),\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: 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 HMAC key is set, so \" +\n `the principal 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 the principal 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`.\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` 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 resolveCallPrincipal(\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<PrincipalWire | 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 principalFor(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","import {\n EXPECTED_RESULT_PARAM_NAME,\n OVERALL_TASK_PARAM_NAME,\n USER_GOAL_PARAM_NAME,\n} from \"./llmText.js\";\n\n/** The fields a vendor scrubber is applied to OUTSIDE an `emit()` build thunk.\n *\n * A closed union rather than `string` for two reasons that both turned out to\n * matter. It makes a typo at a call site a compile error, where three of these\n * are also param-name constants two lines above the call. And it bounds the\n * warning set below to one line per field per process: a `string` would leave\n * that bound resting on every caller happening to pass a literal. */\nexport type ScrubbedField =\n | \"agent-runtime name\"\n | \"_meta\"\n | typeof USER_GOAL_PARAM_NAME\n | typeof EXPECTED_RESULT_PARAM_NAME\n | typeof OVERALL_TASK_PARAM_NAME;\n\nconst warned = new Set<ScrubbedField>();\n\n/** Fail-open wrapper around a VENDOR-supplied scrubber call.\n *\n * SPEC §11.2: Baton instrumentation MUST NOT break the vendor's tool call on\n * its own internal failure. `safeWrite` enforces that for `sink.write`, and\n * `emit` for payload CONSTRUCTION — but the scrubber also runs in plain\n * statements, outside any thunk, in both handlers. A throw there escapes both\n * guards and the call comes back to the agent as `isError: true`, which is the\n * one thing the fail-open property promises cannot happen. Reproduced on both\n * MCP majors before this existed. The default scrubber is ours, so the trigger\n * is a vendor-supplied one — exactly what §7 tells vendors handling sensitive\n * data they MUST supply.\n *\n * ⚠ **The rule is the POSITION, not a list of fields.** Every scrubber\n * application that is not inside an `emit()` build thunk needs this. An earlier\n * version of this comment listed the call sites instead of stating the rule, and\n * the byte-identical `_meta` line in `annotation.ts` was missed because of it —\n * found by review, not by the list. The lint rule in `eslint.config.js` now\n * refuses a bare scrubber call anywhere in `src/`, so a new site has to opt out\n * visibly rather than be remembered.\n *\n * `null` on failure because every caller already treats `null` as \"this field is\n * not available\": runtime detection loses the TIER and falls through to the\n * next, `_meta` becomes absent, an unscrubbed goal param becomes no captured\n * intent. So the field degrades and the call lives. `null` IN is returned\n * unchanged without calling the scrubber, which is what lets each caller drop\n * its own `x !== null ?` guard.\n *\n * ⚠ NOT for a scrubber call inside an `emit()` build thunk. There a throw is\n * already contained, and `null` would be WORSE than dropping the event: a null\n * `result` on a `tool_call_error` means \"the handler raised\" (SPEC §11.4.3), so\n * swallowing a scrubber failure into one would fabricate a failure shape. Drop\n * the event instead — which is what `emit` already does.\n */\nexport function scrubOrNull<T>(\n scrubber: (value: unknown) => unknown,\n value: T | null,\n field: ScrubbedField,\n): T | null {\n if (value === null) return null;\n try {\n // eslint-disable-next-line no-restricted-syntax -- this IS the guard; the one call the rule exists to funnel every other through\n return scrubber(value) as T;\n } catch (err) {\n // Once per field per process. `safeWrite` logs per event because a sink\n // failure is one write per event; this fires up to five times per CALL, and\n // runtime detection fires unconditionally — so the unbounded form would put\n // a line on stderr for every tool call forever. Bounded the way\n // `principalResolution`'s pre-rename warning and `HttpSink.overflowWarned`\n // already are.\n if (!warned.has(field)) {\n warned.add(field);\n process.stderr.write(\n `baton: scrubber threw on ${field}; that field is dropped, tool call continues. ` +\n `Further failures on this field will be silent: ${String(err)}\\n`,\n );\n }\n return null;\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` 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\";\nimport { scrubOrNull } from \"./safeScrub.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 // Fail-open; `safeScrub` carries why `emit`'s guard does not cover this one.\n // ⚠ `<unknown>` deliberately, NOT inferred: `T` would infer `string` and make\n // the guard below look redundant to a reader, when it is load-bearing.\n const scrubbed = scrubOrNull<unknown>(scrubber, cleaned, \"agent-runtime name\");\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`. Identity is `principal`, a different field on a different\n * condition; keep the two claims apart. It is asserted too: the vendor's hook\n * names the person, and nothing in the protocol checks it.\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`, 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 * What result-derived data reaches the wire, and in what shape.\n *\n * Two halves of one question. Detecting MCP's returned error FLAG — the port\n * of `baton` (Python)'s `integrations/_error_result.py`, with one predicate\n * deliberately different, see `isErrorResult`. And the capture MODE (SPEC\n * §11.4), which decides whether any of it egresses at all. The second half\n * governs the SUCCESS path too, so a reader looking for \"where is the result\n * on a good call decided\" is in the right file despite the name — kept as\n * `errorResult.ts` because the filename pins parity with Python's module.\n *\n * SPEC §11.4.3. **A failed MCP tool call is a 200.** The protocol files it as a\n * successful JSON-RPC response whose `CallToolResult` body sets the error flag;\n * a JSON-RPC error means a protocol fault, not a tool failure. So classifying\n * on thrown exceptions alone — which is what §6.1 used to say, and what this\n * package did — files real failures as successes.\n *\n * ⚠ **One spelling, `isError`.** Python's helper probes `is_error` first\n * because that is a Python ATTRIBUTE name the `mcp` 2.x rewrite introduced;\n * MCP's own JSON-RPC schema is camelCase and every server dumps by alias\n * (wire probe, 2026-09-23: seven cells, `is_error` in none of them). The TS\n * SDKs have no snake_case era at all — measured 2026-09-24 on both majors,\n * the value this package sees is the vendor's own literal, camelCase.\n */\n\n/** `error_type` for a returned error, as opposed to a thrown exception whose\n * constructor name is used. Same literal as Python's `TOOL_ERROR_TYPE` and as\n * `baton-extmcp`'s — sensor parity is the point. */\nexport const TOOL_ERROR_TYPE = \"tool_error\";\n\n/** The registered values of `failure_kind` (SPEC §11.4.3), and the single\n * source of truth for them — same posture as `RESULT_CAPTURE_MODES` below,\n * for the same reason: a second hand-written list makes the guarantee \"two\n * lists happen to agree\".\n *\n * ⚠ **THREE of these four are spelled identically to the Console's error\n * code, and one renames.** Measured in\n * `baton-console/backend/src/baton_console/worker/errors.py`, whose\n * `_FAILURE_KIND_TO_CODE` is mostly an ALLOW-LIST: `unknown_tool`,\n * `tool_disabled` and `invalid_argument` map to codes of the same name\n * (`27566c2` added the first two as codes no TEXT lane can reach), and only\n * `output_schema_mismatch` renames, onto `schema_violation`, which already\n * described it.\n *\n * ⚠ A first version of this paragraph had that INVERTED — one match, three\n * renames — because it was copied from `iserror_sensor_probe.md`'s decision\n * table, written 2026-10-01, which recorded the buckets as they stood BEFORE\n * the Console side of this release landed the next day. Corrected rather than\n * overwritten, because the mechanism is the useful part: a design note's\n * \"today\" column goes stale the moment the thing it describes ships, and a\n * code comment that copies one inherits the staleness silently.\n *\n * The consequence of getting it wrong is not cosmetic. That table is an\n * allow-list, so an unregistered value is simply absent from it and falls\n * through to prose classification — which for `tool_disabled` means\n * `unclassified` with the full text in hand, the exact regression this member\n * exists to remove. `invalid_argument` is SINGULAR for that reason (Ujwal,\n * 2026-10-01): the plural was one letter off the Console's spelling, which is\n * the drift that already cost two defects this week.\n *\n * Open, not closed: `events.ts` types the wire member as a plain string, so a\n * later registered value cannot red a conforming producer (SPEC §11.2's\n * fail-open rule). This array is what THIS producer may emit. */\nexport const FAILURE_KINDS = [\n \"unknown_tool\",\n \"tool_disabled\",\n \"invalid_argument\",\n \"output_schema_mismatch\",\n] as const;\n\n/** What this producer may emit for `failure_kind`. Derived, so the type and\n * the registry cannot drift. */\nexport type FailureKind = (typeof FAILURE_KINDS)[number];\n\n/** The one RESULT-SIDE kind: the handler returned and the producer's own\n * conversion of its output rejected it, so `error_body` and `result` are\n * result-derived and `\"off\"` withholds both. */\nexport const OUTPUT_SCHEMA_MISMATCH = \"output_schema_mismatch\" satisfies FailureKind;\n\n/**\n * Which request-side kind a failure above the handler was, from the tool\n * entry the SDK itself looked up — NOT from the result.\n *\n * ⚠ **SPEC §11.4.3 forbids sorting these by inspecting the result object**,\n * and the reason is visible in both majors' `tools/call` handler: all three\n * arrive as the same shape. On 1.x all three are a returned `isError` whose\n * text is `createToolError`'s (`mcp.js:100-108`, inside the handler's own\n * `try`); on 2.x the first two THROW a `ProtocolError` and the third is a\n * returned `isError` (`mcp-DXXb3Vv3.mjs:1394-1397`). Reading the message\n * would be a regex in the producer, which is the thing `failure_kind` exists\n * to remove.\n *\n * So this reads the same two facts the SDK branched on, from the same\n * registry entry (`_registeredTools[name]`), which makes the label agree with\n * the SDK's own decision by construction rather than by matching its prose.\n * `SurfaceState` is deliberately NOT the source: it is a derived copy, it\n * excludes the annotate tool, and a tool registered before `withBaton` ran\n * reaches it only through the retroactive sweep.\n *\n * Absent entry → the tool does not exist. Present and disabled → the vendor\n * turned it off, which is a different remedy from a missing tool and the case\n * the Console cannot classify from text at all. Present and enabled → the\n * handler existed, was callable, and still never ran.\n *\n * ⚠ **That last step is NOT always argument validation, and a first version\n * of this function said it was.** On v2 it is: `tools/call` checks existence,\n * then `enabled`, then calls `validateToolInput`, with nothing in between\n * (`mcp-DXXb3Vv3.mjs:1394-1399`). On `@modelcontextprotocol/sdk` 1.x — the\n * pinned peer — TWO more pre-handler rejections sit in that gap\n * (`mcp.js:112-122`), and one of them is reachable for a tool this package\n * wraps: `execution.taskSupport` declared on a tool registered with an\n * ordinary function callback throws `InternalError` before any argument is\n * looked at. Labelling that `invalid_argument` tells the operator the agent\n * sent bad arguments when the remedy is the VENDOR's own registration — the\n * one failure mode this member exists to prevent, reintroduced by the\n * producer instead of by a regex.\n *\n * So a tool whose entry declares one of those two task modes withdraws the\n * claim: `undefined`, which SPEC §11.4.3 permits outright (\"a producer that\n * cannot emit this member correctly MUST omit it\"). The caller still emits\n * the event — the call failed and the SDK's own message says why — it just\n * does not name a kind it cannot determine. ⚠ The small untruth that buys:\n * §11.4.3 reads an absent member as \"the vendor's handler spoke for itself\",\n * which is not what happened here. Keeping the call visible with its real\n * message is the better of the two, and this is the one shape where that\n * reading is wrong.\n *\n * ⚠ **The predicate is `TASK_MODES`, not \"is `taskSupport` set\" — which was\n * the first version and would have cost `invalid_argument` on the ENTIRE\n * pinned peer.** Measured: 1.x's `registerTool` hands\n * `{taskSupport: \"forbidden\"}` to every ordinary tool it builds\n * (`mcp.js:694,704`), so the member is populated on all of them and the\n * presence test withdrew the claim universally. Caught by\n * `aboveTool.test.ts`'s 1.x leg, which is why that case asserts the kind per\n * major rather than once. The two values below are exactly the ones the SDK\n * itself branches on, which is this function's whole discipline.\n *\n * ⚠ The predicate stays on the REGISTRY ENTRY's own configuration, never the\n * message — and 1.x's OTHER branch (`\"required\"` without task augmentation)\n * needs no clause of its own, because it is reachable only when the handler\n * is a task OBJECT, which `dispatchSlot` already answers `undefined` for and\n * the seam already declines to report on.\n *\n * ⚠ **`TASK_MODES` is a PIN, not a principle, and that is the honest reading.**\n * The other two kinds rest on POSITIVE evidence — an absent entry, an\n * `enabled: false` flag — which is why they are stable across majors.\n * `invalid_argument` is the ELSE branch: an inference from the absence of any\n * other explanation. This `Set` patches that inference by enumerating the two\n * values of one major's `taskSupport` that sit in the gap TODAY, and the SDK\n * does not branch on `taskSupport` to decide THIS question — it branches on it\n * to decide something else, which the code is reading as a proxy. So the next\n * pre-handler rejection either major adds lands in `invalid_argument`\n * silently, with nothing going red, because the elimination still \"succeeds\".\n *\n * The real fix is positive evidence: a THIRD seam around the SDK's own input\n * validation, setting a `validatorRejected` fact on `CallSlot` the way\n * `innerFired` is set, after which this function is three positive tests and\n * no `else` and `TASK_MODES` disappears. Not taken here — it is another\n * per-major internals reach-in and the two majors spell validation\n * differently. Recorded so the `Set` is read as the version pin it is.\n */\nconst TASK_MODES: ReadonlySet<unknown> = new Set([\"required\", \"optional\"]);\n\n/** The registry-entry members this decision reads, declared ONCE.\n *\n * `withBaton.ts`'s `ToolEntry` extends this with the two dispatch-target\n * members the seam needs. Declared here rather than hand-copied as a structural\n * literal because the next flag either SDK branches on has to be added in one\n * place, and `tsc` would not have noticed a second copy going stale. */\nexport interface ToolEntryFacts {\n enabled?: unknown;\n /** 1.x rejects a mis-declared task tool BEFORE argument validation, so this\n * member's VALUE is what withdraws the `invalid_argument` claim. */\n execution?: { taskSupport?: unknown } | null;\n}\n\nexport function requestSideFailureKind(\n entry: ToolEntryFacts | null | undefined,\n): FailureKind | undefined {\n // `== null`, not `=== undefined`: this entry comes out of a cast past the\n // SDK's `private`, so its shape is a declaration rather than a runtime\n // guarantee, and a null would otherwise raise a `TypeError` off a tool call\n // that was going to return the SDK's own error (SPEC §11.2 fail-open —\n // `settleCall`'s guard would catch it, but a sensor should not need one).\n if (entry == null) return \"unknown_tool\";\n if (entry.enabled === false) return \"tool_disabled\";\n return TASK_MODES.has(entry.execution?.taskSupport) ? undefined : \"invalid_argument\";\n}\n\n/** The `error_body` cap, in CODE POINTS, shared by both failure legs (SPEC\n * §11.4.3's two shapes) so a change to the limit cannot move one and leave\n * the other. Python caps the same field at the same number, and its `[:2000]`\n * counts code points — which is why the cut goes through `capCodePoints` and\n * not `String.prototype.slice`. */\nexport const ERROR_BODY_MAX_CODE_POINTS = 2000;\n\n/**\n * True if `value` is a tool result carrying MCP's error flag.\n *\n * ⚠ **No `content`-must-be-a-list guard, and SPEC §11.4.3 now scopes that\n * rule by VANTAGE POINT rather than requiring it of every producer** — the\n * section said \"MUST\" unconditionally until 2026-09-24, and this package is\n * why it moved.\n * Python's adapter receives a result the library has already converted, so an\n * object carrying an `isError` attribute for its own reasons could reach it\n * and must be excluded. This package wraps the vendor's own executor, so what\n * arrives here is the vendor's LITERAL return, and both majors merge that\n * verbatim into the wire result.\n *\n * Measured 2026-09-24 on `@modelcontextprotocol/sdk` 1.x and\n * `@modelcontextprotocol/server` 2.x: a tool returning `{isError: true,\n * rows: 0}` — no `content` at all — reaches the CLIENT as\n * `{content: [], isError: true}`. There is no such thing here as an object\n * that merely spells the flag: spelling it at the top level of a tool's return\n * IS how a TS tool reports failure. A `content` guard would make this sensor\n * miss a failure its caller can see, which is the one thing it may not do.\n *\n * So the invariant is stronger and simpler than Python's, and\n * `errorResult.test.ts` asserts it directly: **for a failure the handler\n * itself reports, this predicate agrees with what the client received.**\n *\n * ⚠ **That scope is load-bearing, because a failure the SDK manufactures\n * ABOVE this wrap point is invisible here.** Measured 2026-09-24 on both\n * majors: a tool registered with an `outputSchema` whose handler returns\n * `content` and no `structuredContent` returns a success-shaped object, so\n * this predicate correctly answers false — and then the SDK's own output\n * validation, which runs after the executor, sends the client\n * `{isError: true, content: [{text: \"Output validation error: …\"}]}`. Baton\n * files `tool_call_end`. Nothing at the handler's vantage point can see it;\n * closing it needs a wrap above the request handler, or a sensor on the wire\n * — which is what `baton-proxy` is, and why the wire probe recorded that the\n * floor an SDK cannot see, the proxy can.\n *\n * ⚠ **And moving THIS sensor up to the request handler would cost more than\n * it closed**, which is why the gap is recorded rather than chased: both\n * majors convert a thrown handler error into a returned `isError` inside that\n * handler (`mcp.js:135`, `mcp-DXXb3Vv3.mjs:1404`), so above it the two failure\n * shapes are the same object and `error_type` collapses to `tool_error` for\n * both. Python's vector pins `\"error_type\": \"ValueError\"`. The throw/return\n * distinction only exists BELOW the request handler, which is where this sits.\n *\n * Guarded end to end — this runs on the vendor's tool-call path (SPEC §11.2:\n * never block the call), so it fails to False.\n */\nexport function isErrorResult(value: unknown): boolean {\n try {\n if (typeof value !== \"object\" || value === null) return false;\n return Boolean((value as { isError?: unknown }).isError);\n } catch {\n return false;\n }\n}\n\n/**\n * The human-readable reason inside an error result.\n *\n * Joins the `content` envelope's text parts, which is where a vendor puts the\n * actual sentence (\"You do not have sufficient access to delete this\n * Project\"). This is what a human reads in the Console, so the fallback is\n * deliberately NOT `String(result)` — `[object Object]` would put noise where\n * the reason belongs. An empty string says \"no reason given\", which is honest\n * and which the Console already renders as such.\n *\n * ⚠ **No truncation here, deliberately.** The caller cuts AFTER scrubbing, to\n * `ERROR_BODY_MAX_CODE_POINTS`, on both failure legs alike.\n * Cutting inside this helper would put the truncation BEFORE the scrubber for\n * one of the two failure shapes and after it for the other — and a PII value\n * straddling the boundary would reach the scrubber as a fragment its pattern\n * cannot match, so the half that survives the cut ships unredacted. That is\n * the bug `/code-review` found in the Python change (`33581cb`); it is not\n * being ported.\n */\nexport function errorText(value: unknown): string {\n const parts: string[] = [];\n try {\n const content = (value as { content?: unknown })?.content;\n if (!Array.isArray(content)) return \"\";\n for (const part of content) {\n const text = (part as { text?: unknown })?.text;\n if (typeof text !== \"string\") continue;\n const trimmed = text.trim();\n if (trimmed) parts.push(trimmed);\n }\n } catch {\n return \"\";\n }\n return parts.join(\"\\n\");\n}\n\n/** The registered values of `resultCaptureMode` (SPEC §11.4), and the single\n * source of truth for them.\n *\n * Shaped after `identity.ts`'s `FORM_BY_MODE` → `PRINCIPAL_ID_MODES`, whose\n * own note says why: a second hand-written list makes the guarantee \"two lists\n * happen to agree\", which is the prose-shaped binding that pattern exists to\n * replace. `config.ts` builds its validator set from THIS array rather than\n * restating the literals, so a mode cannot be accepted at the door without\n * someone having given it a payload shape below. */\nexport const RESULT_CAPTURE_MODES = [\"full\", \"off\"] as const;\n\n/** What a vendor may set. Derived, so the type and the registry cannot drift. */\nexport type ResultCaptureMode = (typeof RESULT_CAPTURE_MODES)[number];\n\n/** The one registered non-default value, on the wire and in the config alike.\n * A string and not a boolean because SPEC reserves a second value for the\n * content ladder's partial rung.\n *\n * `satisfies` and NOT a type annotation: an annotation widens this to\n * `ResultCaptureMode`, and then `case WITHHELD:` stops narrowing the switches\n * below — which silently costs the exhaustiveness that is the whole point of\n * deriving the registry. This keeps the literal type AND checks membership. */\nexport const WITHHELD = \"off\" satisfies ResultCaptureMode;\n\n/** The `tool_call_end` payload members the capture mode decides.\n *\n * `result: null` under `\"off\"` is REDUNDANT here, and saying so is the point.\n * `ToolCallEndPayloadSchema.result` is `z.unknown().nullable().default(null)`,\n * so the key is present with a null value whether or not this branch names it —\n * the declare-rather-than-omit posture is the SCHEMA's, not this function's.\n * Dropping the literal yields a byte-identical wire shape and NOTHING detects\n * it. Kept because it states the intent at the site that decides the mode, not\n * because it is load-bearing.\n *\n * ⚠ **So do not look for a test that would catch its removal — there is none,\n * and two earlier versions of this paragraph named one.** The first said the\n * cross-SDK key-set check, which `withoutNulls` made blind; the second said\n * `errorResult.test.ts`'s `toContain(\"result\")`, which lives in a throw-path\n * test that never sets `resultCaptureMode` and so never enters this branch. The\n * guarantee that matters is asserted where it is produced:\n * `resultCapture.test.ts` pins `result` null under `\"off\"` on this leg. ⚠ The\n * sibling claim on the THROW leg (`withBaton.ts`) does hold —\n * `ToolCallErrorPayloadSchema.result` is `.optional()` with no default, so\n * removing that literal is detectable. Two legs, two different answers, which is\n * why this says which is which. */\n/** ⚠ PRECONDITION: call this ONLY from inside an `emit()` build thunk.\n * It applies the vendor's scrubber bare, which is correct there (a throw\n * drops the event) and wrong anywhere else (a throw reaches the agent as\n * `isError: true` on a call that worked — SPEC §11.2). This is still PROSE,\n * and prose is what let a site be missed once already: the `eslint-disable`\n * below pre-approves the bare call for any future caller, including one\n * outside a thunk. The structural fix is to take the scrubber as a thunk\n * ARGUMENT so no other caller can obtain it; recorded as F1b. */\nexport function endResultFields(\n mode: ResultCaptureMode,\n result: unknown,\n scrubber: (value: unknown) => unknown,\n): { result: unknown; result_capture?: string } {\n // The scrubber is called HERE and not by the caller: SPEC §7 says it MUST\n // NOT be invoked on a withheld result, so a helper handed an already-scrubbed\n // value would be a guard standing after the thing it guards.\n switch (mode) {\n case WITHHELD:\n return { result: null, result_capture: WITHHELD };\n case \"full\":\n // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk (both callers are thunks): emit drops the event, which is correct for a result\n return { result: scrubber(result) };\n }\n}\n\n/** The RETURN failure shape's result-derived members (SPEC §11.4.3(2)).\n *\n * Both are unwrapped FROM the result — `error_body` from its `content` text\n * parts, `result` as the whole envelope — so `\"off\"` withholds both and\n * neither `errorText` nor the scrubber runs on it.\n *\n * ⚠ `error_body` becomes `\"\"` rather than being dropped: it is REQUIRED on\n * `ToolCallErrorPayload`, and widening that array is a conformance change every\n * producer would have to follow. An empty `error_body` is genuinely ambiguous\n * with \"the failure carried no message\", and `result_capture` is what tells the\n * two apart — a second reason the marker is not optional.\n */\n/** ⚠ PRECONDITION: call this ONLY from inside an `emit()` build thunk.\n * It applies the vendor's scrubber bare, which is correct there (a throw\n * drops the event) and wrong anywhere else (a throw reaches the agent as\n * `isError: true` on a call that worked — SPEC §11.2). This is still PROSE,\n * and prose is what let a site be missed once already: the `eslint-disable`\n * below pre-approves the bare call for any future caller, including one\n * outside a thunk. The structural fix is to take the scrubber as a thunk\n * ARGUMENT so no other caller can obtain it; recorded as F1b. */\nexport function returnedErrorFields(\n mode: ResultCaptureMode,\n result: unknown,\n errorBody: (text: string) => string,\n scrubber: (value: unknown) => unknown,\n): { error_body: string; result: unknown; result_capture?: string } {\n return resultDerivedFields(mode, () => errorText(result), result, errorBody, scrubber);\n}\n\n/**\n * The same two members for ANY result-side failure, taking the text as a\n * THUNK rather than unwrapping it here.\n *\n * `returnedErrorFields` above is this with `errorText(result)` as the thunk.\n * The second caller is `failure_kind: \"output_schema_mismatch\"`, where the\n * handler returned and something above it rejected the output: the text there\n * may come off a THROWN value rather than off an envelope's `content`, so the\n * unwrapping cannot live in here.\n *\n * ⚠ **A thunk and not a string, which is the whole reason this is shaped this\n * way.** An eagerly-evaluated argument would unwrap a result the `\"off\"`\n * branch is about to discard — harmless to SPEC §7, which forbids only the\n * VENDOR's scrubber on a withheld result, but it would quietly retire the\n * property this module documents and tests: under `\"off\"` neither `errorText`\n * nor the scrubber touches the result at all.\n */\n/** ⚠ PRECONDITION: call this ONLY from inside an `emit()` build thunk — same\n * as its two siblings, and for the same reason. */\nexport function resultDerivedFields(\n mode: ResultCaptureMode,\n text: () => string,\n result: unknown,\n errorBody: (value: string) => string,\n scrubber: (value: unknown) => unknown,\n): { error_body: string; result: unknown; result_capture?: string } {\n switch (mode) {\n case WITHHELD:\n return { error_body: \"\", result: null, result_capture: WITHHELD };\n case \"full\":\n // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk (every caller is a thunk): emit drops the event, which is correct for a result\n return { error_body: errorBody(text()), result: scrubber(result) };\n }\n}\n\n/**\n * The REQUEST-SIDE failure's two body members, and it takes no capture mode\n * ON PURPOSE.\n *\n * The vendor's handler never ran, so there is no tool result anywhere in\n * this payload: `result` is null because none exists — the same reason\n * §11.4.3's RAISE shape carries null — and `error_body` is the SDK's own\n * rejection text, not anything a tool returned. Nothing here is\n * result-derived, so `\"off\"` has nothing to withhold and the event carries\n * **no `result_capture` marker**: SPEC §11.4's \"present only when results\n * are withheld\" applied, the same reading its library-path paragraph already\n * takes for an `error_body` the vendor supplied.\n *\n * ⚠ **`error_body` is KEPT under `\"off\"`, which is the rule's shape and not\n * an exception to it.** §11.4.3's table says so for all three request-side\n * kinds, and the provenance rule is why: this text describes the PRODUCER's\n * decision, the same standing as the strings `baton-proxy` authors for a\n * call it dropped. It is still scrubbed and capped — `invalid_argument`'s\n * message can echo the argument values the validator rejected, which is\n * exactly what a vendor scrubber is for.\n *\n * ⚠ **Taking a `mode` and ignoring it was the alternative, and it is worse**:\n * a reader would then have to find out WHY the switch has no branches, and a\n * later editor would add them. The absent parameter is the claim.\n */\n/** ⚠ PRECONDITION: call this ONLY from inside an `emit()` build thunk — the\n * same precondition its two siblings above carry, for the same reason: it\n * applies the vendor's scrubber (through `errorBody`) bare. */\nexport function requestSideErrorFields(\n text: string,\n errorBody: (value: string) => string,\n): { error_body: string; result: null } {\n return { error_body: errorBody(text), result: null };\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 { PRINCIPAL_ID_MODES, type PrincipalIdMode } from \"../../identity.js\";\nimport { RESULT_CAPTURE_MODES, type ResultCaptureMode } from \"./errorResult.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\"]);\n// What the vendor may ask us to do with tool RESULT data (SPEC §11.4).\n// `\"full\"` never reaches the wire — absence is what means captured.\n//\n// DERIVED from the registry, never restated — the same rule\n// `PRINCIPAL_ID_MODE_SET` below follows, and for the same reason: a\n// hand-written copy makes the guarantee \"two lists happen to agree\", so a mode\n// could be accepted here that the emitter has no payload shape for.\nconst RESULT_CAPTURE_MODE_SET: ReadonlySet<string> = new Set(RESULT_CAPTURE_MODES);\n// Imported, never restated: the registry is derived from `FORM_BY_MODE`, so a\n// mode cannot be accepted here without someone having chosen its `form`.\n// `principalFor` drops Python's unrecognised-mode branch on the strength of\n// exactly this check, so a second hand-written list would make that a\n// coincidence rather than a guarantee.\nconst PRINCIPAL_ID_MODE_SET: ReadonlySet<string> = new Set(PRINCIPAL_ID_MODES);\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). `\"required\"` (default) injects `user_goal`/`expected_result`/\n * `overall_task` string params on every wrapped tool's advertised schema\n * and ADVERTISES `user_goal` as required in `tools/list`, without enforcing\n * it: a call that omits it still reaches your handler, and its event simply\n * carries no intent. `\"optional\"` injects the same params and advertises\n * none of them as required. `\"off\"` disables injection. The 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 /** Whether tool RESPONSE data is captured at all (SPEC §11.4).\n *\n * `\"full\"` (the default) captures as it always has. `\"off\"` means nothing\n * **derived from what your tool returns** leaves this process: no `result` on\n * `tool_call_end` or `tool_call_error`, and no `error_body` on the\n * returned-failure shape, where that text is unwrapped from the result. Each\n * affected event carries `result_capture: \"off\"`, so a reader has a FACT\n * rather than an absence to guess from — without it a missing result is\n * indistinguishable from \"the tool returned nothing\", and a consumer\n * manufactures a failure that never happened.\n *\n * **Requests are unaffected**: `params` are captured in both modes.\n *\n * ⚠ The message of an error your handler THROWS is KEPT — it is your own code\n * speaking about a call that never returned, so it is not result-derived\n * (SPEC §11.4.3). Thrown messages are a classic leak channel; if that is also\n * a problem for you, say so and the mode grows a stricter value.\n *\n * Not a scrubber rule, deliberately (SPEC §7): a scrubber TRANSFORMS a value\n * that still crosses the network, this DECLARES that nothing crosses. Under\n * `\"off\"` the scrubber is never invoked on the result at all.\n *\n * What it costs you, and the rest of the reasoning: README, \"Not capturing\n * responses at all\". Kept there rather than repeated here — the two copies\n * had already drifted apart in wording by the time this was written. */\n resultCaptureMode?: ResultCaptureMode;\n /** Per-request principal identity — the ASSERTED provenance behind the\n * envelope's `principal` (SPEC §11.4 rung 0), which emits\n * `source: \"asserted\"`. It is the only provenance this SDK has.\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 both SDKs** (SPEC §11.4): unset,\n * no event carries a `principal`. For OAuth, pass `principalFromOAuthSub` or\n * `principalFromOAuthEmail`, which read the validated token the context\n * carries as `authInfo`. MCP auth is HTTP middleware, so on stdio there is no\n * token and a hook names the user from whatever the vendor authenticated.\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 per-tenant HMAC pseudonym and\n * `form: \"hashed\"`; `\"raw\"` emits the subject VERBATIM and `form: \"raw\"`.\n *\n * `\"raw\"` puts real identity in the collector's database and is the vendor's\n * deliberate choice. ⚠ A consumer classifies on `form`, never on this\n * setting — `PrincipalWireSchema` carries the rule and why it is stated that\n * way round. */\n principalIdMode?: PrincipalIdMode;\n /** The HMAC secret for hashed mode. Resolved explicit →\n * `BATON_PRINCIPAL_ID_HMAC_KEY` → unset.\n *\n * ⚠ **With none set, hashed mode DROPS the principal 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 a hashed principal: 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 a principal. 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 a principal. 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 (\n config.resultCaptureMode !== undefined &&\n !RESULT_CAPTURE_MODE_SET.has(config.resultCaptureMode)\n ) {\n // The union literal above already makes an unregistered value a COMPILE\n // error for a TypeScript caller; this covers the JavaScript one, and it\n // matters more here than for most fields because the failure is silent in\n // the one direction that cannot be undone — an unrecognised mode reads as\n // \"not off\", so bodies a vendor believed were switched off get captured\n // and sent, with no error anywhere.\n throw new Error(\n `BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ` +\n `${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`,\n );\n }\n if (config.scrubber !== undefined && typeof config.scrubber !== \"function\") {\n // Refused AT INSTALL, and `scrubOrNull` is what makes this necessary rather\n // than merely tidy. Before the fail-open guard existed, a non-function here\n // (a JS caller, or `new Scrubber().scrub()` instead of `.scrub`) threw a\n // TypeError on the FIRST tool call — loud, immediate, unmistakable. The guard\n // now catches that TypeError, warns once per field, and every scrubbed field\n // degrades to `null` for the life of the process. So the guard converted a\n // loud failure into a silent one, and the door is where that gets paid back.\n // Same argument as `resolvePrincipal` below, found by review of the commit\n // that added the guard.\n throw new Error(\"BatonConfig.scrubber must be a function.\");\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_MODE_SET.has(config.principalIdMode)) {\n throw new Error(\n `BatonConfig.principalIdMode ${JSON.stringify(config.principalIdMode)} must be one of ` +\n `${JSON.stringify([...PRINCIPAL_ID_MODE_SET].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 * `intentParamMode` selects only `user_goal`'s description label (\"REQUIRED.\"\n * or \"OPTIONAL.\"). It never makes a field enforcing: the advertisement of\n * `required` happens on the `tools/list` RESPONSE, in withBaton.ts, and\n * `buildIntentFields` says why it cannot happen here.\n */\nexport function injectGoalParams(\n inputSchema: unknown,\n intentParamMode: IntentParamMode,\n): {\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, intentParamMode);\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 intentParamMode: IntentParamMode,\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 the zod schema, in EVERY mode. That\n // 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 breaking a customer's product to collect a\n // telemetry string. For a wrapper whose whole claim is that it does not\n // change how the wrapped server behaves, that is the wrong trade at any\n // capture rate, so `required` means what it means in the proxy and in\n // Python: ADVERTISED as required, never enforced.\n //\n // The advertisement cannot come from a zod expression, and the reason is\n // structural. Measured 2026-09-01 against both zod majors this package\n // 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 holds the two apart by\n // editing the rendered JSON Schema of a `tools/list` RESPONSE, and since\n // 2026-09-15 this package does the same: withBaton.ts wraps the SDK's\n // `tools/list` handler and `advertiseUserGoalRequired` (below) appends\n // `user_goal` to each injected tool's advertised `required`. The zod field\n // built here stays optional, so validation is unchanged and a call that\n // omits `user_goal` still reaches the vendor's handler.\n //\n // What `intentParamMode` still selects here is the description's leading\n // label, so the text never contradicts the schema it ships inside.\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({ intentParamMode }));\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 * `intentParamMode` selects the `user_goal` label only, as in\n * `injectGoalParams` above.\n */\nexport function injectGoalParamsV2(\n inputSchema: unknown,\n intentParamMode: IntentParamMode,\n): {\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, intentParamMode);\n if (Object.keys(toInject).length === 0)\n return { schema: inputSchema, dispositions };\n return { schema: candidate.extend(toInject), dispositions };\n}\n\n/**\n * The advertisement half of `intentParamMode: \"required\"`, applied to a\n * RENDERED `tools/list` result: `user_goal` is appended to the `required`\n * array (created when absent) of every tool `isInjected` names, and nothing\n * else changes. Copy on write, so the SDK's own result, and anything it\n * shares with a memo, is never mutated, and a caller that catches a throw\n * from here can serve the original untouched.\n *\n * Only the RESPONSE changes. The zod schema the SDK validates with is never\n * touched, so a call omitting `user_goal` still passes validation and still\n * reaches the vendor's handler: advertised as required, never enforced.\n */\nexport function advertiseUserGoalRequired(\n result: unknown,\n isInjected: (toolName: string) => boolean,\n): unknown {\n const tools = (result as { tools?: unknown } | null | undefined)?.tools;\n if (!Array.isArray(tools)) return result;\n let changed = false;\n const advertised = tools.map((tool: unknown) => {\n const entry = tool as { name?: unknown; inputSchema?: unknown } | null;\n if (typeof entry?.name !== \"string\" || !isInjected(entry.name)) return tool;\n const schema = entry.inputSchema as { required?: unknown } | null | undefined;\n if (!schema || typeof schema !== \"object\") return tool;\n const declared: unknown = schema.required ?? [];\n if (!Array.isArray(declared)) return tool;\n const required = declared as unknown[];\n if (required.includes(USER_GOAL_PARAM_NAME)) return tool;\n changed = true;\n return { ...entry, inputSchema: { ...schema, required: [...required, USER_GOAL_PARAM_NAME] } };\n });\n return changed ? { ...(result as Record<string, unknown>), tools: advertised } : result;\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","/** Ready-made `resolvePrincipal` hooks for a server running OAuth.\n *\n * Pass one as `BatonConfig.resolvePrincipal`. Each reads a claim off the\n * validated token the context carries as `authInfo`, and returns `null` when\n * the claim is not there — so they compose:\n *\n * ```ts\n * resolvePrincipal: (ctx) => principalFromOAuthEmail(ctx) ?? principalFromOAuthSub(ctx)\n * ```\n *\n * They are ordinary hooks: what they return is `source: \"asserted\"` like any\n * other (SPEC §11.4). The Python twins are `principal_from_oauth_sub` and\n * `principal_from_oauth_email`, and the two must agree on one token.\n *\n * ⚠ **They read the claims from `authInfo.extra`, and that is a convention,\n * not a contract.** Neither MCP major's `AuthInfo` has a `claims` member — the\n * only place a verifier can put the token's subject is the free-form `extra`\n * bag, and nothing specifies the keys. These hooks expect the standard JWT\n * claim names (`sub`, `iss`, `email`) at the top of `extra`, which is what a\n * verifier that spreads its decoded payload into `extra` produces. A verifier\n * that nests them, renames them or omits them gets `null` here, and its vendor\n * writes a three-line hook reading wherever their verifier put them. Python\n * reads a typed `claims` field instead, which is why the two arms describe the\n * same hooks differently.\n *\n * ⚠ **Never `clientId`.** It names the OAuth APPLICATION, not the person, and\n * is identical for every user of one app; keying on it merges all of them.\n *\n * HTTP only: MCP auth is HTTP middleware, so a stdio call has no token and both\n * hooks return `null` there.\n */\n\nimport { type Principal, pythonStrip } from \"../../identity.js\";\nimport { type PrincipalResolutionContext } from \"./principalResolution.js\";\n\n/** The token's claim bag, or `null`. Never throws: it reads an object a\n * vendor's verifier built, and an identity read may not fail a tool call. */\n// `iss` is coerced in the hook as well as in `normalizePrincipal`: these are\n// public exports, and a vendor wrapping one reads `.issuer` first.\n\nfunction claimsOf(\n context: PrincipalResolutionContext,\n): Record<string, unknown> | null {\n try {\n const extra = context.authInfo?.extra;\n return extra !== null && typeof extra === \"object\" ? extra : null;\n } catch {\n return null;\n }\n}\n\n/** A non-blank string claim, or `null`. Blank is a miss because the hash\n * canonicalizes (strips), so every whitespace-only value is one phantom actor.\n *\n * ⚠ `pythonStrip`, never `.trim()`: the two strip different codepoints\n * (`\\x1f` survives `.trim()`, U+FEFF survives Python's `strip()`), and the\n * Python twins decide blankness with `strip()`. With `.trim()` one token gave a\n * principal on one SDK and none on the other under `email ?? sub`. */\nfunction stringClaim(claims: Record<string, unknown>, name: string): string | null {\n const value = claims[name];\n return typeof value === \"string\" && pythonStrip(value) !== \"\" ? value : null;\n}\n\n/** The token's `sub`, keyed with its `iss` — a subject is unique only per\n * issuer, so two identity providers can hand two people the same one. */\nexport function principalFromOAuthSub(\n context: PrincipalResolutionContext,\n): Principal | null {\n const claims = claimsOf(context);\n if (claims === null) return null;\n const sub = stringClaim(claims, \"sub\");\n const iss = claims.iss;\n return sub === null ? null : { principalId: sub, issuer: typeof iss === \"string\" && iss !== \"\" ? iss : null };\n}\n\n/** The token's `email`, as the WHOLE address and with NO issuer.\n *\n * `principalId` is the whole address and `displayName` the part before the\n * last `@`. The local part alone is not an id — `alice@acme.com` and\n * `alice@contoso.com` are two people. `displayName` IS sent, in every mode: a\n * vendor who hashes ids and does not want `alice` on the wire writes their\n * own hook.\n *\n * No issuer, unlike the `sub` hook: a subject is unique only per issuer, an\n * address on its own, and folding `iss` in would give one person a new\n * pseudonym the day their identity provider changes its issuer URL.\n *\n * ⚠ `email` is not a standard ACCESS-token claim (OIDC puts it in the ID\n * token), so it is here only if the identity provider adds it and the verifier\n * keeps it. `email_verified` is not consulted: whether an unverified address is\n * good enough is the vendor's call. */\nexport function principalFromOAuthEmail(\n context: PrincipalResolutionContext,\n): Principal | null {\n const claims = claimsOf(context);\n if (claims === null) return null;\n const email = stringClaim(claims, \"email\");\n if (email === null) return null;\n const at = email.lastIndexOf(\"@\");\n return {\n principalId: email,\n displayName: at > 0 ? email.slice(0, at) : null,\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;AAA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AQ;AAC1E;AAIO,SAAS,sBACd,SACkB;AAClB,QAAM,SAAS,SAAS,OAAO;AAC/B,MAAI,WAAW,KAAM,QAAO;AAC5B,QAAM,MAAM,YAAY,QAAQ,KAAK;AACrC,QAAM,MAAM,OAAO;AACnB,SAAO,QAAQ,OAAO,OAAO,EAAE,aAAa,KAAK,QAAQ,OAAO,QAAQ,YAAY,QAAQ,KAAK,MAAM,KAAK;AAC9G;AAkBO,SAAS,wBACd,SACkB;AAClB,QAAM,SAAS,SAAS,OAAO;AAC/B,MAAI,WAAW,KAAM,QAAO;AAC5B,QAAM,QAAQ,YAAY,QAAQ,OAAO;AACzC,MAAI,UAAU,KAAM,QAAO;AAC3B,QAAM,KAAK,MAAM,YAAY,GAAG;AAChC,SAAO;AAAA,IACL,aAAa;AAAA,IACb,aAAa,KAAK,IAAI,MAAM,MAAM,GAAG,EAAE,IAAI;AAAA,EAC7C;AACF;","names":["uuidv7","import_uuid","import_zod","isPlainObject","warn","errorBody","import_zod","zV4","zV3","import_node_crypto","uuidv7","durationMs"]}
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/metaCoordinates.ts","../src/_text.ts","../src/identity.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/safeScrub.ts","../src/integrations/mcp/runtimeAdapter.ts","../src/integrations/mcp/sessionResolution.ts","../src/dsn.ts","../src/integrations/mcp/errorResult.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","../src/integrations/mcp/oauthHooks.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 // The twelve resource/prompt lifecycle types (SPEC §11.4.4). Exported for\n // the reason `f1b7ab2` exported `ResultCaptureMode`: the rolled-up\n // `dist/index.d.ts` carries them transitively, because `Event` references\n // them, but WITHOUT `export` — so a vendor could not name one and had to\n // spell `Extract<Event, {event_type: \"resource_read_start\"}>` instead.\n ResourceListStartEvent,\n ResourceListStartPayload,\n ResourceListEndEvent,\n ResourceListEndPayload,\n ResourceListErrorEvent,\n ResourceListErrorPayload,\n ResourceReadStartEvent,\n ResourceReadStartPayload,\n ResourceReadEndEvent,\n ResourceReadEndPayload,\n ResourceReadErrorEvent,\n ResourceReadErrorPayload,\n PromptListStartEvent,\n PromptListStartPayload,\n PromptListEndEvent,\n PromptListEndPayload,\n PromptListErrorEvent,\n PromptListErrorPayload,\n PromptGetStartEvent,\n PromptGetStartPayload,\n PromptGetEndEvent,\n PromptGetEndPayload,\n PromptGetErrorEvent,\n PromptGetErrorPayload,\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 PrincipalWireSchema,\n ResourceListStartEventSchema,\n ResourceListStartPayloadSchema,\n ResourceListEndEventSchema,\n ResourceListEndPayloadSchema,\n ResourceListErrorEventSchema,\n ResourceListErrorPayloadSchema,\n ResourceReadStartEventSchema,\n ResourceReadStartPayloadSchema,\n ResourceReadEndEventSchema,\n ResourceReadEndPayloadSchema,\n ResourceReadErrorEventSchema,\n ResourceReadErrorPayloadSchema,\n PromptListStartEventSchema,\n PromptListStartPayloadSchema,\n PromptListEndEventSchema,\n PromptListEndPayloadSchema,\n PromptListErrorEventSchema,\n PromptListErrorPayloadSchema,\n PromptGetStartEventSchema,\n PromptGetStartPayloadSchema,\n PromptGetEndEventSchema,\n PromptGetEndPayloadSchema,\n PromptGetErrorEventSchema,\n PromptGetErrorPayloadSchema,\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\";\n// `BatonConfig.resultCaptureMode` is typed with it, so a vendor cannot name\n// the field's type without it.\nexport type { ResultCaptureMode } 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`, `PrincipalForm` and\n// `PrincipalResolutionContext` are what a vendor's `resolvePrincipal` hook\n// signs its function against, so a vendor cannot write a typed hook without\n// naming them.\nexport type { Principal, PrincipalForm } from \"./identity.js\";\n// `PrincipalWire` and `principalFor` are NOT exported: they are the\n// PRODUCER's, and `principalFor` is the single construction site for the wire\n// object. `Event.principal` is inferred from `PrincipalWireSchema`, whose\n// members are deliberately open, so a consumer wanting a name for the\n// received shape uses `z.infer<typeof PrincipalWireSchema>` or\n// `Event[\"principal\"]`.\nexport {\n PRINCIPAL_FORM_HASHED,\n PRINCIPAL_FORM_RAW,\n PRINCIPAL_SOURCE_ASSERTED,\n} from \"./identity.js\";\nexport type {\n AuthInfo,\n ResolvePrincipalHook,\n PrincipalResolutionContext,\n} from \"./integrations/mcp/index.js\";\n// The ready-made hooks — the OAuth case is common enough to ship, and a vendor\n// whose verifier keeps claims elsewhere writes their own (see `oauthHooks.ts`).\nexport { principalFromOAuthEmail, principalFromOAuthSub } 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.5.2\";\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\";\nimport type { PrincipalWire } from \"./identity.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 // SPEC §11.4: the producer declares it WITHHELD result-derived data.\n // Absent means CAPTURED, so no consumer needs a version table.\n //\n // `.optional()`, NOT `.default(null)`, for the reason recorded on\n // `ToolCallErrorPayloadSchema.result` below: a default makes this reader\n // an EMITTER, and parsing a stored event from before the member existed\n // would hand back an invented key.\n //\n // ⚠ **This package OMITS the member when capturing, where the Python SDK\n // sends `result_capture: null`.** Both are conformant and SPEC §11.4 says\n // so outright — absent and null are equivalent, and a consumer MUST read\n // the VALUE, never test for the key. It is the same axis `result` already\n // differs on between `baton-sdk` (null) and `baton-proxy` (omitted), per\n // §11.4.3. Omitting is chosen here because the alternative — matching\n // Python — would require regenerating `baton-spec`'s vectors from an\n // UNMERGED branch, pinning a key set no released producer emits.\n result_capture: z.string().nullable().optional(),\n })\n .strict();\nexport type ToolCallEndPayload = z.infer<typeof ToolCallEndPayloadSchema>;\n\n/** Emitted when the call FAILED, which MCP expresses two ways (SPEC §11.4.3):\n * the vendor handler throws, or it returns a result carrying MCP's error flag\n * on a 200. `error_type` is the error's constructor name for a throw and the\n * registered value `\"tool_error\"` for a returned flag; `error_body` is the\n * message or the unwrapped reason (PII-scrubbed, then capped — the limit and\n * its unit live on `ERROR_BODY_MAX_CODE_POINTS` in\n * `integrations/mcp/errorResult.ts`, which both failure legs cut with).\n *\n * ⚠ This schema ACCEPTED `result` one commit before this producer emitted\n * it (`67453eb`), and the split was deliberate. Unlike `baton-console`'s\n * ingest — which forbids unknown keys on the envelope only, leaving `payload`\n * an opaque dict — this schema is `.strict()` down to the payload, and\n * `test/conformance.test.ts` parses every `baton-spec` vector through it. So\n * the `baton-spec` bump carrying the field would have reddened this suite on\n * BOTH error vectors, the throw-shape one included, because it now carries\n * `result: null`. Accepting first is what made that bump safe.\n *\n * `result` carries the full result envelope on the returned shape and is null\n * on a throw, where no result object exists.\n *\n * ⚠ **THE shape claim for this field lives here; everywhere else points at\n * this paragraph.** On THIS producer `tool_call_error.result` and\n * `tool_call_end.result` are the SAME shape — the object the vendor's handler\n * returned, `{content, isError?}`, which neither major converts. The sentence\n * that stood here said `result` is \"deliberately NOT unwrapped the way\n * `tool_call_end.result` unwraps to the developer's return\"; that is Python's\n * contrast, carried over with the rest of the port, and it is FALSE here.\n * SPEC §11.4.3's requirement still binds — whatever is recorded must keep the\n * flag and the reason, which the literal does — but a consumer must not read\n * a TS-sourced `tool_call_end.result` as the bare content array Python's\n * vector shows.\n *\n * Enforced by `emitterConformance.test.ts`'s\n * `PAYLOAD_ALLOWED_TO_DIFFER[\"tool_call_error.returned\"]` and the two shape\n * assertions beside it: the claim stops being true the day that test reds. */\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 // ⚠ `.optional()`, NOT `.default(null)` like the sibling fields — and it\n // stays that way now that the producer emits the field.\n //\n // A default makes the schema an EMITTER: parsing a payload without the key\n // ADDS it. That is wrong in a schema that also READS — a stored event from\n // before the field existed would come back carrying an invented key, and\n // against the pre-`f1e0280` spec pin, whose `events.schema.json` is\n // `additionalProperties: false`, it reddened three tests saying so: a\n // byte-identical vector round-trip, an ajv validation of TS-built events,\n // and a field-for-field payload comparison.\n //\n // `.optional()` accepts the field when a vector carries it and stays\n // silent when it does not. What makes the EMITTED shape complete is the\n // emitter declaring `result` on both failure legs (`withBaton.ts`),\n // explicitly `null` on a throw — not the schema filling it in.\n result: z.unknown().nullable().optional(),\n // SPEC §11.4, on BOTH payloads because the RETURN failure shape withholds\n // `result` too. Same `.optional()` reasoning as the field above it, and\n // same omit-when-capturing posture as `ToolCallEndPayloadSchema`.\n result_capture: z.string().nullable().optional(),\n // SPEC §11.4.3: the producer NAMES a failure it made above the vendor's\n // handler. `tool_call_error` ONLY — unlike `result_capture`, which rides\n // both payloads — because the one case that files `tool_call_end` today\n // IS the false success this member exists to correct, so after the fix\n // nothing carries it on a success payload.\n //\n // A plain `z.string()` and NOT `z.enum(FAILURE_KINDS)`, which SPEC\n // requires rather than permits: a closed enum turns a later registered\n // value into a `ValidationError` on the vendor's tool-call path, which\n // §11.2 says must fail open. The registry in\n // `integrations/mcp/errorResult.ts` constrains what this producer EMITS;\n // it must not constrain what this schema READS.\n //\n // Same `.optional()`-not-`.default(null)` reasoning as the two fields\n // above: a default makes the schema an emitter, and parsing a stored\n // event from before the member existed would hand back an invented key.\n failure_kind: z.string().nullable().optional(),\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/** The principal as emitted — `{id, source, form}`, all three REQUIRED\n * together, plus an optional `display_name` (SPEC §11.4). The runtime shape\n * of `identity.PrincipalWire`.\n *\n * `.strict()` mirrors Python's `extra=\"forbid\"`: a member this producer does\n * not know about is a malformed object, not a richer one.\n *\n * ⚠ **`source` and `form` are `z.string()`, not enums, on purpose** — the same\n * decision `transport_observed` records and the collector's own columns make.\n * A fourth `source` is already foreseen (alias-derived), and an enum would\n * make this producer unable to emit a value SPEC registers later without a\n * release. Worse, it would throw at the emit boundary — `emit()` catches that\n * and DROPS the event, so the tool call survives and the capture does not,\n * which is still the wrong trade for a value SPEC may register later. The\n * safety lives in the consumer rules stated positively — trust only exactly\n * `\"attested\"`, treat anything but exactly `\"hashed\"` as personal data — so an\n * unregistered value fails safe without anything having to reject it. */\nexport const PrincipalWireSchema = z\n .object({\n id: z.string(),\n source: z.string(),\n form: z.string(),\n display_name: z.string().nullable().optional(),\n })\n .strict();\n\n// ⚠ **The producer type and this schema are two declarations of one wire\n// shape, and this is what makes them agree.** Every other wire type in this\n// file is projected with `z.infer`; this one cannot be, because the producer\n// side is deliberately NARROWER (literal `source`/`form`) than the parse side\n// (open `z.string()`) — see `identity.PrincipalWire`.\n//\n// Without the check below the drift is silent in the worst direction: add a\n// member to `PrincipalWire`, and `principalFor` compiles green while\n// `.strict()` rejects the object at the emit boundary, where `emit()` catches\n// the throw and DROPS the event. Capture loss with no error at the site of\n// the change. Asserting the KEY SETS match both ways turns that into a\n// compile error here.\ntype _PrincipalKeysMatch =\n [Exclude<keyof PrincipalWire, keyof z.infer<typeof PrincipalWireSchema>>] extends [never]\n ? [Exclude<keyof z.infer<typeof PrincipalWireSchema>, keyof PrincipalWire>] extends [never]\n ? true\n : never\n : never;\nconst _principalKeysMatch: _PrincipalKeysMatch = true;\nvoid _principalKeysMatch;\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 * `principal` is the resolved principal as emitted — `{id, source, form}`, all\n * three required together, as the vendor's resolver returned and classified\n * it; null when nobody was resolved.\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: PrincipalWireSchema.nullable().default(null),\n transport_observed: 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 // The RESOURCE and PROMPT lifecycles (SPEC §11.4.4). Twelve types whose\n // shapes were set by `baton-proxy`, which has been emitting all of them in\n // production — see the payload schemas below.\n \"resource_list_start\",\n \"resource_list_end\",\n \"resource_list_error\",\n \"resource_read_start\",\n \"resource_read_end\",\n \"resource_read_error\",\n \"prompt_list_start\",\n \"prompt_list_end\",\n \"prompt_list_error\",\n \"prompt_get_start\",\n \"prompt_get_end\",\n \"prompt_get_error\",\n]);\nexport type EventType = z.infer<typeof EventTypeSchema>;\n\n\n// =============================================================================\n// Resource and prompt lifecycle payloads (SPEC §11.4.4)\n// =============================================================================\n//\n// ⚠ **Transcribed from `baton_proxy.emitter`, field for field, because that\n// producer SHIPPED FIRST.** All twelve types have been reaching the Console in\n// production — whose ingest `EventType` lists every one of them — and until\n// the `baton-spec` bump that accompanies this file they had no schema anywhere.\n// So these do not design a shape, they RECORD one, and where the proxy's\n// choices look inconsistent the inconsistency is preserved and annotated: a\n// second producer must copy the shape rather than infer a rule from half of it.\n//\n// ⚠ **No `result_capture` on any of the twelve, and SPEC §11.4.4 makes that\n// normative rather than incidental.** None of these payloads carries a body —\n// a read records its URI and its timing, a list records a count — so there is\n// nothing for `\"off\"` to withhold. The `*_start` payloads DO carry caller data\n// in `params`, which is scrubbed like any other payload; §11.4 says outright\n// that the member is not a statement about request data.\n//\n// ⚠ **No `result` and no `failure_kind` on the six error payloads.** The error\n// flag is a TOOL concept: a failing resource read comes back as a JSON-RPC\n// error, so these carry only §11.4.3's RAISE analogue and that subsection's\n// RETURN discriminator has no counterpart here.\n\n/** `duration_ms`, written once. SPEC defines the member once and eight of the\n * twelve lifecycle payloads carry it, so widening it (to a float, say, or to\n * non-nullable) must not be an eight-site edit where a miss leaves two payload\n * families disagreeing about a member the spec gives one definition. Same\n * spread idiom `envelopeShape` already establishes below. */\nconst timingShape = { duration_ms: z.number().int().nullable().default(null) };\n\n/** The two members every lifecycle FAILURE payload carries, plus its timing.\n * See `ResourceReadErrorPayloadSchema` for how `error_type` is spelled across\n * producers and why `error_body` is kept under every capture mode. */\nconst failureShape = { error_type: z.string(), error_body: z.string(), ...timingShape };\n\n/** `resources/list` reached the server. Deliberately EMPTY — a list request\n * has no subject, and the envelope already names the session, the tenant and\n * the vendor. `.strict()` with no members is the claim, not an oversight. */\nexport const ResourceListStartPayloadSchema = z.object({}).strict();\nexport type ResourceListStartPayload = z.infer<typeof ResourceListStartPayloadSchema>;\n\n/** `resources/list` returned.\n *\n * ⚠ `count` counts the `resources` array ALONE. Resource TEMPLATES are a\n * separate MCP method with their own result array and are not added in, so a\n * template-only server reports `0` — correctly — and a consumer MUST NOT read\n * that as \"this server has no resources\". */\nexport const ResourceListEndPayloadSchema = z\n .object({\n count: z.number().int(),\n ...timingShape,\n })\n .strict();\nexport type ResourceListEndPayload = z.infer<typeof ResourceListEndPayloadSchema>;\n\n/** `resources/list` failed. See `ResourceReadErrorPayloadSchema` for how\n * `error_type` is spelled across producers and why `error_body` is kept. */\nexport const ResourceListErrorPayloadSchema = z\n .object({\n ...failureShape,\n })\n .strict();\nexport type ResourceListErrorPayload = z.infer<typeof ResourceListErrorPayloadSchema>;\n\n/** `resources/read` reached the server.\n *\n * ⚠ **`uri` is ALSO inside `params`.** The proxy builds `params` by removing\n * `_meta` from the request's params and nothing else, and `uri` is one of\n * them — so the subject appears twice. Recorded rather than deduplicated: the\n * dedicated member is what a consumer reads, the bag is what the caller\n * actually sent, and a producer that stripped `uri` out of it would stop being\n * able to say that. */\nexport const ResourceReadStartPayloadSchema = z\n .object({\n uri: z.string(),\n /** The caller's own request params, PII-scrubbed (SPEC §7).\n *\n * ⚠ Nullable because the SCHEMA permits it, not because this producer\n * emits it: `withBaton`'s `paramsBag` answers `{}` for an absent bag,\n * matching `baton-proxy` (`dict(params) if params else {}` — it never\n * emits null). A consumer must still read both, since the schema admits\n * both and a third producer may choose either. */\n params: z.record(z.string(), z.unknown()).nullable().default(null),\n })\n .strict();\nexport type ResourceReadStartPayload = z.infer<typeof ResourceReadStartPayloadSchema>;\n\n/** `resources/read` returned.\n *\n * ⚠ **No content member, and that is the design.** The resource BODY is\n * customer data of exactly the kind the response-capture switch exists to keep\n * off the wire, and the only producer there was never sent it. URI plus timing\n * is what makes a failing or slow read visible without it. */\nexport const ResourceReadEndPayloadSchema = z\n .object({\n uri: z.string(),\n ...timingShape,\n })\n .strict();\nexport type ResourceReadEndPayload = z.infer<typeof ResourceReadEndPayloadSchema>;\n\n/** `resources/read` failed.\n *\n * ⚠ **`error_type` is an unconstrained string and the producers do NOT agree\n * on how to spell it** — stated here for all six error payloads.\n * `baton-proxy` reads the WIRE, so it holds the upstream's JSON-RPC error and\n * files the numeric `code` as a string; this package holds a live exception\n * and files its class name, the way §11.4.3's RAISE shape already does for\n * tools. Both conform — §11.4.3 says this member separates SHAPES and is not a\n * closed set of values — and a consumer MUST NOT read one producer's spelling\n * as the vocabulary.\n *\n * ⚠ **`error_body` is KEPT under every capture mode.** It is a failed FETCH's\n * message, not anything a resource returned, so nothing here is\n * result-derived. */\nexport const ResourceReadErrorPayloadSchema = z\n .object({\n uri: z.string(),\n ...failureShape,\n })\n .strict();\nexport type ResourceReadErrorPayload = z.infer<typeof ResourceReadErrorPayloadSchema>;\n\n/** `prompts/list` reached the server. Empty, for the reason\n * `ResourceListStartPayloadSchema` carries. */\nexport const PromptListStartPayloadSchema = z.object({}).strict();\nexport type PromptListStartPayload = z.infer<typeof PromptListStartPayloadSchema>;\n\n/** `prompts/list` returned. `count` counts the `prompts` array. */\nexport const PromptListEndPayloadSchema = z\n .object({\n count: z.number().int(),\n ...timingShape,\n })\n .strict();\nexport type PromptListEndPayload = z.infer<typeof PromptListEndPayloadSchema>;\n\n/** `prompts/list` failed. See `ResourceReadErrorPayloadSchema`. */\nexport const PromptListErrorPayloadSchema = z\n .object({\n ...failureShape,\n })\n .strict();\nexport type PromptListErrorPayload = z.infer<typeof PromptListErrorPayloadSchema>;\n\n/** `prompts/get` reached the server.\n *\n * ⚠ **`params` is the request's `arguments` member ALONE, not the whole params\n * bag** — the opposite of `ResourceReadStartPayloadSchema`'s choice, measured\n * in the proxy. The two are inconsistent in the only producer that existed;\n * the inconsistency is recorded so a reader does not expect `name` inside\n * `params` the way `uri` does appear there. */\nexport const PromptGetStartPayloadSchema = z\n .object({\n name: z.string(),\n /** The prompt's arguments, PII-scrubbed (SPEC §7). `{}` from this producer\n * where the request supplied none — see `ResourceReadStartPayloadSchema`'s\n * `params` for why the schema is nullable anyway. */\n params: z.record(z.string(), z.unknown()).nullable().default(null),\n })\n .strict();\nexport type PromptGetStartPayload = z.infer<typeof PromptGetStartPayloadSchema>;\n\n/** `prompts/get` returned.\n *\n * ⚠ **No rendered messages.** A prompt's text is authored by the SERVER rather\n * than fetched by a tool, so whether it is customer content at all is a\n * decision nobody has taken — and the standing answer, from the only producer,\n * is that it does not egress. */\nexport const PromptGetEndPayloadSchema = z\n .object({\n name: z.string(),\n ...timingShape,\n })\n .strict();\nexport type PromptGetEndPayload = z.infer<typeof PromptGetEndPayloadSchema>;\n\n/** `prompts/get` failed. See `ResourceReadErrorPayloadSchema`. */\nexport const PromptGetErrorPayloadSchema = z\n .object({\n name: z.string(),\n ...failureShape,\n })\n .strict();\nexport type PromptGetErrorPayload = z.infer<typeof PromptGetErrorPayloadSchema>;\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// ⚠ The twelve lifecycle events carry the SAME `envelopeShape` as the five\n// above, which is what lets one collector endpoint accept all seventeen and\n// one worker order them on `(session_id, sequence_number)`. `call_id` stays\n// absent on them: no producer mints one for these types, so SPEC §11.5.4's\n// FIFO floor is all a consumer has for pairing — recorded rather than fixed.\n\nexport const ResourceListStartEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"resource_list_start\").default(\"resource_list_start\"),\n payload: ResourceListStartPayloadSchema,\n })\n .strict();\nexport type ResourceListStartEvent = z.infer<typeof ResourceListStartEventSchema>;\n\nexport const ResourceListEndEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"resource_list_end\").default(\"resource_list_end\"),\n payload: ResourceListEndPayloadSchema,\n })\n .strict();\nexport type ResourceListEndEvent = z.infer<typeof ResourceListEndEventSchema>;\n\nexport const ResourceListErrorEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"resource_list_error\").default(\"resource_list_error\"),\n payload: ResourceListErrorPayloadSchema,\n })\n .strict();\nexport type ResourceListErrorEvent = z.infer<typeof ResourceListErrorEventSchema>;\n\nexport const ResourceReadStartEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"resource_read_start\").default(\"resource_read_start\"),\n payload: ResourceReadStartPayloadSchema,\n })\n .strict();\nexport type ResourceReadStartEvent = z.infer<typeof ResourceReadStartEventSchema>;\n\nexport const ResourceReadEndEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"resource_read_end\").default(\"resource_read_end\"),\n payload: ResourceReadEndPayloadSchema,\n })\n .strict();\nexport type ResourceReadEndEvent = z.infer<typeof ResourceReadEndEventSchema>;\n\nexport const ResourceReadErrorEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"resource_read_error\").default(\"resource_read_error\"),\n payload: ResourceReadErrorPayloadSchema,\n })\n .strict();\nexport type ResourceReadErrorEvent = z.infer<typeof ResourceReadErrorEventSchema>;\n\nexport const PromptListStartEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"prompt_list_start\").default(\"prompt_list_start\"),\n payload: PromptListStartPayloadSchema,\n })\n .strict();\nexport type PromptListStartEvent = z.infer<typeof PromptListStartEventSchema>;\n\nexport const PromptListEndEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"prompt_list_end\").default(\"prompt_list_end\"),\n payload: PromptListEndPayloadSchema,\n })\n .strict();\nexport type PromptListEndEvent = z.infer<typeof PromptListEndEventSchema>;\n\nexport const PromptListErrorEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"prompt_list_error\").default(\"prompt_list_error\"),\n payload: PromptListErrorPayloadSchema,\n })\n .strict();\nexport type PromptListErrorEvent = z.infer<typeof PromptListErrorEventSchema>;\n\nexport const PromptGetStartEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"prompt_get_start\").default(\"prompt_get_start\"),\n payload: PromptGetStartPayloadSchema,\n })\n .strict();\nexport type PromptGetStartEvent = z.infer<typeof PromptGetStartEventSchema>;\n\nexport const PromptGetEndEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"prompt_get_end\").default(\"prompt_get_end\"),\n payload: PromptGetEndPayloadSchema,\n })\n .strict();\nexport type PromptGetEndEvent = z.infer<typeof PromptGetEndEventSchema>;\n\nexport const PromptGetErrorEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"prompt_get_error\").default(\"prompt_get_error\"),\n payload: PromptGetErrorPayloadSchema,\n })\n .strict();\nexport type PromptGetErrorEvent = z.infer<typeof PromptGetErrorEventSchema>;\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 ResourceListStartEventSchema,\n ResourceListEndEventSchema,\n ResourceListErrorEventSchema,\n ResourceReadStartEventSchema,\n ResourceReadEndEventSchema,\n ResourceReadErrorEventSchema,\n PromptListStartEventSchema,\n PromptListEndEventSchema,\n PromptListErrorEventSchema,\n PromptGetStartEventSchema,\n PromptGetEndEventSchema,\n PromptGetErrorEventSchema,\n]);\n/** ⚠ DERIVED, not hand-listed. It used to be a third list of the same\n * seventeen members, after `EventTypeSchema` and `EventSchema`'s own branches,\n * and the twelve lifecycle types made that visible: three lists to keep in\n * step. `EventSchema` is the discriminated union over exactly these schemas,\n * so its inferred output type IS this union — verified mutually assignable\n * against the hand-written version before the switch.\n *\n * `EventTypeSchema` stays hand-written on purpose: `test/packaging.test.ts`\n * derives its export guard FROM it, which makes it the source of truth rather\n * than a fourth copy. */\nexport type Event = z.infer<typeof EventSchema>;\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` — the latter on FAILURE, which MCP expresses two ways\n * (SPEC §11.4.3): the vendor handler throws, or it returns a result carrying\n * MCP's error flag on a 200. Reading only the first is what this package did,\n * and what §6.1's own wording told it to. Injects server `instructions`\n * (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 is not here yet\" 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 { AsyncLocalStorage } from \"node:async_hooks\";\nimport { v7 as uuidv7 } from \"uuid\";\nimport {\n AnnotationEventSchema,\n type Event,\n PromptGetEndEventSchema,\n PromptGetErrorEventSchema,\n PromptGetStartEventSchema,\n PromptListEndEventSchema,\n PromptListErrorEventSchema,\n PromptListStartEventSchema,\n ResourceListEndEventSchema,\n ResourceListErrorEventSchema,\n ResourceListStartEventSchema,\n ResourceReadEndEventSchema,\n ResourceReadErrorEventSchema,\n ResourceReadStartEventSchema,\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 { scrubOrNull } from \"./safeScrub.js\";\nimport { roundMetaCoordinates } from \"../../metaCoordinates.js\";\nimport {\n resolveBatonConfig,\n resolveTenantId,\n type BatonConfig,\n} from \"./config.js\";\nimport { captureDisabled, DisabledSink, logDisabled } from \"../../optout.js\";\nimport { capCodePoints } from \"../../_text.js\";\nimport { emit } from \"./emit.js\";\nimport {\n ERROR_BODY_MAX_CODE_POINTS,\n endResultFields,\n errorText,\n type FailureKind,\n OUTPUT_SCHEMA_MISMATCH,\n requestSideErrorFields,\n requestSideFailureKind,\n type ResultCaptureMode,\n type ToolEntryFacts,\n resultDerivedFields,\n returnedErrorFields,\n isErrorResult,\n TOOL_ERROR_TYPE,\n} from \"./errorResult.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, observeTransport, 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 resolveCallPrincipal,\n} from \"./principalResolution.js\";\nimport { SessionCounter } from \"./sessionCounter.js\";\nimport {\n advertiseUserGoalRequired,\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 /** Whether result-derived data is withheld (SPEC §11.4). Validated once at\n * the config door, like `intentParamMode`, so nothing downstream re-checks\n * it. */\n resultCaptureMode: ResultCaptureMode;\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 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`, `server.server._serverInfo` and\n// `server.server._requestHandlers` (with the `setRequestHandler` that fills\n// it, for the `tools/list` seam) 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/**\n * What the OUTER `tools/call` seam saw once the request handler was done with\n * it — the only thing the outer tells the inner.\n *\n * Both majors convert a thrown vendor handler into a returned `isError`\n * INSIDE their `tools/call` handler, so `raised` here is NOT the vendor's\n * raise: it is a failure the SDK threw out of the handler entirely, which on\n * v2 is how an unknown or disabled tool arrives\n * (`mcp-DXXb3Vv3.mjs:1394-1397`, both outside that handler's own `try`).\n */\ntype OuterOutcome = { failed: boolean } & (\n | {\n /** `tools/call` THREW. Its own member rather than `err !== undefined`,\n * because `throw undefined` is legal and must not read as a return. */\n raised: true;\n /** The value thrown out of `tools/call`. */\n err: unknown;\n }\n | {\n raised: false;\n /** What `tools/call` returned. On a failure this is the SDK's own error\n * envelope — `createToolError`'s on both majors — not the vendor's\n * value. */\n result: unknown;\n }\n);\n\n/** `tools/call` came back cleanly. A constant because it is the initial value\n * AND the outcome handed to a flush that is not the outer's to judge — two\n * sites, and a fifth member on `OuterOutcome` must not reach only one. */\nconst CLEAN_OUTCOME: OuterOutcome = { failed: false, raised: false, result: undefined };\n\n/**\n * The per-call hand-off between Baton's two seams (SPEC §11.4.3's\n * `failure_kind`).\n *\n * ⚠ **`innerFired` is the discriminator for REQUEST-side vs result-side, and\n * it is the one the withholding rule needs too** — which is why the slot\n * carries no second field for it. `false` means the vendor's handler never ran, so the failure is\n * REQUEST-side and nothing on the payload is derived from a result (`\"off\"`\n * withholds nothing). `true` plus a failure at the outer means the handler\n * returned and something above it rejected what came back, so the failure is\n * RESULT-side and `\"off\"` withholds it. The hand-off and the provenance rule\n * are one mechanism; measured 2026-10-01 on both majors.\n *\n * ⚠ **It is not, however, the ONLY fact the settle reads, and an earlier\n * version of this paragraph said it was.** `settleCall` reads\n * `flushTerminal !== null` FIRST, so the real state space has three members —\n * inner unreached, inner reached but parked nothing (`openCall` threw), inner\n * reached and parked — and the third is subdivided by WHICH lane parked. That\n * last fact travels as the choice between `parkFailure` and `parkSuccess`\n * rather than as a field, which is what let the claim read as true.\n *\n * ⚠ **`flushTerminal` exists because two terminal events on one `call_id`\n * would break pairing** (SPEC §11.5.4 tier 1). The inner has already decided\n * which terminal event this call deserves by the time the outer learns the\n * call failed, so it PARKS that decision as a closure instead of emitting it,\n * and the outer flushes or replaces it. Parking a closure and not a built\n * event is deliberate: `counter.next` and `captured_at` must run at FLUSH, or\n * a replaced `tool_call_end` leaves an allocated sequence number behind and\n * the session's numbering gains a hole no consumer can explain.\n */\ninterface CallSlot {\n /** Set at the TOP of `batonWrap`, before anything that can throw.\n *\n * ⚠ The placement agrees with both majors by construction, not by luck:\n * each runs `validateToolInput` OUTSIDE the executor this wraps\n * (`mcp.js:125`, `mcp-DXXb3Vv3.mjs:1399`), so a rejected argument cannot\n * reach here and mark the flag. `test/integrations/mcp/aboveTool.test.ts`\n * pins that per major — a placement one line lower would still pass the\n * happy path and silently relabel every `invalid_argument`. */\n innerFired: boolean;\n /** The inner's parked terminal event, or `null` when the inner never got\n * far enough to decide on one (its own prelude threw — nothing to flush,\n * and NOT a request-side failure). */\n flushTerminal: ((outcome: OuterOutcome) => Promise<void>) | null;\n}\n\n/** Module-scoped rather than per-install, which is safe for one reason worth\n * naming: a slot is only ever read inside the dynamic extent of the dispatch\n * that created it, and `AsyncLocalStorage` nests — a tool whose handler calls\n * a second seamed server in-process enters that server's slot first, so the\n * inner wrapper there reads its own, not ours. Nothing is shared BETWEEN\n * calls, so there is no per-install state to keep. */\nconst callSlots = new AsyncLocalStorage<CallSlot>();\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/**\n * `error_body` for either failure shape (SPEC §11.4.3), so the two legs cannot\n * drift apart on the one rule they share.\n *\n * ⚠ **Scrub, THEN cut.** A PII value straddling the boundary must reach the\n * scrubber whole; cutting first hands it a fragment no pattern matches, and\n * the surviving half ships unredacted. ⚠ **Cut by CODE POINT** —\n * `capCodePoints` carries that reasoning, and Python's `[:2000]` counts code\n * points, so this is also what makes the two producers agree on what the cap\n * means in the one payload `emitterConformance.test.ts` compares\n * field-for-field.\n */\nfunction errorBody(ctx: WrapContext, text: string): string {\n // eslint-disable-next-line no-restricted-syntax -- called only from emit() build thunks, so emit's guard already covers a throw here\n return capCodePoints(String(ctx.scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);\n}\n\n/** `error_type` for a THROWN value (SPEC §11.4.3's RAISE shape): the\n * exception's class name, `\"Error\"` for anything that is not one. Shared by\n * the inner wrapper's raise lane and the outer seam, which both have to spell\n * it — two spellings would let the same thrown `ProtocolError` arrive under\n * two labels depending on which seam reported it. */\nfunction errorTypeOf(err: unknown): string {\n return err instanceof Error ? err.constructor.name : \"Error\";\n}\n\n/** The human-readable text of a thrown value, by the same rule. */\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** The envelope members every event shares, resolved off one MCP request —\n * everything except `principal`, which is deliberately not in here.\n *\n * Split out of `openCall` so the resource and prompt lifecycle seams (SPEC\n * §11.4.4) can build an envelope without the parts that are specific to a tool\n * call: there is no `principal` on those (see `installLifecycleSeam`), no\n * intent-param strip, and no `call_id`.\n *\n * Returns the PARTS rather than an assembled `common` so each caller spells its\n * own literal, which keeps `openCall` reading as one object and keeps\n * `principal` out of a shape that has no business resolving it.\n *\n * ⚠ **NOT for key order, which a first version of this paragraph claimed.**\n * Zod v4 emits output keys in SHAPE order, not input order, so\n * `envelopeShape` fixes the wire order however a caller spells its literal.\n * Recorded because the wrong reason is the kind a later reader preserves. */\nasync function resolveEnvelopeParts(\n ctx: WrapContext,\n extra: Extra,\n): Promise<{ sessionId: string; runtime: string; scrubbedMeta: unknown }> {\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 // Coordinates are coarsened here: after the ladder above has read the\n // raw meta, and before the vendor's scrubber, so a vendor scrubber still\n // gets the rule (handoff D5). `_meta` only; params and results keep\n // full precision. The annotation tool does the same.\n const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, \"_meta\");\n const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);\n return { sessionId, runtime, scrubbedMeta };\n}\n\n/**\n * Open a tool call: resolve everything the envelope needs, strip Baton's\n * injected intent params out of `params` IN PLACE, and emit the opening\n * events — the session's first proactive annotation, when there is one, then\n * `tool_call_start`.\n *\n * ⚠ **Extracted so BOTH seams open a call the same way.** The inner executor\n * wrapper opens a call that reached the vendor's handler; the outer\n * `tools/call` seam opens one the SDK rejected before the handler ran (SPEC\n * §11.4.3's three request-side `failure_kind`s), and those events must carry\n * the same identity, the same `principal`, the same stripped `params` and the\n * same `call_id` discipline. Two copies of this would be two chances for one\n * of them to drift — which is the miss-mechanism this thread has already paid\n * for twice.\n *\n * Returns what the TERMINAL event needs and nothing more: the envelope, the\n * minted `call_id`, and the session the counter is keyed on.\n */\nasync function openCall(\n ctx: WrapContext,\n toolName: string,\n extra: Extra,\n params: Record<string, unknown>,\n /** Is there a registry entry for this tool? `false` only from the\n * `tools/call` seam's `unknown_tool` path, and it suppresses one warning\n * whose diagnosis would be wrong there — see `extractGoalParam`. */\n registered = true,\n): Promise<{ common: Record<string, unknown>; callId: string; sessionId: string }> {\n // ⚠ HERE, not in the callers. It was a caller obligation in both of them,\n // and this function exists precisely so the two cannot drift — a third\n // caller inheriting \"remember the snapshot first\" would silently stop\n // emitting it, which is the drift `openCall` was extracted to prevent. The\n // ordering invariant (snapshot BEFORE `tool_call_start`) is preserved and is\n // now structural.\n await maybeEmitSurfaceSnapshot(ctx);\n const { sessionId, runtime, scrubbedMeta } = await resolveEnvelopeParts(ctx, 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, registered);\n const rawExpected = extractGoalParam(\n params,\n EXPECTED_RESULT_PARAM_NAME,\n toolName,\n dispositions,\n registered,\n );\n const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions, registered);\n // Guarded because `params` is already stripped in place above.\n const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);\n const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);\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 = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);\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 principal = await resolveCallPrincipal(\n ctx.resolvePrincipal,\n { extra, toolName, arguments: params },\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 five `...common` sites below are the tool-call legs — start, end,\n // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive\n // annotation, the same five Python stamps (`middleware.py`\n // 503/547/586/644/674; it was four until the returned shape landed\n // there too). `surface_snapshot` is deliberately NOT among them: it\n // describes the SERVER and is captured outside any call, so there is no\n // caller to name (register D5).\n principal,\n // Same five stamps, same exclusion: a surface_snapshot describes the\n // SERVER and is captured outside any call, so it has no caller's\n // transport to name any more than it has a caller to name.\n transport_observed: observeTransport(extra),\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 // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw drops the event, which is correct for params\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 return { common, callId, sessionId };\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 // ⚠ FIRST, ahead of every await below. The flag's whole job is to say the\n // vendor's handler was REACHED, and a line of this prelude that threw\n // after a later assignment would leave the outer seam reporting a\n // request-side failure about a call that got this far. See `CallSlot`.\n const slot = callSlots.getStore();\n if (slot) slot.innerFired = true;\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 // ⚠ `params` is the SAME object forwarded to the vendor's handler, and\n // `openCall` strips Baton's injected intent params out of it IN PLACE —\n // which is what keeps `user_goal`/`expected_result` off the tool AND out\n // of the captured `params`, since those must equal the vendor-visible\n // arguments. The outer seam's request-side path passes a COPY instead,\n // for the reason stated there.\n const { common, callId, sessionId } = await openCall(ctx, toolName, extra, params);\n\n /** Emit this call's terminal event, or PARK it for the outer `tools/call`\n * seam when one is running (see `CallSlot`). `replacement` is passed by\n * the SUCCESS lane alone: it is the only terminal event the outer may\n * overwrite, because a parked FAILURE is already the vendor's own code\n * speaking — it raised, or it returned the flag — and SPEC §11.4.3's two\n * shapes own it. Relabelling that as `output_schema_mismatch` would blame\n * our conversion for the vendor's failure. */\n const terminate = async (\n build: () => Event,\n replacement: ((outcome: OuterOutcome) => Event) | null,\n ): Promise<void> => {\n if (!slot) {\n // No outer seam: a direct executor call, or a server whose internals\n // this package could not reach. Emit exactly as it always has — and\n // SPEC §11.4.3 agrees that is the right degradation, since \"a\n // producer with only one seam cannot emit `failure_kind` correctly\n // and MUST omit it\".\n await emit(ctx.sink, build);\n return;\n }\n // ⚠ **A parked terminal already here belongs to an EARLIER-completING\n // call in this same dispatch, and flushing it now is what keeps it from\n // being dropped.** The slot holds one decision, and parking without\n // this would overwrite it: a `tool_call_start` with no terminal, which\n // SPEC §11.5.4 leaves permanently unpaired. Two shapes reach it, one\n // probed and one read:\n //\n // - a vendor handler that invokes a SIBLING tool's wrapped executor\n // in-process — the inner call completes first, so the outer's park\n // lands second and used to erase it;\n // - v2's legacy `inputRequired` shim, which loops\n // `await handler(request, ctxNext)` inside ONE dispatch\n // (`mcp-DXXb3Vv3.mjs:602`), so every round but the last parks and\n // is immediately superseded.\n //\n // The earlier one is flushed UNREPLACED, which is the correct reading\n // rather than a convenience: the outer's outcome describes the call\n // `tools/call` itself dispatched, and that call is always the LAST to\n // decide, because its own `await` encloses everything it called.\n // Relabelling an inner call's success `output_schema_mismatch` would\n // blame whichever round happened to finish first.\n const earlier = slot.flushTerminal;\n if (earlier !== null) await earlier(CLEAN_OUTCOME);\n slot.flushTerminal = async (outcome) => {\n // The choice is made INSIDE the thunk, so either branch allocates its\n // sequence number at flush — the property `CallSlot` exists to keep.\n await emit(ctx.sink, () =>\n replacement !== null && outcome.failed ? replacement(outcome) : build(),\n );\n };\n };\n\n /** Park a terminal event the outer seam may NOT overwrite — the vendor's\n * own code spoke, by raising or by returning the flag, and SPEC §11.4.3's\n * two shapes own it. */\n const parkFailure = (build: () => Event): Promise<void> => terminate(build, null);\n\n /** Park the SUCCESS terminal, with what to emit instead if the outer seam\n * saw the call fail anyway.\n *\n * ⚠ Two functions rather than one optional parameter, so \"only the success\n * lane is replaceable\" is a thing the type system enforces instead of a\n * paragraph a future caller can skip. The invariant used to live only in\n * `terminate`'s docstring, where adding a replacement to the `isError`\n * lane would have compiled, passed every test, and relabelled the\n * vendor's own exception as our conversion's. */\n const parkSuccess = (\n build: () => Event,\n replacement: (outcome: OuterOutcome) => Event,\n ): Promise<void> => terminate(build, replacement);\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 await parkFailure(() =>\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: errorTypeOf(err),\n // ⚠ KEPT under `resultCaptureMode: \"off\"`, and that is the rule's\n // shape rather than an exception to it: the rule is keyed on\n // PROVENANCE, and a thrown error's message is the vendor's own\n // code speaking about a call that returned nothing (SPEC\n // §11.4.3(1)). A switch written as \"drop `error_body`\" would\n // delete the highest-value diagnostic the product has.\n error_body: errorBody(ctx, messageOf(err)),\n duration_ms: durationMs,\n // Explicit, though the field is `.optional()` and this is its\n // absent value. The schema is deliberately not an emitter (see\n // `ToolCallErrorPayloadSchema`), so if this leg stayed silent the\n // key would be missing. Each of the two failure shapes declares\n // which it is, the same reason Python's emitter made the parameter\n // positional-without-default.\n //\n // ⚠ Guarded by `errorResult.test.ts`'s `toContain(\"result\")`, NOT by\n // the cross-SDK key-set check — measured by removing this line. Why,\n // at one site: `endResultFields` in `errorResult.ts`. SPEC §11.4.3\n // states the same void rationale and wants the same amendment.\n result: null,\n },\n }),\n );\n throw err;\n }\n\n const durationMs = Math.round(performance.now() - startedAt);\n\n // The OTHER failure shape (SPEC §11.4.3): the handler returned normally\n // and the result carries MCP's error flag, which rides a 200 rather than a\n // JSON-RPC error. It arrives here rather than through the catch above, and\n // filing it as `tool_call_end` is filing a failure as a success.\n if (isErrorResult(result)) {\n await parkFailure(() =>\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: TOOL_ERROR_TYPE,\n duration_ms: durationMs,\n // Both remaining members are unwrapped FROM the result on this\n // shape, so one projection decides them together and owns the\n // scrubber call. `error_type` is NOT result-derived and is passed\n // regardless: the call still failed (SPEC §11.2.6).\n //\n // ⚠ Under `\"full\"` `result` is the whole envelope, and on this\n // producer that is the same shape `tool_call_end.result` records —\n // which is NOT what Python's contrast says.\n // `ToolCallErrorPayloadSchema` in `events.ts` holds that claim and\n // names the test that enforces it.\n ...returnedErrorFields(\n ctx.resultCaptureMode,\n result,\n (text) => errorBody(ctx, text),\n ctx.scrubber,\n ),\n },\n }),\n );\n // Returned, never thrown. The vendor chose to report this failure as a\n // value, and §11.2 says a sensor does not change what the caller sees.\n return result;\n }\n\n await parkSuccess(\n () =>\n ToolCallEndEventSchema.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 duration_ms: durationMs,\n ...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber),\n },\n }),\n // The handler returned something this sensor reads as a success, and\n // then the outer seam saw the call fail anyway — so what failed is the\n // producer's own conversion of the output (SPEC §11.4.3's\n // `output_schema_mismatch`). Correcting this is the whole point of the\n // second seam: without it this is a `tool_call_end` for a call the\n // CALLER saw fail, which is a success the product invented.\n (outcome) =>\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 // The lane the OUTER came back on, not this one's: on 2.x the\n // conversion failure is converted to a returned `isError` inside\n // `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `\"tool_error\"` is\n // right there. A throw out of the handler is unreachable on\n // either major today for this lane; spelled anyway, because the\n // alternative is a crash on the day it stops being.\n error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,\n // ⚠ The INNER's measurement — the vendor's handler duration —\n // not the outer's. Every other leg means the same thing by this\n // member, and widening it here for one failure kind would make\n // `duration_ms` mean two things in one column.\n duration_ms: durationMs,\n failure_kind: OUTPUT_SCHEMA_MISMATCH,\n // ⚠ **WITHHELD under `\"off\"`, unlike the three request-side\n // kinds.** The message quotes the value the tool returned\n // (\"`'not-an-int'` is not of type `integer`\"), so it is\n // result-derived by provenance and goes — which leaves\n // `failure_kind` as the ONLY surviving signal for this failure\n // under `\"off\"`, and is the measurement that justified putting\n // the member on the wire at all.\n //\n // ⚠ `result` is what the CLIENT received — the SDK's own error\n // envelope — not the vendor's rejected return value. §11.4.3\n // asks for the envelope that holds the flag and the reason, and\n // this package's own invariant is that it agrees with the\n // caller. Recording the rejected output TOO would need a member\n // nothing on the wire has; the loss is deliberate and worth\n // knowing when debugging one of these.\n ...resultDerivedFields(\n ctx.resultCaptureMode,\n () => (outcome.raised ? messageOf(outcome.err) : errorText(outcome.result)),\n // ⚠ `null` on the `raised` lane, never `undefined`, and the\n // union is what forces the branch rather than a comment: the\n // scrubber would answer `undefined` and DROP the key, where the\n // sibling raise lane a few lines up declares `result: null`\n // explicitly, for the reason `ToolCallErrorPayloadSchema`\n // records. One shape for \"no result object existed\", not two.\n outcome.raised ? null : outcome.result ?? null,\n (text) => errorBody(ctx, text),\n ctx.scrubber,\n ),\n },\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 registered: boolean,\n): string | null {\n if (!(paramName in args)) return null;\n const disposition = dispositions ? dispositions[paramName] : undefined;\n if (disposition === \"native\") return null;\n // ⚠ The warning says \"cold registry\", which is a real and useful diagnosis\n // for a tool that EXISTS and was never wired — and a wrong one for a tool\n // that does not exist at all. The `tools/call` seam reaches here for an\n // unknown tool, where there is no entry to have been wired, so the caller\n // says which case it is rather than letting this infer it from an absent\n // disposition that means two different things.\n if (disposition === undefined && registered) {\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, ctx.intentParamMode)\n : injectGoalParams(mutable.inputSchema, ctx.intentParamMode);\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/** The two request-handler internals the request seams reach, shared by both\n * majors' `Protocol`: the per-method dispatch map, and the setter that fills\n * it. Typed `unknown` and checked at install, so a server laid out\n * differently gets no seam rather than a crash. */\ninterface RequestHandlerInternals {\n _requestHandlers?: unknown;\n setRequestHandler?: unknown;\n}\n\nconst TOOLS_LIST_METHOD = \"tools/list\";\nconst TOOLS_LIST_SEAM = Symbol(\"batonToolsListSeam\");\nconst TOOLS_CALL_METHOD = \"tools/call\";\nconst TOOLS_CALL_SEAM = Symbol(\"batonToolsCallSeam\");\ntype SeamedHandler = AnyHandler & { [tag: symbol]: boolean | undefined };\n\n/**\n * Install a seam around ONE JSON-RPC method's request handler.\n *\n * Both majors dispatch requests through `server.server._requestHandlers`, a\n * `Map` keyed by method and read per request (1.x `shared/protocol.js`\n * `_onrequest`; v2 `Protocol._onrequest`), and both `McpServer`s install\n * their tool handlers lazily, on the first `registerTool` (v2 also eagerly,\n * when constructed with a `tools` capability). So both orders are covered: a\n * handler already in the map is wrapped now, and `setRequestHandler` is\n * patched so one set later is wrapped as it lands. Keyed on the map entry\n * rather than on the setter's arguments, because the majors spell the method\n * differently (a zod schema on 1.x, a string on v2) and both land in the same\n * map.\n *\n * ⚠ **Shared by both seams, which is what makes installing two of them\n * safe.** Each one patches `setRequestHandler`, so the second install must\n * reach the first's patch rather than the pristine setter — which it does,\n * because `originalSet` is read at install time, after the earlier patch has\n * landed. That composition held when this was one hand-written function per\n * seam too; one helper makes it structural rather than a property of the call\n * order in `withBaton`.\n *\n * ⚠ A server whose internals do not have this shape gets no seam at all.\n * What that costs differs per seam and is stated at each call site.\n */\nfunction installRequestSeam(\n lowLevel: RequestHandlerInternals,\n method: string,\n seamTag: symbol,\n wrap: (handler: AnyHandler) => AnyHandler,\n): void {\n const table = lowLevel._requestHandlers;\n const originalSet = lowLevel.setRequestHandler;\n if (!(table instanceof Map) || typeof originalSet !== \"function\") return;\n const handlers = table as Map<string, unknown>;\n const setRequestHandler = originalSet as AnyHandler;\n\n const wrapCurrent = (): void => {\n const handler = handlers.get(method) as SeamedHandler | undefined;\n if (typeof handler !== \"function\" || handler[seamTag]) return;\n const seamed = wrap(handler) as SeamedHandler;\n seamed[seamTag] = true;\n handlers.set(method, seamed);\n };\n\n wrapCurrent();\n lowLevel.setRequestHandler = (...args: AnyArgs): unknown => {\n const registered = setRequestHandler.apply(lowLevel, args);\n wrapCurrent();\n return registered;\n };\n}\n\n/**\n * The `tools/list` RESPONSE seam, which is what lets `intentParamMode:\n * \"required\"` advertise `user_goal` as required without the validator\n * enforcing it (see `schemaCompat.buildIntentFields` for why zod cannot).\n *\n * ⚠ Fail-open, twice. A throw from the transform is logged and the SDK's own\n * result goes out untouched, because a vendor's `tools/list` may never break\n * on Baton's account. And a server with no reachable handler map gets no seam,\n * which costs the advertisement and nothing else.\n */\nfunction installToolsListSeam(lowLevel: RequestHandlerInternals, ctx: WrapContext): void {\n const isInjected = (toolName: string): boolean =>\n ctx.paramRegistry.get(toolName)?.[USER_GOAL_PARAM_NAME] === \"injected\";\n const advertise = (result: unknown): unknown => {\n try {\n return advertiseUserGoalRequired(result, isInjected);\n } catch (err) {\n process.stderr.write(\n `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}\\n`,\n );\n return result;\n }\n };\n\n installRequestSeam(lowLevel, TOOLS_LIST_METHOD, TOOLS_LIST_SEAM, (handler) => (...args) => {\n const out = handler(...args);\n return isThenable(out) ? out.then(advertise) : advertise(out);\n });\n}\n\nconst LIFECYCLE_SEAMS = {\n resourceList: Symbol(\"batonResourceListSeam\"),\n resourceRead: Symbol(\"batonResourceReadSeam\"),\n promptList: Symbol(\"batonPromptListSeam\"),\n promptGet: Symbol(\"batonPromptGetSeam\"),\n} as const;\n\n/** The three event schemas one lifecycle family needs, structurally rather\n * than by Zod generics: all twelve `.parse` to something assignable to\n * `Event`, and that is the only thing the seam does with them. */\ninterface LifecycleSchemas {\n start: { parse(value: unknown): Event };\n end: { parse(value: unknown): Event };\n error: { parse(value: unknown): Event };\n}\n\n/**\n * The RESOURCE and PROMPT lifecycle seams (SPEC §11.4.4) — `baton-ts`'s first\n * instrumentation of anything but a tool call.\n *\n * ⚠ **At the REQUEST handler, not at registration**, and that is the whole\n * design rather than a convenience. The vantage point the twelve shapes were\n * defined from is `baton-proxy`'s, which reads the wire: subject, timing,\n * failure, no body. The request handler is the in-process position that sees\n * the same four facts — and it needs no per-family registration patch, since\n * both majors install all four handlers through the one `_requestHandlers` map\n * `installRequestSeam` already handles, lazily and in either order.\n *\n * ⚠ **No `principal` on any of the twelve, and it is a decision.** The vendor's\n * `resolvePrincipal` hook is TOOL-shaped — it takes `{extra, toolName,\n * arguments}` — so calling it with a URI in `toolName` would stretch a contract\n * a vendor's hook cannot anticipate. The proxy stamps no principal on these\n * types either (its twelve enqueue methods take none), so omitting it is parity\n * with the producer the shapes came from rather than a gap this package\n * invented. A later release that wants identity here needs a hook shape first.\n *\n * ⚠ **No `call_id` either**, same reason: no producer mints one for these, so\n * a consumer pairing a start with its end has only SPEC §11.5.4's FIFO floor.\n * §11.4.4 records that rather than leaving it to be discovered.\n *\n * ⚠ **Fail-open throughout (SPEC §11.2).** Every event goes through `emit`,\n * the whole settle is wrapped, and the vendor's result and the vendor's\n * exception pass through untouched in both lanes. A server with no reachable\n * handler map gets no seam, which costs these twelve events and nothing else.\n *\n * ⚠ **The error leg is THROW-ONLY, which is why there is no returned-flag\n * branch here.** `isError` is a `CallToolResult` member; a failing resource\n * read or prompt get comes back as a JSON-RPC error, so `error_type` is the\n * exception's class name — §11.4.3's RAISE spelling. `baton-proxy` files the\n * JSON-RPC numeric code instead, because the wire is what it holds. §11.4.4\n * states the divergence; both conform, and the member is an open string.\n */\n/** One lifecycle family's three event schemas plus the two facts that differ\n * between families. A DATA table, so adding `resources/templates/list` or\n * `completion/complete` is a row rather than a copied block.\n *\n * ⚠ `startParams` stays a CALLBACK while the other two are keys, and the\n * asymmetry is the point: the three `*_start` shapes are genuinely different\n * (none / the whole bag minus `_meta` / the `arguments` member alone) and that\n * difference is the proxy's own inconsistency, which §11.4.4 records. Encoding\n * it as a mode string would only relocate the switch. */\ninterface LifecycleSpec {\n method: string;\n seamTag: symbol;\n schemas: LifecycleSchemas;\n /** The dedicated subject member's key — `\"uri\"` for a read, `\"name\"` for a\n * prompt get, absent for either list, which has no subject. It rides all\n * three legs, so one key decides it for the family. */\n subjectKey?: \"uri\" | \"name\";\n /** Which array of the `*_list` result `count` counts. Absent for the two\n * families that have no count. */\n countKey?: \"resources\" | \"prompts\";\n /** The `*_start` payload's `params` member, or `{}` where the family has\n * none. */\n startParams: (params: Record<string, unknown>) => Record<string, unknown>;\n}\n\nfunction installLifecycleSeam(\n lowLevel: RequestHandlerInternals,\n ctx: WrapContext,\n spec: LifecycleSpec,\n): void {\n installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {\n const request = args[0] as { params?: Record<string, unknown> } | undefined;\n const requestParams = request?.params ?? {};\n const extra = args[1] as Extra;\n\n // ⚠ ONE `const`, not three `let`s with placeholder values. `emit`'s build\n // thunks capture this, and TypeScript will not narrow a captured MUTABLE\n // binding — which is what the three `const envelope = common` aliases an\n // earlier version carried were working around. `null` means the start\n // capture failed, and there is then nothing to stamp the later legs with.\n const opened = await openLifecycleCall(ctx, spec, requestParams, extra);\n\n /** Every leg is the same envelope with a different schema and payload, so\n * one builder owns the parts that must not drift: the stamp, the clock and\n * the sequence number — which `counter.next` must allocate at EMIT time,\n * not before. */\n const fire = async (\n schema: { parse(value: unknown): Event },\n payload: Record<string, unknown>,\n ): Promise<void> => {\n if (opened === null) return;\n await emit(ctx.sink, () =>\n schema.parse({\n ...opened.common,\n sequence_number: ctx.counter.next(opened.sessionId),\n captured_at: new Date().toISOString(),\n payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload }),\n }),\n );\n };\n\n await fire(spec.schemas.start, spec.startParams(requestParams));\n\n const startedAt = performance.now();\n const elapsed = (): number => Math.round(performance.now() - startedAt);\n try {\n const result = await handler(...args);\n await fire(spec.schemas.end, {\n ...(spec.countKey === undefined ? {} : { count: countOf(result, spec.countKey) }),\n duration_ms: elapsed(),\n });\n return result;\n } catch (err) {\n await fire(spec.schemas.error, {\n error_type: errorTypeOf(err),\n // KEPT under every capture mode: a failed FETCH's message is the\n // producer's own diagnostic, not anything a resource returned, so\n // nothing here is result-derived (SPEC §11.4.4). The scrub and the cap\n // are `scrubLifecyclePayload`'s, in that order.\n error_body: messageOf(err),\n duration_ms: elapsed(),\n });\n // Rethrown unchanged — a sensor does not change what the caller sees.\n throw err;\n }\n });\n}\n\n/** Resolve the envelope and the subject for one lifecycle request, or `null`\n * when that failed.\n *\n * Separate from the seam so the three legs share ONE immutable result. Guarded\n * here rather than at each leg because the vendor's request has not run yet:\n * losing the capture costs the pairing, never the call (SPEC §11.2). */\nasync function openLifecycleCall(\n ctx: WrapContext,\n spec: LifecycleSpec,\n requestParams: Record<string, unknown>,\n extra: Extra,\n): Promise<{\n common: Record<string, unknown>;\n sessionId: string;\n subject: Record<string, unknown>;\n} | null> {\n try {\n const parts = await resolveEnvelopeParts(ctx, extra);\n return {\n sessionId: parts.sessionId,\n subject:\n spec.subjectKey === undefined\n ? {}\n : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },\n common: {\n tenant_id: ctx.tenantId,\n vendor_id: ctx.vendorId,\n session_id: parts.sessionId,\n consent_token: ctx.consentToken,\n agent_runtime: parts.runtime,\n transport_observed: observeTransport(extra),\n runtime_meta: parts.scrubbedMeta,\n },\n };\n } catch (err) {\n process.stderr.write(`baton: ${spec.method} capture failed: ${String(err)}\\n`);\n return null;\n }\n}\n\n/** Every lifecycle family, as one table.\n *\n * ⚠ The two `startParams` builders that DO something are deliberately\n * different, and §11.4.4 records why: `baton-proxy` built them differently and\n * these shapes are transcribed from it, not designed. */\nconst NO_PARAMS = (): Record<string, unknown> => EMPTY_PARAMS;\n\n/** Shared because it is only ever SPREAD, never mutated. The thunk used to\n * allocate a throwaway object on every `resources/list` and `prompts/list`\n * request to produce nothing. */\nconst EMPTY_PARAMS: Record<string, unknown> = Object.freeze({});\n\nconst LIFECYCLE_SPECS: readonly LifecycleSpec[] = [\n {\n method: \"resources/list\",\n seamTag: LIFECYCLE_SEAMS.resourceList,\n schemas: {\n start: ResourceListStartEventSchema,\n end: ResourceListEndEventSchema,\n error: ResourceListErrorEventSchema,\n },\n // ⚠ `resources` ALONE. Resource TEMPLATES are a separate MCP method with\n // their own result array and are deliberately not added in, matching the\n // proxy — so a template-only server reports 0, which §11.4.4 says a\n // consumer MUST NOT read as \"this server has no resources\".\n countKey: \"resources\",\n startParams: NO_PARAMS,\n },\n {\n method: \"resources/read\",\n seamTag: LIFECYCLE_SEAMS.resourceRead,\n schemas: {\n start: ResourceReadStartEventSchema,\n end: ResourceReadEndEventSchema,\n error: ResourceReadErrorEventSchema,\n },\n subjectKey: \"uri\",\n // ⚠ The whole params bag MINUS `_meta`, so `uri` lands here as well as in\n // its own member. That duplication is the proxy's and is reproduced on\n // purpose: the dedicated member is what a consumer reads, the bag is what\n // the caller actually sent, and a producer that stripped `uri` out could no\n // longer say the second thing. `_meta` is excluded because it rides the\n // envelope as `runtime_meta` already.\n startParams: (params) => ({ params: paramsBag(params) }),\n },\n {\n method: \"prompts/list\",\n seamTag: LIFECYCLE_SEAMS.promptList,\n schemas: {\n start: PromptListStartEventSchema,\n end: PromptListEndEventSchema,\n error: PromptListErrorEventSchema,\n },\n countKey: \"prompts\",\n startParams: NO_PARAMS,\n },\n {\n method: \"prompts/get\",\n seamTag: LIFECYCLE_SEAMS.promptGet,\n schemas: {\n start: PromptGetStartEventSchema,\n end: PromptGetEndEventSchema,\n error: PromptGetErrorEventSchema,\n },\n subjectKey: \"name\",\n // ⚠ `arguments` ALONE, NOT the whole bag — the opposite of the resource\n // read above, so `name` does NOT appear inside `params`. The two are\n // inconsistent in the producer the shapes came from; the inconsistency is\n // reproduced rather than tidied, because a consumer reading one producer\n // and a second producer reading the other must agree.\n startParams: (params) => ({\n params: paramsBag(params[\"arguments\"] as Record<string, unknown> | undefined),\n }),\n },\n];\n\n/** Install every lifecycle seam. */\nfunction installLifecycleSeams(lowLevel: RequestHandlerInternals, ctx: WrapContext): void {\n for (const spec of LIFECYCLE_SPECS) installLifecycleSeam(lowLevel, ctx, spec);\n}\n\n/** The subject member a `*_read` / `*_get` payload requires, as a string.\n *\n * ⚠ `String()` on a non-string would put `\"[object Object]\"` on the wire for a\n * malformed request — a value that reads like a real URI name and is not. The\n * empty string is what `baton-proxy` emits for an absent subject\n * (`str(params.get(\"uri\") or \"\")`), so an unreadable one takes the same\n * spelling rather than inventing a third. The member is REQUIRED on all three\n * legs, so dropping it is not an option. */\nfunction stringSubject(value: unknown): string {\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** `len(result[key])`, fail-safe. A result this seam cannot read is a count of\n * 0 rather than a dropped event: the call happened and its timing is the part\n * no other signal carries. */\nfunction countOf(result: unknown, key: string): number {\n const list = (result as Record<string, unknown> | null | undefined)?.[key];\n return Array.isArray(list) ? list.length : 0;\n}\n\n/** A `*_start` payload's `params` member: the caller's own request data.\n *\n * ⚠ **Does NOT scrub — `scrubLifecyclePayload` does, over the whole payload.**\n * A first version scrubbed only here, and the result was the worst of both: a\n * resource read of `file:///alice@corp.com/doc.txt` shipped the path REDACTED\n * inside `params` and RAW in the sibling `uri` member, in one event, so the\n * redaction was worthless for that value. Found by review, reproduced on both\n * majors. Scrubbing the whole payload is also what the producer these shapes\n * came from does (`emitter.py`: `payload = self._scrubber(payload)`), so it is\n * the parity position as well as the correct one.\n *\n * `_meta` is dropped: it rides the envelope as `runtime_meta`, where it is\n * coordinate-coarsened first (`roundMetaCoordinates`), so recording it here too\n * would put the same data on one event twice under two treatments — and the\n * coarsening would be the one a consumer could not rely on.\n *\n * ⚠ `{}` and not `null` for an absent bag, which is the proxy's spelling\n * (`dict(params) if params else {}` — it never emits null). The schema permits\n * both, so this is parity rather than conformance. */\nfunction paramsBag(bag: Record<string, unknown> | undefined): Record<string, unknown> {\n if (!bag || typeof bag !== \"object\") return {};\n // One loop rather than `Object.entries().filter().fromEntries()`, which\n // allocated a pair array per key plus two arrays and a closure to produce\n // what is usually a one-key copy — this runs on every `resources/read` and\n // every `prompts/get`.\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(bag)) {\n if (key !== \"_meta\") out[key] = bag[key];\n }\n return out;\n}\n\n/**\n * Scrub a lifecycle payload WHOLE, then cap, and nothing else.\n *\n * ⚠ **Whole, not member by member** — the one rule this family needs and the\n * one a first version got wrong. `uri` and `name` are CALLER-supplied free\n * text (file paths, query strings, account ids, emails), not vendor-registered\n * identifiers like `tool_name`, and they ride all three legs. Scrubbing only\n * `params` left them raw while the same value was redacted one key over.\n *\n * It is also exactly what `baton_proxy.emitter._enqueue` does — one scrubber\n * pass over the whole payload dict — so the Console cannot receive a redacted\n * URI from one producer and a raw one from the other.\n *\n * ⚠ **Cap AFTER the scrub**, which is why the cap lives here rather than in a\n * caller: a PII value straddling `ERROR_BODY_MAX_CODE_POINTS` must reach the\n * scrubber whole, or the surviving half ships unredacted. Same ruling, same\n * reason, as `errorBody` for the tool-call legs — and the reason this path does\n * NOT call `errorBody`, which would scrub that one member a second time.\n *\n * ⚠ PRECONDITION: call this ONLY from inside an `emit()` build thunk. The bare\n * scrubber call is correct there — a throw drops the event, which is the right\n * answer for a payload — and wrong anywhere else (SPEC §11.2: a sensor never\n * breaks the vendor's call).\n */\nfunction scrubLifecyclePayload(\n ctx: WrapContext,\n raw: Record<string, unknown>,\n): Record<string, unknown> {\n // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw drops the event, which is correct for a payload\n const scrubbed = ctx.scrubber(raw) as Record<string, unknown>;\n const body = scrubbed?.[\"error_body\"];\n if (typeof body !== \"string\") return scrubbed;\n // Spread rather than assign: the scrubber is the vendor's and may hand back\n // a frozen object. Key order does not matter — Zod emits in SHAPE order.\n return { ...scrubbed, error_body: capCodePoints(body, ERROR_BODY_MAX_CODE_POINTS) };\n}\n\n/** One tool's registry entry, in the only members either seam reads.\n *\n * The CLASSIFICATION members (`enabled`, `execution`) come from\n * `ToolEntryFacts` in `errorResult.ts`, which is where the decision that reads\n * them lives; this adds the two DISPATCH members, which only this module\n * touches. One declaration per fact, so the next flag either SDK branches on\n * cannot be added to one copy and missed in the other. */\ninterface ToolEntry extends ToolEntryFacts {\n handler?: unknown;\n executor?: unknown;\n}\n\n/**\n * The function an entry actually dispatches through, which differs by SDK\n * major — 1.x invokes `entry.handler`, v2 a closure at `entry.executor`.\n *\n * Shared by `wrapIfNeeded`, which tags it, and the `tools/call` seam, which\n * asks whether it is tagged. Two copies of this rule would let the seam\n * answer \"not ours\" about a tool `wrapIfNeeded` had in fact wrapped, and the\n * consequence is silent: the request-side `failure_kind` events for that tool\n * would simply never be emitted. See {@link wrapIfNeeded} for why getting the\n * per-major choice wrong fails quietly in the first place.\n */\nfunction dispatchSlot(entry: ToolEntry): \"executor\" | \"handler\" | undefined {\n if (typeof entry.executor === \"function\") return \"executor\";\n if (typeof entry.handler === \"function\") return \"handler\";\n return undefined;\n}\n\n/** The dispatch target itself, for a caller that only needs to inspect it. */\nfunction dispatchTarget(entry: ToolEntry): TaggedHandler | undefined {\n const slot = dispatchSlot(entry);\n return slot === undefined ? undefined : (entry[slot] as TaggedHandler);\n}\n\n/**\n * The `tools/call` REQUEST seam — the second of Baton's two tool-call\n * sensors, and the one that can see a failure the SDK manufactures ABOVE the\n * vendor's handler (SPEC §11.4.3's `failure_kind`).\n *\n * Three of those four failures emit NOTHING from the inner wrapper, because\n * the handler it wraps never runs: an unknown tool, a disabled tool and a\n * rejected argument. The fourth is worse than nothing — the handler returns\n * fine and the SDK's own output conversion rejects it, so the inner files\n * `tool_call_end` for a call the CALLER saw fail. This seam closes both: it\n * supplies the missing events itself, and it hands the inner's parked\n * terminal event the outcome so a false success can be replaced.\n *\n * ⚠ **Unconditional, unlike the `tools/list` seam** (which only installs\n * under `intentParamMode: \"required\"`): the correction it makes is not\n * configurable. A server with no reachable handler map gets no seam, and then\n * this producer has one seam again and correctly omits `failure_kind`\n * entirely — `CallSlot` and `terminate` carry that degradation.\n *\n * ⚠ **Fail-open, as the whole capture path must be (SPEC §11.2).** Both the\n * flush and the request-side emission go through `emit`, and `settleCall`'s\n * own guard is below; the vendor's result and the vendor's exception pass\n * through this seam untouched in every lane.\n */\nfunction installToolsCallSeam(\n lowLevel: RequestHandlerInternals,\n toolEntry: (name: string) => ToolEntry | undefined,\n ctx: WrapContext,\n): void {\n installRequestSeam(\n lowLevel,\n TOOLS_CALL_METHOD,\n TOOLS_CALL_SEAM,\n (handler) =>\n async (...args) => {\n const slot: CallSlot = { innerFired: false, flushTerminal: null };\n // Reassigned by both the try and the catch before `finally` reads it;\n // the initializer is for definite assignment, not a live default.\n let outcome: OuterOutcome = CLEAN_OUTCOME;\n try {\n const result = await callSlots.run(slot, () => handler(...args));\n outcome = { failed: isErrorResult(result), raised: false, result };\n return result;\n } catch (err) {\n outcome = { failed: true, raised: true, err };\n throw err;\n } finally {\n // ⚠ **`finally`, never a read after the `await`.** v2 THROWS a\n // `ProtocolError` out of this handler for an unknown or a disabled\n // tool (`mcp-DXXb3Vv3.mjs:1395-1397`), so a settle placed after the\n // await is skipped on exactly the two legs this seam exists for. A\n // probe made that mistake on 2026-10-01 and reported \"the outer\n // never ran\" as a blocker; the trap is in the production seam too,\n // which is why it is named here and not only in the design note.\n await settleCall(slot, outcome, args, toolEntry, ctx);\n }\n },\n );\n}\n\n/**\n * Decide what this call owes the event stream, now that both seams have had\n * their say.\n *\n * ⚠ Fail-open at the top level. Everything below is Baton's own bookkeeping\n * about a call that has already finished — a throw here would surface to the\n * agent as a failed tool call on work that succeeded, which SPEC §11.2\n * forbids outright. `emit` guards each individual event; this guards the\n * decision around them.\n */\nasync function settleCall(\n slot: CallSlot,\n outcome: OuterOutcome,\n args: AnyArgs,\n toolEntry: (name: string) => ToolEntry | undefined,\n ctx: WrapContext,\n): Promise<void> {\n try {\n // The inner reached a terminal decision: flush it, or let the outcome\n // replace it. This is the ONLY path that emits a terminal event for a\n // call the vendor's handler actually ran.\n if (slot.flushTerminal !== null) {\n const flush = slot.flushTerminal;\n // ⚠ **Released BEFORE the await, not after — and not left set at all.**\n // The parked thunk captures this call's `result`, `params` and `extra`,\n // and on an `async_hooks`-backed `AsyncLocalStorage` the slot is copied\n // onto every async resource created inside `run`. So a vendor handler\n // that lazily makes a LONG-LIVED resource during the call (a pool, an\n // interval, a cached promise) pins the slot — and a slot still holding\n // the thunk drags that whole scope along for the resource's lifetime.\n // Clearing it bounds the retention to the dispatch.\n slot.flushTerminal = null;\n await flush(outcome);\n return;\n }\n // The handler ran but parked nothing — `openCall` itself threw. There is\n // no terminal event to flush and this is NOT a request-side failure: the\n // call got past the SDK's own checks. Saying nothing is the honest answer.\n if (slot.innerFired) return;\n // Nothing failed and the inner never fired: a tool this package does not\n // capture (the annotate tool, a task-based tool) was called and worked.\n if (!outcome.failed) return;\n await emitRequestSideFailure(outcome, args, toolEntry, ctx);\n } catch (err) {\n process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}\\n`);\n }\n}\n\n/**\n * Emit the pair of events for a failure the SDK raised BEFORE the vendor's\n * handler ran (SPEC §11.4.3's three request-side `failure_kind`s).\n *\n * The inner wrapper emitted nothing at all for these, so this supplies both\n * legs, through the same `openCall` the inner uses — identical envelope,\n * identical `principal`, a minted `call_id` on the start so SPEC §11.5.4's\n * tier 1 pairs them.\n *\n * ⚠ **The start is not cosmetic.** `baton-console`'s pairer does build a row\n * from an orphan end (`correlate.py` emits `(None, i)`), but with no start it\n * has no `params` — and the arguments are precisely the diagnostic for\n * `invalid_argument`, the commonest of these three.\n *\n * Two callers get NO event, and both omissions are the point:\n *\n * - **Baton's own annotate tool.** It is excluded from `wrapIfNeeded` because\n * it emits `annotation`, not `tool_call_*`; a rejected argument on it would\n * otherwise file an `invalid_argument` about a tool the vendor does not own.\n * - **A registered tool this package did not wrap** — task-based tools, whose\n * `.handler` is an object rather than a function. `wrapIfNeeded` leaves them\n * alone rather than guessing at a shape we capture no events for, and this\n * has to make the same choice or it would report failures for calls whose\n * successes are invisible.\n *\n * An entry that is ABSENT is the opposite case and does get an event: that is\n * `unknown_tool`, where there is nothing to have wrapped.\n */\nasync function emitRequestSideFailure(\n outcome: OuterOutcome,\n args: AnyArgs,\n toolEntry: (name: string) => ToolEntry | undefined,\n ctx: WrapContext,\n): Promise<void> {\n const request = args[0] as { params?: { name?: unknown; arguments?: unknown } } | undefined;\n const toolName = request?.params?.name;\n // A `tools/call` with no string tool name is not a call this sensor can\n // name, and SPEC gives `tool_name` no null spelling on any payload.\n if (typeof toolName !== \"string\") return;\n if (toolName === ctx.annotationToolName) return;\n const entry = toolEntry(toolName);\n // ⚠ `!= null`, so a null entry falls THROUGH to `unknown_tool` rather than\n // into `dispatchTarget`, where reading `.executor` off it would throw. The\n // registry is reached through a cast past the SDK's `private`, so its shape\n // is a declaration and not a runtime guarantee; `requestSideFailureKind`\n // makes the same check for the same reason, and it is this line that lets\n // that one be reached at all.\n if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;\n\n // ⚠ A COPY, unlike the inner wrapper's in-place strip. `openCall` removes\n // Baton's injected intent params from whatever it is given, and here the\n // object is the vendor's live `request.params.arguments` — already consumed\n // by a validator that rejected it, so mutating it changes no outcome, but a\n // sensor that edits the request it is observing is a habit to refuse rather\n // than reason about once. The strip itself is required: these params ARE\n // still in the arguments on this path (validation runs above the executor,\n // and `captureAndInject` spliced the names into the schema), so without it\n // Baton's own params would land in `tool_call_start.params`, which SPEC\n // says equals the vendor-visible arguments.\n const params = { ...((request?.params?.arguments as Record<string, unknown>) ?? {}) };\n const { common, callId, sessionId } = await openCall(\n ctx,\n toolName,\n args[1] as Extra,\n params,\n entry != null,\n );\n\n // `undefined` where the SDK rejected the call for a reason this producer\n // cannot attribute — SPEC §11.4.3 permits omitting the member and\n // `requestSideFailureKind` says which shape that is. The event still goes:\n // the call failed, and the SDK's own message is on it.\n const failureKind: FailureKind | undefined = requestSideFailureKind(entry);\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 // The lane the SDK rejected on, which is NOT the same across majors\n // for one failure: 1.x converts all three to a returned `isError`\n // inside its own `try` (`mcp.js:101-108`), v2 THROWS the first two\n // and returns the third. So the same customer-visible failure is\n // `\"tool_error\"` on one major and `\"ProtocolError\"` on the other —\n // measured 2026-10-01, and deliberately not special-cased: this\n // member is §11.4.3's RAISE/RETURN discriminator and it is reporting\n // the shape faithfully. `failure_kind` is what makes the two\n // comparable, which is the member's whole justification.\n error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,\n // ⚠ `null`, not 0. The vendor's handler never ran, so there is no\n // handler duration to report; the time this call did spend was spent\n // in the SDK's validator, which is not what any other event means by\n // this member. §11.4 types it nullable for cases like this one.\n duration_ms: null,\n // ⚠ A CONDITIONAL SPREAD, not `failure_kind: failureKind`. Zod's\n // `.optional()` accepts `undefined` and keeps the KEY in its output,\n // so the plain form writes a present-but-undefined member — invisible\n // to a JSON-serialising sink and plainly visible to a vendor-supplied\n // one that iterates keys. SPEC §11.4.3 says a producer that cannot\n // determine the kind MUST OMIT the member, and omitting is what this\n // spells.\n ...(failureKind === undefined ? {} : { failure_kind: failureKind }),\n // KEPT under `\"off\"` — see `requestSideErrorFields`, which takes no\n // capture mode because nothing here is derived from a result.\n ...requestSideErrorFields(\n outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),\n (text) => errorBody(ctx, text),\n ),\n },\n }),\n );\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return typeof (value as { then?: unknown } | null | undefined)?.then === \"function\";\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 ToolEntry;\n\n // Task-based tools (experimental) carry an object, not a function, at\n // .handler — `dispatchTarget` answers `undefined` for them, and leaving\n // them untouched is deliberate rather than a gap: we capture no events for\n // that shape, and the `tools/call` seam makes the SAME choice off the SAME\n // predicate so it cannot report a failure for a tool whose successes are\n // invisible.\n // ⚠ The SLOT, not the target, so the rule is decided ONCE. An earlier\n // version called `dispatchTarget` and then re-tested\n // `typeof mutable.executor === \"function\"` to pick where to assign — which\n // is the rule in two spellings, in the one function whose docstring says\n // that is the failure mode.\n const slot = dispatchSlot(mutable);\n if (slot === undefined) return;\n const target = mutable[slot] as TaggedHandler;\n if (target[BATON_WRAPPED]) return;\n const wrapper = batonWrap(nameRef, target, ctx) as TaggedHandler;\n wrapper[BATON_WRAPPED] = true;\n mutable[slot] = 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 } } & RequestHandlerInternals;\n registerTool: (...args: AnyArgs) => unknown;\n // `ToolEntry` and not `unknown`: the `tools/call` seam reads `enabled` and\n // the dispatch target off these entries, so an upstream rename of either\n // lands as a compile error here the way every other reach-in does.\n _registeredTools?: Record<string, ToolEntry>;\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 // \"required\" by default since 2026-09-15 (Ujwal, #features): advertised\n // through the `tools/list` seam, never enforced, so the default asks every\n // agent for `user_goal` and refuses no call that omits it.\n const intentParamMode: IntentParamMode = config.intentParamMode ?? \"required\";\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 resultCaptureMode: config.resultCaptureMode ?? \"full\",\n paramRegistry: new Map(),\n resolvePrincipal: config.resolvePrincipal,\n vendorToolJsonSchema,\n bustSchemaMemo,\n tracker,\n surfaceState,\n emitSurface,\n };\n\n // Server instructions — load-bearing on instruction-aware runtimes (SPEC\n // §5.1.2). No public setter exists post-construction; see module\n // docstring for why this reach-in has no \"preferred path\" to fall back\n // from, unlike Python's adapter.\n const instructions = buildServerInstructions({\n vendorDisplayName: config.vendorDisplayName,\n annotationToolName,\n });\n internals.server._instructions = instructions;\n\n // Before the annotate tool registers: on a server with no tools yet, that\n // registration is what makes the SDK install its `tools/list` handler, and\n // the seam has to be in place to wrap it as it lands.\n if (intentParamMode === \"required\") installToolsListSeam(internals.server, ctx);\n\n // The SECOND tool-call seam (SPEC §11.4.3's `failure_kind`) — unconditional,\n // and installed here for the same reason the `tools/list` seam is: the\n // annotate tool's registration below is what makes a toolless server install\n // its tool handlers at all, so the seam has to be in place to wrap one as it\n // lands.\n //\n // ⚠ The registry is read PER CALL, not captured, so a tool removed after\n // install classifies as `unknown_tool` rather than against a stale snapshot\n // — `update({name: null})` and `remove()` both delete the entry, and the\n // whole point of this lookup is to agree with what the SDK itself just read.\n installToolsCallSeam(\n internals.server,\n // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain\n // object, so `registry[\"constructor\"]` answers `Object` and\n // `registry[\"__proto__\"]` answers `Object.prototype` — both non-undefined,\n // so the \"a tool we did not wrap\" guard would decline to report, and a\n // caller-visible `Tool constructor disabled` would reach the client with\n // this seam silent. An agent hallucinating a prototype-shaped tool name is\n // exactly the kind of failure the seam exists to make visible.\n (name) => {\n const registry = internals._registeredTools;\n return registry && Object.hasOwn(registry, name) ? registry[name] : undefined;\n },\n ctx,\n );\n\n // The four resource/prompt lifecycle seams (SPEC §11.4.4) — unconditional,\n // like the seam above, because what they capture is not configurable.\n //\n // ⚠ **Install ORDER is irrelevant for these four, unlike the two above.**\n // `resources/*` and `prompts/*` handlers are installed by the vendor's own\n // `registerResource` / `registerPrompt`, not by the annotate-tool\n // registration below — and `installRequestSeam` patches `setRequestHandler`,\n // so a primitive registered AFTER `withBaton` is seamed as its handler\n // lands. Verified on both majors. This paragraph used to claim the\n // annotate-tool ordering mattered here, which was the `tools/*` seams'\n // reason copied one function too far.\n installLifecycleSeams(internals.server, ctx);\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 resolvePrincipal: ctx.resolvePrincipal,\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 { roundMetaCoordinates } from \"../../metaCoordinates.js\";\nimport type { Sink } from \"../../sinks.js\";\nimport { deriveAnnotationToolName } from \"./annotationName.js\";\nimport { emit } from \"./emit.js\";\nimport { type ResolvePrincipalHook, resolveCallPrincipal } from \"./principalResolution.js\";\nimport { buildAnnotationToolDescription, SIGNAL_TYPES } from \"./llmText.js\";\nimport { extraEnvelope, extraMeta, observeTransport, 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 { scrubOrNull } from \"./safeScrub.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 — the SAME one the tool-call wrapper\n * holds. */\n resolvePrincipal?: ResolvePrincipalHook | 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 // As in the tool-call wrapper: coordinates coarsened after the ladder\n // read the raw meta, before the vendor's scrubber (handoff D5).\n const scrubbedMeta = scrubOrNull(\n options.scrubber,\n meta ? roundMetaCoordinates(meta) : null,\n \"_meta\",\n );\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 principal = await resolveCallPrincipal(\n options.resolvePrincipal,\n { extra, toolName: name, arguments: args },\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,\n transport_observed: observeTransport(extra),\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 // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape\n intent: options.scrubber(args.user_goal),\n expected_outcome: args.expected_result\n // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape\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 // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape\n workflow: args.overall_task ? options.scrubber(args.overall_task) : null,\n suggested_improvement: args.suggested_improvement\n // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape\n ? options.scrubber(args.suggested_improvement)\n : null,\n // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape\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","/**\n * Coordinate coarsening for a request's `_meta` (handoff D5, 2026-09-15).\n *\n * ChatGPT sends `openai/userLocation` in `_meta` with latitude and longitude\n * at metre precision: two prod values resolved to a storefront and a home.\n * `roundMetaCoordinates` rounds them to 1 decimal (about 11 km) before the\n * meta becomes `runtime_meta`; the city, region, country and timezone beside\n * them stay.\n *\n * `_meta` only, on purpose. This is not a Scrubber rule: a vendor's own tool\n * that takes or returns coordinates keeps them at full precision in the\n * captured params and result. It runs BEFORE the vendor's scrubber, not\n * inside it, so a vendor who supplies their own scrubber still gets it.\n *\n * Mirrors the Python SDK's `round_meta_coordinates`; the two must store the\n * same value for the same client, which is why a tie is written the way\n * Python's `f\"{x:.1f}\"` writes it.\n */\n\nimport { DEPTH_LIMIT } from \"./scrub.js\";\n\n// Case-insensitive exact match, like the Scrubber's REDACT_FIELD_NAMES, so\n// `lat` / `lng` are not matched.\nconst COORD_FIELD_NAMES: ReadonlySet<string> = new Set([\"latitude\", \"longitude\"]);\n\n// A string written as a plain decimal: sign, digits, optional fraction. Whole\n// string, no trimming, no exponent, `Infinity` or `NaN`, the same grammar as\n// the Python SDK's `_DECIMAL.fullmatch`. No `g` flag, so `.test()` is safe.\nconst DECIMAL_STRING = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$/;\n\n/** `{...}` literals and `Object.create(null)` only, as in `scrub.ts`: a\n * `Date` or class instance passes through rather than being rebuilt as a\n * bare object. */\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/** `value` to 1 decimal, written the way Python's `f\"{value:.1f}\"` writes\n * it. `toFixed` rounds from the exact binary value like Python does, with\n * one exception: an exact tie (a fraction of .25 or .75) goes away from\n * zero in `toFixed` and to the even digit in Python. `37.25` is `\"37.2\"`\n * in both SDKs only because of the branch below. */\nfunction toOneDecimal(value: number): string {\n const magnitude = Math.abs(value);\n if (Number.isInteger(magnitude * 4) && !Number.isInteger(magnitude * 2)) {\n // Exact: x.25 * 10 is x2.5, x.75 * 10 is x7.5.\n const tenths = Math.floor(magnitude * 10);\n const even = tenths % 2 === 0 ? tenths : tenths + 1;\n return ((Math.sign(value) * even) / 10).toFixed(1);\n }\n return value.toFixed(1);\n}\n\n/** The rounded coordinate, keeping the value's type, or `undefined` when\n * the rule leaves `value` alone: an integer, `NaN`, `Infinity`, a boolean,\n * null, or a string that is not a decimal. A decimal string always comes\n * back with one decimal, so `\"37\"` becomes `\"37.0\"`. */\nfunction roundCoordinate(value: unknown): number | string | undefined {\n if (typeof value === \"number\") {\n return Number.isFinite(value) && !Number.isInteger(value)\n ? Number(toOneDecimal(value))\n : undefined;\n }\n if (typeof value === \"string\" && DECIMAL_STRING.test(value)) {\n return toOneDecimal(Number(value));\n }\n return undefined;\n}\n\nfunction walk(value: unknown, depth: number): 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 // The value sits at `depth + 1`, where the walk would stop, so the cap\n // applies to a coordinate the same as to anything else. The rule is\n // the key's own value only: a list under `latitude` is walked, not\n // rounded.\n const rounded =\n COORD_FIELD_NAMES.has(k.toLowerCase()) && depth + 1 < DEPTH_LIMIT\n ? roundCoordinate(v)\n : undefined;\n out[k] = rounded ?? walk(v, depth + 1);\n }\n return out;\n }\n if (Array.isArray(value)) {\n return value.map((item) => walk(item, depth + 1));\n }\n return value;\n}\n\n/**\n * A copy of `meta` with every `latitude` / `longitude` value rounded to 1\n * decimal in its own type, at any depth within DEPTH_LIMIT. Pure: `meta`\n * itself is not touched, so the handler and the runtime ladder still see\n * what the client sent.\n */\nexport function roundMetaCoordinates(meta: Record<string, unknown>): Record<string, unknown> {\n return walk(meta, 0) as Record<string, unknown>;\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.principalFor` 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 */\n/** Whether `value` is longer than `max` CODE POINTS — the check form of\n * `capCodePoints`, for a field that is dropped rather than cut. */\nexport function exceedsCodePoints(value: string, max: number): boolean {\n // Each code point is one or two UTF-16 units, so the unit count brackets it.\n if (value.length <= max) return false;\n if (value.length > 2 * max) return true;\n return [...value].length > max;\n}\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","/** Principal identity — what a vendor's resolver hands back, and how it goes\n * on the wire.\n *\n * The TypeScript half of Python's `baton/identity.py`. Baton attaches the\n * resolved principal to every event so the Console can group by\n * `(tenant_id, vendor_id, principal.id)`, at whatever grain the vendor\n * resolved (SPEC §11.4). The resolver decides everything about the value: who\n * it names, whether it is hashed, what a page shows for it. The SDK sends it\n * on as stated.\n */\n\nimport { capCodePoints, exceedsCodePoints } from \"./_text.js\";\n\n/** Where a principal came from. `\"asserted\"` is a vendor's own resolver,\n * which nothing in the protocol checks, and is the only value this SDK\n * emits — `integrations/mcp/principalResolution.ts` has the why, and the\n * wording trap that comes with it. */\nexport const PRINCIPAL_SOURCE_ASSERTED = \"asserted\";\n\n/** What the emitted value IS — the privacy classification, and the only thing\n * SPEC §11.4 lets a consumer classify on. */\nexport const PRINCIPAL_FORM_HASHED = \"hashed\";\nexport const PRINCIPAL_FORM_RAW = \"raw\";\n\n/** Cap on `principal.id`, in code points: it is vendor-supplied text copied\n * onto every event of a call. Mirrors Python's `PRINCIPAL_ID_MAX_LEN`. */\nexport const PRINCIPAL_ID_MAX_LEN = 128;\n\n/** Cap on `displayName`, in CODE POINTS (Python's `len`). Over it the name is\n * DROPPED, not truncated: SPEC §11.4 forbids rewriting it, so both SDKs send\n * the same bytes for one resolver output. */\nexport const DISPLAY_NAME_MAX_LEN = 128;\n\n// Unicode `White_Space`, exactly (SPEC §11.4's blank rule). Not `.trim()`:\n// that also removes U+FEFF and keeps U+0085, which Python's `strip()` does the\n// other way round, so the two SDKs would disagree on what is blank.\nconst ALL_WHITE_SPACE = /^\\p{White_Space}*$/u;\n\n/** The resolver's `displayName` as it goes on the wire, or `null`. Verbatim\n * when usable. A non-string, a blank (only Unicode `White_Space`), an\n * over-long value or one holding a lone surrogate or U+0000 is dropped ALONE — the rest\n * of the principal still ships, because a bad label is no reason to lose a\n * good id. Mirrors Python's `wire_display_name`. */\nexport function wireDisplayName(value: unknown): string | null {\n if (typeof value !== \"string\" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;\n // U+0000: Postgres text refuses it, costing a collector the whole event.\n if (LONE_SURROGATE.test(value) || value.includes(\"\\u0000\") || ALL_WHITE_SPACE.test(value)) return null;\n return value;\n}\n\nexport type PrincipalForm = typeof PRINCIPAL_FORM_HASHED | typeof PRINCIPAL_FORM_RAW;\n\nconst PRINCIPAL_FORMS: ReadonlySet<unknown> = new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);\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 `.trim()` is never correct\n * where the two SDKs must agree on what is blank. */\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/** 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 principal as a vendor's resolver produced it. */\nexport interface Principal {\n /** A stable identifier from the vendor's own system. Never an application\n * id: that names the app and is identical for every one of its users, which\n * merges them into one actor. */\n principalId: string;\n /** What `principalId` is: `\"raw\"`, a real identity, or `\"hashed\"`, a\n * pseudonym the resolver derived itself. A consumer treats anything not\n * `\"hashed\"` as personal data, so leave it unset unless the resolver hashed\n * the value. */\n form?: PrincipalForm | undefined;\n /** What a page shows for this principal — `principalFromOAuthEmail` puts\n * the part of the address before the last `@` here. Sent verbatim and never\n * through the scrubber (SPEC §11.4): the vendor chooses what is safe to\n * show, and it is personal data whatever `form` says. An unusable value is\n * dropped alone — see `wireDisplayName`. */\n displayName?: string | null | undefined;\n}\n\n/** What `normalizePrincipal` hands on: the resolver's `form` is still\n * unchecked, because only `principalFor` has a channel to warn on. */\nexport type ResolvedPrincipal = Omit<Principal, \"form\"> & { form?: unknown };\n\n/** Normalize whatever a vendor's hook returned into a usable principal, or\n * `null` if it gave us nothing usable.\n *\n * TypeScript types vanish at runtime and a hook is vendor code, so a plain\n * string or a half-built object is a MISS, never a partially-built principal.\n */\nexport function normalizePrincipal(result: unknown): ResolvedPrincipal | null {\n if (result === null || typeof result !== \"object\") return null;\n const candidate = result as { principalId?: unknown; form?: unknown; displayName?: unknown };\n if (typeof candidate.principalId !== \"string\") return null;\n // A lone surrogate cannot be UTF-8 encoded: the sink would send U+FFFD in\n // its place, so `\"a\\uD800\"` and `\"a\\uDC00\"` would arrive as one actor.\n if (LONE_SURROGATE.test(candidate.principalId)) return null;\n // U+0000 is refused by Postgres text and would cost a collector the whole event.\n if (candidate.principalId.includes(\"\\u0000\")) return null;\n // A blank id names nobody, and every such caller would merge into one actor.\n if (pythonStrip(candidate.principalId) === \"\") return null;\n const principal: ResolvedPrincipal = { principalId: candidate.principalId };\n if (candidate.form !== undefined) principal.form = candidate.form;\n // Shape only; the name's own rules run once, in `principalFor`.\n if (typeof candidate.displayName === \"string\") principal.displayName = candidate.displayName;\n return principal;\n}\n\n/** The principal AS EMITTED — the finished envelope value (SPEC §11.4).\n *\n * Not `Principal`: that one is what a vendor's `resolvePrincipal` hook HANDS\n * US, this one is what we PUT ON THE WIRE — the same value, with `source`\n * added.\n *\n * **`id`, `source` and `form` are REQUIRED.** A producer emits the whole\n * thing or omits `principal` entirely; a partial object is malformed, not a\n * degraded reading. So there is no conformant event carrying an `id` whose\n * `form` a consumer has to guess.\n */\nexport interface PrincipalWire {\n /** The value, as the vendor's resolver returned it: a real identity, or a\n * pseudonym the resolver derived. Which one is `form`, and it is NEVER the\n * value's shape — a real OIDC subject (`mailto:`, `acct:`, `urn:`,\n * `https:`) reads as a scheme-tagged pseudonym to anything testing for\n * \"letters then a colon\". */\n id: string;\n /** WHERE it came from. Always `\"asserted\"` here — `principalResolution.ts`\n * has the why and the wording trap. */\n source: typeof PRINCIPAL_SOURCE_ASSERTED;\n /** WHAT it is. */\n form: PrincipalForm;\n /** What a page shows; personal data whenever present, whatever `form`\n * says. OMITTED, never `null`, when there is none — so a nameless principal\n * is byte-identical to one from before the member existed. */\n display_name?: string;\n}\n\n// ⚠ **Literal types here, `z.string()` on `PrincipalWireSchema` — and the\n// asymmetry is deliberate.** That schema is the PARSE boundary and must\n// tolerate a value SPEC registers later; this is the PRODUCER type, and this\n// SDK emits exactly one `source` and two `form`s. Widening it would inherit\n// the schema's justification without its reason, and would let a stray\n// string through. Typed this way, adding a source is a compile error in one\n// place — here, where the registry is.\n\n/** The resolver's principal as the wire object.\n *\n * The id is sent as given: not scrubbed, since a scrubber that redacts emails\n * would map every user onto one redaction constant and merge them into a\n * single actor.\n */\nexport function principalFor(\n principal: ResolvedPrincipal,\n onUnregisteredForm?: (form: unknown) => void,\n): PrincipalWire {\n let form: PrincipalForm = PRINCIPAL_FORM_RAW;\n if (principal.form !== undefined) {\n if (PRINCIPAL_FORMS.has(principal.form)) {\n form = principal.form as PrincipalForm;\n } else {\n // SPEC §11.4: anything not \"hashed\" is personal data, so that is the\n // only safe reading of a form nobody registered.\n onUnregisteredForm?.(principal.form);\n }\n }\n const wire: PrincipalWire = {\n // `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so\n // an astral id cut at the boundary would ship a lone surrogate.\n id: capCodePoints(principal.principalId, PRINCIPAL_ID_MAX_LEN),\n source: PRINCIPAL_SOURCE_ASSERTED,\n form,\n };\n const displayName = wireDisplayName(principal.displayName);\n if (displayName !== null) wire.display_name = displayName;\n return wire;\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\n// The leading label tracks `intentParamMode`: under \"required\" the\n// `tools/list` seam in withBaton.ts adds `user_goal` to the advertised\n// `required` list, so a description still opening \"OPTIONAL.\" would\n// contradict the schema it ships inside. Only the label moves; the body is\n// the measured text. Mirrors Python's `build_user_goal_param_description`.\nconst USER_GOAL_PARAM_BODY =\n \"One sentence: what the user is actually trying to accomplish \" +\n \"with this call (their goal, not a restatement of the arguments).\";\nconst USER_GOAL_PARAM_DESCRIPTION = \"OPTIONAL. \" + USER_GOAL_PARAM_BODY;\nconst USER_GOAL_PARAM_DESCRIPTION_REQUIRED = \"REQUIRED. \" + USER_GOAL_PARAM_BODY;\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\n/** `user_goal`'s description, labelled \"REQUIRED.\" under `intentParamMode:\n * \"required\"` and \"OPTIONAL.\" otherwise. */\nexport function buildUserGoalParamDescription(options: { intentParamMode?: string } = {}): string {\n return options.intentParamMode === \"required\"\n ? USER_GOAL_PARAM_DESCRIPTION_REQUIRED\n : 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 who keeps the readable name.** Both names enter the server\n * instructions, whose cap THROWS, so they share one budget. The display name\n * is resolved first, rendered beside the tool name the ladder is about to\n * PROPOSE: the explicit one, else the server-derived candidate before its own\n * budget check, else `{vendorId}_annotate`. The tool name is then checked\n * beside the display name that won. So where the budget has room for only one\n * readable name, the TOOL name keeps it and the display name stays the DSN\n * segment. The tool name is therefore always the one the tool-name rule gives\n * beside the segment, which is the name Python 0.8.4 shipped, and every pair\n * that renders has been checked. Python 0.8.5's tie-break\n * (`resolve_annotation_names`), adopted unchanged; this package's 0.3.4 had\n * let the display name win it.\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/** `{slug}_annotate` from a vendor-chosen name, pattern-checked, or\n * `undefined`. Not yet checked against the instructions budget: the display\n * name is rendered beside this candidate before the tool name's own check. */\nfunction toolNameCandidate(serverName: string): string | 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 return TOOL_NAME_PATTERN.test(candidate) ? candidate : 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 the ladder is about to propose, so a name\n * that does not fit leaves the DSN segment in place: it never takes the\n * readable tool name's budget, and never makes 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 proposed =\n tool.annotationToolName || toolNameCandidate(serverName) || `${tool.vendorId}${SUFFIX}`;\n if (!fitsInstructionsCap({ vendorDisplayName: serverName, annotationToolName: proposed })) {\n warn(\n `baton: the server name (${serverName.length} chars) does not fit the ` +\n \"server-instructions budget as the display name beside the annotation \" +\n `tool ${JSON.stringify(proposed)}; keeping the DSN's server segment. ` +\n \"Pass vendorDisplayName to name the server in fewer characters.\",\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 candidate = toolNameCandidate(serverName);\n if (candidate === undefined) 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: `RequestHandlerExtra.authInfo` — the validated access token, set by\n * the SDK's bearer-auth middleware on an authenticated HTTP request. */\n authInfo?: unknown;\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 declared — this comment said it was not, and that was wrong.**\n * Corrected 2026-09-16 against the installed package. `ServerContext` declares\n * `http?: { req?: globalThis.Request; closeSSE?: ... }`, documented \"The\n * original HTTP request\", at\n * `@modelcontextprotocol/server@2.0.0/dist/createMcpHandler-CLhGwQTn.d.mts:2212`.\n * The `{ authInfo? }`-only shape the old text described is real but is\n * `BaseContext.http` (`:2171`) — a DIFFERENT block, which `ServerContext`\n * intersects, so the member carries both. Two declarations of one property\n * name, and the earlier pass read the wrong one and generalised.\n *\n * The old text also warned \"do not correct this back on the strength of the\n * `.d.ts`\", which is why the exact file and line are cited above rather than\n * the claim repeated: the way past that warning is a narrower read, not a\n * louder assertion. Measurement still backs it — 10 rows, both majors, every\n * transport (v15 probe) — so this is now declared AND measured. */\n http?: { req?: { headers?: unknown } | undefined; authInfo?: unknown } | undefined;\n}\n\n/** A validated access token, as both majors declare it\n * (`@modelcontextprotocol/sdk` 1.x `server/auth/types.d.ts`,\n * `@modelcontextprotocol/server` 2.0.0 `createMcpHandler-*.d.mts:751` — the\n * same six members). Declared structurally for the reason {@link Extra} is.\n *\n * ⚠ **There is no `claims` member.** Whatever a verifier knows about the\n * subject goes in the free-form `extra` bag, and only the vendor's verifier\n * decides what is there. */\nexport interface AuthInfo {\n token: string;\n clientId: string;\n scopes: string[];\n expiresAt?: number | undefined;\n resource?: URL | undefined;\n extra?: Record<string, unknown> | undefined;\n}\n\n/** The request's validated access token, from wherever this major keeps it:\n * `extra.authInfo` on 1.x, `ctx.http.authInfo` on v2. `null` on stdio (MCP\n * auth is HTTP middleware) and on any unauthenticated request.\n *\n * Only an object is passed on; anything else is `null`, so a hook never has\n * to guard against a string or a number arriving where a token should. */\nexport function extraAuthInfo(extra: Extra): AuthInfo | null {\n const found = extra.authInfo ?? extra.http?.authInfo;\n return found !== null && typeof found === \"object\" ? (found as AuthInfo) : null;\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 */\n/** What we observed beneath this call, for the envelope's `transport_observed`.\n *\n * `\"http\"` when a transport request object is reachable — `requestInfo` on the\n * 1.x peer, `http.req` on v2. `\"no-http-request\"` when neither is, which is\n * stdio and in-memory. `\"read-failed\"` if reading the carrier throws.\n *\n * ⚠ **Keyed on the REQUEST OBJECT, never on {@link extraHeaders}.** That\n * function ends in a bare `return null` and — by its own contract above —\n * returns `null` both when no HTTP request is in flight AND when a header it\n * was handed could not be appended (the HTTP/2 pseudo-header guard). So an\n * HTTP call whose headers it declined reads there as no-HTTP. That fold is\n * harmless for identity, which only loses a lookup, and NOT harmless here:\n * `\"no-http-request\"` is a licence, not a label — SPEC §3.4 lets a consumer\n * group a process-wide fallback `session_id` on it and only on it. Handing\n * that out because a header was malformed merges two strangers.\n *\n * ⚠ The v15 probe measured ZERO folds across 10 rows, so this is not a bug we\n * have seen — it is one the shape allows, and Python's equivalent helper has\n * the same fold as a LIVE defect (register A6). Same rule on both SDKs, for the\n * same reason, before either can bite.\n *\n * There is no `null` return. `null` on the envelope means the SDK did not look,\n * which is the library path with no MCP transport at all; every caller here is\n * inside a live MCP call and did look. */\nexport function observeTransport(extra: Extra): string {\n try {\n const carrier = extra.http?.req ?? extra.requestInfo;\n return carrier ? \"http\" : \"no-http-request\";\n } catch {\n return \"read-failed\";\n }\n}\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 ONLY identity provenance (SPEC §11.4).\n *\n * The producer never reads the token itself and never derives the value: who\n * the person is, and whether the id is hashed, are the hook's to state. Every\n * principal this SDK emits is `source: \"asserted\"`. The hook's context carries\n * the validated `authInfo`, and `oauthHooks.ts` ships the two ready-made\n * OAuth hooks.\n *\n * The TypeScript half of Python's `integrations/identity_adapter.py`.\n */\n\nimport {\n type Principal,\n type PrincipalWire,\n PRINCIPAL_FORM_RAW,\n normalizePrincipal,\n principalFor,\n} from \"../../identity.js\";\nimport { warn } from \"./annotationName.js\";\nimport { type AuthInfo, type Extra, extraAuthInfo, 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 /** The validated access token for this request, read from wherever this\n * major keeps it — see `extraAuthInfo`. `null` on stdio and on any\n * unauthenticated request. `principalFromOAuthSub` and\n * `principalFromOAuthEmail` read it, and so can a vendor's own hook.\n *\n * Optional so a vendor hand-building a context in their own tests keeps\n * compiling, as Python's defaulted `claims` keeps theirs running. */\n authInfo?: AuthInfo | null | undefined;\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 authInfo: extraAuthInfo(extra),\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 the principal 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`.\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` 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.** Python runs vendor\n * hooks off the event loop under a 5s budget (`integrations/_hooks.py`); this\n * arm awaits the hook inline, as it does `scrubber`, the only other vendor\n * code on the per-call path. A hook that blocks stalls this request.\n */\nexport async function resolveCallPrincipal(\n hook: ResolvePrincipalHook | undefined,\n call: { extra: Extra; toolName: string; arguments: Record<string, unknown> },\n): Promise<PrincipalWire | null> {\n // The context is built HERE — after the hook check, inside the try — and\n // the signature takes the raw call so a caller cannot do it the other way:\n // a server with no hook pays nothing, and a throw from the header read\n // cannot escape into the vendor's tool call.\n if (hook === undefined) return null;\n try {\n const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);\n const result: unknown = await hook(context);\n // Reading the result stays inside the try: a getter or Proxy on what the\n // hook returned is still the vendor's code.\n const principal = normalizePrincipal(result);\n if (principal === null) {\n warnIfPreRenameShape(result);\n return null;\n }\n return principalFor(principal, (form) => {\n warn(\n `baton: resolvePrincipal returned form ${describeForm(form)}, expected \"raw\" or \"hashed\" — ` +\n `sending it as \"${PRINCIPAL_FORM_RAW}\".`,\n );\n });\n } catch {\n // Broad on purpose: this calls code a VENDOR wrote, and an identity read\n // may not be able to fail a tool call. Nothing is logged to stdout — that\n // stream is the MCP JSON-RPC frame (AGENTS.md boundary rule 2).\n return null;\n }\n}\n\nfunction describeForm(form: unknown): string {\n return typeof form === \"string\" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;\n}\n","import {\n EXPECTED_RESULT_PARAM_NAME,\n OVERALL_TASK_PARAM_NAME,\n USER_GOAL_PARAM_NAME,\n} from \"./llmText.js\";\n\n/** The fields a vendor scrubber is applied to OUTSIDE an `emit()` build thunk.\n *\n * A closed union rather than `string` for two reasons that both turned out to\n * matter. It makes a typo at a call site a compile error, where three of these\n * are also param-name constants two lines above the call. And it bounds the\n * warning set below to one line per field per process: a `string` would leave\n * that bound resting on every caller happening to pass a literal. */\nexport type ScrubbedField =\n | \"agent-runtime name\"\n | \"_meta\"\n | typeof USER_GOAL_PARAM_NAME\n | typeof EXPECTED_RESULT_PARAM_NAME\n | typeof OVERALL_TASK_PARAM_NAME;\n\nconst warned = new Set<ScrubbedField>();\n\n/** Fail-open wrapper around a VENDOR-supplied scrubber call.\n *\n * SPEC §11.2: Baton instrumentation MUST NOT break the vendor's tool call on\n * its own internal failure. `safeWrite` enforces that for `sink.write`, and\n * `emit` for payload CONSTRUCTION — but the scrubber also runs in plain\n * statements, outside any thunk, in both handlers. A throw there escapes both\n * guards and the call comes back to the agent as `isError: true`, which is the\n * one thing the fail-open property promises cannot happen. Reproduced on both\n * MCP majors before this existed. The default scrubber is ours, so the trigger\n * is a vendor-supplied one — exactly what §7 tells vendors handling sensitive\n * data they MUST supply.\n *\n * ⚠ **The rule is the POSITION, not a list of fields.** Every scrubber\n * application that is not inside an `emit()` build thunk needs this. An earlier\n * version of this comment listed the call sites instead of stating the rule, and\n * the byte-identical `_meta` line in `annotation.ts` was missed because of it —\n * found by review, not by the list. The lint rule in `eslint.config.js` now\n * refuses a bare scrubber call anywhere in `src/`, so a new site has to opt out\n * visibly rather than be remembered.\n *\n * `null` on failure because every caller already treats `null` as \"this field is\n * not available\": runtime detection loses the TIER and falls through to the\n * next, `_meta` becomes absent, an unscrubbed goal param becomes no captured\n * intent. So the field degrades and the call lives. `null` IN is returned\n * unchanged without calling the scrubber, which is what lets each caller drop\n * its own `x !== null ?` guard.\n *\n * ⚠ NOT for a scrubber call inside an `emit()` build thunk. There a throw is\n * already contained, and `null` would be WORSE than dropping the event: a null\n * `result` on a `tool_call_error` means \"the handler raised\" (SPEC §11.4.3), so\n * swallowing a scrubber failure into one would fabricate a failure shape. Drop\n * the event instead — which is what `emit` already does.\n */\nexport function scrubOrNull<T>(\n scrubber: (value: unknown) => unknown,\n value: T | null,\n field: ScrubbedField,\n): T | null {\n if (value === null) return null;\n try {\n // eslint-disable-next-line no-restricted-syntax -- this IS the guard; the one call the rule exists to funnel every other through\n return scrubber(value) as T;\n } catch (err) {\n // Once per field per process. `safeWrite` logs per event because a sink\n // failure is one write per event; this fires up to five times per CALL, and\n // runtime detection fires unconditionally — so the unbounded form would put\n // a line on stderr for every tool call forever. Bounded the way\n // `principalResolution`'s pre-rename warning and `HttpSink.overflowWarned`\n // already are.\n if (!warned.has(field)) {\n warned.add(field);\n process.stderr.write(\n `baton: scrubber threw on ${field}; that field is dropped, tool call continues. ` +\n `Further failures on this field will be silent: ${String(err)}\\n`,\n );\n }\n return null;\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` 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\";\nimport { scrubOrNull } from \"./safeScrub.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 // Fail-open; `safeScrub` carries why `emit`'s guard does not cover this one.\n // ⚠ `<unknown>` deliberately, NOT inferred: `T` would infer `string` and make\n // the guard below look redundant to a reader, when it is load-bearing.\n const scrubbed = scrubOrNull<unknown>(scrubber, cleaned, \"agent-runtime name\");\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`. Identity is `principal`, a different field on a different\n * condition; keep the two claims apart. It is asserted too: the vendor's hook\n * names the person, and nothing in the protocol checks it.\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`, 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 * What result-derived data reaches the wire, and in what shape.\n *\n * Two halves of one question. Detecting MCP's returned error FLAG — the port\n * of `baton` (Python)'s `integrations/_error_result.py`, with one predicate\n * deliberately different, see `isErrorResult`. And the capture MODE (SPEC\n * §11.4), which decides whether any of it egresses at all. The second half\n * governs the SUCCESS path too, so a reader looking for \"where is the result\n * on a good call decided\" is in the right file despite the name — kept as\n * `errorResult.ts` because the filename pins parity with Python's module.\n *\n * SPEC §11.4.3. **A failed MCP tool call is a 200.** The protocol files it as a\n * successful JSON-RPC response whose `CallToolResult` body sets the error flag;\n * a JSON-RPC error means a protocol fault, not a tool failure. So classifying\n * on thrown exceptions alone — which is what §6.1 used to say, and what this\n * package did — files real failures as successes.\n *\n * ⚠ **One spelling, `isError`.** Python's helper probes `is_error` first\n * because that is a Python ATTRIBUTE name the `mcp` 2.x rewrite introduced;\n * MCP's own JSON-RPC schema is camelCase and every server dumps by alias\n * (wire probe, 2026-09-23: seven cells, `is_error` in none of them). The TS\n * SDKs have no snake_case era at all — measured 2026-09-24 on both majors,\n * the value this package sees is the vendor's own literal, camelCase.\n */\n\n/** `error_type` for a returned error, as opposed to a thrown exception whose\n * constructor name is used. Same literal as Python's `TOOL_ERROR_TYPE` and as\n * `baton-extmcp`'s — sensor parity is the point. */\nexport const TOOL_ERROR_TYPE = \"tool_error\";\n\n/** The registered values of `failure_kind` (SPEC §11.4.3), and the single\n * source of truth for them — same posture as `RESULT_CAPTURE_MODES` below,\n * for the same reason: a second hand-written list makes the guarantee \"two\n * lists happen to agree\".\n *\n * ⚠ **THREE of these four are spelled identically to the Console's error\n * code, and one renames.** Measured in\n * `baton-console/backend/src/baton_console/worker/errors.py`, whose\n * `_FAILURE_KIND_TO_CODE` is mostly an ALLOW-LIST: `unknown_tool`,\n * `tool_disabled` and `invalid_argument` map to codes of the same name\n * (`27566c2` added the first two as codes no TEXT lane can reach), and only\n * `output_schema_mismatch` renames, onto `schema_violation`, which already\n * described it.\n *\n * ⚠ A first version of this paragraph had that INVERTED — one match, three\n * renames — because it was copied from `iserror_sensor_probe.md`'s decision\n * table, written 2026-10-01, which recorded the buckets as they stood BEFORE\n * the Console side of this release landed the next day. Corrected rather than\n * overwritten, because the mechanism is the useful part: a design note's\n * \"today\" column goes stale the moment the thing it describes ships, and a\n * code comment that copies one inherits the staleness silently.\n *\n * The consequence of getting it wrong is not cosmetic. That table is an\n * allow-list, so an unregistered value is simply absent from it and falls\n * through to prose classification — which for `tool_disabled` means\n * `unclassified` with the full text in hand, the exact regression this member\n * exists to remove. `invalid_argument` is SINGULAR for that reason (Ujwal,\n * 2026-10-01): the plural was one letter off the Console's spelling, which is\n * the drift that already cost two defects this week.\n *\n * Open, not closed: `events.ts` types the wire member as a plain string, so a\n * later registered value cannot red a conforming producer (SPEC §11.2's\n * fail-open rule). This array is what THIS producer may emit. */\nexport const FAILURE_KINDS = [\n \"unknown_tool\",\n \"tool_disabled\",\n \"invalid_argument\",\n \"output_schema_mismatch\",\n] as const;\n\n/** What this producer may emit for `failure_kind`. Derived, so the type and\n * the registry cannot drift. */\nexport type FailureKind = (typeof FAILURE_KINDS)[number];\n\n/** The one RESULT-SIDE kind: the handler returned and the producer's own\n * conversion of its output rejected it, so `error_body` and `result` are\n * result-derived and `\"off\"` withholds both. */\nexport const OUTPUT_SCHEMA_MISMATCH = \"output_schema_mismatch\" satisfies FailureKind;\n\n/**\n * Which request-side kind a failure above the handler was, from the tool\n * entry the SDK itself looked up — NOT from the result.\n *\n * ⚠ **SPEC §11.4.3 forbids sorting these by inspecting the result object**,\n * and the reason is visible in both majors' `tools/call` handler: all three\n * arrive as the same shape. On 1.x all three are a returned `isError` whose\n * text is `createToolError`'s (`mcp.js:100-108`, inside the handler's own\n * `try`); on 2.x the first two THROW a `ProtocolError` and the third is a\n * returned `isError` (`mcp-DXXb3Vv3.mjs:1394-1397`). Reading the message\n * would be a regex in the producer, which is the thing `failure_kind` exists\n * to remove.\n *\n * So this reads the same two facts the SDK branched on, from the same\n * registry entry (`_registeredTools[name]`), which makes the label agree with\n * the SDK's own decision by construction rather than by matching its prose.\n * `SurfaceState` is deliberately NOT the source: it is a derived copy, it\n * excludes the annotate tool, and a tool registered before `withBaton` ran\n * reaches it only through the retroactive sweep.\n *\n * Absent entry → the tool does not exist. Present and disabled → the vendor\n * turned it off, which is a different remedy from a missing tool and the case\n * the Console cannot classify from text at all. Present and enabled → the\n * handler existed, was callable, and still never ran.\n *\n * ⚠ **That last step is NOT always argument validation, and a first version\n * of this function said it was.** On v2 it is: `tools/call` checks existence,\n * then `enabled`, then calls `validateToolInput`, with nothing in between\n * (`mcp-DXXb3Vv3.mjs:1394-1399`). On `@modelcontextprotocol/sdk` 1.x — the\n * pinned peer — TWO more pre-handler rejections sit in that gap\n * (`mcp.js:112-122`), and one of them is reachable for a tool this package\n * wraps: `execution.taskSupport` declared on a tool registered with an\n * ordinary function callback throws `InternalError` before any argument is\n * looked at. Labelling that `invalid_argument` tells the operator the agent\n * sent bad arguments when the remedy is the VENDOR's own registration — the\n * one failure mode this member exists to prevent, reintroduced by the\n * producer instead of by a regex.\n *\n * So a tool whose entry declares one of those two task modes withdraws the\n * claim: `undefined`, which SPEC §11.4.3 permits outright (\"a producer that\n * cannot emit this member correctly MUST omit it\"). The caller still emits\n * the event — the call failed and the SDK's own message says why — it just\n * does not name a kind it cannot determine. ⚠ The small untruth that buys:\n * §11.4.3 reads an absent member as \"the vendor's handler spoke for itself\",\n * which is not what happened here. Keeping the call visible with its real\n * message is the better of the two, and this is the one shape where that\n * reading is wrong.\n *\n * ⚠ **The predicate is `TASK_MODES`, not \"is `taskSupport` set\" — which was\n * the first version and would have cost `invalid_argument` on the ENTIRE\n * pinned peer.** Measured: 1.x's `registerTool` hands\n * `{taskSupport: \"forbidden\"}` to every ordinary tool it builds\n * (`mcp.js:694,704`), so the member is populated on all of them and the\n * presence test withdrew the claim universally. Caught by\n * `aboveTool.test.ts`'s 1.x leg, which is why that case asserts the kind per\n * major rather than once. The two values below are exactly the ones the SDK\n * itself branches on, which is this function's whole discipline.\n *\n * ⚠ The predicate stays on the REGISTRY ENTRY's own configuration, never the\n * message — and 1.x's OTHER branch (`\"required\"` without task augmentation)\n * needs no clause of its own, because it is reachable only when the handler\n * is a task OBJECT, which `dispatchSlot` already answers `undefined` for and\n * the seam already declines to report on.\n *\n * ⚠ **`TASK_MODES` is a PIN, not a principle, and that is the honest reading.**\n * The other two kinds rest on POSITIVE evidence — an absent entry, an\n * `enabled: false` flag — which is why they are stable across majors.\n * `invalid_argument` is the ELSE branch: an inference from the absence of any\n * other explanation. This `Set` patches that inference by enumerating the two\n * values of one major's `taskSupport` that sit in the gap TODAY, and the SDK\n * does not branch on `taskSupport` to decide THIS question — it branches on it\n * to decide something else, which the code is reading as a proxy. So the next\n * pre-handler rejection either major adds lands in `invalid_argument`\n * silently, with nothing going red, because the elimination still \"succeeds\".\n *\n * The real fix is positive evidence: a THIRD seam around the SDK's own input\n * validation, setting a `validatorRejected` fact on `CallSlot` the way\n * `innerFired` is set, after which this function is three positive tests and\n * no `else` and `TASK_MODES` disappears. Not taken here — it is another\n * per-major internals reach-in and the two majors spell validation\n * differently. Recorded so the `Set` is read as the version pin it is.\n */\nconst TASK_MODES: ReadonlySet<unknown> = new Set([\"required\", \"optional\"]);\n\n/** The registry-entry members this decision reads, declared ONCE.\n *\n * `withBaton.ts`'s `ToolEntry` extends this with the two dispatch-target\n * members the seam needs. Declared here rather than hand-copied as a structural\n * literal because the next flag either SDK branches on has to be added in one\n * place, and `tsc` would not have noticed a second copy going stale. */\nexport interface ToolEntryFacts {\n enabled?: unknown;\n /** 1.x rejects a mis-declared task tool BEFORE argument validation, so this\n * member's VALUE is what withdraws the `invalid_argument` claim. */\n execution?: { taskSupport?: unknown } | null;\n}\n\nexport function requestSideFailureKind(\n entry: ToolEntryFacts | null | undefined,\n): FailureKind | undefined {\n // `== null`, not `=== undefined`: this entry comes out of a cast past the\n // SDK's `private`, so its shape is a declaration rather than a runtime\n // guarantee, and a null would otherwise raise a `TypeError` off a tool call\n // that was going to return the SDK's own error (SPEC §11.2 fail-open —\n // `settleCall`'s guard would catch it, but a sensor should not need one).\n if (entry == null) return \"unknown_tool\";\n if (entry.enabled === false) return \"tool_disabled\";\n return TASK_MODES.has(entry.execution?.taskSupport) ? undefined : \"invalid_argument\";\n}\n\n/** The `error_body` cap, in CODE POINTS, shared by both failure legs (SPEC\n * §11.4.3's two shapes) so a change to the limit cannot move one and leave\n * the other. Python caps the same field at the same number, and its `[:2000]`\n * counts code points — which is why the cut goes through `capCodePoints` and\n * not `String.prototype.slice`. */\nexport const ERROR_BODY_MAX_CODE_POINTS = 2000;\n\n/**\n * True if `value` is a tool result carrying MCP's error flag.\n *\n * ⚠ **No `content`-must-be-a-list guard, and SPEC §11.4.3 now scopes that\n * rule by VANTAGE POINT rather than requiring it of every producer** — the\n * section said \"MUST\" unconditionally until 2026-09-24, and this package is\n * why it moved.\n * Python's adapter receives a result the library has already converted, so an\n * object carrying an `isError` attribute for its own reasons could reach it\n * and must be excluded. This package wraps the vendor's own executor, so what\n * arrives here is the vendor's LITERAL return, and both majors merge that\n * verbatim into the wire result.\n *\n * Measured 2026-09-24 on `@modelcontextprotocol/sdk` 1.x and\n * `@modelcontextprotocol/server` 2.x: a tool returning `{isError: true,\n * rows: 0}` — no `content` at all — reaches the CLIENT as\n * `{content: [], isError: true}`. There is no such thing here as an object\n * that merely spells the flag: spelling it at the top level of a tool's return\n * IS how a TS tool reports failure. A `content` guard would make this sensor\n * miss a failure its caller can see, which is the one thing it may not do.\n *\n * So the invariant is stronger and simpler than Python's, and\n * `errorResult.test.ts` asserts it directly: **for a failure the handler\n * itself reports, this predicate agrees with what the client received.**\n *\n * ⚠ **That scope is load-bearing, because a failure the SDK manufactures\n * ABOVE this wrap point is invisible here.** Measured 2026-09-24 on both\n * majors: a tool registered with an `outputSchema` whose handler returns\n * `content` and no `structuredContent` returns a success-shaped object, so\n * this predicate correctly answers false — and then the SDK's own output\n * validation, which runs after the executor, sends the client\n * `{isError: true, content: [{text: \"Output validation error: …\"}]}`. Baton\n * files `tool_call_end`. Nothing at the handler's vantage point can see it;\n * closing it needs a wrap above the request handler, or a sensor on the wire\n * — which is what `baton-proxy` is, and why the wire probe recorded that the\n * floor an SDK cannot see, the proxy can.\n *\n * ⚠ **And moving THIS sensor up to the request handler would cost more than\n * it closed**, which is why the gap is recorded rather than chased: both\n * majors convert a thrown handler error into a returned `isError` inside that\n * handler (`mcp.js:135`, `mcp-DXXb3Vv3.mjs:1404`), so above it the two failure\n * shapes are the same object and `error_type` collapses to `tool_error` for\n * both. Python's vector pins `\"error_type\": \"ValueError\"`. The throw/return\n * distinction only exists BELOW the request handler, which is where this sits.\n *\n * Guarded end to end — this runs on the vendor's tool-call path (SPEC §11.2:\n * never block the call), so it fails to False.\n */\nexport function isErrorResult(value: unknown): boolean {\n try {\n if (typeof value !== \"object\" || value === null) return false;\n return Boolean((value as { isError?: unknown }).isError);\n } catch {\n return false;\n }\n}\n\n/**\n * The human-readable reason inside an error result.\n *\n * Joins the `content` envelope's text parts, which is where a vendor puts the\n * actual sentence (\"You do not have sufficient access to delete this\n * Project\"). This is what a human reads in the Console, so the fallback is\n * deliberately NOT `String(result)` — `[object Object]` would put noise where\n * the reason belongs. An empty string says \"no reason given\", which is honest\n * and which the Console already renders as such.\n *\n * ⚠ **No truncation here, deliberately.** The caller cuts AFTER scrubbing, to\n * `ERROR_BODY_MAX_CODE_POINTS`, on both failure legs alike.\n * Cutting inside this helper would put the truncation BEFORE the scrubber for\n * one of the two failure shapes and after it for the other — and a PII value\n * straddling the boundary would reach the scrubber as a fragment its pattern\n * cannot match, so the half that survives the cut ships unredacted. That is\n * the bug `/code-review` found in the Python change (`33581cb`); it is not\n * being ported.\n */\nexport function errorText(value: unknown): string {\n const parts: string[] = [];\n try {\n const content = (value as { content?: unknown })?.content;\n if (!Array.isArray(content)) return \"\";\n for (const part of content) {\n const text = (part as { text?: unknown })?.text;\n if (typeof text !== \"string\") continue;\n const trimmed = text.trim();\n if (trimmed) parts.push(trimmed);\n }\n } catch {\n return \"\";\n }\n return parts.join(\"\\n\");\n}\n\n/** The registered values of `resultCaptureMode` (SPEC §11.4), and the single\n * source of truth for them.\n *\n * A second hand-written list would make the guarantee \"two lists happen to\n * agree\". `config.ts` builds its validator set from THIS array rather than\n * restating the literals, so a mode cannot be accepted at the door without\n * someone having given it a payload shape below. */\nexport const RESULT_CAPTURE_MODES = [\"full\", \"off\"] as const;\n\n/** What a vendor may set. Derived, so the type and the registry cannot drift. */\nexport type ResultCaptureMode = (typeof RESULT_CAPTURE_MODES)[number];\n\n/** The one registered non-default value, on the wire and in the config alike.\n * A string and not a boolean because SPEC reserves a second value for the\n * content ladder's partial rung.\n *\n * `satisfies` and NOT a type annotation: an annotation widens this to\n * `ResultCaptureMode`, and then `case WITHHELD:` stops narrowing the switches\n * below — which silently costs the exhaustiveness that is the whole point of\n * deriving the registry. This keeps the literal type AND checks membership. */\nexport const WITHHELD = \"off\" satisfies ResultCaptureMode;\n\n/** The `tool_call_end` payload members the capture mode decides.\n *\n * `result: null` under `\"off\"` is REDUNDANT here, and saying so is the point.\n * `ToolCallEndPayloadSchema.result` is `z.unknown().nullable().default(null)`,\n * so the key is present with a null value whether or not this branch names it —\n * the declare-rather-than-omit posture is the SCHEMA's, not this function's.\n * Dropping the literal yields a byte-identical wire shape and NOTHING detects\n * it. Kept because it states the intent at the site that decides the mode, not\n * because it is load-bearing.\n *\n * ⚠ **So do not look for a test that would catch its removal — there is none,\n * and two earlier versions of this paragraph named one.** The first said the\n * cross-SDK key-set check, which `withoutNulls` made blind; the second said\n * `errorResult.test.ts`'s `toContain(\"result\")`, which lives in a throw-path\n * test that never sets `resultCaptureMode` and so never enters this branch. The\n * guarantee that matters is asserted where it is produced:\n * `resultCapture.test.ts` pins `result` null under `\"off\"` on this leg. ⚠ The\n * sibling claim on the THROW leg (`withBaton.ts`) does hold —\n * `ToolCallErrorPayloadSchema.result` is `.optional()` with no default, so\n * removing that literal is detectable. Two legs, two different answers, which is\n * why this says which is which. */\n/** ⚠ PRECONDITION: call this ONLY from inside an `emit()` build thunk.\n * It applies the vendor's scrubber bare, which is correct there (a throw\n * drops the event) and wrong anywhere else (a throw reaches the agent as\n * `isError: true` on a call that worked — SPEC §11.2). This is still PROSE,\n * and prose is what let a site be missed once already: the `eslint-disable`\n * below pre-approves the bare call for any future caller, including one\n * outside a thunk. The structural fix is to take the scrubber as a thunk\n * ARGUMENT so no other caller can obtain it; recorded as F1b. */\nexport function endResultFields(\n mode: ResultCaptureMode,\n result: unknown,\n scrubber: (value: unknown) => unknown,\n): { result: unknown; result_capture?: string } {\n // The scrubber is called HERE and not by the caller: SPEC §7 says it MUST\n // NOT be invoked on a withheld result, so a helper handed an already-scrubbed\n // value would be a guard standing after the thing it guards.\n switch (mode) {\n case WITHHELD:\n return { result: null, result_capture: WITHHELD };\n case \"full\":\n // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk (both callers are thunks): emit drops the event, which is correct for a result\n return { result: scrubber(result) };\n }\n}\n\n/** The RETURN failure shape's result-derived members (SPEC §11.4.3(2)).\n *\n * Both are unwrapped FROM the result — `error_body` from its `content` text\n * parts, `result` as the whole envelope — so `\"off\"` withholds both and\n * neither `errorText` nor the scrubber runs on it.\n *\n * ⚠ `error_body` becomes `\"\"` rather than being dropped: it is REQUIRED on\n * `ToolCallErrorPayload`, and widening that array is a conformance change every\n * producer would have to follow. An empty `error_body` is genuinely ambiguous\n * with \"the failure carried no message\", and `result_capture` is what tells the\n * two apart — a second reason the marker is not optional.\n */\n/** ⚠ PRECONDITION: call this ONLY from inside an `emit()` build thunk.\n * It applies the vendor's scrubber bare, which is correct there (a throw\n * drops the event) and wrong anywhere else (a throw reaches the agent as\n * `isError: true` on a call that worked — SPEC §11.2). This is still PROSE,\n * and prose is what let a site be missed once already: the `eslint-disable`\n * below pre-approves the bare call for any future caller, including one\n * outside a thunk. The structural fix is to take the scrubber as a thunk\n * ARGUMENT so no other caller can obtain it; recorded as F1b. */\nexport function returnedErrorFields(\n mode: ResultCaptureMode,\n result: unknown,\n errorBody: (text: string) => string,\n scrubber: (value: unknown) => unknown,\n): { error_body: string; result: unknown; result_capture?: string } {\n return resultDerivedFields(mode, () => errorText(result), result, errorBody, scrubber);\n}\n\n/**\n * The same two members for ANY result-side failure, taking the text as a\n * THUNK rather than unwrapping it here.\n *\n * `returnedErrorFields` above is this with `errorText(result)` as the thunk.\n * The second caller is `failure_kind: \"output_schema_mismatch\"`, where the\n * handler returned and something above it rejected the output: the text there\n * may come off a THROWN value rather than off an envelope's `content`, so the\n * unwrapping cannot live in here.\n *\n * ⚠ **A thunk and not a string, which is the whole reason this is shaped this\n * way.** An eagerly-evaluated argument would unwrap a result the `\"off\"`\n * branch is about to discard — harmless to SPEC §7, which forbids only the\n * VENDOR's scrubber on a withheld result, but it would quietly retire the\n * property this module documents and tests: under `\"off\"` neither `errorText`\n * nor the scrubber touches the result at all.\n */\n/** ⚠ PRECONDITION: call this ONLY from inside an `emit()` build thunk — same\n * as its two siblings, and for the same reason. */\nexport function resultDerivedFields(\n mode: ResultCaptureMode,\n text: () => string,\n result: unknown,\n errorBody: (value: string) => string,\n scrubber: (value: unknown) => unknown,\n): { error_body: string; result: unknown; result_capture?: string } {\n switch (mode) {\n case WITHHELD:\n return { error_body: \"\", result: null, result_capture: WITHHELD };\n case \"full\":\n // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk (every caller is a thunk): emit drops the event, which is correct for a result\n return { error_body: errorBody(text()), result: scrubber(result) };\n }\n}\n\n/**\n * The REQUEST-SIDE failure's two body members, and it takes no capture mode\n * ON PURPOSE.\n *\n * The vendor's handler never ran, so there is no tool result anywhere in\n * this payload: `result` is null because none exists — the same reason\n * §11.4.3's RAISE shape carries null — and `error_body` is the SDK's own\n * rejection text, not anything a tool returned. Nothing here is\n * result-derived, so `\"off\"` has nothing to withhold and the event carries\n * **no `result_capture` marker**: SPEC §11.4's \"present only when results\n * are withheld\" applied, the same reading its library-path paragraph already\n * takes for an `error_body` the vendor supplied.\n *\n * ⚠ **`error_body` is KEPT under `\"off\"`, which is the rule's shape and not\n * an exception to it.** §11.4.3's table says so for all three request-side\n * kinds, and the provenance rule is why: this text describes the PRODUCER's\n * decision, the same standing as the strings `baton-proxy` authors for a\n * call it dropped. It is still scrubbed and capped — `invalid_argument`'s\n * message can echo the argument values the validator rejected, which is\n * exactly what a vendor scrubber is for.\n *\n * ⚠ **Taking a `mode` and ignoring it was the alternative, and it is worse**:\n * a reader would then have to find out WHY the switch has no branches, and a\n * later editor would add them. The absent parameter is the claim.\n */\n/** ⚠ PRECONDITION: call this ONLY from inside an `emit()` build thunk — the\n * same precondition its two siblings above carry, for the same reason: it\n * applies the vendor's scrubber (through `errorBody`) bare. */\nexport function requestSideErrorFields(\n text: string,\n errorBody: (value: string) => string,\n): { error_body: string; result: null } {\n return { error_body: errorBody(text), result: null };\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 { RESULT_CAPTURE_MODES, type ResultCaptureMode } from \"./errorResult.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\"]);\n// What the vendor may ask us to do with tool RESULT data (SPEC §11.4).\n// `\"full\"` never reaches the wire — absence is what means captured.\n//\n// DERIVED from the registry, never restated: a hand-written copy makes the\n// guarantee \"two lists happen to agree\", so a mode could be accepted here that\n// the emitter has no payload shape for.\nconst RESULT_CAPTURE_MODE_SET: ReadonlySet<string> = new Set(RESULT_CAPTURE_MODES);\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). `\"required\"` (default) injects `user_goal`/`expected_result`/\n * `overall_task` string params on every wrapped tool's advertised schema\n * and ADVERTISES `user_goal` as required in `tools/list`, without enforcing\n * it: a call that omits it still reaches your handler, and its event simply\n * carries no intent. `\"optional\"` injects the same params and advertises\n * none of them as required. `\"off\"` disables injection. The 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 /** Whether tool RESPONSE data is captured at all (SPEC §11.4).\n *\n * `\"full\"` (the default) captures as it always has. `\"off\"` means nothing\n * **derived from what your tool returns** leaves this process: no `result` on\n * `tool_call_end` or `tool_call_error`, and no `error_body` on the\n * returned-failure shape, where that text is unwrapped from the result. Each\n * affected event carries `result_capture: \"off\"`, so a reader has a FACT\n * rather than an absence to guess from — without it a missing result is\n * indistinguishable from \"the tool returned nothing\", and a consumer\n * manufactures a failure that never happened.\n *\n * **Requests are unaffected**: `params` are captured in both modes.\n *\n * ⚠ The message of an error your handler THROWS is KEPT — it is your own code\n * speaking about a call that never returned, so it is not result-derived\n * (SPEC §11.4.3). Thrown messages are a classic leak channel; if that is also\n * a problem for you, say so and the mode grows a stricter value.\n *\n * Not a scrubber rule, deliberately (SPEC §7): a scrubber TRANSFORMS a value\n * that still crosses the network, this DECLARES that nothing crosses. Under\n * `\"off\"` the scrubber is never invoked on the result at all.\n *\n * What it costs you, and the rest of the reasoning: README, \"Not capturing\n * responses at all\". Kept there rather than repeated here — the two copies\n * had already drifted apart in wording by the time this was written. */\n resultCaptureMode?: ResultCaptureMode;\n /** Per-request principal identity — the ASSERTED provenance behind the\n * envelope's `principal` (SPEC §11.4 rung 0), which emits\n * `source: \"asserted\"`. It is the only provenance this SDK has.\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 both SDKs** (SPEC §11.4): unset,\n * no event carries a `principal`. For OAuth, pass `principalFromOAuthSub` or\n * `principalFromOAuthEmail`, which read the validated token the context\n * carries as `authInfo`. MCP auth is HTTP middleware, so on stdio there is no\n * token and a hook names the user from whatever the vendor authenticated.\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 *\n * The SDK sends what the hook returns and does nothing else to it: the id\n * as given, `form` to say whether the hook hashed it, and `displayName` for\n * what a page shows. A vendor who must not send real identities hashes\n * inside the hook and returns `form: \"hashed\"`. */\n resolvePrincipal?: ResolvePrincipalHook;\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.\n const fromEnv = typeof process !== \"undefined\" ? process.env?.BATON_TENANT_ID : undefined;\n if (fromEnv) return fromEnv;\n return vendorId;\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 a principal. 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};\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 (\n config.resultCaptureMode !== undefined &&\n !RESULT_CAPTURE_MODE_SET.has(config.resultCaptureMode)\n ) {\n // The union literal above already makes an unregistered value a COMPILE\n // error for a TypeScript caller; this covers the JavaScript one, and it\n // matters more here than for most fields because the failure is silent in\n // the one direction that cannot be undone — an unrecognised mode reads as\n // \"not off\", so bodies a vendor believed were switched off get captured\n // and sent, with no error anywhere.\n throw new Error(\n `BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ` +\n `${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`,\n );\n }\n if (config.scrubber !== undefined && typeof config.scrubber !== \"function\") {\n // Refused AT INSTALL, and `scrubOrNull` is what makes this necessary rather\n // than merely tidy. Before the fail-open guard existed, a non-function here\n // (a JS caller, or `new Scrubber().scrub()` instead of `.scrub`) threw a\n // TypeError on the FIRST tool call — loud, immediate, unmistakable. The guard\n // now catches that TypeError, warns once per field, and every scrubbed field\n // degrades to `null` for the life of the process. So the guard converted a\n // loud failure into a silent one, and the door is where that gets paid back.\n // Same argument as `resolvePrincipal` below, found by review of the commit\n // that added the guard.\n throw new Error(\"BatonConfig.scrubber must be a function.\");\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}\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 * `intentParamMode` selects only `user_goal`'s description label (\"REQUIRED.\"\n * or \"OPTIONAL.\"). It never makes a field enforcing: the advertisement of\n * `required` happens on the `tools/list` RESPONSE, in withBaton.ts, and\n * `buildIntentFields` says why it cannot happen here.\n */\nexport function injectGoalParams(\n inputSchema: unknown,\n intentParamMode: IntentParamMode,\n): {\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, intentParamMode);\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 intentParamMode: IntentParamMode,\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 the zod schema, in EVERY mode. That\n // 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 breaking a customer's product to collect a\n // telemetry string. For a wrapper whose whole claim is that it does not\n // change how the wrapped server behaves, that is the wrong trade at any\n // capture rate, so `required` means what it means in the proxy and in\n // Python: ADVERTISED as required, never enforced.\n //\n // The advertisement cannot come from a zod expression, and the reason is\n // structural. Measured 2026-09-01 against both zod majors this package\n // 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 holds the two apart by\n // editing the rendered JSON Schema of a `tools/list` RESPONSE, and since\n // 2026-09-15 this package does the same: withBaton.ts wraps the SDK's\n // `tools/list` handler and `advertiseUserGoalRequired` (below) appends\n // `user_goal` to each injected tool's advertised `required`. The zod field\n // built here stays optional, so validation is unchanged and a call that\n // omits `user_goal` still reaches the vendor's handler.\n //\n // What `intentParamMode` still selects here is the description's leading\n // label, so the text never contradicts the schema it ships inside.\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({ intentParamMode }));\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 * `intentParamMode` selects the `user_goal` label only, as in\n * `injectGoalParams` above.\n */\nexport function injectGoalParamsV2(\n inputSchema: unknown,\n intentParamMode: IntentParamMode,\n): {\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, intentParamMode);\n if (Object.keys(toInject).length === 0)\n return { schema: inputSchema, dispositions };\n return { schema: candidate.extend(toInject), dispositions };\n}\n\n/**\n * The advertisement half of `intentParamMode: \"required\"`, applied to a\n * RENDERED `tools/list` result: `user_goal` is appended to the `required`\n * array (created when absent) of every tool `isInjected` names, and nothing\n * else changes. Copy on write, so the SDK's own result, and anything it\n * shares with a memo, is never mutated, and a caller that catches a throw\n * from here can serve the original untouched.\n *\n * Only the RESPONSE changes. The zod schema the SDK validates with is never\n * touched, so a call omitting `user_goal` still passes validation and still\n * reaches the vendor's handler: advertised as required, never enforced.\n */\nexport function advertiseUserGoalRequired(\n result: unknown,\n isInjected: (toolName: string) => boolean,\n): unknown {\n const tools = (result as { tools?: unknown } | null | undefined)?.tools;\n if (!Array.isArray(tools)) return result;\n let changed = false;\n const advertised = tools.map((tool: unknown) => {\n const entry = tool as { name?: unknown; inputSchema?: unknown } | null;\n if (typeof entry?.name !== \"string\" || !isInjected(entry.name)) return tool;\n const schema = entry.inputSchema as { required?: unknown } | null | undefined;\n if (!schema || typeof schema !== \"object\") return tool;\n const declared: unknown = schema.required ?? [];\n if (!Array.isArray(declared)) return tool;\n const required = declared as unknown[];\n if (required.includes(USER_GOAL_PARAM_NAME)) return tool;\n changed = true;\n return { ...entry, inputSchema: { ...schema, required: [...required, USER_GOAL_PARAM_NAME] } };\n });\n return changed ? { ...(result as Record<string, unknown>), tools: advertised } : result;\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","/** Ready-made `resolvePrincipal` hooks for a server running OAuth.\n *\n * Pass one as `BatonConfig.resolvePrincipal`. Each reads a claim off the\n * validated token the context carries as `authInfo`, and returns `null` when\n * the claim is not there — so they compose:\n *\n * ```ts\n * resolvePrincipal: (ctx) => principalFromOAuthEmail(ctx) ?? principalFromOAuthSub(ctx)\n * ```\n *\n * They are ordinary hooks: what they return is `source: \"asserted\"` like any\n * other (SPEC §11.4). The Python twins are `principal_from_oauth_sub` and\n * `principal_from_oauth_email`, and the two must agree on one token.\n *\n * ⚠ **They read the claims from `authInfo.extra`, and that is a convention,\n * not a contract.** Neither MCP major's `AuthInfo` has a `claims` member — the\n * only place a verifier can put the token's subject is the free-form `extra`\n * bag, and nothing specifies the keys. These hooks expect the standard JWT\n * claim names (`sub`, `iss`, `email`) at the top of `extra`, which is what a\n * verifier that spreads its decoded payload into `extra` produces. A verifier\n * that nests them, renames them or omits them gets `null` here, and its vendor\n * writes a three-line hook reading wherever their verifier put them. Python\n * reads a typed `claims` field instead, which is why the two arms describe the\n * same hooks differently.\n *\n * ⚠ **Never `clientId`.** It names the OAuth APPLICATION, not the person, and\n * is identical for every user of one app; keying on it merges all of them.\n *\n * HTTP only: MCP auth is HTTP middleware, so a stdio call has no token and both\n * hooks return `null` there.\n */\n\nimport { type Principal, pythonStrip } from \"../../identity.js\";\nimport { type PrincipalResolutionContext } from \"./principalResolution.js\";\n\n/** The token's claim bag, or `null`. Never throws: it reads an object a\n * vendor's verifier built, and an identity read may not fail a tool call. */\nfunction claimsOf(\n context: PrincipalResolutionContext,\n): Record<string, unknown> | null {\n try {\n const extra = context.authInfo?.extra;\n return extra !== null && typeof extra === \"object\" ? extra : null;\n } catch {\n return null;\n }\n}\n\n/** A non-blank string claim, or `null`. Blank is a miss: it names nobody, and\n * every such caller would merge into one actor.\n *\n * ⚠ `pythonStrip`, never `.trim()`: the two strip different codepoints\n * (`\\x1f` survives `.trim()`, U+FEFF survives Python's `strip()`), and the\n * Python twins decide blankness with `strip()`. With `.trim()` one token gave a\n * principal on one SDK and none on the other under `email ?? sub`. */\nfunction stringClaim(claims: Record<string, unknown>, name: string): string | null {\n const value = claims[name];\n return typeof value === \"string\" && pythonStrip(value) !== \"\" ? value : null;\n}\n\n/** The token's `sub`. A subject is unique only per issuer: a vendor running\n * two identity providers writes a hook that combines it with `iss`. */\nexport function principalFromOAuthSub(\n context: PrincipalResolutionContext,\n): Principal | null {\n const claims = claimsOf(context);\n if (claims === null) return null;\n const sub = stringClaim(claims, \"sub\");\n return sub === null ? null : { principalId: sub };\n}\n\n/** The token's `email`, as the WHOLE address.\n *\n * `principalId` is the whole address and `displayName` the part before the\n * last `@`. The local part alone is not an id — `alice@acme.com` and\n * `alice@contoso.com` are two people. A vendor who does not want `alice` on\n * the wire writes their own hook.\n *\n * ⚠ `email` is not a standard ACCESS-token claim (OIDC puts it in the ID\n * token), so it is here only if the identity provider adds it and the verifier\n * keeps it. `email_verified` is not consulted: whether an unverified address is\n * good enough is the vendor's call. */\nexport function principalFromOAuthEmail(\n context: PrincipalResolutionContext,\n): Principal | null {\n const claims = claimsOf(context);\n if (claims === null) return null;\n const email = stringClaim(claims, \"email\");\n if (email === null) return null;\n const at = email.lastIndexOf(\"@\");\n return {\n principalId: email,\n displayName: at > 0 ? email.slice(0, at) : null,\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;AAA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