/** * LLM proxy capture fork (FEAT-458 S3, ADR-013 "Accepted" — Decision 3/4). * * Structurally distinct from `src/capture/claude.ts` per this ADR's own * framing: `claude.ts` reads a completed transcript FILE after the fact and * is incapable of mutating live traffic by construction. This module * consumes a live BODY-ONLY tee of an in-flight proxy exchange * (`src/proxy/server.ts`'s `ProxyTeeSink`) — it must not import or extend * any of `claude.ts`'s file-reading assumptions, and it never receives, is * never passed, and has no field capable of carrying request/response * HEADERS. The proxy forwards the `Authorization` header (and everything * else) to the upstream unchanged (`src/proxy/server.ts`); this module only * ever sees the two Buffer streams `ProxyTeeSink` hands it — that exclusion * is a type-boundary property, not a runtime filter (ADR-013 review * decision 3, "enforced by type boundary + regression test" — see * tests/proxy/canary-header-exclusion.test.ts). * * Reuses, unmodified: `src/ingest/spool.ts` (durable write — no new trust * boundary) and `src/capture/relevance-gate.ts` (source-side filtering, * ADR-012 decision 2) — same taxonomy and dedup mechanics hook-tap capture * already uses. * * Wire-format support (FEAT-458 S5): both OpenAI chat-completions and the * Anthropic Messages API — the shape Claude Code itself speaks — are * parsed, detected from BODY BYTES ONLY per the header-exclusion invariant * above (there is no content-type header available to branch on even if * this module were allowed to see headers, which it structurally is not). * See `extractResponseTurn` / `extractSseResponseTurn` for the per-format * detection logic. * * Decompression (FEAT-458 S7): every real upstream (Anthropic, OpenAI, ...) * gzip-compresses response bodies by default, so the bytes this module's tee * actually receives are compressed, not the plaintext JSON/SSE the parsers * above expect. The obvious fix — read the response's Content-Encoding * value — is exactly what the header-exclusion invariant above forbids: this * module cannot see, and must never gain a way to see, ANY header, including * that one. `decompressBody` below therefore detects and reverses * compression from the BODY BYTES ALONE (magic-number sniffing, with a * speculative fallback for brotli, which has no magic number at all) — * never a transport-metadata channel. See its own doc for the full detail. */ import { type RelevanceGateOptions } from './relevance-gate.js'; import type { ProxyTeeSink } from '../proxy/server.js'; import type { Config } from '../config/config.js'; /** * Reverse whatever compression (if any) a tee'd body is under — BODY BYTES * ONLY, per this file's own exclusion invariant (module doc above): there is * no transport-metadata channel this function reads or could read to learn * the encoding; every candidate below is chosen purely by sniffing the bytes * themselves. * * Order matters: gzip, zlib/deflate, and zstd each carry an unambiguous * magic number, so those are sniffed and attempted directly. Brotli has NO * magic number at all — the ONLY way to detect it from bytes alone is to * speculatively attempt a brotli decode and see whether it succeeds; raw * (headerless) deflate is the same story and is tried last. A plaintext * body (the common case whenever a client requests no compression) matches * none of the sniffable magics and reliably fails both speculative decodes * (a compressed-format decoder rejects arbitrary text as structurally * invalid input almost immediately) — so it falls through unchanged, exactly * today's pre-decompression behavior. * * Every attempt is independently wrapped: a corrupt/truncated stream, a * codec unavailable on the running Node build (zstd support is feature- * probed, not assumed), or a decode that would exceed * `MAX_DECOMPRESSED_BODY_BYTES` all fail the SAME way — silently, moving on * to the next candidate, or, once every candidate is exhausted, returning * the ORIGINAL bytes untouched. This function only ever operates on the * caller's own copy of the tee'd bytes (see `finishCapture` below) — it has * no way to reach, and never touches, the bytes already forwarded to the * client. */ export declare function decompressBody(raw: Buffer): Buffer; export interface ProxyTurn { role: 'user' | 'assistant'; text: string; } /** * Wire shape this module produces — same `CanonicalIngestSchema` (v1.0) * transcript-kind envelope every other capture path builds * (`src/server/routes/ingest.ts`), tagged `capture_source: 'proxy'` * (ADR-013 Decision 1, Repudiation row — a second live value alongside * `'auto_capture'`, migration 024's already-unconstrained TEXT column). */ export interface ProxyCaptureEnvelope { /** * `CanonicalIngestSchema.event` is a closed enum written for Claude Code's * own hook lifecycle (`pre_compact` | `session_end` | `subagent_stop`) — * none of those literally describe "one proxied LLM call completed", and * this module deliberately does not invent a fourth value (widening that * enum is a wire-contract change outside this slice's scope). `session_end` * is the closest existing analogue: each captured exchange is a complete, * closed unit on its own (there is no proxy-side session concept at all — * see `session_id` below) rather than a mid-stream checkpoint, which rules * out `pre_compact`/`subagent_stop`. */ event: 'session_end'; /** * The proxy has no session correlator to key off — headers are * structurally excluded (no client-supplied session/request id survives * to this module) and the body carries no session concept of its own. One * random id per captured EXCHANGE (not one per proxy process, not one per * upstream connection) is the only correlation-free option available at * body-only visibility. */ session_id: string; /** No cwd/repo signal reaches a body-only capture fork — a fixed sentinel * distinguishes proxy-sourced rows from every other project_id without * fabricating a project this module cannot actually know. */ project_id: 'llm-proxy'; captured_at: string; kind: 'transcript'; tool: 'llm-proxy'; turns: ProxyTurn[]; client_scrub_applied: boolean; client_scrub_hits: number; client_version: string; client_scrub_version: string; wire_version: 'v1.0'; capture_source: 'proxy'; /** FEAT-458 S6 — omitted entirely (not `null`) when `extractUsageMetadata` * returns null (no recognized provider shape in the response body) so * the field round-trips through `CanonicalIngestSchema`'s `.optional()` * (src/server/routes/ingest.ts) rather than failing zod validation with * a literal null against an object schema. */ proxy_usage?: ProxyUsageMetadata; } /** * Parse an accumulated request-body buffer (already fully reassembled from * tee'd chunks — see `createProxyCaptureTee` below) into user turns. Only * `role: 'user'` messages become turns — `system`/`assistant`/`tool` * messages in the request are the caller's own prior context, not this * exchange's new human input, and (for a client that resends full history * on every call) capturing them here would re-spool the same content on * every request, exactly the volume the relevance gate's dedup window * exists to cut. Tolerant of any parse failure — returns no turns rather * than throwing (fail-silent capture, ADR-013 Decision 2). * * Wire-format note: an Anthropic Messages API request carries its system * prompt in a top-level `system` field (a string, or an array of text * blocks) rather than as a `role: 'system'` entry inside `messages[]` — * unlike OpenAI, which puts system content in `messages[]` where the * `role !== 'user'` filter above already excludes it. This function * deliberately never reads `parsed.system` at all, for both APIs: it's * boilerplate that repeats on every call in a client that resends full * history (exactly the redundant-volume problem the role filter above * exists to avoid for OpenAI's system messages too), it can be large, and * it is the highest-sensitivity part of the payload (product/tool * instructions, not user-authored content) — capturing it isn't this * module's call to make silently. The `role: 'user'` filter is what * happens to also make this the behavior for both formats; no per-format * branch was needed. `messages[].content` itself — string or array of * typed blocks (Anthropic user turns can include `tool_result` blocks * alongside `text`) — is handled by `extractContentBlockText`, which only * ever pulls `type: 'text'` blocks; a `tool_result` block is therefore * skipped like any other non-text block, consistent with "only NEW human * input becomes a turn." */ export declare function extractRequestTurns(rawBody: string): ProxyTurn[]; /** * Parse an accumulated response-body buffer into a single assistant turn. * Body-only visibility means there is no `content-type` header to branch * on, so BOTH the streaming-vs-whole-JSON split AND the OpenAI-vs-Anthropic * wire-format split are detected from the bytes themselves — see * `extractSseResponseTurn` below for the streaming-format sniff. A * non-streaming response of either format is a single JSON object; a * streaming one is a newline-delimited SSE sequence. Tries JSON first * (cheap, and unambiguous when it succeeds — an SSE body is never valid * whole-buffer JSON), falls back to SSE parsing. Any malformed line/chunk * is skipped, never fatal — matches `claude.ts`'s own transcript-parsing * tolerance for a still-forming/imperfect stream. */ export declare function extractResponseTurn(rawBody: string): ProxyTurn | null; /** * Token/cost telemetry for one exchange — BODY BYTES ONLY, same visibility * as turn extraction above, never headers. * * WIRED into `ProxyCaptureEnvelope` / `finishCapture` below as of FEAT-458 * S6 — `CanonicalIngestSchema` (src/server/routes/ingest.ts) now carries an * explicit optional `proxy_usage` field, so the previously-documented strip- * mode hazard (an unknown envelope field silently REMOVED by zod's default * "strip" behavior at drain-time `safeParse`, not rejected — the false- * confidence failure mode this module already got bitten by once, module * doc, S3) is closed: the field now has a schema home before it is ever * attached, not after. * * - `model`: read from the REQUEST body's top-level `model` field only, * for both wire formats — a client always specifies what to call, so * it's unconditionally present there, unlike the response side (an * Anthropic streaming response only echoes it inside the `message_start` * event, which a truncated/aborted capture might not have; some * gateways drop it from non-streaming responses entirely). One source of * truth, always populated when the request parsed at all. * - `stop_reason`: Anthropic's `stop_reason` / OpenAI's `finish_reason`, * normalized into one field. `truncated` is derived from it: Anthropic * `"max_tokens"` / OpenAI `"length"` — both mean the reply was cut off * before the model finished, which the operator cares about regardless * of which API served it. * - Cache fields (`cache_creation_input_tokens` / `cache_read_input_tokens`) * are Anthropic-only and kept SEPARATE from `input_tokens` rather than * folded in — this is the operator's single biggest lever on API cost * and collapsing it into one number would erase the signal that matters. * - Every numeric field is `number | null` — `null` means "not present in * this body" and is never coerced to `0`. A fabricated zero here would * silently corrupt any cost aggregation built on top later; a missing * value must stay visibly missing. The clearest case is OpenAI streaming * without `stream_options.include_usage` set — no chunk ever carries a * `usage` field, so every token count stays `null` while `model` and * `stop_reason` (available independent of that flag) still populate. * - No dollar-cost computation — a per-model pricing table rots the moment * prices change, and a confidently-wrong dollar figure is worse than raw * counts. Pricing is a deliberate, separate decision. * - Returns `null` only when the response body itself carries no * recognizable provider shape at all (empty, malformed, or neither * `choices` nor `content`/Anthropic-event-typed) — matches * `extractResponseTurn`'s own "unrecognized shape → null" convention. */ export interface ProxyUsageMetadata { provider: 'anthropic' | 'openai'; model: string | null; input_tokens: number | null; output_tokens: number | null; /** OpenAI only (`usage.total_tokens`) — Anthropic doesn't report a * pre-summed total, and this module doesn't compute one itself (that * would be silently wrong the instant cache tokens are involved). */ total_tokens: number | null; cache_creation_input_tokens: number | null; cache_read_input_tokens: number | null; stop_reason: string | null; truncated: boolean; } /** Public entry point — see the interface doc above for the full field * rationale. Mirrors `extractResponseTurn`'s own whole-JSON-then-SSE * detection order and per-shape branching, on the SAME accumulated * request/response body buffers (already fully reassembled — see * `createProxyCaptureTee` below). */ export declare function extractUsageMetadata(reqBody: string, resBody: string): ProxyUsageMetadata | null; /** * Stable idempotency key (mirrors `claudeIdempotencyKey`'s exclusion * pattern): a SHA-256 stable-stringify hash of the envelope's CONTENT, * excluding both `captured_at` (varies every call even for identical * content) and `session_id` (this module mints a fresh random one per * exchange — see `ProxyCaptureEnvelope.session_id` doc — so including it * would defeat idempotency entirely, never colliding even for byte-identical * re-sends). Re-capturing an identical exchange therefore produces the SAME * key — a same-path spool overwrite, never an accumulating duplicate. */ export declare function proxyIdempotencyKey(envelope: ProxyCaptureEnvelope): string; export interface ProxyCaptureOptions { dataDir: string; clientVersion: string; relevanceGate: RelevanceGateOptions; /** * Wave A slice A3: the operator's real resolved config, threaded through * to `writeToSpool` so spool-write redaction honors the same * `security.redaction.*` settings (enabled flag, entropy threshold, custom * patterns) the daemon's own ingest-time redaction does — never a second, * independently-drifting redaction posture for the proxy path. Optional * only so existing callers/tests that construct `ProxyCaptureOptions` * without it keep compiling; `writeToSpool` itself still defaults to * `defaultConfig()` (redaction ON) when omitted, so leaving this unset is * fail-safe, not fail-open. `src/cli/proxy.ts` (the only real production * caller) always passes the resolved config. */ redactConfig?: Config; } /** * Build a capture-fork attachment point for the LLM proxy. Call this ONCE * per proxy process — the returned factory is exactly what gets passed as * `ProxyServeOpts.createTee`; `src/proxy/server.ts` calls THAT once per * incoming request to obtain a fresh, per-exchange sink. Two different * closure lifetimes on purpose: * * - This function's own closure (`recentHashes`) lives for the whole * proxy process — the correct scope for the relevance gate's dedup * window (ADR-012 decision 2) on a long-running daemon, unlike the * one-shot `capture claude` CLI's per-invocation (and therefore * always-empty-at-start) window. * - The inner per-request closure (`reqChunks`/`resChunks`/the two * `*Ended` flags) lives for exactly one exchange, so two concurrent * requests through the same proxy never share — or corrupt — each * other's buffered bytes. */ export declare function createProxyCaptureTee(opts: ProxyCaptureOptions): () => ProxyTeeSink;