@goodtiming/baton-sdk 1.1.1 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.cjs +1453 -957
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +102 -1
- package/dist/index.d.ts +102 -1
- package/dist/index.js +1453 -957
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/version.ts","../src/events.ts","../src/uuid7.ts","../src/runtime.ts","../src/warn.ts","../src/_object.ts","../src/scrub.ts","../src/sinks.ts","../src/_text.ts","../src/deadline.ts","../src/drops.ts","../src/sequence.ts","../src/integrations/mcp/withBaton.ts","../src/integrations/mcp/annotation.ts","../src/metaCoordinates.ts","../src/integrations/mcp/llmText.ts","../src/integrations/mcp/annotationName.ts","../src/integrations/mcp/emit.ts","../src/identity.ts","../src/integrations/mcp/mcpTypes.ts","../src/integrations/mcp/principalResolution.ts","../src/integrations/mcp/zodCompat.ts","../src/integrations/mcp/schemaCompat.ts","../src/integrations/mcp/safeScrub.ts","../src/integrations/mcp/clientObserved.ts","../src/integrations/mcp/sessionResolution.ts","../src/dsn.ts","../src/integrations/mcp/errorResult.ts","../src/integrations/mcp/captureSettings.ts","../src/integrations/mcp/config.ts","../src/optout.ts","../src/integrations/mcp/inputRequired.ts","../src/integrations/mcp/handle.ts","../src/integrations/mcp/perCaller.ts","../src/integrations/mcp/sessionCounter.ts","../src/integrations/mcp/surface.ts","../src/integrations/mcp/oauthHooks.ts","../src/library/session.ts","../src/library/surface.ts","../src/library/client.ts","../src/library/reportTool.ts"],"sourcesContent":["// TS-prefixed so `sdk_version` distinguishes TypeScript-sourced events from\n// Python (`baton-sdk`) ones in the Console — see design-notes/typescript_sdk.md.\nexport const SDK_VERSION = \"ts-1.1.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 * NOT camelCase).\n */\n\nimport { z } from \"zod\";\nimport { uuid7 } from \"./uuid7.js\";\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` is the value the SDK stripped from the injected `user_goal`\n * param, and `call_expected` / `call_workflow` the retired `expected_result` /\n * `overall_task` a stale client may still send (see `llmText.ts`); they ride\n * as SIBLINGS of `params` — `params` stays exactly the vendor-visible\n * 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 nullable. An annotation with `what_happened`\n * filled is a report; one without is a note (SPEC §11.4). `signal_type` is\n * kept for events from older producers: this SDK always sends it null. */\nexport const AnnotationPayloadSchema = z\n .object({\n intent: z.string().nullable().default(null),\n expected_outcome: z.string().nullable().default(null),\n what_happened: 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 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/** This process's lost-event counts by reason, as running totals (SPEC §11.4.7). */\nexport const ClientReportPayloadSchema = z\n .object({\n instance_id: z.uuid(),\n dropped: z.record(z.string(), z.number().int().nonnegative()),\n })\n .strict();\n/** @experimental May change in a minor release. */\nexport type ClientReportPayload = z.infer<typeof ClientReportPayloadSchema>;\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// Strict, with the headers spelled out, so a header that is not registered\n// cannot reach the wire: `clientObserved.test.ts`, \"refuses an unregistered\n// header at the schema\".\nexport const ClientObservedSchema = z\n .object({\n info: z.object({ name: z.string().optional(), version: z.string().optional() }).strict().optional(),\n headers: z\n .object({ \"user-agent\": z.string().optional(), \"x-anthropic-client\": z.string().optional() })\n .strict()\n .optional(),\n })\n .strict();\n\n/** Which collector settings a call ran under (SPEC §11.4, §2.6). A member\n * with no value is left out. */\nexport const CaptureObservedSchema = z\n .object({\n settings_version: z.number().int().min(1).optional(),\n audience: z.string().optional(),\n overlay: z.string().optional(),\n })\n .strict();\nexport type CaptureObserved = z.infer<typeof CaptureObservedSchema>;\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 `identityWire` 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(() => uuid7()),\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 // Legacy (SPEC §3.4): never set by this SDK, so always the default. The\n // consumer names the client from `client_observed`.\n agent_runtime: z.string().default(\"unknown\"),\n principal: PrincipalWireSchema.nullable().default(null),\n organization: PrincipalWireSchema.nullable().default(null),\n // No length rules here: zod counts UTF-16 units, SPEC §11.4 code points.\n // `cleanLabels` applies them.\n labels: z.array(z.string()).nullable().default(null),\n capture: CaptureObservedSchema.nullable().default(null),\n transport_observed: z.string().nullable().default(null),\n session_id_origin: z.string().nullable().default(null),\n client_observed: ClientObservedSchema.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 \"client_report\",\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 // SPEC §11.4.5.\n \"tool_list_start\",\n \"tool_list_end\",\n \"tool_list_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/** `tools/list` reached the server (SPEC §11.4.5). Empty, for the reason\n * `ResourceListStartPayloadSchema` carries. */\nexport const ToolListStartPayloadSchema = z.object({}).strict();\nexport type ToolListStartPayload = z.infer<typeof ToolListStartPayloadSchema>;\n\n/** `tools/list` returned. `count` is the length of the `tools` array in that\n * one response, this SDK's own tool included. */\nexport const ToolListEndPayloadSchema = z\n .object({\n count: z.number().int(),\n ...timingShape,\n })\n .strict();\nexport type ToolListEndPayload = z.infer<typeof ToolListEndPayloadSchema>;\n\n/** `tools/list` failed. See `ResourceReadErrorPayloadSchema`. */\nexport const ToolListErrorPayloadSchema = z\n .object({\n ...failureShape,\n })\n .strict();\nexport type ToolListErrorPayload = z.infer<typeof ToolListErrorPayloadSchema>;\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\n/** SPEC §11.4: a tool-call leg always carries the id its other leg carries. */\nconst REQUIRED_CALL_ID = z.string().min(1);\n\nexport const ToolCallStartEventSchema = z\n .object({\n ...envelopeShape,\n call_id: REQUIRED_CALL_ID,\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 call_id: REQUIRED_CALL_ID,\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 call_id: REQUIRED_CALL_ID,\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\nexport const ClientReportEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"client_report\").default(\"client_report\"),\n payload: ClientReportPayloadSchema,\n })\n .strict();\n/** @experimental May change in a minor release. */\nexport type ClientReportEvent = z.infer<typeof ClientReportEventSchema>;\n\n// ⚠ The lifecycle events carry the SAME `envelopeShape` as the five\n// above, which is what lets one collector endpoint accept every type 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\nexport const ToolListStartEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"tool_list_start\").default(\"tool_list_start\"),\n payload: ToolListStartPayloadSchema,\n })\n .strict();\nexport type ToolListStartEvent = z.infer<typeof ToolListStartEventSchema>;\n\nexport const ToolListEndEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"tool_list_end\").default(\"tool_list_end\"),\n payload: ToolListEndPayloadSchema,\n })\n .strict();\nexport type ToolListEndEvent = z.infer<typeof ToolListEndEventSchema>;\n\nexport const ToolListErrorEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"tool_list_error\").default(\"tool_list_error\"),\n payload: ToolListErrorPayloadSchema,\n })\n .strict();\nexport type ToolListErrorEvent = z.infer<typeof ToolListErrorEventSchema>;\n\n// =============================================================================\n// Discriminated union — mirrors Python's `Event` (discriminator: event_type)\n// =============================================================================\n\n/** @experimental The zod schema for any event. Its type names zod's, so it may\n * change with a zod major. */\nexport const EventSchema = z.discriminatedUnion(\"event_type\", [\n ToolCallStartEventSchema,\n ToolCallEndEventSchema,\n ToolCallErrorEventSchema,\n AnnotationEventSchema,\n SurfaceSnapshotEventSchema,\n ClientReportEventSchema,\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 ToolListStartEventSchema,\n ToolListEndEventSchema,\n ToolListErrorEventSchema,\n]);\n/** ⚠ DERIVED, not hand-listed. It used to be a third list of the same\n * 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","import * as crypto from \"node:crypto\";\n\nconst COUNTER_MAX = 0xfff;\n\nlet lastMs = -1;\nlet counter = 0;\n\n/** RFC 9562 UUIDv7, strictly increasing within this process: a 12-bit counter\n * orders ids minted in one millisecond, as the Python SDK's `_uuid.py` does. */\nexport function uuid7(): string {\n const bytes = crypto.randomBytes(18);\n // Seeded below half the counter's range, so a burst has room to count up.\n const seed = ((bytes[16]! << 8) | bytes[17]!) & 0x7ff;\n const now = Date.now();\n if (now > lastMs) {\n lastMs = now;\n counter = seed;\n } else if (++counter > COUNTER_MAX) {\n lastMs += 1;\n counter = seed;\n }\n\n bytes.writeUIntBE(lastMs, 0, 6);\n bytes[6] = 0x70 | (counter >> 8);\n bytes[7] = counter & 0xff;\n bytes[8] = 0x80 | (bytes[8]! & 0x3f);\n\n const hex = bytes.toString(\"hex\", 0, 16);\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","/** Whether this runs on Cloudflare Workers. `WebSocketPair` is there at\n * every compatibility date; `navigator` only from 2022-03-21. */\nexport function onWorkers(): boolean {\n return typeof (globalThis as { WebSocketPair?: unknown }).WebSocketPair === \"function\" ||\n (typeof navigator !== \"undefined\" && navigator.userAgent === \"Cloudflare-Workers\");\n}\n\n/** The global `fetch`, looked up at each call. Called as a method, a\n * Worker's `fetch` throws \"Illegal invocation\". */\nexport const globalFetch: typeof fetch = (input, init) => fetch(input, init);\n\n/** Adds `listener` for `event` to `process`, and returns what takes it off\n * that same `process`, which a test may since have swapped for a stand-in.\n * `undefined` where `process` takes no listeners, as on an edge runtime. */\nexport function onProcess(event: \"beforeExit\" | \"exit\", listener: () => void): (() => void) | undefined {\n const target = typeof process !== \"undefined\" ? process : undefined;\n if (typeof target?.on !== \"function\") return undefined;\n try {\n target.on(event, listener);\n } catch {\n return undefined;\n }\n return () => {\n try {\n target.off(event, listener);\n } catch {\n // A stand-in with `on` and no working `off`: nothing more to take off.\n }\n };\n}\n","import { onWorkers } from \"./runtime.js\";\n\n/** `process.emitWarning`, else a stderr line (`stderrLine`). On a Worker it is\n * `console.warn`, because a Worker prints nothing for `emitWarning`. Never\n * `console.log`: under stdio, stdout carries the MCP JSON-RPC frames. */\nexport function warn(message: string): void {\n if (onWorkers()) {\n // eslint-disable-next-line no-console -- console.warn writes to stderr, never to stdout\n console.warn(message);\n return;\n }\n try {\n if (typeof process !== \"undefined\" && typeof process.emitWarning === \"function\") return process.emitWarning(message);\n } catch {\n // A stand-in `emitWarning` that throws: Baton's own catch blocks call this.\n }\n stderrLine(message);\n}\n\n/** One line to stderr, or to `console.warn` where `process.stderr` is missing\n * or its write throws.\n * Never throws: it reports failures from inside Baton's own catch blocks. */\nexport function stderrLine(message: string): void {\n stderrLines([message]);\n}\n\n/** `lines` to stderr in one write, or each to `console.warn`. Never throws. */\nexport function stderrLines(lines: readonly string[]): void {\n try {\n // eslint-disable-next-line no-restricted-syntax -- this is the guarded read\n const stderr = typeof process !== \"undefined\" ? process.stderr : undefined;\n if (typeof stderr?.write === \"function\") return void stderr.write(lines.map((line) => `${line}\\n`).join(\"\"));\n } catch {\n // An ended or stand-in stderr: try `console.warn`.\n }\n for (const line of lines) {\n try {\n // eslint-disable-next-line no-console -- console.warn writes to stderr, never to stdout\n console.warn(line);\n } catch {\n // Nowhere left to report it.\n }\n }\n}\n\n/** `String(err)`, which throws for an object with no usable `toString`. */\nexport function printable(err: unknown): string {\n try {\n return String(err);\n } catch {\n return \"(an error that cannot be printed)\";\n }\n}\n","/** True only for `{...}` literals and `Object.create(null)` — the TS\n * analogue of Python's `isinstance(value, dict)`. A class instance, `Date` or\n * `Map` is not one, as it is not a dict in Python. */\nexport function 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/** Any object but an array, class instances included. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\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\nimport { warn } from \"./warn.js\";\nimport { isPlainObject } from \"./_object.js\";\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\nexport const DEPTH_MARKER = \"[REDACTED:depth-limit]\";\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// SPEC §7's whitespace set; JS `\\s` is wider. Held by \"no pattern uses `\\s` or\n// the `u` flag\" in scrub.test.ts.\nconst WS_CHARS = String.raw` \\t\\n\\r\\f\\u00a0`;\nconst PHONE_SEP = String.raw`[${WS_CHARS}\\-.]`;\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.\nexport const PATTERNS: ReadonlyArray<readonly [string, RegExp]> = [\n [\"jwt\", /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b/g],\n [\"bearer\", new RegExp(String.raw`\\bBearer[${WS_CHARS}]+[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 // `-`, `.` or `WS_CHARS`, 10 digits. Conservative — won't catch every\n // international format, but won't trip on every 10-digit identifier.\n [\n \"phone\",\n new RegExp(String.raw`\\b(?:\\+?1${PHONE_SEP}?)?\\(?\\d{3}\\)?${PHONE_SEP}?\\d{3}${PHONE_SEP}?\\d{4}\\b`, \"g\"),\n ],\n];\n\n// Credit-card candidates — Luhn-filtered before redacting to keep false\n// positives down on long numeric IDs (timestamps, order numbers).\nexport const 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/**\n * Stateful recursive scrubber with the default ruleset baked in.\n *\n * Construct one per `withBaton` or `createBaton` 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 private warnedDepth = false;\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 pastTheDepthLimit(): string {\n this.bump(\"depth_limit\");\n if (!this.warnedDepth) {\n this.warnedDepth = true;\n warn(\n `baton: a payload nests deeper than ${DEPTH_LIMIT} levels; containers past that depth are sent as ${JSON.stringify(DEPTH_MARKER)}`,\n );\n }\n return DEPTH_MARKER;\n }\n\n private walk(value: unknown, depth: number, forceField: string | null): unknown {\n if (depth >= DEPTH_LIMIT && (isPlainObject(value) || Array.isArray(value))) {\n return this.pastTheDepthLimit();\n }\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 * The same four sinks as `sinks.py`:\n *\n * - `StdoutSink` — JSONL to stderr, or to a stream the vendor passes (MCP\n * stdio transport reserves stdout for JSON-RPC framing).\n * - `FileSink` — JSONL appended to a file.\n * - `HttpSink` — POST batches to any HTTP endpoint with bearer auth;\n * bounded buffer, retry with backoff, circuit breaker. This is the contract a\n * Console or any compatible collector consumes.\n * - `MultiSink` — every event to each of several sinks.\n */\n\nimport * as fs from \"node:fs\";\nimport * as fsp from \"node:fs/promises\";\nimport { capCodePoints, escapeForLog } from \"./_text.js\";\nimport { MAX_TIMER_MS, raceDeadline, SHUTDOWN_FLUSH_TIMEOUT_MS, TIMED_OUT } from \"./deadline.js\";\nimport { PROCESS_DROPS } from \"./drops.js\";\nimport { ClientReportEventSchema, type Event } from \"./events.js\";\nimport { globalFetch, onProcess, onWorkers } from \"./runtime.js\";\nimport { nextClockSequence } from \"./sequence.js\";\nimport { printable, stderrLine, stderrLines, warn } from \"./warn.js\";\n\nconst REFUSAL_BODY_MAX_LEN = 500;\n/** The least time between two refusal warnings with the same status, so a\n * collector refusing every event is not one warning per event. */\nconst REFUSAL_LOG_MS = 60_000;\n\nexport interface Sink {\n /** Hand one event to the sink. Baton calls a sink you write from a queue,\n * one event at a time for each install or client the sink is given to,\n * never from the vendor's call: a slow write delays later events, not the\n * vendor. */\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 with\n * `SinkClosedError`. */\n aclose(): Promise<void>;\n}\n\n/** `write` was called after `aclose`. */\nexport class SinkClosedError extends Error {\n override name = \"SinkClosedError\";\n}\n\n/** By name, not `instanceof`: a vendor sink may throw the class from the\n * other build (ESM or CommonJS) of this package. */\nexport function isSinkClosed(err: unknown): boolean {\n return err instanceof Error && err.name === \"SinkClosedError\";\n}\n\nconst warnedClosed = new WeakSet<Sink>();\n\n/** SPEC §11.2 rules 7 and 8: dropped, counted under `after_close`, and\n * warned about once for each sink passed. Baton passes its queue, or an\n * `HttpSink` that has none, so that is once per queue. */\nexport function droppedAfterClose(sink: Sink): void {\n PROCESS_DROPS.add(\"after_close\");\n if (warnedClosed.has(sink)) return;\n warnedClosed.add(sink);\n warn(\"baton: the sink is closed; further events are dropped.\");\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 if (isSinkClosed(err)) return droppedAfterClose(sink);\n PROCESS_DROPS.add(\"write_failed\");\n stderrLine(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}`);\n }\n}\n\nfunction isTimerMs(value: unknown): value is number {\n return typeof value === \"number\" && value >= 0 && value <= MAX_TIMER_MS;\n}\n\nfunction timerMsOption(given: unknown, name: string, fallback: number): number {\n if (isTimerMs(given)) return given;\n if (given !== undefined) warn(`baton: ${name} must be from 0 to ${MAX_TIMER_MS} ms; using ${fallback}.`);\n return fallback;\n}\n\nfunction shutdownBudgetMs(sink: Sink): number {\n try {\n // MultiSink runs its sinks side by side, so it needs the longest budget.\n if (sink instanceof MultiSink) return Math.max(...sink[\"sinks\"].map(shutdownBudgetMs));\n if (sink instanceof QueuedSink) return shutdownBudgetMs(sink.inner);\n const budget: unknown = sink instanceof HttpSink ? sink[\"shutdownFlushTimeoutMs\"] : undefined;\n if (isTimerMs(budget)) return budget;\n } catch {\n // A Proxy or subclass whose read throws gets the default.\n }\n return SHUTDOWN_FLUSH_TIMEOUT_MS;\n}\n\n/** A sink's `flush()` or `aclose()`, telling Baton's own how much time is\n * left. Any other, a subclass's override included, is called as it is. */\nexport function callWithin(sink: Sink, method: \"flush\" | \"aclose\", ms: number): Promise<void> {\n if (sink[method] === HttpSink.prototype[method]) return (sink as HttpSink)[`${method}Within`](ms);\n if (sink[method] === MultiSink.prototype[method]) return (sink as MultiSink)[`${method}Within`](ms);\n return sink[method]();\n}\n\n/** Run a sink's `flush()` or `aclose()` for the vendor (or `work`, which is\n * handed the budget and ends in one): never rejects, and returns within the\n * sink's shutdown budget. The budget gets a little extra, so `HttpSink`, which\n * enforces its own, is the one whose warning, which counts what was left, is\n * shown. */\nexport async function boundedSinkCall(\n sink: Sink,\n method: \"flush\" | \"aclose\",\n work: (budgetMs: number) => unknown = () => sink[method](),\n): Promise<void> {\n const what = `${method}()`;\n const budget = shutdownBudgetMs(sink);\n const ms = budget + 250;\n // `Promise.resolve().then(work)` also catches a sync throw and a method\n // that returns no promise.\n const settled = Promise.resolve()\n .then(() => work(budget))\n .then(\n () => undefined,\n (err: unknown) => warn(`baton: ${what} failed: ${printable(err)}`),\n );\n if ((await raceDeadline(settled, ms)) === TIMED_OUT) {\n warn(`baton: ${what} took over ${String(ms)} ms and was left unfinished.`);\n }\n}\n\n// =============================================================================\n// StdoutSink — JSONL to a writable stream (default: stderr)\n// =============================================================================\n\nexport interface StdoutSinkOptions {\n /** Defaults to stderr (`console.warn` where `process.stderr` is missing or\n * cannot write): the MCP\n * stdio transport reserves stdout for JSON-RPC framing. Pass\n * `process.stdout` for non-MCP (library API) use if preferred. */\n stream?: NodeJS.WritableStream;\n}\n\nexport class StdoutSink implements Sink {\n private readonly stream: NodeJS.WritableStream | undefined;\n private closed = false;\n\n constructor(options: StdoutSinkOptions = {}) {\n this.stream = options.stream;\n }\n\n async write(event: Event): Promise<void> {\n if (this.closed) throw new SinkClosedError(\"StdoutSink is closed\");\n const line = JSON.stringify(event);\n if (this.stream) this.stream.write(line + \"\\n\");\n else stderrLine(line);\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// FileSink — JSONL append to a path\n// =============================================================================\n\n/** Appends one JSON envelope per line to a file, opened on the first write so\n * an unused sink creates no file. Each line reaches the file before `write`\n * resolves, so `tail -f` sees it at once. */\nexport class FileSink implements Sink {\n private file: fsp.FileHandle | null = null;\n private closeOnce: Promise<void> | undefined;\n /** Writes run one after another: two at once on one file can interleave. */\n private last: Promise<unknown> = Promise.resolve();\n private closed = false;\n\n constructor(private readonly path: string) {}\n\n async write(event: Event): Promise<void> {\n if (this.closed) throw new SinkClosedError(\"FileSink is closed\");\n const line = JSON.stringify(event) + \"\\n\";\n const written = this.last.then(async () => {\n this.file ??= await fsp.open(this.path, \"a\");\n await this.file.appendFile(line);\n });\n this.last = written.catch(() => undefined);\n await written;\n }\n\n async flush(): Promise<void> {\n await this.last;\n }\n\n /** A second call waits for the first (SPEC §11.2 rule 7). */\n aclose(): Promise<void> {\n this.closed = true;\n this.closeOnce ??= this.last.then(async () => {\n await this.file?.close();\n this.file = null;\n });\n return this.closeOnce;\n }\n}\n\n// =============================================================================\n// MultiSink — fan out to several sinks\n// =============================================================================\n\n/** Sends each event to every sink, e.g. `new MultiSink([new StdoutSink(),\n * new HttpSink(...)])` to watch what is shipped. Every sink is tried even when\n * one fails; one failure is rethrown as is, several as an `AggregateError`. */\nexport class MultiSink implements Sink {\n private readonly sinks: readonly Sink[];\n\n constructor(sinks: readonly Sink[]) {\n if (sinks.length === 0) throw new Error(\"MultiSink requires at least one sink\");\n this.sinks = [...sinks];\n }\n\n write(event: Event): Promise<void> {\n return this.fanOut((sink) => sink.write(event));\n }\n\n flush(): Promise<void> {\n return this.flushWithin(Infinity);\n }\n\n aclose(): Promise<void> {\n return this.acloseWithin(Infinity);\n }\n\n private flushWithin(ms: number): Promise<void> {\n return this.fanOut((sink) => callWithin(sink, \"flush\", ms));\n }\n\n private acloseWithin(ms: number): Promise<void> {\n return this.fanOut((sink) => callWithin(sink, \"aclose\", ms));\n }\n\n private async fanOut(op: (sink: Sink) => Promise<void>): Promise<void> {\n // The async wrapper turns a sink that throws synchronously into a rejection.\n const results = await Promise.allSettled(this.sinks.map(async (sink) => op(sink)));\n let errors = results.flatMap((r): unknown[] => (r.status === \"rejected\" ? [r.reason] : []));\n // Another sink took the event, so it was not lost.\n if (errors.length < results.length) errors = errors.filter((e) => !isSinkClosed(e));\n if (errors.length === 0) return;\n if (errors.length === 1 || errors.every(isSinkClosed)) throw errors[0];\n throw new AggregateError(errors, \"MultiSink fan-out failures\");\n }\n}\n\n// =============================================================================\n// QueuedSink — every sink but HttpSink, written off the vendor's call\n// =============================================================================\n\nconst QUEUE_BOUND = 1000;\n/** Events written before the writer gives the event loop a turn. */\nconst WRITES_PER_TURN = 100;\n/** The part of close's budget kept for the inner sink's own close. */\nconst CLOSE_GRACE_MS = 250;\n\n/** Later than a microtask, so the vendor's call goes on before the write. */\nconst later = (run: () => void): void => {\n if (typeof setImmediate === \"function\") setImmediate(run);\n else setTimeout(run, 0);\n};\n\nconst withUnwrittenEvents = new Set<QueuedSink>();\n/** Each `process` the exit hand-off was tried on, once: a test may swap in a\n * stand-in, and the real `process` still needs its own. */\nconst exitTriedOn = new WeakSet<object>();\n\n/** At `process.exit()` nothing can be awaited: queued events go synchronously\n * to a `StdoutSink` on stdout/stderr or a `FileSink`, and are reported as\n * possibly lost for any other sink (SPEC §11.2 rules 7 and 8). */\nfunction hookExit(): void {\n const target = typeof process !== \"undefined\" ? process : undefined;\n if (target === undefined || exitTriedOn.has(target)) return;\n exitTriedOn.add(target);\n onProcess(\"exit\", () => {\n try {\n let unsure = 0;\n for (const sink of withUnwrittenEvents) unsure += sink.handOffAtExit();\n if (unsure > 0) stderrLine(`baton: process exiting; ${unsure} event(s) may not have been written.`);\n } catch {\n // A throw here would turn the vendor's clean exit into a crash.\n }\n });\n}\n\n/** Writes `events` before it returns, for the sinks that can: at exit nothing\n * can be awaited. False for any other sink, or a stream that may write later. */\nfunction writeNow(sink: Sink, events: Event[]): boolean {\n const json = (): string[] => events.map((event) => JSON.stringify(event));\n const lines = (): string => json().map((line) => line + \"\\n\").join(\"\");\n if (sink instanceof StdoutSink) {\n const stream = sink[\"stream\"];\n // eslint-disable-next-line no-restricted-syntax -- reached only when the vendor passed a stream, and only compared\n if (stream !== undefined && stream !== process.stdout && stream !== process.stderr) return false;\n if (sink[\"closed\"]) return true;\n if (stream === undefined) stderrLines(json());\n else stream.write(lines());\n } else if (sink instanceof FileSink) {\n if (!sink[\"closed\"]) fs.appendFileSync(sink[\"path\"], lines());\n } else return false;\n return true;\n}\n\n/** Holds events for `inner` and writes them one at a time, in order, after\n * the call that recorded them has gone on, so a slow, stuck or failing sink\n * never slows the vendor (SPEC §11.2 rules 3 and 8). */\nexport class QueuedSink implements Sink {\n private readonly queue: Event[] = [];\n private closed = false;\n private draining = false;\n /** Set when close ran out of time or the process is exiting: what was left is already handled. */\n private abandoned = false;\n private inFlight = 0;\n /** A flush waits until `settled`, the events written or lost, reaches `taken` as it was. */\n private taken = 0;\n private settled = 0;\n /** Writes that returned, so a dropped event does not look like progress. */\n private ended = 0;\n /** `ended` when a flush waited its whole budget: until a write ends, later flushes return at once. */\n private stuckAt: number | null = null;\n private waiters: { upTo: number; resolve: () => void }[] = [];\n private overflowWarned = false;\n private failWarned = false;\n private copyWarned = false;\n private closeOnce: Promise<void> | undefined;\n\n constructor(readonly inner: Sink) {}\n\n private get unwritten(): number {\n return this.queue.length + this.inFlight;\n }\n\n /** Writes what waits to a `StdoutSink` or `FileSink` at once; answers how\n * many events may not be written. */\n handOffAtExit(): number {\n this.abandoned = true;\n const waiting = this.queue.splice(0);\n let written = false;\n try {\n written = waiting.length === 0 || writeNow(this.inner, waiting);\n } catch {\n // Counted below as not written.\n }\n return this.inFlight + (written ? 0 : waiting.length);\n }\n\n async write(event: Event): Promise<void> {\n if (this.closed) throw new SinkClosedError(\"the sink is closed\");\n // A copy, because the sink writes later: by then the vendor may have\n // changed a params or result object the event still points at. JSON,\n // so the copy is what a sink that writes JSON would have written.\n let copy: Event;\n try {\n copy = JSON.parse(JSON.stringify(event)) as Event;\n } catch (err) {\n PROCESS_DROPS.add(\"encode_failed\");\n if (!this.copyWarned) {\n this.copyWarned = true;\n // Only the error's name: its message can quote the event's own text.\n warn(`baton: an event could not be copied and was dropped (${(err as Error)?.name ?? \"Error\"}). Later ones are not logged.`);\n }\n return;\n }\n this.queue.push(copy);\n this.taken++;\n if (this.queue.length > QUEUE_BOUND) {\n this.queue.shift();\n this.settle();\n PROCESS_DROPS.add(\"buffer_full\");\n if (!this.overflowWarned) {\n this.overflowWarned = true;\n warn(`baton: the sink's queue is full (${QUEUE_BOUND}); oldest events dropped. Further overflows will be silent.`);\n }\n }\n withUnwrittenEvents.add(this);\n hookExit();\n if (!this.draining) {\n this.draining = true;\n later(() => void this.drain());\n }\n }\n\n /** Waits for the events written before it, not for later ones (SPEC §11.2 rule 7). */\n async flush(): Promise<void> {\n if (this.closed || this.stuckAt === this.ended) return;\n const budget = shutdownBudgetMs(this.inner);\n const start = performance.now();\n if ((await raceDeadline(this.settledUpTo(this.taken), budget)) === TIMED_OUT) this.stuckAt = this.ended;\n await callWithin(this.inner, \"flush\", Math.max(0, budget - (performance.now() - start)));\n }\n\n /** A second call waits for the first (SPEC §11.2 rule 7). */\n aclose(): Promise<void> {\n this.closeOnce ??= this.close(shutdownBudgetMs(this.inner));\n return this.closeOnce;\n }\n\n /** Takes events until the queue is empty, as `HttpSink` does, so an event\n * recorded while close runs is not refused. */\n private async close(ms: number): Promise<void> {\n const start = performance.now();\n const deadline = start + ms - Math.min(CLOSE_GRACE_MS, ms / 2);\n let timedOut = false;\n while (this.settled < this.taken && !timedOut) {\n timedOut = (await raceDeadline(this.settledUpTo(this.taken), deadline - performance.now())) === TIMED_OUT;\n }\n this.closed = true;\n if (timedOut) {\n const unwritten = this.unwritten;\n this.abandoned = true;\n this.queue.length = 0;\n withUnwrittenEvents.delete(this);\n PROCESS_DROPS.add(\"unsent_at_close\", unwritten);\n warn(`baton: closed with ${unwritten} event(s) not yet written to the sink.`);\n }\n await callWithin(this.inner, \"aclose\", Math.max(0, ms - (performance.now() - start)));\n }\n\n private async drain(): Promise<void> {\n try {\n let event: Event | undefined;\n let written = 0;\n while (!this.abandoned && (event = this.queue.shift()) !== undefined) {\n this.inFlight = 1;\n try {\n await this.inner.write(event);\n } catch (err) {\n if (!this.abandoned) this.lose(err);\n } finally {\n this.inFlight = 0;\n this.ended++;\n this.settle();\n }\n // A sink that answers at once would otherwise hold the event loop for the whole queue.\n if (++written % WRITES_PER_TURN === 0) await new Promise<void>((resolve) => later(resolve));\n }\n } catch {\n // Only `lose` can get here, after it counted the event: a warning\n // that throws must not stop the queue.\n } finally {\n this.draining = false;\n if (this.queue.length === 0) withUnwrittenEvents.delete(this);\n else if (!this.abandoned) {\n this.draining = true;\n later(() => void this.drain());\n }\n }\n }\n\n private lose(err: unknown): void {\n if (isSinkClosed(err)) return droppedAfterClose(this);\n PROCESS_DROPS.add(\"write_failed\");\n if (this.failWarned) return;\n this.failWarned = true;\n warn(`baton: the sink failed to write an event; it was dropped. Later failures are not logged: ${printable(err)}`);\n }\n\n private settle(): void {\n this.settled++;\n this.waiters = this.waiters.filter((w) => {\n if (w.upTo > this.settled) return true;\n w.resolve();\n return false;\n });\n }\n\n private settledUpTo(upTo: number): Promise<void> {\n if (this.settled >= upTo) return Promise.resolve();\n return new Promise((resolve) => this.waiters.push({ upTo, resolve }));\n }\n}\n\n/** HttpSink already queues; any other sink gets a new `QueuedSink`, one for\n * each install or client. */\nexport function offTheCall(sink: Sink): Sink {\n // An HttpSink subclass that keeps HttpSink's write still only queues.\n if (sink instanceof QueuedSink || (sink instanceof HttpSink && sink.write === HttpSink.prototype.write)) return sink;\n return new QueuedSink(sink);\n}\n\n// =============================================================================\n// HttpSink — batches + bearer + bounded buffer + retry + circuit breaker\n// =============================================================================\n\nconst BATCH_OPEN = '{\"events\":[';\nconst BATCH_CLOSE = \"]}\";\nexport const BATCH_FRAME_BYTES = (BATCH_OPEN + BATCH_CLOSE).length;\n/** SPEC §2.5's caps on one batch. */\nconst BATCH_MAX_EVENTS = 100;\nexport const BATCH_MAX_BYTES = 1_048_576;\nconst FLUSH_INTERVAL_MS = 5000;\n/** SPEC §2.5: `Retry-After` is honoured from 1 to 60 seconds. */\nconst RETRY_AFTER_MIN_S = 1;\nconst RETRY_AFTER_MAX_S = 60;\n\ntype SendOutcome = \"success\" | \"permanent_failure\" | \"transient_failure\";\n\n/** An event waiting to be sent, or the loss report riding a batch\n * (`reportSum` set), which is never in the buffer. */\ninterface Waiting {\n event: Event;\n json: string;\n bytes: number;\n writtenAt: number;\n reportSum?: number;\n}\n\ninterface Refusal {\n kind: string;\n detail: string;\n}\n\ntype Answer =\n | { kind: \"answered\"; refused: Map<string, Refusal> }\n | { kind: \"refused\"; refusal: Refusal; status: number }\n | { kind: \"too_large\" }\n | { kind: \"no_batch_endpoint\" }\n | { kind: \"transient\"; retryAfterMs: number | null };\n\nconst utf8 = new TextEncoder();\n\nfunction utf8Bytes(text: string): number {\n return typeof Buffer === \"undefined\" ? utf8.encode(text).length : Buffer.byteLength(text, \"utf8\");\n}\n\nfunction sum(values: Iterable<number>): number {\n let total = 0;\n for (const value of values) total += value;\n return total;\n}\n\n/** A whole number of seconds, clamped; `null` for anything else (SPEC §2.5). */\nfunction retryAfterMs(header: string | null): number | null {\n const value = header?.trim() ?? \"\";\n if (!/^\\d+$/.test(value)) return null;\n return Math.min(Math.max(Number(value), RETRY_AFTER_MIN_S), RETRY_AFTER_MAX_S) * 1000;\n}\n\ntype BatchKey = Pick<Event, \"tenant_id\" | \"vendor_id\">;\n\nfunction sameBatch(a: BatchKey, b: BatchKey): boolean {\n return a.tenant_id === b.tenant_id && a.vendor_id === b.vendor_id;\n}\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 return this.msUntilRequest() === 0;\n }\n\n msUntilRequest(): number {\n if (this.openedAt === null) return 0;\n return Math.max(this.openedAt + this.resetMs - Date.now(), 0);\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 /** How long the flush at process exit, or an explicit `flush()` or\n * `aclose()`, may take in total, in ms, at most 2^31 - 1. Default 3000. */\n shutdownFlushTimeoutMs?: number;\n /** The longest an event waits before its batch is sent, in ms. Default\n * 5000, or 0 on Cloudflare Workers. At 0 a write sends at once. */\n flushIntervalMs?: number;\n /** Injectable for tests; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n}\n\n/** POST events to an HTTP endpoint in batches. Bounded buffer + retry +\n * circuit breaker.\n *\n * This is the contract a Console or any compatible collector consumes:\n * `POST {url}/v0/events/batch` (SPEC §2.5) with `Authorization: Bearer\n * {apiKey}` and `{\"events\": [...]}` of SPEC §11.4 envelopes. A batch goes when\n * 100 events wait, when the next would take the body over 1 MiB, or\n * `flushIntervalMs` after the oldest waiting one was written. A collector\n * with no batch endpoint gets one event per `POST {url}/v0/events`.\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 /** Waiting events only: a batch being sent is out of it, so the bound\n * never pushes out an event in flight (SPEC §11.2 rule 4). */\n private readonly buffer: Waiting[] = [];\n private bufferedBytes = 0;\n private sendingEvents = 0;\n private readonly bufferSize: number;\n private readonly requestTimeoutMs: number;\n private readonly shutdownFlushTimeoutMs: number;\n private readonly flushIntervalMs: number;\n /** Set when an exit pass ends; cleared once a normal drain sends\n * everything, which means the process went on. */\n private exitPassRan = false;\n /** Whether the exit pass warned about every event now buffered. */\n private unsentWarned = false;\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 /** Per status or refusal code, so a new kind of refusal, such as a 401\n * after a 422, still warns. */\n private readonly refusals = new Map<string, { loggedAt: number; unlogged: number }>();\n /** Aborted once `aclose()` returns: nothing Baton started may keep the\n * process alive after the vendor closed it. */\n private readonly closing = new AbortController();\n /** The drain chain's tail when a flush() or aclose() gave up waiting, until it settles. */\n private stalledDrain: Promise<unknown> | null = null;\n private skipWarnedFor: Promise<unknown> | null = null;\n private closeOnce: Promise<void> | undefined;\n private drainChain: Promise<void> = Promise.resolve();\n private queuedDrain: Promise<void> | null = null;\n /** Whether the queued pass sends everything waiting, not only what is due. */\n private forceNext = false;\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n /** Set by a failed batch: only the timer, a flush, a close or, at\n * `flushIntervalMs` 0, a write after `retryFrom` tries again. */\n private waitForTimer = false;\n /** When a failed batch may be tried again. At `flushIntervalMs` 0 the\n * first write from then retries, as a Worker may drop the timer. */\n private retryFrom = 0;\n /** Nothing is sent before this `Date.now()`, from a 429's `Retry-After`. */\n private retryAt = 0;\n /** Set for the life of the sink by a 404 or 405 on the batch path. */\n private batchless = false;\n private exitHooks: { beforeExit: () => void; exit: () => void; off: () => void } | null = null;\n /** The `process` the exit hooks were last tried on, so a refusal is not retried per write. */\n private exitHooksTriedOn: object | undefined;\n /** The least time between two of this sink's loss reports. */\n private static reportIntervalMs = 60_000;\n /** Totals only grow, so their sum tells whether they changed. */\n private reportedSum = 0;\n private lastReportAt = -Infinity;\n private reportsStopped = false;\n /** The envelope of a report due to ride the next batch, and when it was set up.\n * `built` is the report once taken: a kept batch resends it unchanged (SPEC §11.4.7). */\n private pendingReport: (Pick<Event, \"tenant_id\" | \"vendor_id\" | \"consent_token\"> & { built?: Waiting }) | null = null;\n private reportSetAt = 0;\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.requestTimeoutMs = options.requestTimeoutMs ?? 1000;\n this.shutdownFlushTimeoutMs = timerMsOption(\n options.shutdownFlushTimeoutMs,\n \"shutdownFlushTimeoutMs\",\n SHUTDOWN_FLUSH_TIMEOUT_MS,\n );\n // A Worker may drop a timer its request left behind, and with it every later send.\n this.flushIntervalMs = timerMsOption(options.flushIntervalMs, \"flushIntervalMs\", onWorkers() ? 0 : FLUSH_INTERVAL_MS);\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 ?? globalFetch;\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 * would write a publishable key into the vendor's logs. 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 private get closed(): boolean {\n return this.closing.signal.aborted;\n }\n\n private get unsent(): number {\n return this.buffer.length + this.sendingEvents;\n }\n\n /** Encodes at once, not when the batch is cut, because the byte cap\n * decides when a batch goes. */\n async write(event: Event): Promise<void> {\n if (this.closed) throw new SinkClosedError(\"HttpSink is closed\");\n const json = this.encode(event);\n if (json === null) return;\n const bytes = utf8Bytes(json);\n if (BATCH_FRAME_BYTES + bytes > BATCH_MAX_BYTES) {\n this.refuse(1, { kind: \"over 1 MiB\", detail: `${bytes} bytes` }, false);\n return;\n }\n this.enqueue({ event, json, bytes, writtenAt: Date.now() });\n this.unsentWarned = false;\n const held = this.waitForTimer && !(this.flushIntervalMs === 0 && Date.now() >= this.retryFrom);\n if (!held && (this.flushIntervalMs === 0 || this.batchIsFull())) void this.scheduleDrain(false);\n else this.armTimer(Math.max(this.buffer[0]!.writtenAt + this.flushIntervalMs, held ? this.retryFrom : 0) - Date.now());\n this.ensureExitHooksRegistered();\n }\n\n flush(): Promise<void> {\n return this.flushWithin(Infinity);\n }\n\n /** A second call waits for the first (SPEC §11.2 rule 7). */\n aclose(): Promise<void> {\n return this.acloseWithin(Infinity);\n }\n\n private async flushWithin(ms: number): Promise<void> {\n if (this.closed) return;\n await this.drainWithinBudget(\"flush()\", Math.min(ms, this.shutdownFlushTimeoutMs));\n }\n\n private acloseWithin(ms: number): Promise<void> {\n this.closeOnce ??= this.close(Math.min(ms, this.shutdownFlushTimeoutMs));\n return this.closeOnce;\n }\n\n private async close(ms: number): Promise<void> {\n this.stopReports();\n await this.drainWithinBudget(\"aclose()\", ms);\n this.closing.abort();\n this.clearTimer();\n const unsent = this.unsent;\n if (unsent > 0) {\n PROCESS_DROPS.add(\"unsent_at_close\", unsent);\n warn(`baton: the sink closed with ${unsent} event(s) unsent.`);\n }\n this.warnUnloggedRefusals(\"the sink closed\");\n this.exitHooks?.off();\n this.exitHooks = null;\n }\n\n /** SPEC §11.2 rule 7: an explicit flush or close returns within `ms` and\n * never rejects. While an earlier wait's drain is still stuck, a flush\n * returns at once, without queuing a pass, and a close gives it `ms`. The\n * drain is not cancelled here, so after `flush()` it goes on sending;\n * `aclose()` stops it. */\n private async drainWithinBudget(what: \"flush()\" | \"aclose()\", ms: number): Promise<void> {\n if (this.stalledDrain) {\n if (what === \"aclose()\") {\n await raceDeadline(this.stalledDrain, ms);\n return;\n }\n if (this.skipWarnedFor !== this.stalledDrain) {\n this.skipWarnedFor = this.stalledDrain;\n warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.unsent} event(s) wait to be sent.`);\n }\n return;\n }\n const settled = this.scheduleDrain(true).catch(() => undefined);\n if ((await raceDeadline(settled, ms)) !== TIMED_OUT) return;\n // A wait shorter than the budget, the time a caller had left, does not\n // show that the drain is stuck.\n if (ms < this.shutdownFlushTimeoutMs) return;\n const stalled = this.drainChain.catch(() => undefined);\n this.stalledDrain = stalled;\n void stalled.then(() => {\n if (this.stalledDrain === stalled) this.stalledDrain = null;\n });\n if (what === \"flush()\") {\n warn(`baton: flush() took over ${ms} ms; it goes on in the background.`);\n }\n }\n\n private enqueue(waiting: Waiting): void {\n this.buffer.push(waiting);\n this.bufferedBytes += waiting.bytes;\n this.dropOverflow();\n }\n\n private dropOverflow(): void {\n while (this.buffer.length > this.bufferSize) {\n PROCESS_DROPS.add(\"buffer_full\");\n if (!this.overflowWarned) {\n warn(\n `Baton HTTP sink buffer full (${this.bufferSize}); oldest events dropped. Further overflows will be silent.`,\n );\n this.overflowWarned = true;\n }\n this.bufferedBytes -= this.buffer.shift()!.bytes;\n }\n }\n\n private batchIsFull(): boolean {\n return (\n this.buffer.length >= BATCH_MAX_EVENTS ||\n BATCH_FRAME_BYTES + this.bufferedBytes + this.buffer.length - 1 > BATCH_MAX_BYTES\n );\n }\n\n /** The timer must not keep the vendor's process alive: the exit hooks send\n * what is left. */\n private armTimer(delayMs: number): void {\n if (this.flushTimer !== null || this.closed) return;\n const timer = setTimeout(\n () => {\n this.flushTimer = null;\n this.waitForTimer = false;\n void this.scheduleDrain(false);\n },\n Math.min(Math.max(delayMs, 0), MAX_TIMER_MS),\n );\n (timer as { unref?: () => void }).unref?.();\n this.flushTimer = timer;\n }\n\n private clearTimer(): void {\n if (this.flushTimer === null) return;\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n\n /** Runs `drainLocked` after the pass under way, one pass at a time, so two\n * never send at once or race on the buffer. A pass not yet started is\n * shared by every caller: one per write would grow without bound while a\n * slow collector holds a pass. */\n private scheduleDrain(force: boolean): Promise<void> {\n this.forceNext ||= force;\n if (this.queuedDrain) return this.queuedDrain;\n const run = (): Promise<void> => {\n this.queuedDrain = null;\n const forced = this.forceNext;\n this.forceNext = false;\n return this.drainLocked(forced);\n };\n this.queuedDrain = this.drainChain.then(run, run);\n // One handler per pass, here, so a caller that drops the promise cannot\n // leave an unhandled rejection, and a write adds nothing to a queued pass.\n this.queuedDrain.catch(() => undefined);\n this.drainChain = this.queuedDrain;\n return this.queuedDrain;\n }\n\n /** Best-effort flush when the process is about to exit without an\n * explicit `aclose()`. SIGKILL, or SIGTERM with no installed handler, skip\n * both hooks: a vendor needing that guarantee must call `aclose()` from\n * their own handler. */\n private ensureExitHooksRegistered(): void {\n const target = typeof process !== \"undefined\" ? process : undefined;\n if (this.exitHooks || target === undefined || target === this.exitHooksTriedOn) return;\n this.exitHooksTriedOn = target;\n const beforeExit = (): void => {\n // Node re-fires `beforeExit` once the pass's work is done; one pass only.\n if (this.unsent === 0 || this.exitPassRan) {\n this.warnUnloggedRefusals(\"process exiting\");\n return;\n }\n this.drainChain = this.drainChain\n .then(\n () => this.exitPass(),\n () => this.exitPass(),\n )\n .catch(() => undefined);\n };\n // `process.exit()` skips `beforeExit`. At `exit` nothing can be sent and\n // `emitWarning` would never print, so the count is written straight out.\n const exit = (): void => {\n try {\n if (this.unsent > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());\n this.warnUnloggedRefusals(\"process exiting\", stderrLine);\n } catch {\n // A throw here would turn the vendor's clean exit into a crash.\n }\n };\n const offBeforeExit = onProcess(\"beforeExit\", beforeExit);\n const offExit = onProcess(\"exit\", exit);\n if (offBeforeExit === undefined || offExit === undefined) {\n // Both or neither: workersRuntime.test.ts, \"HttpSink leaves no exit hook behind\".\n offBeforeExit?.();\n offExit?.();\n return;\n }\n this.exitHooks = { beforeExit, exit, off: () => (offBeforeExit(), offExit()) };\n }\n\n /** One attempt per batch, no retry, within `shutdownFlushTimeoutMs` in\n * total (SPEC §11.2); what is left is reported, not sent. */\n private async exitPass(): Promise<void> {\n const deadline = Date.now() + this.shutdownFlushTimeoutMs;\n while (this.circuit.canRequest() && Date.now() >= this.retryAt && Date.now() < deadline) {\n const batch = this.takeBatch(false);\n if (batch === null) break;\n if (!this.putBack(await this.sendBatch(batch, 0, deadline), batch)) break;\n }\n this.exitPassRan = true;\n this.unsentWarned = true;\n if (this.unsent > 0) warn(this.unsentAtExit());\n this.warnUnloggedRefusals(\"process exiting\");\n }\n\n private unsentAtExit(): string {\n return `baton: process exiting with ${this.unsent} unsent event(s).`;\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 /** Counts `n` refused events and logs them, at most once a minute per\n * kind. A refused event is otherwise dropped silently, which looks the same\n * from the vendor's process as an accepted one. The collector's own message\n * is logged because it names the field at fault; it is capped and escaped\n * because it is a remote server's text landing in the vendor's log. */\n private refuse(n: number, { kind, detail }: Refusal, byCollector = true): void {\n if (n === 0) return;\n PROCESS_DROPS.add(\"refused\", n);\n const unlogged = this.refusalToLog(kind, n);\n if (unlogged === null) return;\n const what = n === 1 ? \"an event and it has\" : `${n} events and they have`;\n warn(\n `baton: ${byCollector ? \"collector REFUSED\" : \"REFUSED, unsent,\"} ${what} been dropped (${kind}): ` +\n `${escapeForLog(capCodePoints(detail, REFUSAL_BODY_MAX_LEN))} — the event is gone; nothing retries a refusal.` +\n (unlogged > 0 ? ` ${unlogged} more refused since the last such warning.` : \"\"),\n );\n }\n\n private warnUnloggedRefusals(when: string, emit: (message: string) => void = warn): void {\n let total = 0;\n for (const seen of this.refusals.values()) {\n total += seen.unlogged;\n seen.unlogged = 0;\n }\n if (total > 0) emit(`baton: ${when}; ${total} more event(s) refused since the last such warning.`);\n }\n\n /** How many refusals of `kind` went unlogged before these `n`, or `null`\n * when these go unlogged too. */\n private refusalToLog(kind: string, n: number): number | null {\n const now = performance.now();\n const seen = this.refusals.get(kind);\n if (seen !== undefined && now - seen.loggedAt < REFUSAL_LOG_MS) {\n seen.unlogged += n;\n return null;\n }\n this.refusals.set(kind, { loggedAt: now, unlogged: 0 });\n return seen?.unlogged ?? 0;\n }\n\n /** Enough of the body for `REFUSAL_BODY_MAX_LEN` code points; the rest is\n * cancelled unread, so a large error page does not hold the drain. */\n private static async readHead(response: Response): Promise<string> {\n const reader = (response.body as ReadableStream<Uint8Array> | null)?.getReader();\n if (reader === undefined) return \"\";\n const decoder = new TextDecoder();\n let text = \"\";\n try {\n // A code point is at most two UTF-16 units.\n while (text.length < REFUSAL_BODY_MAX_LEN * 2) {\n const { done, value } = await reader.read();\n if (done) return text + decoder.decode();\n text += decoder.decode(value, { stream: true });\n }\n return text;\n } finally {\n void reader.cancel().catch(() => {});\n }\n }\n\n /** Sends what is due, one batch at a time; `force` (a flush or close) sends\n * everything waiting. A report set up before the pass rides along; one set\n * up by this pass's own delivery waits for the next batch. */\n private async drainLocked(force: boolean): Promise<void> {\n let failed = false;\n let reportDue = this.pendingReport !== null;\n while (!this.closed) {\n if (!this.isDue(force, reportDue)) break;\n // SPEC §2.5: nothing is sent during a 429's wait, not even at close.\n if (!this.circuit.canRequest() || Date.now() < this.retryAt) {\n failed = true;\n break;\n }\n const batch = this.takeBatch(reportDue);\n if (batch === null) break;\n if (batch.some((w) => w.reportSum !== undefined)) reportDue = false;\n if (!this.putBack(await this.sendBatch(batch, this.maxRetries, Infinity), batch)) {\n failed = true;\n break;\n }\n }\n if (!failed && this.unsent === 0) this.exitPassRan = false;\n this.waitForTimer = failed;\n this.clearTimer();\n if (failed) {\n const wait = Math.max(this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest());\n this.retryFrom = Date.now() + wait;\n if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(wait);\n return;\n }\n const next = Math.min(this.buffer[0]?.writtenAt ?? Infinity, this.reportRidesHead() ? this.reportSetAt : Infinity);\n if (next !== Infinity) this.armTimer(next + this.flushIntervalMs - Date.now());\n }\n\n /** A due report makes the next batch due only when it can ride it; the\n * timer is armed the same way, so a pass that sends nothing never re-arms\n * it at a time already past. */\n private isDue(force: boolean, reportDue: boolean): boolean {\n const now = Date.now();\n if (reportDue && this.reportRidesHead() && (force || this.reportSetAt + this.flushIntervalMs <= now)) return true;\n return this.buffer.length > 0 && (force || this.batchIsFull() || this.buffer[0]!.writtenAt + this.flushIntervalMs <= now);\n }\n\n /** A pending report can go in the next batch: alone, or with the head event's tenant and vendor. */\n private reportRidesHead(): boolean {\n const head = this.buffer[0];\n return this.pendingReport !== null && (head === undefined || sameBatch(this.pendingReport, head.event));\n }\n\n /** Takes the head of the buffer that fits one batch: one tenant and vendor\n * (SPEC §2.5), at most 100 events and 1 MiB. A due report with the head\n * event's tenant and vendor takes one of those places, and goes alone when\n * the head event fits only without it. A report that cannot ride the head\n * waits for a batch it can ride. Without a batch endpoint the same events\n * go one per request. */\n private takeBatch(withReport: boolean): Waiting[] | null {\n const batch: Waiting[] = [];\n let bytes = BATCH_FRAME_BYTES - 1;\n let eventBytes = 0;\n const report = withReport && this.reportRidesHead() ? (this.pendingReport!.built ?? this.buildReport()) : null;\n // A due report keeps its place, or a run of full batches never carries it (SPEC §11.4.7).\n const maxEvents = BATCH_MAX_EVENTS - (report ? 1 : 0);\n const maxBytes = BATCH_MAX_BYTES - (report ? 1 + report.bytes : 0);\n const fits = (w: Waiting): boolean =>\n bytes + 1 + w.bytes <= maxBytes &&\n (batch.length === 0 || (batch.length < maxEvents && sameBatch(w.event, batch[0]!.event)));\n for (const waiting of this.buffer) {\n if (!fits(waiting)) break;\n batch.push(waiting);\n bytes += 1 + waiting.bytes;\n eventBytes += waiting.bytes;\n }\n this.buffer.splice(0, batch.length);\n this.bufferedBytes -= eventBytes;\n this.sendingEvents = batch.length;\n if (report !== null) batch.push(report);\n return batch.length > 0 ? batch : null;\n }\n\n /** Puts what a failure `kept` of the batch `taken` back at the head of the\n * buffer, and keeps its report unless `taken` had no events; `true` when\n * nothing was kept. */\n private putBack(kept: Waiting[], taken: Waiting[]): boolean {\n this.sendingEvents = 0;\n // close() has already counted these as unsent_at_close.\n if (this.closed) return kept.length === 0;\n const events: Waiting[] = [];\n for (const waiting of kept) {\n if (waiting.reportSum !== undefined) {\n // Read now, not at take time: a 404 during the send switches to one event per request.\n if (taken.every((w) => w.reportSum !== undefined) || this.batchless) this.pendingReport = null;\n continue;\n }\n events.push(waiting);\n this.bufferedBytes += waiting.bytes;\n }\n this.buffer.unshift(...events);\n this.dropOverflow();\n return kept.length === 0;\n }\n\n /** After a delivery, sets up a report of this process's loss totals (SPEC\n * §11.4.7) to ride the next batch. It stays outside the buffer, so it never\n * pushes an event out and is never counted as one. */\n private maybeReport({ tenant_id, vendor_id, consent_token }: Event): void {\n const now = performance.now();\n if (\n this.reportsStopped ||\n this.pendingReport !== null ||\n now - this.lastReportAt < HttpSink.reportIntervalMs\n ) {\n return;\n }\n if (sum(Object.values(PROCESS_DROPS.total())) === this.reportedSum) return;\n this.lastReportAt = now;\n this.reportSetAt = Date.now();\n this.pendingReport = { tenant_id, vendor_id, consent_token };\n }\n\n private stopReports(): void {\n this.reportsStopped = true;\n this.pendingReport = null;\n }\n\n private buildReport(): Waiting | null {\n if (this.pendingReport === null) return null;\n const { tenant_id, vendor_id, consent_token } = this.pendingReport;\n const totals = PROCESS_DROPS.total();\n try {\n const report = ClientReportEventSchema.parse({\n tenant_id,\n vendor_id,\n consent_token,\n session_id: PROCESS_DROPS.instanceId,\n sequence_number: nextClockSequence(),\n captured_at: new Date().toISOString(),\n payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals },\n });\n const json = JSON.stringify(report);\n this.pendingReport.built = { event: report, json, bytes: utf8Bytes(json), writtenAt: Date.now(), reportSum: sum(Object.values(totals)) };\n return this.pendingReport.built;\n } catch {\n // A lost report is never counted (SPEC §11.4.7).\n this.pendingReport = null;\n return null;\n }\n }\n\n /** Sends one batch, splitting it on 413, until every event in it is\n * delivered or refused. Returns what a failure kept, to go back in the\n * buffer. */\n private async sendBatch(batch: Waiting[], retries: number, deadline: number): Promise<Waiting[]> {\n if (this.batchless && batch.length > 1) return this.sendEachAlone(batch, retries, deadline);\n const batchless = this.batchless;\n const body = batchless ? batch[0]!.json : BATCH_OPEN + batch.map((w) => w.json).join(\",\") + BATCH_CLOSE;\n for (let attempt = 0; ; attempt++) {\n const timeLeft = deadline - Date.now();\n if (timeLeft <= 0) return batch;\n const answer = await this.post(body, batch.length, batchless, Math.min(this.requestTimeoutMs, timeLeft));\n if (answer.kind === \"no_batch_endpoint\") {\n this.batchless = true;\n warn(\"baton: the collector has no batch endpoint; sending one event per request.\");\n return this.sendEachAlone(batch, retries, deadline);\n }\n if (answer.kind === \"too_large\") {\n const half = Math.floor(batch.length / 2);\n const kept = await this.sendBatch(batch.slice(0, half), retries, deadline);\n if (kept.length > 0) return [...kept, ...batch.slice(half)];\n return this.sendBatch(batch.slice(half), retries, deadline);\n }\n if (answer.kind === \"transient\") {\n if (answer.retryAfterMs !== null) {\n this.retryAt = Date.now() + answer.retryAfterMs;\n return batch;\n }\n if (attempt < retries && !this.closed) {\n await this.sleepUnlessClosed(Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs));\n if (!this.closed) continue;\n }\n this.circuit.recordFailure();\n return batch;\n }\n this.circuit.recordSuccess();\n this.settle(batch, answer, batchless);\n return [];\n }\n }\n\n private async sendEachAlone(batch: Waiting[], retries: number, deadline: number): Promise<Waiting[]> {\n for (const [i, waiting] of batch.entries()) {\n if (this.closed) return batch.slice(i);\n const kept = await this.sendBatch([waiting], retries, deadline);\n if (kept.length > 0) return [...kept, ...batch.slice(i + 1)];\n }\n return [];\n }\n\n /** `alone` is one event per request (SPEC §2.5), so a whole refusal there is that event's own. */\n private settle(batch: Waiting[], answer: Extract<Answer, { kind: \"answered\" | \"refused\" }>, alone: boolean): void {\n // close() has already counted these as unsent_at_close.\n if (this.closed) return;\n let lastDelivered: Event | null = null;\n const refused = new Map<string, { first: Refusal; n: number }>();\n for (const waiting of batch) {\n if (waiting.reportSum === undefined) this.sendingEvents -= 1;\n const refusal = answer.kind === \"refused\" ? answer.refusal : answer.refused.get(waiting.event.event_id);\n if (waiting.reportSum !== undefined) {\n this.pendingReport = null;\n if (refusal === undefined) this.reportedSum = waiting.reportSum;\n // A collector that predates `client_report` refuses it this way. A whole\n // batch refused may be another event's fault, and another code is not about the type.\n else if (answer.kind === \"answered\" ? refusal.kind === \"payload_malformed\" : alone && (answer.status === 400 || answer.status === 422)) {\n this.reportsStopped = true;\n }\n } else if (refusal === undefined) {\n lastDelivered = waiting.event;\n } else {\n const seen = refused.get(refusal.kind);\n if (seen) seen.n += 1;\n else refused.set(refusal.kind, { first: refusal, n: 1 });\n }\n }\n for (const { first, n } of refused.values()) this.refuse(n, first);\n if (lastDelivered !== null) {\n PROCESS_DROPS.logRecovery();\n this.maybeReport(lastDelivered);\n }\n }\n\n /** `null`, with a warning, for an event `JSON.stringify` rejects. */\n private encode(event: Event): string | null {\n try {\n return JSON.stringify(event);\n } catch (err) {\n PROCESS_DROPS.add(\"encode_failed\");\n // Only the error's name: its message can quote the event's own text.\n warn(\n `baton: a ${event.event_type} event could not be encoded and has been dropped (${(err as Error)?.name ?? \"Error\"}) — the event is gone; the events after it are still sent.`,\n );\n return null;\n }\n }\n\n private sleepUnlessClosed(ms: number): Promise<void> {\n if (this.closed) return Promise.resolve();\n return new Promise((resolve) => {\n const done = (): void => {\n clearTimeout(timer);\n this.closing.signal.removeEventListener(\"abort\", done);\n resolve();\n };\n const timer = setTimeout(done, ms);\n this.closing.signal.addEventListener(\"abort\", done);\n });\n }\n\n /** Aborted by the timeout or by `aclose()`. Built by hand: `AbortSignal.any`\n * is missing before Node 20.3, and on some later versions it keeps every\n * combined signal alive as long as the long-lived `closing` signal. Any body\n * read is under the same signal, so a stalled body cannot hold the drain. */\n private async post(body: string, size: number, batchless: boolean, timeoutMs: number): Promise<Answer> {\n // A listener added to an aborted signal never fires, so the request would run on.\n if (this.closed) return { kind: \"transient\", retryAfterMs: null };\n const request = new AbortController();\n const abort = (): void => request.abort();\n const timer = setTimeout(abort, timeoutMs);\n this.closing.signal.addEventListener(\"abort\", abort);\n try {\n const response = await this.fetchImpl(batchless ? `${this.url}/v0/events` : `${this.url}/v0/events/batch`, {\n method: \"POST\",\n headers: this.authHeaders(),\n body,\n signal: request.signal,\n // SPEC §2.5: a redirect is a failure, not followed.\n redirect: \"manual\",\n });\n const { status } = response;\n const outcome = HttpSink.classifyStatus(status);\n if (outcome === \"success\") {\n if (batchless) {\n void response.body?.cancel().catch(() => undefined);\n return { kind: \"answered\", refused: new Map() };\n }\n return { kind: \"answered\", refused: HttpSink.refusedIn(await response.text()) };\n }\n const other = HttpSink.otherAnswer(response, size, batchless);\n if (other !== null) {\n // An unread body holds its connection until GC.\n void response.body?.cancel().catch(() => undefined);\n return other;\n }\n const detail = await HttpSink.readHead(response).catch(() => \"<unreadable>\");\n return { kind: \"refused\", status, refusal: { kind: `HTTP ${status}`, detail } };\n } catch {\n return { kind: \"transient\", retryAfterMs: null };\n } finally {\n clearTimeout(timer);\n this.closing.signal.removeEventListener(\"abort\", abort);\n }\n }\n\n /** Every answer but a 2xx and a refusal of the whole batch. */\n private static otherAnswer(response: Response, size: number, batchless: boolean): Answer | null {\n const { status } = response;\n if (status === 413 && size > 1) return { kind: \"too_large\" };\n if ((status === 404 || status === 405) && !batchless) return { kind: \"no_batch_endpoint\" };\n if (status === 429) return { kind: \"transient\", retryAfterMs: retryAfterMs(response.headers.get(\"Retry-After\")) };\n if (HttpSink.classifyStatus(status) === \"transient_failure\") return { kind: \"transient\", retryAfterMs: null };\n return null;\n }\n\n /** The refused results by `event_id` (SPEC §2.5). An event with no readable\n * result was delivered. */\n private static refusedIn(text: string): Map<string, Refusal> {\n const refused = new Map<string, Refusal>();\n let results: unknown;\n try {\n results = (JSON.parse(text) as { results?: unknown } | null)?.results;\n } catch {\n return refused;\n }\n if (!Array.isArray(results)) return refused;\n const str = (value: unknown): string => (typeof value === \"string\" ? value : \"\");\n for (const result of results as { event_id?: unknown; status?: unknown; error?: { code?: unknown; message?: unknown } }[]) {\n if (result?.status !== \"refused\" || typeof result.event_id !== \"string\") continue;\n refused.set(result.event_id, { kind: str(result.error?.code) || \"no code\", detail: str(result.error?.message) });\n }\n return refused;\n }\n}\n","/** String helpers shared by the capture and log paths. */\n\n// Unicode `White_Space`, exactly (SPEC §11.4's blank rule). Not `.trim()`, which\n// also removes U+FEFF and keeps U+0085, nor `str.strip()`, which also removes U+001C-U+001F.\nconst WHITE_SPACE = /^\\p{White_Space}$/u;\nconst ALL_WHITE_SPACE = /^\\p{White_Space}*$/u;\n\n/** `value` without leading and trailing characters matching `space`, a\n * one-character pattern. A scan, not `/^x+|x+$/`, which is quadratic on a long\n * run of spaces inside the string. */\nexport function stripEdges(value: string, space: RegExp): string {\n let start = 0;\n let end = value.length;\n while (start < end && space.test(value[start]!)) start++;\n while (end > start && space.test(value[end - 1]!)) end--;\n return value.slice(start, end);\n}\n\nexport function stripWhiteSpace(value: string): string {\n return stripEdges(value, WHITE_SPACE);\n}\n\nexport function isBlank(value: string): boolean {\n return ALL_WHITE_SPACE.test(value);\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/** 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/** Backslashes and control, format and separator characters as `\\u{hex}`, so\n * text from outside cannot break or recolour a log line, or pass for an escape. */\nexport function escapeForLog(value: string): string {\n return value.replace(/[\\\\\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]/gu, (c) => `\\\\u{${c.codePointAt(0)!.toString(16)}}`);\n}\n","export const TIMED_OUT = Symbol(\"timedOut\");\n\n/** Larger values overflow Node's timer, which then fires at once. */\nexport const MAX_TIMER_MS = 2 ** 31 - 1;\n\n/** `work`'s result, or `TIMED_OUT` if it has not settled within `ms`. */\nexport async function raceDeadline<T>(work: PromiseLike<T>, ms: number): Promise<T | typeof TIMED_OUT> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), Math.min(ms, MAX_TIMER_MS));\n // A pending deadline must not hold a finished process open. Outside Node a\n // timer is a number with no `unref`: `principalResolution.test.ts`,\n // \"where a timer is a plain number\".\n (timer as { unref?: () => void }).unref?.();\n });\n try {\n return await Promise.race([work, deadline]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** SPEC §11.2 rule 7's budget for a flush at exit, or an explicit flush or close. */\nexport const SHUTDOWN_FLUSH_TIMEOUT_MS = 3000;\n","import { uuid7 } from \"./uuid7.js\";\nimport { warn } from \"./warn.js\";\n\n/** Why an event was not delivered. Wire values (SPEC §11.2 rule 8), so they\n * change only with SPEC. */\nexport const DROP_REASONS = [\n \"buffer_full\",\n \"refused\",\n \"encode_failed\",\n \"write_failed\",\n \"after_close\",\n \"unsent_at_close\",\n] as const;\nexport type DropReason = (typeof DROP_REASONS)[number];\n\n/** The least time between two \"delivering again\" warnings, so steady loss\n * beside steady delivery, such as an overflowing buffer, is not one per event. */\nconst RECOVERY_LOG_MS = 60_000;\n\n/** Events this process did not deliver, by reason: every event is either\n * delivered or counted here, except at close, where the count is best effort\n * (SPEC §11.2 rule 8). One per process, like the sequence clock. */\nclass DropCounts {\n // Made on first use: a Worker refuses random values while its modules load.\n #instanceId: string | undefined;\n readonly #total = new Map<DropReason, number>();\n readonly #sinceDelivery = new Map<DropReason, number>();\n #lastRecoveryLog = -RECOVERY_LOG_MS;\n\n add(reason: DropReason, n = 1): void {\n if (n <= 0) return;\n this.#total.set(reason, (this.#total.get(reason) ?? 0) + n);\n this.#sinceDelivery.set(reason, (this.#sinceDelivery.get(reason) ?? 0) + n);\n }\n\n total(): Partial<Record<DropReason, number>> {\n return Object.fromEntries(this.#total);\n }\n\n /** Called on each delivery: names what was lost before it, the other half of\n * a drop's own warning, which says only that loss started. */\n logRecovery(): void {\n if (this.#sinceDelivery.size === 0) return;\n const now = performance.now();\n if (now - this.#lastRecoveryLog < RECOVERY_LOG_MS) return;\n const lost = [...this.#sinceDelivery].sort(([a], [b]) => a.localeCompare(b));\n this.#sinceDelivery.clear();\n this.#lastRecoveryLog = now;\n const total = lost.reduce((sum, [, n]) => sum + n, 0);\n warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(\", \")}.`);\n }\n\n /** Names this process in its loss reports (SPEC §11.4.7). */\n get instanceId(): string {\n return (this.#instanceId ??= uuid7());\n }\n\n /** For tests: the counts are one per process. */\n clear(): void {\n this.#instanceId = undefined;\n this.#total.clear();\n this.#sinceDelivery.clear();\n this.#lastRecoveryLog = -RECOVERY_LOG_MS;\n }\n}\n\nexport const PROCESS_DROPS = new DropCounts();\n","let lastSequence = 0;\n\nexport function nowMicros(): number {\n return Math.floor((performance.timeOrigin + performance.now()) * 1000);\n}\n\n/** Sequence numbers from the clock, in microseconds (SPEC §5.6 rule 3). One\n * counter for the process: strictly increasing across all sessions is\n * strictly increasing within each, and nothing grows per session. */\nexport function nextClockSequence(): number {\n lastSequence = Math.max(lastSequence + 1, nowMicros());\n return lastSequence;\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 under `reportMode: \"on\"` (SPEC §5.1.1), injects\n * a `user_goal` intent param on every wrapped tool's schema (SPEC §11.4.1\n * `call_intent`/`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 * On a low-level `Server`, which has no tool registry, the same is done at its\n * `tools/list` and `tools/call` handlers: see `installLowLevelToolSeams`.\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 * as asyncHooks from \"node:async_hooks\";\nimport { uuid7 } from \"../../uuid7.js\";\nimport {\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 ToolListEndEventSchema,\n ToolListErrorEventSchema,\n ToolListStartEventSchema,\n} from \"../../events.js\";\nimport { boundedSinkCall, offTheCall, StdoutSink, type Sink } from \"../../sinks.js\";\nimport {\n type AnnotationTool,\n buildAnnotationTool,\n annotationInputJsonSchema,\n callAnnotationTool,\n registerAnnotationTool,\n TOOL_NAME_PARAM_NAME,\n} from \"./annotation.js\";\nimport { Scrubber } from \"../../scrub.js\";\nimport { scrubOrNull } from \"./safeScrub.js\";\nimport { roundMetaCoordinates } from \"../../metaCoordinates.js\";\nimport {\n resolveInstallConfig,\n resolveTenantId,\n withServerDisplayName,\n type BatonConfig,\n type ResolvedBatonConfig,\n} from \"./config.js\";\nimport { captureDisabled, DisabledSink, logDisabled, logUnconfigured } from \"../../optout.js\";\nimport { capCodePoints, isBlank } from \"../../_text.js\";\nimport { printable, stderrLine, warn } from \"../../warn.js\";\nimport { isRecord } from \"../../_object.js\";\nimport { emit } from \"./emit.js\";\nimport {\n ERROR_BODY_MAX_CODE_POINTS,\n endResultFields,\n errorText,\n errorTypeOf,\n type FailureKind,\n scrubbedErrorBody,\n messageOf,\n type InputValidation,\n OUTPUT_SCHEMA_MISMATCH,\n requestSideFailureFields,\n requestSideFailureKind,\n type ResultCaptureMode,\n type ToolEntryFacts,\n resultDerivedFields,\n returnedErrorFields,\n isErrorResult,\n TOOL_ERROR_TYPE,\n WITHHELD,\n} from \"./errorResult.js\";\nimport { isInputRequired, resumesPausedCall } from \"./inputRequired.js\";\nimport { BatonHandle } from \"./handle.js\";\nimport {\n deriveAnnotationToolName,\n resolveAnnotationToolName,\n usableServerName,\n} from \"./annotationName.js\";\nimport {\n buildServerInstructions,\n declaresParam,\n INSTRUCTIONS_SUBAGENT_CLAUSE,\n INTENT_INSTRUCTIONS,\n INTENT_SOURCE_PARAM,\n instructionsSuffixServed,\n mayDeclareParam,\n RETIRED_PARAM_NAMES,\n requiredParamNames,\n USER_GOAL_PARAM_NAME,\n withVendorInstructions,\n} from \"./llmText.js\";\nimport {\n extraMeta,\n isThenable,\n observeTransport,\n type Extra,\n} from \"./mcpTypes.js\";\nimport { observeClient } from \"./clientObserved.js\";\nimport { resolveSessionId, type ResolvedSession } from \"./sessionResolution.js\";\nimport {\n type ResolvePrincipalHook,\n type ResolvedCaller,\n callerEnvelope,\n resolveCaller,\n} from \"./principalResolution.js\";\nimport type { CaptureSettings } from \"./captureSettings.js\";\nimport { PerCallerSurface } from \"./perCaller.js\";\nimport { ServerCounter, SessionCounter } from \"./sessionCounter.js\";\nimport {\n advertiseIntentParamsRequired,\n withToolInputSchema,\n injectGoalParams,\n injectGoalParamsV2,\n toolInputJsonSchema,\n type IntentParamDispositions,\n type IntentParamMode,\n DEFAULT_INTENT_PARAM_MODE,\n takesUserGoalJson,\n withUserGoalJson,\n standardInputJsonSchema,\n EMPTY_OBJECT_JSON_SCHEMA,\n} from \"./schemaCompat.js\";\nimport { PROCESS_DROPS } from \"../../drops.js\";\nimport { assembleSurface, buildServerMeta, buildSeamAugmentations, SentSurfaces, 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: SupportedServer;\n scrubber: (value: unknown) => unknown;\n annotationToolName: string;\n intentParamMode: IntentParamMode;\n /** The config's `resultCaptureMode` (SPEC §11.4), validated once at the\n * config door. A call runs under the one `openCall` returns, which Console\n * settings can change. */\n configResultCaptureMode: 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 /** Tool `name` declares its own `user_goal`: take the subagent sentence\n * out of the instructions, or it sends the turn number into the vendor's\n * argument. */\n dropSubagentClause: (name: string) => void;\n servedInstructions: () => unknown;\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 /** Under `settings: \"console\"`; shared by every server one `createBaton` wraps. */\n captureSettings: CaptureSettings | undefined;\n perCaller: PerCallerSurface | undefined;\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 `install`,\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`, `parkSuccess` and\n * `parkPause` 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 /** Baton's intent params, taken off the request by the seam before the\n * host's input check or any vendor code sees them (SPEC §5.1.2). */\n stripped: StrippedParams;\n /** The tool they were taken from: only its wrapper may take them, so a tool\n * Baton did not wrap cannot pass them to one it runs in-process. */\n strippedFor: string | null;\n /** Set by the probe on `validateToolInput`; stays `\"unseen\"` when the call\n * was refused before the SDK validated it. */\n validation: InputValidation;\n}\n\nconst INTENT_PARAM_NAMES = [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES] as const;\ntype MutableStrippedParams = Partial<Record<(typeof INTENT_PARAM_NAMES)[number], string | null>>;\ntype StrippedParams = Readonly<MutableStrippedParams>;\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 asyncHooks.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 dirty = false;\n\n constructor(\n private readonly serverMeta: ReturnType<typeof buildServerMeta>,\n readonly sentSurfaces: SentSurfaces,\n ) {}\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 const before = this.rawTools.get(name);\n const tool = { name, description: description ?? null, inputSchema: inputSchemaJson };\n // A low-level Server's tools are noted on every list it serves.\n if (before !== undefined && before.tool.description === tool.description) {\n const same = before.tool.inputSchema === inputSchemaJson || JSON.stringify(before.tool.inputSchema) === JSON.stringify(inputSchemaJson);\n if (same) return;\n }\n this.rawTools.set(name, { disabled: before?.disabled ?? false, tool });\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 return scrubbedErrorBody(ctx.scrubber, text);\n}\n\n/** The envelope members every event shares, resolved off one MCP request —\n * everything except `principal` and `organization`, which are deliberately not in here.\n *\n * Split out of `openCall` so the lifecycle seams (SPEC §11.4.4, §11.4.5) can\n * build an envelope without the parts that are specific to a tool call: the\n * intent-param strip and the `call_id`. `principal` and `organization` are the caller's to\n * resolve, because the hook's input differs between a call and a listing.\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.\n *\n * Not for key order: Zod v4 emits output keys in SHAPE order, so\n * `envelopeShape` fixes the wire order however a caller spells its literal. */\nasync function resolveEnvelopeParts(\n ctx: WrapContext,\n extra: Extra,\n): Promise<ResolvedSession & { scrubbedMeta: unknown }> {\n // Coordinates are coarsened before the vendor's scrubber, so a vendor\n // scrubber still gets the rule. `_meta` only; params and results keep full\n // precision. The annotation tool does the same.\n const meta = extraMeta(extra);\n const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, \"_meta\");\n const session = await resolveSessionId(ctx.fallbackSessionId, extra);\n return { ...session, 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 * `tool_call_start`, unless the request resumes a paused call.\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.\n *\n * Returns what the TERMINAL event needs and nothing more: the envelope, with\n * this call's `call_id` in it, 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 /** What the seam took off the request. Passed in, not read from\n * `callSlots`: the request-side path runs outside its own slot. */\n stripped: StrippedParams,\n unlisted: Unlisted = \"warn\",\n): Promise<{ common: Record<string, unknown>; session: ResolvedSession; resultCaptureMode: ResultCaptureMode }> {\n // Snapshot BEFORE tool_call_start, from inside openCall so every caller inherits the order.\n await maybeEmitSurfaceSnapshot(ctx);\n const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);\n\n // The seam has usually stripped them already. Strip IN PLACE for a server it\n // could not reach: `params` is the SAME object forwarded to the vendor\n // handler, and the captured `params` must equal the vendor-visible arguments.\n const dispositions = ctx.paramRegistry.get(toolName);\n const rawIntent =\n stripped[USER_GOAL_PARAM_NAME] ??\n extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, unlisted);\n const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);\n const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map((name) =>\n dispositions === undefined || dispositions[name] === \"native\" || unlisted === \"leave\" || unlisted === \"goalOnly\"\n ? null\n : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name),\n );\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 client = observeClient(extra, ctx);\n const caller = await resolveCaller(\n ctx.resolvePrincipal,\n { extra, toolName, arguments: params },\n ctx.captureSettings,\n client,\n );\n const resultCaptureMode = caller.settings?.resultCaptureMode ?? ctx.configResultCaptureMode;\n\n const common = {\n tenant_id: ctx.tenantId,\n vendor_id: ctx.vendorId,\n session_id: session.sessionId,\n consent_token: ctx.consentToken,\n // Every `...common` site is an event of this call, so `call_id` rides in\n // it. `surface_snapshot` is deliberately not among them: it describes the\n // SERVER and is captured outside any call, so it has no caller, transport\n // or client to name.\n ...callerEnvelope(caller),\n transport_observed: observeTransport(extra),\n session_id_origin: session.origin,\n client_observed: client,\n runtime_meta: scrubbedMeta,\n call_id: uuid7(),\n };\n\n if (resumesPausedCall(extra)) return { common, session, resultCaptureMode };\n await emit(ctx.sink, () =>\n ToolCallStartEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.nextFor(session),\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, session, resultCaptureMode };\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(\n nameRef: { current: string },\n original: AnyHandler,\n ctx: WrapContext,\n unlisted: Unlisted = \"warn\",\n): 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 // Handed over once: a tool this handler calls in-process shares the slot.\n const stripped = slot?.strippedFor === toolName ? slot.stripped : {};\n if (slot) slot.strippedFor = null;\n const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped, unlisted);\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) | null,\n replacement: ((outcome: OuterOutcome) => Event) | null,\n ): Promise<void> => {\n if (!slot) {\n // No outer seam: a direct executor call, a low-level Server, or a\n // server whose internals 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 if (build !== null) 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 paused round parks a terminal\n // only a failure sends, and the next round supersedes it.\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 if (replacement !== null && outcome.failed) await emit(ctx.sink, () => replacement(outcome));\n else if (build !== null) await emit(ctx.sink, build);\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 /** Park a paused round: it sends nothing unless the SDK then fails the call. */\n const parkPause = (replacement: (outcome: OuterOutcome) => Event): Promise<void> =>\n terminate(null, 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 sequence_number: ctx.counter.nextFor(session),\n captured_at: new Date().toISOString(),\n payload: {\n tool_name: toolName,\n error_type: errorTypeOf(err),\n // SPEC §11.4.3(1): the MCP SDK has no tool-error class to mark a\n // raised message public, so under \"off\" every one is withheld.\n ...resultDerivedFields(\n resultCaptureMode,\n () => messageOf(err),\n null,\n (text) => errorBody(ctx, text),\n ctx.scrubber,\n ),\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 handler returned and the outer seam then saw the call fail: on the\n // success lane what failed is the producer's own conversion of the output\n // (SPEC §11.4.3's `output_schema_mismatch`), and after a pause it is the\n // SDK's handling of the input request. The stream would otherwise file the\n // caller's failure as a success, or not at all.\n const failedAbove = (outcome: OuterOutcome, failureKind?: string): Event =>\n ToolCallErrorEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.nextFor(session),\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 pause the SDK rejects on 2026-07-28 raises, so\n // both lanes are reachable.\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 // Omitted, not null, when undetermined: SPEC §11.4.3 says MUST OMIT.\n ...(failureKind === undefined ? {} : { failure_kind: failureKind }),\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 an\n // `output_schema_mismatch` under `\"off\"`, and is the measurement\n // that justified putting 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 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 if (isInputRequired(result)) {\n await parkPause(failedAbove);\n return result;\n }\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 sequence_number: ctx.counter.nextFor(session),\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 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 sequence_number: ctx.counter.nextFor(session),\n captured_at: new Date().toISOString(),\n payload: {\n tool_name: toolName,\n duration_ms: durationMs,\n ...endResultFields(resultCaptureMode, result, ctx.scrubber),\n },\n }),\n (outcome) => failedAbove(outcome, OUTPUT_SCHEMA_MISMATCH),\n );\n\n return result;\n };\n}\n\n/** What a call to a tool Baton did not add `user_goal` to does with it: strip\n * it with the cold-registry warning, strip it quietly (the caller has warned,\n * or the tool does not exist), or, on a low-level Server, strip only\n * `user_goal` and leave the retired names, or leave them all. */\ntype Unlisted = \"warn\" | \"quiet\" | \"goalOnly\" | \"leave\";\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 * A tool with no entry is handled as `unlisted` says. */\nfunction extractGoalParam(\n args: Record<string, unknown>,\n paramName: string,\n toolName: string,\n dispositions: IntentParamDispositions | undefined,\n unlisted: Unlisted,\n): string | null {\n if (!(paramName in args)) return null;\n const disposition = dispositions ? dispositions[paramName] : undefined;\n if (disposition === \"native\") return null;\n if (disposition === undefined && unlisted === \"leave\") return null;\n if (disposition === undefined && unlisted === \"warn\") {\n stderrLine(\n `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)`,\n );\n }\n return popText(args, paramName);\n}\n\nfunction popText(args: Record<string, unknown>, paramName: string): string | null {\n if (!(paramName in args)) return null;\n const raw = args[paramName];\n delete args[paramName];\n return typeof raw === \"string\" && !isBlank(raw) ? raw : null;\n}\n\n/** Take Baton's intent params off a `tools/call` request, before the host's\n * input check and before a tool Baton did not wrap (a 1.x task tool) sees them.\n * Only from a tool Baton injected into: on any other, a value is the vendor's. */\nfunction stripIntentParams(\n params: { name?: unknown; arguments?: unknown } | undefined,\n ctx: WrapContext,\n): StrippedParams {\n const toolName = params?.name;\n const args = params?.arguments;\n if (typeof toolName !== \"string\") return {};\n if (toolName === ctx.annotationToolName) return {};\n if (typeof args !== \"object\" || args === null || Array.isArray(args)) return {};\n const dispositions = ctx.paramRegistry.get(toolName);\n const stripped: MutableStrippedParams = {};\n for (const name of INTENT_PARAM_NAMES) {\n if (dispositions === undefined || dispositions[name] === \"native\" || !(name in args)) continue;\n stripped[name] = popText(args as Record<string, unknown>, name);\n }\n return stripped;\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 is not\n * among the last `SENT_SURFACES_CAP` that `sentSurfaces` has seen. `dirty`\n * is cleared FIRST so a hashing/serialization error (deterministic — would\n * just re-throw identically every call) costs one attempt per surface\n * change, not a retry storm. The write only queues, so a snapshot counts as\n * sent once queued; a sink that later fails to write it counts it `write_failed`. */\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 stderrLine(`baton: surface snapshot capture failed: ${String(err)}`);\n return;\n }\n const sent = ctx.surfaceState.sentSurfaces;\n if (sent.wasSent(digest)) return;\n // Reserved before the write, so two servers sharing `sentSurfaces` cannot both\n // send it: `createBaton.test.ts`, \"when the first requests arrive together\".\n sent.mark(digest);\n const seam = buildSeamAugmentations({\n injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],\n intentParamNames: [USER_GOAL_PARAM_NAME],\n intentParamMode: ctx.intentParamMode,\n requiredParamNames: requiredParamNames(ctx.intentParamMode),\n instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions()),\n });\n await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });\n}\n\nfunction declaredIntentParams(vendorSchema: unknown): IntentParamDispositions {\n const declared: IntentParamDispositions = {};\n for (const name of INTENT_PARAM_NAMES) {\n if (declaresParam(vendorSchema, name)) declared[name] = \"native\";\n }\n return declared;\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` as the vendor's own\n * field (`\"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 const vendorSchema = ctx.vendorToolJsonSchema(name, mutable.inputSchema);\n ctx.surfaceState.noteTool(name, vendorSchema, mutable.description);\n // From the JSON schema: a v2 schema that is not zod gets no injection, but\n // its `user_goal` still counts.\n if (declaresParam(vendorSchema, USER_GOAL_PARAM_NAME)) ctx.dropSubagentClause(name);\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 // A schema that could not be extended still has its own names to keep.\n const declared = declaredIntentParams(vendorSchema);\n if (Object.keys(declared).length > 0) ctx.paramRegistry.set(name, declared);\n else 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 `install`.\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 // Two seams may wrap one method. Without the inner seam's tag on the\n // outer handler, the inner seam would wrap again on the next\n // `setRequestHandler`: \"each seam applies once\" in `toolList.test.ts`.\n for (const tag of Object.getOwnPropertySymbols(handler)) seamed[tag] = handler[tag];\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 a name be advertised as\n * required without the validator enforcing it (see\n * `schemaCompat.buildIntentFields` for why zod cannot). Two sets of names:\n * `requiredParamNames` on each tool Baton injected them into, under\n * `intentParamMode: \"required\"`, and `tool_name` on the annotate tool, in\n * every mode (SPEC §5.1.1).\n *\n * On an McpServer the annotate tool lists Baton's own rendering of its\n * schema, as a low-level Server's list already does: the SDK renders it with\n * the vendor's zod, which may differ (reportToolSchema.test.ts).\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, listsOwnReportTool: boolean): void {\n const names = [...requiredParamNames(ctx.intentParamMode), TOOL_NAME_PARAM_NAME];\n const isInjected = (toolName: string, paramName: string): boolean =>\n toolName === ctx.annotationToolName\n ? paramName === TOOL_NAME_PARAM_NAME\n : ctx.paramRegistry.get(toolName)?.[paramName] === \"injected\";\n const advertise = (result: unknown): unknown => {\n try {\n const served = listsOwnReportTool || ctx.annotationToolName === \"\"\n ? result\n : withToolInputSchema(result, ctx.annotationToolName, annotationInputJsonSchema(lowLevelMajor(lowLevel)));\n return advertiseIntentParamsRequired(served, names, isInjected);\n } catch (err) {\n stderrLine(\n `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}`,\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\ntype LowLevelInternals = {\n _instructions?: string;\n _serverInfo?: { name?: unknown };\n} & RequestHandlerInternals;\n\nconst LOW_LEVEL_LIST_SEAM = Symbol(\"batonLowLevelListSeam\");\nconst LOW_LEVEL_CALL_SEAM = Symbol(\"batonLowLevelCallSeam\");\nconst LOW_LEVEL_HANDSHAKE_SEAM = Symbol(\"batonLowLevelHandshakeSeam\");\n\n/** What one Baton knows of a low-level `Server`'s tools, shared by every\n * server it wraps, so a server made per request knows the tools another one\n * served. `given` is the `tools` option until it is read, once, into `givenTools`. */\ninterface KnownTools {\n given: BatonConfig[\"tools\"];\n givenTools: ToolInfo[];\n served: Map<string, ToolInfo>;\n /** Tools some version of which may declare `user_goal`. A name is never removed. */\n keepsGoal: Set<string>;\n /** Tools whose calls keep `user_goal` until a version of them is read. */\n unread: Set<string>;\n}\n\ntype ToolInfo = { name: string; description: unknown; inputSchema: unknown };\ntype ReadOptions = { surface: boolean };\n\n/**\n * `tools/list` and `tools/call` on a low-level `Server`, which has no tool\n * registry: what Baton knows of a tool comes from the `tools` option and from\n * the lists this Baton's servers serve. A server's surface and report-name\n * check use only the `tools` option and its own lists; what other servers\n * served only decides which calls lose `user_goal`.\n *\n * ⚠ Every call is traced. `user_goal` comes off every call, since a client\n * sends it only because Baton listed it, except to a tool that may take its\n * own (`known.keepsGoal`) or that Baton could not read (`known.unread`):\n * `lowLevelServer.test.ts`, \"a tool Baton does not know\", \"leaves a call's\n * user_goal when the root combiner names user_goal\" and \"a given tool it\n * cannot read\".\n */\nfunction installLowLevelToolSeams(\n lowLevel: LowLevelInternals,\n ctx: WrapContext,\n annotationTool: AnnotationTool | undefined,\n known: KnownTools,\n warnOnce: (key: string, message: string) => void,\n /** The vendor lists a tool with the report tool's name: drop the pointer to it. */\n reportToolTaken: () => void,\n): void {\n let reportTool = annotationTool;\n const listedReportTool = reportTool && {\n name: reportTool.name,\n description: reportTool.description,\n inputSchema: annotationInputJsonSchema(lowLevelMajor(lowLevel)),\n };\n const skipTool = (name: string, err: unknown): void => {\n known.unread.add(name);\n warnOnce(\n `tool-unread:${name}`,\n `baton: could not read tool ${JSON.stringify(name)}; its calls keep user_goal until Baton can read it: ${printable(err)}`,\n );\n };\n const skipNote = (name: string, err: unknown): void => {\n if (known.unread.has(name)) return;\n warnOnce(`tool-unnoted:${name}`, `baton: could not note tool ${JSON.stringify(name)}; Baton adds no user_goal to it: ${printable(err)}`);\n };\n // Below the root only where Baton cannot add its own `user_goal` at the root.\n const keepGoalIfDeclared = (tools: ToolInfo[]): void => {\n for (const { name, inputSchema } of tools) {\n try {\n const checked = known.served.get(name)?.inputSchema === inputSchema && !known.unread.has(name);\n if (!known.keepsGoal.has(name) && !checked) {\n const declares =\n isRecord(inputSchema) && takesUserGoalJson(inputSchema) ? declaresParam : mayDeclareParam;\n if (declares(inputSchema, USER_GOAL_PARAM_NAME)) known.keepsGoal.add(name);\n }\n known.unread.delete(name);\n } catch (err) {\n skipTool(name, err);\n }\n }\n };\n\n const read = (tools: ToolInfo[], { surface }: ReadOptions): void => {\n if (surface && reportTool !== undefined && tools.some((tool) => tool.name === reportTool?.name)) {\n warnOnce(\n \"report-tool-name-taken\",\n `baton: the server lists its own tool ${JSON.stringify(reportTool.name)}, so Baton's report ` +\n \"tool is not added; set annotationToolName to another name\",\n );\n reportTool = undefined;\n ctx.annotationToolName = \"\";\n reportToolTaken();\n }\n readToolList(tools, ctx, surface, skipNote);\n };\n\n // Per caller lists may differ: keep every tool, and a version that declares\n // its own `user_goal` over one that does not, so a server reading this map\n // registers it as the tool's own and not as one Baton added.\n const learn = (tools: ToolInfo[]): void => {\n keepGoalIfDeclared(tools);\n for (const tool of tools) {\n const held = known.served.get(tool.name);\n const ownGoal = (info: ToolInfo | undefined) => declaresParam(info?.inputSchema, USER_GOAL_PARAM_NAME);\n if (held === undefined || !ownGoal(held) || ownGoal(tool)) known.served.set(tool.name, tool);\n }\n };\n\n let caughtUp = false;\n const catchUp = (): void => {\n if (caughtUp) return;\n caughtUp = true;\n if (known.given !== undefined) {\n const given = known.given;\n known.given = undefined;\n try {\n const tools: unknown = typeof given === \"function\" ? given() : given;\n if (!Array.isArray(tools)) throw new Error(\"it is not an array of tools\");\n known.givenTools = toolInfos(tools, skipTool);\n keepGoalIfDeclared(known.givenTools);\n } catch (err) {\n warnOnce(\n \"tools-unread\",\n `baton: could not read the tools option; Baton learns the tools from tools/list: ${printable(err)}`,\n );\n }\n }\n read(known.givenTools, { surface: true });\n read([...known.served.values()], { surface: false });\n };\n\n installRequestSeam(lowLevel, TOOLS_LIST_METHOD, LOW_LEVEL_LIST_SEAM, (handler) => async (...args) => {\n catchUp();\n const result = await handler(...args);\n try {\n const listed = listedTools(result);\n if (listed === null) return result;\n const tools = toolInfos(listed, skipTool);\n learn(tools);\n read(tools, { surface: true });\n // On the first page, which every client reads.\n const firstPage = (args[0] as { params?: { cursor?: unknown } } | undefined)?.params?.cursor === undefined;\n return servedToolList(result as Record<string, unknown>, listed, ctx, firstPage && reportTool ? listedReportTool : undefined);\n } catch (err) {\n stderrLine(`baton: tools/list capture failed; serving the vendor's own result: ${printable(err)}`);\n return result;\n }\n });\n\n // Before `initialize`, so a known tool's own `user_goal` takes the subagent\n // sentence out of the instructions it answers with.\n const readFirst =\n (handler: AnyHandler): AnyHandler =>\n (...args) => {\n catchUp();\n return handler(...args);\n };\n installRequestSeam(lowLevel, \"initialize\", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);\n installRequestSeam(lowLevel, \"server/discover\", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);\n\n installRequestSeam(lowLevel, TOOLS_CALL_METHOD, LOW_LEVEL_CALL_SEAM, (handler) => async (...args) => {\n catchUp();\n ctx.perCaller?.followSettings();\n const request = args[0] as { params?: { name?: unknown; arguments?: unknown; task?: unknown } } | undefined;\n const name = request?.params?.name;\n if (typeof name !== \"string\") return handler(...args);\n if (name === reportTool?.name) return callAnnotationTool(reportTool, request?.params?.arguments, args[1] as Extra);\n const injected = ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === \"injected\";\n const unlisted: Unlisted = injected ? \"warn\" : known.keepsGoal.has(name) || known.unread.has(name) ? \"leave\" : \"goalOnly\";\n // The request's own object: `openCall` takes Baton's params off it in\n // place, before the SDK's parse hands the vendor a copy.\n const params = request?.params?.arguments;\n const toolArgs = isRecord(params) ? params : {};\n if (\n unlisted === \"goalOnly\" &&\n USER_GOAL_PARAM_NAME in toolArgs &&\n !known.served.has(name) &&\n !known.givenTools.some((tool) => tool.name === name)\n ) {\n warnOnce(\n \"user-goal-unlisted\",\n `baton: ${JSON.stringify(name)} is not in any tool list this process has read, so Baton took ` +\n \"user_goal off it without knowing whether the tool declares its own; pass your tools as the tools option\",\n );\n }\n // A task-based call answers with the task, not the tool's result, so it\n // is not captured, as on an McpServer.\n if (request?.params?.task !== undefined) {\n if (injected) stripIntentParams(request.params, ctx);\n else extractGoalParam(toolArgs, USER_GOAL_PARAM_NAME, name, ctx.paramRegistry.get(name), unlisted);\n return handler(...args);\n }\n return batonWrap({ current: name }, () => handler(...args), ctx, unlisted)(toolArgs, args[1]);\n });\n}\n\n/** v2's `Protocol` has the result-validation hook; 1.x's has not. */\nfunction lowLevelMajor(lowLevel: LowLevelInternals): 1 | 2 {\n return typeof (lowLevel as { _wrapHandler?: unknown })._wrapHandler === \"function\" ? 2 : 1;\n}\n\nfunction listedTools(result: unknown): unknown[] | null {\n return isRecord(result) && Array.isArray(result.tools) ? (result.tools as unknown[]) : null;\n}\n\n/** Each named tool's fields, read one tool at a time: a tool whose fields\n * cannot be read is skipped, not the list. */\nfunction toolInfos(tools: unknown[], skip: (name: string, err: unknown) => void): ToolInfo[] {\n const infos: ToolInfo[] = [];\n for (const tool of tools) {\n let name: unknown;\n try {\n name = isRecord(tool) ? tool.name : undefined;\n if (typeof name !== \"string\") continue;\n infos.push({ name, description: (tool as ToolInfo).description, inputSchema: (tool as ToolInfo).inputSchema });\n } catch (err) {\n if (typeof name === \"string\") skip(name, err);\n }\n }\n return infos;\n}\n\n/** Note each tool's own schema in the registry, and in the surface when it\n * is one this server serves. */\nfunction readToolList(\n tools: ToolInfo[],\n ctx: WrapContext,\n surface: boolean,\n skip: (name: string, err: unknown) => void,\n): void {\n for (const { name, inputSchema, description } of tools) {\n try {\n const schema = isRecord(inputSchema) ? inputSchema : null;\n if (surface) {\n ctx.surfaceState.noteTool(name, schema ?? EMPTY_OBJECT_JSON_SCHEMA, typeof description === \"string\" ? description : undefined);\n }\n const dispositions = declaredIntentParams(schema);\n if (dispositions[USER_GOAL_PARAM_NAME] === \"native\") ctx.dropSubagentClause(name);\n else if (schema !== null && takesUserGoalJson(schema)) dispositions[USER_GOAL_PARAM_NAME] = \"injected\";\n if (Object.keys(dispositions).length > 0) ctx.paramRegistry.set(name, dispositions);\n else ctx.paramRegistry.delete(name);\n } catch (err) {\n ctx.paramRegistry.delete(name);\n skip(name, err);\n }\n }\n}\n\nfunction servedToolList(\n result: Record<string, unknown>,\n listed: unknown[],\n ctx: WrapContext,\n reportTool: Record<string, unknown> | undefined,\n): unknown {\n const tools = listed.map((tool) => {\n if (!isRecord(tool) || typeof tool.name !== \"string\") return tool;\n if (ctx.paramRegistry.get(tool.name)?.[USER_GOAL_PARAM_NAME] !== \"injected\") return tool;\n // `required` is the `tools/list` seam's, which follows `intentParamMode`.\n return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema as Record<string, unknown>, ctx.intentParamMode, false) };\n });\n if (reportTool !== undefined) tools.push(reportTool);\n return { ...result, tools };\n}\n\nconst LIFECYCLE_SEAMS = {\n resourceList: Symbol(\"batonResourceListSeam\"),\n resourceRead: Symbol(\"batonResourceReadSeam\"),\n promptList: Symbol(\"batonPromptListSeam\"),\n promptGet: Symbol(\"batonPromptGetSeam\"),\n toolList: Symbol(\"batonToolListSeam\"),\n} as const;\n\n/** The three event schemas one lifecycle family needs, structurally rather\n * than by Zod generics: every one `.parse`s 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 `call_id`**: no producer mints one for these, so a consumer pairing\n * 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 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\" | \"tools\";\n /** The `*_start` payload's `params` member, or `{}` where the family has\n * none. */\n startParams: (params: Record<string, unknown>) => Record<string, unknown>;\n /** The result as this caller is served it. */\n rewriteResult?: (ctx: WrapContext, result: unknown, caller: ResolvedCaller) => 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 ctx.perCaller?.followSettings();\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.nextFor` 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.nextFor(opened.session),\n captured_at: new Date().toISOString(),\n payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload }),\n }),\n );\n };\n\n if (!resumesPausedCall(extra)) 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 served = await handler(...args);\n // Unlike tools, this seam wraps the SDK's pause handling, so a pause the\n // SDK then fails throws into the catch below.\n if (isInputRequired(served)) return served;\n const result =\n opened !== null && spec.rewriteResult !== undefined\n ? spec.rewriteResult(ctx, served, opened.caller)\n : served;\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 (SPEC §11.4.4), though it can quote what\n // the handler fetched, so `\"off\"` warns instead: `warnAboutSettings`.\n // The scrub and the cap 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 session: ResolvedSession;\n subject: Record<string, unknown>;\n caller: ResolvedCaller;\n} | null> {\n try {\n const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);\n const client = observeClient(extra, ctx);\n const caller = await resolveCaller(\n ctx.resolvePrincipal,\n { extra, toolName: null, arguments: {} },\n ctx.captureSettings,\n client,\n );\n return {\n session,\n caller,\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: session.sessionId,\n consent_token: ctx.consentToken,\n ...callerEnvelope(caller),\n transport_observed: observeTransport(extra),\n session_id_origin: session.origin,\n client_observed: client,\n runtime_meta: scrubbedMeta,\n },\n };\n } catch (err) {\n stderrLine(`baton: ${spec.method} capture failed: ${String(err)}`);\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 method: TOOLS_LIST_METHOD,\n seamTag: LIFECYCLE_SEAMS.toolList,\n schemas: {\n start: ToolListStartEventSchema,\n end: ToolListEndEventSchema,\n error: ToolListErrorEventSchema,\n },\n countKey: \"tools\",\n startParams: NO_PARAMS,\n rewriteResult: (ctx, result, caller) => ctx.perCaller?.toolsFor(result, caller) ?? result,\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**: the correction it makes is not configurable. A\n * 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 ctx.perCaller?.followSettings();\n const request = args[0] as { params?: { name?: unknown; arguments?: unknown } } | undefined;\n const name = request?.params?.name;\n const slot: CallSlot = {\n innerFired: false,\n flushTerminal: null,\n stripped: stripIntentParams(request?.params, ctx),\n strippedFor: typeof name === \"string\" ? name : null,\n validation: \"unseen\",\n };\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// Module-local, like the seam markers: a second copy of this package wraps\n// on top of this probe and gets its own slots written.\nconst VALIDATION_PROBE = Symbol(\"baton.validationProbe\");\n\n/**\n * Record on the call's slot what the SDK's `validateToolInput` did, so the\n * `tools/call` seam can tell a rejected argument from a refusal above the\n * executor without reading the message. Both majors call it on the instance,\n * right before `executeToolHandler`. A later replacement that does not call\n * through leaves every slot `\"unseen\"`, and a rejected argument reads as\n * `refused` (SPEC §11.4.3: the producer cannot tell why).\n */\nfunction installValidationProbe(server: SupportedServer): void {\n const target = server as unknown as {\n validateToolInput?: ((...args: unknown[]) => Promise<unknown>) & { [VALIDATION_PROBE]?: true };\n };\n const original = target.validateToolInput;\n if (typeof original !== \"function\" || original[VALIDATION_PROBE]) return;\n const probe = async function (this: unknown, ...args: unknown[]): Promise<unknown> {\n const slot = callSlots.getStore();\n try {\n const parsed = await original.apply(this, args);\n if (slot) slot.validation = \"passed\";\n return parsed;\n } catch (err) {\n if (slot) slot.validation = \"rejected\";\n throw err;\n }\n };\n Object.assign(probe, { [VALIDATION_PROBE]: true as const });\n target.validateToolInput = probe;\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, slot, toolEntry, ctx);\n } catch (err) {\n PROCESS_DROPS.add(\"encode_failed\");\n stderrLine(`baton: settling a tool call failed; events dropped: ${String(err)}`);\n }\n}\n\n/**\n * Emit the pair of events for a call that failed BEFORE the vendor's handler\n * ran: one of the SDK's three request-side `failure_kind`s, or a refusal by\n * vendor code above the executor (`refused`, SPEC §11.4.3).\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 slot: CallSlot,\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 intent params from whatever it is given, and here the object is\n // the vendor's live `request.params.arguments`, already consumed by\n // whatever rejected the call. The seam edits the request only before\n // validation (`stripIntentParams`). An unknown tool still carries them, and\n // without this strip they would land in `tool_call_start.params`, which\n // SPEC says equals the vendor-visible arguments.\n const params = { ...((request?.params?.arguments as Record<string, unknown>) ?? {}) };\n const { common, session, resultCaptureMode } = await openCall(\n ctx,\n toolName,\n args[1] as Extra,\n params,\n slot.stripped,\n entry != null ? \"warn\" : \"quiet\",\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, slot.validation);\n const text = (): string => (outcome.raised ? messageOf(outcome.err) : errorText(outcome.result));\n await emit(ctx.sink, () =>\n ToolCallErrorEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.nextFor(session),\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 // above the handler, which is not what any other event means by this\n // 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 ...requestSideFailureFields(\n failureKind,\n resultCaptureMode,\n text,\n outcome.raised ? null : outcome.result,\n (value) => errorBody(ctx, value),\n ctx.scrubber,\n ),\n },\n }),\n );\n}\n\n/** Wrap the entry's CURRENT dispatch target iff it isn't already Baton's\n * wrapper. The `BATON_WRAPPED` tag lives on the wrapped FUNCTION, not the\n * entry object, so a `.update()` that swaps in a fresh vendor callback\n * (untagged) is correctly reprocessed, while one that leaves it alone is a\n * cheap no-op.\n *\n * WHICH function that is differs by SDK major, and getting it wrong fails\n * silently. 1.x's `tools/call` handler invokes `entry.handler`, so patching\n * that field intercepts the call. **v2 dispatches through `entry.executor`**\n * — a closure built at registration over the handler\n * (`createToolExecutor(inputSchema, handler)`; `executeToolHandler` is\n * literally `return tool.executor(args, ctx)`). Patching `entry.handler` on\n * v2 therefore does nothing at all: the vendor handler still runs, the\n * wrapper never fires, and the server emits zero events while looking\n * perfectly healthy — measured against `@modelcontextprotocol/server@2.0.0`\n * and pinned by `test/integrations/mcp/withBatonV2.test.ts`, whose RED\n * signature against a handler-only patch is an empty event list and no\n * error at all. Worse, the schema half\n * of `withBaton` keeps working, so a half-ported install would advertise\n * intent params, collect a goal from the agent, and capture none of it.\n *\n * On v2 we wrap the executor by capture-and-delegate, and deliberately do\n * NOT also wrap `entry.handler`: nothing dispatches through it there, and\n * tagging both would double-wrap once `update({callback})` regenerates the\n * executor over the untouched handler. */\nfunction wrapIfNeeded(nameRef: { current: string }, entry: unknown, ctx: WrapContext): void {\n if (!entry || typeof entry !== \"object\") return;\n const mutable = entry as 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/** The official SDK's low-level `Server`, 1.x or v2, on which the vendor sets\n * its own `tools/list` and `tools/call` handlers. */\nexport interface SupportedLowLevelServer {\n setRequestHandler(method: unknown, ...rest: unknown[]): unknown;\n}\n\nexport type SupportedServer = SupportedMcpServer | SupportedLowLevelServer;\n\n/** Install Baton into an `McpServer` or a low-level `Server`. See module\n * docstring for usage. */\nexport function withBaton(server: SupportedServer, 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 `resolveInstallConfig`, 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 // 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 return inertHandle(supplied.sink ?? new DisabledSink(), \"baton-disabled\");\n }\n const { resolved, unconfigured } = resolveInstallConfig(supplied);\n const handle = install(server, supplied, resolved, newBatonState(resolved), unconfigured);\n // After the checks, so an install that fails does not first warn about it.\n if (unconfigured) logUnconfigured(\"withBaton\");\n else warnAboutSettings(resolved);\n const settings = resolved.captureSettings;\n if (settings === undefined) return handle;\n // Last, so an install that fails reads no settings: \"a failed install reads no settings\".\n settings.start();\n return new SettingsHandle(handle, settings);\n}\n\n/** Stops the settings read when the vendor closes. */\nclass SettingsHandle extends BatonHandle {\n constructor(\n private readonly inner: BatonHandle,\n private readonly settings: CaptureSettings,\n ) {\n super(inner);\n }\n\n // The inner handle holds the queue in front of the sink.\n override flush(): Promise<void> {\n return this.inner.flush();\n }\n\n override async aclose(): Promise<void> {\n this.settings.stop();\n await this.inner.aclose();\n }\n}\n\n/** One Baton for a process that builds a new `McpServer` for every request.\n * Owns the sink, so a request has nothing to close. */\nexport interface Baton {\n wrap(server: SupportedServer): void;\n flush(): Promise<void>;\n aclose(): Promise<void>;\n}\n\n/** Create once at startup, then `wrap` each per-request server. For a server\n * that lives as long as the process, use `withBaton`. */\nexport function createBaton(supplied: BatonConfig = {}): Baton {\n const disabledBy = captureDisabled();\n if (disabledBy !== null) {\n logDisabled(disabledBy, \"createBaton\");\n const unused = supplied.sink ?? new DisabledSink();\n return {\n wrap: () => {},\n flush: () => boundedSinkCall(unused, \"flush\"),\n aclose: () => boundedSinkCall(unused, \"aclose\"),\n };\n }\n\n // Everything the environment or a bad config can decide is settled here, so\n // a request cannot fail on it or be switched off by it:\n // `createBaton.test.ts`, \"reads the environment once\".\n const { resolved, unconfigured } = resolveInstallConfig(supplied);\n if (resolved.reportMode === \"on\") deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);\n // After every check that needs no server; those that do run on each `wrap`.\n if (unconfigured) logUnconfigured(\"createBaton\");\n else warnAboutSettings(resolved);\n const sink = unconfigured ? new DisabledSink() : offTheCall(resolved.sink ?? new StdoutSink());\n const config = {\n ...resolved,\n sink,\n tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId),\n };\n const state = newBatonState(resolved);\n // One read for every server this Baton wraps.\n resolved.captureSettings?.start();\n return {\n wrap: (server) => {\n install(server, supplied, config, state, unconfigured);\n },\n flush: () => boundedSinkCall(sink, \"flush\"),\n aclose: () => {\n resolved.captureSettings?.stop();\n return boundedSinkCall(sink, \"aclose\");\n },\n };\n}\n\n/** A handle for an install that added nothing. The session id is a constant: a\n * real one would name a session no event exists under. */\nfunction inertHandle(sink: Sink, sessionId: string): BatonHandle {\n return new BatonHandle({ sink, sessionId, vendorId: \"\", annotationToolName: \"\" });\n}\n\n/** Which of the two servers this is, told apart by shape because this\n * package imports neither SDK. */\nfunction serverShapeOf(server: SupportedServer): \"mcpServer\" | \"lowLevel\" {\n const candidate = server as {\n server?: unknown;\n registerTool?: unknown;\n setRequestHandler?: unknown;\n _requestHandlers?: unknown;\n _serverInfo?: unknown;\n } | null;\n if (typeof candidate?.registerTool === \"function\" && typeof candidate.server === \"object\" && candidate.server !== null) {\n return \"mcpServer\";\n }\n // `_serverInfo` tells a Server from a Client, which has the same handler map.\n const isServer = typeof candidate?._serverInfo === \"object\" && candidate._serverInfo !== null;\n if (typeof candidate?.setRequestHandler === \"function\" && candidate._requestHandlers instanceof Map && isServer) {\n return \"lowLevel\";\n }\n throw new TypeError(\n \"Baton needs an McpServer or a low-level Server, from @modelcontextprotocol/sdk \" +\n \"or @modelcontextprotocol/server.\",\n );\n}\n\n/** Shared by every server one Baton wraps, so per-request servers act as one:\n * `createBaton.test.ts`, \"numbers one client session across requests\". */\ninterface BatonState {\n sentSurfaces: SentSurfaces;\n /** Kinds of warning already written, so `createBaton` writes each once and not per request. */\n warned: Set<string>;\n counter: SessionCounter;\n scrubber: (value: unknown) => unknown;\n lowLevelTools: KnownTools;\n}\n\nfunction newBatonState(config: BatonConfig): BatonState {\n return {\n sentSurfaces: new SentSurfaces(),\n warned: new Set(),\n counter: new SessionCounter(),\n scrubber: config.scrubber ?? new Scrubber().scrub,\n lowLevelTools: { given: config.tools, givenTools: [], served: new Map(), keepsGoal: new Set(), unread: new Set() },\n };\n}\n\nfunction install(\n server: SupportedServer,\n supplied: BatonConfig,\n resolved: ResolvedBatonConfig,\n { sentSurfaces, warned, counter: sharedCounter, scrubber, lowLevelTools }: BatonState,\n /** Nothing says where events go (SPEC §11.2 rule 10): check, then add nothing. */\n unconfigured: boolean,\n): BatonHandle {\n const shape = serverShapeOf(server);\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: LowLevelInternals;\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 const lowLevel = shape === \"mcpServer\" ? internals.server : (server as unknown as LowLevelInternals);\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: lowLevel._serverInfo?.name,\n className: internals.constructor.name,\n }));\n\n const config =\n resolved.reportMode === \"on\" ? withServerDisplayName(resolved, supplied, serverName) : resolved;\n const reports = reportsFor(config);\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 = reports\n ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName })\n : \"\";\n const ours = reports\n ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName })\n : INTENT_INSTRUCTIONS;\n\n if (unconfigured) return inertHandle(new DisabledSink(), \"baton-unconfigured\");\n // Truthy, not `Object.hasOwn`: the SDK refuses a name the same way, so\n // `constructor` is refused here, before the server changes.\n if (shape === \"mcpServer\" && reports && internals._registeredTools?.[annotationToolName]) {\n throw new Error(\n `Tool ${annotationToolName} is already registered, so Baton cannot add its report tool. ` +\n \"If it is your tool, set annotationToolName to another name; if Baton is already on \" +\n \"this server, call withBaton once.\",\n );\n }\n\n // The checks that change nothing are above this line; from here on the install\n // builds a sink and changes the server.\n const given = config.sink ?? new StdoutSink();\n const sink = offTheCall(given);\n const intentParamMode: IntentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;\n // Per server: two connections are never one session (SPEC §3.4), as\n // `createBaton.test.ts` \"never joins two connections that have no session id\" checks.\n const fallbackSessionId = `sdk-${uuid7()}`;\n const counter = new ServerCounter(sharedCounter, fallbackSessionId);\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\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(lowLevel);\n const surfaceState = new SurfaceState(serverMeta, sentSurfaces);\n\n const emitSurface = async (\n sessionId: string,\n digest: string,\n snapshot: Record<string, unknown>,\n ): Promise<void> => {\n // Deliberately NOT scrubbed — this is the vendor's own static tool\n // surface, not caller-supplied data (mirrors Python's emit_surface).\n await emit(sink, () =>\n SurfaceSnapshotEventSchema.parse({\n tenant_id: tenantId,\n vendor_id: config.vendorId,\n session_id: sessionId,\n session_id_origin: \"minted\",\n consent_token: config.consentToken,\n sequence_number: counter.next(sessionId, false),\n captured_at: new Date().toISOString(),\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 );\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 const warnOnce = (key: string, message: string): void => {\n if (warned.has(key)) return;\n warned.add(key);\n stderrLine(message);\n };\n\n const dropSubagentClause = (name: string): void => {\n const current = lowLevel._instructions;\n if (current === INTENT_INSTRUCTIONS) {\n lowLevel._instructions = \"\";\n } else if (typeof current === \"string\" && current.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) {\n // A replace, not a suffix strip: the vendor may have appended text after ours.\n lowLevel._instructions = current.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, \"\");\n } else {\n return;\n }\n warnOnce(\n \"native-user-goal\",\n `baton: tool ${JSON.stringify(name)} declares its own user_goal, so the subagent ` +\n \"sentence was removed from the server instructions; a session that already started keeps it\",\n );\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 const json = standardInputJsonSchema(inputSchema);\n if (json) return json;\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 EMPTY_OBJECT_JSON_SCHEMA;\n }\n };\n\n installValidationProbe(server);\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 configResultCaptureMode: config.resultCaptureMode ?? \"full\",\n paramRegistry: new Map(),\n resolvePrincipal: config.resolvePrincipal,\n captureSettings: config.captureSettings,\n perCaller: undefined,\n vendorToolJsonSchema,\n bustSchemaMemo,\n dropSubagentClause,\n servedInstructions: () => lowLevel._instructions,\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 writeInstructions = (text: string): void => {\n lowLevel._instructions = withVendorInstructions(lowLevel, text, (message) =>\n warnOnce(\"instructions-length\", message),\n );\n };\n writeInstructions(ours);\n const rewriteInstructions = (text: string): void => {\n writeInstructions(text);\n const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === \"native\");\n if (native !== undefined) dropSubagentClause(native[0]);\n };\n if (config.captureSettings !== undefined) {\n ctx.perCaller = new PerCallerSurface({\n settings: config.captureSettings,\n intentParamMode,\n // Read, not copied: a low-level Server's own tool can take the name.\n get annotationToolName() {\n return ctx.annotationToolName;\n },\n instructions: ours,\n writeInstructions: rewriteInstructions,\n injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === \"injected\",\n });\n // Now, not at the first request: `initialize` passes no seam of ours.\n ctx.perCaller.followSettings();\n }\n\n const annotationOptions = !reports ? undefined : {\n sink,\n counter: ctx.counter,\n tenantId: ctx.tenantId,\n vendorId: ctx.vendorId,\n vendorDisplayName: reports.vendorDisplayName,\n consentToken: ctx.consentToken,\n resolvePrincipal: ctx.resolvePrincipal,\n captureSettings: ctx.captureSettings,\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 };\n\n // Innermost, so every seam below sees the list with Baton's additions.\n if (shape === \"lowLevel\") {\n installLowLevelToolSeams(\n lowLevel,\n ctx,\n annotationOptions && buildAnnotationTool(server, annotationOptions),\n lowLevelTools,\n warnOnce,\n () => rewriteInstructions(INTENT_INSTRUCTIONS),\n );\n }\n\n // Before any tool registers: on a server with no tools yet, the first\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 installToolsListSeam(lowLevel, ctx, shape === \"lowLevel\");\n\n // The SECOND tool-call seam (SPEC §11.4.3's `failure_kind`), installed here\n // for the same reason the `tools/list` seam is. Not on a low-level Server,\n // which has no registry to classify a refused call against.\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 if (shape === \"mcpServer\") installToolsCallSeam(\n lowLevel,\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 lifecycle seams (SPEC §11.4.4, §11.4.5) — unconditional, like the\n // seam above, because what they capture is not configurable. After the\n // `tools/list` seam, so they wrap it and the per-caller rewrite sees the\n // advertised `required`: consoleSettings.test.ts, \"two callers in different\n // audiences see different tool lists\".\n installLifecycleSeams(lowLevel, ctx);\n\n const handle = (name: string): BatonHandle =>\n new BatonHandle({\n sink: given,\n queue: sink,\n vendorId: config.vendorId,\n sessionId: fallbackSessionId,\n annotationToolName: name,\n });\n if (shape === \"lowLevel\") return handle(annotationToolName);\n\n const resolvedAnnotationToolName = annotationOptions\n ? registerAnnotationTool(server as SupportedMcpServer, annotationOptions)\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 handle(resolvedAnnotationToolName);\n}\n\n/** The display name the reports need, or `undefined` under `reportMode: \"off\"`. */\nfunction reportsFor(config: ResolvedBatonConfig): { vendorDisplayName: string } | undefined {\n if (config.reportMode !== \"on\") return undefined;\n // `validateBatonConfig` refuses reportMode \"on\" without one.\n return { vendorDisplayName: config.vendorDisplayName ?? \"\" };\n}\n\n/** Once per `withBaton` or `createBaton`, not per request. */\nfunction warnAboutSettings(config: ResolvedBatonConfig): void {\n if (config.reportMode !== \"on\" && config.annotationToolName !== undefined) {\n stderrLine(\n `baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect ` +\n 'with reportMode: \"off\", because no annotation tool is registered',\n );\n }\n if (config.resultCaptureMode === WITHHELD) {\n warn(\n 'baton: resultCaptureMode \"off\" does not withhold the message of a failed tool list, ' +\n \"resource or prompt request. tool_list_error, resource_list_error, resource_read_error, \" +\n \"prompt_list_error and prompt_get_error carry that message, which can include text your \" +\n \"handler or middleware threw. Throw a message that does not quote what your code fetched.\",\n );\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 / what_happened / tool_name / suggested_improvement /\n * context) and emits an `annotation`\n * event. Port of `baton` (Python)'s `integrations/official/annotation.py`\n * `user_goal` is required by the schema, and a call that is not a report is\n * refused.\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 { isBlank } from \"../../_text.js\";\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, callerEnvelope, resolveCaller } from \"./principalResolution.js\";\nimport type { CaptureSettings } from \"./captureSettings.js\";\nimport { buildAnnotationToolDescription, buildRefusalText } from \"./llmText.js\";\nimport { standardInputJsonSchema, toolInputJsonSchema } from \"./schemaCompat.js\";\nimport { extraMeta, observeTransport, type Extra } from \"./mcpTypes.js\";\nimport type { SupportedMcpServer } from \"./withBaton.js\";\nimport { observeClient } from \"./clientObserved.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 what_happened?: string | undefined;\n tool_name?: string | null | 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 /** The vendor's identity resolver — the SAME one the tool-call wrapper\n * holds. */\n resolvePrincipal?: ResolvePrincipalHook | undefined;\n captureSettings?: CaptureSettings | undefined;\n}\n\n/** Advertised as required on the annotate tool (by the `tools/list` seam in\n * withBaton.ts, and in `reportTool`'s schema) and never enforced: the zod\n * schema keeps it optional. */\nexport const TOOL_NAME_PARAM_NAME = \"tool_name\";\n\nexport const ANNOTATION_INPUT_SHAPE = {\n user_goal: z.string(),\n what_happened: z.string().optional(),\n // Nullable so a report whose agent sends an explicit null is taken,\n // not rejected by validation.\n tool_name: z.string().nullable().optional(),\n suggested_improvement: z.string().optional(),\n // zod renders \"any value\" as `{}`, which some MCP clients refuse (reportToolSchema.test.ts).\n context: z.record(z.string(), z.unknown()).meta({ additionalProperties: true }).optional(),\n};\n\n/** SPEC §11.4: an annotation is a report when its account is filled. */\nexport function isReport(whatHappened: unknown): whatHappened is string {\n return typeof whatHappened === \"string\" && !isBlank(whatHappened);\n}\n\nexport interface AnnotationTool {\n name: string;\n description: string;\n /** Runs on arguments the input schema has already accepted. */\n handler: (args: AnnotationArgs, extra: Extra) => Promise<CallToolResultLike>;\n}\n\ninterface CallToolResultLike {\n content: Array<{ type: \"text\"; text: string }>;\n isError?: boolean;\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 tool = buildAnnotationTool(server, options);\n server.registerTool(\n tool.name,\n { description: tool.description, inputSchema: ANNOTATION_INPUT_SHAPE },\n tool.handler,\n );\n return tool.name;\n}\n\nconst ANNOTATION_ARGS = z.object(ANNOTATION_INPUT_SHAPE);\n\n/** The report tool's input schema as Baton lists it on a server of that\n * major: v2 renders draft 2020-12 from the schema itself, 1.x through its own\n * converter. */\nexport function annotationInputJsonSchema(major: 1 | 2): Record<string, unknown> {\n // A zod without the Standard JSON Schema interface falls back to the 1.x\n // converter, so a vendor's boot never fails on the report tool's schema.\n return (annotationJsonSchemas[major] ??=\n (major === 2 ? standardInputJsonSchema(ANNOTATION_ARGS) : undefined) ?? toolInputJsonSchema(ANNOTATION_INPUT_SHAPE));\n}\n\nconst annotationJsonSchemas: Partial<Record<1 | 2, Record<string, unknown>>> = {};\n\n/** `tools/call` for the annotation tool on a server with no tool registry to\n * validate its arguments, so the check `McpServer` makes is made here. */\nexport function callAnnotationTool(\n tool: AnnotationTool,\n args: unknown,\n extra: Extra,\n): Promise<CallToolResultLike> {\n const parsed = ANNOTATION_ARGS.safeParse(args ?? {});\n if (parsed.success) return tool.handler(parsed.data, extra);\n return Promise.resolve({\n content: [{ type: \"text\", text: `Invalid arguments for tool ${tool.name}: ${parsed.error.message}` }],\n isError: true,\n });\n}\n\n/** The annotation tool for `server`, which is read only for the client the\n * `initialize` handshake declared. */\nexport function buildAnnotationTool(\n server: unknown,\n options: RegisterAnnotationToolOptions,\n): AnnotationTool {\n const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);\n const description = buildAnnotationToolDescription({\n vendorDisplayName: options.vendorDisplayName,\n });\n const refusal = buildRefusalText({ annotationToolName: name });\n\n return {\n name,\n description,\n handler: async (args: AnnotationArgs, extra: Extra) => {\n // Refused in the handler, not by requiring `what_happened` in the\n // schema: an agent that must fill it to get a call through invents a\n // problem, and that corrupts the reports.\n const whatHappened = args.what_happened;\n if (!isReport(whatHappened)) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({\n ok: false,\n error: refusal,\n }),\n },\n ],\n };\n }\n // Sent as given (SPEC §5.1.1): \"\" means the agent said no tool exists,\n // null means it said nothing, and the two must not merge.\n const reportedTool = args.tool_name ?? null;\n\n const meta = extraMeta(extra);\n // As in the tool-call wrapper: coordinates coarsened before the\n // vendor's scrubber.\n const scrubbedMeta = scrubOrNull(\n options.scrubber,\n meta ? roundMetaCoordinates(meta) : null,\n \"_meta\",\n );\n const session = await resolveSessionId(options.fallbackSessionId, extra);\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.\n const client = observeClient(extra, { server, scrubber: options.scrubber });\n const caller = await resolveCaller(\n options.resolvePrincipal,\n { extra, toolName: name, arguments: args },\n options.captureSettings,\n client,\n );\n\n await emit(options.sink, () =>\n AnnotationEventSchema.parse({\n tenant_id: options.tenantId,\n vendor_id: options.vendorId,\n session_id: session.sessionId,\n sequence_number: options.counter.nextFor(session),\n captured_at: new Date().toISOString(),\n consent_token: options.consentToken,\n ...callerEnvelope(caller),\n transport_observed: observeTransport(extra),\n session_id_origin: session.origin,\n client_observed: client,\n runtime_meta: scrubbedMeta,\n payload: {\n // The agent-facing `user_goal` is stored as the wire key `intent`.\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 // 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 what_happened: options.scrubber(whatHappened),\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 tool_name: reportedTool ? options.scrubber(reportedTool) : reportedTool,\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","/**\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\";\nimport { isPlainObject } from \"./_object.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/** `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 still sees 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","/**\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 rationale. Kept in sync by hand, as there is no\n * cross-language codegen for prose, and checked:\n * `test/integrations/mcp/llmTextVectors.json` is Python's own rendering,\n * compared string-for-string.\n *\n * **Python's text.** Under `reportMode: \"on\"` it renders what Python\n * renders: the instructions are one sentence pointing at the\n * annotation tool, and the tool's description holds the triggers, the\n * recovery rule and the fields, so each rule is written once.\n */\n\nimport { isBlank } from \"../../_text.js\";\nimport { stderrLine } from \"../../warn.js\";\n\n// Holds no report rule: each is written once, in the report tool's description.\nconst REPORT_POINTER_TEMPLATE = (vendorDisplayName: string, annotationToolName: string) =>\n `Use \\`${annotationToolName}\\` to report a ${vendorDisplayName} tool call ` +\n \"that went wrong, or a request no tool covers; its description says when and how.\";\n\n// The format SPEC §5.1.1 gives for user_goal.\nconst USER_GOAL_FORMAT = \"'<n>: <what this call is for>; success is <what its result should show>'\";\n\nconst ANNOTATION_TOOL_DESCRIPTION_TEMPLATE = (\n vendorDisplayName: string,\n) => `Report a ${vendorDisplayName} tool call that went wrong, so \\\n${vendorDisplayName} can fix it. Call this right after a call errors, times \\\nout, or returns an empty, unhelpful or contradictory result. Also call it \\\nonce per user request when no tool or field covers what they asked for, or \\\nyou had to work around one. Do not call it before a tool call or for normal \\\nsuccessful work.\n\nA report does not replace the work: after it, work out why the call failed, \\\nfix the input and try again (do not repeat the same failing call), and still \\\nanswer the user.\n\nFields:\n - user_goal: the same ${USER_GOAL_FORMAT} as on this server's other tools.\n - what_happened: REQUIRED. 1-2 plain sentences in your own words: what you \\\nasked for, what came back, and why it was unusable. Not a category.\n - tool_name: REQUIRED. The ${vendorDisplayName} tool that went wrong, or \\\nnone if no tool exists for the request.\n - suggested_improvement: one concrete sentence on the product change that \\\nwould 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. When no tool covers the \\\nrequest also missing_capability_field and requested_capability.`;\n\n// Where Claude Code truncates InitializeResult.instructions. The cap below it\n// leaves room for the fixed subagent sentence.\nconst CLAUDE_CODE_TRUNCATION_CAP = 2087;\nconst INSTRUCTIONS_LENGTH_CAP = 1500;\n\ninterface InstructionNames {\n vendorDisplayName: string;\n annotationToolName: string;\n}\n\nfunction renderServerInstructions(options: InstructionNames): string {\n return REPORT_POINTER_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. 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 // The subagent sentence has no names in it, so it comes out of the headroom\n // under the truncation cap, not out of the budget the names share.\n return rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;\n}\n\nexport function buildAnnotationToolDescription(options: { vendorDisplayName: string }): string {\n return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);\n}\n\n/** What the annotation tool answers when a call has no account (SPEC §5.1.1). */\nexport function buildRefusalText(options: { annotationToolName: string }): string {\n return (\n `${options.annotationToolName} is reactive-only on this server. Call it only AFTER ` +\n \"a tool call returns an unhelpful, empty, failed or contradictory result, or \" +\n \"when no tool covers what the user asked for. What the user is trying to do \" +\n \"is already recorded on each tool call, so no pre-call annotation is needed — \" +\n \"nothing was lost. If a tool call really went wrong, or no tool covers the \" +\n \"request, call this again and say what_happened. If neither is true, do NOT \" +\n \"re-send: that would file a report for a call that did not go wrong.\"\n );\n}\n\n// =============================================================================\n// Intent-param injection text — mirrors `baton` (Python)'s\n// `integrations/_llm_text.py` byte-for-byte. This is the capture path that\n// survives runtimes which drop `instructions`, notably Claude Desktop.\n// =============================================================================\n\nexport const USER_GOAL_PARAM_NAME = \"user_goal\";\n\n// Not injected. A client with an old tool list may still send them, and\n// `overall_task` carries the turn number the Console falls back to.\nexport const EXPECTED_RESULT_PARAM_NAME = \"expected_result\";\nexport const OVERALL_TASK_PARAM_NAME = \"overall_task\";\nexport const RETIRED_PARAM_NAMES = [EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME] as const;\n\n/** Provenance value stamped on `tool_call_start.payload.intent_source` when\n * intent came from an injected param. The Console reads this string. */\nexport const INTENT_SOURCE_PARAM = \"injected_param\";\n\n/** `intent_source` when the vendor's code passed intent to `client.trace()`. */\nexport const INTENT_SOURCE_LIBRARY = \"library_arg\";\n\n// The leading number says which user message the call answers (SPEC §5.1.1).\n//\n// Do not reword: the text is the Python SDK's, byte for byte\n// (`llmText.test.ts`, \"parity with the Python SDK's rendered text\"). Only the\n// leading label tracks `intentParamMode`, so it agrees with the `required`\n// list the `tools/list` seam advertises.\nconst USER_GOAL_PARAM_BODY =\n `Write it as ${USER_GOAL_FORMAT}. n is the number of the user's current message in this ` +\n \"conversation (1 for the first). Use the same number on every call you make \" +\n \"for that message, including calls made after reading tool results; it goes \" +\n \"up only when the user sends another message.\";\nconst USER_GOAL_PARAM_DESCRIPTION = \"OPTIONAL. \" + USER_GOAL_PARAM_BODY;\nconst USER_GOAL_PARAM_DESCRIPTION_REQUIRED = \"REQUIRED. \" + USER_GOAL_PARAM_BODY;\n\n// A main agent that delegates may never load this server's tool schemas, so the\n// param description above never reaches it and its subagents get no number.\nexport const INSTRUCTIONS_SUBAGENT_CLAUSE =\n \"\\n\\nWhen you hand work to a subagent that may call this server's tools, tell it \" +\n \"the number of the user's current message in this conversation, and that it \" +\n \"must start user_goal with that number on every call to this server's \" +\n \"tools. This applies only to this server's tools.\";\n\n/** The server instructions a vendor serving MCP itself puts in its\n * `initialize` result beside `user_goal` (SPEC §5.6), and all of Baton's\n * instructions under `reportMode: \"off\"`. */\nexport const INTENT_INSTRUCTIONS = INSTRUCTIONS_SUBAGENT_CLAUSE.trim();\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\n/** Which injected params `intentParamMode` advertises as required. */\nexport function requiredParamNames(intentParamMode: string): string[] {\n return intentParamMode === \"required\" ? [USER_GOAL_PARAM_NAME] : [];\n}\n\n/** Whether a tool's vendor-true JSON `inputSchema` declares `name` itself. */\nexport function declaresParam(schema: unknown, name: string): boolean {\n const props = (schema as { properties?: unknown } | null | undefined)?.properties;\n return typeof props === \"object\" && props !== null && name in props;\n}\n\n// What a schema forbids, or values it shows, never names a parameter it takes.\nconst NOT_ACCEPTED = new Set([\"not\", \"const\", \"enum\", \"default\", \"examples\"]);\n// Their keys are the vendor's names, so a property called \"default\" is searched.\nconst NAMED_SCHEMAS = new Set([\"properties\", \"patternProperties\", \"$defs\", \"definitions\", \"dependentSchemas\"]);\n\n/** Whether a JSON schema may take `name` anywhere: as a property or a\n * required name at any depth, or behind a `$ref` to another document, which\n * Baton cannot read. */\nexport function mayDeclareParam(schema: unknown, name: string): boolean {\n const seen = new Set<object>();\n const walk = (node: unknown): boolean => {\n if (typeof node !== \"object\" || node === null || seen.has(node)) return false;\n seen.add(node);\n const { required, $ref } = node as { required?: unknown; $ref?: unknown };\n if (declaresParam(node, name) || (Array.isArray(required) && required.includes(name))) return true;\n if (typeof $ref === \"string\" && !$ref.startsWith(\"#\")) return true;\n return Object.entries(node).some(([key, child]: [string, unknown]) => {\n if (NAMED_SCHEMAS.has(key) && typeof child === \"object\" && child !== null) return Object.values(child).some(walk);\n return !NOT_ACCEPTED.has(key) && walk(child);\n });\n };\n return walk(schema);\n}\n\n/** Whether Baton's text is in the served instructions. Without the annotation\n * tool it is only the subagent sentence, which a tool declaring its own\n * `user_goal` removes. */\nexport function instructionsSuffixServed(annotationToolName: string, served: unknown): boolean {\n if (annotationToolName) return true;\n return typeof served === \"string\" && served.includes(INTENT_INSTRUCTIONS);\n}\n\n/** One injected param, for a vendor adding it to its own API (SPEC §5.6).\n * `description` is the text an agent reads on an MCP server, without the\n * leading \"OPTIONAL.\" / \"REQUIRED.\" label: whether the vendor's API requires\n * it is the vendor's call. `traceOption` is the `client.trace()` option the\n * agent's answer goes to. */\nexport interface IntentParam {\n readonly name: string;\n readonly description: string;\n readonly traceOption: \"intent\";\n}\n\nexport const INTENT_PARAMS: readonly IntentParam[] = Object.freeze([\n Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: \"intent\" }),\n]);\n\nconst VENDOR_INSTRUCTIONS = Symbol(\"batonVendorInstructions\");\nconst escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n// Where our paragraph begins under `reportMode` \"on\" and \"off\". The pointer is\n// matched whole: its opening, \"Use `\", is how a vendor's own paragraph may start.\nconst OURS_STARTS = [\n new RegExp(\n \"^\" + REPORT_POINTER_TEMPLATE(\"\\u0000\", \"\\u0000\").split(\"\\u0000\").map(escapeRegExp).join(\".+?\"),\n ),\n new RegExp(\"^\" + escapeRegExp(INTENT_INSTRUCTIONS)),\n];\n\ninterface InstructionsHolder {\n _instructions?: string | undefined;\n [VENDOR_INSTRUCTIONS]?: string | undefined;\n}\n\nfunction endsInOurs(current: unknown, vendor: unknown): boolean {\n if (typeof current !== \"string\") return false;\n const prefix = typeof vendor === \"string\" && !isBlank(vendor) ? `${vendor}\\n\\n` : \"\";\n if (!current.startsWith(prefix)) return false;\n const rest = current.slice(prefix.length);\n return OURS_STARTS.some((start) => start.test(rest));\n}\n\n/** SPEC §5.1.2: the vendor's own instructions first, ours below them.\n *\n * The runtime cuts at `CLAUDE_CODE_TRUNCATION_CAP` from the end, so the order\n * decides whose text is lost. The vendor's text is remembered on the server, so\n * a second install replaces our paragraph rather than appending another; text\n * the vendor set in between replaces what was remembered. */\nexport function withVendorInstructions(\n server: object,\n ours: string,\n warn: (message: string) => void = stderrLine,\n): string {\n const holder = server as InstructionsHolder;\n const current = holder._instructions;\n let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current;\n if (!endsInOurs(current, vendor)) {\n vendor = current;\n holder[VENDOR_INSTRUCTIONS] = vendor;\n }\n if (typeof vendor !== \"string\" || isBlank(vendor)) return ours;\n const combined = `${vendor}\\n\\n${ours}`;\n if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {\n warn(\n `baton: the server instructions are ${combined.length} chars (yours ${vendor.length}, ` +\n `Baton's ${ours.length}); Claude Code cuts them at ~${CLAUDE_CODE_TRUNCATION_CAP}, ` +\n \"so the end of Baton's text is lost there\",\n );\n }\n return combined;\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 { stripEdges } from \"../../_text.js\";\nimport { warn } from \"../../warn.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\n/** What Python's `str.strip()` removes: Unicode `White_Space` plus\n * U+001C-U+001F. The server-name rule keeps it, as the Console's slug rule does. */\nconst SEPARATORS = \"\\\\x1c-\\\\x1f\";\nconst PYTHON_SPACE = new RegExp(`^[\\\\p{White_Space}${SEPARATORS}]$`, \"u\");\n\nfunction pythonStrip(value: string): string {\n return stripEdges(value, PYTHON_SPACE);\n}\n\nfunction isPlaceholderLiteral(name: string): boolean {\n return PLACEHOLDER_LITERALS.has(pythonStrip(name).toLowerCase());\n}\n\nfunction isLibraryPlaceholder(serverName: string, className: string): boolean {\n if (isPlaceholderLiteral(serverName)) return true;\n const stripped = pythonStrip(serverName);\n const stem = stripped.replace(RANDOM_SUFFIX, \"\");\n return stem !== stripped && stem === className;\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/** `{slug}_annotate` from a display name, as an adapter derives it from a\n * server of that name, or `undefined` where an adapter would fall back. */\nexport function toolNameForDisplayName(vendorDisplayName: string): string | undefined {\n if (isPlaceholderLiteral(vendorDisplayName)) return undefined;\n const candidate = toolNameCandidate(vendorDisplayName);\n return candidate !== undefined &&\n fitsInstructionsCap({ vendorDisplayName, annotationToolName: candidate })\n ? candidate\n : undefined;\n}\n\n/** The last step of the ladder. 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 return validateAnnotationToolName(override || `${vendorId}${SUFFIX}`);\n}\n\n/** The ladder's one throw site. */\nexport function validateAnnotationToolName(name: string): string {\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\";\nimport { PROCESS_DROPS } from \"../../drops.js\";\nimport { printable, stderrLine } from \"../../warn.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_DROPS.add(\"encode_failed\");\n stderrLine(`baton: event construction failed; event dropped: ${printable(err)}`);\n return;\n }\n await safeWrite(sink, event);\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, isBlank } 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/** 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 return usableText(value, DISPLAY_NAME_MAX_LEN) ? value : null;\n}\n\n/** SPEC §11.4's rule for `display_name` and labels. Mirrors Python's `usable_text`. */\nfunction usableText(value: unknown, maxCodePoints: number): value is string {\n if (typeof value !== \"string\" || exceedsCodePoints(value, maxCodePoints)) return false;\n // U+0000: Postgres text refuses it, costing a collector the whole event.\n return !LONE_SURROGATE.test(value) && !value.includes(\"\\u0000\") && !isBlank(value);\n}\n\nexport const LABELS_MAX = 20;\nexport const LABEL_MAX_LEN = 64;\n/** How many a resolver's labels are read up to, so an endless iterable cannot hang a call. */\nconst LABELS_READ_MAX = 1000;\n\n/** The envelope's `labels`: `null`, never an empty list (SPEC §11.4). */\nexport function wireLabels(labels: readonly string[]): readonly string[] | null {\n return labels.length > 0 ? labels : null;\n}\n\n/** The usable labels, in the order given, without repeats, at most\n * `LABELS_MAX` (SPEC §11.4). Mirrors Python's `clean_labels`. */\nexport function cleanLabels(values: Iterable<unknown>): string[] {\n const kept = new Set<string>();\n for (const value of values) {\n if (usableText(value, LABEL_MAX_LEN)) {\n kept.add(value);\n if (kept.size === LABELS_MAX) break;\n }\n }\n return [...kept];\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/** 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/** 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 /** The company this principal belongs to. Sent as `organization`, and\n * dropped alone when unusable (SPEC §11.4). */\n organization?: Organization | null | undefined;\n /** As `Organization.labels`. A principal's labels and its organization's\n * are sent together. */\n labels?: readonly string[] | undefined;\n}\n\n/** The company or workspace the caller belongs to, as the vendor sees it.\n * Sent as `organization` (SPEC §11.4), beside `principal` or alone. It is\n * never counted as a person. `form` describes `organizationId` alone. */\nexport interface Organization {\n organizationId: string;\n form?: PrincipalForm | undefined;\n displayName?: string | null | undefined;\n /** Your names for the groups this caller is in, for Console settings to\n * match (SPEC §11.4). Baton sees them, so use group names or keys you keep,\n * never raw ids. */\n labels?: readonly string[] | undefined;\n}\n\nfunction usableId(id: unknown): id is string {\n if (typeof id !== \"string\") return false;\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(id)) return false;\n // U+0000 is refused by Postgres text and would cost a collector the whole event.\n if (id.includes(\"\\u0000\")) return false;\n // A blank id names nobody, and every such caller would merge into one actor.\n return !isBlank(id);\n}\n\nfunction readIdentity(\n result: unknown,\n idKey: \"principalId\" | \"organizationId\",\n): { id: string; form: unknown; displayName: string | undefined } | null {\n if (result === null || typeof result !== \"object\") return null;\n const candidate = result as Record<string, unknown>;\n const id = candidate[idKey];\n if (!usableId(id)) return null;\n // Shape only; the name's own rules run once, in `identityWire`.\n const displayName = typeof candidate.displayName === \"string\" ? candidate.displayName : undefined;\n return { id, form: candidate.form, displayName };\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/** The organization as emitted: `principal`'s members and rules, with its\n * own `form` (SPEC §11.4). */\nexport type OrganizationWire = PrincipalWire;\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 envelope's `principal`, `organization` and `labels`. Either, both or\n * neither identity may be set: SPEC §11.4 keeps them independent. */\nexport interface CallerWire {\n principal: PrincipalWire | null;\n organization: OrganizationWire | null;\n labels: readonly string[];\n}\n\nexport const NO_CALLER: CallerWire = Object.freeze({ principal: null, organization: null, labels: [] });\n\n/** Told why `callerFor` dropped or rewrote something. `key` is fixed text, so\n * a caller can report each kind of problem once; `message` may hold part of\n * the vendor's value. */\nexport type CallerWarning = (key: string, message: string) => void;\n\n/** What a `resolvePrincipal` hook returned, or `principal` was given, as wire\n * objects: a `Principal`, which may carry its `organization`, or an\n * `Organization` alone. Each is dropped alone when unusable. Never throws:\n * the value is vendor code, and a getter or Proxy on it may. */\nexport function callerFor(result: unknown, warn: CallerWarning): CallerWire {\n try {\n return readCaller(result, warn);\n } catch {\n warn(\"unreadable\", \"could not be read — sending neither principal nor organization.\");\n return NO_CALLER;\n }\n}\n\nfunction readCaller(result: unknown, warn: CallerWarning): CallerWire {\n if (result === undefined || result === null) return NO_CALLER;\n if (typeof result !== \"object\") {\n warn(\"not-object\", `got a ${typeof result}, not an object — sending neither principal nor organization.`);\n return NO_CALLER;\n }\n // A `principalId` or an `organization` key makes it a `Principal`, so a\n // missing or blank person still keeps the company; otherwise an `Organization`.\n if (!(\"principalId\" in result) && !(\"organization\" in result)) {\n if (\"organizationId\" in result) {\n return {\n principal: null,\n organization: identityFor(result, \"organization\", warn),\n labels: labelsOf([result], warn),\n };\n }\n if (typeof (result as { userId?: unknown }).userId === \"string\") {\n warn(\n \"user-id\",\n \"returned { userId }, which was renamed to { principalId } in 0.3.5, so the principal \" +\n \"is dropped from every event until it returns the new key.\",\n );\n } else {\n warn(\"no-id\", \"got an object with neither principalId nor organizationId — sending neither.\");\n }\n return NO_CALLER;\n }\n if (\"organizationId\" in result) {\n warn(\"flat-organization-id\", \"got principalId and organizationId side by side; put the company in `organization`.\");\n }\n const nested = (result as { organization?: unknown }).organization;\n return {\n principal: identityFor(result, \"principal\", warn),\n organization: nested == null ? null : identityFor(nested, \"organization\", warn),\n labels: labelsOf([result, nested], warn),\n };\n}\n\nfunction labelsOf(sources: unknown[], warn: CallerWarning): string[] {\n const labels: unknown[] = [];\n for (const source of sources) {\n try {\n const given = (source as { labels?: unknown } | null | undefined)?.labels;\n if (typeof given === \"string\" || typeof (given as Iterable<unknown> | null | undefined)?.[Symbol.iterator] !== \"function\") {\n continue;\n }\n let read = 0;\n for (const label of given as Iterable<unknown>) {\n labels.push(label);\n if (++read === LABELS_READ_MAX) break;\n }\n } catch {\n warn(\"labels\", \"labels could not be read — sending the ones read before the failure.\");\n }\n }\n return cleanLabels(labels);\n}\n\nfunction identityFor(\n value: unknown,\n member: \"principal\" | \"organization\",\n warn: CallerWarning,\n): PrincipalWire | null {\n const idKey = member === \"principal\" ? \"principalId\" : \"organizationId\";\n const identity = readIdentity(value, idKey);\n if (identity === null) {\n warn(`${member}:id`, `${member} has no usable ${idKey} — sending no ${member}.`);\n return null;\n }\n return identityWire(identity.id, identity.form, identity.displayName, (form) =>\n warn(`${member}:form`, `${member} form ${describeForm(form)} is not registered — sending \"raw\".`),\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\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 one. */\nfunction identityWire(\n id: string,\n stated: unknown,\n displayName: unknown,\n onUnregisteredForm?: (form: unknown) => void,\n): PrincipalWire {\n let form: PrincipalForm = PRINCIPAL_FORM_RAW;\n if (stated !== undefined) {\n if (PRINCIPAL_FORMS.has(stated)) {\n form = stated 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?.(stated);\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(id, PRINCIPAL_ID_MAX_LEN),\n source: PRINCIPAL_SOURCE_ASSERTED,\n form,\n };\n const name = wireDisplayName(displayName);\n if (name !== null) wire.display_name = name;\n return wire;\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 }` — it keeps `sessionId`\n * but moves the request `_meta` down under `mcpReq`. Read only at the 1.x\n * location and every v2 event silently loses its `runtime_meta`: no error,\n * just worse data. Use {@link extraMeta}, never `extra._meta`.\n *\n * The SECOND divergence, same shape: 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 * silently loses `client_observed.info` 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?:\n | { _meta?: unknown; envelope?: unknown; inputResponses?: unknown; requestState?: () => unknown }\n | 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 `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\nexport function isThenable(value: unknown): value is PromiseLike<unknown> {\n return typeof (value as { then?: unknown } | null | undefined)?.then === \"function\";\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 CallerWire,\n type Organization,\n type Principal,\n NO_CALLER,\n callerFor,\n wireLabels,\n} from \"../../identity.js\";\nimport type { ClientObserved } from \"./clientObserved.js\";\nimport { raceDeadline, TIMED_OUT } from \"../../deadline.js\";\nimport { warn } from \"../../warn.js\";\nimport type { CallSettings, CaptureSettings } from \"./captureSettings.js\";\nimport {\n type AuthInfo,\n type Extra,\n extraAuthInfo,\n extraHeaders,\n extraMeta,\n isThenable,\n} 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.\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. `null` on a\n * request that is not a tool call. */\n toolName: string | null;\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. Empty on a\n * request that is not a tool call. */\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 | Organization | null | Promise<Principal | Organization | null>;\n\n/** Build the hook's input from whichever major's context arrived.\n *\n * ⚠ **ONE factory, called by every emit path.** Every request that resolves\n * a principal goes through here rather than each\n * assembling 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 | null,\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/** How long a vendor's hook may take, the same budget Python gives one. */\nexport const HOOK_TIMEOUT_MS = 5000;\n\nasync function withinHookBudget(answer: unknown): Promise<unknown> {\n if (!isThenable(answer)) return answer;\n const first = await raceDeadline(answer, HOOK_TIMEOUT_MS);\n if (first !== TIMED_OUT) return first;\n warn(\n `baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1000)}s; ` +\n \"this request is sent without a principal.\",\n );\n return null;\n}\n\n// The hook runs on every request, so each kind of problem is reported once.\nconst warned = new Set<string>();\n\nfunction warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n warn(`baton: resolvePrincipal ${message}`);\n}\n\n/** The caller as wire objects, and the capture settings it runs under. */\nexport interface ResolvedCaller extends CallerWire {\n /** `undefined` means the config's values. */\n settings?: CallSettings;\n}\n\n/** The envelope's `principal`, `organization`, `labels` and `capture`. */\nexport function callerEnvelope(caller: ResolvedCaller): Record<string, unknown> {\n return {\n principal: caller.principal,\n organization: caller.organization,\n labels: wireLabels(caller.labels),\n capture: caller.settings?.capture ?? null,\n };\n}\n\nlet settingsWarned = false;\n\n/** The envelope's `principal`, `organization` and labels for one request,\n * and with `settings` the capture settings it runs under (SPEC §2.6).\n *\n * ⚠ **Never throws.** A hook that raises, returns the wrong shape, or returns\n * `null` yields an anonymous request, not a failed one — `principal` and\n * `organization` are additive analytics, and a vendor's own bug in their\n * resolver may not fail their request (SPEC §11.2 fail-open). Settings that\n * fail to apply leave the config's values.\n *\n * A hook that has not answered within `HOOK_TIMEOUT_MS` is given up on, which\n * cannot bound one that blocks synchronously.\n */\nexport async function resolveCaller(\n hook: ResolvePrincipalHook | undefined,\n call: { extra: Extra; toolName: string | null; arguments: Record<string, unknown> },\n settings?: CaptureSettings,\n client: ClientObserved | null = null,\n): Promise<ResolvedCaller> {\n const caller = await resolveIdentity(hook, call);\n if (settings === undefined) return caller;\n try {\n const callSettings = settings.forCaller({\n labels: caller.labels,\n clientName: client?.info?.name ?? null,\n shareKey: caller.principal?.id ?? null,\n });\n return callSettings === undefined ? caller : { ...caller, settings: callSettings };\n } catch {\n if (!settingsWarned) {\n settingsWarned = true;\n warn(\"baton: applying capture settings failed; this request uses the config's values\");\n }\n return caller;\n }\n}\n\nasync function resolveIdentity(\n hook: ResolvePrincipalHook | undefined,\n call: { extra: Extra; toolName: string | null; arguments: Record<string, unknown> },\n): Promise<CallerWire> {\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 request.\n if (hook === undefined) return NO_CALLER;\n try {\n const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);\n const result: unknown = await withinHookBudget(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 return callerFor(result, warnOnce);\n } catch {\n // Broad on purpose: this calls code a VENDOR wrote, and an identity read\n // may not be able to fail a request. Nothing is logged to stdout — that\n // stream is the MCP JSON-RPC frame (AGENTS.md boundary rule 2).\n return NO_CALLER;\n }\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` into a vendor's EXISTING Zod object schema has to\n * build the injected field with a schema instance from the SAME zod major as\n * 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 { RETIRED_PARAM_NAMES, USER_GOAL_PARAM_NAME, buildUserGoalParamDescription, declaresParam } from \"./llmText.js\";\nimport { isRecord } from \"../../_object.js\";\n\nexport type IntentParamMode = \"optional\" | \"required\";\nexport const DEFAULT_INTENT_PARAM_MODE: IntentParamMode = \"required\";\n\n// A property beside a root `$ref` or combiner is not seen by the subschema's\n// `additionalProperties: false`, so a client validator would refuse the call.\nconst ROOT_COMBINERS = [\"$ref\", \"oneOf\", \"anyOf\", \"allOf\"] as const;\n\n/** Whether Baton may add `user_goal` to a tool's JSON Schema `inputSchema`. */\nexport function takesUserGoalJson(schema: Record<string, unknown>): boolean {\n // `undefined` counts as missing: JSON drops the key, so the agent would see none.\n const properties = schema.properties ?? {};\n return isRecord(properties) && !ROOT_COMBINERS.some((key) => key in schema);\n}\n\n/** `schema` with `user_goal` added as `injectGoalParams` adds it to a zod one.\n * A schema that declares its own, or that `takesUserGoalJson` refuses, is\n * returned as it is. */\nexport function withUserGoalJson(\n schema: Record<string, unknown>,\n intentParamMode: IntentParamMode,\n listRequired: boolean,\n): Record<string, unknown> {\n if (!takesUserGoalJson(schema) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return schema;\n const properties = (schema.properties ?? {}) as Record<string, unknown>;\n const goal = { type: \"string\", description: buildUserGoalParamDescription({ intentParamMode }) };\n const served: Record<string, unknown> = { ...schema, properties: { ...properties, [USER_GOAL_PARAM_NAME]: goal } };\n const required = Array.isArray(schema.required) ? (schema.required as unknown[]) : [];\n if (listRequired && !required.includes(USER_GOAL_PARAM_NAME)) served.required = [...required, USER_GOAL_PARAM_NAME];\n return served;\n}\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.\nexport const EMPTY_OBJECT_JSON_SCHEMA = { type: \"object\", properties: {} };\n\n/**\n * Splice `user_goal` into `inputSchema`'s 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 the description labels (\"REQUIRED.\" or\n * \"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, how `mode` labels them, or when a vendor's own field of the\n * 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 // A retired name the vendor declares is the vendor's, and is forwarded.\n for (const name of RETIRED_PARAM_NAMES) {\n if (name in existingShape) dispositions[name] = \"native\";\n }\n\n // Optional in the zod schema, in every mode: a required field would make the\n // vendor's server refuse a call that omits it. Zod cannot advertise required\n // without enforcing it, so `required` is advertised on the `tools/list`\n // response instead, by `advertiseIntentParamsRequired`.\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 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`, 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 description labels 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 * Applied to a rendered `tools/list` result: each of `names` that\n * `isInjected` says Baton added to a tool is appended to that tool's\n * `required` array. Serves `intentParamMode: \"required\"` and the annotate\n * tool's `tool_name`.\n *\n * Copy on write, so a caller that catches a throw from here can serve the\n * original. Only the response changes; the zod schema stays optional, which\n * is what keeps the names advertised and never enforced\n * (`intentAdvertise.test.ts`, \"serves a call with NEITHER name\").\n */\nexport function advertiseIntentParamsRequired(\n result: unknown,\n names: readonly string[],\n isInjected: (toolName: string, paramName: 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 const toolName = entry?.name;\n if (typeof toolName !== \"string\") 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 const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));\n if (missing.length === 0) return tool;\n changed = true;\n return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };\n });\n return changed ? { ...(result as Record<string, unknown>), tools: advertised } : result;\n}\n\n/** `result` with the tool `name` listing `inputSchema`. Copy on write. */\nexport function withToolInputSchema(result: unknown, name: string, inputSchema: Record<string, unknown>): unknown {\n const tools = (result as { tools?: unknown } | null | undefined)?.tools;\n if (!Array.isArray(tools)) return result;\n const at = tools.findIndex((tool) => isRecord(tool) && tool.name === name);\n if (at === -1) return result;\n const served: unknown[] = [...(tools as unknown[])];\n served[at] = { ...(tools[at] as Record<string, unknown>), inputSchema };\n return { ...(result as Record<string, unknown>), tools: served };\n}\n\n/** A v2 schema's draft 2020-12 rendering through its own Standard JSON Schema\n * converter, the one v2 lists tools with; `undefined` when it has none. */\nexport function standardInputJsonSchema(schema: unknown): Record<string, unknown> | undefined {\n try {\n const standard = (schema as { \"~standard\"?: { jsonSchema?: { input?: (o: unknown) => Record<string, unknown> } } })?.[\"~standard\"];\n return standard?.jsonSchema?.input?.({ target: \"draft-2020-12\" });\n } catch {\n return undefined;\n }\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","import {\n EXPECTED_RESULT_PARAM_NAME,\n OVERALL_TASK_PARAM_NAME,\n USER_GOAL_PARAM_NAME,\n} from \"./llmText.js\";\nimport { printable, stderrLine } from \"../../warn.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 | \"client_observed\"\n | \"_meta\"\n | typeof USER_GOAL_PARAM_NAME\n | typeof EXPECTED_RESULT_PARAM_NAME\n | typeof OVERALL_TASK_PARAM_NAME\n | \"params\"\n | \"intent\"\n | \"expected_outcome\"\n | \"workflow\"\n | \"context\";\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\": a `client_observed` value is left out, `_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: this fires several times per call, so\n // warning every time would print a stderr line on every tool call.\n if (!warned.has(field)) {\n warned.add(field);\n stderrLine(\n `baton: scrubber threw on ${field}; that field is dropped, tool call continues. ` +\n `Further failures on this field will be silent: ${printable(err)}`,\n );\n }\n return null;\n }\n}\n","/** The envelope's `client_observed` (SPEC §11.4): what the client said about\n * itself, sent uninterpreted. The consumer names the client; this SDK does\n * not, and sends `agent_runtime: \"unknown\"` on every event. */\n\nimport { capCodePoints } from \"../../_text.js\";\nimport { extraEnvelope, extraHeaders, extraMeta, type Extra } from \"./mcpTypes.js\";\nimport { scrubOrNull } from \"./safeScrub.js\";\n\n/** The per-request carrier for the client's declaration, reserved by MCP\n * 2026-07-28. Written out because the 1.x peer exports no such constant and\n * importing v2's would pin a major for a string. */\nexport const CLIENT_INFO_META_KEY = \"io.modelcontextprotocol/clientInfo\";\n\n// The only headers ever copied. A request also carries credentials, so this\n// is a list in the SDK and not a config option: `test/integrations/mcp/clientObserved.test.ts`,\n// \"never copies a header that is not registered\".\nconst OBSERVED_HEADERS = [\"user-agent\", \"x-anthropic-client\"] as const;\n\nconst CLIENT_INFO_MAX_LEN = 128;\nconst HEADER_VALUE_MAX_LEN = 256;\n\nexport interface ClientObserved {\n info?: { name?: string; version?: string };\n headers?: Partial<Record<(typeof OBSERVED_HEADERS)[number], string>>;\n}\n\n/** `scrubber` is required so a call site cannot send these values unscrubbed\n * by leaving it out. */\ninterface ObserveClientOptions {\n /** The MCP server object that was wrapped: it holds the handshake. */\n server?: unknown;\n scrubber: (value: unknown) => unknown;\n}\n\ninterface DeclaredClientInfo {\n name?: unknown;\n version?: unknown;\n}\n\nconst hasText = (value: unknown): value is string => typeof value === \"string\" && value !== \"\";\n\n/** The pair one source declared, or `undefined` when it holds no text at all,\n * so a malformed declaration on the request does not hide the handshake's. */\nfunction declared(info: unknown): DeclaredClientInfo | undefined {\n if (!info || typeof info !== \"object\") return undefined;\n const { name, version } = info as DeclaredClientInfo;\n return hasText(name) || hasText(version) ? { name, version } : undefined;\n}\n\n/** The request's own declaration. v2 lifts the reserved key out of `_meta`\n * into the envelope and 1.x leaves it in, so both are read. */\nfunction declaredOnRequest(extra: Extra): DeclaredClientInfo | undefined {\n for (const source of [extraEnvelope(extra), extraMeta(extra)]) {\n const found = declared(source?.[CLIENT_INFO_META_KEY]);\n if (found) return found;\n }\n return undefined;\n}\n\n/** The handshake's declaration, which neither peer puts on the handler's\n * context: both cache it on the server object. A server object reused for\n * a later connection reports the previous client until the new one\n * initializes. */\nfunction declaredOnConnection(server: unknown): DeclaredClientInfo | undefined {\n if (!server) return undefined;\n const inner = (server as { server?: unknown }).server;\n const holder = (inner ?? server) as {\n getClientVersion?: () => DeclaredClientInfo | undefined;\n };\n if (typeof holder.getClientVersion !== \"function\") return undefined;\n return declared(holder.getClientVersion());\n}\n\nfunction observedInfo(extra: Extra, options: ObserveClientOptions): ClientObserved[\"info\"] {\n // Both fields come from one source, so the pair is one the client sent.\n return cleanInfo(declaredOnRequest(extra) ?? declaredOnConnection(options.server), options.scrubber);\n}\n\nfunction cleanInfo(\n sent: DeclaredClientInfo | undefined,\n scrubber: ObserveClientOptions[\"scrubber\"],\n): ClientObserved[\"info\"] {\n const info: NonNullable<ClientObserved[\"info\"]> = {};\n const name = clean(sent?.name, scrubber, CLIENT_INFO_MAX_LEN);\n const version = clean(sent?.version, scrubber, CLIENT_INFO_MAX_LEN);\n if (name !== undefined) info.name = name;\n if (version !== undefined) info.version = version;\n return Object.keys(info).length > 0 ? info : undefined;\n}\n\nfunction cleanHeaders(\n sent: Headers | null | undefined,\n scrubber: ObserveClientOptions[\"scrubber\"],\n): ClientObserved[\"headers\"] {\n const headers: NonNullable<ClientObserved[\"headers\"]> = {};\n for (const header of OBSERVED_HEADERS) {\n const value = clean(sent?.get(header), scrubber, HEADER_VALUE_MAX_LEN);\n if (value !== undefined) headers[header] = value;\n }\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nfunction clean(\n value: unknown,\n scrubber: ObserveClientOptions[\"scrubber\"],\n max: number,\n): string | undefined {\n if (!hasText(value)) return undefined;\n const scrubbed = scrubOrNull<unknown>(scrubber, value, \"client_observed\");\n if (!hasText(scrubbed)) return undefined;\n return capCodePoints(scrubbed, max);\n}\n\n/** These read a third party's request and server objects, which may throw.\n * One failing read costs its own member, never the other or the call. */\nfunction orNothing<T>(read: () => T | undefined): T | undefined {\n try {\n return read();\n } catch {\n return undefined;\n }\n}\n\nfunction assemble(\n info: ClientObserved[\"info\"],\n headers: ClientObserved[\"headers\"],\n): ClientObserved | null {\n if (info === undefined && headers === undefined) return null;\n return { ...(info && { info }), ...(headers && { headers }) };\n}\n\n/** `null` when nothing was observed. */\nexport function observeClient(extra: Extra, options: ObserveClientOptions): ClientObserved | null {\n return assemble(\n orNothing(() => observedInfo(extra, options)),\n orNothing(() => cleanHeaders(extraHeaders(extra), options.scrubber)),\n );\n}\n\n/** Headers as a vendor's server framework holds them: a fetch `Headers`, or a\n * plain record such as Node's `req.headers`. */\nexport type HeaderInput = Headers | Record<string, string | readonly string[] | undefined>;\n\n/** Only the registered names are copied in, so a header the platform refuses\n * to hold cannot cost the ones we read. */\nfunction append(headers: Headers, name: string, value: string): void {\n try {\n headers.append(name, value);\n } catch {\n // A value Headers will not hold (a newline, a non-Latin-1 character) costs only itself.\n }\n}\n\nfunction registeredHeaders(input: HeaderInput): Headers {\n const out = new Headers();\n if (typeof (input as Headers).get === \"function\") {\n for (const name of OBSERVED_HEADERS) {\n const value: unknown = (input as Headers).get(name);\n if (typeof value === \"string\") append(out, name, value);\n }\n return out;\n }\n for (const [key, value] of Object.entries(input)) {\n const name = key.toLowerCase();\n if (!(OBSERVED_HEADERS as readonly string[]).includes(name)) continue;\n for (const line of typeof value === \"string\" ? [value] : Array.isArray(value) ? value : []) {\n if (typeof line === \"string\") append(out, name, line);\n }\n }\n return out;\n}\n\n/** The library path's `client_observed` (SPEC §5.6 rule 4): what the vendor's\n * code passed, under the same rules as what a client sends over MCP. A\n * declaration in the request's `_meta` wins over `clientInfo`, as the\n * request's own wins over the handshake's on MCP. */\nexport function clientObservedFrom(\n clientInfo: unknown,\n headers: HeaderInput | undefined,\n scrubber: ObserveClientOptions[\"scrubber\"],\n meta?: Record<string, unknown> | null,\n): ClientObserved | null {\n return assemble(\n orNothing(() => cleanInfo(declared(meta?.[CLIENT_INFO_META_KEY]) ?? declared(clientInfo), scrubber)),\n orNothing(() => (headers ? cleanHeaders(registeredHeaders(headers), scrubber) : undefined)),\n );\n}\n","import { stripWhiteSpace } from \"../../_text.js\";\nimport { uuid7 } from \"../../uuid7.js\";\nimport { extraHeaders, observeTransport, type Extra } from \"./mcpTypes.js\";\n\n/** A `session_id` with the envelope's `session_id_origin` (SPEC §11.4). The\n * rung that answered decides the origin, never the id's spelling. */\nexport interface ResolvedSession {\n sessionId: string;\n origin: \"observed\" | \"minted\";\n perCall: boolean;\n}\n\n/** SPEC §3.4 rungs 4 and 5. The header is read as well as `extra.sessionId`\n * because a stateless transport reports no id even when the client sends one.\n *\n * No vendor hook: an id the SDK did not mint must not key the session (the\n * join rule). What a vendor knows about a caller goes in `principal`. */\nexport async function resolveSessionId(\n fallbackSessionId: string,\n extra: Extra,\n): Promise<ResolvedSession> {\n if (typeof extra.sessionId === \"string\" && extra.sessionId) {\n return { sessionId: extra.sessionId, origin: \"observed\", perCall: false };\n }\n const fromHeader = sessionIdFromHeader(extra);\n if (fromHeader !== null) return { sessionId: fromHeader, origin: \"observed\", perCall: false };\n if (observeTransport(extra) === \"http\") {\n return { sessionId: `sdk-${uuid7()}`, origin: \"minted\", perCall: true };\n }\n return { sessionId: fallbackSessionId, origin: \"minted\", perCall: false };\n}\n\n/** Blank is a miss, as on the Python side: a whitespace-only id would file\n * every such call under one session. Never throws into the tool call. */\nfunction sessionIdFromHeader(extra: Extra): string | null {\n try {\n const value = extraHeaders(extra)?.get(\"mcp-session-id\");\n return value ? stripWhiteSpace(value) || null : null;\n } catch {\n return null;\n }\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/batch` 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\nimport { stripWhiteSpace } from \"./_text.js\";\nimport { warn } from \"./warn.js\";\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// NUL, LF and CR are what `new Headers` refuses, so a key holding one could\n// never be sent. The tab can be sent, but is refused because `baton` refuses\n// it anywhere in a DSN: a tab inside a key is a line wrap from copying, not\n// part of any minted key. Narrow on purpose otherwise: the tail's alphabet\n// belongs to the console's mint, and a parser stricter than the mint refuses\n// valid keys in the field.\n// eslint-disable-next-line no-control-regex\nconst NOT_IN_A_KEY = /[\\x00\\t\\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/** 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/batch` 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/batch` 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. */\nexport function 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 const dsn = typeof raw === \"string\" ? stripWhiteSpace(raw) : \"\";\n if (dsn === \"\") fail(\"dsn must be a non-empty string\");\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.\n fail(\n `dsn ${safe} has a tab, a line break or a null inside its key — no ` +\n `key from /account contains one, so this DSN could not have worked. ` +\n `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/batch` 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\nimport { capCodePoints, stripWhiteSpace } from \"../../_text.js\";\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 \"refused\",\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/** The handler never ran because code above it refused the call: a vendor's\n * wrapper on the `tools/call` handler, or an override of the SDK's\n * `executeToolHandler`. Its message is the vendor's, so `\"off\"` withholds it. */\nexport const REFUSED = \"refused\" satisfies FailureKind;\n\n/** What the SDK's own `validateToolInput` did with this call: never reached\n * (or replaced by something that skips the probe), accepted the arguments, or\n * rejected them. */\nexport type InputValidation = \"unseen\" | \"passed\" | \"rejected\";\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 * ⚠ **`invalid_argument` rests on positive evidence where the probe is\n * live**: `withBaton` wraps the SDK's `validateToolInput` and records a\n * rejection. `\"unseen\"` is the inference: the call stopped before validation,\n * which is a vendor's gate or one of 1.x's two task-mode checks, and\n * `TASK_MODES` keeps the second out of `refused`. A pre-validation rejection\n * either major adds later would be labelled `refused` with nothing going red.\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 `failure_kind` claim. */\n execution?: { taskSupport?: unknown } | null;\n}\n\nexport function requestSideFailureKind(\n entry: ToolEntryFacts | null | undefined,\n validation: InputValidation,\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 if (validation === \"rejected\") return \"invalid_argument\";\n if (TASK_MODES.has(entry.execution?.taskSupport)) return undefined;\n return REFUSED;\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 = stripWhiteSpace(text);\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/** The body members for a call that failed before the vendor's handler ran.\n * The SDK's own rejections are kept under `\"off\"`; a refusal is the vendor's\n * code speaking, so it is withheld like a tool's own failure.\n *\n * ⚠ PRECONDITION: call this ONLY from inside an `emit()` build thunk, as its\n * siblings above. */\nexport function requestSideFailureFields(\n kind: FailureKind | undefined,\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 return kind === REFUSED\n ? resultDerivedFields(mode, text, result ?? null, errorBody, scrubber)\n : requestSideErrorFields(text(), errorBody);\n}\n\n/** `error_type` for a thrown value: its class name, or `\"Error\"` for a non-Error. */\nexport function 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. */\nexport function messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Scrub the whole text, then cut it: cutting first could split a secret so\n * no pattern matches the half that ships. Call only inside an emit() build\n * thunk, where a scrubber throw drops the event. */\nexport function scrubbedErrorBody(scrubber: (value: unknown) => unknown, text: string): string {\n // eslint-disable-next-line no-restricted-syntax -- callers are emit() build thunks\n return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);\n}\n","/** Capture settings read from the collector (SPEC §2.6): fetch, match, apply.\n * The TypeScript half of Python's `_capture_settings.py`. */\n\nimport * as crypto from \"node:crypto\";\nimport { isRecord } from \"../../_object.js\";\nimport type { CaptureObserved } from \"../../events.js\";\nimport { globalFetch } from \"../../runtime.js\";\nimport { warn } from \"../../warn.js\";\nimport { RESULT_CAPTURE_MODES, type ResultCaptureMode } from \"./errorResult.js\";\nimport type { IntentParamMode } from \"./schemaCompat.js\";\n\nexport const SETTINGS_PATH = \"/v0/settings\";\nexport const TENANT_HEADER = \"X-Baton-Tenant-Id\";\nexport const SETTINGS_MODES = [\"local\", \"console\"] as const;\nexport type SettingsMode = (typeof SETTINGS_MODES)[number];\nexport const DEFAULT_SETTINGS_REFRESH_MS = 60_000;\nexport const MIN_SETTINGS_REFRESH_MS = 15_000;\nconst REQUEST_TIMEOUT_MS = 10_000;\n\nexport type ReportMode = \"on\" | \"off\";\nconst MATCH_KEYS: ReadonlySet<string> = new Set([\"label\", \"client\", \"share\"]);\n// Shared with the config check, so a mode the config takes is one a document can set.\nexport const INTENT_PARAM_MODES: ReadonlySet<string> = new Set([\"optional\", \"required\"]);\nexport const REPORT_MODES: ReadonlySet<string> = new Set([\"on\", \"off\"]);\n// Derived from the registry, so no mode is accepted that the emitter has no payload shape for.\nexport const RESULT_CAPTURE_MODE_SET: ReadonlySet<string> = new Set(RESULT_CAPTURE_MODES);\n\n/** What a `match` rule can see about one request. */\nexport interface Caller {\n labels: readonly string[];\n clientName: string | null;\n shareKey: string | null;\n}\n\n/** The settings one call runs under. An unset mode means the config's value. */\nexport interface CallSettings {\n capture: CaptureObserved;\n resultCaptureMode?: ResultCaptureMode;\n intentParamMode?: IntentParamMode;\n reportMode?: ReportMode;\n}\n\nexport function shareBucket(vendorId: string, key: string): number {\n const digest = crypto.createHash(\"sha256\").update(`${vendorId}\\n${key}`, \"utf-8\").digest();\n return Number(digest.readBigUInt64BE(0) % 10000n);\n}\n\n/** One audience, its `match` checked once when the document is read. */\ninterface Audience {\n settings: CallSettings;\n labels: ReadonlySet<string> | null;\n clients: ReadonlySet<string> | null;\n shareThreshold: number | null;\n}\n\nfunction matchesEveryone(audience: Audience): boolean {\n return audience.labels === null && audience.clients === null && audience.shareThreshold === null;\n}\n\nfunction matches(audience: Audience, caller: Caller, bucket: number | null): boolean {\n if (audience.labels !== null && !caller.labels.some((label) => audience.labels!.has(label))) return false;\n if (audience.clients !== null && (caller.clientName === null || !audience.clients.has(caller.clientName))) {\n return false;\n }\n if (audience.shareThreshold !== null && (bucket === null || bucket >= audience.shareThreshold)) return false;\n return true;\n}\n\nexport class SettingsDocument {\n private readonly usesShare: boolean;\n private readonly unmatched: CallSettings;\n /** Whether some caller can get reports, so the instructions point to the\n * tool. Read only where the code's value is \"on\": no tool exists otherwise. */\n readonly reportsOnForAnyone: boolean;\n\n constructor(\n readonly version: number,\n private readonly audiences: readonly Audience[],\n ) {\n this.usesShare = audiences.some((a) => a.shareThreshold !== null);\n this.unmatched = { capture: { settings_version: version } };\n // With no catch-all audience, a caller can fall through to the code's value.\n this.reportsOnForAnyone =\n audiences.some((a) => a.settings.reportMode !== \"off\") || !audiences.some(matchesEveryone);\n }\n\n settingsFor(caller: Caller, vendorId: string): CallSettings {\n const bucket = caller.shareKey !== null && this.usesShare ? shareBucket(vendorId, caller.shareKey) : null;\n return this.audiences.find((audience) => matches(audience, caller, bucket))?.settings ?? this.unmatched;\n }\n\n}\n\nfunction stringSet(value: unknown): ReadonlySet<string> | null {\n if (!Array.isArray(value) || !value.every((v) => typeof v === \"string\")) return null;\n return new Set(value);\n}\n\n/** `null` for an audience that can match nobody (SPEC §2.6). */\nfunction readAudience(\n version: number,\n id: string,\n match: Record<string, unknown>,\n capture: Record<string, unknown>,\n): Audience | null {\n if (!Object.keys(match).every((key) => MATCH_KEYS.has(key))) return null;\n let labels: ReadonlySet<string> | null = null;\n let clients: ReadonlySet<string> | null = null;\n let shareThreshold: number | null = null;\n if (Object.hasOwn(match, \"label\") && (labels = stringSet(match.label)) === null) return null;\n if (Object.hasOwn(match, \"client\") && (clients = stringSet(match.client)) === null) return null;\n if (Object.hasOwn(match, \"share\")) {\n const share = match.share;\n if (typeof share !== \"number\" || !(share > 0 && share <= 1)) return null;\n // SPEC §2.6's formula, pinned by \"a half rounds up\".\n shareThreshold = Math.floor(share * 10000 + 0.5);\n }\n const settings: CallSettings = { capture: { settings_version: version, audience: id } };\n const { results, goal, reports } = capture;\n if (typeof results === \"string\" && RESULT_CAPTURE_MODE_SET.has(results)) {\n settings.resultCaptureMode = results as ResultCaptureMode;\n }\n if (typeof goal === \"string\" && INTENT_PARAM_MODES.has(goal)) settings.intentParamMode = goal as IntentParamMode;\n if (typeof reports === \"string\" && REPORT_MODES.has(reports)) settings.reportMode = reports as ReportMode;\n return { settings, labels, clients, shareThreshold };\n}\n\n/** The document in `body`, or `null` when it is not a valid one (SPEC §2.6). */\nexport function parseDocument(body: string): SettingsDocument | null {\n let data: unknown;\n try {\n data = JSON.parse(body);\n } catch {\n return null;\n }\n if (!isRecord(data)) return null;\n const { version, audiences } = data;\n if (typeof version !== \"number\" || !Number.isInteger(version) || version < 1) return null;\n if (!Array.isArray(audiences) || audiences.length === 0) return null;\n const parsed: Audience[] = [];\n for (const audience of audiences) {\n if (!isRecord(audience)) return null;\n const { id, match, capture } = audience;\n if (typeof id !== \"string\" || !isRecord(match) || !isRecord(capture)) return null;\n const readable = readAudience(version, id, match, capture);\n if (readable !== null) parsed.push(readable);\n }\n return new SettingsDocument(version, parsed);\n}\n\n/** Where `CaptureSettings` gets its document: the fetcher, or a test's stand-in. */\nexport interface SettingsSource {\n readonly document: SettingsDocument | null;\n start(): void;\n stop(): void;\n}\n\nexport interface SettingsFetcherOptions {\n origin: string;\n apiKey: string;\n tenantId: string;\n vendorId: string;\n refreshMs: number;\n /** Injectable for tests; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n}\n\n/** Reads the document in the background and holds the last good one. A call\n * never waits on it. */\nexport class SettingsFetcher implements SettingsSource {\n private readonly url: string;\n // `#`, not `private`, so logging a config shows no key: \"logging the config shows no key\".\n readonly #headers: Record<string, string>;\n private readonly refreshMs: number;\n private readonly fetchImpl: typeof fetch;\n private etag: string | null = null;\n private held: SettingsDocument | null = null;\n private timer: ReturnType<typeof setInterval> | null = null;\n private reading: AbortController | null = null;\n private warned = false;\n\n constructor(options: SettingsFetcherOptions) {\n this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;\n this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };\n this.refreshMs = options.refreshMs;\n this.fetchImpl = options.fetchImpl ?? globalFetch;\n }\n\n get document(): SettingsDocument | null {\n return this.held;\n }\n\n start(): void {\n if (this.timer !== null) return;\n this.timer = setInterval(() => void this.readOnce(), this.refreshMs);\n // The read must not keep a vendor's process alive.\n (this.timer as { unref?: () => void }).unref?.();\n void this.readOnce();\n }\n\n stop(): void {\n if (this.timer !== null) clearInterval(this.timer);\n this.timer = null;\n this.reading?.abort();\n this.reading = null;\n }\n\n /** One request. Never rejects: a failure keeps what is held. */\n async readOnce(): Promise<void> {\n if (this.reading !== null) return;\n const reading = new AbortController();\n this.reading = reading;\n const timeout = setTimeout(() => reading.abort(), REQUEST_TIMEOUT_MS);\n (timeout as { unref?: () => void }).unref?.();\n try {\n await this.read(reading.signal);\n } catch {\n // Kept quiet: the collector being down must not fill the vendor's logs.\n } finally {\n clearTimeout(timeout);\n if (this.reading === reading) this.reading = null;\n }\n }\n\n private async read(signal: AbortSignal): Promise<void> {\n const headers = this.etag === null ? this.#headers : { ...this.#headers, \"If-None-Match\": this.etag };\n const response = await this.fetchImpl(this.url, { method: \"GET\", headers, redirect: \"manual\", signal });\n if (response.status !== 200) {\n // An unread body holds its connection until GC.\n void response.body?.cancel().catch(() => undefined);\n }\n // An answer that lands after `stop()` is dropped.\n if (signal.aborted) return;\n if (response.status === 204) {\n this.held = null;\n this.etag = null;\n } else if (response.status === 200) {\n const document = parseDocument(await response.text());\n if (signal.aborted) return;\n if (document === null) {\n if (!this.warned) {\n this.warned = true;\n warn(\"baton: the collector sent capture settings this SDK cannot read\");\n }\n return;\n }\n this.held = document;\n this.etag = response.headers.get(\"etag\");\n }\n }\n}\n\n/** Per-call settings from the matched audience (SPEC §2.6). */\nexport class CaptureSettings {\n constructor(\n private readonly vendorId: string,\n private readonly source: SettingsSource,\n ) {}\n\n start(): void {\n this.source.start();\n }\n\n stop(): void {\n this.source.stop();\n }\n\n get document(): SettingsDocument | null {\n return this.source.document;\n }\n\n /** `undefined` while no document is held, and the config's values apply. */\n forCaller(caller: Caller): CallSettings | undefined {\n return this.document?.settingsFor(caller, this.vendorId);\n }\n}\n","/**\n * `BatonConfig` — vendor-side configuration for `withBaton`. A trimmed\n * mirror of `baton` (Python)'s `integrations/_config.py::VendorConfig`.\n */\n\nimport { dsnFromEnvironment, 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 { MAX_TIMER_MS } from \"../../deadline.js\";\nimport { RESULT_CAPTURE_MODES, type ResultCaptureMode } from \"./errorResult.js\";\nimport { onWorkers } from \"../../runtime.js\";\nimport { HttpSink, type Sink } from \"../../sinks.js\";\nimport { warn } from \"../../warn.js\";\nimport {\n CaptureSettings,\n DEFAULT_SETTINGS_REFRESH_MS,\n INTENT_PARAM_MODES,\n MIN_SETTINGS_REFRESH_MS,\n REPORT_MODES,\n RESULT_CAPTURE_MODE_SET,\n SETTINGS_MODES,\n SettingsFetcher,\n type SettingsMode,\n} from \"./captureSettings.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\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. With no DSN, `tenantId` or sink\n * either, the install adds nothing instead (SPEC §11.2 rule 10). */\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 * under `reportMode: \"on\"`, and unused otherwise. */\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 to `\"customer-consented\"`, so the customer never has to carry\n * it.** The field stays on the wire: SPEC §2.3 governs the envelope, not the\n * config.\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. With a `vendorId` and no DSN, defaults to `new StdoutSink()`. */\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. Has no effect unless\n * `reportMode: \"on\"`, and warns if set without it. */\n annotationToolName?: string;\n /** Whether the agent is given a tool to report a call that went wrong.\n * Unset, it is `\"on\"` with `settings: \"console\"` and `\"off\"` otherwise.\n * `\"off\"` registers no annotation tool, and Baton's server\n * instructions are `INTENT_INSTRUCTIONS` alone, below your own. Each call's\n * goal still arrives through `user_goal`. `\"on\"` registers the tool and\n * serves its instructions. */\n reportMode?: \"on\" | \"off\";\n /** Where capture settings come from. `\"local\"` (default): the values in\n * this config, and Baton is never asked. `\"console\"`: the settings saved on\n * the Console's Capture page, read from the collector every\n * `settingsRefreshMs`, so they can differ by label, client or a share of\n * callers (SPEC §2.6). Needs a `dsn`. Until the first read succeeds, and\n * whenever nothing is saved, this config's values apply. A read never\n * delays startup or a call.\n *\n * `results` (`resultCaptureMode`) is applied per call. `goal`\n * (`intentParamMode`) and `reports` (`reportMode`) are applied per\n * `tools/list`. With `reportMode: \"off\"` no annotation tool is registered,\n * so the Console can hide reports from some callers only when they are on\n * here. */\n settings?: SettingsMode;\n /** How often `settings: \"console\"` reads the saved settings, in\n * milliseconds. Default 60000, at least 15000. */\n settingsRefreshMs?: number;\n /** Per-tool intent-param injection (mirrors baton-extmcp's vendor-neutral\n * naming). `\"required\"` (default) injects a `user_goal` string param on\n * every wrapped tool's advertised schema and ADVERTISES it as required in\n * `tools/list`, without enforcing it: a call that omits it still reaches\n * your handler, and its event simply carries no intent. `\"optional\"` injects\n * the same param and does not advertise it as required. There is no\n * `\"off\"`: nothing else would capture what the user is trying to do. The param is stripped before the vendor\n * handler runs, so the tool never sees it.\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\";\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 withheld too (SPEC\n * §11.4.3): the MCP SDK has no tool-error class to mark one public.\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, on the annotation tool, on every\n * `tools/list` request and on every resource and prompt request, with an\n * adapter-neutral\n * {@link PrincipalResolutionContext}: headers folded to ONE case-insensitive\n * shape across both SDK majors, the request's `_meta`, the tool name, and\n * the arguments the vendor's own handler will see. On a request that is not\n * a tool call the tool name is `null` and the arguments are empty. Return a `Principal`,\n * 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 request: a hook that throws or returns junk yields an\n * anonymous one. A hook that has not answered after 5 seconds is given up\n * on, and that request is anonymous. ⚠ That only bounds an async hook: one that\n * blocks synchronously holds the whole process, and nothing can interrupt it.\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 /** A low-level `Server`'s tools, as its `tools/list` answers them, or a\n * function that returns them. Read once per `withBaton` or `createBaton`.\n * Without it Baton learns the tools from the lists its servers serve, so a\n * process that has served none yet, such as a fresh worker, takes\n * `user_goal` off every call, even from a tool that declares its own. An\n * `McpServer` does not read it. */\n tools?: readonly unknown[] | (() => readonly unknown[]);\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 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\nconst STAND_IN_VENDOR_ID = \"unset\";\n\n/**\n * `resolveBatonConfig` for an install, and whether nothing says where events\n * go: no DSN, no `vendorId`, no `tenantId` and no sink (SPEC §11.2 rule 10).\n * `BATON_TENANT_ID` does not count, so a stale one cannot stop a server. Then\n * the config gets a stand-in identity, so every check still runs.\n */\nexport function resolveInstallConfig(config: BatonConfig): {\n resolved: ResolvedBatonConfig;\n unconfigured: boolean;\n} {\n const unconfigured =\n !config.dsn &&\n dsnFromEnvironment() === undefined &&\n !config.vendorId &&\n !config.tenantId &&\n config.sink === undefined;\n const resolved = resolveBatonConfig(\n unconfigured\n ? {\n ...config,\n vendorId: STAND_IN_VENDOR_ID,\n vendorDisplayName: config.vendorDisplayName ?? STAND_IN_VENDOR_ID,\n }\n : config,\n );\n return { resolved, unconfigured };\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 consentToken: string;\n /** Not yet reading; set only under `settings: \"console\"`. */\n captureSettings?: CaptureSettings;\n}\n\nlet consoleOffWarned = false;\n\n/** A Worker cannot keep reading the settings in the background, so there\n * `settings: \"console\"` is dropped and this config's capture values apply.\n * The report tool it turns on stays on. */\nfunction withoutConsoleOnWorkers(config: BatonConfig): BatonConfig {\n if (config.settings !== \"console\" || !onWorkers()) return config;\n if (!consoleOffWarned) {\n consoleOffWarned = true;\n warn('baton: settings: \"console\" is not supported on Cloudflare Workers yet; the Console\\'s settings are not read and this config\\'s capture values apply.');\n }\n const rest: BatonConfig = { ...config, reportMode: config.reportMode ?? \"on\" };\n delete rest.settings;\n return rest;\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 the settings read under `settings: \"console\"`, 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 * Knows nothing about the server being wrapped. The one field that depends on\n * it, the display name, is finished by `withServerDisplayName`.\n */\nexport function resolveBatonConfig(supplied: BatonConfig): ResolvedBatonConfig {\n const dsnString = selectDsn(\n supplied.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(supplied.vendorId),\n tenantId: supplied.tenantId !== undefined,\n sink: supplied.sink !== undefined,\n },\n \"BatonConfig\",\n );\n // Without a dsn, `settings: \"console\"` is refused below, on Workers too.\n const config = dsnString === undefined ? supplied : withoutConsoleOnWorkers(supplied);\n\n if (dsnString === undefined) {\n const defaulted: BatonConfig = {\n ...config,\n consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN,\n };\n validateBatonConfig(defaulted);\n if (defaulted.settings === \"console\") {\n throw new Error(\n 'BatonConfig.settings: \"console\" reads the Capture page with the dsn\\'s key, so it needs a dsn.',\n );\n }\n return defaulted;\n }\n\n const dsn = parseDsn(dsnString);\n // The packed string is DELETED rather than overwritten with `undefined`:\n // `exactOptionalPropertyTypes` refuses the latter, and dropping the property\n // is what is wanted anyway — see the note above about not keeping the\n // bearer on an object that outlives this call.\n const rest: BatonConfig = { ...config };\n delete rest.dsn;\n const identity: BatonConfig = {\n ...rest,\n vendorId: dsn.vendorId,\n tenantId: dsn.tenantId,\n // `??`, for the same reason as `consentToken` directly below, and the\n // inconsistency was worth fixing rather than mirroring: with no dsn,\n // `vendorDisplayName: \"\"` is REFUSED by validation; with one, `||` quietly\n // substituted the server slug. One input, two answers, decided by whether\n // a dsn happens to be present — and this string reaches the calling agent\n // in the server instructions and the annotation tool description, which is\n // the whitelabel obligation the validator cites when it refuses the empty\n // one. ⚠ Python uses `or` here and still has the inconsistency.\n vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,\n // `??`, not `||`: an explicit empty string must survive to the validation\n // below and be REFUSED there, rather than be quietly replaced by the\n // default it was deliberately not left as.\n consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN,\n ...(config.reportMode === undefined && config.settings === \"console\" ? { reportMode: \"on\" as const } : {}),\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 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/batch`\n // itself, exactly as it does for an explicitly-constructed sink.\n sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),\n ...(identity.settings === \"console\"\n ? {\n captureSettings: new CaptureSettings(\n dsn.vendorId,\n new SettingsFetcher({\n origin: dsn.origin,\n apiKey: dsn.key,\n tenantId: dsn.tenantId,\n vendorId: dsn.vendorId,\n refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS,\n }),\n ),\n }\n : {}),\n };\n}\n\n/** Between an explicit display name and the DSN's server segment sits the\n * server's own name: the segment is an opaque `srv-<8 hex>`, and it was what\n * agents were told the vendor is called. `serverName` is already through\n * `usableServerName`, so `undefined` when there is none to use. */\nexport function withServerDisplayName(\n resolved: ResolvedBatonConfig,\n supplied: BatonConfig,\n serverName: string | undefined,\n): ResolvedBatonConfig {\n if (supplied.vendorDisplayName !== undefined) return resolved;\n const fromServer = displayNameFromServer(serverName, {\n vendorId: resolved.vendorId,\n annotationToolName: supplied.annotationToolName,\n });\n return fromServer === undefined ? resolved : { ...resolved, vendorDisplayName: fromServer };\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.reportMode !== undefined && !REPORT_MODES.has(config.reportMode)) {\n throw new Error(\n `BatonConfig.reportMode ${JSON.stringify(config.reportMode)} must be one of ` +\n `${JSON.stringify([...REPORT_MODES].sort())}.`,\n );\n }\n if (!config.vendorDisplayName && config.reportMode === \"on\") {\n throw new Error(\n \"BatonConfig needs a vendorDisplayName with reportMode: \\\"on\\\" — used in server \" +\n \"instructions 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 as string | undefined) === \"off\") {\n throw new Error(\n 'BatonConfig.intentParamMode: \"off\" would leave nothing capturing what the user is ' +\n 'trying to do. Use \"required\" (the default) or \"optional\".',\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.settings !== undefined && !(SETTINGS_MODES as readonly string[]).includes(config.settings)) {\n throw new Error(\n `BatonConfig.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`,\n );\n }\n const refresh: unknown = config.settingsRefreshMs;\n if (\n refresh !== undefined &&\n (typeof refresh !== \"number\" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))\n ) {\n throw new Error(\n `BatonConfig.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} ` +\n `to ${String(MAX_TIMER_MS)}.`,\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 (config.tools !== undefined && !Array.isArray(config.tools) && typeof config.tools !== \"function\") {\n throw new Error(\"BatonConfig.tools must be an array of tools or a function that returns one.\");\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 and remains unbuilt, so no\n * vendor-facing wording may imply otherwise.\n */\n\nimport { stripWhiteSpace } from \"./_text.js\";\nimport type { Sink } from \"./sinks.js\";\nimport { warn } from \"./warn.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(stripWhiteSpace(value).toLowerCase())) {\n return SWITCH;\n }\n return null;\n}\n\n/**\n * Say so once, on stderr, never on stdout.\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 warn(\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/** SPEC §11.2 rule 10. */\nexport function logUnconfigured(surface: string): void {\n warn(`baton: no DSN (dsn or BATON_DSN), so ${surface} installed nothing and records nothing`);\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","// Multi-round-trip requests (protocol revision 2026-07-28): a paused round sends\n// no terminal event and a resumed round no start, so the rounds are one call.\n\nimport { isRecord } from \"../../_object.js\";\nimport type { Extra } from \"./mcpTypes.js\";\n\n/** Guarded like `isErrorResult`: it reads the vendor's result on the call path. */\nexport function isInputRequired(result: unknown): boolean {\n try {\n return isRecord(result) && result.resultType === \"input_required\";\n } catch {\n return false;\n }\n}\n\n/** `requestState` is an accessor the SDK sets on every request, so its value\n * is read, not its presence. */\nexport function resumesPausedCall(extra: Extra | undefined): boolean {\n try {\n const req = extra?.mcpReq;\n if (req === undefined) return false;\n return req.inputResponses !== undefined || req.requestState?.() !== undefined;\n } catch {\n return false;\n }\n}\n","import { boundedSinkCall, 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 /** The sink the vendor passed, or the default one. */\n readonly sink: Sink;\n readonly #queue: Sink;\n readonly vendorId: string;\n /** The install's own session id: what stdio and in-memory calls, and the\n * surface snapshot, carry when no session id resolves. A call over HTTP\n * with no session to read gets a per-request id instead (SPEC §3.4 rung 5). */\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 /** What Baton writes to, in front of `sink`. */\n queue?: Sink;\n vendorId: string;\n sessionId: string;\n annotationToolName: string;\n }) {\n this.sink = options.sink;\n this.#queue = options.queue ?? 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. Never rejects; returns within\n * the shutdown budget (SPEC §11.2 rule 7). */\n async flush(): Promise<void> {\n await boundedSinkCall(this.#queue, \"flush\");\n }\n\n /** Flush and release sink resources, on the same terms as `flush()`. */\n async aclose(): Promise<void> {\n await boundedSinkCall(this.#queue, \"aclose\");\n }\n}\n","/** The tool list and instructions under the Console's per-caller settings\n * (SPEC §2.6). The TypeScript half of Python's `_per_caller.py`. */\n\nimport { printable, stderrLine } from \"../../warn.js\";\nimport type { CaptureSettings } from \"./captureSettings.js\";\nimport { INTENT_INSTRUCTIONS, USER_GOAL_PARAM_NAME, buildUserGoalParamDescription } from \"./llmText.js\";\nimport type { ResolvedCaller } from \"./principalResolution.js\";\nimport type { IntentParamMode } from \"./schemaCompat.js\";\n\nexport interface PerCallerOptions {\n settings: CaptureSettings;\n intentParamMode: IntentParamMode;\n /** `\"\"` under `reportMode: \"off\"`. */\n annotationToolName: string;\n /** Ours, with the report pointer. */\n instructions: string;\n writeInstructions: (ours: string) => void;\n /** Whether this tool's `user_goal` is Baton's; a tool's own is left alone. */\n injectsGoal: (toolName: string) => boolean;\n}\n\n/** Rewrites each `tools/list` result for its caller, and keeps the\n * instructions' report pointer while some audience has reports on. */\nexport class PerCallerSurface {\n private pointerOn = true;\n\n constructor(private readonly options: PerCallerOptions) {}\n\n /** Called at install and on every request; writes only when the report\n * pointer should change. */\n followSettings(): void {\n if (this.options.annotationToolName === \"\") return;\n try {\n const document = this.options.settings.document;\n const pointerOn = document === null || document.reportsOnForAnyone;\n if (pointerOn === this.pointerOn) return;\n this.options.writeInstructions(pointerOn ? this.options.instructions : INTENT_INSTRUCTIONS);\n this.pointerOn = pointerOn;\n } catch (err) {\n stderrLine(`baton: could not update the server instructions for new settings: ${printable(err)}`);\n }\n }\n\n /** `result` with the caller's goal and reports settings; as served on any failure. */\n toolsFor(result: unknown, caller: ResolvedCaller): unknown {\n const settings = caller.settings;\n if (settings === undefined) return result;\n const { intentParamMode, annotationToolName, injectsGoal } = this.options;\n const goal = settings.intentParamMode ?? intentParamMode;\n const hideReports = annotationToolName !== \"\" && settings.reportMode === \"off\";\n if (goal === intentParamMode && !hideReports) return result;\n try {\n const tools = (result as { tools?: unknown } | null | undefined)?.tools;\n if (!Array.isArray(tools)) return result;\n const served: unknown[] = [];\n for (const tool of tools) {\n const name = (tool as { name?: unknown } | null)?.name;\n if (hideReports && name === annotationToolName) continue;\n const rewrite = goal !== intentParamMode && typeof name === \"string\" && injectsGoal(name);\n served.push(rewrite ? withGoalMode(tool, goal) : tool);\n }\n return { ...(result as Record<string, unknown>), tools: served };\n } catch (err) {\n stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);\n return result;\n }\n }\n}\n\n/** A copy of `tool` whose `user_goal` reads and is listed as `goal` says. */\nfunction withGoalMode(tool: unknown, goal: IntentParamMode): unknown {\n const entry = tool as { inputSchema?: unknown };\n const schema = entry.inputSchema as { properties?: unknown; required?: unknown } | null | undefined;\n const properties = schema?.properties as Record<string, unknown> | null | undefined;\n const param = properties?.[USER_GOAL_PARAM_NAME];\n if (typeof param !== \"object\" || param === null) return tool;\n const others = Array.isArray(schema!.required)\n ? (schema!.required as unknown[]).filter((name) => name !== USER_GOAL_PARAM_NAME)\n : [];\n const required = goal === \"required\" ? [...others, USER_GOAL_PARAM_NAME] : others;\n return {\n ...entry,\n inputSchema: {\n ...schema,\n properties: {\n ...properties,\n [USER_GOAL_PARAM_NAME]: { ...param, description: buildUserGoalParamDescription({ intentParamMode: goal }) },\n },\n ...(required.length > 0 || Array.isArray(schema!.required) ? { required } : {}),\n },\n };\n}\n","import { nextClockSequence, nowMicros } from \"../../sequence.js\";\n\nexport const SESSION_CAP = 4096;\n\n/** Per-session sequence numbers (SPEC §11.2 rule 5), for the\n * `SESSION_CAP` most recently used sessions. A minted session counts from 1;\n * an observed one is also at least the clock in µs, so its numbers still rise\n * after it is forgotten. */\nexport class SessionCounter {\n private readonly counters = new Map<string, number>();\n\n /** A per-call session is numbered by the clock: a counter would fill with\n * sessions that never come back and push out live ones. */\n nextFor(session: { sessionId: string; origin: \"observed\" | \"minted\"; perCall: boolean }): number {\n return session.perCall ? nextClockSequence() : this.next(session.sessionId, session.origin === \"observed\");\n }\n\n next(sessionId: string, observed: boolean): number {\n const previous = this.counters.get(sessionId) ?? 0;\n const next = observed ? Math.max(previous + 1, nowMicros()) : previous + 1;\n this.counters.delete(sessionId);\n this.counters.set(sessionId, next);\n if (this.counters.size > SESSION_CAP) this.counters.delete(this.counters.keys().next().value as string);\n return next;\n }\n}\n\n/** One server's counter: its own fallback session is numbered here, so the entry\n * goes with the server; every other session through the Baton's shared counter. */\nexport class ServerCounter extends SessionCounter {\n private ownSequence = 0;\n\n constructor(\n private readonly shared: SessionCounter,\n private readonly ownSessionId: string,\n ) {\n super();\n }\n\n override next(sessionId: string, observed: boolean): number {\n return sessionId === this.ownSessionId ? ++this.ownSequence : this.shared.next(sessionId, observed);\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 * as crypto from \"node:crypto\";\n\nexport function surfaceHash(surface: unknown): string {\n const canonical = canonicalJson(surface);\n const digest = crypto.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((v) => (v === undefined ? \"null\" : canonicalJson(v))).join(\",\")}]`;\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record)\n .filter((k) => record[k] !== undefined)\n .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\nexport const SENT_SURFACES_CAP = 256;\n\n/** The last `SENT_SURFACES_CAP` surface hashes sent, least recent dropped\n * first. Bounded because a tool list that differs per caller would otherwise\n * grow it for the life of the process; a dropped hash is only sent again. */\nexport class SentSurfaces {\n private readonly hashes = new Set<string>();\n\n wasSent(digest: string): boolean {\n if (!this.hashes.has(digest)) return false;\n this.hashes.delete(digest);\n this.hashes.add(digest);\n return true;\n }\n\n mark(digest: string): void {\n this.hashes.add(digest);\n if (this.hashes.size > SENT_SURFACES_CAP) {\n this.hashes.delete(this.hashes.values().next().value as string);\n }\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. */\nexport function buildSeamAugmentations(options: {\n injectedToolNames: string[];\n intentParamNames: string[];\n intentParamMode: \"optional\" | \"required\";\n requiredParamNames: string[];\n /** Whether Baton's text reached the served instructions; `null` when the\n * producer cannot tell. */\n instructionsSuffix: boolean | null;\n}): Record<string, unknown> {\n return {\n injected_tools: [...options.injectedToolNames].sort(),\n intent_param: {\n names: [...options.intentParamNames].sort(),\n required_names: [...options.requiredParamNames].sort(),\n mode: options.intentParamMode,\n },\n instructions_suffix: options.instructionsSuffix,\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 } from \"../../identity.js\";\nimport { isBlank } from \"../../_text.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. */\nfunction stringClaim(claims: Record<string, unknown>, name: string): string | null {\n const value = claims[name];\n return typeof value === \"string\" && !isBlank(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","/** The library API's session block and sequence numbers (SPEC §5.6). */\n\nimport * as asyncHooks from \"node:async_hooks\";\nimport {\n NO_CALLER,\n callerFor,\n wireLabels,\n type OrganizationWire,\n type PrincipalWire,\n} from \"../identity.js\";\nimport {\n clientObservedFrom,\n type ClientObserved,\n type HeaderInput,\n} from \"../integrations/mcp/clientObserved.js\";\nimport { roundMetaCoordinates } from \"../metaCoordinates.js\";\nimport { scrubOrNull } from \"../integrations/mcp/safeScrub.js\";\nimport { uuid7 } from \"../uuid7.js\";\nimport { isRecord } from \"../_object.js\";\nimport { stripWhiteSpace } from \"../_text.js\";\nimport { stderrLine } from \"../warn.js\";\n\nconst TRANSPORT_LIBRARY = \"library\";\nconst TURN_ID_META_KEY = \"baton/turn_id\";\n\n/** What `client.session(...)` gives every call inside it. */\nexport interface LibrarySession {\n readonly sessionId: string;\n readonly origin: \"observed\" | \"minted\";\n readonly principal: PrincipalWire | null;\n readonly organization: OrganizationWire | null;\n readonly labels: readonly string[];\n readonly clientObserved: ClientObserved | null;\n readonly runtimeMeta: Record<string, unknown> | null;\n}\n\nexport function sessionEnvelope(session: LibrarySession): Record<string, unknown> {\n return {\n session_id: session.sessionId,\n session_id_origin: session.origin,\n transport_observed: TRANSPORT_LIBRARY,\n principal: session.principal,\n organization: session.organization,\n labels: wireLabels(session.labels),\n client_observed: session.clientObserved,\n runtime_meta: session.runtimeMeta,\n };\n}\n\nexport interface SessionValues {\n sessionId?: string;\n principal?: unknown;\n clientInfo?: { name?: string; version?: string };\n headers?: HeaderInput;\n turnId?: string;\n meta?: unknown;\n}\n\nfunction warn(message: string): void {\n stderrLine(`baton: ${message}`);\n}\n\nfunction vendorId(name: string, value: unknown): string | null {\n const cleaned = typeof value === \"string\" ? stripWhiteSpace(value) : \"\";\n if (cleaned !== \"\") return cleaned;\n if (value !== undefined && value !== null) {\n warn(`${name} is not a non-blank string — ignoring it.`);\n }\n return null;\n}\n\nfunction blank(sessionId: string, origin: LibrarySession[\"origin\"]): LibrarySession {\n return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };\n}\n\nfunction requestMeta(meta: unknown): Record<string, unknown> | null {\n if (isRecord(meta)) return meta;\n if (meta !== undefined && meta !== null) warn(\"meta is not an object — ignoring it.\");\n return null;\n}\n\nfunction runtimeMeta(\n meta: Record<string, unknown> | null,\n turnId: string | null,\n scrubber: (value: unknown) => unknown,\n): Record<string, unknown> | null {\n // A client could send its own `baton/turn_id`; on a library event that key\n // is the vendor's (SPEC §11.4.1), so the client's copy never rides.\n const clientKeys = Object.fromEntries(Object.entries(meta ?? {}).filter(([key]) => key !== TURN_ID_META_KEY));\n const cleaned =\n Object.keys(clientKeys).length > 0 ? scrubOrNull(scrubber, roundMetaCoordinates(clientKeys), \"_meta\") : null;\n const out: Record<string, unknown> = isRecord(cleaned) ? { ...cleaned } : {};\n if (turnId !== null) out[TURN_ID_META_KEY] = turnId;\n return Object.keys(out).length > 0 ? out : null;\n}\n\n/** A `session()` block's values. A value that is not usable is logged and dropped. */\nexport function newSession(\n values: SessionValues,\n scrubber: (value: unknown) => unknown,\n disabled: boolean,\n): LibrarySession {\n const id = vendorId(\"sessionId\", values.sessionId);\n const base = id !== null ? blank(id, \"observed\") : blank(uuid7(), \"minted\");\n // Off stops the work too: no scrubber runs on a value that is never sent.\n if (disabled) return base;\n const meta = requestMeta(values.meta);\n return {\n ...base,\n ...callerFor(values.principal, (_key, message) => warn(`principal ${message}`)),\n clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber, meta),\n runtimeMeta: runtimeMeta(meta, vendorId(\"turnId\", values.turnId), scrubber),\n };\n}\n\n// The owning client is stored with the block so one client's block never\n// reaches another client's events.\nconst current = new asyncHooks.AsyncLocalStorage<{ owner: object; session: LibrarySession }>();\n\nexport function runInSession<T>(owner: object, session: LibrarySession, fn: () => T): T {\n return current.run({ owner, session }, fn);\n}\n\n/** `owner`'s open block, or a minted session for this call alone. */\nexport function sessionForCall(owner: object): LibrarySession {\n const entry = current.getStore();\n return entry !== undefined && entry.owner === owner ? entry.session : blank(uuid7(), \"minted\");\n}\n\n","/** The library's `listTools`: the tool list a vendor serving MCP itself hands\n * its agents, and the `surface_snapshot` of the list it started from (SPEC\n * §5.6, §11.4.2). */\n\nimport { requiredParamNames, USER_GOAL_PARAM_NAME } from \"../integrations/mcp/llmText.js\";\nimport { DEFAULT_INTENT_PARAM_MODE, withUserGoalJson } from \"../integrations/mcp/schemaCompat.js\";\nimport { assembleSurface, buildSeamAugmentations, surfaceHash, type ServerMeta } from \"../integrations/mcp/surface.js\";\nimport { printable, stderrLine } from \"../warn.js\";\nimport { isRecord } from \"../_object.js\";\n\n/** The vendor's own `initialize` values, as it serves them. */\nexport interface ListToolsOptions {\n serverInfo?: Record<string, unknown> | null;\n capabilities?: Record<string, unknown> | null;\n instructions?: string | null;\n}\n\nexport interface Surface {\n surface: Record<string, unknown>;\n digest: string;\n}\n\n/** `tools` with `user_goal` added, and the surface of `tools` as passed with\n * its hash. Never throws: a list it cannot read is served as it\n * came, with no surface. */\nexport function serveTools<T>(\n tools: readonly T[],\n options: ListToolsOptions,\n): { served: T[]; surface: Surface | null } {\n let served: T[];\n try {\n served = tools.map(servedEntry);\n } catch (err) {\n stderrLine(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}`);\n return { served: tools as T[], surface: null };\n }\n try {\n // Sorted so the same tools in another order hash the same, as in the adapters.\n const nameOf = (tool: unknown) => (isRecord(tool) ? String(tool.name) : \"\");\n const ordered = [...tools].sort((a, b) => {\n const [x, y] = [nameOf(a), nameOf(b)];\n return x < y ? -1 : x > y ? 1 : 0;\n });\n const meta = {\n server_info: options.serverInfo ?? null,\n capabilities: options.capabilities ?? null,\n instructions: options.instructions ?? null,\n } as ServerMeta;\n // Copied because a queued snapshot outlives the vendor's objects.\n const surface = JSON.parse(\n JSON.stringify(assembleSurface(meta, ordered as Array<Record<string, unknown>>)),\n ) as Record<string, unknown>;\n return { served, surface: { surface, digest: surfaceHash(surface) } };\n } catch (err) {\n stderrLine(`baton: surface snapshot capture failed: ${printable(err)}`);\n return { served, surface: null };\n }\n}\n\nexport function snapshotPayload({ surface, digest }: Surface): Record<string, unknown> {\n return {\n surface_hash: digest,\n ...surface,\n seam_augmentations: buildSeamAugmentations({\n injectedToolNames: [],\n intentParamNames: [USER_GOAL_PARAM_NAME],\n intentParamMode: DEFAULT_INTENT_PARAM_MODE,\n requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),\n instructionsSuffix: null,\n }),\n };\n}\n\nfunction servedEntry<T>(tool: T): T {\n if (!isRecord(tool) || !isRecord(tool.inputSchema)) return tool;\n return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, DEFAULT_INTENT_PARAM_MODE, true) };\n}\n","/**\n * The library API (SPEC §5.6): `Client` for a vendor whose agents reach it\n * through something other than MCP — a REST API, a skill, or a tool loop in\n * the vendor's own agent. Twin of the Python SDK's `baton.Client`, with the\n * `with` blocks as callbacks:\n *\n * const client = new Client({ dsn: process.env.BATON_DSN });\n * app.use((req, res, next) =>\n * client.session({ sessionId: req.get(\"x-conversation-id\") }, () =>\n * client.trace({ toolName: req.path, params: req.body }, () => next()),\n * ),\n * );\n *\n * Capture never throws into the vendor's code: a callback's own throw is\n * recorded and rethrown unchanged, and every failure of ours is logged and\n * dropped. Only a bad config throws, and only from the constructor.\n */\n\nimport { nextClockSequence } from \"../sequence.js\";\nimport type { Event } from \"../events.js\";\nimport {\n AnnotationEventSchema,\n DEFAULT_CONSENT_TOKEN,\n SurfaceSnapshotEventSchema,\n ToolCallEndEventSchema,\n ToolCallErrorEventSchema,\n ToolCallStartEventSchema,\n} from \"../events.js\";\nimport { parseDsn, selectDsn } from \"../dsn.js\";\nimport { captureDisabled, DisabledSink, logDisabled } from \"../optout.js\";\nimport { Scrubber } from \"../scrub.js\";\nimport { boundedSinkCall, droppedAfterClose, HttpSink, offTheCall, safeWrite, type Sink } from \"../sinks.js\";\nimport { PROCESS_DROPS } from \"../drops.js\";\nimport { printable, stderrLine } from \"../warn.js\";\nimport { uuid7 } from \"../uuid7.js\";\nimport { resolveTenantId } from \"../integrations/mcp/config.js\";\nimport { emit } from \"../integrations/mcp/emit.js\";\nimport {\n errorTypeOf,\n messageOf,\n RESULT_CAPTURE_MODES,\n type ResultCaptureMode,\n scrubbedErrorBody,\n WITHHELD,\n} from \"../integrations/mcp/errorResult.js\";\nimport { INTENT_SOURCE_LIBRARY } from \"../integrations/mcp/llmText.js\";\nimport { isThenable } from \"../integrations/mcp/mcpTypes.js\";\nimport { scrubOrNull, type ScrubbedField } from \"../integrations/mcp/safeScrub.js\";\nimport { SentSurfaces } from \"../integrations/mcp/surface.js\";\nimport {\n type LibrarySession,\n newSession,\n runInSession,\n sessionEnvelope,\n sessionForCall,\n} from \"./session.js\";\nimport { type ListToolsOptions, serveTools, snapshotPayload, type Surface } from \"./surface.js\";\nimport { type Organization, type Principal } from \"../identity.js\";\nimport { isBlank } from \"../_text.js\";\nimport type { HeaderInput } from \"../integrations/mcp/clientObserved.js\";\nimport { isPlainObject } from \"../_object.js\";\n\nexport interface ClientOptions {\n /** The packed connection string from /account. Resolved explicit →\n * `BATON_DSN`; it builds the sink and supplies `vendorId` and `tenantId`. */\n dsn?: string;\n /** Required unless a `dsn` is given. */\n sink?: Sink;\n /** Explicit → `BATON_VENDOR_ID`. Required unless a `dsn` supplies it. */\n vendorId?: string;\n /** Explicit → `BATON_TENANT_ID` → `vendorId`. */\n tenantId?: string;\n /** Explicit → `BATON_CONSENT_TOKEN` → the SDK default. */\n consentToken?: string;\n /** Defaults to `new Scrubber().scrub`; pass `identityScrub` to opt out. */\n scrubber?: (value: unknown) => unknown;\n /** `\"off\"` sends no result: see `BatonConfig.resultCaptureMode`. */\n resultCaptureMode?: ResultCaptureMode;\n}\n\nexport interface SessionOptions {\n /** The vendor's own id for the conversation; without one, the block mints one. */\n sessionId?: string;\n /** Who the vendor says is calling: a `Principal`, which may carry its\n * `organization`, or an `Organization` alone when only the company is known.\n * A block with only a company and no `sessionId` gets a session of its own,\n * so pass your own `sessionId` to keep a conversation's blocks together. */\n principal?: Principal | Organization;\n /** What the calling client said about itself. */\n clientInfo?: { name?: string; version?: string };\n /** The request's headers; only registered ones are kept. */\n headers?: HeaderInput;\n /** The vendor's own id for the user request these calls answer. Pass the\n * same value to every block that serves it, and those calls stay one turn. */\n turnId?: string;\n /** The request's MCP `_meta`, for a vendor serving MCP itself. It is sent\n * as `runtime_meta`, and a client declaration in it wins over `clientInfo`. */\n meta?: Record<string, unknown>;\n}\n\nexport interface TraceOptions {\n toolName: string;\n intent?: string;\n expectedOutcome?: string;\n workflow?: string;\n params?: Record<string, unknown>;\n consentToken?: string;\n}\n\nexport interface AnnotateOptions {\n whatHappened?: string;\n toolName?: string;\n intent?: string;\n expectedOutcome?: string;\n workflow?: string;\n suggestedImprovement?: string;\n context?: Record<string, unknown>;\n}\n\nexport interface ObservedError {\n /** `errorType` and `errorBody` are derived from it unless given. */\n error?: unknown;\n errorType?: string;\n errorBody?: string;\n}\n\ninterface Resolved {\n sink: Sink;\n vendorId: string;\n tenantId: string;\n consentToken: string;\n resultCaptureMode: ResultCaptureMode;\n}\n\nfunction fromEnv(name: string): string | undefined {\n const value = typeof process !== \"undefined\" ? process.env?.[name] : undefined;\n return value ? value : undefined;\n}\n\nfunction resolveConsentToken(explicit: string | undefined): string {\n if (explicit !== undefined && !explicit) {\n throw new Error(\n \"Client consentToken was set to an empty string, and events without one \" +\n \"MUST be rejected by the consumer per SPEC §2.3. Omit it to take the SDK's default.\",\n );\n }\n return explicit ?? fromEnv(\"BATON_CONSENT_TOKEN\") ?? DEFAULT_CONSENT_TOKEN;\n}\n\nfunction resolveClientOptions(options: ClientOptions): Resolved {\n const resultCaptureMode = options.resultCaptureMode ?? \"full\";\n if (!(RESULT_CAPTURE_MODES as readonly string[]).includes(resultCaptureMode)) {\n throw new Error(\n `Client resultCaptureMode ${JSON.stringify(resultCaptureMode)} must be one of ` +\n `${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`,\n );\n }\n if (options.scrubber !== undefined && typeof options.scrubber !== \"function\") {\n throw new Error(\"Client scrubber must be a function.\");\n }\n const dsnString = selectDsn(\n options.dsn,\n {\n vendorId: Boolean(options.vendorId),\n tenantId: Boolean(options.tenantId),\n sink: options.sink !== undefined,\n },\n \"Client\",\n );\n const consentToken = resolveConsentToken(options.consentToken);\n if (dsnString !== undefined) {\n const dsn = parseDsn(dsnString);\n return {\n sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),\n vendorId: dsn.vendorId,\n tenantId: dsn.tenantId,\n consentToken,\n resultCaptureMode,\n };\n }\n if (options.sink === undefined) {\n throw new Error(\n \"Client needs somewhere to send events: pass sink (for example new HttpSink(url, \" +\n \"{ apiKey }) or new StdoutSink()), or dsn — the packed value from /account, \" +\n \"which builds the sink for you.\",\n );\n }\n const vendorId = options.vendorId || fromEnv(\"BATON_VENDOR_ID\");\n if (!vendorId) {\n throw new Error(\"Client needs a vendorId, or the BATON_VENDOR_ID environment variable.\");\n }\n return {\n sink: options.sink,\n vendorId,\n tenantId: resolveTenantId(options.tenantId || undefined, vendorId),\n consentToken,\n resultCaptureMode,\n };\n}\n\nconst hasText = (value: string | null | undefined): boolean =>\n typeof value === \"string\" && !isBlank(value);\n\n/** `[error_type, error_body]` of a thrown value. Never throws: a vendor's\n * error can be any value, including one whose getters throw. */\nfunction describeError(err: unknown): [string, string] {\n let type = \"Error\";\n let body = \"\";\n // Each read is separate, so a throwing message getter still leaves the type.\n try {\n type = errorTypeOf(err);\n } catch {\n // unreadable\n }\n try {\n body = messageOf(err) || (err instanceof Error && typeof err.stack === \"string\" ? err.stack : \"\");\n } catch {\n // unreadable\n }\n return [type, body];\n}\n\n/** A wrapped function's arguments as `params`: one plain-object argument is\n * a tool's named arguments, as on MCP; anything else is kept as a list. */\nfunction paramsOf(args: readonly unknown[]): Record<string, unknown> {\n if (args.length === 1 && isPlainObject(args[0])) return args[0];\n return args.length === 0 ? {} : { args };\n}\n\n/** What a client holds that its traces read. */\nclass Core {\n closed = false;\n // A snapshot describes the server, so it takes no block's session,\n // principal or client (SPEC §5.6 rule 7).\n private readonly surfaceSessionId = uuid7();\n private readonly sentSurfaces = new SentSurfaces();\n\n readonly sink: Sink;\n readonly vendorId: string;\n readonly tenantId: string;\n readonly consentToken: string;\n readonly resultCaptureMode: ResultCaptureMode;\n readonly scrubber: (value: unknown) => unknown;\n readonly disabled: boolean;\n\n constructor(resolved: Resolved & { scrubber: (value: unknown) => unknown; disabled: boolean }) {\n this.sink = offTheCall(resolved.sink);\n this.vendorId = resolved.vendorId;\n this.tenantId = resolved.tenantId;\n this.consentToken = resolved.consentToken;\n this.resultCaptureMode = resolved.resultCaptureMode;\n this.scrubber = resolved.scrubber;\n this.disabled = resolved.disabled;\n }\n\n /** The envelope members every event of `session` shares. Call inside a\n * build thunk, so `captured_at` is the build time. */\n envelope(session: LibrarySession, consentToken: string, sequence: number): Record<string, unknown> {\n return {\n tenant_id: this.tenantId,\n vendor_id: this.vendorId,\n ...sessionEnvelope(session),\n sequence_number: sequence,\n captured_at: new Date().toISOString(),\n consent_token: consentToken,\n };\n }\n\n /** False when nothing may be emitted: the off switch, or a closed client. */\n live(): boolean {\n if (this.disabled) return false;\n if (!this.closed) return true;\n // Keyed on the sink, so an event its queue refused while closing and one\n // refused here share one warning (SPEC §11.2 rule 7).\n droppedAfterClose(this.sink);\n return false;\n }\n\n /** Never rejects. */\n emit(build: () => Event): Promise<void> {\n return emit(this.sink, build);\n }\n\n /** Sends `surface` unless this client already has. Never rejects. The\n * write only queues, so a surface counts as sent once queued. */\n sendSurface(surface: Surface): Promise<void> {\n if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();\n this.sentSurfaces.mark(surface.digest);\n let event: Event;\n try {\n event = SurfaceSnapshotEventSchema.parse({\n tenant_id: this.tenantId,\n vendor_id: this.vendorId,\n session_id: this.surfaceSessionId,\n session_id_origin: \"minted\",\n sequence_number: nextClockSequence(),\n captured_at: new Date().toISOString(),\n consent_token: this.consentToken,\n payload: snapshotPayload(surface),\n });\n } catch (err) {\n PROCESS_DROPS.add(\"encode_failed\");\n stderrLine(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}`);\n return Promise.resolve();\n }\n return safeWrite(this.sink, event);\n }\n\n scrub(value: unknown, field: ScrubbedField): unknown {\n return scrubOrNull(this.scrubber, value, field);\n }\n\n annotate(session: LibrarySession, consentToken: string, options: AnnotateOptions): Promise<void> {\n if (!this.live()) return Promise.resolve();\n const sequence = nextClockSequence();\n // The text fields are scrubbed bare inside the thunk: an annotation is one\n // report, so a scrubber throw drops it whole, as on the MCP path.\n /* eslint-disable no-restricted-syntax -- inside the emit() build thunk */\n const text = (value: string | undefined): string | null =>\n value === undefined ? null : (this.scrubber(value) as string | null);\n return this.emit(() =>\n AnnotationEventSchema.parse({\n ...this.envelope(session, consentToken, sequence),\n payload: {\n intent: text(options.intent),\n expected_outcome: text(options.expectedOutcome),\n what_happened: hasText(options.whatHappened) ? text(options.whatHappened) : null,\n tool_name: options.toolName ? text(options.toolName) : (options.toolName ?? null),\n workflow: text(options.workflow),\n suggested_improvement: text(options.suggestedImprovement),\n context:\n options.context && Object.keys(options.context).length > 0\n ? this.scrub(options.context, \"context\")\n : null,\n },\n }),\n );\n /* eslint-enable no-restricted-syntax */\n }\n}\n\nconst UNSET = Symbol(\"unset\");\n// `observed()` ran and the result was deliberately not kept (resultCaptureMode \"off\").\nconst WITHHELD_RESULT = Symbol(\"withheld\");\n// The scrubber threw on the result. Re-thrown inside the build thunk so the\n// end event is dropped rather than sent with a result the tool never returned.\nconst SCRUB_FAILED = Symbol(\"scrubFailed\");\n\n// Set by `Trace`'s static block, so only `Client` can start, end or fail a trace.\nlet runTrace: <T>(core: Core, session: LibrarySession, options: TraceOptions, fn: (trace: Trace) => T) => T;\n\n/** One traced call, handed to the `client.trace()` callback. */\nexport class Trace {\n readonly #core: Core;\n readonly #session: LibrarySession;\n readonly #options: TraceOptions;\n readonly #consentToken: string;\n readonly #callId = uuid7();\n #startedAt = 0;\n #result: unknown = UNSET;\n #error: { type: string; body: string } | null = null;\n #observedWarned = false;\n\n private constructor(core: Core, session: LibrarySession, options: TraceOptions) {\n this.#core = core;\n this.#session = session;\n this.#options = options;\n this.#consentToken = options.consentToken || core.consentToken;\n }\n\n /** The session this call's events carry. */\n get sessionId(): string {\n return this.#session.sessionId;\n }\n\n /** Record the outcome. Without a call, the callback's return value is the\n * result. `observed(undefined, { error })` records a failure the callback\n * caught and did not rethrow. The last call wins. */\n observed(result?: unknown, failure?: ObservedError): this {\n if ((this.#result !== UNSET || this.#error !== null) && !this.#observedWarned) {\n this.#observedWarned = true;\n stderrLine(\"baton: Trace.observed() called more than once; the last call wins.\");\n }\n this.#result = UNSET;\n this.#error = null;\n if (this.#core.disabled) return this;\n let errorType = failure?.errorType;\n let errorBody = failure?.errorBody;\n if (failure?.error !== undefined) {\n const [derivedType, derivedBody] = describeError(failure.error);\n errorType ||= derivedType;\n errorBody ||= derivedBody;\n }\n if (errorType !== undefined || errorBody !== undefined) {\n this.#error = { type: errorType || \"Error\", body: errorBody ?? \"\" };\n } else if (this.#core.resultCaptureMode === WITHHELD) {\n // Decided here, so a withheld result never reaches the scrubber (SPEC §7).\n this.#result = WITHHELD_RESULT;\n } else {\n // Scrubbed now, so a result object the caller changes later is recorded\n // as it was when observed.\n try {\n // eslint-disable-next-line no-restricted-syntax -- the throw is caught here and parks SCRUB_FAILED, which drops the end event\n this.#result = this.#core.scrubber(result);\n } catch (err) {\n stderrLine(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}`);\n this.#result = SCRUB_FAILED;\n }\n }\n return this;\n }\n\n /** Report on this call, in its session. */\n annotate(options: AnnotateOptions): Promise<void> {\n return this.#core.annotate(this.#session, this.#consentToken, options);\n }\n\n #envelope(sequence: number): Record<string, unknown> {\n return { ...this.#core.envelope(this.#session, this.#consentToken, sequence), call_id: this.#callId };\n }\n\n #durationMs(): number {\n return Math.trunc(performance.now() - this.#startedAt);\n }\n\n #start(): void {\n this.#startedAt = performance.now();\n if (!this.#core.live()) return;\n const sequence = nextClockSequence();\n const o = this.#options;\n // Fail-open per field, outside the thunk: a scrubber throw here must not\n // drop the start event and leave the call's end unpaired.\n const params = o.params === undefined ? {} : (this.#core.scrub(o.params, \"params\") ?? {});\n const textOf = (value: string | undefined, field: ScrubbedField): string | null => {\n const scrubbed = value === undefined ? null : this.#core.scrub(value, field);\n return typeof scrubbed === \"string\" ? scrubbed : null;\n };\n const intent = textOf(o.intent, \"intent\");\n const expected = textOf(o.expectedOutcome, \"expected_outcome\");\n const workflow = textOf(o.workflow, \"workflow\");\n const stated = [intent, expected, workflow].some(hasText);\n void this.#core.emit(() =>\n ToolCallStartEventSchema.parse({\n ...this.#envelope(sequence),\n payload: {\n tool_name: o.toolName,\n params,\n call_intent: intent,\n call_expected: expected,\n call_workflow: workflow,\n intent_source: stated ? INTENT_SOURCE_LIBRARY : null,\n },\n }),\n );\n }\n\n #end(value: unknown): void {\n const durationMs = this.#durationMs();\n if (!this.#core.live()) return;\n if (this.#result === UNSET && this.#error === null) this.observed(value);\n const sequence = nextClockSequence();\n const error = this.#error;\n if (error !== null) {\n this.#emitError(sequence, error.type, error.body, durationMs);\n return;\n }\n const result = this.#result;\n void this.#core.emit(() => {\n if (result === SCRUB_FAILED) throw new Error(\"the scrubber threw on this result\");\n return ToolCallEndEventSchema.parse({\n ...this.#envelope(sequence),\n payload: {\n tool_name: this.#options.toolName,\n duration_ms: durationMs,\n ...(result === WITHHELD_RESULT\n ? { result: null, result_capture: WITHHELD }\n : { result }),\n },\n });\n });\n }\n\n #fail(err: unknown): void {\n const durationMs = this.#durationMs();\n if (!this.#core.live()) return;\n this.#emitError(nextClockSequence(), ...describeError(err), durationMs);\n }\n\n #emitError(sequence: number, type: string, body: string, durationMs: number): void {\n void this.#core.emit(() =>\n ToolCallErrorEventSchema.parse({\n ...this.#envelope(sequence),\n payload: {\n tool_name: this.#options.toolName,\n error_type: type,\n error_body: scrubbedErrorBody(this.#core.scrubber, body),\n duration_ms: durationMs,\n result: null,\n },\n }),\n );\n }\n\n static {\n runTrace = <T>(core: Core, session: LibrarySession, options: TraceOptions, fn: (trace: Trace) => T): T => {\n const trace = new Trace(core, session, options);\n trace.#start();\n let value: T;\n try {\n value = fn(trace);\n } catch (err) {\n trace.#fail(err);\n throw err;\n }\n if (!isThenable(value)) {\n trace.#end(value);\n return value;\n }\n return Promise.resolve(value).then(\n (resolved) => {\n trace.#end(resolved);\n return resolved;\n },\n (err: unknown) => {\n trace.#fail(err);\n throw err;\n },\n ) as T;\n };\n }\n}\n\n/** The library API's client. One per process. */\nexport class Client {\n readonly #core: Core;\n #closing: Promise<void> | undefined;\n\n constructor(options: ClientOptions = {}) {\n const switchName = captureDisabled();\n let resolved: Resolved;\n if (switchName !== null) {\n // Off means never throw, so nothing is validated; a sink the caller\n // passed is kept so `aclose()` still releases it.\n logDisabled(switchName, \"Client\");\n resolved = {\n sink: options.sink ?? new DisabledSink(),\n vendorId: \"\",\n tenantId: \"\",\n consentToken: DEFAULT_CONSENT_TOKEN,\n resultCaptureMode: \"full\",\n };\n } else {\n resolved = resolveClientOptions(options);\n }\n this.#core = new Core({\n ...resolved,\n scrubber: options.scrubber ?? new Scrubber().scrub,\n disabled: switchName !== null,\n });\n }\n\n /** Run `fn` with one session, principal, client and turn for every\n * `trace()` and `annotate()` inside it, including after its awaits. Open\n * one per request or conversation. Returns what `fn` returns. */\n session<T>(options: SessionOptions, fn: () => T): T {\n let block: LibrarySession;\n try {\n block = newSession(options, this.#core.scrubber, this.#core.disabled);\n } catch (err) {\n stderrLine(`baton: session values could not be read; using a minted session: ${printable(err)}`);\n block = newSession({}, this.#core.scrubber, this.#core.disabled);\n }\n return runInSession(this, block, fn);\n }\n\n /** Run `fn` as one traced tool call and return what it returns. When `fn`\n * returns a promise or other thenable, the call ends when it settles, and\n * what comes back is a new native Promise of the same value: `then` is\n * called exactly once, so a lazy query builder is not run twice. A throw or\n * rejection is recorded and passed on unchanged. */\n trace<T>(options: TraceOptions, fn: (trace: Trace) => T): T {\n // `?? {}` for a JavaScript caller: missing options must not throw into its code.\n return runTrace(this.#core, sessionForCall(this), options ?? ({} as TraceOptions), fn);\n }\n\n /** `fn`, traced on every call. A single plain-object argument is sent as\n * `params`, as an MCP tool's arguments are; other arguments as\n * `{ args: [...] }`, unless `options.params` is given. */\n wrap<A extends unknown[], R>(options: string | TraceOptions, fn: (...args: A) => R): (...args: A) => R {\n const base: TraceOptions = typeof options === \"string\" ? { toolName: options } : (options ?? {});\n // eslint-disable-next-line @typescript-eslint/no-this-alias -- the wrapper keeps its own `this` for `fn`\n const client = this;\n return function (this: unknown, ...args: A): R {\n return client.trace({ ...base, params: base.params ?? paramsOf(args) }, () => fn.apply(this, args));\n };\n }\n\n /** Emit an annotation in the open `session()` block, or in a session of its\n * own outside one. To report on a traced call, use `trace.annotate()`. */\n annotate(options: AnnotateOptions & { consentToken?: string }): Promise<void> {\n const given = options ?? {};\n return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);\n }\n\n /** `tools`, the vendor's own `tools/list` entries, with `user_goal` added\n * to each `inputSchema` as `withBaton` adds it, and a `surface_snapshot`\n * of `tools` as passed, sent once per distinct surface. For a vendor\n * serving MCP itself (SPEC §5.6).\n *\n * Pass the tools before anything of Baton's is added, so the snapshot\n * describes the vendor's own surface. `options` holds the vendor's own\n * `initialize` values. The input is not changed. Never rejects over the\n * tool list: one it cannot read is returned as it came. Does not wait for\n * the snapshot to be sent; `flush()` does. */\n async listTools<T>(tools: readonly T[], options: ListToolsOptions = {}): Promise<T[]> {\n if (this.#core.disabled) return tools as T[];\n const { served, surface } = serveTools(tools, options);\n if (surface !== null) void this.#core.sendSurface(surface);\n return served;\n }\n\n /** Wait for events so far to reach the sink, then flush it. Never rejects;\n * returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */\n async flush(): Promise<void> {\n await boundedSinkCall(this.#core.sink, \"flush\");\n }\n\n /** Flush, then close the sink. Later events are dropped. */\n aclose(): Promise<void> {\n this.#closing ??= boundedSinkCall(this.#core.sink, \"aclose\").then(() => {\n this.#core.closed = true;\n });\n return this.#closing;\n }\n}\n","/** The annotation tool as data, for a vendor offering it through its own API (SPEC §5.6). */\n\nimport { isRecord } from \"../_object.js\";\nimport {\n ANNOTATION_INPUT_SHAPE,\n isReport,\n TOOL_NAME_PARAM_NAME,\n} from \"../integrations/mcp/annotation.js\";\nimport {\n toolNameForDisplayName,\n validateAnnotationToolName,\n} from \"../integrations/mcp/annotationName.js\";\nimport {\n buildAnnotationToolDescription,\n buildRefusalText,\n buildServerInstructions,\n fitsInstructionsCap,\n USER_GOAL_PARAM_NAME,\n} from \"../integrations/mcp/llmText.js\";\nimport { toolInputJsonSchema } from \"../integrations/mcp/schemaCompat.js\";\nimport type { AnnotateOptions } from \"./client.js\";\n\n/** The tool an MCP adapter registers under `reportMode: \"on\"`. */\nexport interface ReportTool {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: Record<string, unknown>;\n /** The report pointer and `INTENT_INSTRUCTIONS`, for a vendor serving MCP itself. */\n readonly instructions: string;\n /** What to answer when `annotateArgs` returns `null`. */\n readonly refusal: string;\n /** The `annotate()` options for this tool's `args`, or `null` when there is\n * no `what_happened`: answer `refusal` and send nothing. */\n annotateArgs(args: Readonly<Record<string, unknown>>): AnnotateOptions | null;\n}\n\nfunction inputSchema(): Record<string, unknown> {\n const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);\n delete schema.$schema;\n return { ...schema, required: [...(schema.required as string[]), TOOL_NAME_PARAM_NAME] };\n}\n\nconst nonEmptyText = (value: unknown): value is string => typeof value === \"string\" && value !== \"\";\n\nconst nonEmptyObject = (value: unknown): value is Record<string, unknown> =>\n isRecord(value) && Object.keys(value).length > 0;\n\nfunction annotateArgs(args: Readonly<Record<string, unknown>>): AnnotateOptions | null {\n const whatHappened = args.what_happened;\n if (!isReport(whatHappened)) return null;\n const options: AnnotateOptions = { whatHappened };\n // Sent as written, \"\" included: SPEC §5.1.1 gives tool_name three states.\n const toolName = args[TOOL_NAME_PARAM_NAME];\n if (typeof toolName === \"string\") options.toolName = toolName;\n const intent = args[USER_GOAL_PARAM_NAME];\n if (nonEmptyText(intent)) options.intent = intent;\n if (nonEmptyText(args.suggested_improvement)) {\n options.suggestedImprovement = args.suggested_improvement;\n }\n if (nonEmptyObject(args.context)) options.context = args.context;\n return options;\n}\n\n/** The annotation tool an adapter registers on a server named\n * `vendorDisplayName`. `name` overrides the name made from it. */\nexport function reportTool(options: { vendorDisplayName: string; name?: string }): ReportTool {\n const { vendorDisplayName } = options;\n const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);\n if (derived === undefined) {\n throw new Error(\n `vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, ` +\n \"or one too long for the instructions. Pass name.\",\n );\n }\n const name = validateAnnotationToolName(derived);\n if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: name })) {\n throw new Error(\n `vendorDisplayName and name ${JSON.stringify(name)} are too long together for ` +\n \"the instructions. Shorten one of them.\",\n );\n }\n return {\n name,\n description: buildAnnotationToolDescription({ vendorDisplayName }),\n inputSchema: inputSchema(),\n instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),\n refusal: buildRefusalText({ annotationToolName: name }),\n annotateArgs,\n };\n}\n"],"mappings":";AAEO,IAAM,cAAc;;;ACa3B,SAAS,SAAS;;;ACflB,YAAY,YAAY;AAExB,IAAM,cAAc;AAEpB,IAAI,SAAS;AACb,IAAI,UAAU;AAIP,SAAS,QAAgB;AAC9B,QAAM,QAAe,mBAAY,EAAE;AAEnC,QAAM,QAAS,MAAM,EAAE,KAAM,IAAK,MAAM,EAAE,KAAM;AAChD,QAAM,MAAM,KAAK,IAAI;AACrB,MAAI,MAAM,QAAQ;AAChB,aAAS;AACT,cAAU;AAAA,EACZ,WAAW,EAAE,UAAU,aAAa;AAClC,cAAU;AACV,cAAU;AAAA,EACZ;AAEA,QAAM,YAAY,QAAQ,GAAG,CAAC;AAC9B,QAAM,CAAC,IAAI,MAAQ,WAAW;AAC9B,QAAM,CAAC,IAAI,UAAU;AACrB,QAAM,CAAC,IAAI,MAAQ,MAAM,CAAC,IAAK;AAE/B,QAAM,MAAM,MAAM,SAAS,OAAO,GAAG,EAAE;AACvC,SAAO,GAAG,IAAI,MAAM,GAAG,CAAC,CAAC,IAAI,IAAI,MAAM,GAAG,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC,IAAI,IAAI,MAAM,EAAE,CAAC;AAC1G;;;ADOO,IAAM,6BAA6B,EACvC,OAAO;AAAA,EACN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,KAAK,oBAAoB;AACxC,MAAI,aAAa,MAAM,EAAG,SAAQ,SAAS;AAC3C,MAAI,aAAa,KAAK,qBAAqB,GAAG;AAC5C,YAAQ,uBAAuB,KAAK;AAAA,EACtC;AACA,MAAI,eAAe,KAAK,OAAO,EAAG,SAAQ,UAAU,KAAK;AACzD,SAAO;AACT;AAIO,SAAS,WAAW,SAAmE;AAC5F,QAAM,EAAE,kBAAkB,IAAI;AAC9B,QAAM,UAAU,QAAQ,QAAQ,uBAAuB,iBAAiB;AACxE,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI;AAAA,MACR,qBAAqB,KAAK,UAAU,iBAAiB,CAAC;AAAA,IAExD;AAAA,EACF;AACA,QAAM,OAAO,2BAA2B,OAAO;AAC/C,MAAI,CAAC,oBAAoB,EAAE,mBAAmB,oBAAoB,KAAK,CAAC,GAAG;AACzE,UAAM,IAAI;AAAA,MACR,8BAA8B,KAAK,UAAU,IAAI,CAAC;AAAA,IAEpD;AAAA,EACF;AACA,SAAO;AAAA,IACL;AAAA,IACA,aAAa,+BAA+B,EAAE,kBAAkB,CAAC;AAAA,IACjE,aAAa,YAAY;AAAA,IACzB,cAAc,wBAAwB,EAAE,mBAAmB,oBAAoB,KAAK,CAAC;AAAA,IACrF,SAAS,iBAAiB,EAAE,oBAAoB,KAAK,CAAC;AAAA,IACtD;AAAA,EACF;AACF;","names":["sum","emit","z","walk","current","warn","vendorId","warn","inputSchema","declared","warned","z","fromEnv","errorBody","crypto","vendorId","vendorId","fromEnv","crypto","durationMs","declared","warnOnce","reportTool","inputSchema","warned","counter","current","json","asyncHooks","warn","vendorId","hasText","errorBody"]}
|
|
1
|
+
{"version":3,"sources":["../src/version.ts","../src/events.ts","../src/uuid7.ts","../src/runtime.ts","../src/warn.ts","../src/_object.ts","../src/scrub.ts","../src/sinks.ts","../src/_text.ts","../src/deadline.ts","../src/drops.ts","../src/sequence.ts","../src/integrations/mcp/withBaton.ts","../src/integrations/mcp/annotation.ts","../src/metaCoordinates.ts","../src/integrations/mcp/overlays.ts","../src/integrations/mcp/llmText.ts","../src/integrations/mcp/annotationName.ts","../src/integrations/mcp/emit.ts","../src/identity.ts","../src/integrations/mcp/captureSettings.ts","../src/integrations/mcp/errorResult.ts","../src/integrations/mcp/mcpTypes.ts","../src/integrations/mcp/principalResolution.ts","../src/integrations/mcp/zodCompat.ts","../src/integrations/mcp/schemaCompat.ts","../src/integrations/mcp/safeScrub.ts","../src/integrations/mcp/clientObserved.ts","../src/integrations/mcp/sessionResolution.ts","../src/dsn.ts","../src/integrations/mcp/config.ts","../src/optout.ts","../src/integrations/mcp/inputRequired.ts","../src/integrations/mcp/handle.ts","../src/integrations/mcp/perCaller.ts","../src/integrations/mcp/sessionCounter.ts","../src/integrations/mcp/surface.ts","../src/integrations/mcp/oauthHooks.ts","../src/library/session.ts","../src/library/surface.ts","../src/library/client.ts","../src/library/reportTool.ts"],"sourcesContent":["// TS-prefixed so `sdk_version` distinguishes TypeScript-sourced events from\n// Python (`baton-sdk`) ones in the Console — see design-notes/typescript_sdk.md.\nexport const SDK_VERSION = \"ts-1.2.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 * NOT camelCase).\n */\n\nimport { z } from \"zod\";\nimport { uuid7 } from \"./uuid7.js\";\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` is the value the SDK stripped from the injected `user_goal`\n * param, and `call_expected` / `call_workflow` the retired `expected_result` /\n * `overall_task` a stale client may still send (see `llmText.ts`); they ride\n * as SIBLINGS of `params` — `params` stays exactly the vendor-visible\n * 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 nullable. An annotation with `what_happened`\n * filled is a report; one without is a note (SPEC §11.4). `signal_type` is\n * kept for events from older producers: this SDK always sends it null. */\nexport const AnnotationPayloadSchema = z\n .object({\n intent: z.string().nullable().default(null),\n expected_outcome: z.string().nullable().default(null),\n what_happened: 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 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/** This process's lost-event counts by reason, as running totals (SPEC §11.4.7). */\nexport const ClientReportPayloadSchema = z\n .object({\n instance_id: z.uuid(),\n dropped: z.record(z.string(), z.number().int().nonnegative()),\n })\n .strict();\n/** @experimental May change in a minor release. */\nexport type ClientReportPayload = z.infer<typeof ClientReportPayloadSchema>;\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// Strict, with the headers spelled out, so a header that is not registered\n// cannot reach the wire: `clientObserved.test.ts`, \"refuses an unregistered\n// header at the schema\".\nexport const ClientObservedSchema = z\n .object({\n info: z.object({ name: z.string().optional(), version: z.string().optional() }).strict().optional(),\n headers: z\n .object({ \"user-agent\": z.string().optional(), \"x-anthropic-client\": z.string().optional() })\n .strict()\n .optional(),\n })\n .strict();\n\n/** Which collector settings a call ran under (SPEC §11.4, §2.6). A member\n * with no value is left out. */\nexport const CaptureObservedSchema = z\n .object({\n settings_version: z.number().int().min(1).optional(),\n audience: z.string().optional(),\n overlay: z.string().optional(),\n candidate: z.string().optional(),\n task: z.string().optional(),\n })\n .strict();\nexport type CaptureObserved = z.infer<typeof CaptureObservedSchema>;\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 `identityWire` 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(() => uuid7()),\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 // Legacy (SPEC §3.4): never set by this SDK, so always the default. The\n // consumer names the client from `client_observed`.\n agent_runtime: z.string().default(\"unknown\"),\n principal: PrincipalWireSchema.nullable().default(null),\n organization: PrincipalWireSchema.nullable().default(null),\n // No length rules here: zod counts UTF-16 units, SPEC §11.4 code points.\n // `cleanLabels` applies them.\n labels: z.array(z.string()).nullable().default(null),\n capture: CaptureObservedSchema.nullable().default(null),\n transport_observed: z.string().nullable().default(null),\n session_id_origin: z.string().nullable().default(null),\n client_observed: ClientObservedSchema.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 \"client_report\",\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 // SPEC §11.4.5.\n \"tool_list_start\",\n \"tool_list_end\",\n \"tool_list_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/** `tools/list` reached the server (SPEC §11.4.5). Empty, for the reason\n * `ResourceListStartPayloadSchema` carries. */\nexport const ToolListStartPayloadSchema = z.object({}).strict();\nexport type ToolListStartPayload = z.infer<typeof ToolListStartPayloadSchema>;\n\n/** `tools/list` returned. `count` is the length of the `tools` array in that\n * one response, this SDK's own tool included. */\nexport const ToolListEndPayloadSchema = z\n .object({\n count: z.number().int(),\n ...timingShape,\n })\n .strict();\nexport type ToolListEndPayload = z.infer<typeof ToolListEndPayloadSchema>;\n\n/** `tools/list` failed. See `ResourceReadErrorPayloadSchema`. */\nexport const ToolListErrorPayloadSchema = z\n .object({\n ...failureShape,\n })\n .strict();\nexport type ToolListErrorPayload = z.infer<typeof ToolListErrorPayloadSchema>;\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\n/** SPEC §11.4: a tool-call leg always carries the id its other leg carries. */\nconst REQUIRED_CALL_ID = z.string().min(1);\n\nexport const ToolCallStartEventSchema = z\n .object({\n ...envelopeShape,\n call_id: REQUIRED_CALL_ID,\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 call_id: REQUIRED_CALL_ID,\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 call_id: REQUIRED_CALL_ID,\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\nexport const ClientReportEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"client_report\").default(\"client_report\"),\n payload: ClientReportPayloadSchema,\n })\n .strict();\n/** @experimental May change in a minor release. */\nexport type ClientReportEvent = z.infer<typeof ClientReportEventSchema>;\n\n// ⚠ The lifecycle events carry the SAME `envelopeShape` as the five\n// above, which is what lets one collector endpoint accept every type 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\nexport const ToolListStartEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"tool_list_start\").default(\"tool_list_start\"),\n payload: ToolListStartPayloadSchema,\n })\n .strict();\nexport type ToolListStartEvent = z.infer<typeof ToolListStartEventSchema>;\n\nexport const ToolListEndEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"tool_list_end\").default(\"tool_list_end\"),\n payload: ToolListEndPayloadSchema,\n })\n .strict();\nexport type ToolListEndEvent = z.infer<typeof ToolListEndEventSchema>;\n\nexport const ToolListErrorEventSchema = z\n .object({\n ...envelopeShape,\n event_type: z.literal(\"tool_list_error\").default(\"tool_list_error\"),\n payload: ToolListErrorPayloadSchema,\n })\n .strict();\nexport type ToolListErrorEvent = z.infer<typeof ToolListErrorEventSchema>;\n\n// =============================================================================\n// Discriminated union — mirrors Python's `Event` (discriminator: event_type)\n// =============================================================================\n\n/** @experimental The zod schema for any event. Its type names zod's, so it may\n * change with a zod major. */\nexport const EventSchema = z.discriminatedUnion(\"event_type\", [\n ToolCallStartEventSchema,\n ToolCallEndEventSchema,\n ToolCallErrorEventSchema,\n AnnotationEventSchema,\n SurfaceSnapshotEventSchema,\n ClientReportEventSchema,\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 ToolListStartEventSchema,\n ToolListEndEventSchema,\n ToolListErrorEventSchema,\n]);\n/** ⚠ DERIVED, not hand-listed. It used to be a third list of the same\n * 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","import * as crypto from \"node:crypto\";\n\nconst COUNTER_MAX = 0xfff;\n\nlet lastMs = -1;\nlet counter = 0;\n\n/** RFC 9562 UUIDv7, strictly increasing within this process: a 12-bit counter\n * orders ids minted in one millisecond, as the Python SDK's `_uuid.py` does. */\nexport function uuid7(): string {\n const bytes = crypto.randomBytes(18);\n // Seeded below half the counter's range, so a burst has room to count up.\n const seed = ((bytes[16]! << 8) | bytes[17]!) & 0x7ff;\n const now = Date.now();\n if (now > lastMs) {\n lastMs = now;\n counter = seed;\n } else if (++counter > COUNTER_MAX) {\n lastMs += 1;\n counter = seed;\n }\n\n bytes.writeUIntBE(lastMs, 0, 6);\n bytes[6] = 0x70 | (counter >> 8);\n bytes[7] = counter & 0xff;\n bytes[8] = 0x80 | (bytes[8]! & 0x3f);\n\n const hex = bytes.toString(\"hex\", 0, 16);\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","/** Whether this runs on Cloudflare Workers. `WebSocketPair` is there at\n * every compatibility date; `navigator` only from 2022-03-21. */\nexport function onWorkers(): boolean {\n return typeof (globalThis as { WebSocketPair?: unknown }).WebSocketPair === \"function\" ||\n (typeof navigator !== \"undefined\" && navigator.userAgent === \"Cloudflare-Workers\");\n}\n\n/** The global `fetch`, looked up at each call. Called as a method, a\n * Worker's `fetch` throws \"Illegal invocation\". */\nexport const globalFetch: typeof fetch = (input, init) => fetch(input, init);\n\n/** Adds `listener` for `event` to `process`, and returns what takes it off\n * that same `process`, which a test may since have swapped for a stand-in.\n * `undefined` where `process` takes no listeners, as on an edge runtime. */\nexport function onProcess(event: \"beforeExit\" | \"exit\", listener: () => void): (() => void) | undefined {\n const target = typeof process !== \"undefined\" ? process : undefined;\n if (typeof target?.on !== \"function\") return undefined;\n try {\n target.on(event, listener);\n } catch {\n return undefined;\n }\n return () => {\n try {\n target.off(event, listener);\n } catch {\n // A stand-in with `on` and no working `off`: nothing more to take off.\n }\n };\n}\n","import { onWorkers } from \"./runtime.js\";\n\n/** `process.emitWarning`, else a stderr line (`stderrLine`). On a Worker it is\n * `console.warn`, because a Worker prints nothing for `emitWarning`. Never\n * `console.log`: under stdio, stdout carries the MCP JSON-RPC frames. */\nexport function warn(message: string): void {\n if (onWorkers()) {\n // eslint-disable-next-line no-console -- console.warn writes to stderr, never to stdout\n console.warn(message);\n return;\n }\n try {\n if (typeof process !== \"undefined\" && typeof process.emitWarning === \"function\") return process.emitWarning(message);\n } catch {\n // A stand-in `emitWarning` that throws: Baton's own catch blocks call this.\n }\n stderrLine(message);\n}\n\n/** One line to stderr, or to `console.warn` where `process.stderr` is missing\n * or its write throws.\n * Never throws: it reports failures from inside Baton's own catch blocks. */\nexport function stderrLine(message: string): void {\n stderrLines([message]);\n}\n\n/** `lines` to stderr in one write, or each to `console.warn`. Never throws. */\nexport function stderrLines(lines: readonly string[]): void {\n try {\n // eslint-disable-next-line no-restricted-syntax -- this is the guarded read\n const stderr = typeof process !== \"undefined\" ? process.stderr : undefined;\n if (typeof stderr?.write === \"function\") return void stderr.write(lines.map((line) => `${line}\\n`).join(\"\"));\n } catch {\n // An ended or stand-in stderr: try `console.warn`.\n }\n for (const line of lines) {\n try {\n // eslint-disable-next-line no-console -- console.warn writes to stderr, never to stdout\n console.warn(line);\n } catch {\n // Nowhere left to report it.\n }\n }\n}\n\n/** `String(err)`, which throws for an object with no usable `toString`. */\nexport function printable(err: unknown): string {\n try {\n return String(err);\n } catch {\n return \"(an error that cannot be printed)\";\n }\n}\n","/** True only for `{...}` literals and `Object.create(null)` — the TS\n * analogue of Python's `isinstance(value, dict)`. A class instance, `Date` or\n * `Map` is not one, as it is not a dict in Python. */\nexport function 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/** Any object but an array, class instances included. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\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\nimport { warn } from \"./warn.js\";\nimport { isPlainObject } from \"./_object.js\";\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\nexport const DEPTH_MARKER = \"[REDACTED:depth-limit]\";\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// SPEC §7's whitespace set; JS `\\s` is wider. Held by \"no pattern uses `\\s` or\n// the `u` flag\" in scrub.test.ts.\nconst WS_CHARS = String.raw` \\t\\n\\r\\f\\u00a0`;\nconst PHONE_SEP = String.raw`[${WS_CHARS}\\-.]`;\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.\nexport const PATTERNS: ReadonlyArray<readonly [string, RegExp]> = [\n [\"jwt\", /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b/g],\n [\"bearer\", new RegExp(String.raw`\\bBearer[${WS_CHARS}]+[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 // `-`, `.` or `WS_CHARS`, 10 digits. Conservative — won't catch every\n // international format, but won't trip on every 10-digit identifier.\n [\n \"phone\",\n new RegExp(String.raw`\\b(?:\\+?1${PHONE_SEP}?)?\\(?\\d{3}\\)?${PHONE_SEP}?\\d{3}${PHONE_SEP}?\\d{4}\\b`, \"g\"),\n ],\n];\n\n// Credit-card candidates — Luhn-filtered before redacting to keep false\n// positives down on long numeric IDs (timestamps, order numbers).\nexport const 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/**\n * Stateful recursive scrubber with the default ruleset baked in.\n *\n * Construct one per `withBaton` or `createBaton` 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 private warnedDepth = false;\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 pastTheDepthLimit(): string {\n this.bump(\"depth_limit\");\n if (!this.warnedDepth) {\n this.warnedDepth = true;\n warn(\n `baton: a payload nests deeper than ${DEPTH_LIMIT} levels; containers past that depth are sent as ${JSON.stringify(DEPTH_MARKER)}`,\n );\n }\n return DEPTH_MARKER;\n }\n\n private walk(value: unknown, depth: number, forceField: string | null): unknown {\n if (depth >= DEPTH_LIMIT && (isPlainObject(value) || Array.isArray(value))) {\n return this.pastTheDepthLimit();\n }\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 * The same four sinks as `sinks.py`:\n *\n * - `StdoutSink` — JSONL to stderr, or to a stream the vendor passes (MCP\n * stdio transport reserves stdout for JSON-RPC framing).\n * - `FileSink` — JSONL appended to a file.\n * - `HttpSink` — POST batches to any HTTP endpoint with bearer auth;\n * bounded buffer, retry with backoff, circuit breaker. This is the contract a\n * Console or any compatible collector consumes.\n * - `MultiSink` — every event to each of several sinks.\n */\n\nimport * as fs from \"node:fs\";\nimport * as fsp from \"node:fs/promises\";\nimport { capCodePoints, escapeForLog } from \"./_text.js\";\nimport { MAX_TIMER_MS, raceDeadline, SHUTDOWN_FLUSH_TIMEOUT_MS, TIMED_OUT } from \"./deadline.js\";\nimport { PROCESS_DROPS } from \"./drops.js\";\nimport { ClientReportEventSchema, type Event } from \"./events.js\";\nimport { globalFetch, onProcess, onWorkers } from \"./runtime.js\";\nimport { nextClockSequence } from \"./sequence.js\";\nimport { printable, stderrLine, stderrLines, warn } from \"./warn.js\";\n\nconst REFUSAL_BODY_MAX_LEN = 500;\n/** The least time between two refusal warnings with the same status, so a\n * collector refusing every event is not one warning per event. */\nconst REFUSAL_LOG_MS = 60_000;\n\nexport interface Sink {\n /** Hand one event to the sink. Baton calls a sink you write from a queue,\n * one event at a time for each install or client the sink is given to,\n * never from the vendor's call: a slow write delays later events, not the\n * vendor. */\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 with\n * `SinkClosedError`. */\n aclose(): Promise<void>;\n}\n\n/** `write` was called after `aclose`. */\nexport class SinkClosedError extends Error {\n override name = \"SinkClosedError\";\n}\n\n/** By name, not `instanceof`: a vendor sink may throw the class from the\n * other build (ESM or CommonJS) of this package. */\nexport function isSinkClosed(err: unknown): boolean {\n return err instanceof Error && err.name === \"SinkClosedError\";\n}\n\nconst warnedClosed = new WeakSet<Sink>();\n\n/** SPEC §11.2 rules 7 and 8: dropped, counted under `after_close`, and\n * warned about once for each sink passed. Baton passes its queue, or an\n * `HttpSink` that has none, so that is once per queue. */\nexport function droppedAfterClose(sink: Sink): void {\n PROCESS_DROPS.add(\"after_close\");\n if (warnedClosed.has(sink)) return;\n warnedClosed.add(sink);\n warn(\"baton: the sink is closed; further events are dropped.\");\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 if (isSinkClosed(err)) return droppedAfterClose(sink);\n PROCESS_DROPS.add(\"write_failed\");\n stderrLine(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}`);\n }\n}\n\nfunction isTimerMs(value: unknown): value is number {\n return typeof value === \"number\" && value >= 0 && value <= MAX_TIMER_MS;\n}\n\nfunction timerMsOption(given: unknown, name: string, fallback: number): number {\n if (isTimerMs(given)) return given;\n if (given !== undefined) warn(`baton: ${name} must be from 0 to ${MAX_TIMER_MS} ms; using ${fallback}.`);\n return fallback;\n}\n\nfunction shutdownBudgetMs(sink: Sink): number {\n try {\n // MultiSink runs its sinks side by side, so it needs the longest budget.\n if (sink instanceof MultiSink) return Math.max(...sink[\"sinks\"].map(shutdownBudgetMs));\n if (sink instanceof QueuedSink) return shutdownBudgetMs(sink.inner);\n const budget: unknown = sink instanceof HttpSink ? sink[\"shutdownFlushTimeoutMs\"] : undefined;\n if (isTimerMs(budget)) return budget;\n } catch {\n // A Proxy or subclass whose read throws gets the default.\n }\n return SHUTDOWN_FLUSH_TIMEOUT_MS;\n}\n\n/** A sink's `flush()` or `aclose()`, telling Baton's own how much time is\n * left. Any other, a subclass's override included, is called as it is. */\nexport function callWithin(sink: Sink, method: \"flush\" | \"aclose\", ms: number): Promise<void> {\n if (sink[method] === HttpSink.prototype[method]) return (sink as HttpSink)[`${method}Within`](ms);\n if (sink[method] === MultiSink.prototype[method]) return (sink as MultiSink)[`${method}Within`](ms);\n return sink[method]();\n}\n\n/** Run a sink's `flush()` or `aclose()` for the vendor (or `work`, which is\n * handed the budget and ends in one): never rejects, and returns within the\n * sink's shutdown budget. The budget gets a little extra, so `HttpSink`, which\n * enforces its own, is the one whose warning, which counts what was left, is\n * shown. */\nexport async function boundedSinkCall(\n sink: Sink,\n method: \"flush\" | \"aclose\",\n work: (budgetMs: number) => unknown = () => sink[method](),\n): Promise<void> {\n const what = `${method}()`;\n const budget = shutdownBudgetMs(sink);\n const ms = budget + 250;\n // `Promise.resolve().then(work)` also catches a sync throw and a method\n // that returns no promise.\n const settled = Promise.resolve()\n .then(() => work(budget))\n .then(\n () => undefined,\n (err: unknown) => warn(`baton: ${what} failed: ${printable(err)}`),\n );\n if ((await raceDeadline(settled, ms)) === TIMED_OUT) {\n warn(`baton: ${what} took over ${String(ms)} ms and was left unfinished.`);\n }\n}\n\n// =============================================================================\n// StdoutSink — JSONL to a writable stream (default: stderr)\n// =============================================================================\n\nexport interface StdoutSinkOptions {\n /** Defaults to stderr (`console.warn` where `process.stderr` is missing or\n * cannot write): the MCP\n * stdio transport reserves stdout for JSON-RPC framing. Pass\n * `process.stdout` for non-MCP (library API) use if preferred. */\n stream?: NodeJS.WritableStream;\n}\n\nexport class StdoutSink implements Sink {\n private readonly stream: NodeJS.WritableStream | undefined;\n private closed = false;\n\n constructor(options: StdoutSinkOptions = {}) {\n this.stream = options.stream;\n }\n\n async write(event: Event): Promise<void> {\n if (this.closed) throw new SinkClosedError(\"StdoutSink is closed\");\n const line = JSON.stringify(event);\n if (this.stream) this.stream.write(line + \"\\n\");\n else stderrLine(line);\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// FileSink — JSONL append to a path\n// =============================================================================\n\n/** Appends one JSON envelope per line to a file, opened on the first write so\n * an unused sink creates no file. Each line reaches the file before `write`\n * resolves, so `tail -f` sees it at once. */\nexport class FileSink implements Sink {\n private file: fsp.FileHandle | null = null;\n private closeOnce: Promise<void> | undefined;\n /** Writes run one after another: two at once on one file can interleave. */\n private last: Promise<unknown> = Promise.resolve();\n private closed = false;\n\n constructor(private readonly path: string) {}\n\n async write(event: Event): Promise<void> {\n if (this.closed) throw new SinkClosedError(\"FileSink is closed\");\n const line = JSON.stringify(event) + \"\\n\";\n const written = this.last.then(async () => {\n this.file ??= await fsp.open(this.path, \"a\");\n await this.file.appendFile(line);\n });\n this.last = written.catch(() => undefined);\n await written;\n }\n\n async flush(): Promise<void> {\n await this.last;\n }\n\n /** A second call waits for the first (SPEC §11.2 rule 7). */\n aclose(): Promise<void> {\n this.closed = true;\n this.closeOnce ??= this.last.then(async () => {\n await this.file?.close();\n this.file = null;\n });\n return this.closeOnce;\n }\n}\n\n// =============================================================================\n// MultiSink — fan out to several sinks\n// =============================================================================\n\n/** Sends each event to every sink, e.g. `new MultiSink([new StdoutSink(),\n * new HttpSink(...)])` to watch what is shipped. Every sink is tried even when\n * one fails; one failure is rethrown as is, several as an `AggregateError`. */\nexport class MultiSink implements Sink {\n private readonly sinks: readonly Sink[];\n\n constructor(sinks: readonly Sink[]) {\n if (sinks.length === 0) throw new Error(\"MultiSink requires at least one sink\");\n this.sinks = [...sinks];\n }\n\n write(event: Event): Promise<void> {\n return this.fanOut((sink) => sink.write(event));\n }\n\n flush(): Promise<void> {\n return this.flushWithin(Infinity);\n }\n\n aclose(): Promise<void> {\n return this.acloseWithin(Infinity);\n }\n\n private flushWithin(ms: number): Promise<void> {\n return this.fanOut((sink) => callWithin(sink, \"flush\", ms));\n }\n\n private acloseWithin(ms: number): Promise<void> {\n return this.fanOut((sink) => callWithin(sink, \"aclose\", ms));\n }\n\n private async fanOut(op: (sink: Sink) => Promise<void>): Promise<void> {\n // The async wrapper turns a sink that throws synchronously into a rejection.\n const results = await Promise.allSettled(this.sinks.map(async (sink) => op(sink)));\n let errors = results.flatMap((r): unknown[] => (r.status === \"rejected\" ? [r.reason] : []));\n // Another sink took the event, so it was not lost.\n if (errors.length < results.length) errors = errors.filter((e) => !isSinkClosed(e));\n if (errors.length === 0) return;\n if (errors.length === 1 || errors.every(isSinkClosed)) throw errors[0];\n throw new AggregateError(errors, \"MultiSink fan-out failures\");\n }\n}\n\n// =============================================================================\n// QueuedSink — every sink but HttpSink, written off the vendor's call\n// =============================================================================\n\nconst QUEUE_BOUND = 1000;\n/** Events written before the writer gives the event loop a turn. */\nconst WRITES_PER_TURN = 100;\n/** The part of close's budget kept for the inner sink's own close. */\nconst CLOSE_GRACE_MS = 250;\n\n/** Later than a microtask, so the vendor's call goes on before the write. */\nconst later = (run: () => void): void => {\n if (typeof setImmediate === \"function\") setImmediate(run);\n else setTimeout(run, 0);\n};\n\nconst withUnwrittenEvents = new Set<QueuedSink>();\n/** Each `process` the exit hand-off was tried on, once: a test may swap in a\n * stand-in, and the real `process` still needs its own. */\nconst exitTriedOn = new WeakSet<object>();\n\n/** At `process.exit()` nothing can be awaited: queued events go synchronously\n * to a `StdoutSink` on stdout/stderr or a `FileSink`, and are reported as\n * possibly lost for any other sink (SPEC §11.2 rules 7 and 8). */\nfunction hookExit(): void {\n const target = typeof process !== \"undefined\" ? process : undefined;\n if (target === undefined || exitTriedOn.has(target)) return;\n exitTriedOn.add(target);\n onProcess(\"exit\", () => {\n try {\n let unsure = 0;\n for (const sink of withUnwrittenEvents) unsure += sink.handOffAtExit();\n if (unsure > 0) stderrLine(`baton: process exiting; ${unsure} event(s) may not have been written.`);\n } catch {\n // A throw here would turn the vendor's clean exit into a crash.\n }\n });\n}\n\n/** Writes `events` before it returns, for the sinks that can: at exit nothing\n * can be awaited. False for any other sink, or a stream that may write later. */\nfunction writeNow(sink: Sink, events: Event[]): boolean {\n const json = (): string[] => events.map((event) => JSON.stringify(event));\n const lines = (): string => json().map((line) => line + \"\\n\").join(\"\");\n if (sink instanceof StdoutSink) {\n const stream = sink[\"stream\"];\n // eslint-disable-next-line no-restricted-syntax -- reached only when the vendor passed a stream, and only compared\n if (stream !== undefined && stream !== process.stdout && stream !== process.stderr) return false;\n if (sink[\"closed\"]) return true;\n if (stream === undefined) stderrLines(json());\n else stream.write(lines());\n } else if (sink instanceof FileSink) {\n if (!sink[\"closed\"]) fs.appendFileSync(sink[\"path\"], lines());\n } else return false;\n return true;\n}\n\n/** Holds events for `inner` and writes them one at a time, in order, after\n * the call that recorded them has gone on, so a slow, stuck or failing sink\n * never slows the vendor (SPEC §11.2 rules 3 and 8). */\nexport class QueuedSink implements Sink {\n private readonly queue: Event[] = [];\n private closed = false;\n private draining = false;\n /** Set when close ran out of time or the process is exiting: what was left is already handled. */\n private abandoned = false;\n private inFlight = 0;\n /** A flush waits until `settled`, the events written or lost, reaches `taken` as it was. */\n private taken = 0;\n private settled = 0;\n /** Writes that returned, so a dropped event does not look like progress. */\n private ended = 0;\n /** `ended` when a flush waited its whole budget: until a write ends, later flushes return at once. */\n private stuckAt: number | null = null;\n private waiters: { upTo: number; resolve: () => void }[] = [];\n private overflowWarned = false;\n private failWarned = false;\n private copyWarned = false;\n private closeOnce: Promise<void> | undefined;\n\n constructor(readonly inner: Sink) {}\n\n private get unwritten(): number {\n return this.queue.length + this.inFlight;\n }\n\n /** Writes what waits to a `StdoutSink` or `FileSink` at once; answers how\n * many events may not be written. */\n handOffAtExit(): number {\n this.abandoned = true;\n const waiting = this.queue.splice(0);\n let written = false;\n try {\n written = waiting.length === 0 || writeNow(this.inner, waiting);\n } catch {\n // Counted below as not written.\n }\n return this.inFlight + (written ? 0 : waiting.length);\n }\n\n async write(event: Event): Promise<void> {\n if (this.closed) throw new SinkClosedError(\"the sink is closed\");\n // A copy, because the sink writes later: by then the vendor may have\n // changed a params or result object the event still points at. JSON,\n // so the copy is what a sink that writes JSON would have written.\n let copy: Event;\n try {\n copy = JSON.parse(JSON.stringify(event)) as Event;\n } catch (err) {\n PROCESS_DROPS.add(\"encode_failed\");\n if (!this.copyWarned) {\n this.copyWarned = true;\n // Only the error's name: its message can quote the event's own text.\n warn(`baton: an event could not be copied and was dropped (${(err as Error)?.name ?? \"Error\"}). Later ones are not logged.`);\n }\n return;\n }\n this.queue.push(copy);\n this.taken++;\n if (this.queue.length > QUEUE_BOUND) {\n this.queue.shift();\n this.settle();\n PROCESS_DROPS.add(\"buffer_full\");\n if (!this.overflowWarned) {\n this.overflowWarned = true;\n warn(`baton: the sink's queue is full (${QUEUE_BOUND}); oldest events dropped. Further overflows will be silent.`);\n }\n }\n withUnwrittenEvents.add(this);\n hookExit();\n if (!this.draining) {\n this.draining = true;\n later(() => void this.drain());\n }\n }\n\n /** Waits for the events written before it, not for later ones (SPEC §11.2 rule 7). */\n async flush(): Promise<void> {\n if (this.closed || this.stuckAt === this.ended) return;\n const budget = shutdownBudgetMs(this.inner);\n const start = performance.now();\n if ((await raceDeadline(this.settledUpTo(this.taken), budget)) === TIMED_OUT) this.stuckAt = this.ended;\n await callWithin(this.inner, \"flush\", Math.max(0, budget - (performance.now() - start)));\n }\n\n /** A second call waits for the first (SPEC §11.2 rule 7). */\n aclose(): Promise<void> {\n this.closeOnce ??= this.close(shutdownBudgetMs(this.inner));\n return this.closeOnce;\n }\n\n /** Takes events until the queue is empty, as `HttpSink` does, so an event\n * recorded while close runs is not refused. */\n private async close(ms: number): Promise<void> {\n const start = performance.now();\n const deadline = start + ms - Math.min(CLOSE_GRACE_MS, ms / 2);\n let timedOut = false;\n while (this.settled < this.taken && !timedOut) {\n timedOut = (await raceDeadline(this.settledUpTo(this.taken), deadline - performance.now())) === TIMED_OUT;\n }\n this.closed = true;\n if (timedOut) {\n const unwritten = this.unwritten;\n this.abandoned = true;\n this.queue.length = 0;\n withUnwrittenEvents.delete(this);\n PROCESS_DROPS.add(\"unsent_at_close\", unwritten);\n warn(`baton: closed with ${unwritten} event(s) not yet written to the sink.`);\n }\n await callWithin(this.inner, \"aclose\", Math.max(0, ms - (performance.now() - start)));\n }\n\n private async drain(): Promise<void> {\n try {\n let event: Event | undefined;\n let written = 0;\n while (!this.abandoned && (event = this.queue.shift()) !== undefined) {\n this.inFlight = 1;\n try {\n await this.inner.write(event);\n } catch (err) {\n if (!this.abandoned) this.lose(err);\n } finally {\n this.inFlight = 0;\n this.ended++;\n this.settle();\n }\n // A sink that answers at once would otherwise hold the event loop for the whole queue.\n if (++written % WRITES_PER_TURN === 0) await new Promise<void>((resolve) => later(resolve));\n }\n } catch {\n // Only `lose` can get here, after it counted the event: a warning\n // that throws must not stop the queue.\n } finally {\n this.draining = false;\n if (this.queue.length === 0) withUnwrittenEvents.delete(this);\n else if (!this.abandoned) {\n this.draining = true;\n later(() => void this.drain());\n }\n }\n }\n\n private lose(err: unknown): void {\n if (isSinkClosed(err)) return droppedAfterClose(this);\n PROCESS_DROPS.add(\"write_failed\");\n if (this.failWarned) return;\n this.failWarned = true;\n warn(`baton: the sink failed to write an event; it was dropped. Later failures are not logged: ${printable(err)}`);\n }\n\n private settle(): void {\n this.settled++;\n this.waiters = this.waiters.filter((w) => {\n if (w.upTo > this.settled) return true;\n w.resolve();\n return false;\n });\n }\n\n private settledUpTo(upTo: number): Promise<void> {\n if (this.settled >= upTo) return Promise.resolve();\n return new Promise((resolve) => this.waiters.push({ upTo, resolve }));\n }\n}\n\n/** HttpSink already queues; any other sink gets a new `QueuedSink`, one for\n * each install or client. */\nexport function offTheCall(sink: Sink): Sink {\n // An HttpSink subclass that keeps HttpSink's write still only queues.\n if (sink instanceof QueuedSink || (sink instanceof HttpSink && sink.write === HttpSink.prototype.write)) return sink;\n return new QueuedSink(sink);\n}\n\n// =============================================================================\n// HttpSink — batches + bearer + bounded buffer + retry + circuit breaker\n// =============================================================================\n\nconst BATCH_OPEN = '{\"events\":[';\nconst BATCH_CLOSE = \"]}\";\nexport const BATCH_FRAME_BYTES = (BATCH_OPEN + BATCH_CLOSE).length;\n/** SPEC §2.5's caps on one batch. */\nconst BATCH_MAX_EVENTS = 100;\nexport const BATCH_MAX_BYTES = 1_048_576;\nconst FLUSH_INTERVAL_MS = 5000;\n/** SPEC §2.5: `Retry-After` is honoured from 1 to 60 seconds. */\nconst RETRY_AFTER_MIN_S = 1;\nconst RETRY_AFTER_MAX_S = 60;\n\ntype SendOutcome = \"success\" | \"permanent_failure\" | \"transient_failure\";\n\n/** An event waiting to be sent, or the loss report riding a batch\n * (`reportSum` set), which is never in the buffer. */\ninterface Waiting {\n event: Event;\n json: string;\n bytes: number;\n writtenAt: number;\n reportSum?: number;\n}\n\ninterface Refusal {\n kind: string;\n detail: string;\n}\n\ntype Answer =\n | { kind: \"answered\"; refused: Map<string, Refusal> }\n | { kind: \"refused\"; refusal: Refusal; status: number }\n | { kind: \"too_large\" }\n | { kind: \"no_batch_endpoint\" }\n | { kind: \"transient\"; retryAfterMs: number | null };\n\nconst utf8 = new TextEncoder();\n\nfunction utf8Bytes(text: string): number {\n return typeof Buffer === \"undefined\" ? utf8.encode(text).length : Buffer.byteLength(text, \"utf8\");\n}\n\nfunction sum(values: Iterable<number>): number {\n let total = 0;\n for (const value of values) total += value;\n return total;\n}\n\n/** A whole number of seconds, clamped; `null` for anything else (SPEC §2.5). */\nfunction retryAfterMs(header: string | null): number | null {\n const value = header?.trim() ?? \"\";\n if (!/^\\d+$/.test(value)) return null;\n return Math.min(Math.max(Number(value), RETRY_AFTER_MIN_S), RETRY_AFTER_MAX_S) * 1000;\n}\n\ntype BatchKey = Pick<Event, \"tenant_id\" | \"vendor_id\">;\n\nfunction sameBatch(a: BatchKey, b: BatchKey): boolean {\n return a.tenant_id === b.tenant_id && a.vendor_id === b.vendor_id;\n}\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 return this.msUntilRequest() === 0;\n }\n\n msUntilRequest(): number {\n if (this.openedAt === null) return 0;\n return Math.max(this.openedAt + this.resetMs - Date.now(), 0);\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 /** How long the flush at process exit, or an explicit `flush()` or\n * `aclose()`, may take in total, in ms, at most 2^31 - 1. Default 3000. */\n shutdownFlushTimeoutMs?: number;\n /** The longest an event waits before its batch is sent, in ms. Default\n * 5000, or 0 on Cloudflare Workers. At 0 a write sends at once. */\n flushIntervalMs?: number;\n /** Injectable for tests; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n}\n\n/** POST events to an HTTP endpoint in batches. Bounded buffer + retry +\n * circuit breaker.\n *\n * This is the contract a Console or any compatible collector consumes:\n * `POST {url}/v0/events/batch` (SPEC §2.5) with `Authorization: Bearer\n * {apiKey}` and `{\"events\": [...]}` of SPEC §11.4 envelopes. A batch goes when\n * 100 events wait, when the next would take the body over 1 MiB, or\n * `flushIntervalMs` after the oldest waiting one was written. A collector\n * with no batch endpoint gets one event per `POST {url}/v0/events`.\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 /** Waiting events only: a batch being sent is out of it, so the bound\n * never pushes out an event in flight (SPEC §11.2 rule 4). */\n private readonly buffer: Waiting[] = [];\n private bufferedBytes = 0;\n private sendingEvents = 0;\n private readonly bufferSize: number;\n private readonly requestTimeoutMs: number;\n private readonly shutdownFlushTimeoutMs: number;\n private readonly flushIntervalMs: number;\n /** Set when an exit pass ends; cleared once a normal drain sends\n * everything, which means the process went on. */\n private exitPassRan = false;\n /** Whether the exit pass warned about every event now buffered. */\n private unsentWarned = false;\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 /** Per status or refusal code, so a new kind of refusal, such as a 401\n * after a 422, still warns. */\n private readonly refusals = new Map<string, { loggedAt: number; unlogged: number }>();\n /** Aborted once `aclose()` returns: nothing Baton started may keep the\n * process alive after the vendor closed it. */\n private readonly closing = new AbortController();\n /** The drain chain's tail when a flush() or aclose() gave up waiting, until it settles. */\n private stalledDrain: Promise<unknown> | null = null;\n private skipWarnedFor: Promise<unknown> | null = null;\n private closeOnce: Promise<void> | undefined;\n private drainChain: Promise<void> = Promise.resolve();\n private queuedDrain: Promise<void> | null = null;\n /** Whether the queued pass sends everything waiting, not only what is due. */\n private forceNext = false;\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n /** Set by a failed batch: only the timer, a flush, a close or, at\n * `flushIntervalMs` 0, a write after `retryFrom` tries again. */\n private waitForTimer = false;\n /** When a failed batch may be tried again. At `flushIntervalMs` 0 the\n * first write from then retries, as a Worker may drop the timer. */\n private retryFrom = 0;\n /** Nothing is sent before this `Date.now()`, from a 429's `Retry-After`. */\n private retryAt = 0;\n /** Set for the life of the sink by a 404 or 405 on the batch path. */\n private batchless = false;\n private exitHooks: { beforeExit: () => void; exit: () => void; off: () => void } | null = null;\n /** The `process` the exit hooks were last tried on, so a refusal is not retried per write. */\n private exitHooksTriedOn: object | undefined;\n /** The least time between two of this sink's loss reports. */\n private static reportIntervalMs = 60_000;\n /** Totals only grow, so their sum tells whether they changed. */\n private reportedSum = 0;\n private lastReportAt = -Infinity;\n private reportsStopped = false;\n /** The envelope of a report due to ride the next batch, and when it was set up.\n * `built` is the report once taken: a kept batch resends it unchanged (SPEC §11.4.7). */\n private pendingReport: (Pick<Event, \"tenant_id\" | \"vendor_id\" | \"consent_token\"> & { built?: Waiting }) | null = null;\n private reportSetAt = 0;\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.requestTimeoutMs = options.requestTimeoutMs ?? 1000;\n this.shutdownFlushTimeoutMs = timerMsOption(\n options.shutdownFlushTimeoutMs,\n \"shutdownFlushTimeoutMs\",\n SHUTDOWN_FLUSH_TIMEOUT_MS,\n );\n // A Worker may drop a timer its request left behind, and with it every later send.\n this.flushIntervalMs = timerMsOption(options.flushIntervalMs, \"flushIntervalMs\", onWorkers() ? 0 : FLUSH_INTERVAL_MS);\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 ?? globalFetch;\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 * would write a publishable key into the vendor's logs. 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 private get closed(): boolean {\n return this.closing.signal.aborted;\n }\n\n private get unsent(): number {\n return this.buffer.length + this.sendingEvents;\n }\n\n /** Encodes at once, not when the batch is cut, because the byte cap\n * decides when a batch goes. */\n async write(event: Event): Promise<void> {\n if (this.closed) throw new SinkClosedError(\"HttpSink is closed\");\n const json = this.encode(event);\n if (json === null) return;\n const bytes = utf8Bytes(json);\n if (BATCH_FRAME_BYTES + bytes > BATCH_MAX_BYTES) {\n this.refuse(1, { kind: \"over 1 MiB\", detail: `${bytes} bytes` }, false);\n return;\n }\n this.enqueue({ event, json, bytes, writtenAt: Date.now() });\n this.unsentWarned = false;\n const held = this.waitForTimer && !(this.flushIntervalMs === 0 && Date.now() >= this.retryFrom);\n if (!held && (this.flushIntervalMs === 0 || this.batchIsFull())) void this.scheduleDrain(false);\n else this.armTimer(Math.max(this.buffer[0]!.writtenAt + this.flushIntervalMs, held ? this.retryFrom : 0) - Date.now());\n this.ensureExitHooksRegistered();\n }\n\n flush(): Promise<void> {\n return this.flushWithin(Infinity);\n }\n\n /** A second call waits for the first (SPEC §11.2 rule 7). */\n aclose(): Promise<void> {\n return this.acloseWithin(Infinity);\n }\n\n private async flushWithin(ms: number): Promise<void> {\n if (this.closed) return;\n await this.drainWithinBudget(\"flush()\", Math.min(ms, this.shutdownFlushTimeoutMs));\n }\n\n private acloseWithin(ms: number): Promise<void> {\n this.closeOnce ??= this.close(Math.min(ms, this.shutdownFlushTimeoutMs));\n return this.closeOnce;\n }\n\n private async close(ms: number): Promise<void> {\n this.stopReports();\n await this.drainWithinBudget(\"aclose()\", ms);\n this.closing.abort();\n this.clearTimer();\n const unsent = this.unsent;\n if (unsent > 0) {\n PROCESS_DROPS.add(\"unsent_at_close\", unsent);\n warn(`baton: the sink closed with ${unsent} event(s) unsent.`);\n }\n this.warnUnloggedRefusals(\"the sink closed\");\n this.exitHooks?.off();\n this.exitHooks = null;\n }\n\n /** SPEC §11.2 rule 7: an explicit flush or close returns within `ms` and\n * never rejects. While an earlier wait's drain is still stuck, a flush\n * returns at once, without queuing a pass, and a close gives it `ms`. The\n * drain is not cancelled here, so after `flush()` it goes on sending;\n * `aclose()` stops it. */\n private async drainWithinBudget(what: \"flush()\" | \"aclose()\", ms: number): Promise<void> {\n if (this.stalledDrain) {\n if (what === \"aclose()\") {\n await raceDeadline(this.stalledDrain, ms);\n return;\n }\n if (this.skipWarnedFor !== this.stalledDrain) {\n this.skipWarnedFor = this.stalledDrain;\n warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.unsent} event(s) wait to be sent.`);\n }\n return;\n }\n const settled = this.scheduleDrain(true).catch(() => undefined);\n if ((await raceDeadline(settled, ms)) !== TIMED_OUT) return;\n // A wait shorter than the budget, the time a caller had left, does not\n // show that the drain is stuck.\n if (ms < this.shutdownFlushTimeoutMs) return;\n const stalled = this.drainChain.catch(() => undefined);\n this.stalledDrain = stalled;\n void stalled.then(() => {\n if (this.stalledDrain === stalled) this.stalledDrain = null;\n });\n if (what === \"flush()\") {\n warn(`baton: flush() took over ${ms} ms; it goes on in the background.`);\n }\n }\n\n private enqueue(waiting: Waiting): void {\n this.buffer.push(waiting);\n this.bufferedBytes += waiting.bytes;\n this.dropOverflow();\n }\n\n private dropOverflow(): void {\n while (this.buffer.length > this.bufferSize) {\n PROCESS_DROPS.add(\"buffer_full\");\n if (!this.overflowWarned) {\n warn(\n `Baton HTTP sink buffer full (${this.bufferSize}); oldest events dropped. Further overflows will be silent.`,\n );\n this.overflowWarned = true;\n }\n this.bufferedBytes -= this.buffer.shift()!.bytes;\n }\n }\n\n private batchIsFull(): boolean {\n return (\n this.buffer.length >= BATCH_MAX_EVENTS ||\n BATCH_FRAME_BYTES + this.bufferedBytes + this.buffer.length - 1 > BATCH_MAX_BYTES\n );\n }\n\n /** The timer must not keep the vendor's process alive: the exit hooks send\n * what is left. */\n private armTimer(delayMs: number): void {\n if (this.flushTimer !== null || this.closed) return;\n const timer = setTimeout(\n () => {\n this.flushTimer = null;\n this.waitForTimer = false;\n void this.scheduleDrain(false);\n },\n Math.min(Math.max(delayMs, 0), MAX_TIMER_MS),\n );\n (timer as { unref?: () => void }).unref?.();\n this.flushTimer = timer;\n }\n\n private clearTimer(): void {\n if (this.flushTimer === null) return;\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n\n /** Runs `drainLocked` after the pass under way, one pass at a time, so two\n * never send at once or race on the buffer. A pass not yet started is\n * shared by every caller: one per write would grow without bound while a\n * slow collector holds a pass. */\n private scheduleDrain(force: boolean): Promise<void> {\n this.forceNext ||= force;\n if (this.queuedDrain) return this.queuedDrain;\n const run = (): Promise<void> => {\n this.queuedDrain = null;\n const forced = this.forceNext;\n this.forceNext = false;\n return this.drainLocked(forced);\n };\n this.queuedDrain = this.drainChain.then(run, run);\n // One handler per pass, here, so a caller that drops the promise cannot\n // leave an unhandled rejection, and a write adds nothing to a queued pass.\n this.queuedDrain.catch(() => undefined);\n this.drainChain = this.queuedDrain;\n return this.queuedDrain;\n }\n\n /** Best-effort flush when the process is about to exit without an\n * explicit `aclose()`. SIGKILL, or SIGTERM with no installed handler, skip\n * both hooks: a vendor needing that guarantee must call `aclose()` from\n * their own handler. */\n private ensureExitHooksRegistered(): void {\n const target = typeof process !== \"undefined\" ? process : undefined;\n if (this.exitHooks || target === undefined || target === this.exitHooksTriedOn) return;\n this.exitHooksTriedOn = target;\n const beforeExit = (): void => {\n // Node re-fires `beforeExit` once the pass's work is done; one pass only.\n if (this.unsent === 0 || this.exitPassRan) {\n this.warnUnloggedRefusals(\"process exiting\");\n return;\n }\n this.drainChain = this.drainChain\n .then(\n () => this.exitPass(),\n () => this.exitPass(),\n )\n .catch(() => undefined);\n };\n // `process.exit()` skips `beforeExit`. At `exit` nothing can be sent and\n // `emitWarning` would never print, so the count is written straight out.\n const exit = (): void => {\n try {\n if (this.unsent > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());\n this.warnUnloggedRefusals(\"process exiting\", stderrLine);\n } catch {\n // A throw here would turn the vendor's clean exit into a crash.\n }\n };\n const offBeforeExit = onProcess(\"beforeExit\", beforeExit);\n const offExit = onProcess(\"exit\", exit);\n if (offBeforeExit === undefined || offExit === undefined) {\n // Both or neither: workersRuntime.test.ts, \"HttpSink leaves no exit hook behind\".\n offBeforeExit?.();\n offExit?.();\n return;\n }\n this.exitHooks = { beforeExit, exit, off: () => (offBeforeExit(), offExit()) };\n }\n\n /** One attempt per batch, no retry, within `shutdownFlushTimeoutMs` in\n * total (SPEC §11.2); what is left is reported, not sent. */\n private async exitPass(): Promise<void> {\n const deadline = Date.now() + this.shutdownFlushTimeoutMs;\n while (this.circuit.canRequest() && Date.now() >= this.retryAt && Date.now() < deadline) {\n const batch = this.takeBatch(false);\n if (batch === null) break;\n if (!this.putBack(await this.sendBatch(batch, 0, deadline), batch)) break;\n }\n this.exitPassRan = true;\n this.unsentWarned = true;\n if (this.unsent > 0) warn(this.unsentAtExit());\n this.warnUnloggedRefusals(\"process exiting\");\n }\n\n private unsentAtExit(): string {\n return `baton: process exiting with ${this.unsent} unsent event(s).`;\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 /** Counts `n` refused events and logs them, at most once a minute per\n * kind. A refused event is otherwise dropped silently, which looks the same\n * from the vendor's process as an accepted one. The collector's own message\n * is logged because it names the field at fault; it is capped and escaped\n * because it is a remote server's text landing in the vendor's log. */\n private refuse(n: number, { kind, detail }: Refusal, byCollector = true): void {\n if (n === 0) return;\n PROCESS_DROPS.add(\"refused\", n);\n const unlogged = this.refusalToLog(kind, n);\n if (unlogged === null) return;\n const what = n === 1 ? \"an event and it has\" : `${n} events and they have`;\n warn(\n `baton: ${byCollector ? \"collector REFUSED\" : \"REFUSED, unsent,\"} ${what} been dropped (${kind}): ` +\n `${escapeForLog(capCodePoints(detail, REFUSAL_BODY_MAX_LEN))} — the event is gone; nothing retries a refusal.` +\n (unlogged > 0 ? ` ${unlogged} more refused since the last such warning.` : \"\"),\n );\n }\n\n private warnUnloggedRefusals(when: string, emit: (message: string) => void = warn): void {\n let total = 0;\n for (const seen of this.refusals.values()) {\n total += seen.unlogged;\n seen.unlogged = 0;\n }\n if (total > 0) emit(`baton: ${when}; ${total} more event(s) refused since the last such warning.`);\n }\n\n /** How many refusals of `kind` went unlogged before these `n`, or `null`\n * when these go unlogged too. */\n private refusalToLog(kind: string, n: number): number | null {\n const now = performance.now();\n const seen = this.refusals.get(kind);\n if (seen !== undefined && now - seen.loggedAt < REFUSAL_LOG_MS) {\n seen.unlogged += n;\n return null;\n }\n this.refusals.set(kind, { loggedAt: now, unlogged: 0 });\n return seen?.unlogged ?? 0;\n }\n\n /** Enough of the body for `REFUSAL_BODY_MAX_LEN` code points; the rest is\n * cancelled unread, so a large error page does not hold the drain. */\n private static async readHead(response: Response): Promise<string> {\n const reader = (response.body as ReadableStream<Uint8Array> | null)?.getReader();\n if (reader === undefined) return \"\";\n const decoder = new TextDecoder();\n let text = \"\";\n try {\n // A code point is at most two UTF-16 units.\n while (text.length < REFUSAL_BODY_MAX_LEN * 2) {\n const { done, value } = await reader.read();\n if (done) return text + decoder.decode();\n text += decoder.decode(value, { stream: true });\n }\n return text;\n } finally {\n void reader.cancel().catch(() => {});\n }\n }\n\n /** Sends what is due, one batch at a time; `force` (a flush or close) sends\n * everything waiting. A report set up before the pass rides along; one set\n * up by this pass's own delivery waits for the next batch. */\n private async drainLocked(force: boolean): Promise<void> {\n let failed = false;\n let reportDue = this.pendingReport !== null;\n while (!this.closed) {\n if (!this.isDue(force, reportDue)) break;\n // SPEC §2.5: nothing is sent during a 429's wait, not even at close.\n if (!this.circuit.canRequest() || Date.now() < this.retryAt) {\n failed = true;\n break;\n }\n const batch = this.takeBatch(reportDue);\n if (batch === null) break;\n if (batch.some((w) => w.reportSum !== undefined)) reportDue = false;\n if (!this.putBack(await this.sendBatch(batch, this.maxRetries, Infinity), batch)) {\n failed = true;\n break;\n }\n }\n if (!failed && this.unsent === 0) this.exitPassRan = false;\n this.waitForTimer = failed;\n this.clearTimer();\n if (failed) {\n const wait = Math.max(this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest());\n this.retryFrom = Date.now() + wait;\n if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(wait);\n return;\n }\n const next = Math.min(this.buffer[0]?.writtenAt ?? Infinity, this.reportRidesHead() ? this.reportSetAt : Infinity);\n if (next !== Infinity) this.armTimer(next + this.flushIntervalMs - Date.now());\n }\n\n /** A due report makes the next batch due only when it can ride it; the\n * timer is armed the same way, so a pass that sends nothing never re-arms\n * it at a time already past. */\n private isDue(force: boolean, reportDue: boolean): boolean {\n const now = Date.now();\n if (reportDue && this.reportRidesHead() && (force || this.reportSetAt + this.flushIntervalMs <= now)) return true;\n return this.buffer.length > 0 && (force || this.batchIsFull() || this.buffer[0]!.writtenAt + this.flushIntervalMs <= now);\n }\n\n /** A pending report can go in the next batch: alone, or with the head event's tenant and vendor. */\n private reportRidesHead(): boolean {\n const head = this.buffer[0];\n return this.pendingReport !== null && (head === undefined || sameBatch(this.pendingReport, head.event));\n }\n\n /** Takes the head of the buffer that fits one batch: one tenant and vendor\n * (SPEC §2.5), at most 100 events and 1 MiB. A due report with the head\n * event's tenant and vendor takes one of those places, and goes alone when\n * the head event fits only without it. A report that cannot ride the head\n * waits for a batch it can ride. Without a batch endpoint the same events\n * go one per request. */\n private takeBatch(withReport: boolean): Waiting[] | null {\n const batch: Waiting[] = [];\n let bytes = BATCH_FRAME_BYTES - 1;\n let eventBytes = 0;\n const report = withReport && this.reportRidesHead() ? (this.pendingReport!.built ?? this.buildReport()) : null;\n // A due report keeps its place, or a run of full batches never carries it (SPEC §11.4.7).\n const maxEvents = BATCH_MAX_EVENTS - (report ? 1 : 0);\n const maxBytes = BATCH_MAX_BYTES - (report ? 1 + report.bytes : 0);\n const fits = (w: Waiting): boolean =>\n bytes + 1 + w.bytes <= maxBytes &&\n (batch.length === 0 || (batch.length < maxEvents && sameBatch(w.event, batch[0]!.event)));\n for (const waiting of this.buffer) {\n if (!fits(waiting)) break;\n batch.push(waiting);\n bytes += 1 + waiting.bytes;\n eventBytes += waiting.bytes;\n }\n this.buffer.splice(0, batch.length);\n this.bufferedBytes -= eventBytes;\n this.sendingEvents = batch.length;\n if (report !== null) batch.push(report);\n return batch.length > 0 ? batch : null;\n }\n\n /** Puts what a failure `kept` of the batch `taken` back at the head of the\n * buffer, and keeps its report unless `taken` had no events; `true` when\n * nothing was kept. */\n private putBack(kept: Waiting[], taken: Waiting[]): boolean {\n this.sendingEvents = 0;\n // close() has already counted these as unsent_at_close.\n if (this.closed) return kept.length === 0;\n const events: Waiting[] = [];\n for (const waiting of kept) {\n if (waiting.reportSum !== undefined) {\n // Read now, not at take time: a 404 during the send switches to one event per request.\n if (taken.every((w) => w.reportSum !== undefined) || this.batchless) this.pendingReport = null;\n continue;\n }\n events.push(waiting);\n this.bufferedBytes += waiting.bytes;\n }\n this.buffer.unshift(...events);\n this.dropOverflow();\n return kept.length === 0;\n }\n\n /** After a delivery, sets up a report of this process's loss totals (SPEC\n * §11.4.7) to ride the next batch. It stays outside the buffer, so it never\n * pushes an event out and is never counted as one. */\n private maybeReport({ tenant_id, vendor_id, consent_token }: Event): void {\n const now = performance.now();\n if (\n this.reportsStopped ||\n this.pendingReport !== null ||\n now - this.lastReportAt < HttpSink.reportIntervalMs\n ) {\n return;\n }\n if (sum(Object.values(PROCESS_DROPS.total())) === this.reportedSum) return;\n this.lastReportAt = now;\n this.reportSetAt = Date.now();\n this.pendingReport = { tenant_id, vendor_id, consent_token };\n }\n\n private stopReports(): void {\n this.reportsStopped = true;\n this.pendingReport = null;\n }\n\n private buildReport(): Waiting | null {\n if (this.pendingReport === null) return null;\n const { tenant_id, vendor_id, consent_token } = this.pendingReport;\n const totals = PROCESS_DROPS.total();\n try {\n const report = ClientReportEventSchema.parse({\n tenant_id,\n vendor_id,\n consent_token,\n session_id: PROCESS_DROPS.instanceId,\n sequence_number: nextClockSequence(),\n captured_at: new Date().toISOString(),\n payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals },\n });\n const json = JSON.stringify(report);\n this.pendingReport.built = { event: report, json, bytes: utf8Bytes(json), writtenAt: Date.now(), reportSum: sum(Object.values(totals)) };\n return this.pendingReport.built;\n } catch {\n // A lost report is never counted (SPEC §11.4.7).\n this.pendingReport = null;\n return null;\n }\n }\n\n /** Sends one batch, splitting it on 413, until every event in it is\n * delivered or refused. Returns what a failure kept, to go back in the\n * buffer. */\n private async sendBatch(batch: Waiting[], retries: number, deadline: number): Promise<Waiting[]> {\n if (this.batchless && batch.length > 1) return this.sendEachAlone(batch, retries, deadline);\n const batchless = this.batchless;\n const body = batchless ? batch[0]!.json : BATCH_OPEN + batch.map((w) => w.json).join(\",\") + BATCH_CLOSE;\n for (let attempt = 0; ; attempt++) {\n const timeLeft = deadline - Date.now();\n if (timeLeft <= 0) return batch;\n const answer = await this.post(body, batch.length, batchless, Math.min(this.requestTimeoutMs, timeLeft));\n if (answer.kind === \"no_batch_endpoint\") {\n this.batchless = true;\n warn(\"baton: the collector has no batch endpoint; sending one event per request.\");\n return this.sendEachAlone(batch, retries, deadline);\n }\n if (answer.kind === \"too_large\") {\n const half = Math.floor(batch.length / 2);\n const kept = await this.sendBatch(batch.slice(0, half), retries, deadline);\n if (kept.length > 0) return [...kept, ...batch.slice(half)];\n return this.sendBatch(batch.slice(half), retries, deadline);\n }\n if (answer.kind === \"transient\") {\n if (answer.retryAfterMs !== null) {\n this.retryAt = Date.now() + answer.retryAfterMs;\n return batch;\n }\n if (attempt < retries && !this.closed) {\n await this.sleepUnlessClosed(Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs));\n if (!this.closed) continue;\n }\n this.circuit.recordFailure();\n return batch;\n }\n this.circuit.recordSuccess();\n this.settle(batch, answer, batchless);\n return [];\n }\n }\n\n private async sendEachAlone(batch: Waiting[], retries: number, deadline: number): Promise<Waiting[]> {\n for (const [i, waiting] of batch.entries()) {\n if (this.closed) return batch.slice(i);\n const kept = await this.sendBatch([waiting], retries, deadline);\n if (kept.length > 0) return [...kept, ...batch.slice(i + 1)];\n }\n return [];\n }\n\n /** `alone` is one event per request (SPEC §2.5), so a whole refusal there is that event's own. */\n private settle(batch: Waiting[], answer: Extract<Answer, { kind: \"answered\" | \"refused\" }>, alone: boolean): void {\n // close() has already counted these as unsent_at_close.\n if (this.closed) return;\n let lastDelivered: Event | null = null;\n const refused = new Map<string, { first: Refusal; n: number }>();\n for (const waiting of batch) {\n if (waiting.reportSum === undefined) this.sendingEvents -= 1;\n const refusal = answer.kind === \"refused\" ? answer.refusal : answer.refused.get(waiting.event.event_id);\n if (waiting.reportSum !== undefined) {\n this.pendingReport = null;\n if (refusal === undefined) this.reportedSum = waiting.reportSum;\n // A collector that predates `client_report` refuses it this way. A whole\n // batch refused may be another event's fault, and another code is not about the type.\n else if (answer.kind === \"answered\" ? refusal.kind === \"payload_malformed\" : alone && (answer.status === 400 || answer.status === 422)) {\n this.reportsStopped = true;\n }\n } else if (refusal === undefined) {\n lastDelivered = waiting.event;\n } else {\n const seen = refused.get(refusal.kind);\n if (seen) seen.n += 1;\n else refused.set(refusal.kind, { first: refusal, n: 1 });\n }\n }\n for (const { first, n } of refused.values()) this.refuse(n, first);\n if (lastDelivered !== null) {\n PROCESS_DROPS.logRecovery();\n this.maybeReport(lastDelivered);\n }\n }\n\n /** `null`, with a warning, for an event `JSON.stringify` rejects. */\n private encode(event: Event): string | null {\n try {\n return JSON.stringify(event);\n } catch (err) {\n PROCESS_DROPS.add(\"encode_failed\");\n // Only the error's name: its message can quote the event's own text.\n warn(\n `baton: a ${event.event_type} event could not be encoded and has been dropped (${(err as Error)?.name ?? \"Error\"}) — the event is gone; the events after it are still sent.`,\n );\n return null;\n }\n }\n\n private sleepUnlessClosed(ms: number): Promise<void> {\n if (this.closed) return Promise.resolve();\n return new Promise((resolve) => {\n const done = (): void => {\n clearTimeout(timer);\n this.closing.signal.removeEventListener(\"abort\", done);\n resolve();\n };\n const timer = setTimeout(done, ms);\n this.closing.signal.addEventListener(\"abort\", done);\n });\n }\n\n /** Aborted by the timeout or by `aclose()`. Built by hand: `AbortSignal.any`\n * is missing before Node 20.3, and on some later versions it keeps every\n * combined signal alive as long as the long-lived `closing` signal. Any body\n * read is under the same signal, so a stalled body cannot hold the drain. */\n private async post(body: string, size: number, batchless: boolean, timeoutMs: number): Promise<Answer> {\n // A listener added to an aborted signal never fires, so the request would run on.\n if (this.closed) return { kind: \"transient\", retryAfterMs: null };\n const request = new AbortController();\n const abort = (): void => request.abort();\n const timer = setTimeout(abort, timeoutMs);\n this.closing.signal.addEventListener(\"abort\", abort);\n try {\n const response = await this.fetchImpl(batchless ? `${this.url}/v0/events` : `${this.url}/v0/events/batch`, {\n method: \"POST\",\n headers: this.authHeaders(),\n body,\n signal: request.signal,\n // SPEC §2.5: a redirect is a failure, not followed.\n redirect: \"manual\",\n });\n const { status } = response;\n const outcome = HttpSink.classifyStatus(status);\n if (outcome === \"success\") {\n if (batchless) {\n void response.body?.cancel().catch(() => undefined);\n return { kind: \"answered\", refused: new Map() };\n }\n return { kind: \"answered\", refused: HttpSink.refusedIn(await response.text()) };\n }\n const other = HttpSink.otherAnswer(response, size, batchless);\n if (other !== null) {\n // An unread body holds its connection until GC.\n void response.body?.cancel().catch(() => undefined);\n return other;\n }\n const detail = await HttpSink.readHead(response).catch(() => \"<unreadable>\");\n return { kind: \"refused\", status, refusal: { kind: `HTTP ${status}`, detail } };\n } catch {\n return { kind: \"transient\", retryAfterMs: null };\n } finally {\n clearTimeout(timer);\n this.closing.signal.removeEventListener(\"abort\", abort);\n }\n }\n\n /** Every answer but a 2xx and a refusal of the whole batch. */\n private static otherAnswer(response: Response, size: number, batchless: boolean): Answer | null {\n const { status } = response;\n if (status === 413 && size > 1) return { kind: \"too_large\" };\n if ((status === 404 || status === 405) && !batchless) return { kind: \"no_batch_endpoint\" };\n if (status === 429) return { kind: \"transient\", retryAfterMs: retryAfterMs(response.headers.get(\"Retry-After\")) };\n if (HttpSink.classifyStatus(status) === \"transient_failure\") return { kind: \"transient\", retryAfterMs: null };\n return null;\n }\n\n /** The refused results by `event_id` (SPEC §2.5). An event with no readable\n * result was delivered. */\n private static refusedIn(text: string): Map<string, Refusal> {\n const refused = new Map<string, Refusal>();\n let results: unknown;\n try {\n results = (JSON.parse(text) as { results?: unknown } | null)?.results;\n } catch {\n return refused;\n }\n if (!Array.isArray(results)) return refused;\n const str = (value: unknown): string => (typeof value === \"string\" ? value : \"\");\n for (const result of results as { event_id?: unknown; status?: unknown; error?: { code?: unknown; message?: unknown } }[]) {\n if (result?.status !== \"refused\" || typeof result.event_id !== \"string\") continue;\n refused.set(result.event_id, { kind: str(result.error?.code) || \"no code\", detail: str(result.error?.message) });\n }\n return refused;\n }\n}\n","/** String helpers shared by the capture and log paths. */\n\n// Unicode `White_Space`, exactly (SPEC §11.4's blank rule). Not `.trim()`, which\n// also removes U+FEFF and keeps U+0085, nor `str.strip()`, which also removes U+001C-U+001F.\nconst WHITE_SPACE = /^\\p{White_Space}$/u;\nconst ALL_WHITE_SPACE = /^\\p{White_Space}*$/u;\n\n/** `value` without leading and trailing characters matching `space`, a\n * one-character pattern. A scan, not `/^x+|x+$/`, which is quadratic on a long\n * run of spaces inside the string. */\nexport function stripEdges(value: string, space: RegExp): string {\n let start = 0;\n let end = value.length;\n while (start < end && space.test(value[start]!)) start++;\n while (end > start && space.test(value[end - 1]!)) end--;\n return value.slice(start, end);\n}\n\nexport function stripWhiteSpace(value: string): string {\n return stripEdges(value, WHITE_SPACE);\n}\n\n/** `value` without trailing white space: SPEC §2.6's append rule. */\nexport function stripWhiteSpaceEnd(value: string): string {\n let end = value.length;\n while (end > 0 && WHITE_SPACE.test(value[end - 1]!)) end--;\n return value.slice(0, end);\n}\n\nexport function isBlank(value: string): boolean {\n return ALL_WHITE_SPACE.test(value);\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/** 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/** Backslashes and control, format and separator characters as `\\u{hex}`, so\n * text from outside cannot break or recolour a log line, or pass for an escape. */\nexport function escapeForLog(value: string): string {\n return value.replace(/[\\\\\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]/gu, (c) => `\\\\u{${c.codePointAt(0)!.toString(16)}}`);\n}\n","export const TIMED_OUT = Symbol(\"timedOut\");\n\n/** Larger values overflow Node's timer, which then fires at once. */\nexport const MAX_TIMER_MS = 2 ** 31 - 1;\n\n/** `work`'s result, or `TIMED_OUT` if it has not settled within `ms`. */\nexport async function raceDeadline<T>(work: PromiseLike<T>, ms: number): Promise<T | typeof TIMED_OUT> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), Math.min(ms, MAX_TIMER_MS));\n // A pending deadline must not hold a finished process open. Outside Node a\n // timer is a number with no `unref`: `principalResolution.test.ts`,\n // \"where a timer is a plain number\".\n (timer as { unref?: () => void }).unref?.();\n });\n try {\n return await Promise.race([work, deadline]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** SPEC §11.2 rule 7's budget for a flush at exit, or an explicit flush or close. */\nexport const SHUTDOWN_FLUSH_TIMEOUT_MS = 3000;\n","import { uuid7 } from \"./uuid7.js\";\nimport { warn } from \"./warn.js\";\n\n/** Why an event was not delivered. Wire values (SPEC §11.2 rule 8), so they\n * change only with SPEC. */\nexport const DROP_REASONS = [\n \"buffer_full\",\n \"refused\",\n \"encode_failed\",\n \"write_failed\",\n \"after_close\",\n \"unsent_at_close\",\n] as const;\nexport type DropReason = (typeof DROP_REASONS)[number];\n\n/** The least time between two \"delivering again\" warnings, so steady loss\n * beside steady delivery, such as an overflowing buffer, is not one per event. */\nconst RECOVERY_LOG_MS = 60_000;\n\n/** Events this process did not deliver, by reason: every event is either\n * delivered or counted here, except at close, where the count is best effort\n * (SPEC §11.2 rule 8). One per process, like the sequence clock. */\nclass DropCounts {\n // Made on first use: a Worker refuses random values while its modules load.\n #instanceId: string | undefined;\n readonly #total = new Map<DropReason, number>();\n readonly #sinceDelivery = new Map<DropReason, number>();\n #lastRecoveryLog = -RECOVERY_LOG_MS;\n\n add(reason: DropReason, n = 1): void {\n if (n <= 0) return;\n this.#total.set(reason, (this.#total.get(reason) ?? 0) + n);\n this.#sinceDelivery.set(reason, (this.#sinceDelivery.get(reason) ?? 0) + n);\n }\n\n total(): Partial<Record<DropReason, number>> {\n return Object.fromEntries(this.#total);\n }\n\n /** Called on each delivery: names what was lost before it, the other half of\n * a drop's own warning, which says only that loss started. */\n logRecovery(): void {\n if (this.#sinceDelivery.size === 0) return;\n const now = performance.now();\n if (now - this.#lastRecoveryLog < RECOVERY_LOG_MS) return;\n const lost = [...this.#sinceDelivery].sort(([a], [b]) => a.localeCompare(b));\n this.#sinceDelivery.clear();\n this.#lastRecoveryLog = now;\n const total = lost.reduce((sum, [, n]) => sum + n, 0);\n warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(\", \")}.`);\n }\n\n /** Names this process in its loss reports (SPEC §11.4.7). */\n get instanceId(): string {\n return (this.#instanceId ??= uuid7());\n }\n\n /** For tests: the counts are one per process. */\n clear(): void {\n this.#instanceId = undefined;\n this.#total.clear();\n this.#sinceDelivery.clear();\n this.#lastRecoveryLog = -RECOVERY_LOG_MS;\n }\n}\n\nexport const PROCESS_DROPS = new DropCounts();\n","let lastSequence = 0;\n\nexport function nowMicros(): number {\n return Math.floor((performance.timeOrigin + performance.now()) * 1000);\n}\n\n/** Sequence numbers from the clock, in microseconds (SPEC §5.6 rule 3). One\n * counter for the process: strictly increasing across all sessions is\n * strictly increasing within each, and nothing grows per session. */\nexport function nextClockSequence(): number {\n lastSequence = Math.max(lastSequence + 1, nowMicros());\n return lastSequence;\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 under `reportMode: \"on\"` (SPEC §5.1.1), injects\n * a `user_goal` intent param on every wrapped tool's schema (SPEC §11.4.1\n * `call_intent`/`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 * On a low-level `Server`, which has no tool registry, the same is done at its\n * `tools/list` and `tools/call` handlers: see `installLowLevelToolSeams`.\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 * as asyncHooks from \"node:async_hooks\";\nimport { uuid7 } from \"../../uuid7.js\";\nimport {\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 ToolListEndEventSchema,\n ToolListErrorEventSchema,\n ToolListStartEventSchema,\n} from \"../../events.js\";\nimport { boundedSinkCall, offTheCall, StdoutSink, type Sink } from \"../../sinks.js\";\nimport {\n type AnnotationTool,\n buildAnnotationTool,\n annotationInputJsonSchema,\n callAnnotationTool,\n registerAnnotationTool,\n TOOL_NAME_PARAM_NAME,\n} from \"./annotation.js\";\nimport { Scrubber } from \"../../scrub.js\";\nimport { scrubOrNull } from \"./safeScrub.js\";\nimport { roundMetaCoordinates } from \"../../metaCoordinates.js\";\nimport {\n resolveInstallConfig,\n resolveTenantId,\n withServerDisplayName,\n type BatonConfig,\n type ResolvedBatonConfig,\n} from \"./config.js\";\nimport { captureDisabled, DisabledSink, logDisabled, logUnconfigured } from \"../../optout.js\";\nimport { capCodePoints, isBlank } from \"../../_text.js\";\nimport { printable, stderrLine, warn } from \"../../warn.js\";\nimport { isRecord } from \"../../_object.js\";\nimport { emit } from \"./emit.js\";\nimport {\n ERROR_BODY_MAX_CODE_POINTS,\n endResultFields,\n errorText,\n errorTypeOf,\n type FailureKind,\n scrubbedErrorBody,\n messageOf,\n type InputValidation,\n OUTPUT_SCHEMA_MISMATCH,\n requestSideFailureFields,\n requestSideFailureKind,\n type ResultCaptureMode,\n type ToolEntryFacts,\n resultDerivedFields,\n returnedErrorFields,\n isErrorResult,\n TOOL_ERROR_TYPE,\n WITHHELD,\n} from \"./errorResult.js\";\nimport { isInputRequired, resumesPausedCall } from \"./inputRequired.js\";\nimport { BatonHandle } from \"./handle.js\";\nimport {\n deriveAnnotationToolName,\n resolveAnnotationToolName,\n usableServerName,\n} from \"./annotationName.js\";\nimport {\n buildReportPointer,\n buildServerInstructions,\n declaresParam,\n INTENT_INSTRUCTIONS,\n INTENT_SOURCE_PARAM,\n instructionsSuffixServed,\n mayDeclareParam,\n RETIRED_PARAM_NAMES,\n requiredParamNames,\n removeSubagentClause,\n USER_GOAL_PARAM_NAME,\n writeOurs,\n} from \"./llmText.js\";\nimport {\n extraMeta,\n isThenable,\n observeTransport,\n type Extra,\n} from \"./mcpTypes.js\";\nimport { observeClient } from \"./clientObserved.js\";\nimport { resolveSessionId, type ResolvedSession } from \"./sessionResolution.js\";\nimport {\n type ResolvePrincipalHook,\n type ResolvedCaller,\n callerEnvelope,\n resolveCaller,\n} from \"./principalResolution.js\";\nimport { type CaptureSettings, candidateNeedsConsole, mayHide } from \"./captureSettings.js\";\nimport { PerCallerSurface } from \"./perCaller.js\";\nimport { ServerCounter, SessionCounter } from \"./sessionCounter.js\";\nimport {\n advertiseIntentParamsRequired,\n withToolInputSchema,\n injectGoalParams,\n injectGoalParamsV2,\n toolInputJsonSchema,\n type IntentParamDispositions,\n type IntentParamMode,\n DEFAULT_INTENT_PARAM_MODE,\n takesUserGoalJson,\n withUserGoalJson,\n standardInputJsonSchema,\n EMPTY_OBJECT_JSON_SCHEMA,\n} from \"./schemaCompat.js\";\nimport { PROCESS_DROPS } from \"../../drops.js\";\nimport { assembleSurface, buildServerMeta, buildSeamAugmentations, SentSurfaces, 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: SupportedServer;\n scrubber: (value: unknown) => unknown;\n annotationToolName: string;\n intentParamMode: IntentParamMode;\n /** The config's `resultCaptureMode` (SPEC §11.4), validated once at the\n * config door. A call runs under the one `openCall` returns, which Console\n * settings can change. */\n configResultCaptureMode: 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 /** Tool `name` declares its own `user_goal`: take the subagent sentence\n * out of the instructions, or it sends the turn number into the vendor's\n * argument. */\n dropSubagentClause: (name: string) => void;\n servedInstructions: () => unknown;\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 /** Under `settings: \"console\"`; shared by every server one `createBaton` wraps. */\n captureSettings: CaptureSettings | undefined;\n perCaller: PerCallerSurface | undefined;\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 `install`,\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`, `parkSuccess` and\n * `parkPause` 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 /** Baton's intent params, taken off the request by the seam before the\n * host's input check or any vendor code sees them (SPEC §5.1.2). */\n stripped: StrippedParams;\n /** The tool they were taken from: only its wrapper may take them, so a tool\n * Baton did not wrap cannot pass them to one it runs in-process. */\n strippedFor: string | null;\n /** Set by the probe on `validateToolInput`; stays `\"unseen\"` when the call\n * was refused before the SDK validated it. */\n validation: InputValidation;\n /** The caller, when the seam resolved it to check for a hidden tool, so\n * the vendor's hook runs once per call. */\n caller?: ResolvedCaller;\n /** How a low-level Server's call treats `user_goal` on a tool it has not listed. */\n unlisted?: Unlisted;\n}\n\nconst INTENT_PARAM_NAMES = [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES] as const;\ntype MutableStrippedParams = Partial<Record<(typeof INTENT_PARAM_NAMES)[number], string | null>>;\ntype StrippedParams = Readonly<MutableStrippedParams>;\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 asyncHooks.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 dirty = false;\n servedOverlayId: string | null = null;\n\n constructor(\n private readonly serverMeta: ReturnType<typeof buildServerMeta>,\n readonly sentSurfaces: SentSurfaces,\n ) {}\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 const before = this.rawTools.get(name);\n const tool = { name, description: description ?? null, inputSchema: inputSchemaJson };\n // A low-level Server's tools are noted on every list it serves.\n if (before !== undefined && before.tool.description === tool.description) {\n const same = before.tool.inputSchema === inputSchemaJson || JSON.stringify(before.tool.inputSchema) === JSON.stringify(inputSchemaJson);\n if (same) return;\n }\n this.rawTools.set(name, { disabled: before?.disabled ?? false, tool });\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 return scrubbedErrorBody(ctx.scrubber, text);\n}\n\n/** The envelope members every event shares, resolved off one MCP request —\n * everything except `principal` and `organization`, which are deliberately not in here.\n *\n * Split out of `openCall` so the lifecycle seams (SPEC §11.4.4, §11.4.5) can\n * build an envelope without the parts that are specific to a tool call: the\n * intent-param strip and the `call_id`. `principal` and `organization` are the caller's to\n * resolve, because the hook's input differs between a call and a listing.\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.\n *\n * Not for key order: Zod v4 emits output keys in SHAPE order, so\n * `envelopeShape` fixes the wire order however a caller spells its literal. */\nasync function resolveEnvelopeParts(\n ctx: WrapContext,\n extra: Extra,\n): Promise<ResolvedSession & { scrubbedMeta: unknown }> {\n // Coordinates are coarsened before the vendor's scrubber, so a vendor\n // scrubber still gets the rule. `_meta` only; params and results keep full\n // precision. The annotation tool does the same.\n const meta = extraMeta(extra);\n const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, \"_meta\");\n const session = await resolveSessionId(ctx.fallbackSessionId, extra);\n return { ...session, 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 * `tool_call_start`, unless the request resumes a paused call.\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.\n *\n * Returns what the TERMINAL event needs and nothing more: the envelope, with\n * this call's `call_id` in it, 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 /** What the seam took off the request. Passed in, not read from\n * `callSlots`: the request-side path runs outside its own slot. */\n stripped: StrippedParams,\n unlisted: Unlisted = \"warn\",\n resolved?: ResolvedCaller,\n): Promise<{ common: Record<string, unknown>; session: ResolvedSession; resultCaptureMode: ResultCaptureMode }> {\n // Snapshot BEFORE tool_call_start, from inside openCall so every caller inherits the order.\n await maybeEmitSurfaceSnapshot(ctx);\n const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);\n\n // The seam has usually stripped them already. Strip IN PLACE for a server it\n // could not reach: `params` is the SAME object forwarded to the vendor\n // handler, and the captured `params` must equal the vendor-visible arguments.\n const dispositions = ctx.paramRegistry.get(toolName);\n const rawIntent =\n stripped[USER_GOAL_PARAM_NAME] ??\n extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, unlisted);\n const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);\n const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map((name) =>\n dispositions === undefined || dispositions[name] === \"native\" || unlisted === \"leave\" || unlisted === \"goalOnly\"\n ? null\n : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name),\n );\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 client = observeClient(extra, ctx);\n const caller =\n resolved ??\n (await resolveCaller(ctx.resolvePrincipal, { extra, toolName, arguments: params }, ctx.captureSettings, client));\n const resultCaptureMode = caller.settings?.resultCaptureMode ?? ctx.configResultCaptureMode;\n\n const common = {\n tenant_id: ctx.tenantId,\n vendor_id: ctx.vendorId,\n session_id: session.sessionId,\n consent_token: ctx.consentToken,\n // Every `...common` site is an event of this call, so `call_id` rides in\n // it. `surface_snapshot` is deliberately not among them: it describes the\n // SERVER and is captured outside any call, so it has no caller, transport\n // or client to name.\n ...callerEnvelope(caller),\n transport_observed: observeTransport(extra),\n session_id_origin: session.origin,\n client_observed: client,\n runtime_meta: scrubbedMeta,\n call_id: uuid7(),\n };\n\n if (resumesPausedCall(extra)) return { common, session, resultCaptureMode };\n await emit(ctx.sink, () =>\n ToolCallStartEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.nextFor(session),\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, session, resultCaptureMode };\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(\n nameRef: { current: string },\n original: AnyHandler,\n ctx: WrapContext,\n unlisted: Unlisted = \"warn\",\n /** The caller the low-level seam already resolved for this call. */\n resolved?: ResolvedCaller,\n): 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 // Handed over once: a tool this handler calls in-process shares the slot.\n const ours = slot?.strippedFor === toolName ? slot : undefined;\n if (slot) slot.strippedFor = null;\n const { common, session, resultCaptureMode } = await openCall(\n ctx,\n toolName,\n extra,\n params,\n ours?.stripped ?? {},\n unlisted,\n ours?.caller ?? resolved,\n );\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) | null,\n replacement: ((outcome: OuterOutcome) => Event) | null,\n ): Promise<void> => {\n if (!slot) {\n // No outer seam: a direct executor call, a low-level Server, or a\n // server whose internals 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 if (build !== null) 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 paused round parks a terminal\n // only a failure sends, and the next round supersedes it.\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 if (replacement !== null && outcome.failed) await emit(ctx.sink, () => replacement(outcome));\n else if (build !== null) await emit(ctx.sink, build);\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 /** Park a paused round: it sends nothing unless the SDK then fails the call. */\n const parkPause = (replacement: (outcome: OuterOutcome) => Event): Promise<void> =>\n terminate(null, 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 sequence_number: ctx.counter.nextFor(session),\n captured_at: new Date().toISOString(),\n payload: {\n tool_name: toolName,\n error_type: errorTypeOf(err),\n // SPEC §11.4.3(1): the MCP SDK has no tool-error class to mark a\n // raised message public, so under \"off\" every one is withheld.\n ...resultDerivedFields(\n resultCaptureMode,\n () => messageOf(err),\n null,\n (text) => errorBody(ctx, text),\n ctx.scrubber,\n ),\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 handler returned and the outer seam then saw the call fail: on the\n // success lane what failed is the producer's own conversion of the output\n // (SPEC §11.4.3's `output_schema_mismatch`), and after a pause it is the\n // SDK's handling of the input request. The stream would otherwise file the\n // caller's failure as a success, or not at all.\n const failedAbove = (outcome: OuterOutcome, failureKind?: string): Event =>\n ToolCallErrorEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.nextFor(session),\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 pause the SDK rejects on 2026-07-28 raises, so\n // both lanes are reachable.\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 // Omitted, not null, when undetermined: SPEC §11.4.3 says MUST OMIT.\n ...(failureKind === undefined ? {} : { failure_kind: failureKind }),\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 an\n // `output_schema_mismatch` under `\"off\"`, and is the measurement\n // that justified putting 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 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 if (isInputRequired(result)) {\n await parkPause(failedAbove);\n return result;\n }\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 sequence_number: ctx.counter.nextFor(session),\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 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 sequence_number: ctx.counter.nextFor(session),\n captured_at: new Date().toISOString(),\n payload: {\n tool_name: toolName,\n duration_ms: durationMs,\n ...endResultFields(resultCaptureMode, result, ctx.scrubber),\n },\n }),\n (outcome) => failedAbove(outcome, OUTPUT_SCHEMA_MISMATCH),\n );\n\n return result;\n };\n}\n\n/** What a call to a tool Baton did not add `user_goal` to does with it: strip\n * it with the cold-registry warning, strip it quietly (the caller has warned,\n * or the tool does not exist), or, on a low-level Server, strip only\n * `user_goal` and leave the retired names, or leave them all. */\ntype Unlisted = \"warn\" | \"quiet\" | \"goalOnly\" | \"leave\";\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 * A tool with no entry is handled as `unlisted` says. */\nfunction extractGoalParam(\n args: Record<string, unknown>,\n paramName: string,\n toolName: string,\n dispositions: IntentParamDispositions | undefined,\n unlisted: Unlisted,\n): string | null {\n if (!(paramName in args)) return null;\n const disposition = dispositions ? dispositions[paramName] : undefined;\n if (disposition === \"native\") return null;\n if (disposition === undefined && unlisted === \"leave\") return null;\n if (disposition === undefined && unlisted === \"warn\") {\n stderrLine(\n `baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)`,\n );\n }\n return popText(args, paramName);\n}\n\nfunction popText(args: Record<string, unknown>, paramName: string): string | null {\n if (!(paramName in args)) return null;\n const raw = args[paramName];\n delete args[paramName];\n return typeof raw === \"string\" && !isBlank(raw) ? raw : null;\n}\n\n/** Take Baton's intent params off a `tools/call` request, before the host's\n * input check and before a tool Baton did not wrap (a 1.x task tool) sees them.\n * Only from a tool Baton injected into: on any other, a value is the vendor's. */\nfunction stripIntentParams(\n params: { name?: unknown; arguments?: unknown } | undefined,\n ctx: WrapContext,\n): StrippedParams {\n const toolName = params?.name;\n const args = params?.arguments;\n if (typeof toolName !== \"string\") return {};\n if (toolName === ctx.annotationToolName) return {};\n if (typeof args !== \"object\" || args === null || Array.isArray(args)) return {};\n const dispositions = ctx.paramRegistry.get(toolName);\n const stripped: MutableStrippedParams = {};\n for (const name of INTENT_PARAM_NAMES) {\n if (dispositions === undefined || dispositions[name] === \"native\" || !(name in args)) continue;\n stripped[name] = popText(args as Record<string, unknown>, name);\n }\n return stripped;\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 is not\n * among the last `SENT_SURFACES_CAP` that `sentSurfaces` has seen. `dirty`\n * is cleared FIRST so a hashing/serialization error (deterministic — would\n * just re-throw identically every call) costs one attempt per surface\n * change, not a retry storm. The write only queues, so a snapshot counts as\n * sent once queued; a sink that later fails to write it counts it `write_failed`. */\nasync function maybeEmitSurfaceSnapshot(ctx: WrapContext): Promise<void> {\n const overlayId = ctx.perCaller?.serverOverlay?.id ?? null;\n if (overlayId !== ctx.surfaceState.servedOverlayId) {\n ctx.surfaceState.servedOverlayId = overlayId;\n ctx.surfaceState.dirty = true;\n }\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 stderrLine(`baton: surface snapshot capture failed: ${String(err)}`);\n return;\n }\n const sent = ctx.surfaceState.sentSurfaces;\n if (sent.wasSent(digest, overlayId)) return;\n // Reserved before the write, so two servers sharing `sentSurfaces` cannot both\n // send it: `createBaton.test.ts`, \"when the first requests arrive together\".\n sent.mark(digest, overlayId);\n const seam = buildSeamAugmentations({\n injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],\n intentParamNames: [USER_GOAL_PARAM_NAME],\n intentParamMode: ctx.intentParamMode,\n requiredParamNames: requiredParamNames(ctx.intentParamMode),\n instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions()),\n });\n // SPEC §11.4.2: present only from a producer that applies overlays.\n if (ctx.captureSettings !== undefined) seam.server_overlay = overlayId;\n await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });\n}\n\nfunction declaredIntentParams(vendorSchema: unknown): IntentParamDispositions {\n const declared: IntentParamDispositions = {};\n for (const name of INTENT_PARAM_NAMES) {\n if (declaresParam(vendorSchema, name)) declared[name] = \"native\";\n }\n return declared;\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` as the vendor's own\n * field (`\"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 const vendorSchema = ctx.vendorToolJsonSchema(name, mutable.inputSchema);\n ctx.surfaceState.noteTool(name, vendorSchema, mutable.description);\n // From the JSON schema: a v2 schema that is not zod gets no injection, but\n // its `user_goal` still counts.\n if (declaresParam(vendorSchema, USER_GOAL_PARAM_NAME)) ctx.dropSubagentClause(name);\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 // A schema that could not be extended still has its own names to keep.\n const declared = declaredIntentParams(vendorSchema);\n if (Object.keys(declared).length > 0) ctx.paramRegistry.set(name, declared);\n else 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 `install`.\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 // Two seams may wrap one method. Without the inner seam's tag on the\n // outer handler, the inner seam would wrap again on the next\n // `setRequestHandler`: \"each seam applies once\" in `toolList.test.ts`.\n for (const tag of Object.getOwnPropertySymbols(handler)) seamed[tag] = handler[tag];\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 a name be advertised as\n * required without the validator enforcing it (see\n * `schemaCompat.buildIntentFields` for why zod cannot). Two sets of names:\n * `requiredParamNames` on each tool Baton injected them into, under\n * `intentParamMode: \"required\"`, and `tool_name` on the annotate tool, in\n * every mode (SPEC §5.1.1).\n *\n * On an McpServer the annotate tool lists Baton's own rendering of its\n * schema, as a low-level Server's list already does: the SDK renders it with\n * the vendor's zod, which may differ (reportToolSchema.test.ts).\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, listsOwnReportTool: boolean): void {\n const names = [...requiredParamNames(ctx.intentParamMode), TOOL_NAME_PARAM_NAME];\n const isInjected = (toolName: string, paramName: string): boolean =>\n toolName === ctx.annotationToolName\n ? paramName === TOOL_NAME_PARAM_NAME\n : ctx.paramRegistry.get(toolName)?.[paramName] === \"injected\";\n const advertise = (result: unknown): unknown => {\n try {\n const served = listsOwnReportTool || ctx.annotationToolName === \"\"\n ? result\n : withToolInputSchema(result, ctx.annotationToolName, annotationInputJsonSchema(lowLevelMajor(lowLevel)));\n return advertiseIntentParamsRequired(served, names, isInjected);\n } catch (err) {\n stderrLine(\n `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}`,\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\ntype LowLevelInternals = {\n _instructions?: string;\n _serverInfo?: { name?: unknown };\n} & RequestHandlerInternals;\n\nconst LOW_LEVEL_LIST_SEAM = Symbol(\"batonLowLevelListSeam\");\nconst LOW_LEVEL_CALL_SEAM = Symbol(\"batonLowLevelCallSeam\");\nconst LOW_LEVEL_HANDSHAKE_SEAM = Symbol(\"batonLowLevelHandshakeSeam\");\nconst SETTINGS_SEAM = Symbol(\"batonSettingsSeam\");\n\n/** What one Baton knows of a low-level `Server`'s tools, shared by every\n * server it wraps, so a server made per request knows the tools another one\n * served. `given` is the `tools` option until it is read, once, into `givenTools`. */\ninterface KnownTools {\n given: BatonConfig[\"tools\"];\n givenTools: ToolInfo[];\n served: Map<string, ToolInfo>;\n /** Tools some version of which may declare `user_goal`. A name is never removed. */\n keepsGoal: Set<string>;\n /** Tools whose calls keep `user_goal` until a version of them is read. */\n unread: Set<string>;\n}\n\ntype ToolInfo = { name: string; description: unknown; inputSchema: unknown };\ntype ReadOptions = { surface: boolean };\n\n/**\n * `tools/list` and `tools/call` on a low-level `Server`, which has no tool\n * registry: what Baton knows of a tool comes from the `tools` option and from\n * the lists this Baton's servers serve. A server's surface and report-name\n * check use only the `tools` option and its own lists; what other servers\n * served only decides which calls lose `user_goal`.\n *\n * ⚠ Every call is traced. `user_goal` comes off every call, since a client\n * sends it only because Baton listed it, except to a tool that may take its\n * own (`known.keepsGoal`) or that Baton could not read (`known.unread`):\n * `lowLevelServer.test.ts`, \"a tool Baton does not know\", \"leaves a call's\n * user_goal when the root combiner names user_goal\" and \"a given tool it\n * cannot read\".\n */\nfunction installLowLevelToolSeams(\n lowLevel: LowLevelInternals,\n ctx: WrapContext,\n annotationTool: AnnotationTool | undefined,\n known: KnownTools,\n warnOnce: (key: string, message: string) => void,\n /** The vendor lists a tool with the report tool's name: drop the pointer to it. */\n reportToolTaken: () => void,\n): void {\n let reportTool = annotationTool;\n const listedReportTool = reportTool && {\n name: reportTool.name,\n description: reportTool.description,\n inputSchema: annotationInputJsonSchema(lowLevelMajor(lowLevel)),\n };\n const skipTool = (name: string, err: unknown): void => {\n known.unread.add(name);\n warnOnce(\n `tool-unread:${name}`,\n `baton: could not read tool ${JSON.stringify(name)}; its calls keep user_goal until Baton can read it: ${printable(err)}`,\n );\n };\n const skipNote = (name: string, err: unknown): void => {\n if (known.unread.has(name)) return;\n warnOnce(`tool-unnoted:${name}`, `baton: could not note tool ${JSON.stringify(name)}; Baton adds no user_goal to it: ${printable(err)}`);\n };\n // Below the root only where Baton cannot add its own `user_goal` at the root.\n const keepGoalIfDeclared = (tools: ToolInfo[]): void => {\n for (const { name, inputSchema } of tools) {\n try {\n const checked = known.served.get(name)?.inputSchema === inputSchema && !known.unread.has(name);\n if (!known.keepsGoal.has(name) && !checked) {\n const declares =\n isRecord(inputSchema) && takesUserGoalJson(inputSchema) ? declaresParam : mayDeclareParam;\n if (declares(inputSchema, USER_GOAL_PARAM_NAME)) known.keepsGoal.add(name);\n }\n known.unread.delete(name);\n } catch (err) {\n skipTool(name, err);\n }\n }\n };\n\n const read = (tools: ToolInfo[], { surface }: ReadOptions): void => {\n if (surface && reportTool !== undefined && tools.some((tool) => tool.name === reportTool?.name)) {\n warnOnce(\n \"report-tool-name-taken\",\n `baton: the server lists its own tool ${JSON.stringify(reportTool.name)}, so Baton's report ` +\n \"tool is not added; set annotationToolName to another name\",\n );\n reportTool = undefined;\n ctx.annotationToolName = \"\";\n reportToolTaken();\n }\n readToolList(tools, ctx, surface, skipNote);\n };\n\n // Per caller lists may differ: keep every tool, and a version that declares\n // its own `user_goal` over one that does not, so a server reading this map\n // registers it as the tool's own and not as one Baton added.\n const learn = (tools: ToolInfo[]): void => {\n keepGoalIfDeclared(tools);\n for (const tool of tools) {\n const held = known.served.get(tool.name);\n const ownGoal = (info: ToolInfo | undefined) => declaresParam(info?.inputSchema, USER_GOAL_PARAM_NAME);\n if (held === undefined || !ownGoal(held) || ownGoal(tool)) known.served.set(tool.name, tool);\n }\n };\n\n let caughtUp = false;\n const catchUp = (): void => {\n if (caughtUp) return;\n caughtUp = true;\n if (known.given !== undefined) {\n const given = known.given;\n known.given = undefined;\n try {\n const tools: unknown = typeof given === \"function\" ? given() : given;\n if (!Array.isArray(tools)) throw new Error(\"it is not an array of tools\");\n known.givenTools = toolInfos(tools, skipTool);\n keepGoalIfDeclared(known.givenTools);\n } catch (err) {\n warnOnce(\n \"tools-unread\",\n `baton: could not read the tools option; Baton learns the tools from tools/list: ${printable(err)}`,\n );\n }\n }\n read(known.givenTools, { surface: true });\n read([...known.served.values()], { surface: false });\n };\n\n installRequestSeam(lowLevel, TOOLS_LIST_METHOD, LOW_LEVEL_LIST_SEAM, (handler) => async (...args) => {\n catchUp();\n const result = await handler(...args);\n try {\n const listed = listedTools(result);\n if (listed === null) return result;\n const tools = toolInfos(listed, skipTool);\n learn(tools);\n read(tools, { surface: true });\n // On the first page, which every client reads.\n const firstPage = (args[0] as { params?: { cursor?: unknown } } | undefined)?.params?.cursor === undefined;\n return servedToolList(result as Record<string, unknown>, listed, ctx, firstPage && reportTool ? listedReportTool : undefined);\n } catch (err) {\n stderrLine(`baton: tools/list capture failed; serving the vendor's own result: ${printable(err)}`);\n return result;\n }\n });\n\n // Before `initialize`, so a known tool's own `user_goal` takes the subagent\n // sentence out of the instructions it answers with.\n const readFirst =\n (handler: AnyHandler): AnyHandler =>\n (...args) => {\n catchUp();\n return handler(...args);\n };\n installRequestSeam(lowLevel, \"initialize\", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);\n installRequestSeam(lowLevel, \"server/discover\", LOW_LEVEL_HANDSHAKE_SEAM, readFirst);\n\n installRequestSeam(lowLevel, TOOLS_CALL_METHOD, LOW_LEVEL_CALL_SEAM, (handler) => async (...args) => {\n catchUp();\n const request = args[0] as { params?: { name?: unknown; arguments?: unknown; task?: unknown } } | undefined;\n const name = request?.params?.name;\n if (typeof name !== \"string\") return handler(...args);\n if (name === reportTool?.name) return callAnnotationTool(reportTool, request?.params?.arguments, args[1] as Extra);\n const injected = ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === \"injected\";\n const unlisted: Unlisted = injected ? \"warn\" : known.keepsGoal.has(name) || known.unread.has(name) ? \"leave\" : \"goalOnly\";\n // Baton's params off `args` in place, by the rule `openCall` uses.\n const strip = (args: Record<string, unknown>): StrippedParams =>\n injected\n ? stripIntentParams({ name, arguments: args }, ctx)\n : { [USER_GOAL_PARAM_NAME]: extractGoalParam(args, USER_GOAL_PARAM_NAME, name, ctx.paramRegistry.get(name), unlisted) };\n let slot: CallSlot | undefined;\n if (mayHide(ctx.captureSettings, name)) {\n // On a copy, so the hook and a hidden call's events see what any other call's would.\n const hookArgs = isRecord(request?.params?.arguments) ? { ...request.params.arguments } : {};\n const checked: CallSlot = { innerFired: false, flushTerminal: null, stripped: strip(hookArgs), strippedFor: name, validation: \"unseen\", unlisted };\n if (await hiddenFrom(checked, name, hookArgs, args[1] as Extra, ctx)) {\n // The vendor never sees this call, so its events take the stripped copy.\n if (request?.params !== undefined && isRecord(request.params.arguments)) request.params.arguments = hookArgs;\n return answerHidden(lowLevel, name, (outcome) => settleCall(checked, outcome, args, () => undefined, ctx, \"tool_hidden\"));\n }\n slot = checked;\n }\n // The request's own object: `openCall` takes Baton's params off it in\n // place, before the SDK's parse hands the vendor a copy.\n const params = request?.params?.arguments;\n const toolArgs = isRecord(params) ? params : {};\n if (\n unlisted === \"goalOnly\" &&\n USER_GOAL_PARAM_NAME in toolArgs &&\n !known.served.has(name) &&\n !known.givenTools.some((tool) => tool.name === name)\n ) {\n warnOnce(\n \"user-goal-unlisted\",\n `baton: ${JSON.stringify(name)} is not in any tool list this process has read, so Baton took ` +\n \"user_goal off it without knowing whether the tool declares its own; pass your tools as the tools option\",\n );\n }\n // A task-based call answers with the task, not the tool's result, so it\n // is not captured, as on an McpServer.\n if (request?.params?.task !== undefined) {\n strip(toolArgs);\n return handler(...args);\n }\n return batonWrap({ current: name }, () => handler(...args), ctx, unlisted, slot?.caller)(toolArgs, args[1]);\n });\n}\n\n/** v2's `Protocol` has the result-validation hook; 1.x's has not. */\nfunction lowLevelMajor(lowLevel: LowLevelInternals): 1 | 2 {\n return typeof (lowLevel as { _wrapHandler?: unknown })._wrapHandler === \"function\" ? 2 : 1;\n}\n\nfunction listedTools(result: unknown): unknown[] | null {\n return isRecord(result) && Array.isArray(result.tools) ? (result.tools as unknown[]) : null;\n}\n\n/** Each named tool's fields, read one tool at a time: a tool whose fields\n * cannot be read is skipped, not the list. */\nfunction toolInfos(tools: unknown[], skip: (name: string, err: unknown) => void): ToolInfo[] {\n const infos: ToolInfo[] = [];\n for (const tool of tools) {\n let name: unknown;\n try {\n name = isRecord(tool) ? tool.name : undefined;\n if (typeof name !== \"string\") continue;\n infos.push({ name, description: (tool as ToolInfo).description, inputSchema: (tool as ToolInfo).inputSchema });\n } catch (err) {\n if (typeof name === \"string\") skip(name, err);\n }\n }\n return infos;\n}\n\n/** Note each tool's own schema in the registry, and in the surface when it\n * is one this server serves. */\nfunction readToolList(\n tools: ToolInfo[],\n ctx: WrapContext,\n surface: boolean,\n skip: (name: string, err: unknown) => void,\n): void {\n for (const { name, inputSchema, description } of tools) {\n try {\n const schema = isRecord(inputSchema) ? inputSchema : null;\n if (surface) {\n ctx.surfaceState.noteTool(name, schema ?? EMPTY_OBJECT_JSON_SCHEMA, typeof description === \"string\" ? description : undefined);\n }\n const dispositions = declaredIntentParams(schema);\n if (dispositions[USER_GOAL_PARAM_NAME] === \"native\") ctx.dropSubagentClause(name);\n else if (schema !== null && takesUserGoalJson(schema)) dispositions[USER_GOAL_PARAM_NAME] = \"injected\";\n if (Object.keys(dispositions).length > 0) ctx.paramRegistry.set(name, dispositions);\n else ctx.paramRegistry.delete(name);\n } catch (err) {\n ctx.paramRegistry.delete(name);\n skip(name, err);\n }\n }\n}\n\nfunction servedToolList(\n result: Record<string, unknown>,\n listed: unknown[],\n ctx: WrapContext,\n reportTool: Record<string, unknown> | undefined,\n): unknown {\n const tools = listed.map((tool) => {\n if (!isRecord(tool) || typeof tool.name !== \"string\") return tool;\n if (ctx.paramRegistry.get(tool.name)?.[USER_GOAL_PARAM_NAME] !== \"injected\") return tool;\n // `required` is the `tools/list` seam's, which follows `intentParamMode`.\n return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema as Record<string, unknown>, ctx.intentParamMode, false) };\n });\n if (reportTool !== undefined) tools.push(reportTool);\n return { ...result, tools };\n}\n\nconst LIFECYCLE_SEAMS = {\n resourceList: Symbol(\"batonResourceListSeam\"),\n resourceRead: Symbol(\"batonResourceReadSeam\"),\n promptList: Symbol(\"batonPromptListSeam\"),\n promptGet: Symbol(\"batonPromptGetSeam\"),\n toolList: Symbol(\"batonToolListSeam\"),\n} as const;\n\n/** The three event schemas one lifecycle family needs, structurally rather\n * than by Zod generics: every one `.parse`s 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 `call_id`**: no producer mints one for these, so a consumer pairing\n * 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 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\" | \"tools\";\n /** The `*_start` payload's `params` member, or `{}` where the family has\n * none. */\n startParams: (params: Record<string, unknown>) => Record<string, unknown>;\n /** The result as this caller is served it. */\n rewriteResult?: (ctx: WrapContext, result: unknown, caller: ResolvedCaller) => 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 ctx.perCaller?.followSettings();\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.nextFor` 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.nextFor(opened.session),\n captured_at: new Date().toISOString(),\n payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload }),\n }),\n );\n };\n\n if (!resumesPausedCall(extra)) 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 served = await handler(...args);\n // Unlike tools, this seam wraps the SDK's pause handling, so a pause the\n // SDK then fails throws into the catch below.\n if (isInputRequired(served)) return served;\n const result =\n opened !== null && spec.rewriteResult !== undefined\n ? spec.rewriteResult(ctx, served, opened.caller)\n : served;\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 (SPEC §11.4.4), though it can quote what\n // the handler fetched, so `\"off\"` warns instead: `warnAboutSettings`.\n // The scrub and the cap 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 session: ResolvedSession;\n subject: Record<string, unknown>;\n caller: ResolvedCaller;\n} | null> {\n try {\n const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);\n const client = observeClient(extra, ctx);\n const caller = await resolveCaller(\n ctx.resolvePrincipal,\n { extra, toolName: null, arguments: {} },\n ctx.captureSettings,\n client,\n );\n return {\n session,\n caller,\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: session.sessionId,\n consent_token: ctx.consentToken,\n ...callerEnvelope(caller),\n transport_observed: observeTransport(extra),\n session_id_origin: session.origin,\n client_observed: client,\n runtime_meta: scrubbedMeta,\n },\n };\n } catch (err) {\n stderrLine(`baton: ${spec.method} capture failed: ${String(err)}`);\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 method: TOOLS_LIST_METHOD,\n seamTag: LIFECYCLE_SEAMS.toolList,\n schemas: {\n start: ToolListStartEventSchema,\n end: ToolListEndEventSchema,\n error: ToolListErrorEventSchema,\n },\n countKey: \"tools\",\n startParams: NO_PARAMS,\n rewriteResult: (ctx, result, caller) => ctx.perCaller?.toolsFor(result, caller) ?? result,\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**: the correction it makes is not configurable. A\n * 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 request = args[0] as { params?: { name?: unknown; arguments?: unknown } } | undefined;\n const name = request?.params?.name;\n const slot: CallSlot = {\n innerFired: false,\n flushTerminal: null,\n stripped: stripIntentParams(request?.params, ctx),\n strippedFor: typeof name === \"string\" ? name : null,\n validation: \"unseen\",\n };\n const toolArgs = request?.params?.arguments;\n if (\n typeof name === \"string\" &&\n toolEntry(name) != null &&\n (await hiddenFrom(slot, name, isRecord(toolArgs) ? toolArgs : {}, args[1] as Extra, ctx))\n ) {\n return answerHidden(lowLevel, name, (outcome) => settleCall(slot, outcome, args, toolEntry, ctx, \"tool_hidden\"));\n }\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/** Whether the caller's overlay hides `name`. Resolves the caller only when\n * some audience hides it, and keeps it on `slot` for the call's capture. */\nasync function hiddenFrom(\n slot: CallSlot,\n name: string,\n params: Record<string, unknown>,\n extra: Extra,\n ctx: WrapContext,\n): Promise<boolean> {\n try {\n if (name === ctx.annotationToolName || !mayHide(ctx.captureSettings, name)) return false;\n slot.caller = await resolveCaller(\n ctx.resolvePrincipal,\n { extra, toolName: name, arguments: params },\n ctx.captureSettings,\n observeClient(extra, ctx),\n );\n return slot.caller.settings?.overlay?.hiddenTools.has(name) ?? false;\n } catch (err) {\n stderrLine(`baton: could not check whether the tool is hidden; it is served: ${printable(err)}`);\n return false;\n }\n}\n\n/** The host's own answer to a call for a tool it does not have, on each\n * major, after `settle` has the outcome. */\nasync function answerHidden(\n lowLevel: RequestHandlerInternals,\n name: string,\n settle: (outcome: OuterOutcome) => Promise<void>,\n): Promise<unknown> {\n if (lowLevelMajor(lowLevel) === 1) {\n const result = { content: [{ type: \"text\", text: `MCP error -32602: Tool ${name} not found` }], isError: true };\n await settle({ failed: true, raised: false, result });\n return result;\n }\n const err = new ProtocolError(`Tool ${name} not found`);\n await settle({ failed: true, raised: true, err });\n throw err;\n}\n\n/** Named as v2's own, so a hidden tool's `error_type` matches an unknown one's. */\nclass ProtocolError extends Error {\n readonly code = -32602;\n}\n\n// Module-local, like the seam markers: a second copy of this package wraps\n// on top of this probe and gets its own slots written.\nconst VALIDATION_PROBE = Symbol(\"baton.validationProbe\");\n\n/**\n * Record on the call's slot what the SDK's `validateToolInput` did, so the\n * `tools/call` seam can tell a rejected argument from a refusal above the\n * executor without reading the message. Both majors call it on the instance,\n * right before `executeToolHandler`. A later replacement that does not call\n * through leaves every slot `\"unseen\"`, and a rejected argument reads as\n * `refused` (SPEC §11.4.3: the producer cannot tell why).\n */\nfunction installValidationProbe(server: SupportedServer): void {\n const target = server as unknown as {\n validateToolInput?: ((...args: unknown[]) => Promise<unknown>) & { [VALIDATION_PROBE]?: true };\n };\n const original = target.validateToolInput;\n if (typeof original !== \"function\" || original[VALIDATION_PROBE]) return;\n const probe = async function (this: unknown, ...args: unknown[]): Promise<unknown> {\n const slot = callSlots.getStore();\n try {\n const parsed = await original.apply(this, args);\n if (slot) slot.validation = \"passed\";\n return parsed;\n } catch (err) {\n if (slot) slot.validation = \"rejected\";\n throw err;\n }\n };\n Object.assign(probe, { [VALIDATION_PROBE]: true as const });\n target.validateToolInput = probe;\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 kind?: FailureKind,\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, slot, toolEntry, ctx, kind);\n } catch (err) {\n PROCESS_DROPS.add(\"encode_failed\");\n stderrLine(`baton: settling a tool call failed; events dropped: ${String(err)}`);\n }\n}\n\n/**\n * Emit the pair of events for a call that failed BEFORE the vendor's handler\n * ran: one of the SDK's three request-side `failure_kind`s, or a refusal by\n * vendor code above the executor (`refused`, SPEC §11.4.3).\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 slot: CallSlot,\n toolEntry: (name: string) => ToolEntry | undefined,\n ctx: WrapContext,\n kind?: FailureKind,\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 intent params from whatever it is given, and here the object is\n // the vendor's live `request.params.arguments`, already consumed by\n // whatever rejected the call. The seam edits the request only before\n // validation (`stripIntentParams`). An unknown tool still carries them, and\n // without this strip they would land in `tool_call_start.params`, which\n // SPEC says equals the vendor-visible arguments.\n const params = { ...((request?.params?.arguments as Record<string, unknown>) ?? {}) };\n const { common, session, resultCaptureMode } = await openCall(\n ctx,\n toolName,\n args[1] as Extra,\n params,\n slot.stripped,\n slot.unlisted ?? (entry != null ? \"warn\" : \"quiet\"),\n slot.caller,\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 = kind ?? requestSideFailureKind(entry, slot.validation);\n const text = (): string => (outcome.raised ? messageOf(outcome.err) : errorText(outcome.result));\n await emit(ctx.sink, () =>\n ToolCallErrorEventSchema.parse({\n ...common,\n sequence_number: ctx.counter.nextFor(session),\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 // above the handler, which is not what any other event means by this\n // 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 ...requestSideFailureFields(\n failureKind,\n resultCaptureMode,\n text,\n outcome.raised ? null : outcome.result,\n (value) => errorBody(ctx, value),\n ctx.scrubber,\n ),\n },\n }),\n );\n}\n\n/** Wrap the entry's CURRENT dispatch target iff it isn't already Baton's\n * wrapper. The `BATON_WRAPPED` tag lives on the wrapped FUNCTION, not the\n * entry object, so a `.update()` that swaps in a fresh vendor callback\n * (untagged) is correctly reprocessed, while one that leaves it alone is a\n * cheap no-op.\n *\n * WHICH function that is differs by SDK major, and getting it wrong fails\n * silently. 1.x's `tools/call` handler invokes `entry.handler`, so patching\n * that field intercepts the call. **v2 dispatches through `entry.executor`**\n * — a closure built at registration over the handler\n * (`createToolExecutor(inputSchema, handler)`; `executeToolHandler` is\n * literally `return tool.executor(args, ctx)`). Patching `entry.handler` on\n * v2 therefore does nothing at all: the vendor handler still runs, the\n * wrapper never fires, and the server emits zero events while looking\n * perfectly healthy — measured against `@modelcontextprotocol/server@2.0.0`\n * and pinned by `test/integrations/mcp/withBatonV2.test.ts`, whose RED\n * signature against a handler-only patch is an empty event list and no\n * error at all. Worse, the schema half\n * of `withBaton` keeps working, so a half-ported install would advertise\n * intent params, collect a goal from the agent, and capture none of it.\n *\n * On v2 we wrap the executor by capture-and-delegate, and deliberately do\n * NOT also wrap `entry.handler`: nothing dispatches through it there, and\n * tagging both would double-wrap once `update({callback})` regenerates the\n * executor over the untouched handler. */\nfunction wrapIfNeeded(nameRef: { current: string }, entry: unknown, ctx: WrapContext): void {\n if (!entry || typeof entry !== \"object\") return;\n const mutable = entry as 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/** The official SDK's low-level `Server`, 1.x or v2, on which the vendor sets\n * its own `tools/list` and `tools/call` handlers. */\nexport interface SupportedLowLevelServer {\n setRequestHandler(method: unknown, ...rest: unknown[]): unknown;\n}\n\nexport type SupportedServer = SupportedMcpServer | SupportedLowLevelServer;\n\n/** Install Baton into an `McpServer` or a low-level `Server`. See module\n * docstring for usage. */\nexport function withBaton(server: SupportedServer, 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 `resolveInstallConfig`, 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 // 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 return inertHandle(supplied.sink ?? new DisabledSink(), \"baton-disabled\");\n }\n const { resolved, unconfigured } = resolveInstallConfig(supplied);\n const handle = install(server, supplied, resolved, newBatonState(resolved), unconfigured);\n // After the checks, so an install that fails does not first warn about it.\n if (unconfigured) logUnconfigured(\"withBaton\");\n else warnAboutSettings(resolved);\n const settings = resolved.captureSettings;\n if (settings === undefined) return handle;\n // Last, so an install that fails reads no settings: \"a failed install reads no settings\".\n settings.start();\n return new SettingsHandle(handle, settings);\n}\n\n/** Stops the settings read when the vendor closes. */\nclass SettingsHandle extends BatonHandle {\n constructor(\n private readonly inner: BatonHandle,\n private readonly settings: CaptureSettings,\n ) {\n super(inner);\n }\n\n // The inner handle holds the queue in front of the sink.\n override flush(): Promise<void> {\n return this.inner.flush();\n }\n\n override async aclose(): Promise<void> {\n this.settings.stop();\n await this.inner.aclose();\n }\n}\n\n/** One Baton for a process that builds a new `McpServer` for every request.\n * Owns the sink, so a request has nothing to close. */\nexport interface Baton {\n wrap(server: SupportedServer): void;\n flush(): Promise<void>;\n aclose(): Promise<void>;\n}\n\n/** Create once at startup, then `wrap` each per-request server. For a server\n * that lives as long as the process, use `withBaton`. */\nexport function createBaton(supplied: BatonConfig = {}): Baton {\n const disabledBy = captureDisabled();\n if (disabledBy !== null) {\n logDisabled(disabledBy, \"createBaton\");\n const unused = supplied.sink ?? new DisabledSink();\n return {\n wrap: () => {},\n flush: () => boundedSinkCall(unused, \"flush\"),\n aclose: () => boundedSinkCall(unused, \"aclose\"),\n };\n }\n\n // Everything the environment or a bad config can decide is settled here, so\n // a request cannot fail on it or be switched off by it:\n // `createBaton.test.ts`, \"reads the environment once\".\n const { resolved, unconfigured } = resolveInstallConfig(supplied);\n if (resolved.reportMode === \"on\") deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);\n // After every check that needs no server; those that do run on each `wrap`.\n if (unconfigured) logUnconfigured(\"createBaton\");\n else warnAboutSettings(resolved);\n const sink = unconfigured ? new DisabledSink() : offTheCall(resolved.sink ?? new StdoutSink());\n const config = {\n ...resolved,\n sink,\n tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId),\n };\n const state = newBatonState(resolved);\n // One read for every server this Baton wraps.\n resolved.captureSettings?.start();\n return {\n wrap: (server) => {\n install(server, supplied, config, state, unconfigured);\n },\n flush: () => boundedSinkCall(sink, \"flush\"),\n aclose: () => {\n resolved.captureSettings?.stop();\n return boundedSinkCall(sink, \"aclose\");\n },\n };\n}\n\n/** A handle for an install that added nothing. The session id is a constant: a\n * real one would name a session no event exists under. */\nfunction inertHandle(sink: Sink, sessionId: string): BatonHandle {\n return new BatonHandle({ sink, sessionId, vendorId: \"\", annotationToolName: \"\" });\n}\n\n/** Which of the two servers this is, told apart by shape because this\n * package imports neither SDK. */\nfunction serverShapeOf(server: SupportedServer): \"mcpServer\" | \"lowLevel\" {\n const candidate = server as {\n server?: unknown;\n registerTool?: unknown;\n setRequestHandler?: unknown;\n _requestHandlers?: unknown;\n _serverInfo?: unknown;\n } | null;\n if (typeof candidate?.registerTool === \"function\" && typeof candidate.server === \"object\" && candidate.server !== null) {\n return \"mcpServer\";\n }\n // `_serverInfo` tells a Server from a Client, which has the same handler map.\n const isServer = typeof candidate?._serverInfo === \"object\" && candidate._serverInfo !== null;\n if (typeof candidate?.setRequestHandler === \"function\" && candidate._requestHandlers instanceof Map && isServer) {\n return \"lowLevel\";\n }\n throw new TypeError(\n \"Baton needs an McpServer or a low-level Server, from @modelcontextprotocol/sdk \" +\n \"or @modelcontextprotocol/server.\",\n );\n}\n\n/** Shared by every server one Baton wraps, so per-request servers act as one:\n * `createBaton.test.ts`, \"numbers one client session across requests\". */\ninterface BatonState {\n sentSurfaces: SentSurfaces;\n /** Kinds of warning already written, so `createBaton` writes each once and not per request. */\n warned: Set<string>;\n counter: SessionCounter;\n scrubber: (value: unknown) => unknown;\n lowLevelTools: KnownTools;\n}\n\nfunction newBatonState(config: BatonConfig): BatonState {\n return {\n sentSurfaces: new SentSurfaces(),\n warned: new Set(),\n counter: new SessionCounter(),\n scrubber: config.scrubber ?? new Scrubber().scrub,\n lowLevelTools: { given: config.tools, givenTools: [], served: new Map(), keepsGoal: new Set(), unread: new Set() },\n };\n}\n\nfunction install(\n server: SupportedServer,\n supplied: BatonConfig,\n resolved: ResolvedBatonConfig,\n { sentSurfaces, warned, counter: sharedCounter, scrubber, lowLevelTools }: BatonState,\n /** Nothing says where events go (SPEC §11.2 rule 10): check, then add nothing. */\n unconfigured: boolean,\n): BatonHandle {\n const shape = serverShapeOf(server);\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: LowLevelInternals;\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 const lowLevel = shape === \"mcpServer\" ? internals.server : (server as unknown as LowLevelInternals);\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: lowLevel._serverInfo?.name,\n className: internals.constructor.name,\n }));\n\n const config =\n resolved.reportMode === \"on\" ? withServerDisplayName(resolved, supplied, serverName) : resolved;\n const reports = reportsFor(config);\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 = reports\n ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName })\n : \"\";\n const ours = reports\n ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName })\n : INTENT_INSTRUCTIONS;\n\n if (unconfigured) return inertHandle(new DisabledSink(), \"baton-unconfigured\");\n // Truthy, not `Object.hasOwn`: the SDK refuses a name the same way, so\n // `constructor` is refused here, before the server changes.\n if (shape === \"mcpServer\" && reports && internals._registeredTools?.[annotationToolName]) {\n throw new Error(\n `Tool ${annotationToolName} is already registered, so Baton cannot add its report tool. ` +\n \"If it is your tool, set annotationToolName to another name; if Baton is already on \" +\n \"this server, call withBaton once.\",\n );\n }\n\n // The checks that change nothing are above this line; from here on the install\n // builds a sink and changes the server.\n const given = config.sink ?? new StdoutSink();\n const sink = offTheCall(given);\n const intentParamMode: IntentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;\n // Per server: two connections are never one session (SPEC §3.4), as\n // `createBaton.test.ts` \"never joins two connections that have no session id\" checks.\n const fallbackSessionId = `sdk-${uuid7()}`;\n const counter = new ServerCounter(sharedCounter, fallbackSessionId);\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\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(lowLevel);\n const surfaceState = new SurfaceState(serverMeta, sentSurfaces);\n\n const emitSurface = async (\n sessionId: string,\n digest: string,\n snapshot: Record<string, unknown>,\n ): Promise<void> => {\n // Deliberately NOT scrubbed — this is the vendor's own static tool\n // surface, not caller-supplied data (mirrors Python's emit_surface).\n await emit(sink, () =>\n SurfaceSnapshotEventSchema.parse({\n tenant_id: tenantId,\n vendor_id: config.vendorId,\n session_id: sessionId,\n session_id_origin: \"minted\",\n consent_token: config.consentToken,\n sequence_number: counter.next(sessionId, false),\n captured_at: new Date().toISOString(),\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 );\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 const warnOnce = (key: string, message: string): void => {\n if (warned.has(key)) return;\n warned.add(key);\n stderrLine(message);\n };\n\n const warnLength = (message: string): void => warnOnce(\"instructions-length\", message);\n const setInstructions = (text: string): void => {\n lowLevel._instructions = text;\n };\n const dropSubagentClause = (name: string): void => {\n if (!removeSubagentClause(lowLevel, setInstructions, warnLength)) return;\n warnOnce(\n \"native-user-goal\",\n `baton: tool ${JSON.stringify(name)} declares its own user_goal, so the subagent ` +\n \"sentence was removed from the server instructions; a session that already started keeps it\",\n );\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 const json = standardInputJsonSchema(inputSchema);\n if (json) return json;\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 EMPTY_OBJECT_JSON_SCHEMA;\n }\n };\n\n installValidationProbe(server);\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 configResultCaptureMode: config.resultCaptureMode ?? \"full\",\n paramRegistry: new Map(),\n resolvePrincipal: config.resolvePrincipal,\n captureSettings: config.captureSettings,\n perCaller: undefined,\n vendorToolJsonSchema,\n bustSchemaMemo,\n dropSubagentClause,\n servedInstructions: () => lowLevel._instructions,\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 writeInstructions = (text: string, subagent: string | null = INTENT_INSTRUCTIONS): void => {\n writeOurs(lowLevel, text, subagent, setInstructions, warnLength);\n };\n writeInstructions(ours);\n const rewriteInstructions = (text: string): void => {\n writeInstructions(text);\n const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === \"native\");\n if (native !== undefined) dropSubagentClause(native[0]);\n };\n if (config.captureSettings !== undefined) {\n ctx.perCaller = new PerCallerSurface({\n settings: config.captureSettings,\n intentParamMode,\n // Read, not copied: a low-level Server's own tool can take the name.\n get annotationToolName() {\n return ctx.annotationToolName;\n },\n pointer: () =>\n reports && ctx.annotationToolName\n ? buildReportPointer({ vendorDisplayName: reports.vendorDisplayName, annotationToolName: ctx.annotationToolName })\n : undefined,\n writeInstructions,\n subagentLine: () => ![...ctx.paramRegistry.values()].some((d) => d[USER_GOAL_PARAM_NAME] === \"native\"),\n injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === \"injected\",\n });\n ctx.perCaller.followSettings();\n }\n\n const annotationOptions = !reports ? undefined : {\n sink,\n counter: ctx.counter,\n tenantId: ctx.tenantId,\n vendorId: ctx.vendorId,\n vendorDisplayName: reports.vendorDisplayName,\n consentToken: ctx.consentToken,\n resolvePrincipal: ctx.resolvePrincipal,\n captureSettings: ctx.captureSettings,\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 };\n\n // Innermost, so every seam below sees the list with Baton's additions.\n if (shape === \"lowLevel\") {\n installLowLevelToolSeams(\n lowLevel,\n ctx,\n annotationOptions && buildAnnotationTool(server, annotationOptions),\n lowLevelTools,\n warnOnce,\n () => (ctx.perCaller ? ctx.perCaller.refresh() : rewriteInstructions(INTENT_INSTRUCTIONS)),\n );\n }\n\n // Before any tool registers: on a server with no tools yet, the first\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 installToolsListSeam(lowLevel, ctx, shape === \"lowLevel\");\n\n // The SECOND tool-call seam (SPEC §11.4.3's `failure_kind`), installed here\n // for the same reason the `tools/list` seam is. Not on a low-level Server,\n // which has no registry to classify a refused call against.\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 if (shape === \"mcpServer\") installToolsCallSeam(\n lowLevel,\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 lifecycle seams (SPEC §11.4.4, §11.4.5) — unconditional, like the\n // seam above, because what they capture is not configurable. After the\n // `tools/list` seam, so they wrap it and the per-caller rewrite sees the\n // advertised `required`: consoleSettings.test.ts, \"two callers in different\n // audiences see different tool lists\".\n installLifecycleSeams(lowLevel, ctx);\n\n // Last, so it wraps every seam above: each request waits for\n // `BATON_CANDIDATE`'s change, and a connection reads the instructions once,\n // from its handshake.\n const settings = config.captureSettings;\n if (settings !== undefined) {\n const waitFirst =\n (handler: AnyHandler): AnyHandler =>\n async (...args) => {\n if (!settings.isReady) await settings.ready;\n ctx.perCaller?.followSettings();\n return handler(...args);\n };\n for (const method of [\"initialize\", \"server/discover\", TOOLS_LIST_METHOD, TOOLS_CALL_METHOD]) {\n installRequestSeam(lowLevel, method, SETTINGS_SEAM, waitFirst);\n }\n }\n\n const handle = (name: string): BatonHandle =>\n new BatonHandle({\n sink: given,\n queue: sink,\n vendorId: config.vendorId,\n sessionId: fallbackSessionId,\n annotationToolName: name,\n });\n if (shape === \"lowLevel\") return handle(annotationToolName);\n\n const resolvedAnnotationToolName = annotationOptions\n ? registerAnnotationTool(server as SupportedMcpServer, annotationOptions)\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 handle(resolvedAnnotationToolName);\n}\n\n/** The display name the reports need, or `undefined` under `reportMode: \"off\"`. */\nfunction reportsFor(config: ResolvedBatonConfig): { vendorDisplayName: string } | undefined {\n if (config.reportMode !== \"on\") return undefined;\n // `validateBatonConfig` refuses reportMode \"on\" without one.\n return { vendorDisplayName: config.vendorDisplayName ?? \"\" };\n}\n\n/** Once per `withBaton` or `createBaton`, not per request. */\nfunction warnAboutSettings(config: ResolvedBatonConfig): void {\n if (config.reportMode !== \"on\" && config.annotationToolName !== undefined) {\n stderrLine(\n `baton: annotationToolName=${JSON.stringify(config.annotationToolName)} has no effect ` +\n 'with reportMode: \"off\", because no annotation tool is registered',\n );\n }\n candidateNeedsConsole(config.settings);\n if (config.resultCaptureMode === WITHHELD) {\n warn(\n 'baton: resultCaptureMode \"off\" does not withhold the message of a failed tool list, ' +\n \"resource or prompt request. tool_list_error, resource_list_error, resource_read_error, \" +\n \"prompt_list_error and prompt_get_error carry that message, which can include text your \" +\n \"handler or middleware threw. Throw a message that does not quote what your code fetched.\",\n );\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 / what_happened / tool_name / suggested_improvement /\n * context) and emits an `annotation`\n * event. Port of `baton` (Python)'s `integrations/official/annotation.py`\n * `user_goal` is required by the schema, and a call that is not a report is\n * refused.\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 { isBlank } from \"../../_text.js\";\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, callerEnvelope, resolveCaller } from \"./principalResolution.js\";\nimport { type CaptureSettings, overlayChanges } from \"./captureSettings.js\";\nimport type { Overlay } from \"./overlays.js\";\nimport { buildAnnotationToolDescription, buildRefusalText } from \"./llmText.js\";\nimport { standardInputJsonSchema, toolInputJsonSchema } from \"./schemaCompat.js\";\nimport { extraMeta, observeTransport, type Extra } from \"./mcpTypes.js\";\nimport type { SupportedMcpServer } from \"./withBaton.js\";\nimport { observeClient } from \"./clientObserved.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 what_happened?: string | undefined;\n tool_name?: string | null | 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 /** The vendor's identity resolver — the SAME one the tool-call wrapper\n * holds. */\n resolvePrincipal?: ResolvePrincipalHook | undefined;\n captureSettings?: CaptureSettings | undefined;\n}\n\n/** Advertised as required on the annotate tool (by the `tools/list` seam in\n * withBaton.ts, and in `reportTool`'s schema) and never enforced: the zod\n * schema keeps it optional. */\nexport const TOOL_NAME_PARAM_NAME = \"tool_name\";\n\nexport const ANNOTATION_INPUT_SHAPE = {\n user_goal: z.string(),\n what_happened: z.string().optional(),\n // Nullable so a report whose agent sends an explicit null is taken,\n // not rejected by validation.\n tool_name: z.string().nullable().optional(),\n suggested_improvement: z.string().optional(),\n // zod renders \"any value\" as `{}`, which some MCP clients refuse (reportToolSchema.test.ts).\n context: z.record(z.string(), z.unknown()).meta({ additionalProperties: true }).optional(),\n};\n\n/** SPEC §11.4: an annotation is a report when its account is filled. */\nexport function isReport(whatHappened: unknown): whatHappened is string {\n return typeof whatHappened === \"string\" && !isBlank(whatHappened);\n}\n\nexport interface AnnotationTool {\n name: string;\n description: string;\n /** Runs on arguments the input schema has already accepted. */\n handler: (args: AnnotationArgs, extra: Extra) => Promise<CallToolResultLike>;\n}\n\ninterface CallToolResultLike {\n content: Array<{ type: \"text\"; text: string }>;\n isError?: boolean;\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 tool = buildAnnotationTool(server, options);\n server.registerTool(\n tool.name,\n { description: tool.description, inputSchema: ANNOTATION_INPUT_SHAPE },\n tool.handler,\n );\n return tool.name;\n}\n\nconst ANNOTATION_ARGS = z.object(ANNOTATION_INPUT_SHAPE);\n\n/** The report tool's input schema as Baton lists it on a server of that\n * major: v2 renders draft 2020-12 from the schema itself, 1.x through its own\n * converter. */\nexport function annotationInputJsonSchema(major: 1 | 2): Record<string, unknown> {\n // A zod without the Standard JSON Schema interface falls back to the 1.x\n // converter, so a vendor's boot never fails on the report tool's schema.\n return (annotationJsonSchemas[major] ??=\n (major === 2 ? standardInputJsonSchema(ANNOTATION_ARGS) : undefined) ?? toolInputJsonSchema(ANNOTATION_INPUT_SHAPE));\n}\n\nconst annotationJsonSchemas: Partial<Record<1 | 2, Record<string, unknown>>> = {};\n\n/** `tools/call` for the annotation tool on a server with no tool registry to\n * validate its arguments, so the check `McpServer` makes is made here. */\nexport function callAnnotationTool(\n tool: AnnotationTool,\n args: unknown,\n extra: Extra,\n): Promise<CallToolResultLike> {\n const parsed = ANNOTATION_ARGS.safeParse(args ?? {});\n if (parsed.success) return tool.handler(parsed.data, extra);\n return Promise.resolve({\n content: [{ type: \"text\", text: `Invalid arguments for tool ${tool.name}: ${parsed.error.message}` }],\n isError: true,\n });\n}\n\n/** The annotation tool for `server`, which is read only for the client the\n * `initialize` handshake declared. */\nexport function buildAnnotationTool(\n server: unknown,\n options: RegisterAnnotationToolOptions,\n): AnnotationTool {\n const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);\n const description = buildAnnotationToolDescription({\n vendorDisplayName: options.vendorDisplayName,\n });\n const refused = (overlay?: Overlay) => ({\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ ok: false, error: buildRefusalText({ annotationToolName: name, overlay }) }),\n },\n ],\n });\n\n return {\n name,\n description,\n handler: async (args: AnnotationArgs, extra: Extra) => {\n // Refused in the handler, not by requiring `what_happened` in the\n // schema: an agent that must fill it to get a call through invents a\n // problem, and that corrupts the reports.\n const whatHappened = args.what_happened;\n if (!isReport(whatHappened) && !overlayChanges(options.captureSettings, \"report_tool.refusal\")) return refused();\n // Sent as given (SPEC §5.1.1): \"\" means the agent said no tool exists,\n // null means it said nothing, and the two must not merge.\n const reportedTool = args.tool_name ?? null;\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.\n const client = observeClient(extra, { server, scrubber: options.scrubber });\n const caller = await resolveCaller(\n options.resolvePrincipal,\n { extra, toolName: name, arguments: args },\n options.captureSettings,\n client,\n );\n if (!isReport(whatHappened)) return refused(caller.settings?.overlay);\n\n const meta = extraMeta(extra);\n // As in the tool-call wrapper: coordinates coarsened before the\n // vendor's scrubber.\n const scrubbedMeta = scrubOrNull(\n options.scrubber,\n meta ? roundMetaCoordinates(meta) : null,\n \"_meta\",\n );\n const session = await resolveSessionId(options.fallbackSessionId, extra);\n\n await emit(options.sink, () =>\n AnnotationEventSchema.parse({\n tenant_id: options.tenantId,\n vendor_id: options.vendorId,\n session_id: session.sessionId,\n sequence_number: options.counter.nextFor(session),\n captured_at: new Date().toISOString(),\n consent_token: options.consentToken,\n ...callerEnvelope(caller),\n transport_observed: observeTransport(extra),\n session_id_origin: session.origin,\n client_observed: client,\n runtime_meta: scrubbedMeta,\n payload: {\n // The agent-facing `user_goal` is stored as the wire key `intent`.\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 // 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 what_happened: options.scrubber(whatHappened),\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 tool_name: reportedTool ? options.scrubber(reportedTool) : reportedTool,\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","/**\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\";\nimport { isPlainObject } from \"./_object.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/** `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 still sees 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","/** Overlays in the settings document (SPEC §2.6): read, place, and change text.\n * The TypeScript half of Python's `_overlays.py`. */\n\nimport { isRecord } from \"../../_object.js\";\nimport { stripWhiteSpaceEnd } from \"../../_text.js\";\nimport { warn } from \"../../warn.js\";\n\nexport type Place = \"audience\" | \"server\";\n\nexport const INSTRUCTION_PIECES: readonly string[] = [\"instructions.subagent\", \"instructions.report_pointer\"];\nconst AUDIENCE_PIECES: readonly string[] = [\"goal_param.description\", \"report_tool.description\", \"report_tool.refusal\"];\nconst TEXT_CHANGES: readonly string[] = [\"append\", \"replace\"];\nconst FLAG_CHANGES: readonly string[] = [\"remove\", \"required\"];\n\n// Overlay ids never change once saved, so one warning per action is enough.\nconst warned = new Set<string>();\nconst unreadable = new Set<string>();\n\nexport function warnSkipped(overlayId: string, index: number, reason: string): void {\n const key = JSON.stringify([overlayId, index]);\n if (warned.has(key)) return;\n warned.add(key);\n warn(`baton: overlay ${JSON.stringify(overlayId)} action ${index} is skipped: ${reason}`);\n}\n\nexport interface Action {\n readonly index: number;\n readonly change: string;\n readonly text?: string;\n readonly tool?: string;\n readonly param?: string;\n readonly piece?: string;\n readonly instructions?: true;\n}\n\nexport class Overlay {\n readonly hiddenTools: ReadonlySet<string>;\n\n constructor(\n readonly id: string,\n readonly actions: readonly Action[],\n ) {\n this.hiddenTools = new Set(\n actions.filter((a) => a.tool !== undefined && a.param === undefined && a.change === \"remove\").map((a) => a.tool!),\n );\n }\n\n pieceActions(piece: string): readonly Action[] {\n return this.actions.filter((a) => a.piece === piece);\n }\n\n instructionAppends(): string[] {\n return this.actions.filter((a) => a.instructions && a.text !== undefined).map((a) => a.text!);\n }\n}\n\nexport type TextSource = \"default\" | \"appended\" | \"replaced\";\n\n/** `text` after `actions`, and its `agent_text` source. */\nexport function changedText(\n text: string | undefined,\n actions: readonly Action[],\n): { text: string | undefined; source: TextSource } {\n let source: TextSource = \"default\";\n for (const action of actions) {\n if (action.change === \"replace\") {\n text = action.text;\n source = \"replaced\";\n } else if (action.change === \"append\" && action.text !== undefined) {\n const kept = stripWhiteSpaceEnd(text ?? \"\");\n text = kept ? `${kept}\\n\\n${action.text}` : action.text;\n if (source === \"default\") source = \"appended\";\n }\n }\n return { text, source };\n}\n\n/** `text`, the piece `piece` of Baton's text, after `overlay`. */\nexport function overlaid(text: string, overlay: Overlay | undefined, piece: string): string {\n if (overlay === undefined) return text;\n return changedText(text, overlay.pieceActions(piece)).text ?? text;\n}\n\n/** The document's `overlays`; one that is not an object holds none. */\nexport function readOverlays(value: unknown): Record<string, unknown> {\n return isRecord(value) ? value : {};\n}\n\n/** The overlay `overlayId` names, holding the actions allowed in `place`.\n * `undefined` with one warning when it cannot be read; a bad action is skipped alone. */\nexport function overlayFor(overlays: Record<string, unknown>, overlayId: unknown, place: Place): Overlay | undefined {\n if (overlayId === undefined || overlayId === null) return undefined;\n let id: string;\n let body: unknown;\n if (typeof overlayId === \"string\") {\n id = overlayId;\n body = Object.hasOwn(overlays, id) ? overlays[id] : undefined;\n } else {\n id = JSON.stringify(overlayId);\n }\n const actions = isRecord(body) ? body.actions : undefined;\n if (!Array.isArray(actions)) {\n if (!unreadable.has(id)) {\n unreadable.add(id);\n warn(`baton: overlay ${JSON.stringify(id)} cannot be read; none is applied there`);\n }\n return undefined;\n }\n const kept: Action[] = [];\n actions.forEach((raw, index) => {\n const read = readAction(index, raw, place);\n if (typeof read === \"string\") warnSkipped(id, index, read);\n else kept.push(read);\n });\n return new Overlay(id, kept);\n}\n\n/** The action, or why it is skipped. */\nfunction readAction(index: number, raw: unknown, place: Place): Action | string {\n if (!isRecord(raw) || !isRecord(raw.target)) return \"it has no target\";\n const target = raw.target;\n const changes = [...TEXT_CHANGES, ...FLAG_CHANGES].filter((c) => Object.hasOwn(raw, c));\n if (changes.length !== 1 || Object.keys(raw).length !== 2) return \"it needs exactly one change\";\n const change = changes[0]!;\n const value = raw[change];\n if (TEXT_CHANGES.includes(change) && typeof value !== \"string\") return `'${change}' needs text`;\n if (FLAG_CHANGES.includes(change) && value !== true) return `'${change}' must be true`;\n const text = typeof value === \"string\" ? { text: value } : {};\n const keys = Object.keys(target).sort().join(\",\");\n if (keys === \"tool\" && typeof target.tool === \"string\") {\n if (change === \"required\") return \"only a param can be required\";\n return placed({ index, change, ...text, tool: target.tool }, place, \"audience\");\n }\n if (keys === \"param,tool\" && typeof target.tool === \"string\" && typeof target.param === \"string\") {\n return placed({ index, change, ...text, tool: target.tool, param: target.param }, place, \"audience\");\n }\n if (keys === \"instructions\" && target.instructions === true) {\n if (change !== \"append\") return \"the instructions take only 'append'\";\n return placed({ index, change, ...text, instructions: true }, place, \"server\");\n }\n if (keys === \"agent_text\" && typeof target.agent_text === \"string\") {\n const piece = target.agent_text;\n if (!TEXT_CHANGES.includes(change)) return \"agent_text takes only 'append' or 'replace'\";\n if (INSTRUCTION_PIECES.includes(piece)) return placed({ index, change, ...text, piece }, place, \"server\");\n if (AUDIENCE_PIECES.includes(piece)) return placed({ index, change, ...text, piece }, place, \"audience\");\n return `unknown agent_text ${JSON.stringify(piece)}`;\n }\n return \"unknown target\";\n}\n\nfunction placed(action: Action, place: Place, allowed: Place): Action | string {\n if (place === allowed) return action;\n return `this target goes only in ${allowed === \"server\" ? \"server_overlay\" : \"an audience's overlay\"}`;\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 rationale. Kept in sync by hand, as there is no\n * cross-language codegen for prose, and checked:\n * `test/integrations/mcp/llmTextVectors.json` is Python's own rendering,\n * compared string-for-string.\n *\n * **Python's text.** Under `reportMode: \"on\"` it renders what Python\n * renders: the instructions are one sentence pointing at the\n * annotation tool, and the tool's description holds the triggers, the\n * recovery rule and the fields, so each rule is written once.\n */\n\nimport { isBlank } from \"../../_text.js\";\nimport { stderrLine } from \"../../warn.js\";\nimport { type Overlay, overlaid } from \"./overlays.js\";\n\n// Holds no report rule: each is written once, in the report tool's description.\nconst REPORT_POINTER_TEMPLATE = (vendorDisplayName: string, annotationToolName: string) =>\n `Use \\`${annotationToolName}\\` to report a ${vendorDisplayName} tool call ` +\n \"that went wrong, or a request no tool covers; its description says when and how.\";\n\n// The format SPEC §5.1.1 gives for user_goal.\nconst USER_GOAL_FORMAT = \"'<n>: <what this call is for>; success is <what its result should show>'\";\n\nconst ANNOTATION_TOOL_DESCRIPTION_TEMPLATE = (\n vendorDisplayName: string,\n) => `Report a ${vendorDisplayName} tool call that went wrong, so \\\n${vendorDisplayName} can fix it. Call this right after a call errors, times \\\nout, or returns an empty, unhelpful or contradictory result. Also call it \\\nonce per user request when no tool or field covers what they asked for, or \\\nyou had to work around one. Do not call it before a tool call or for normal \\\nsuccessful work.\n\nA report does not replace the work: after it, work out why the call failed, \\\nfix the input and try again (do not repeat the same failing call), and still \\\nanswer the user.\n\nFields:\n - user_goal: the same ${USER_GOAL_FORMAT} as on this server's other tools.\n - what_happened: REQUIRED. 1-2 plain sentences in your own words: what you \\\nasked for, what came back, and why it was unusable. Not a category.\n - tool_name: REQUIRED. The ${vendorDisplayName} tool that went wrong, or \\\nnone if no tool exists for the request.\n - suggested_improvement: one concrete sentence on the product change that \\\nwould 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. When no tool covers the \\\nrequest also missing_capability_field and requested_capability.`;\n\n// Where Claude Code truncates InitializeResult.instructions. The cap below it\n// leaves room for the fixed subagent sentence.\nconst CLAUDE_CODE_TRUNCATION_CAP = 2087;\nconst INSTRUCTIONS_LENGTH_CAP = 1500;\n\ninterface InstructionNames {\n vendorDisplayName: string;\n annotationToolName: string;\n}\n\n/** The report pointer paragraph, without the subagent sentence. */\nexport function buildReportPointer(options: InstructionNames): string {\n return REPORT_POINTER_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. 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 buildReportPointer(options).length <= INSTRUCTIONS_LENGTH_CAP;\n}\n\nexport function buildServerInstructions(options: InstructionNames): string {\n const rendered = buildReportPointer(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 // The subagent sentence has no names in it, so it comes out of the headroom\n // under the truncation cap, not out of the budget the names share.\n return rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;\n}\n\nexport function buildAnnotationToolDescription(options: { vendorDisplayName: string }): string {\n return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);\n}\n\n/** What the annotation tool answers when a call has no account (SPEC §5.1.1),\n * after the caller's `overlay`. */\nexport function buildRefusalText(options: { annotationToolName: string; overlay?: Overlay | undefined }): string {\n const text =\n `${options.annotationToolName} is reactive-only on this server. Call it only AFTER ` +\n \"a tool call returns an unhelpful, empty, failed or contradictory result, or \" +\n \"when no tool covers what the user asked for. What the user is trying to do \" +\n \"is already recorded on each tool call, so no pre-call annotation is needed — \" +\n \"nothing was lost. If a tool call really went wrong, or no tool covers the \" +\n \"request, call this again and say what_happened. If neither is true, do NOT \" +\n \"re-send: that would file a report for a call that did not go wrong.\";\n return overlaid(text, options.overlay, \"report_tool.refusal\");\n}\n\n// =============================================================================\n// Intent-param injection text — mirrors `baton` (Python)'s\n// `integrations/_llm_text.py` byte-for-byte. This is the capture path that\n// survives runtimes which drop `instructions`, notably Claude Desktop.\n// =============================================================================\n\nexport const USER_GOAL_PARAM_NAME = \"user_goal\";\n\n// Not injected. A client with an old tool list may still send them, and\n// `overall_task` carries the turn number the Console falls back to.\nexport const EXPECTED_RESULT_PARAM_NAME = \"expected_result\";\nexport const OVERALL_TASK_PARAM_NAME = \"overall_task\";\nexport const RETIRED_PARAM_NAMES = [EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME] as const;\n\n/** Provenance value stamped on `tool_call_start.payload.intent_source` when\n * intent came from an injected param. The Console reads this string. */\nexport const INTENT_SOURCE_PARAM = \"injected_param\";\n\n/** `intent_source` when the vendor's code passed intent to `client.trace()`. */\nexport const INTENT_SOURCE_LIBRARY = \"library_arg\";\n\n// The leading number says which user message the call answers (SPEC §5.1.1).\n//\n// Do not reword: the text is the Python SDK's, byte for byte\n// (`llmText.test.ts`, \"parity with the Python SDK's rendered text\"). Only the\n// leading label tracks `intentParamMode`, so it agrees with the `required`\n// list the `tools/list` seam advertises.\nconst USER_GOAL_PARAM_BODY =\n `Write it as ${USER_GOAL_FORMAT}. n is the number of the user's current message in this ` +\n \"conversation (1 for the first). Use the same number on every call you make \" +\n \"for that message, including calls made after reading tool results; it goes \" +\n \"up only when the user sends another message.\";\nconst USER_GOAL_PARAM_DESCRIPTION = \"OPTIONAL. \" + USER_GOAL_PARAM_BODY;\nconst USER_GOAL_PARAM_DESCRIPTION_REQUIRED = \"REQUIRED. \" + USER_GOAL_PARAM_BODY;\n\n// A main agent that delegates may never load this server's tool schemas, so the\n// param description above never reaches it and its subagents get no number.\nexport const INSTRUCTIONS_SUBAGENT_CLAUSE =\n \"\\n\\nWhen you hand work to a subagent that may call this server's tools, tell it \" +\n \"the number of the user's current message in this conversation, and that it \" +\n \"must start user_goal with that number on every call to this server's \" +\n \"tools. This applies only to this server's tools.\";\n\n/** The server instructions a vendor serving MCP itself puts in its\n * `initialize` result beside `user_goal` (SPEC §5.6), and all of Baton's\n * instructions under `reportMode: \"off\"`. */\nexport const INTENT_INSTRUCTIONS = INSTRUCTIONS_SUBAGENT_CLAUSE.trim();\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\n/** Which injected params `intentParamMode` advertises as required. */\nexport function requiredParamNames(intentParamMode: string): string[] {\n return intentParamMode === \"required\" ? [USER_GOAL_PARAM_NAME] : [];\n}\n\n/** Whether a tool's vendor-true JSON `inputSchema` declares `name` itself. */\nexport function declaresParam(schema: unknown, name: string): boolean {\n const props = (schema as { properties?: unknown } | null | undefined)?.properties;\n return typeof props === \"object\" && props !== null && name in props;\n}\n\n// What a schema forbids, or values it shows, never names a parameter it takes.\nconst NOT_ACCEPTED = new Set([\"not\", \"const\", \"enum\", \"default\", \"examples\"]);\n// Their keys are the vendor's names, so a property called \"default\" is searched.\nconst NAMED_SCHEMAS = new Set([\"properties\", \"patternProperties\", \"$defs\", \"definitions\", \"dependentSchemas\"]);\n\n/** Whether a JSON schema may take `name` anywhere: as a property or a\n * required name at any depth, or behind a `$ref` to another document, which\n * Baton cannot read. */\nexport function mayDeclareParam(schema: unknown, name: string): boolean {\n const seen = new Set<object>();\n const walk = (node: unknown): boolean => {\n if (typeof node !== \"object\" || node === null || seen.has(node)) return false;\n seen.add(node);\n const { required, $ref } = node as { required?: unknown; $ref?: unknown };\n if (declaresParam(node, name) || (Array.isArray(required) && required.includes(name))) return true;\n if (typeof $ref === \"string\" && !$ref.startsWith(\"#\")) return true;\n return Object.entries(node).some(([key, child]: [string, unknown]) => {\n if (NAMED_SCHEMAS.has(key) && typeof child === \"object\" && child !== null) return Object.values(child).some(walk);\n return !NOT_ACCEPTED.has(key) && walk(child);\n });\n };\n return walk(schema);\n}\n\n/** Whether Baton's text is in the served instructions. Without the annotation\n * tool it is only the subagent sentence, which a tool declaring its own\n * `user_goal` removes. */\nexport function instructionsSuffixServed(annotationToolName: string, served: unknown): boolean {\n if (annotationToolName) return true;\n return typeof served === \"string\" && served.includes(INTENT_INSTRUCTIONS);\n}\n\n/** One injected param, for a vendor adding it to its own API (SPEC §5.6).\n * `description` is the text an agent reads on an MCP server, without the\n * leading \"OPTIONAL.\" / \"REQUIRED.\" label: whether the vendor's API requires\n * it is the vendor's call. `traceOption` is the `client.trace()` option the\n * agent's answer goes to. */\nexport interface IntentParam {\n readonly name: string;\n readonly description: string;\n readonly traceOption: \"intent\";\n}\n\nexport const INTENT_PARAMS: readonly IntentParam[] = Object.freeze([\n Object.freeze({ name: USER_GOAL_PARAM_NAME, description: USER_GOAL_PARAM_BODY, traceOption: \"intent\" }),\n]);\n\nconst VENDOR_INSTRUCTIONS = Symbol(\"batonVendorInstructions\");\nconst OURS = Symbol(\"batonInstructions\");\nconst SUBAGENT = Symbol(\"batonSubagentSentence\");\n\ninterface InstructionsHolder {\n _instructions?: string | undefined;\n [VENDOR_INSTRUCTIONS]?: string | undefined;\n [OURS]?: string;\n [SUBAGENT]?: string | undefined;\n}\n\nfunction joined(vendor: unknown, ours: string): string {\n if (typeof vendor !== \"string\" || isBlank(vendor)) return ours;\n return ours ? `${vendor}\\n\\n${ours}` : vendor;\n}\n\nfunction vendorText(holder: InstructionsHolder): string | undefined {\n const current = holder._instructions;\n const written = holder[OURS];\n const vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current;\n return written !== undefined && current === joined(vendor, written) ? vendor : current;\n}\n\n/** Write `ours` below the vendor's instructions (SPEC §5.1.2). `subagent` is\n * the subagent sentence `ours` ends with, if it does.\n *\n * What was written is remembered on the server once the write succeeds, so a\n * second install or a new setting replaces our paragraph rather than appending\n * another; text the vendor set in between replaces what was remembered. */\nexport function writeOurs(\n server: object,\n ours: string,\n subagent: string | null,\n write: (instructions: string) => void,\n warn: (message: string) => void = stderrLine,\n): void {\n const holder = server as InstructionsHolder;\n const vendor = vendorText(holder);\n write(withVendorInstructions(server, ours, warn));\n holder[VENDOR_INSTRUCTIONS] = vendor;\n holder[OURS] = ours;\n holder[SUBAGENT] = subagent && ours.endsWith(subagent) ? subagent : undefined;\n}\n\n/** Take the subagent sentence out of what `writeOurs` wrote; whether there was one. */\nexport function removeSubagentClause(\n server: object,\n write: (instructions: string) => void,\n warn: (message: string) => void = stderrLine,\n): boolean {\n const holder = server as InstructionsHolder;\n const ours = holder[OURS];\n const subagent = holder[SUBAGENT];\n if (ours === undefined || !subagent || holder._instructions !== joined(holder[VENDOR_INSTRUCTIONS], ours)) {\n return false;\n }\n const kept = ours.slice(0, ours.length - subagent.length);\n writeOurs(server, kept.endsWith(\"\\n\\n\") ? kept.slice(0, -2) : kept, null, write, warn);\n return true;\n}\n\n/** The instructions `writeOurs` writes: the vendor's first, ours below.\n * The runtime cuts at `CLAUDE_CODE_TRUNCATION_CAP` from the end, so the order\n * decides whose text is lost. */\nexport function withVendorInstructions(\n server: object,\n ours: string,\n warn: (message: string) => void = stderrLine,\n): string {\n const vendor = vendorText(server);\n const combined = joined(vendor, ours);\n if (combined === ours) return ours;\n const vendorLength = vendor?.length ?? 0;\n if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {\n warn(\n `baton: the server instructions are ${combined.length} chars (yours ${vendorLength}, ` +\n `Baton's ${ours.length}); Claude Code cuts them at ~${CLAUDE_CODE_TRUNCATION_CAP}, ` +\n \"so the end of Baton's text is lost there\",\n );\n }\n return combined;\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 { stripEdges } from \"../../_text.js\";\nimport { warn } from \"../../warn.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\n/** What Python's `str.strip()` removes: Unicode `White_Space` plus\n * U+001C-U+001F. The server-name rule keeps it, as the Console's slug rule does. */\nconst SEPARATORS = \"\\\\x1c-\\\\x1f\";\nconst PYTHON_SPACE = new RegExp(`^[\\\\p{White_Space}${SEPARATORS}]$`, \"u\");\n\nfunction pythonStrip(value: string): string {\n return stripEdges(value, PYTHON_SPACE);\n}\n\nfunction isPlaceholderLiteral(name: string): boolean {\n return PLACEHOLDER_LITERALS.has(pythonStrip(name).toLowerCase());\n}\n\nfunction isLibraryPlaceholder(serverName: string, className: string): boolean {\n if (isPlaceholderLiteral(serverName)) return true;\n const stripped = pythonStrip(serverName);\n const stem = stripped.replace(RANDOM_SUFFIX, \"\");\n return stem !== stripped && stem === className;\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/** `{slug}_annotate` from a display name, as an adapter derives it from a\n * server of that name, or `undefined` where an adapter would fall back. */\nexport function toolNameForDisplayName(vendorDisplayName: string): string | undefined {\n if (isPlaceholderLiteral(vendorDisplayName)) return undefined;\n const candidate = toolNameCandidate(vendorDisplayName);\n return candidate !== undefined &&\n fitsInstructionsCap({ vendorDisplayName, annotationToolName: candidate })\n ? candidate\n : undefined;\n}\n\n/** The last step of the ladder. 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 return validateAnnotationToolName(override || `${vendorId}${SUFFIX}`);\n}\n\n/** The ladder's one throw site. */\nexport function validateAnnotationToolName(name: string): string {\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\";\nimport { PROCESS_DROPS } from \"../../drops.js\";\nimport { printable, stderrLine } from \"../../warn.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_DROPS.add(\"encode_failed\");\n stderrLine(`baton: event construction failed; event dropped: ${printable(err)}`);\n return;\n }\n await safeWrite(sink, event);\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, isBlank } 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/** 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 return usableText(value, DISPLAY_NAME_MAX_LEN) ? value : null;\n}\n\n/** SPEC §11.4's rule for `display_name` and labels. Mirrors Python's `usable_text`. */\nfunction usableText(value: unknown, maxCodePoints: number): value is string {\n if (typeof value !== \"string\" || exceedsCodePoints(value, maxCodePoints)) return false;\n // U+0000: Postgres text refuses it, costing a collector the whole event.\n return !LONE_SURROGATE.test(value) && !value.includes(\"\\u0000\") && !isBlank(value);\n}\n\nexport const LABELS_MAX = 20;\nexport const LABEL_MAX_LEN = 64;\n/** How many a resolver's labels are read up to, so an endless iterable cannot hang a call. */\nconst LABELS_READ_MAX = 1000;\n\n/** The envelope's `labels`: `null`, never an empty list (SPEC §11.4). */\nexport function wireLabels(labels: readonly string[]): readonly string[] | null {\n return labels.length > 0 ? labels : null;\n}\n\n/** The usable labels, in the order given, without repeats, at most\n * `LABELS_MAX` (SPEC §11.4). Mirrors Python's `clean_labels`. */\nexport function cleanLabels(values: Iterable<unknown>): string[] {\n const kept = new Set<string>();\n for (const value of values) {\n if (usableText(value, LABEL_MAX_LEN)) {\n kept.add(value);\n if (kept.size === LABELS_MAX) break;\n }\n }\n return [...kept];\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/** 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/** 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 /** The company this principal belongs to. Sent as `organization`, and\n * dropped alone when unusable (SPEC §11.4). */\n organization?: Organization | null | undefined;\n /** As `Organization.labels`. A principal's labels and its organization's\n * are sent together. */\n labels?: readonly string[] | undefined;\n}\n\n/** The company or workspace the caller belongs to, as the vendor sees it.\n * Sent as `organization` (SPEC §11.4), beside `principal` or alone. It is\n * never counted as a person. `form` describes `organizationId` alone. */\nexport interface Organization {\n organizationId: string;\n form?: PrincipalForm | undefined;\n displayName?: string | null | undefined;\n /** Your names for the groups this caller is in, for Console settings to\n * match (SPEC §11.4). Baton sees them, so use group names or keys you keep,\n * never raw ids. */\n labels?: readonly string[] | undefined;\n}\n\nfunction usableId(id: unknown): id is string {\n if (typeof id !== \"string\") return false;\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(id)) return false;\n // U+0000 is refused by Postgres text and would cost a collector the whole event.\n if (id.includes(\"\\u0000\")) return false;\n // A blank id names nobody, and every such caller would merge into one actor.\n return !isBlank(id);\n}\n\nfunction readIdentity(\n result: unknown,\n idKey: \"principalId\" | \"organizationId\",\n): { id: string; form: unknown; displayName: string | undefined } | null {\n if (result === null || typeof result !== \"object\") return null;\n const candidate = result as Record<string, unknown>;\n const id = candidate[idKey];\n if (!usableId(id)) return null;\n // Shape only; the name's own rules run once, in `identityWire`.\n const displayName = typeof candidate.displayName === \"string\" ? candidate.displayName : undefined;\n return { id, form: candidate.form, displayName };\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/** The organization as emitted: `principal`'s members and rules, with its\n * own `form` (SPEC §11.4). */\nexport type OrganizationWire = PrincipalWire;\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 envelope's `principal`, `organization` and `labels`. Either, both or\n * neither identity may be set: SPEC §11.4 keeps them independent. */\nexport interface CallerWire {\n principal: PrincipalWire | null;\n organization: OrganizationWire | null;\n labels: readonly string[];\n}\n\nexport const NO_CALLER: CallerWire = Object.freeze({ principal: null, organization: null, labels: [] });\n\n/** Told why `callerFor` dropped or rewrote something. `key` is fixed text, so\n * a caller can report each kind of problem once; `message` may hold part of\n * the vendor's value. */\nexport type CallerWarning = (key: string, message: string) => void;\n\n/** What a `resolvePrincipal` hook returned, or `principal` was given, as wire\n * objects: a `Principal`, which may carry its `organization`, or an\n * `Organization` alone. Each is dropped alone when unusable. Never throws:\n * the value is vendor code, and a getter or Proxy on it may. */\nexport function callerFor(result: unknown, warn: CallerWarning): CallerWire {\n try {\n return readCaller(result, warn);\n } catch {\n warn(\"unreadable\", \"could not be read — sending neither principal nor organization.\");\n return NO_CALLER;\n }\n}\n\nfunction readCaller(result: unknown, warn: CallerWarning): CallerWire {\n if (result === undefined || result === null) return NO_CALLER;\n if (typeof result !== \"object\") {\n warn(\"not-object\", `got a ${typeof result}, not an object — sending neither principal nor organization.`);\n return NO_CALLER;\n }\n // A `principalId` or an `organization` key makes it a `Principal`, so a\n // missing or blank person still keeps the company; otherwise an `Organization`.\n if (!(\"principalId\" in result) && !(\"organization\" in result)) {\n if (\"organizationId\" in result) {\n return {\n principal: null,\n organization: identityFor(result, \"organization\", warn),\n labels: labelsOf([result], warn),\n };\n }\n if (typeof (result as { userId?: unknown }).userId === \"string\") {\n warn(\n \"user-id\",\n \"returned { userId }, which was renamed to { principalId } in 0.3.5, so the principal \" +\n \"is dropped from every event until it returns the new key.\",\n );\n } else {\n warn(\"no-id\", \"got an object with neither principalId nor organizationId — sending neither.\");\n }\n return NO_CALLER;\n }\n if (\"organizationId\" in result) {\n warn(\"flat-organization-id\", \"got principalId and organizationId side by side; put the company in `organization`.\");\n }\n const nested = (result as { organization?: unknown }).organization;\n return {\n principal: identityFor(result, \"principal\", warn),\n organization: nested == null ? null : identityFor(nested, \"organization\", warn),\n labels: labelsOf([result, nested], warn),\n };\n}\n\nfunction labelsOf(sources: unknown[], warn: CallerWarning): string[] {\n const labels: unknown[] = [];\n for (const source of sources) {\n try {\n const given = (source as { labels?: unknown } | null | undefined)?.labels;\n if (typeof given === \"string\" || typeof (given as Iterable<unknown> | null | undefined)?.[Symbol.iterator] !== \"function\") {\n continue;\n }\n let read = 0;\n for (const label of given as Iterable<unknown>) {\n labels.push(label);\n if (++read === LABELS_READ_MAX) break;\n }\n } catch {\n warn(\"labels\", \"labels could not be read — sending the ones read before the failure.\");\n }\n }\n return cleanLabels(labels);\n}\n\nfunction identityFor(\n value: unknown,\n member: \"principal\" | \"organization\",\n warn: CallerWarning,\n): PrincipalWire | null {\n const idKey = member === \"principal\" ? \"principalId\" : \"organizationId\";\n const identity = readIdentity(value, idKey);\n if (identity === null) {\n warn(`${member}:id`, `${member} has no usable ${idKey} — sending no ${member}.`);\n return null;\n }\n return identityWire(identity.id, identity.form, identity.displayName, (form) =>\n warn(`${member}:form`, `${member} form ${describeForm(form)} is not registered — sending \"raw\".`),\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\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 one. */\nfunction identityWire(\n id: string,\n stated: unknown,\n displayName: unknown,\n onUnregisteredForm?: (form: unknown) => void,\n): PrincipalWire {\n let form: PrincipalForm = PRINCIPAL_FORM_RAW;\n if (stated !== undefined) {\n if (PRINCIPAL_FORMS.has(stated)) {\n form = stated 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?.(stated);\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(id, PRINCIPAL_ID_MAX_LEN),\n source: PRINCIPAL_SOURCE_ASSERTED,\n form,\n };\n const name = wireDisplayName(displayName);\n if (name !== null) wire.display_name = name;\n return wire;\n}\n","/** Capture settings read from the collector (SPEC §2.6): fetch, match, apply.\n * The TypeScript half of Python's `_capture_settings.py`. */\n\nimport * as crypto from \"node:crypto\";\nimport { isRecord } from \"../../_object.js\";\nimport { stripWhiteSpace } from \"../../_text.js\";\nimport type { CaptureObserved } from \"../../events.js\";\nimport { TIMED_OUT, raceDeadline } from \"../../deadline.js\";\nimport { globalFetch } from \"../../runtime.js\";\nimport { warn } from \"../../warn.js\";\nimport { RESULT_CAPTURE_MODES, type ResultCaptureMode } from \"./errorResult.js\";\nimport { type Overlay, overlayFor, readOverlays } from \"./overlays.js\";\nimport type { IntentParamMode } from \"./schemaCompat.js\";\n\nexport const SETTINGS_PATH = \"/v0/settings\";\nexport const TENANT_HEADER = \"X-Baton-Tenant-Id\";\nexport const SETTINGS_MODES = [\"local\", \"console\"] as const;\nexport type SettingsMode = (typeof SETTINGS_MODES)[number];\nexport const DEFAULT_SETTINGS_REFRESH_MS = 60_000;\nexport const MIN_SETTINGS_REFRESH_MS = 15_000;\nconst REQUEST_TIMEOUT_MS = 10_000;\n\nexport const CANDIDATE_ENV = \"BATON_CANDIDATE\";\nexport const CANDIDATE_HEADER = \"baton-candidate\";\nexport const CANDIDATES_HELD = 32;\nexport const CANDIDATE_READS_AT_ONCE = 4;\nexport const CANDIDATE_START_TIMEOUT_MS = 5_000;\n// The header is the caller's: it becomes a query value and a cache key.\nconst CANDIDATE_ID = /^[A-Za-z0-9_-]{1,128}$/;\nexport const TASK_ENV = \"BATON_TASK\";\nexport const TASK_HEADER = \"baton-task\";\nconst TASK_ID = /^[A-Za-z0-9_.:-]{1,128}$/;\n\nfunction matchingId(pattern: RegExp, value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n const id = stripWhiteSpace(value);\n return pattern.test(id) ? id : null;\n}\n\nfunction headerId(headers: Headers | null, name: string, parse: (value: unknown) => string | null): string | null {\n try {\n return parse(headers?.get(name));\n } catch {\n return null;\n }\n}\n\n/** `value` as a change id, stripped, or `null` when it cannot be one. */\nexport function candidateId(value: unknown): string | null {\n return matchingId(CANDIDATE_ID, value);\n}\n\n/** The `Baton-Candidate` header's change id. Never throws. */\nexport function headerCandidate(headers: Headers | null): string | null {\n return headerId(headers, CANDIDATE_HEADER, candidateId);\n}\n\n/** `value` as a test run's task id, stripped, or `null` when it cannot be one. */\nexport function taskId(value: unknown): string | null {\n return matchingId(TASK_ID, value);\n}\n\n/** The `Baton-Task` header's task id. Never throws. */\nexport function headerTask(headers: Headers | null): string | null {\n return headerId(headers, TASK_HEADER, taskId);\n}\n\n/** `BATON_TASK`; a value that cannot be a task id is dropped. */\nexport function envTask(): string | null {\n return taskId(typeof process !== \"undefined\" ? process.env?.[TASK_ENV] : undefined);\n}\n\n/** `BATON_CANDIDATE`, or `null` when unset. A value that cannot be an id is reported. */\nexport function envCandidate(): string | null {\n const value = typeof process !== \"undefined\" ? process.env?.[CANDIDATE_ENV] : undefined;\n if (!value) return null;\n const id = candidateId(value);\n if (id === null) warn(`baton: ${CANDIDATE_ENV} is not a change id; today's settings apply.`);\n return id;\n}\n\n/** `BATON_CANDIDATE` is read only with Console settings; said loudly, since a\n * test run would otherwise measure today's text. */\nexport function candidateNeedsConsole(settings: SettingsMode | undefined): void {\n if (settings !== \"console\" && envCandidate() !== null) {\n warn(\n `baton: ${CANDIDATE_ENV} is set, but this server's settings are not \"console\", ` +\n \"so the change is not fetched; today's settings apply.\",\n );\n }\n}\n\nexport type ReportMode = \"on\" | \"off\";\nconst MATCH_KEYS: ReadonlySet<string> = new Set([\"label\", \"client\", \"share\"]);\n// Shared with the config check, so a mode the config takes is one a document can set.\nexport const INTENT_PARAM_MODES: ReadonlySet<string> = new Set([\"optional\", \"required\"]);\nexport const REPORT_MODES: ReadonlySet<string> = new Set([\"on\", \"off\"]);\n// Derived from the registry, so no mode is accepted that the emitter has no payload shape for.\nexport const RESULT_CAPTURE_MODE_SET: ReadonlySet<string> = new Set(RESULT_CAPTURE_MODES);\n\n/** What a `match` rule can see about one request. */\nexport interface Caller {\n labels: readonly string[];\n clientName: string | null;\n shareKey: string | null;\n /** From the request's headers: `candidate` selects a document, never an\n * audience; `task` only tags the events served under it. */\n candidate?: string | null;\n task?: string | null;\n}\n\n/** The settings one call runs under. An unset mode means the config's value. */\nexport interface CallSettings {\n capture: CaptureObserved;\n resultCaptureMode?: ResultCaptureMode;\n intentParamMode?: IntentParamMode;\n reportMode?: ReportMode;\n overlay?: Overlay;\n}\n\nexport function shareBucket(vendorId: string, key: string): number {\n const digest = crypto.createHash(\"sha256\").update(`${vendorId}\\n${key}`, \"utf-8\").digest();\n return Number(digest.readBigUInt64BE(0) % 10000n);\n}\n\n/** One audience, its `match` checked once when the document is read. */\ninterface Audience {\n settings: CallSettings;\n labels: ReadonlySet<string> | null;\n clients: ReadonlySet<string> | null;\n shareThreshold: number | null;\n}\n\nfunction matchesEveryone(audience: Audience): boolean {\n return audience.labels === null && audience.clients === null && audience.shareThreshold === null;\n}\n\nfunction matches(audience: Audience, caller: Caller, bucket: number | null): boolean {\n if (audience.labels !== null && !caller.labels.some((label) => audience.labels!.has(label))) return false;\n if (audience.clients !== null && (caller.clientName === null || !audience.clients.has(caller.clientName))) {\n return false;\n }\n if (audience.shareThreshold !== null && (bucket === null || bucket >= audience.shareThreshold)) return false;\n return true;\n}\n\nexport class SettingsDocument {\n private readonly usesShare: boolean;\n private readonly unmatched: CallSettings;\n /** Whether some caller can get reports, so the instructions point to the\n * tool. Read only where the code's value is \"on\": no tool exists otherwise. */\n readonly reportsOnForAnyone: boolean;\n /** The tools some audience's overlay hides. */\n readonly hiddenSomewhere: ReadonlySet<string>;\n /** The pieces of Baton's text some audience's overlay changes. */\n readonly audiencePieces: ReadonlySet<string>;\n\n constructor(\n readonly version: number,\n private readonly audiences: readonly Audience[],\n readonly serverOverlay?: Overlay,\n candidate?: string,\n ) {\n const overlays = audiences.flatMap((a) => (a.settings.overlay === undefined ? [] : [a.settings.overlay]));\n this.hiddenSomewhere = new Set(overlays.flatMap((o) => [...o.hiddenTools]));\n this.audiencePieces = new Set(overlays.flatMap((o) => o.actions.flatMap((a) => (a.piece === undefined ? [] : [a.piece]))));\n this.usesShare = audiences.some((a) => a.shareThreshold !== null);\n this.unmatched = { capture: { settings_version: version, ...(candidate === undefined ? {} : { candidate }) } };\n // With no catch-all audience, a caller can fall through to the code's value.\n this.reportsOnForAnyone =\n audiences.some((a) => a.settings.reportMode !== \"off\") || !audiences.some(matchesEveryone);\n }\n\n settingsFor(caller: Caller, vendorId: string): CallSettings {\n const bucket = caller.shareKey !== null && this.usesShare ? shareBucket(vendorId, caller.shareKey) : null;\n return this.audiences.find((audience) => matches(audience, caller, bucket))?.settings ?? this.unmatched;\n }\n\n}\n\nfunction stringSet(value: unknown): ReadonlySet<string> | null {\n if (!Array.isArray(value) || !value.every((v) => typeof v === \"string\")) return null;\n return new Set(value);\n}\n\n/** `null` for an audience that can match nobody (SPEC §2.6). */\nfunction readAudience(\n version: number,\n id: string,\n match: Record<string, unknown>,\n capture: Record<string, unknown>,\n overlay: Overlay | undefined,\n candidate: string | undefined,\n): Audience | null {\n if (!Object.keys(match).every((key) => MATCH_KEYS.has(key))) return null;\n let labels: ReadonlySet<string> | null = null;\n let clients: ReadonlySet<string> | null = null;\n let shareThreshold: number | null = null;\n if (Object.hasOwn(match, \"label\") && (labels = stringSet(match.label)) === null) return null;\n if (Object.hasOwn(match, \"client\") && (clients = stringSet(match.client)) === null) return null;\n if (Object.hasOwn(match, \"share\")) {\n const share = match.share;\n if (typeof share !== \"number\" || !(share > 0 && share <= 1)) return null;\n // SPEC §2.6's formula, pinned by \"a half rounds up\".\n shareThreshold = Math.floor(share * 10000 + 0.5);\n }\n const settings: CallSettings = {\n capture: {\n settings_version: version,\n audience: id,\n ...(overlay === undefined ? {} : { overlay: overlay.id }),\n ...(candidate === undefined ? {} : { candidate }),\n },\n };\n if (overlay !== undefined) settings.overlay = overlay;\n const { results, goal, reports } = capture;\n if (typeof results === \"string\" && RESULT_CAPTURE_MODE_SET.has(results)) {\n settings.resultCaptureMode = results as ResultCaptureMode;\n }\n if (typeof goal === \"string\" && INTENT_PARAM_MODES.has(goal)) settings.intentParamMode = goal as IntentParamMode;\n if (typeof reports === \"string\" && REPORT_MODES.has(reports)) settings.reportMode = reports as ReportMode;\n return { settings, labels, clients, shareThreshold };\n}\n\n/** The document in `body`, or `null` when it is not a valid one (SPEC §2.6).\n * With `candidate`, valid only when it names that change. */\nexport function parseDocument(body: string, candidate?: string): SettingsDocument | null {\n let data: unknown;\n try {\n data = JSON.parse(body);\n } catch {\n return null;\n }\n if (!isRecord(data)) return null;\n const { version, audiences } = data;\n if (typeof version !== \"number\" || !Number.isInteger(version) || version < 1) return null;\n if (!Array.isArray(audiences) || audiences.length === 0) return null;\n if (candidate !== undefined && data.candidate !== candidate) return null;\n const overlays = readOverlays(data.overlays);\n const parsed: Audience[] = [];\n for (const audience of audiences) {\n if (!isRecord(audience)) return null;\n const { id, match, capture } = audience;\n if (typeof id !== \"string\" || !isRecord(match) || !isRecord(capture)) return null;\n const overlay = overlayFor(overlays, audience.overlay, \"audience\");\n const readable = readAudience(version, id, match, capture, overlay, candidate);\n if (readable !== null) parsed.push(readable);\n }\n return new SettingsDocument(version, parsed, overlayFor(overlays, data.server_overlay, \"server\"), candidate);\n}\n\n/** Where `CaptureSettings` gets its document: the fetcher, or a test's stand-in. */\nexport interface SettingsSource {\n readonly document: SettingsDocument | null;\n start(): void;\n stop(): void;\n /** One read of change `candidate`. Never rejects. */\n fetchCandidate(candidate: string, timeoutMs: number): Promise<CandidateRead>;\n}\n\nexport type CandidateRead =\n | { outcome: \"loaded\"; document: SettingsDocument }\n | { outcome: \"refused\" | \"unknown\" | \"failed\" };\n\nexport interface SettingsFetcherOptions {\n origin: string;\n apiKey: string;\n tenantId: string;\n vendorId: string;\n refreshMs: number;\n /** Injectable for tests; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n}\n\n/** Reads the document in the background and holds the last good one. A call\n * never waits on it. */\nexport class SettingsFetcher implements SettingsSource {\n private readonly url: string;\n // `#`, not `private`, so logging a config shows no key: \"logging the config shows no key\".\n readonly #headers: Record<string, string>;\n private readonly refreshMs: number;\n private readonly fetchImpl: typeof fetch;\n private etag: string | null = null;\n private held: SettingsDocument | null = null;\n private timer: ReturnType<typeof setInterval> | null = null;\n private reading: AbortController | null = null;\n private readonly candidateReads = new Set<AbortController>();\n private warned = false;\n\n constructor(options: SettingsFetcherOptions) {\n this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;\n this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };\n this.refreshMs = options.refreshMs;\n this.fetchImpl = options.fetchImpl ?? globalFetch;\n }\n\n get document(): SettingsDocument | null {\n return this.held;\n }\n\n start(): void {\n if (this.timer !== null) return;\n this.timer = setInterval(() => void this.readOnce(), this.refreshMs);\n // The read must not keep a vendor's process alive.\n (this.timer as { unref?: () => void }).unref?.();\n void this.readOnce();\n }\n\n stop(): void {\n if (this.timer !== null) clearInterval(this.timer);\n this.timer = null;\n this.reading?.abort();\n this.reading = null;\n for (const read of this.candidateReads) read.abort();\n }\n\n async fetchCandidate(candidate: string, timeoutMs: number): Promise<CandidateRead> {\n const reading = new AbortController();\n const timeout = setTimeout(() => reading.abort(), timeoutMs);\n (timeout as { unref?: () => void }).unref?.();\n this.candidateReads.add(reading);\n try {\n const url = `${this.url}&${new URLSearchParams({ candidate }).toString()}`;\n const response = await this.fetchImpl(url, {\n method: \"GET\",\n headers: this.#headers,\n redirect: \"manual\",\n signal: reading.signal,\n });\n if (response.status !== 200) void response.body?.cancel().catch(() => undefined);\n if (response.status === 403) return { outcome: \"refused\" };\n if (response.status === 404) return { outcome: \"unknown\" };\n if (response.status === 200) {\n const document = parseDocument(await response.text(), candidate);\n if (document !== null) return { outcome: \"loaded\", document };\n }\n } catch {\n // A failed read is tried again later.\n } finally {\n clearTimeout(timeout);\n this.candidateReads.delete(reading);\n }\n return { outcome: \"failed\" };\n }\n\n /** One request. Never rejects: a failure keeps what is held. */\n async readOnce(): Promise<void> {\n if (this.reading !== null) return;\n const reading = new AbortController();\n this.reading = reading;\n const timeout = setTimeout(() => reading.abort(), REQUEST_TIMEOUT_MS);\n (timeout as { unref?: () => void }).unref?.();\n try {\n await this.read(reading.signal);\n } catch {\n // Kept quiet: the collector being down must not fill the vendor's logs.\n } finally {\n clearTimeout(timeout);\n if (this.reading === reading) this.reading = null;\n }\n }\n\n private async read(signal: AbortSignal): Promise<void> {\n const headers = this.etag === null ? this.#headers : { ...this.#headers, \"If-None-Match\": this.etag };\n const response = await this.fetchImpl(this.url, { method: \"GET\", headers, redirect: \"manual\", signal });\n if (response.status !== 200) {\n // An unread body holds its connection until GC.\n void response.body?.cancel().catch(() => undefined);\n }\n // An answer that lands after `stop()` is dropped.\n if (signal.aborted) return;\n if (response.status === 204) {\n this.held = null;\n this.etag = null;\n } else if (response.status === 200) {\n const document = parseDocument(await response.text());\n if (signal.aborted) return;\n if (document === null) {\n if (!this.warned) {\n this.warned = true;\n warn(\"baton: the collector sent capture settings this SDK cannot read\");\n }\n return;\n }\n this.held = document;\n this.etag = response.headers.get(\"etag\");\n }\n }\n}\n\nconst PENDING = Symbol(\"pending\");\n\n/** Per-call settings from the matched audience (SPEC §2.6), and the test\n * changes a test key may fetch by id: `BATON_CANDIDATE` for the process, the\n * `Baton-Candidate` header for one HTTP request, which wins. */\nexport class CaptureSettings {\n private processDocument: SettingsDocument | null = null;\n /** `BATON_CANDIDATE`'s read; requests wait for it. */\n ready: Promise<void> = Promise.resolve();\n isReady = true;\n // id -> its document, `null` for an unknown id, `PENDING`, or the time a failed read may be tried again.\n private readonly held = new Map<string, SettingsDocument | null | typeof PENDING | number>();\n // A 403 is about the key, so it answers every id for this process.\n private refused = false;\n private stopped = false;\n retryAfterMs = REQUEST_TIMEOUT_MS;\n\n constructor(\n private readonly vendorId: string,\n private readonly source: SettingsSource,\n private readonly candidate: string | null = null,\n private readonly task: string | null = null,\n private readonly startTimeoutMs = CANDIDATE_START_TIMEOUT_MS,\n ) {}\n\n start(): void {\n const candidate = this.candidate;\n if (candidate !== null && this.processDocument === null) {\n const cannotLoad = (why: string): void =>\n warn(`baton: ${CANDIDATE_ENV}=${candidate} could not be loaded (${why}); today's settings apply.`);\n const fetched = this.source.fetchCandidate(candidate, this.startTimeoutMs);\n this.isReady = false;\n // Bounded here too, so a fetch that ignores its signal cannot hold up requests.\n this.ready = raceDeadline(fetched, this.startTimeoutMs).then((read) => {\n this.isReady = true;\n if (this.stopped) return;\n if (read === TIMED_OUT) {\n cannotLoad(\"no answer\");\n // A late answer is never served, so a run sees one set of settings;\n // a 403 still says the key is the cause.\n void fetched.then((late) => {\n if (!this.stopped && late.outcome === \"refused\") this.record(candidate, late);\n });\n return;\n }\n this.record(candidate, read);\n if (read.outcome === \"loaded\") this.processDocument = read.document;\n else if (read.outcome !== \"refused\") cannotLoad(read.outcome === \"unknown\" ? \"unknown id\" : \"no answer\");\n });\n }\n this.source.start();\n }\n\n stop(): void {\n this.stopped = true;\n this.source.stop();\n }\n\n /** The document for a request with no header of its own. */\n get document(): SettingsDocument | null {\n return this.processDocument ?? this.source.document;\n }\n\n /** `undefined` while no document is held, and the config's values apply. */\n forCaller(caller: Caller): CallSettings | undefined {\n const document =\n caller.candidate == null ? this.document : (this.headerDocument(caller.candidate) ?? this.source.document);\n const settings = document?.settingsFor(caller, this.vendorId);\n const task = caller.candidate == null ? this.task : caller.task;\n if (settings === undefined || task == null || settings.capture.candidate === undefined) return settings;\n return { ...settings, capture: { ...settings.capture, task } };\n }\n\n /** Whether `test` holds for some document a request could be served under now. */\n someDocument(test: (document: SettingsDocument) => boolean): boolean {\n const today = this.document;\n if (today !== null && test(today)) return true;\n for (const held of this.held.values()) if (held instanceof SettingsDocument && test(held)) return true;\n return false;\n }\n\n /** The header's change if it is held. The first sight of an id starts its\n * read in the background, unless too many are already running. */\n private headerDocument(candidate: string): SettingsDocument | null {\n if (this.refused) return null;\n const held = this.held.get(candidate);\n if (held !== undefined && !(typeof held === \"number\" && held <= Date.now())) {\n this.held.delete(candidate);\n this.held.set(candidate, held);\n return held instanceof SettingsDocument ? held : null;\n }\n if ([...this.held.values()].filter((v) => v === PENDING).length >= CANDIDATE_READS_AT_ONCE) return null;\n this.held.delete(candidate);\n this.held.set(candidate, PENDING);\n this.evict();\n void this.source.fetchCandidate(candidate, REQUEST_TIMEOUT_MS).then((read) => {\n if (!this.stopped) this.record(candidate, read);\n });\n return null;\n }\n\n private record(candidate: string, read: CandidateRead): void {\n if (read.outcome === \"refused\") {\n if (!this.refused) {\n warn(\"baton: this server's key is not a test key, so test changes are not fetched; today's settings apply.\");\n }\n this.held.delete(candidate);\n this.refused = true;\n } else if (read.outcome === \"failed\") {\n this.held.set(candidate, Date.now() + this.retryAfterMs);\n } else {\n this.held.set(candidate, read.outcome === \"loaded\" ? read.document : null);\n this.evict();\n }\n }\n\n private evict(): void {\n // A read in flight is never dropped, so it cannot be started twice.\n for (const [key, value] of this.held) {\n if (this.held.size <= CANDIDATES_HELD) return;\n if (value !== PENDING) this.held.delete(key);\n }\n }\n}\n\n/** Whether some audience's overlay changes `piece` of Baton's text. */\nexport function overlayChanges(settings: CaptureSettings | undefined, piece: string): boolean {\n return settings?.someDocument((d) => d.audiencePieces.has(piece)) ?? false;\n}\n\n/** Whether some audience's overlay, today or in a held change, hides `name`. */\nexport function mayHide(settings: CaptureSettings | undefined, name: string): boolean {\n return settings?.someDocument((d) => d.hiddenSomewhere.has(name)) ?? false;\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\nimport { capCodePoints, stripWhiteSpace } from \"../../_text.js\";\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 \"tool_hidden\",\n \"invalid_argument\",\n \"output_schema_mismatch\",\n \"refused\",\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/** The handler never ran because code above it refused the call: a vendor's\n * wrapper on the `tools/call` handler, or an override of the SDK's\n * `executeToolHandler`. Its message is the vendor's, so `\"off\"` withholds it. */\nexport const REFUSED = \"refused\" satisfies FailureKind;\n\n/** What the SDK's own `validateToolInput` did with this call: never reached\n * (or replaced by something that skips the probe), accepted the arguments, or\n * rejected them. */\nexport type InputValidation = \"unseen\" | \"passed\" | \"rejected\";\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 * ⚠ **`invalid_argument` rests on positive evidence where the probe is\n * live**: `withBaton` wraps the SDK's `validateToolInput` and records a\n * rejection. `\"unseen\"` is the inference: the call stopped before validation,\n * which is a vendor's gate or one of 1.x's two task-mode checks, and\n * `TASK_MODES` keeps the second out of `refused`. A pre-validation rejection\n * either major adds later would be labelled `refused` with nothing going red.\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 `failure_kind` claim. */\n execution?: { taskSupport?: unknown } | null;\n}\n\nexport function requestSideFailureKind(\n entry: ToolEntryFacts | null | undefined,\n validation: InputValidation,\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 if (validation === \"rejected\") return \"invalid_argument\";\n if (TASK_MODES.has(entry.execution?.taskSupport)) return undefined;\n return REFUSED;\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 = stripWhiteSpace(text);\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/** The body members for a call that failed before the vendor's handler ran.\n * The SDK's own rejections are kept under `\"off\"`; a refusal is the vendor's\n * code speaking, so it is withheld like a tool's own failure.\n *\n * ⚠ PRECONDITION: call this ONLY from inside an `emit()` build thunk, as its\n * siblings above. */\nexport function requestSideFailureFields(\n kind: FailureKind | undefined,\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 return kind === REFUSED\n ? resultDerivedFields(mode, text, result ?? null, errorBody, scrubber)\n : requestSideErrorFields(text(), errorBody);\n}\n\n/** `error_type` for a thrown value: its class name, or `\"Error\"` for a non-Error. */\nexport function 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. */\nexport function messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Scrub the whole text, then cut it: cutting first could split a secret so\n * no pattern matches the half that ships. Call only inside an emit() build\n * thunk, where a scrubber throw drops the event. */\nexport function scrubbedErrorBody(scrubber: (value: unknown) => unknown, text: string): string {\n // eslint-disable-next-line no-restricted-syntax -- callers are emit() build thunks\n return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);\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 }` — it keeps `sessionId`\n * but moves the request `_meta` down under `mcpReq`. Read only at the 1.x\n * location and every v2 event silently loses its `runtime_meta`: no error,\n * just worse data. Use {@link extraMeta}, never `extra._meta`.\n *\n * The SECOND divergence, same shape: 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 * silently loses `client_observed.info` 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?:\n | { _meta?: unknown; envelope?: unknown; inputResponses?: unknown; requestState?: () => unknown }\n | 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 `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\nexport function isThenable(value: unknown): value is PromiseLike<unknown> {\n return typeof (value as { then?: unknown } | null | undefined)?.then === \"function\";\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 CallerWire,\n type Organization,\n type Principal,\n NO_CALLER,\n callerFor,\n wireLabels,\n} from \"../../identity.js\";\nimport type { ClientObserved } from \"./clientObserved.js\";\nimport { raceDeadline, TIMED_OUT } from \"../../deadline.js\";\nimport { warn } from \"../../warn.js\";\nimport { type CallSettings, type CaptureSettings, headerCandidate, headerTask } from \"./captureSettings.js\";\nimport {\n type AuthInfo,\n type Extra,\n extraAuthInfo,\n extraHeaders,\n extraMeta,\n isThenable,\n} 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.\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. `null` on a\n * request that is not a tool call. */\n toolName: string | null;\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. Empty on a\n * request that is not a tool call. */\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 | Organization | null | Promise<Principal | Organization | null>;\n\n/** Build the hook's input from whichever major's context arrived.\n *\n * ⚠ **ONE factory, called by every emit path.** Every request that resolves\n * a principal goes through here rather than each\n * assembling 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 | null,\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/** How long a vendor's hook may take, the same budget Python gives one. */\nexport const HOOK_TIMEOUT_MS = 5000;\n\nasync function withinHookBudget(answer: unknown): Promise<unknown> {\n if (!isThenable(answer)) return answer;\n const first = await raceDeadline(answer, HOOK_TIMEOUT_MS);\n if (first !== TIMED_OUT) return first;\n warn(\n `baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1000)}s; ` +\n \"this request is sent without a principal.\",\n );\n return null;\n}\n\n// The hook runs on every request, so each kind of problem is reported once.\nconst warned = new Set<string>();\n\nfunction warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n warn(`baton: resolvePrincipal ${message}`);\n}\n\n/** The caller as wire objects, and the capture settings it runs under. */\nexport interface ResolvedCaller extends CallerWire {\n /** `undefined` means the config's values. */\n settings?: CallSettings;\n}\n\n/** The envelope's `principal`, `organization`, `labels` and `capture`. */\nexport function callerEnvelope(caller: ResolvedCaller): Record<string, unknown> {\n return {\n principal: caller.principal,\n organization: caller.organization,\n labels: wireLabels(caller.labels),\n capture: caller.settings?.capture ?? null,\n };\n}\n\nlet settingsWarned = false;\n\n/** The envelope's `principal`, `organization` and labels for one request,\n * and with `settings` the capture settings it runs under (SPEC §2.6).\n *\n * ⚠ **Never throws.** A hook that raises, returns the wrong shape, or returns\n * `null` yields an anonymous request, not a failed one — `principal` and\n * `organization` are additive analytics, and a vendor's own bug in their\n * resolver may not fail their request (SPEC §11.2 fail-open). Settings that\n * fail to apply leave the config's values.\n *\n * A hook that has not answered within `HOOK_TIMEOUT_MS` is given up on, which\n * cannot bound one that blocks synchronously.\n */\nexport async function resolveCaller(\n hook: ResolvePrincipalHook | undefined,\n call: { extra: Extra; toolName: string | null; arguments: Record<string, unknown> },\n settings?: CaptureSettings,\n client: ClientObserved | null = null,\n): Promise<ResolvedCaller> {\n const caller = await resolveIdentity(hook, call);\n if (settings === undefined) return caller;\n try {\n const headers = extraHeaders(call.extra);\n const candidate = headerCandidate(headers);\n const callSettings = settings.forCaller({\n labels: caller.labels,\n clientName: client?.info?.name ?? null,\n shareKey: caller.principal?.id ?? null,\n candidate,\n task: candidate === null ? null : headerTask(headers),\n });\n return callSettings === undefined ? caller : { ...caller, settings: callSettings };\n } catch {\n if (!settingsWarned) {\n settingsWarned = true;\n warn(\"baton: applying capture settings failed; this request uses the config's values\");\n }\n return caller;\n }\n}\n\nasync function resolveIdentity(\n hook: ResolvePrincipalHook | undefined,\n call: { extra: Extra; toolName: string | null; arguments: Record<string, unknown> },\n): Promise<CallerWire> {\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 request.\n if (hook === undefined) return NO_CALLER;\n try {\n const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);\n const result: unknown = await withinHookBudget(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 return callerFor(result, warnOnce);\n } catch {\n // Broad on purpose: this calls code a VENDOR wrote, and an identity read\n // may not be able to fail a request. Nothing is logged to stdout — that\n // stream is the MCP JSON-RPC frame (AGENTS.md boundary rule 2).\n return NO_CALLER;\n }\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` into a vendor's EXISTING Zod object schema has to\n * build the injected field with a schema instance from the SAME zod major as\n * 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 { RETIRED_PARAM_NAMES, USER_GOAL_PARAM_NAME, buildUserGoalParamDescription, declaresParam } from \"./llmText.js\";\nimport { isRecord } from \"../../_object.js\";\n\nexport type IntentParamMode = \"optional\" | \"required\";\nexport const DEFAULT_INTENT_PARAM_MODE: IntentParamMode = \"required\";\n\n// A property beside a root `$ref` or combiner is not seen by the subschema's\n// `additionalProperties: false`, so a client validator would refuse the call.\nconst ROOT_COMBINERS = [\"$ref\", \"oneOf\", \"anyOf\", \"allOf\"] as const;\n\n/** Whether Baton may add `user_goal` to a tool's JSON Schema `inputSchema`. */\nexport function takesUserGoalJson(schema: Record<string, unknown>): boolean {\n // `undefined` counts as missing: JSON drops the key, so the agent would see none.\n const properties = schema.properties ?? {};\n return isRecord(properties) && !ROOT_COMBINERS.some((key) => key in schema);\n}\n\n/** `schema` with `user_goal` added as `injectGoalParams` adds it to a zod one.\n * A schema that declares its own, or that `takesUserGoalJson` refuses, is\n * returned as it is. */\nexport function withUserGoalJson(\n schema: Record<string, unknown>,\n intentParamMode: IntentParamMode,\n listRequired: boolean,\n): Record<string, unknown> {\n if (!takesUserGoalJson(schema) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return schema;\n const properties = (schema.properties ?? {}) as Record<string, unknown>;\n const goal = { type: \"string\", description: buildUserGoalParamDescription({ intentParamMode }) };\n const served: Record<string, unknown> = { ...schema, properties: { ...properties, [USER_GOAL_PARAM_NAME]: goal } };\n const required = Array.isArray(schema.required) ? (schema.required as unknown[]) : [];\n if (listRequired && !required.includes(USER_GOAL_PARAM_NAME)) served.required = [...required, USER_GOAL_PARAM_NAME];\n return served;\n}\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.\nexport const EMPTY_OBJECT_JSON_SCHEMA = { type: \"object\", properties: {} };\n\n/**\n * Splice `user_goal` into `inputSchema`'s 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 the description labels (\"REQUIRED.\" or\n * \"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, how `mode` labels them, or when a vendor's own field of the\n * 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 // A retired name the vendor declares is the vendor's, and is forwarded.\n for (const name of RETIRED_PARAM_NAMES) {\n if (name in existingShape) dispositions[name] = \"native\";\n }\n\n // Optional in the zod schema, in every mode: a required field would make the\n // vendor's server refuse a call that omits it. Zod cannot advertise required\n // without enforcing it, so `required` is advertised on the `tools/list`\n // response instead, by `advertiseIntentParamsRequired`.\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 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`, 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 description labels 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 * Applied to a rendered `tools/list` result: each of `names` that\n * `isInjected` says Baton added to a tool is appended to that tool's\n * `required` array. Serves `intentParamMode: \"required\"` and the annotate\n * tool's `tool_name`.\n *\n * Copy on write, so a caller that catches a throw from here can serve the\n * original. Only the response changes; the zod schema stays optional, which\n * is what keeps the names advertised and never enforced\n * (`intentAdvertise.test.ts`, \"serves a call with NEITHER name\").\n */\nexport function advertiseIntentParamsRequired(\n result: unknown,\n names: readonly string[],\n isInjected: (toolName: string, paramName: 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 const toolName = entry?.name;\n if (typeof toolName !== \"string\") 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 const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));\n if (missing.length === 0) return tool;\n changed = true;\n return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };\n });\n return changed ? { ...(result as Record<string, unknown>), tools: advertised } : result;\n}\n\n/** `result` with the tool `name` listing `inputSchema`. Copy on write. */\nexport function withToolInputSchema(result: unknown, name: string, inputSchema: Record<string, unknown>): unknown {\n const tools = (result as { tools?: unknown } | null | undefined)?.tools;\n if (!Array.isArray(tools)) return result;\n const at = tools.findIndex((tool) => isRecord(tool) && tool.name === name);\n if (at === -1) return result;\n const served: unknown[] = [...(tools as unknown[])];\n served[at] = { ...(tools[at] as Record<string, unknown>), inputSchema };\n return { ...(result as Record<string, unknown>), tools: served };\n}\n\n/** A v2 schema's draft 2020-12 rendering through its own Standard JSON Schema\n * converter, the one v2 lists tools with; `undefined` when it has none. */\nexport function standardInputJsonSchema(schema: unknown): Record<string, unknown> | undefined {\n try {\n const standard = (schema as { \"~standard\"?: { jsonSchema?: { input?: (o: unknown) => Record<string, unknown> } } })?.[\"~standard\"];\n return standard?.jsonSchema?.input?.({ target: \"draft-2020-12\" });\n } catch {\n return undefined;\n }\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","import {\n EXPECTED_RESULT_PARAM_NAME,\n OVERALL_TASK_PARAM_NAME,\n USER_GOAL_PARAM_NAME,\n} from \"./llmText.js\";\nimport { printable, stderrLine } from \"../../warn.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 | \"client_observed\"\n | \"_meta\"\n | typeof USER_GOAL_PARAM_NAME\n | typeof EXPECTED_RESULT_PARAM_NAME\n | typeof OVERALL_TASK_PARAM_NAME\n | \"params\"\n | \"intent\"\n | \"expected_outcome\"\n | \"workflow\"\n | \"context\";\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\": a `client_observed` value is left out, `_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: this fires several times per call, so\n // warning every time would print a stderr line on every tool call.\n if (!warned.has(field)) {\n warned.add(field);\n stderrLine(\n `baton: scrubber threw on ${field}; that field is dropped, tool call continues. ` +\n `Further failures on this field will be silent: ${printable(err)}`,\n );\n }\n return null;\n }\n}\n","/** The envelope's `client_observed` (SPEC §11.4): what the client said about\n * itself, sent uninterpreted. The consumer names the client; this SDK does\n * not, and sends `agent_runtime: \"unknown\"` on every event. */\n\nimport { capCodePoints } from \"../../_text.js\";\nimport { extraEnvelope, extraHeaders, extraMeta, type Extra } from \"./mcpTypes.js\";\nimport { scrubOrNull } from \"./safeScrub.js\";\n\n/** The per-request carrier for the client's declaration, reserved by MCP\n * 2026-07-28. Written out because the 1.x peer exports no such constant and\n * importing v2's would pin a major for a string. */\nexport const CLIENT_INFO_META_KEY = \"io.modelcontextprotocol/clientInfo\";\n\n// The only headers ever copied. A request also carries credentials, so this\n// is a list in the SDK and not a config option: `test/integrations/mcp/clientObserved.test.ts`,\n// \"never copies a header that is not registered\".\nconst OBSERVED_HEADERS = [\"user-agent\", \"x-anthropic-client\"] as const;\n\nconst CLIENT_INFO_MAX_LEN = 128;\nconst HEADER_VALUE_MAX_LEN = 256;\n\nexport interface ClientObserved {\n info?: { name?: string; version?: string };\n headers?: Partial<Record<(typeof OBSERVED_HEADERS)[number], string>>;\n}\n\n/** `scrubber` is required so a call site cannot send these values unscrubbed\n * by leaving it out. */\ninterface ObserveClientOptions {\n /** The MCP server object that was wrapped: it holds the handshake. */\n server?: unknown;\n scrubber: (value: unknown) => unknown;\n}\n\ninterface DeclaredClientInfo {\n name?: unknown;\n version?: unknown;\n}\n\nconst hasText = (value: unknown): value is string => typeof value === \"string\" && value !== \"\";\n\n/** The pair one source declared, or `undefined` when it holds no text at all,\n * so a malformed declaration on the request does not hide the handshake's. */\nfunction declared(info: unknown): DeclaredClientInfo | undefined {\n if (!info || typeof info !== \"object\") return undefined;\n const { name, version } = info as DeclaredClientInfo;\n return hasText(name) || hasText(version) ? { name, version } : undefined;\n}\n\n/** The request's own declaration. v2 lifts the reserved key out of `_meta`\n * into the envelope and 1.x leaves it in, so both are read. */\nfunction declaredOnRequest(extra: Extra): DeclaredClientInfo | undefined {\n for (const source of [extraEnvelope(extra), extraMeta(extra)]) {\n const found = declared(source?.[CLIENT_INFO_META_KEY]);\n if (found) return found;\n }\n return undefined;\n}\n\n/** The handshake's declaration, which neither peer puts on the handler's\n * context: both cache it on the server object. A server object reused for\n * a later connection reports the previous client until the new one\n * initializes. */\nfunction declaredOnConnection(server: unknown): DeclaredClientInfo | undefined {\n if (!server) return undefined;\n const inner = (server as { server?: unknown }).server;\n const holder = (inner ?? server) as {\n getClientVersion?: () => DeclaredClientInfo | undefined;\n };\n if (typeof holder.getClientVersion !== \"function\") return undefined;\n return declared(holder.getClientVersion());\n}\n\nfunction observedInfo(extra: Extra, options: ObserveClientOptions): ClientObserved[\"info\"] {\n // Both fields come from one source, so the pair is one the client sent.\n return cleanInfo(declaredOnRequest(extra) ?? declaredOnConnection(options.server), options.scrubber);\n}\n\nfunction cleanInfo(\n sent: DeclaredClientInfo | undefined,\n scrubber: ObserveClientOptions[\"scrubber\"],\n): ClientObserved[\"info\"] {\n const info: NonNullable<ClientObserved[\"info\"]> = {};\n const name = clean(sent?.name, scrubber, CLIENT_INFO_MAX_LEN);\n const version = clean(sent?.version, scrubber, CLIENT_INFO_MAX_LEN);\n if (name !== undefined) info.name = name;\n if (version !== undefined) info.version = version;\n return Object.keys(info).length > 0 ? info : undefined;\n}\n\nfunction cleanHeaders(\n sent: Headers | null | undefined,\n scrubber: ObserveClientOptions[\"scrubber\"],\n): ClientObserved[\"headers\"] {\n const headers: NonNullable<ClientObserved[\"headers\"]> = {};\n for (const header of OBSERVED_HEADERS) {\n const value = clean(sent?.get(header), scrubber, HEADER_VALUE_MAX_LEN);\n if (value !== undefined) headers[header] = value;\n }\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nfunction clean(\n value: unknown,\n scrubber: ObserveClientOptions[\"scrubber\"],\n max: number,\n): string | undefined {\n if (!hasText(value)) return undefined;\n const scrubbed = scrubOrNull<unknown>(scrubber, value, \"client_observed\");\n if (!hasText(scrubbed)) return undefined;\n return capCodePoints(scrubbed, max);\n}\n\n/** These read a third party's request and server objects, which may throw.\n * One failing read costs its own member, never the other or the call. */\nfunction orNothing<T>(read: () => T | undefined): T | undefined {\n try {\n return read();\n } catch {\n return undefined;\n }\n}\n\nfunction assemble(\n info: ClientObserved[\"info\"],\n headers: ClientObserved[\"headers\"],\n): ClientObserved | null {\n if (info === undefined && headers === undefined) return null;\n return { ...(info && { info }), ...(headers && { headers }) };\n}\n\n/** `null` when nothing was observed. */\nexport function observeClient(extra: Extra, options: ObserveClientOptions): ClientObserved | null {\n return assemble(\n orNothing(() => observedInfo(extra, options)),\n orNothing(() => cleanHeaders(extraHeaders(extra), options.scrubber)),\n );\n}\n\n/** Headers as a vendor's server framework holds them: a fetch `Headers`, or a\n * plain record such as Node's `req.headers`. */\nexport type HeaderInput = Headers | Record<string, string | readonly string[] | undefined>;\n\n/** Only the registered names are copied in, so a header the platform refuses\n * to hold cannot cost the ones we read. */\nfunction append(headers: Headers, name: string, value: string): void {\n try {\n headers.append(name, value);\n } catch {\n // A value Headers will not hold (a newline, a non-Latin-1 character) costs only itself.\n }\n}\n\nfunction registeredHeaders(input: HeaderInput): Headers {\n const out = new Headers();\n if (typeof (input as Headers).get === \"function\") {\n for (const name of OBSERVED_HEADERS) {\n const value: unknown = (input as Headers).get(name);\n if (typeof value === \"string\") append(out, name, value);\n }\n return out;\n }\n for (const [key, value] of Object.entries(input)) {\n const name = key.toLowerCase();\n if (!(OBSERVED_HEADERS as readonly string[]).includes(name)) continue;\n for (const line of typeof value === \"string\" ? [value] : Array.isArray(value) ? value : []) {\n if (typeof line === \"string\") append(out, name, line);\n }\n }\n return out;\n}\n\n/** The library path's `client_observed` (SPEC §5.6 rule 4): what the vendor's\n * code passed, under the same rules as what a client sends over MCP. A\n * declaration in the request's `_meta` wins over `clientInfo`, as the\n * request's own wins over the handshake's on MCP. */\nexport function clientObservedFrom(\n clientInfo: unknown,\n headers: HeaderInput | undefined,\n scrubber: ObserveClientOptions[\"scrubber\"],\n meta?: Record<string, unknown> | null,\n): ClientObserved | null {\n return assemble(\n orNothing(() => cleanInfo(declared(meta?.[CLIENT_INFO_META_KEY]) ?? declared(clientInfo), scrubber)),\n orNothing(() => (headers ? cleanHeaders(registeredHeaders(headers), scrubber) : undefined)),\n );\n}\n","import { stripWhiteSpace } from \"../../_text.js\";\nimport { uuid7 } from \"../../uuid7.js\";\nimport { extraHeaders, observeTransport, type Extra } from \"./mcpTypes.js\";\n\n/** A `session_id` with the envelope's `session_id_origin` (SPEC §11.4). The\n * rung that answered decides the origin, never the id's spelling. */\nexport interface ResolvedSession {\n sessionId: string;\n origin: \"observed\" | \"minted\";\n perCall: boolean;\n}\n\n/** SPEC §3.4 rungs 4 and 5. The header is read as well as `extra.sessionId`\n * because a stateless transport reports no id even when the client sends one.\n *\n * No vendor hook: an id the SDK did not mint must not key the session (the\n * join rule). What a vendor knows about a caller goes in `principal`. */\nexport async function resolveSessionId(\n fallbackSessionId: string,\n extra: Extra,\n): Promise<ResolvedSession> {\n if (typeof extra.sessionId === \"string\" && extra.sessionId) {\n return { sessionId: extra.sessionId, origin: \"observed\", perCall: false };\n }\n const fromHeader = sessionIdFromHeader(extra);\n if (fromHeader !== null) return { sessionId: fromHeader, origin: \"observed\", perCall: false };\n if (observeTransport(extra) === \"http\") {\n return { sessionId: `sdk-${uuid7()}`, origin: \"minted\", perCall: true };\n }\n return { sessionId: fallbackSessionId, origin: \"minted\", perCall: false };\n}\n\n/** Blank is a miss, as on the Python side: a whitespace-only id would file\n * every such call under one session. Never throws into the tool call. */\nfunction sessionIdFromHeader(extra: Extra): string | null {\n try {\n const value = extraHeaders(extra)?.get(\"mcp-session-id\");\n return value ? stripWhiteSpace(value) || null : null;\n } catch {\n return null;\n }\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 * ; \"baton_tk_\" (a test key) does not warn\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/batch` 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\nimport { stripWhiteSpace } from \"./_text.js\";\nimport { warn } from \"./warn.js\";\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// NUL, LF and CR are what `new Headers` refuses, so a key holding one could\n// never be sent. The tab can be sent, but is refused because `baton` refuses\n// it anywhere in a DSN: a tab inside a key is a line wrap from copying, not\n// part of any minted key. Narrow on purpose otherwise: the tail's alphabet\n// belongs to the console's mint, and a parser stricter than the mint refuses\n// valid keys in the field.\n// eslint-disable-next-line no-control-regex\nconst NOT_IN_A_KEY = /[\\x00\\t\\n\\r]/;\n\nconst PUBLISHABLE_PREFIX = \"baton_pk_\";\nconst SECRET_PREFIX = \"baton_sk_\";\nconst TEST_PREFIX = \"baton_tk_\";\nconst KEY_PREFIXES = [PUBLISHABLE_PREFIX, SECRET_PREFIX, TEST_PREFIX];\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. An older key has no type letters, so\n * that branch needs a floor longer than any legal server name: a server called\n * `baton_<name>` must not read as a key.\n */\nconst KEY_RUN =\n /baton_(?:(?:pk|sk|tk)_[A-Za-z0-9_%-]{8,}|[A-Za-z0-9_%-]{43,})/g;\n\nfunction looksLikeAKey(value: string): boolean {\n return KEY_PREFIXES.some((prefix) => value.startsWith(prefix));\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 no key 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/** 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/batch` 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/batch` 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. */\nexport function 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 const dsn = typeof raw === \"string\" ? stripWhiteSpace(raw) : \"\";\n if (dsn === \"\") fail(\"dsn must be a non-empty string\");\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.\n fail(\n `dsn ${safe} has a tab, a line break or a null inside its key — no ` +\n `key from /account contains one, so this DSN could not have worked. ` +\n `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/batch` and hands the result to `fetch` as a HOSTNAME — which puts\n // the bearer in a DNS query and a TLS SNI field on every send, to every\n // resolver in path. The bearer also silently becomes the one-character\n // userinfo, so nothing downstream even authenticates.\n //\n // Checked BEFORE `NOT_IN_A_HOST`, as in Python: a key contains none of those\n // characters, so the order only matters for WHICH sentence a paste error\n // gets, and this one names the mistake.\n if (containsKey(authority)) {\n fail(\n `dsn ${safe} has the KEY where the host belongs. The order is key, ` +\n `@, host — check whether the two are the wrong way round: ` +\n `https://baton_pk_...@host/ten_.../<server>`,\n );\n }\n if (NOT_IN_A_HOST.test(authority)) {\n fail(\n `dsn ${safe} has whitespace, a control character or a backslash inside ` +\n `its host. Those are silently REMOVED or reinterpreted when a URL is ` +\n `parsed, so the address dialled would not be the one you wrote — ` +\n `check for a line wrap or a stray space where the value was copied.`,\n );\n }\n\n // ⚠ **`new URL` is the host validator, and it runs only AFTER the credential\n // is split off.** Node's `ERR_INVALID_URL` carries the string it was handed\n // on `error.input`, so validating the whole DSN would put the bearer into an\n // exception — the single thing this module exists to prevent. Handed the\n // authority alone, the worst that error can hold is a hostname.\n //\n // ⚠ **Nothing from the caught error crosses over — not the object, not\n // `{ cause }`, not its message.** `cause` is the TypeScript twin of Python's\n // `__context__` trap: it survives on the thrown error and is reachable by\n // anything that walks the chain — an error reporter, a structured logger,\n // vitest's own diff. Only the constructor NAME is carried, and it carries no\n // input.\n //\n // Python reaches this check earlier (its `urlsplit` runs before the key\n // checks above), so a string that is BOTH keyless and unparseable gets the\n // \"carries no key\" sentence here and \"not a parseable URL\" there. Both\n // refuse, neither leaks; the order is what the leak-safe placement costs.\n let hostReason: string | null = null;\n let parsedAuthority: URL | null = null;\n try {\n parsedAuthority = new URL(`${parts.scheme}://${authority}`);\n } catch (error) {\n hostReason = error instanceof Error ? error.constructor.name : \"Error\";\n }\n if (parsedAuthority === null) {\n fail(`dsn ${safe} is not a parseable URL (${hostReason ?? \"Error\"})`);\n }\n\n // ⚠ **An assertion on `parsedAuthority.pathname`/`search`/`hash` stood here\n // and has been DELETED.** It was the first answer to the backslash smuggle,\n // and `NOT_IN_A_HOST` above is the second and better one — so it became a\n // guard no input could reach, which mutation testing showed by reddening\n // nothing when removed. Two rules answering for one input is what the\n // character class exists to stop being; the parsed object is still used, as\n // the validator that a host is a host at all.\n\n // ⚠ **A BACKSLASH smuggles a path into the authority, and the validator said\n // yes.** WHATWG folds `\\` to `/` for special schemes, so\n // `new URL(\"https://ingest.example.com\\evil\")` parses happily with host\n // `ingest.example.com` and path `/evil` — while the split above, which ends\n // the authority at `/`, `?` or `#`, keeps the whole thing as the authority.\n // The origin became `https://ingest.example.com\\evil`, `HttpSink` appended\n // `/v0/events`, and `fetch` resolved that to\n // `https://ingest.example.com/evil/v0/events`: a 404 at the first tool call,\n // in production, from an install that raised nothing — the exact failure the\n // \"loud at install\" promise exists to prevent.\n //\n // Asserted on what the URL parser MADE of the authority rather than by\n // adding `\\` to the terminator set, because the question is not which\n // characters WHATWG folds — it is whether anything but a host survived.\n const segments = parts.path.split(\"/\").filter((segment) => segment !== \"\");\n // Destructured with a rest element rather than length-checked, so the two\n // names narrow to `string` from the same test that refuses the wrong count.\n // `segments.length !== 2` would read more directly and `noUncheckedIndexedAccess`\n // cannot see through it — leaving a choice between an assertion that lies\n // the day someone edits the check, and an unreachable branch no test covers.\n const [workspace, server, ...extra] = segments;\n if (workspace === undefined || server === undefined || extra.length > 0) {\n fail(\n `dsn ${safe} must carry exactly two path segments — the workspace and ` +\n `the server, as in /ten_.../<server>. A missing server is never ` +\n `defaulted: it is what the key is bound to.`,\n );\n }\n\n for (const [slot, segment] of [\n [\"workspace\", workspace],\n [\"server\", server],\n ] as const) {\n if (containsKey(segment)) {\n // Checked BEFORE the pattern tests below, which would otherwise\n // interpolate the segment — and a key is far more useful to name by its\n // slot than to print back.\n fail(\n `dsn ${safe} has a KEY in the ${slot} slot. The key goes before the @, ` +\n `and the path carries the workspace and the server: ` +\n `https://baton_pk_...@host/ten_.../<server>`,\n );\n }\n }\n\n if (!WORKSPACE_PATTERN.test(workspace)) {\n fail(\n `dsn ${safe} has ${JSON.stringify(workspace)} where the workspace ` +\n `belongs — expected ten_ followed by 8 or 32 hex characters. If the two ` +\n `path segments are the right way round, this is not a Baton DSN.`,\n );\n }\n if (!VENDOR_ID_PATTERN.test(server)) {\n fail(\n `dsn ${safe} has ${JSON.stringify(server)} where the server belongs ` +\n `— it must match ${VENDOR_ID_PATTERN.source}, because this value becomes ` +\n `the annotation tool name prefix as well as the envelope's vendor_id.`,\n );\n }\n\n if (key.startsWith(SECRET_PREFIX)) {\n // A warning, never a refusal. The KEY ROW is the authority on what a key\n // may do, not its prefix — an SDK enforcing a console policy turns a typo\n // at the mint site into a confusing client-side error. But a secret key\n // inside a server that ships to strangers is worth saying out loud, and\n // this is the only place that can say it. The prefix only — the point is\n // not to repeat the secret.\n warn(\n `baton: this DSN carries a ${SECRET_PREFIX} key (a workspace SECRET) where ` +\n `a ${PUBLISHABLE_PREFIX} key belongs. It will work. But if this server ` +\n `ships to anyone else, that key reads and writes everything the ` +\n `workspace holds — mint a publishable key at /account instead.`,\n );\n }\n\n return sealKey({\n origin: `${parts.scheme}://${authority}`,\n tenantId: workspace,\n vendorId: server,\n key,\n });\n}\n\n/**\n * The parsed DSN, with its bearer kept out of anything that prints the object.\n *\n * `dsn.key` still reads the key — the sink needs it. What changes is the\n * INCIDENTAL paths: `console.log(dsn)`, `util.inspect`, and the\n * `JSON.stringify` inside every structured logger, each of which would\n * otherwise write a publishable key into a vendor's log the moment anyone\n * debugs their install. Python's copy takes the same precaution one field at a\n * time (`field(repr=False)`); a JS object has no repr, so the two hooks that\n * stand in for one are both defined.\n *\n * Both are non-enumerable, so `{...dsn}` and `Object.keys` are unchanged — a\n * spread that silently dropped the bearer would be a far worse trap than the\n * one being closed.\n */\nfunction sealKey(dsn: Dsn): Dsn {\n const shown = {\n origin: dsn.origin,\n tenantId: dsn.tenantId,\n vendorId: dsn.vendorId,\n key: \"<key>\",\n };\n Object.defineProperty(dsn, \"toJSON\", {\n value: () => shown,\n enumerable: false,\n });\n // `Symbol.for`, not an import of `node:util`: this package runs on edge and\n // worker runtimes too, and a registry symbol is inert where nothing reads it.\n Object.defineProperty(dsn, Symbol.for(\"nodejs.util.inspect.custom\"), {\n value: () => shown,\n enumerable: false,\n });\n return dsn;\n}\n","/**\n * `BatonConfig` — vendor-side configuration for `withBaton`. A trimmed\n * mirror of `baton` (Python)'s `integrations/_config.py::VendorConfig`.\n */\n\nimport { dsnFromEnvironment, 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 { MAX_TIMER_MS } from \"../../deadline.js\";\nimport { RESULT_CAPTURE_MODES, type ResultCaptureMode } from \"./errorResult.js\";\nimport { onWorkers } from \"../../runtime.js\";\nimport { HttpSink, type Sink } from \"../../sinks.js\";\nimport { warn } from \"../../warn.js\";\nimport {\n CaptureSettings,\n DEFAULT_SETTINGS_REFRESH_MS,\n INTENT_PARAM_MODES,\n MIN_SETTINGS_REFRESH_MS,\n REPORT_MODES,\n RESULT_CAPTURE_MODE_SET,\n SETTINGS_MODES,\n SettingsFetcher,\n envCandidate,\n envTask,\n type SettingsMode,\n} from \"./captureSettings.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\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. With no DSN, `tenantId` or sink\n * either, the install adds nothing instead (SPEC §11.2 rule 10). */\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 * under `reportMode: \"on\"`, and unused otherwise. */\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 to `\"customer-consented\"`, so the customer never has to carry\n * it.** The field stays on the wire: SPEC §2.3 governs the envelope, not the\n * config.\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. With a `vendorId` and no DSN, defaults to `new StdoutSink()`. */\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. Has no effect unless\n * `reportMode: \"on\"`, and warns if set without it. */\n annotationToolName?: string;\n /** Whether the agent is given a tool to report a call that went wrong.\n * Unset, it is `\"on\"` with `settings: \"console\"` and `\"off\"` otherwise.\n * `\"off\"` registers no annotation tool, and Baton's server\n * instructions are `INTENT_INSTRUCTIONS` alone, below your own. Each call's\n * goal still arrives through `user_goal`. `\"on\"` registers the tool and\n * serves its instructions. */\n reportMode?: \"on\" | \"off\";\n /** Where capture settings come from. `\"local\"` (default): the values in\n * this config, and Baton is never asked. `\"console\"`: the settings saved on\n * the Console's Capture page, read from the collector every\n * `settingsRefreshMs`, so they can differ by label, client or a share of\n * callers (SPEC §2.6). Needs a `dsn`. Until the first read succeeds, and\n * whenever nothing is saved, this config's values apply. A read never\n * delays startup or a call.\n *\n * `results` (`resultCaptureMode`) is applied per call. `goal`\n * (`intentParamMode`) and `reports` (`reportMode`) are applied per\n * `tools/list`. With `reportMode: \"off\"` no annotation tool is registered,\n * so the Console can hide reports from some callers only when they are on\n * here. */\n settings?: SettingsMode;\n /** How often `settings: \"console\"` reads the saved settings, in\n * milliseconds. Default 60000, at least 15000. */\n settingsRefreshMs?: number;\n /** Per-tool intent-param injection (mirrors baton-extmcp's vendor-neutral\n * naming). `\"required\"` (default) injects a `user_goal` string param on\n * every wrapped tool's advertised schema and ADVERTISES it as required in\n * `tools/list`, without enforcing it: a call that omits it still reaches\n * your handler, and its event simply carries no intent. `\"optional\"` injects\n * the same param and does not advertise it as required. There is no\n * `\"off\"`: nothing else would capture what the user is trying to do. The param is stripped before the vendor\n * handler runs, so the tool never sees it.\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\";\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 withheld too (SPEC\n * §11.4.3): the MCP SDK has no tool-error class to mark one public.\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, on the annotation tool, on every\n * `tools/list` request and on every resource and prompt request, with an\n * adapter-neutral\n * {@link PrincipalResolutionContext}: headers folded to ONE case-insensitive\n * shape across both SDK majors, the request's `_meta`, the tool name, and\n * the arguments the vendor's own handler will see. On a request that is not\n * a tool call the tool name is `null` and the arguments are empty. Return a `Principal`,\n * 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 request: a hook that throws or returns junk yields an\n * anonymous one. A hook that has not answered after 5 seconds is given up\n * on, and that request is anonymous. ⚠ That only bounds an async hook: one that\n * blocks synchronously holds the whole process, and nothing can interrupt it.\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 /** A low-level `Server`'s tools, as its `tools/list` answers them, or a\n * function that returns them. Read once per `withBaton` or `createBaton`.\n * Without it Baton learns the tools from the lists its servers serve, so a\n * process that has served none yet, such as a fresh worker, takes\n * `user_goal` off every call, even from a tool that declares its own. An\n * `McpServer` does not read it. */\n tools?: readonly unknown[] | (() => readonly unknown[]);\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 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\nconst STAND_IN_VENDOR_ID = \"unset\";\n\n/**\n * `resolveBatonConfig` for an install, and whether nothing says where events\n * go: no DSN, no `vendorId`, no `tenantId` and no sink (SPEC §11.2 rule 10).\n * `BATON_TENANT_ID` does not count, so a stale one cannot stop a server. Then\n * the config gets a stand-in identity, so every check still runs.\n */\nexport function resolveInstallConfig(config: BatonConfig): {\n resolved: ResolvedBatonConfig;\n unconfigured: boolean;\n} {\n const unconfigured =\n !config.dsn &&\n dsnFromEnvironment() === undefined &&\n !config.vendorId &&\n !config.tenantId &&\n config.sink === undefined;\n const resolved = resolveBatonConfig(\n unconfigured\n ? {\n ...config,\n vendorId: STAND_IN_VENDOR_ID,\n vendorDisplayName: config.vendorDisplayName ?? STAND_IN_VENDOR_ID,\n }\n : config,\n );\n return { resolved, unconfigured };\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 consentToken: string;\n /** Not yet reading; set only under `settings: \"console\"`. */\n captureSettings?: CaptureSettings;\n}\n\nlet consoleOffWarned = false;\n\n/** A Worker cannot keep reading the settings in the background, so there\n * `settings: \"console\"` is dropped and this config's capture values apply.\n * The report tool it turns on stays on. */\nfunction withoutConsoleOnWorkers(config: BatonConfig): BatonConfig {\n if (config.settings !== \"console\" || !onWorkers()) return config;\n if (!consoleOffWarned) {\n consoleOffWarned = true;\n warn('baton: settings: \"console\" is not supported on Cloudflare Workers yet; the Console\\'s settings are not read and this config\\'s capture values apply.');\n }\n const rest: BatonConfig = { ...config, reportMode: config.reportMode ?? \"on\" };\n delete rest.settings;\n return rest;\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 the settings read under `settings: \"console\"`, 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 * Knows nothing about the server being wrapped. The one field that depends on\n * it, the display name, is finished by `withServerDisplayName`.\n */\nexport function resolveBatonConfig(supplied: BatonConfig): ResolvedBatonConfig {\n const dsnString = selectDsn(\n supplied.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(supplied.vendorId),\n tenantId: supplied.tenantId !== undefined,\n sink: supplied.sink !== undefined,\n },\n \"BatonConfig\",\n );\n // Without a dsn, `settings: \"console\"` is refused below, on Workers too.\n const config = dsnString === undefined ? supplied : withoutConsoleOnWorkers(supplied);\n\n if (dsnString === undefined) {\n const defaulted: BatonConfig = {\n ...config,\n consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN,\n };\n validateBatonConfig(defaulted);\n if (defaulted.settings === \"console\") {\n throw new Error(\n 'BatonConfig.settings: \"console\" reads the Capture page with the dsn\\'s key, so it needs a dsn.',\n );\n }\n return defaulted;\n }\n\n const dsn = parseDsn(dsnString);\n // The packed string is DELETED rather than overwritten with `undefined`:\n // `exactOptionalPropertyTypes` refuses the latter, and dropping the property\n // is what is wanted anyway — see the note above about not keeping the\n // bearer on an object that outlives this call.\n const rest: BatonConfig = { ...config };\n delete rest.dsn;\n const identity: BatonConfig = {\n ...rest,\n vendorId: dsn.vendorId,\n tenantId: dsn.tenantId,\n // `??`, for the same reason as `consentToken` directly below, and the\n // inconsistency was worth fixing rather than mirroring: with no dsn,\n // `vendorDisplayName: \"\"` is REFUSED by validation; with one, `||` quietly\n // substituted the server slug. One input, two answers, decided by whether\n // a dsn happens to be present — and this string reaches the calling agent\n // in the server instructions and the annotation tool description, which is\n // the whitelabel obligation the validator cites when it refuses the empty\n // one. ⚠ Python uses `or` here and still has the inconsistency.\n vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,\n // `??`, not `||`: an explicit empty string must survive to the validation\n // below and be REFUSED there, rather than be quietly replaced by the\n // default it was deliberately not left as.\n consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN,\n ...(config.reportMode === undefined && config.settings === \"console\" ? { reportMode: \"on\" as const } : {}),\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 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/batch`\n // itself, exactly as it does for an explicitly-constructed sink.\n sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),\n ...(identity.settings === \"console\"\n ? {\n captureSettings: new CaptureSettings(\n dsn.vendorId,\n new SettingsFetcher({\n origin: dsn.origin,\n apiKey: dsn.key,\n tenantId: dsn.tenantId,\n vendorId: dsn.vendorId,\n refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS,\n }),\n envCandidate(),\n envTask(),\n ),\n }\n : {}),\n };\n}\n\n/** Between an explicit display name and the DSN's server segment sits the\n * server's own name: the segment is an opaque `srv-<8 hex>`, and it was what\n * agents were told the vendor is called. `serverName` is already through\n * `usableServerName`, so `undefined` when there is none to use. */\nexport function withServerDisplayName(\n resolved: ResolvedBatonConfig,\n supplied: BatonConfig,\n serverName: string | undefined,\n): ResolvedBatonConfig {\n if (supplied.vendorDisplayName !== undefined) return resolved;\n const fromServer = displayNameFromServer(serverName, {\n vendorId: resolved.vendorId,\n annotationToolName: supplied.annotationToolName,\n });\n return fromServer === undefined ? resolved : { ...resolved, vendorDisplayName: fromServer };\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.reportMode !== undefined && !REPORT_MODES.has(config.reportMode)) {\n throw new Error(\n `BatonConfig.reportMode ${JSON.stringify(config.reportMode)} must be one of ` +\n `${JSON.stringify([...REPORT_MODES].sort())}.`,\n );\n }\n if (!config.vendorDisplayName && config.reportMode === \"on\") {\n throw new Error(\n \"BatonConfig needs a vendorDisplayName with reportMode: \\\"on\\\" — used in server \" +\n \"instructions 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 as string | undefined) === \"off\") {\n throw new Error(\n 'BatonConfig.intentParamMode: \"off\" would leave nothing capturing what the user is ' +\n 'trying to do. Use \"required\" (the default) or \"optional\".',\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.settings !== undefined && !(SETTINGS_MODES as readonly string[]).includes(config.settings)) {\n throw new Error(\n `BatonConfig.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`,\n );\n }\n const refresh: unknown = config.settingsRefreshMs;\n if (\n refresh !== undefined &&\n (typeof refresh !== \"number\" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))\n ) {\n throw new Error(\n `BatonConfig.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} ` +\n `to ${String(MAX_TIMER_MS)}.`,\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 (config.tools !== undefined && !Array.isArray(config.tools) && typeof config.tools !== \"function\") {\n throw new Error(\"BatonConfig.tools must be an array of tools or a function that returns one.\");\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 and remains unbuilt, so no\n * vendor-facing wording may imply otherwise.\n */\n\nimport { stripWhiteSpace } from \"./_text.js\";\nimport type { Sink } from \"./sinks.js\";\nimport { warn } from \"./warn.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(stripWhiteSpace(value).toLowerCase())) {\n return SWITCH;\n }\n return null;\n}\n\n/**\n * Say so once, on stderr, never on stdout.\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 warn(\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/** SPEC §11.2 rule 10. */\nexport function logUnconfigured(surface: string): void {\n warn(`baton: no DSN (dsn or BATON_DSN), so ${surface} installed nothing and records nothing`);\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","// Multi-round-trip requests (protocol revision 2026-07-28): a paused round sends\n// no terminal event and a resumed round no start, so the rounds are one call.\n\nimport { isRecord } from \"../../_object.js\";\nimport type { Extra } from \"./mcpTypes.js\";\n\n/** Guarded like `isErrorResult`: it reads the vendor's result on the call path. */\nexport function isInputRequired(result: unknown): boolean {\n try {\n return isRecord(result) && result.resultType === \"input_required\";\n } catch {\n return false;\n }\n}\n\n/** `requestState` is an accessor the SDK sets on every request, so its value\n * is read, not its presence. */\nexport function resumesPausedCall(extra: Extra | undefined): boolean {\n try {\n const req = extra?.mcpReq;\n if (req === undefined) return false;\n return req.inputResponses !== undefined || req.requestState?.() !== undefined;\n } catch {\n return false;\n }\n}\n","import { boundedSinkCall, 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 /** The sink the vendor passed, or the default one. */\n readonly sink: Sink;\n readonly #queue: Sink;\n readonly vendorId: string;\n /** The install's own session id: what stdio and in-memory calls, and the\n * surface snapshot, carry when no session id resolves. A call over HTTP\n * with no session to read gets a per-request id instead (SPEC §3.4 rung 5). */\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 /** What Baton writes to, in front of `sink`. */\n queue?: Sink;\n vendorId: string;\n sessionId: string;\n annotationToolName: string;\n }) {\n this.sink = options.sink;\n this.#queue = options.queue ?? 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. Never rejects; returns within\n * the shutdown budget (SPEC §11.2 rule 7). */\n async flush(): Promise<void> {\n await boundedSinkCall(this.#queue, \"flush\");\n }\n\n /** Flush and release sink resources, on the same terms as `flush()`. */\n async aclose(): Promise<void> {\n await boundedSinkCall(this.#queue, \"aclose\");\n }\n}\n","/** The tool list and instructions under the Console's per-caller settings\n * (SPEC §2.6). The TypeScript half of Python's `_per_caller.py`. */\n\nimport { isRecord } from \"../../_object.js\";\nimport { stripWhiteSpaceEnd } from \"../../_text.js\";\nimport { printable, stderrLine } from \"../../warn.js\";\nimport type { CaptureSettings, SettingsDocument } from \"./captureSettings.js\";\nimport { INTENT_INSTRUCTIONS, USER_GOAL_PARAM_NAME, buildUserGoalParamDescription, declaresParam } from \"./llmText.js\";\nimport { type Action, type Overlay, changedText, overlaid, warnSkipped } from \"./overlays.js\";\nimport type { ResolvedCaller } from \"./principalResolution.js\";\nimport type { IntentParamMode } from \"./schemaCompat.js\";\n\nexport interface PerCallerOptions {\n settings: CaptureSettings;\n intentParamMode: IntentParamMode;\n /** `\"\"` under `reportMode: \"off\"`. */\n annotationToolName: string;\n /** The report pointer paragraph; `undefined` with no report tool. */\n pointer: () => string | undefined;\n /** `subagent` is the subagent sentence `ours` ends with, if it does. */\n writeInstructions: (ours: string, subagent: string | null) => void;\n /** False once a tool declares its own `user_goal`. */\n subagentLine: () => boolean;\n /** Whether this tool's `user_goal` is Baton's; a tool's own is left alone. */\n injectsGoal: (toolName: string) => boolean;\n}\n\nconst UNREAD = Symbol(\"unread\");\n\n/** Rewrites each `tools/list` result for its caller, and keeps the\n * instructions' report pointer while some audience has reports on, with the\n * server overlay applied. */\nexport class PerCallerSurface {\n private document: SettingsDocument | null | typeof UNREAD = UNREAD;\n private served: string | null = null;\n serverOverlay: Overlay | undefined;\n\n constructor(private readonly options: PerCallerOptions) {}\n\n /** Called at install and on every request; writes only when the report\n * pointer or the server overlay should change. */\n followSettings(): void {\n try {\n const document = this.options.settings.document;\n if (document === this.document) return;\n const overlay = document?.serverOverlay;\n const pointer = this.options.pointer();\n const pointerOn = pointer !== undefined && (document === null || document.reportsOnForAnyone);\n const served = JSON.stringify([pointerOn, overlay?.id ?? null]);\n if (served !== this.served) {\n const { ours, subagent } = batonParagraphs(pointerOn ? pointer : undefined, overlay, this.options.subagentLine());\n this.options.writeInstructions(ours, subagent);\n this.served = served;\n this.serverOverlay = overlay;\n }\n this.document = document;\n } catch (err) {\n stderrLine(`baton: could not update the server instructions for new settings: ${printable(err)}`);\n }\n }\n\n /** `followSettings` after the report pointer changed outside the settings. */\n refresh(): void {\n this.document = UNREAD;\n this.served = null;\n this.followSettings();\n }\n\n /** `result` with the caller's goal, reports and overlay; as served on any failure. */\n toolsFor(result: unknown, caller: ResolvedCaller): unknown {\n const settings = caller.settings;\n if (settings === undefined) return result;\n const { intentParamMode, annotationToolName, injectsGoal } = this.options;\n const goal = settings.intentParamMode ?? intentParamMode;\n const hideReports = annotationToolName !== \"\" && settings.reportMode === \"off\";\n const overlay = settings.overlay;\n if (goal === intentParamMode && !hideReports && overlay === undefined) return result;\n try {\n const tools = (result as { tools?: unknown } | null | undefined)?.tools;\n if (!Array.isArray(tools)) return result;\n const served: unknown[] = [];\n const injected: boolean[] = [];\n for (const tool of tools) {\n const name = (tool as { name?: unknown } | null)?.name;\n if (hideReports && name === annotationToolName) continue;\n const ours =\n typeof name === \"string\" &&\n injectsGoal(name) &&\n declaresParam((tool as { inputSchema?: unknown } | null)?.inputSchema, USER_GOAL_PARAM_NAME);\n served.push(goal !== intentParamMode && ours ? withGoalMode(tool, goal) : tool);\n injected.push(ours);\n }\n const rewritten =\n overlay === undefined ? served : withOverlay(served, injected, overlay, annotationToolName || undefined);\n return { ...(result as Record<string, unknown>), tools: rewritten };\n } catch (err) {\n stderrLine(`baton: could not apply capture settings to the tool list: ${printable(err)}`);\n return result;\n }\n }\n}\n\n/** Baton's paragraphs of the instructions, and the subagent sentence they end with if any. */\nexport function batonParagraphs(\n pointer: string | undefined,\n overlay: Overlay | undefined,\n subagentLine: boolean,\n): { ours: string; subagent: string | null } {\n const parts = overlay?.instructionAppends() ?? [];\n if (pointer !== undefined) parts.push(overlaid(pointer, overlay, \"instructions.report_pointer\"));\n if (subagentLine) parts.push(overlaid(INTENT_INSTRUCTIONS, overlay, \"instructions.subagent\"));\n // SPEC §2.6's append rule: each paragraph loses the white space at its end.\n const kept = parts.map(stripWhiteSpaceEnd);\n return { ours: kept.filter((part) => part).join(\"\\n\\n\"), subagent: (subagentLine && kept.at(-1)) || null };\n}\n\ntype Tool = Record<string, unknown>;\ntype Schema = { properties?: unknown; required?: unknown } & Record<string, unknown>;\n\n/** SPEC §2.6: the audience overlay's actions on the tool list, in order.\n * `injected` says which tools carry Baton's `user_goal`. */\nfunction withOverlay(\n tools: unknown[],\n injected: readonly boolean[],\n overlay: Overlay,\n reportTool: string | undefined,\n): unknown[] {\n const position = new Map<unknown, number>();\n tools.forEach((tool, i) => position.set((tool as { name?: unknown } | null)?.name, i));\n const hidden = new Set<number>();\n for (const action of overlay.actions) {\n if (action.tool === undefined) continue;\n const i = position.get(action.tool);\n if (i === undefined) {\n warnSkipped(overlay.id, action.index, `no tool is named ${JSON.stringify(action.tool)}`);\n } else if (action.tool === reportTool) {\n warnSkipped(overlay.id, action.index, \"the report tool takes agent_text targets only\");\n } else if (action.param === undefined && action.change === \"remove\") {\n hidden.add(i);\n } else if (action.param === undefined) {\n tools[i] = withDescription(tools[i] as Tool, [action]);\n } else {\n const reason = paramChange(tools, i, action, injected[i]!);\n if (reason !== undefined) warnSkipped(overlay.id, action.index, reason);\n }\n }\n const goalActions = overlay.pieceActions(\"goal_param.description\");\n if (goalActions.length > 0) {\n injected.forEach((ours, i) => {\n if (ours) describeParam(tools, i, USER_GOAL_PARAM_NAME, goalActions);\n });\n }\n const reportActions = overlay.pieceActions(\"report_tool.description\");\n const reportAt = reportTool === undefined ? undefined : position.get(reportTool);\n if (reportActions.length > 0 && reportAt !== undefined) {\n tools[reportAt] = withDescription(tools[reportAt] as Tool, reportActions);\n }\n return tools.filter((_, i) => !hidden.has(i));\n}\n\nfunction withDescription(tool: Tool, actions: readonly Action[]): Tool {\n const description = typeof tool.description === \"string\" ? tool.description : undefined;\n return { ...tool, description: changedText(description, actions).text };\n}\n\n/** Apply one param action to `tools[i]`; why it was skipped, else `undefined`. */\nfunction paramChange(tools: unknown[], i: number, action: Action, injected: boolean): string | undefined {\n const param = action.param!;\n const tool = tools[i] as Tool;\n const schema = tool.inputSchema as Schema | undefined;\n const properties = isRecord(schema) && isRecord(schema.properties) ? schema.properties : undefined;\n if (properties === undefined || !Object.hasOwn(properties, param)) {\n return `${JSON.stringify(action.tool)} has no param ${JSON.stringify(param)}`;\n }\n if (injected && param === USER_GOAL_PARAM_NAME) return \"Baton's user_goal takes the goal_param.description target\";\n const required = Array.isArray(schema!.required) ? (schema!.required as unknown[]) : [];\n if (action.change === \"remove\") {\n if (required.includes(param)) return `${JSON.stringify(action.tool)} requires ${JSON.stringify(param)}`;\n const kept = Object.fromEntries(Object.entries(properties).filter(([name]) => name !== param));\n tools[i] = { ...tool, inputSchema: { ...schema, properties: kept } };\n } else if (action.change === \"required\") {\n if (!required.includes(param)) tools[i] = { ...tool, inputSchema: { ...schema, required: [...required, param] } };\n } else {\n describeParam(tools, i, param, [action]);\n }\n return undefined;\n}\n\nfunction describeParam(tools: unknown[], i: number, param: string, actions: readonly Action[]): void {\n const tool = tools[i] as Tool;\n const schema = tool.inputSchema as Schema;\n const properties = schema.properties as Record<string, unknown>;\n const described = isRecord(properties[param]) ? properties[param] : {};\n const current = typeof described.description === \"string\" ? described.description : undefined;\n const description = changedText(current, actions).text;\n tools[i] = {\n ...tool,\n inputSchema: { ...schema, properties: { ...properties, [param]: { ...described, description } } },\n };\n}\n\n/** A copy of `tool` whose `user_goal` reads and is listed as `goal` says. */\nfunction withGoalMode(tool: unknown, goal: IntentParamMode): unknown {\n const entry = tool as { inputSchema?: unknown };\n const schema = entry.inputSchema as { properties?: unknown; required?: unknown } | null | undefined;\n const properties = schema?.properties as Record<string, unknown> | null | undefined;\n const param = properties?.[USER_GOAL_PARAM_NAME];\n if (typeof param !== \"object\" || param === null) return tool;\n const others = Array.isArray(schema!.required)\n ? (schema!.required as unknown[]).filter((name) => name !== USER_GOAL_PARAM_NAME)\n : [];\n const required = goal === \"required\" ? [...others, USER_GOAL_PARAM_NAME] : others;\n return {\n ...entry,\n inputSchema: {\n ...schema,\n properties: {\n ...properties,\n [USER_GOAL_PARAM_NAME]: { ...param, description: buildUserGoalParamDescription({ intentParamMode: goal }) },\n },\n ...(required.length > 0 || Array.isArray(schema!.required) ? { required } : {}),\n },\n };\n}\n","import { nextClockSequence, nowMicros } from \"../../sequence.js\";\n\nexport const SESSION_CAP = 4096;\n\n/** Per-session sequence numbers (SPEC §11.2 rule 5), for the\n * `SESSION_CAP` most recently used sessions. A minted session counts from 1;\n * an observed one is also at least the clock in µs, so its numbers still rise\n * after it is forgotten. */\nexport class SessionCounter {\n private readonly counters = new Map<string, number>();\n\n /** A per-call session is numbered by the clock: a counter would fill with\n * sessions that never come back and push out live ones. */\n nextFor(session: { sessionId: string; origin: \"observed\" | \"minted\"; perCall: boolean }): number {\n return session.perCall ? nextClockSequence() : this.next(session.sessionId, session.origin === \"observed\");\n }\n\n next(sessionId: string, observed: boolean): number {\n const previous = this.counters.get(sessionId) ?? 0;\n const next = observed ? Math.max(previous + 1, nowMicros()) : previous + 1;\n this.counters.delete(sessionId);\n this.counters.set(sessionId, next);\n if (this.counters.size > SESSION_CAP) this.counters.delete(this.counters.keys().next().value as string);\n return next;\n }\n}\n\n/** One server's counter: its own fallback session is numbered here, so the entry\n * goes with the server; every other session through the Baton's shared counter. */\nexport class ServerCounter extends SessionCounter {\n private ownSequence = 0;\n\n constructor(\n private readonly shared: SessionCounter,\n private readonly ownSessionId: string,\n ) {\n super();\n }\n\n override next(sessionId: string, observed: boolean): number {\n return sessionId === this.ownSessionId ? ++this.ownSequence : this.shared.next(sessionId, observed);\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 * as crypto from \"node:crypto\";\n\nexport function surfaceHash(surface: unknown): string {\n const canonical = canonicalJson(surface);\n const digest = crypto.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((v) => (v === undefined ? \"null\" : canonicalJson(v))).join(\",\")}]`;\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record)\n .filter((k) => record[k] !== undefined)\n .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\nexport const SENT_SURFACES_CAP = 256;\n\n/** The last `SENT_SURFACES_CAP` surface hashes sent, least recent dropped\n * first. Bounded because a tool list that differs per caller would otherwise\n * grow it for the life of the process; a dropped hash is only sent again. */\nexport class SentSurfaces {\n private readonly hashes = new Set<string>();\n private serverOverlay: string | null = null;\n\n /** `serverOverlay` is not in `surface_hash`, and a snapshot is sent again\n * whenever it changes (SPEC §11.4.2). */\n wasSent(digest: string, serverOverlay: string | null = null): boolean {\n if (serverOverlay !== this.serverOverlay || !this.hashes.has(digest)) return false;\n this.hashes.delete(digest);\n this.hashes.add(digest);\n return true;\n }\n\n mark(digest: string, serverOverlay: string | null = null): void {\n if (serverOverlay !== this.serverOverlay) {\n this.hashes.clear();\n this.serverOverlay = serverOverlay;\n }\n this.hashes.add(digest);\n if (this.hashes.size > SENT_SURFACES_CAP) {\n this.hashes.delete(this.hashes.values().next().value as string);\n }\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. */\nexport function buildSeamAugmentations(options: {\n injectedToolNames: string[];\n intentParamNames: string[];\n intentParamMode: \"optional\" | \"required\";\n requiredParamNames: string[];\n /** Whether Baton's text reached the served instructions; `null` when the\n * producer cannot tell. */\n instructionsSuffix: boolean | null;\n}): Record<string, unknown> {\n return {\n injected_tools: [...options.injectedToolNames].sort(),\n intent_param: {\n names: [...options.intentParamNames].sort(),\n required_names: [...options.requiredParamNames].sort(),\n mode: options.intentParamMode,\n },\n instructions_suffix: options.instructionsSuffix,\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 } from \"../../identity.js\";\nimport { isBlank } from \"../../_text.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. */\nfunction stringClaim(claims: Record<string, unknown>, name: string): string | null {\n const value = claims[name];\n return typeof value === \"string\" && !isBlank(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","/** The library API's session block and sequence numbers (SPEC §5.6). */\n\nimport * as asyncHooks from \"node:async_hooks\";\nimport {\n NO_CALLER,\n callerFor,\n wireLabels,\n type OrganizationWire,\n type PrincipalWire,\n} from \"../identity.js\";\nimport {\n clientObservedFrom,\n type ClientObserved,\n type HeaderInput,\n} from \"../integrations/mcp/clientObserved.js\";\nimport { roundMetaCoordinates } from \"../metaCoordinates.js\";\nimport { scrubOrNull } from \"../integrations/mcp/safeScrub.js\";\nimport { uuid7 } from \"../uuid7.js\";\nimport { isRecord } from \"../_object.js\";\nimport { stripWhiteSpace } from \"../_text.js\";\nimport { stderrLine } from \"../warn.js\";\n\nconst TRANSPORT_LIBRARY = \"library\";\nconst TURN_ID_META_KEY = \"baton/turn_id\";\n\n/** What `client.session(...)` gives every call inside it. */\nexport interface LibrarySession {\n readonly sessionId: string;\n readonly origin: \"observed\" | \"minted\";\n readonly principal: PrincipalWire | null;\n readonly organization: OrganizationWire | null;\n readonly labels: readonly string[];\n readonly clientObserved: ClientObserved | null;\n readonly runtimeMeta: Record<string, unknown> | null;\n}\n\nexport function sessionEnvelope(session: LibrarySession): Record<string, unknown> {\n return {\n session_id: session.sessionId,\n session_id_origin: session.origin,\n transport_observed: TRANSPORT_LIBRARY,\n principal: session.principal,\n organization: session.organization,\n labels: wireLabels(session.labels),\n client_observed: session.clientObserved,\n runtime_meta: session.runtimeMeta,\n };\n}\n\nexport interface SessionValues {\n sessionId?: string;\n principal?: unknown;\n clientInfo?: { name?: string; version?: string };\n headers?: HeaderInput;\n turnId?: string;\n meta?: unknown;\n}\n\nfunction warn(message: string): void {\n stderrLine(`baton: ${message}`);\n}\n\nfunction vendorId(name: string, value: unknown): string | null {\n const cleaned = typeof value === \"string\" ? stripWhiteSpace(value) : \"\";\n if (cleaned !== \"\") return cleaned;\n if (value !== undefined && value !== null) {\n warn(`${name} is not a non-blank string — ignoring it.`);\n }\n return null;\n}\n\nfunction blank(sessionId: string, origin: LibrarySession[\"origin\"]): LibrarySession {\n return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };\n}\n\nfunction requestMeta(meta: unknown): Record<string, unknown> | null {\n if (isRecord(meta)) return meta;\n if (meta !== undefined && meta !== null) warn(\"meta is not an object — ignoring it.\");\n return null;\n}\n\nfunction runtimeMeta(\n meta: Record<string, unknown> | null,\n turnId: string | null,\n scrubber: (value: unknown) => unknown,\n): Record<string, unknown> | null {\n // A client could send its own `baton/turn_id`; on a library event that key\n // is the vendor's (SPEC §11.4.1), so the client's copy never rides.\n const clientKeys = Object.fromEntries(Object.entries(meta ?? {}).filter(([key]) => key !== TURN_ID_META_KEY));\n const cleaned =\n Object.keys(clientKeys).length > 0 ? scrubOrNull(scrubber, roundMetaCoordinates(clientKeys), \"_meta\") : null;\n const out: Record<string, unknown> = isRecord(cleaned) ? { ...cleaned } : {};\n if (turnId !== null) out[TURN_ID_META_KEY] = turnId;\n return Object.keys(out).length > 0 ? out : null;\n}\n\n/** A `session()` block's values. A value that is not usable is logged and dropped. */\nexport function newSession(\n values: SessionValues,\n scrubber: (value: unknown) => unknown,\n disabled: boolean,\n): LibrarySession {\n const id = vendorId(\"sessionId\", values.sessionId);\n const base = id !== null ? blank(id, \"observed\") : blank(uuid7(), \"minted\");\n // Off stops the work too: no scrubber runs on a value that is never sent.\n if (disabled) return base;\n const meta = requestMeta(values.meta);\n return {\n ...base,\n ...callerFor(values.principal, (_key, message) => warn(`principal ${message}`)),\n clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber, meta),\n runtimeMeta: runtimeMeta(meta, vendorId(\"turnId\", values.turnId), scrubber),\n };\n}\n\n// The owning client is stored with the block so one client's block never\n// reaches another client's events.\nconst current = new asyncHooks.AsyncLocalStorage<{ owner: object; session: LibrarySession }>();\n\nexport function runInSession<T>(owner: object, session: LibrarySession, fn: () => T): T {\n return current.run({ owner, session }, fn);\n}\n\n/** `owner`'s open block, or a minted session for this call alone. */\nexport function sessionForCall(owner: object): LibrarySession {\n const entry = current.getStore();\n return entry !== undefined && entry.owner === owner ? entry.session : blank(uuid7(), \"minted\");\n}\n\n","/** The library's `listTools`: the tool list a vendor serving MCP itself hands\n * its agents, and the `surface_snapshot` of the list it started from (SPEC\n * §5.6, §11.4.2). */\n\nimport { requiredParamNames, USER_GOAL_PARAM_NAME } from \"../integrations/mcp/llmText.js\";\nimport { DEFAULT_INTENT_PARAM_MODE, withUserGoalJson } from \"../integrations/mcp/schemaCompat.js\";\nimport { assembleSurface, buildSeamAugmentations, surfaceHash, type ServerMeta } from \"../integrations/mcp/surface.js\";\nimport { printable, stderrLine } from \"../warn.js\";\nimport { isRecord } from \"../_object.js\";\n\n/** The vendor's own `initialize` values, as it serves them. */\nexport interface ListToolsOptions {\n serverInfo?: Record<string, unknown> | null;\n capabilities?: Record<string, unknown> | null;\n instructions?: string | null;\n}\n\nexport interface Surface {\n surface: Record<string, unknown>;\n digest: string;\n}\n\n/** `tools` with `user_goal` added, and the surface of `tools` as passed with\n * its hash. Never throws: a list it cannot read is served as it\n * came, with no surface. */\nexport function serveTools<T>(\n tools: readonly T[],\n options: ListToolsOptions,\n): { served: T[]; surface: Surface | null } {\n let served: T[];\n try {\n served = tools.map(servedEntry);\n } catch (err) {\n stderrLine(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}`);\n return { served: tools as T[], surface: null };\n }\n try {\n // Sorted so the same tools in another order hash the same, as in the adapters.\n const nameOf = (tool: unknown) => (isRecord(tool) ? String(tool.name) : \"\");\n const ordered = [...tools].sort((a, b) => {\n const [x, y] = [nameOf(a), nameOf(b)];\n return x < y ? -1 : x > y ? 1 : 0;\n });\n const meta = {\n server_info: options.serverInfo ?? null,\n capabilities: options.capabilities ?? null,\n instructions: options.instructions ?? null,\n } as ServerMeta;\n // Copied because a queued snapshot outlives the vendor's objects.\n const surface = JSON.parse(\n JSON.stringify(assembleSurface(meta, ordered as Array<Record<string, unknown>>)),\n ) as Record<string, unknown>;\n return { served, surface: { surface, digest: surfaceHash(surface) } };\n } catch (err) {\n stderrLine(`baton: surface snapshot capture failed: ${printable(err)}`);\n return { served, surface: null };\n }\n}\n\nexport function snapshotPayload({ surface, digest }: Surface): Record<string, unknown> {\n return {\n surface_hash: digest,\n ...surface,\n seam_augmentations: buildSeamAugmentations({\n injectedToolNames: [],\n intentParamNames: [USER_GOAL_PARAM_NAME],\n intentParamMode: DEFAULT_INTENT_PARAM_MODE,\n requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),\n instructionsSuffix: null,\n }),\n };\n}\n\nfunction servedEntry<T>(tool: T): T {\n if (!isRecord(tool) || !isRecord(tool.inputSchema)) return tool;\n return { ...tool, inputSchema: withUserGoalJson(tool.inputSchema, DEFAULT_INTENT_PARAM_MODE, true) };\n}\n","/**\n * The library API (SPEC §5.6): `Client` for a vendor whose agents reach it\n * through something other than MCP — a REST API, a skill, or a tool loop in\n * the vendor's own agent. Twin of the Python SDK's `baton.Client`, with the\n * `with` blocks as callbacks:\n *\n * const client = new Client({ dsn: process.env.BATON_DSN });\n * app.use((req, res, next) =>\n * client.session({ sessionId: req.get(\"x-conversation-id\") }, () =>\n * client.trace({ toolName: req.path, params: req.body }, () => next()),\n * ),\n * );\n *\n * Capture never throws into the vendor's code: a callback's own throw is\n * recorded and rethrown unchanged, and every failure of ours is logged and\n * dropped. Only a bad config throws, and only from the constructor.\n */\n\nimport { nextClockSequence } from \"../sequence.js\";\nimport type { Event } from \"../events.js\";\nimport {\n AnnotationEventSchema,\n DEFAULT_CONSENT_TOKEN,\n SurfaceSnapshotEventSchema,\n ToolCallEndEventSchema,\n ToolCallErrorEventSchema,\n ToolCallStartEventSchema,\n} from \"../events.js\";\nimport { parseDsn, selectDsn } from \"../dsn.js\";\nimport { captureDisabled, DisabledSink, logDisabled } from \"../optout.js\";\nimport { Scrubber } from \"../scrub.js\";\nimport { boundedSinkCall, droppedAfterClose, HttpSink, offTheCall, safeWrite, type Sink } from \"../sinks.js\";\nimport { PROCESS_DROPS } from \"../drops.js\";\nimport { printable, stderrLine } from \"../warn.js\";\nimport { uuid7 } from \"../uuid7.js\";\nimport { resolveTenantId } from \"../integrations/mcp/config.js\";\nimport { emit } from \"../integrations/mcp/emit.js\";\nimport {\n errorTypeOf,\n messageOf,\n RESULT_CAPTURE_MODES,\n type ResultCaptureMode,\n scrubbedErrorBody,\n WITHHELD,\n} from \"../integrations/mcp/errorResult.js\";\nimport { INTENT_SOURCE_LIBRARY } from \"../integrations/mcp/llmText.js\";\nimport { isThenable } from \"../integrations/mcp/mcpTypes.js\";\nimport { scrubOrNull, type ScrubbedField } from \"../integrations/mcp/safeScrub.js\";\nimport { SentSurfaces } from \"../integrations/mcp/surface.js\";\nimport {\n type LibrarySession,\n newSession,\n runInSession,\n sessionEnvelope,\n sessionForCall,\n} from \"./session.js\";\nimport { type ListToolsOptions, serveTools, snapshotPayload, type Surface } from \"./surface.js\";\nimport { type Organization, type Principal } from \"../identity.js\";\nimport { isBlank } from \"../_text.js\";\nimport type { HeaderInput } from \"../integrations/mcp/clientObserved.js\";\nimport { isPlainObject } from \"../_object.js\";\n\nexport interface ClientOptions {\n /** The packed connection string from /account. Resolved explicit →\n * `BATON_DSN`; it builds the sink and supplies `vendorId` and `tenantId`. */\n dsn?: string;\n /** Required unless a `dsn` is given. */\n sink?: Sink;\n /** Explicit → `BATON_VENDOR_ID`. Required unless a `dsn` supplies it. */\n vendorId?: string;\n /** Explicit → `BATON_TENANT_ID` → `vendorId`. */\n tenantId?: string;\n /** Explicit → `BATON_CONSENT_TOKEN` → the SDK default. */\n consentToken?: string;\n /** Defaults to `new Scrubber().scrub`; pass `identityScrub` to opt out. */\n scrubber?: (value: unknown) => unknown;\n /** `\"off\"` sends no result: see `BatonConfig.resultCaptureMode`. */\n resultCaptureMode?: ResultCaptureMode;\n}\n\nexport interface SessionOptions {\n /** The vendor's own id for the conversation; without one, the block mints one. */\n sessionId?: string;\n /** Who the vendor says is calling: a `Principal`, which may carry its\n * `organization`, or an `Organization` alone when only the company is known.\n * A block with only a company and no `sessionId` gets a session of its own,\n * so pass your own `sessionId` to keep a conversation's blocks together. */\n principal?: Principal | Organization;\n /** What the calling client said about itself. */\n clientInfo?: { name?: string; version?: string };\n /** The request's headers; only registered ones are kept. */\n headers?: HeaderInput;\n /** The vendor's own id for the user request these calls answer. Pass the\n * same value to every block that serves it, and those calls stay one turn. */\n turnId?: string;\n /** The request's MCP `_meta`, for a vendor serving MCP itself. It is sent\n * as `runtime_meta`, and a client declaration in it wins over `clientInfo`. */\n meta?: Record<string, unknown>;\n}\n\nexport interface TraceOptions {\n toolName: string;\n intent?: string;\n expectedOutcome?: string;\n workflow?: string;\n params?: Record<string, unknown>;\n consentToken?: string;\n}\n\nexport interface AnnotateOptions {\n whatHappened?: string;\n toolName?: string;\n intent?: string;\n expectedOutcome?: string;\n workflow?: string;\n suggestedImprovement?: string;\n context?: Record<string, unknown>;\n}\n\nexport interface ObservedError {\n /** `errorType` and `errorBody` are derived from it unless given. */\n error?: unknown;\n errorType?: string;\n errorBody?: string;\n}\n\ninterface Resolved {\n sink: Sink;\n vendorId: string;\n tenantId: string;\n consentToken: string;\n resultCaptureMode: ResultCaptureMode;\n}\n\nfunction fromEnv(name: string): string | undefined {\n const value = typeof process !== \"undefined\" ? process.env?.[name] : undefined;\n return value ? value : undefined;\n}\n\nfunction resolveConsentToken(explicit: string | undefined): string {\n if (explicit !== undefined && !explicit) {\n throw new Error(\n \"Client consentToken was set to an empty string, and events without one \" +\n \"MUST be rejected by the consumer per SPEC §2.3. Omit it to take the SDK's default.\",\n );\n }\n return explicit ?? fromEnv(\"BATON_CONSENT_TOKEN\") ?? DEFAULT_CONSENT_TOKEN;\n}\n\nfunction resolveClientOptions(options: ClientOptions): Resolved {\n const resultCaptureMode = options.resultCaptureMode ?? \"full\";\n if (!(RESULT_CAPTURE_MODES as readonly string[]).includes(resultCaptureMode)) {\n throw new Error(\n `Client resultCaptureMode ${JSON.stringify(resultCaptureMode)} must be one of ` +\n `${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`,\n );\n }\n if (options.scrubber !== undefined && typeof options.scrubber !== \"function\") {\n throw new Error(\"Client scrubber must be a function.\");\n }\n const dsnString = selectDsn(\n options.dsn,\n {\n vendorId: Boolean(options.vendorId),\n tenantId: Boolean(options.tenantId),\n sink: options.sink !== undefined,\n },\n \"Client\",\n );\n const consentToken = resolveConsentToken(options.consentToken);\n if (dsnString !== undefined) {\n const dsn = parseDsn(dsnString);\n return {\n sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),\n vendorId: dsn.vendorId,\n tenantId: dsn.tenantId,\n consentToken,\n resultCaptureMode,\n };\n }\n if (options.sink === undefined) {\n throw new Error(\n \"Client needs somewhere to send events: pass sink (for example new HttpSink(url, \" +\n \"{ apiKey }) or new StdoutSink()), or dsn — the packed value from /account, \" +\n \"which builds the sink for you.\",\n );\n }\n const vendorId = options.vendorId || fromEnv(\"BATON_VENDOR_ID\");\n if (!vendorId) {\n throw new Error(\"Client needs a vendorId, or the BATON_VENDOR_ID environment variable.\");\n }\n return {\n sink: options.sink,\n vendorId,\n tenantId: resolveTenantId(options.tenantId || undefined, vendorId),\n consentToken,\n resultCaptureMode,\n };\n}\n\nconst hasText = (value: string | null | undefined): boolean =>\n typeof value === \"string\" && !isBlank(value);\n\n/** `[error_type, error_body]` of a thrown value. Never throws: a vendor's\n * error can be any value, including one whose getters throw. */\nfunction describeError(err: unknown): [string, string] {\n let type = \"Error\";\n let body = \"\";\n // Each read is separate, so a throwing message getter still leaves the type.\n try {\n type = errorTypeOf(err);\n } catch {\n // unreadable\n }\n try {\n body = messageOf(err) || (err instanceof Error && typeof err.stack === \"string\" ? err.stack : \"\");\n } catch {\n // unreadable\n }\n return [type, body];\n}\n\n/** A wrapped function's arguments as `params`: one plain-object argument is\n * a tool's named arguments, as on MCP; anything else is kept as a list. */\nfunction paramsOf(args: readonly unknown[]): Record<string, unknown> {\n if (args.length === 1 && isPlainObject(args[0])) return args[0];\n return args.length === 0 ? {} : { args };\n}\n\n/** What a client holds that its traces read. */\nclass Core {\n closed = false;\n // A snapshot describes the server, so it takes no block's session,\n // principal or client (SPEC §5.6 rule 7).\n private readonly surfaceSessionId = uuid7();\n private readonly sentSurfaces = new SentSurfaces();\n\n readonly sink: Sink;\n readonly vendorId: string;\n readonly tenantId: string;\n readonly consentToken: string;\n readonly resultCaptureMode: ResultCaptureMode;\n readonly scrubber: (value: unknown) => unknown;\n readonly disabled: boolean;\n\n constructor(resolved: Resolved & { scrubber: (value: unknown) => unknown; disabled: boolean }) {\n this.sink = offTheCall(resolved.sink);\n this.vendorId = resolved.vendorId;\n this.tenantId = resolved.tenantId;\n this.consentToken = resolved.consentToken;\n this.resultCaptureMode = resolved.resultCaptureMode;\n this.scrubber = resolved.scrubber;\n this.disabled = resolved.disabled;\n }\n\n /** The envelope members every event of `session` shares. Call inside a\n * build thunk, so `captured_at` is the build time. */\n envelope(session: LibrarySession, consentToken: string, sequence: number): Record<string, unknown> {\n return {\n tenant_id: this.tenantId,\n vendor_id: this.vendorId,\n ...sessionEnvelope(session),\n sequence_number: sequence,\n captured_at: new Date().toISOString(),\n consent_token: consentToken,\n };\n }\n\n /** False when nothing may be emitted: the off switch, or a closed client. */\n live(): boolean {\n if (this.disabled) return false;\n if (!this.closed) return true;\n // Keyed on the sink, so an event its queue refused while closing and one\n // refused here share one warning (SPEC §11.2 rule 7).\n droppedAfterClose(this.sink);\n return false;\n }\n\n /** Never rejects. */\n emit(build: () => Event): Promise<void> {\n return emit(this.sink, build);\n }\n\n /** Sends `surface` unless this client already has. Never rejects. The\n * write only queues, so a surface counts as sent once queued. */\n sendSurface(surface: Surface): Promise<void> {\n if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();\n this.sentSurfaces.mark(surface.digest);\n let event: Event;\n try {\n event = SurfaceSnapshotEventSchema.parse({\n tenant_id: this.tenantId,\n vendor_id: this.vendorId,\n session_id: this.surfaceSessionId,\n session_id_origin: \"minted\",\n sequence_number: nextClockSequence(),\n captured_at: new Date().toISOString(),\n consent_token: this.consentToken,\n payload: snapshotPayload(surface),\n });\n } catch (err) {\n PROCESS_DROPS.add(\"encode_failed\");\n stderrLine(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}`);\n return Promise.resolve();\n }\n return safeWrite(this.sink, event);\n }\n\n scrub(value: unknown, field: ScrubbedField): unknown {\n return scrubOrNull(this.scrubber, value, field);\n }\n\n annotate(session: LibrarySession, consentToken: string, options: AnnotateOptions): Promise<void> {\n if (!this.live()) return Promise.resolve();\n const sequence = nextClockSequence();\n // The text fields are scrubbed bare inside the thunk: an annotation is one\n // report, so a scrubber throw drops it whole, as on the MCP path.\n /* eslint-disable no-restricted-syntax -- inside the emit() build thunk */\n const text = (value: string | undefined): string | null =>\n value === undefined ? null : (this.scrubber(value) as string | null);\n return this.emit(() =>\n AnnotationEventSchema.parse({\n ...this.envelope(session, consentToken, sequence),\n payload: {\n intent: text(options.intent),\n expected_outcome: text(options.expectedOutcome),\n what_happened: hasText(options.whatHappened) ? text(options.whatHappened) : null,\n tool_name: options.toolName ? text(options.toolName) : (options.toolName ?? null),\n workflow: text(options.workflow),\n suggested_improvement: text(options.suggestedImprovement),\n context:\n options.context && Object.keys(options.context).length > 0\n ? this.scrub(options.context, \"context\")\n : null,\n },\n }),\n );\n /* eslint-enable no-restricted-syntax */\n }\n}\n\nconst UNSET = Symbol(\"unset\");\n// `observed()` ran and the result was deliberately not kept (resultCaptureMode \"off\").\nconst WITHHELD_RESULT = Symbol(\"withheld\");\n// The scrubber threw on the result. Re-thrown inside the build thunk so the\n// end event is dropped rather than sent with a result the tool never returned.\nconst SCRUB_FAILED = Symbol(\"scrubFailed\");\n\n// Set by `Trace`'s static block, so only `Client` can start, end or fail a trace.\nlet runTrace: <T>(core: Core, session: LibrarySession, options: TraceOptions, fn: (trace: Trace) => T) => T;\n\n/** One traced call, handed to the `client.trace()` callback. */\nexport class Trace {\n readonly #core: Core;\n readonly #session: LibrarySession;\n readonly #options: TraceOptions;\n readonly #consentToken: string;\n readonly #callId = uuid7();\n #startedAt = 0;\n #result: unknown = UNSET;\n #error: { type: string; body: string } | null = null;\n #observedWarned = false;\n\n private constructor(core: Core, session: LibrarySession, options: TraceOptions) {\n this.#core = core;\n this.#session = session;\n this.#options = options;\n this.#consentToken = options.consentToken || core.consentToken;\n }\n\n /** The session this call's events carry. */\n get sessionId(): string {\n return this.#session.sessionId;\n }\n\n /** Record the outcome. Without a call, the callback's return value is the\n * result. `observed(undefined, { error })` records a failure the callback\n * caught and did not rethrow. The last call wins. */\n observed(result?: unknown, failure?: ObservedError): this {\n if ((this.#result !== UNSET || this.#error !== null) && !this.#observedWarned) {\n this.#observedWarned = true;\n stderrLine(\"baton: Trace.observed() called more than once; the last call wins.\");\n }\n this.#result = UNSET;\n this.#error = null;\n if (this.#core.disabled) return this;\n let errorType = failure?.errorType;\n let errorBody = failure?.errorBody;\n if (failure?.error !== undefined) {\n const [derivedType, derivedBody] = describeError(failure.error);\n errorType ||= derivedType;\n errorBody ||= derivedBody;\n }\n if (errorType !== undefined || errorBody !== undefined) {\n this.#error = { type: errorType || \"Error\", body: errorBody ?? \"\" };\n } else if (this.#core.resultCaptureMode === WITHHELD) {\n // Decided here, so a withheld result never reaches the scrubber (SPEC §7).\n this.#result = WITHHELD_RESULT;\n } else {\n // Scrubbed now, so a result object the caller changes later is recorded\n // as it was when observed.\n try {\n // eslint-disable-next-line no-restricted-syntax -- the throw is caught here and parks SCRUB_FAILED, which drops the end event\n this.#result = this.#core.scrubber(result);\n } catch (err) {\n stderrLine(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}`);\n this.#result = SCRUB_FAILED;\n }\n }\n return this;\n }\n\n /** Report on this call, in its session. */\n annotate(options: AnnotateOptions): Promise<void> {\n return this.#core.annotate(this.#session, this.#consentToken, options);\n }\n\n #envelope(sequence: number): Record<string, unknown> {\n return { ...this.#core.envelope(this.#session, this.#consentToken, sequence), call_id: this.#callId };\n }\n\n #durationMs(): number {\n return Math.trunc(performance.now() - this.#startedAt);\n }\n\n #start(): void {\n this.#startedAt = performance.now();\n if (!this.#core.live()) return;\n const sequence = nextClockSequence();\n const o = this.#options;\n // Fail-open per field, outside the thunk: a scrubber throw here must not\n // drop the start event and leave the call's end unpaired.\n const params = o.params === undefined ? {} : (this.#core.scrub(o.params, \"params\") ?? {});\n const textOf = (value: string | undefined, field: ScrubbedField): string | null => {\n const scrubbed = value === undefined ? null : this.#core.scrub(value, field);\n return typeof scrubbed === \"string\" ? scrubbed : null;\n };\n const intent = textOf(o.intent, \"intent\");\n const expected = textOf(o.expectedOutcome, \"expected_outcome\");\n const workflow = textOf(o.workflow, \"workflow\");\n const stated = [intent, expected, workflow].some(hasText);\n void this.#core.emit(() =>\n ToolCallStartEventSchema.parse({\n ...this.#envelope(sequence),\n payload: {\n tool_name: o.toolName,\n params,\n call_intent: intent,\n call_expected: expected,\n call_workflow: workflow,\n intent_source: stated ? INTENT_SOURCE_LIBRARY : null,\n },\n }),\n );\n }\n\n #end(value: unknown): void {\n const durationMs = this.#durationMs();\n if (!this.#core.live()) return;\n if (this.#result === UNSET && this.#error === null) this.observed(value);\n const sequence = nextClockSequence();\n const error = this.#error;\n if (error !== null) {\n this.#emitError(sequence, error.type, error.body, durationMs);\n return;\n }\n const result = this.#result;\n void this.#core.emit(() => {\n if (result === SCRUB_FAILED) throw new Error(\"the scrubber threw on this result\");\n return ToolCallEndEventSchema.parse({\n ...this.#envelope(sequence),\n payload: {\n tool_name: this.#options.toolName,\n duration_ms: durationMs,\n ...(result === WITHHELD_RESULT\n ? { result: null, result_capture: WITHHELD }\n : { result }),\n },\n });\n });\n }\n\n #fail(err: unknown): void {\n const durationMs = this.#durationMs();\n if (!this.#core.live()) return;\n this.#emitError(nextClockSequence(), ...describeError(err), durationMs);\n }\n\n #emitError(sequence: number, type: string, body: string, durationMs: number): void {\n void this.#core.emit(() =>\n ToolCallErrorEventSchema.parse({\n ...this.#envelope(sequence),\n payload: {\n tool_name: this.#options.toolName,\n error_type: type,\n error_body: scrubbedErrorBody(this.#core.scrubber, body),\n duration_ms: durationMs,\n result: null,\n },\n }),\n );\n }\n\n static {\n runTrace = <T>(core: Core, session: LibrarySession, options: TraceOptions, fn: (trace: Trace) => T): T => {\n const trace = new Trace(core, session, options);\n trace.#start();\n let value: T;\n try {\n value = fn(trace);\n } catch (err) {\n trace.#fail(err);\n throw err;\n }\n if (!isThenable(value)) {\n trace.#end(value);\n return value;\n }\n return Promise.resolve(value).then(\n (resolved) => {\n trace.#end(resolved);\n return resolved;\n },\n (err: unknown) => {\n trace.#fail(err);\n throw err;\n },\n ) as T;\n };\n }\n}\n\n/** The library API's client. One per process. */\nexport class Client {\n readonly #core: Core;\n #closing: Promise<void> | undefined;\n\n constructor(options: ClientOptions = {}) {\n const switchName = captureDisabled();\n let resolved: Resolved;\n if (switchName !== null) {\n // Off means never throw, so nothing is validated; a sink the caller\n // passed is kept so `aclose()` still releases it.\n logDisabled(switchName, \"Client\");\n resolved = {\n sink: options.sink ?? new DisabledSink(),\n vendorId: \"\",\n tenantId: \"\",\n consentToken: DEFAULT_CONSENT_TOKEN,\n resultCaptureMode: \"full\",\n };\n } else {\n resolved = resolveClientOptions(options);\n }\n this.#core = new Core({\n ...resolved,\n scrubber: options.scrubber ?? new Scrubber().scrub,\n disabled: switchName !== null,\n });\n }\n\n /** Run `fn` with one session, principal, client and turn for every\n * `trace()` and `annotate()` inside it, including after its awaits. Open\n * one per request or conversation. Returns what `fn` returns. */\n session<T>(options: SessionOptions, fn: () => T): T {\n let block: LibrarySession;\n try {\n block = newSession(options, this.#core.scrubber, this.#core.disabled);\n } catch (err) {\n stderrLine(`baton: session values could not be read; using a minted session: ${printable(err)}`);\n block = newSession({}, this.#core.scrubber, this.#core.disabled);\n }\n return runInSession(this, block, fn);\n }\n\n /** Run `fn` as one traced tool call and return what it returns. When `fn`\n * returns a promise or other thenable, the call ends when it settles, and\n * what comes back is a new native Promise of the same value: `then` is\n * called exactly once, so a lazy query builder is not run twice. A throw or\n * rejection is recorded and passed on unchanged. */\n trace<T>(options: TraceOptions, fn: (trace: Trace) => T): T {\n // `?? {}` for a JavaScript caller: missing options must not throw into its code.\n return runTrace(this.#core, sessionForCall(this), options ?? ({} as TraceOptions), fn);\n }\n\n /** `fn`, traced on every call. A single plain-object argument is sent as\n * `params`, as an MCP tool's arguments are; other arguments as\n * `{ args: [...] }`, unless `options.params` is given. */\n wrap<A extends unknown[], R>(options: string | TraceOptions, fn: (...args: A) => R): (...args: A) => R {\n const base: TraceOptions = typeof options === \"string\" ? { toolName: options } : (options ?? {});\n // eslint-disable-next-line @typescript-eslint/no-this-alias -- the wrapper keeps its own `this` for `fn`\n const client = this;\n return function (this: unknown, ...args: A): R {\n return client.trace({ ...base, params: base.params ?? paramsOf(args) }, () => fn.apply(this, args));\n };\n }\n\n /** Emit an annotation in the open `session()` block, or in a session of its\n * own outside one. To report on a traced call, use `trace.annotate()`. */\n annotate(options: AnnotateOptions & { consentToken?: string }): Promise<void> {\n const given = options ?? {};\n return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);\n }\n\n /** `tools`, the vendor's own `tools/list` entries, with `user_goal` added\n * to each `inputSchema` as `withBaton` adds it, and a `surface_snapshot`\n * of `tools` as passed, sent once per distinct surface. For a vendor\n * serving MCP itself (SPEC §5.6).\n *\n * Pass the tools before anything of Baton's is added, so the snapshot\n * describes the vendor's own surface. `options` holds the vendor's own\n * `initialize` values. The input is not changed. Never rejects over the\n * tool list: one it cannot read is returned as it came. Does not wait for\n * the snapshot to be sent; `flush()` does. */\n async listTools<T>(tools: readonly T[], options: ListToolsOptions = {}): Promise<T[]> {\n if (this.#core.disabled) return tools as T[];\n const { served, surface } = serveTools(tools, options);\n if (surface !== null) void this.#core.sendSurface(surface);\n return served;\n }\n\n /** Wait for events so far to reach the sink, then flush it. Never rejects;\n * returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */\n async flush(): Promise<void> {\n await boundedSinkCall(this.#core.sink, \"flush\");\n }\n\n /** Flush, then close the sink. Later events are dropped. */\n aclose(): Promise<void> {\n this.#closing ??= boundedSinkCall(this.#core.sink, \"aclose\").then(() => {\n this.#core.closed = true;\n });\n return this.#closing;\n }\n}\n","/** The annotation tool as data, for a vendor offering it through its own API (SPEC §5.6). */\n\nimport { isRecord } from \"../_object.js\";\nimport {\n ANNOTATION_INPUT_SHAPE,\n isReport,\n TOOL_NAME_PARAM_NAME,\n} from \"../integrations/mcp/annotation.js\";\nimport {\n toolNameForDisplayName,\n validateAnnotationToolName,\n} from \"../integrations/mcp/annotationName.js\";\nimport {\n buildAnnotationToolDescription,\n buildRefusalText,\n buildServerInstructions,\n fitsInstructionsCap,\n USER_GOAL_PARAM_NAME,\n} from \"../integrations/mcp/llmText.js\";\nimport { toolInputJsonSchema } from \"../integrations/mcp/schemaCompat.js\";\nimport type { AnnotateOptions } from \"./client.js\";\n\n/** The tool an MCP adapter registers under `reportMode: \"on\"`. */\nexport interface ReportTool {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: Record<string, unknown>;\n /** The report pointer and `INTENT_INSTRUCTIONS`, for a vendor serving MCP itself. */\n readonly instructions: string;\n /** What to answer when `annotateArgs` returns `null`. */\n readonly refusal: string;\n /** The `annotate()` options for this tool's `args`, or `null` when there is\n * no `what_happened`: answer `refusal` and send nothing. */\n annotateArgs(args: Readonly<Record<string, unknown>>): AnnotateOptions | null;\n}\n\nfunction inputSchema(): Record<string, unknown> {\n const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);\n delete schema.$schema;\n return { ...schema, required: [...(schema.required as string[]), TOOL_NAME_PARAM_NAME] };\n}\n\nconst nonEmptyText = (value: unknown): value is string => typeof value === \"string\" && value !== \"\";\n\nconst nonEmptyObject = (value: unknown): value is Record<string, unknown> =>\n isRecord(value) && Object.keys(value).length > 0;\n\nfunction annotateArgs(args: Readonly<Record<string, unknown>>): AnnotateOptions | null {\n const whatHappened = args.what_happened;\n if (!isReport(whatHappened)) return null;\n const options: AnnotateOptions = { whatHappened };\n // Sent as written, \"\" included: SPEC §5.1.1 gives tool_name three states.\n const toolName = args[TOOL_NAME_PARAM_NAME];\n if (typeof toolName === \"string\") options.toolName = toolName;\n const intent = args[USER_GOAL_PARAM_NAME];\n if (nonEmptyText(intent)) options.intent = intent;\n if (nonEmptyText(args.suggested_improvement)) {\n options.suggestedImprovement = args.suggested_improvement;\n }\n if (nonEmptyObject(args.context)) options.context = args.context;\n return options;\n}\n\n/** The annotation tool an adapter registers on a server named\n * `vendorDisplayName`. `name` overrides the name made from it. */\nexport function reportTool(options: { vendorDisplayName: string; name?: string }): ReportTool {\n const { vendorDisplayName } = options;\n const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);\n if (derived === undefined) {\n throw new Error(\n `vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, ` +\n \"or one too long for the instructions. Pass name.\",\n );\n }\n const name = validateAnnotationToolName(derived);\n if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: name })) {\n throw new Error(\n `vendorDisplayName and name ${JSON.stringify(name)} are too long together for ` +\n \"the instructions. Shorten one of them.\",\n );\n }\n return {\n name,\n description: buildAnnotationToolDescription({ vendorDisplayName }),\n inputSchema: inputSchema(),\n instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),\n refusal: buildRefusalText({ annotationToolName: name }),\n annotateArgs,\n };\n}\n"],"mappings":";AAEO,IAAM,cAAc;;;ACa3B,SAAS,SAAS;;;ACflB,YAAY,YAAY;AAExB,IAAM,cAAc;AAEpB,IAAI,SAAS;AACb,IAAI,UAAU;AAIP,SAAS,QAAgB;AAC9B,QAAM,QAAe,mBAAY,EAAE;AAEnC,QAAM,QAAS,MAAM,EAAE,KAAM,IAAK,MAAM,EAAE,KAAM;AAChD,QAAM,MAAM,KAAK,IAAI;AACrB,MAAI,MAAM,QAAQ;AAChB,aAAS;AACT,cAAU;AAAA,EACZ,WAAW,EAAE,UAAU,aAAa;AAClC,cAAU;AACV,cAAU;AAAA,EACZ;AAEA,QAAM,YAAY,QAAQ,GAAG,CAAC;AAC9B,QAAM,CAAC,IAAI,MAAQ,WAAW;AAC9B,QAAM,CAAC,IAAI,UAAU;AACrB,QAAM,CAAC,IA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,QAAM,UAAU,QAAQ,QAAQ,uBAAuB,iBAAiB;AACxE,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI;AAAA,MACR,qBAAqB,KAAK,UAAU,iBAAiB,CAAC;AAAA,IAExD;AAAA,EACF;AACA,QAAM,OAAO,2BAA2B,OAAO;AAC/C,MAAI,CAAC,oBAAoB,EAAE,mBAAmB,oBAAoB,KAAK,CAAC,GAAG;AACzE,UAAM,IAAI;AAAA,MACR,8BAA8B,KAAK,UAAU,IAAI,CAAC;AAAA,IAEpD;AAAA,EACF;AACA,SAAO;AAAA,IACL;AAAA,IACA,aAAa,+BAA+B,EAAE,kBAAkB,CAAC;AAAA,IACjE,aAAa,YAAY;AAAA,IACzB,cAAc,wBAAwB,EAAE,mBAAmB,oBAAoB,KAAK,CAAC;AAAA,IACrF,SAAS,iBAAiB,EAAE,oBAAoB,KAAK,CAAC;AAAA,IACtD;AAAA,EACF;AACF;","names":["sum","emit","z","walk","current","warn","vendorId","warn","crypto","errorBody","vendorId","warned","inputSchema","declared","warned","z","fromEnv","vendorId","fromEnv","reportTool","current","crypto","durationMs","declared","warnOnce","reportTool","inputSchema","args","outcome","warned","counter","json","asyncHooks","warn","vendorId","hasText","errorBody"]}
|