Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy
Rust
add opt-in traffic capture
Raine Virta5bdaa6ddda9c
diff --git a/README.md b/README.mdindex de7bf38..eb83297 100644--- a/README.md+++ b/README.md@@ -492,6 +492,7 @@ Windows, and at| `XDG_STATE_HOME` | — | `~/.local/state` | Linux/macOS base dir for `proxy.log` || `CCP_LOG_STDERR` | `log.stderr` | unset | Also mirror log lines to stderr || `CCP_LOG_VERBOSE` | `log.verbose` | unset | Log full request/response bodies + every SSE event |+| `CCP_TRAFFIC_LOG` | — | unset | Write per-request traffic captures under `traffic/` for session debugging || `CCP_ALIAS_PROVIDER` | `aliasProvider` | `codex` | Route Anthropic-style aliases (`haiku`, `sonnet`, `opus`, `claude-*`) through `codex` or `kimi` || `CCP_KIMI_OAUTH_HOST` | `kimi.oauthHost` | `https://auth.kimi.com` | Override Kimi's OAuth host (debugging only) || `CCP_KIMI_BASE_URL` | `kimi.baseUrl` | `https://api.kimi.com/coding/v1` | Override Kimi's API base URL |@@ -516,6 +517,12 @@ affecting other keys.`%LOCALAPPDATA%\claude-code-proxy\proxy.log` on Windows (falling back to`%USERPROFILE%\AppData\Local`). Secrets (`authorization`, `access`,`refresh`, `id_token`, `ChatGPT-Account-Id`, …) are redacted before write.+- `traffic/` — per-request captures written when `CCP_TRAFFIC_LOG=1` is set.+ Captures live under the state directory, grouped by Claude Code session and+ request sequence. They include inbound Anthropic requests, translated upstream+ requests, upstream headers, upstream events, and downstream events. Token and+ account headers are redacted, but prompt and tool content are intentionally+ preserved for debugging.- `config.json` — optional configuration file (see table above). It lives at`~/.config/claude-code-proxy/config.json` on macOS,`${XDG_CONFIG_HOME:-$HOME/.config}/claude-code-proxy/config.json` on Linux,diff --git a/src/log.ts b/src/log.tsindex 9dee9ce..cc5b060 100644--- a/src/log.ts+++ b/src/log.ts@@ -15,6 +15,8 @@ export const REDACT_KEYS = new Set(["code","code_verifier","chatgpt-account-id",+ "cookie",+ "set-cookie","x-api-key",]);diff --git a/src/providers/codex/client.ts b/src/providers/codex/client.tsindex 935010b..03cb9ee 100644--- a/src/providers/codex/client.ts+++ b/src/providers/codex/client.ts@@ -7,6 +7,7 @@ import type { Logger } from "../../log.ts";import type { RequestContext } from "../types.ts";import type { ResponsesRequest } from "./translate/request.ts";import { retryOn429, sleep } from "../retry.ts";+import { headersToRecord } from "../../traffic.ts";import { summarizeCodexRequestSize } from "./request-summary.ts";const FETCH_WATCHDOG_INTERVAL_MS = 30_000;@@ -79,13 +80,13 @@ async function attemptPostCodex(log: Logger,): Promise<CodexResponse> {let auth = await getAuth();- let resp = await doFetch(auth.access, auth.accountId, body, log, ctx.signal, ctx.sessionId);+ let resp = await doFetch(auth.access, auth.accountId, body, ctx, log);if (resp.status === 401) {log.warn("got 401, refreshing token", {});try {auth = await forceRefresh();- resp = await doFetch(auth.access, auth.accountId, body, log, ctx.signal, ctx.sessionId);+ resp = await doFetch(auth.access, auth.accountId, body, ctx, log);} catch (err) {log.error("refresh after 401 failed", { err: String(err) });}@@ -93,6 +94,7 @@ async function attemptPostCodex(if (resp.status === 403) {const text = await safeText(resp);+ ctx.traffic?.writeText("031-upstream-error-body", text);log.error("403 from upstream (non-refreshable)", { body: text });throw new CodexError(403, "Forbidden", text);}@@ -100,11 +102,13 @@ async function attemptPostCodex(if (resp.status === 429) {const retryAfter = resp.headers.get("retry-after") || undefined;const text = await safeText(resp);+ ctx.traffic?.writeText("031-upstream-error-body", text);throw new CodexError(429, "Rate limited", text, { retryAfter });}if (!resp.ok) {const text = await safeText(resp);+ ctx.traffic?.writeText("031-upstream-error-body", text);throw new CodexError(resp.status, "Upstream error", text);}@@ -117,9 +121,8 @@ async function doFetch(accessToken: string,accountId: string | undefined,body: ResponsesRequest,+ ctx: RequestContext,log: Logger,- signal?: AbortSignal,- sessionId?: string,): Promise<Response> {const headers = new Headers({"Content-Type": "application/json",@@ -131,16 +134,24 @@ async function doFetch(const userAgent = codexUserAgent(`claude-code-proxy/${PROXY_VERSION}`);if (userAgent) headers.set("User-Agent", userAgent);if (accountId) headers.set("ChatGPT-Account-Id", accountId);- if (sessionId) {- headers.set("session_id", sessionId);- headers.set("x-client-request-id", sessionId);- headers.set("x-codex-window-id", `${sessionId}:0`);+ if (ctx.sessionId) {+ headers.set("session_id", ctx.sessionId);+ headers.set("x-client-request-id", ctx.sessionId);+ headers.set("x-codex-window-id", `${ctx.sessionId}:0`);}const codexUrl = codexBaseUrl(CODEX_API_ENDPOINT);const bodyJson = JSON.stringify(body);const size = summarizeCodexRequestSize(body, bodyJson);+ ctx.traffic?.writeJson("020-upstream-request", body);+ ctx.traffic?.writeJson("021-upstream-request-metadata", {+ provider: "codex",+ url: codexUrl,+ method: "POST",+ headers: headersToRecord(headers),+ size,+ });log.debug("posting to codex", {url: codexUrl,@@ -166,8 +177,8 @@ async function doFetch(const timeout = setTimeout(() => {headerTimeout.abort(new CodexHeaderTimeoutError(fetchHeaderTimeoutMs));}, fetchHeaderTimeoutMs);- const onAbort = () => headerTimeout.abort(signal?.reason);- signal?.addEventListener("abort", onAbort, { once: true });+ const onAbort = () => headerTimeout.abort(ctx.signal.reason);+ ctx.signal.addEventListener("abort", onAbort, { once: true });try {const resp = await fetch(codexUrl, {method: "POST",@@ -175,9 +186,16 @@ async function doFetch(body: bodyJson,signal: headerTimeout.signal,});+ const elapsedMs = Date.now() - startedAt;+ ctx.traffic?.writeJson("030-upstream-response-headers", {+ status: resp.status,+ statusText: resp.statusText,+ elapsedMs,+ headers: headersToRecord(resp.headers),+ });log.debug("received codex response headers", {status: resp.status,- elapsedMs: Date.now() - startedAt,+ elapsedMs,});return resp;} catch (err) {@@ -186,7 +204,7 @@ async function doFetch(}throw err;} finally {- signal?.removeEventListener("abort", onAbort);+ ctx.signal.removeEventListener("abort", onAbort);clearTimeout(timeout);clearInterval(watchdog);}diff --git a/src/providers/codex/index.ts b/src/providers/codex/index.tsindex 42c3bf2..820c1fe 100644--- a/src/providers/codex/index.ts+++ b/src/providers/codex/index.ts@@ -304,6 +304,7 @@ async function handleMessages(body: AnthropicRequest, ctx: RequestContext): PromreqId: ctx.reqId,signal: ctx.signal,upstreamHeaders: upstream.headers,+ traffic: ctx.traffic,requestSize,onFinish: logVerbose()? (finish) => {@@ -350,6 +351,7 @@ async function handleMessages(body: AnthropicRequest, ctx: RequestContext): PrommessageId,model: body.model,log: ctx.childLogger("codex.accumulate"),+ traffic: ctx.traffic,});if (logVerbose()) {const { serverModel, serverReasoningIncluded } = upstreamHeaderSnapshot(upstream.headers);diff --git a/src/providers/codex/translate/accumulate.ts b/src/providers/codex/translate/accumulate.tsindex 480eeaa..4708ebb 100644--- a/src/providers/codex/translate/accumulate.ts+++ b/src/providers/codex/translate/accumulate.ts@@ -1,6 +1,8 @@import { mapUsageToAnthropic, reduceUpstream } from "./reducer.ts";import type { CodexUsage } from "./reducer.ts";import type { Logger } from "../../../log.ts";+import type { TrafficCapture } from "../../types.ts";+import { attachTrafficCapture, createUpstreamStreamDiagnostics } from "./reducer.ts";export { UpstreamStreamError } from "./reducer.ts";@@ -35,7 +37,7 @@ export interface AccumulatedResponse {*/export async function accumulateResponse(upstream: ReadableStream<Uint8Array>,- opts: { messageId: string; model: string; log: Logger },+ opts: { messageId: string; model: string; log: Logger; traffic?: TrafficCapture },): Promise<AccumulatedResponse> {type Block =| { kind: "text"; text: string }@@ -47,7 +49,9 @@ export async function accumulateResponse(let usage: ReturnType<typeof mapUsageToAnthropic> | undefined;let rawUsage: CodexUsage | undefined;- for await (const e of reduceUpstream(upstream, opts.log)) {+ const diagnostics = attachTrafficCapture(createUpstreamStreamDiagnostics(), opts.traffic);++ for await (const e of reduceUpstream(upstream, opts.log, diagnostics)) {switch (e.kind) {case "text-start":blocks.set(e.index, { kind: "text", text: "" });diff --git a/src/providers/codex/translate/reducer.ts b/src/providers/codex/translate/reducer.tsindex 7220d4b..5c69553 100644--- a/src/providers/codex/translate/reducer.ts+++ b/src/providers/codex/translate/reducer.ts@@ -1,6 +1,7 @@import { createSseStreamStats, parseSseStream, type SseStreamStats } from "../../../sse.ts";import type { Logger } from "../../../log.ts";import { logVerbose } from "../../../config.ts";+import type { TrafficCapture } from "../../types.ts";export class UpstreamStreamError extends Error {constructor(@@ -95,7 +96,10 @@ function toolArgJsonState(args: string): Record<string, unknown> {const parsed = JSON.parse(trimmed);return {parseOk: true,- parsedKeys: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? Object.keys(parsed) : undefined,+ parsedKeys:+ parsed && typeof parsed === "object" && !Array.isArray(parsed)+ ? Object.keys(parsed)+ : undefined,trimmedLength: trimmed.length,trailingWhitespace: args.length - trimmed.length,};@@ -131,7 +135,11 @@ function logBufferedToolProgress(log: Logger, state: ToolState, force = false):function throwIfBufferedToolExceeded(log: Logger, state: ToolState): void {if (!state.bufferUntilDone) return;const elapsedMs = Date.now() - state.startedAt;- if (state.argsAccum.length <= BUFFERED_TOOL_MAX_ARGS_BYTES && elapsedMs <= BUFFERED_TOOL_MAX_DURATION_MS) return;+ if (+ state.argsAccum.length <= BUFFERED_TOOL_MAX_ARGS_BYTES &&+ elapsedMs <= BUFFERED_TOOL_MAX_DURATION_MS+ )+ return;log.warn("buffered tool arguments exceeded safe limits", {outputIndex: state.outputIndex,index: state.index,@@ -185,6 +193,7 @@ export interface UpstreamStreamDiagnostics {stats: SseStreamStats;lastEventType?: string;sawTerminalEvent: boolean;+ traffic?: TrafficCapture;}export function createUpstreamStreamDiagnostics(): UpstreamStreamDiagnostics {@@ -194,6 +203,14 @@ export function createUpstreamStreamDiagnostics(): UpstreamStreamDiagnostics {};}+export function attachTrafficCapture(+ diagnostics: UpstreamStreamDiagnostics,+ traffic: TrafficCapture | undefined,+): UpstreamStreamDiagnostics {+ diagnostics.traffic = traffic;+ return diagnostics;+}+export async function* reduceUpstream(upstream: ReadableStream<Uint8Array>,log: Logger,@@ -217,6 +234,7 @@ export async function* reduceUpstream(}const t: string = p.type || evt.event || "";diagnostics.lastEventType = t;+ diagnostics.traffic?.writeJson("040-upstream-event", p);if (logVerbose())log.debug("upstream event", { type: t, output_index: p.output_index, item_id: p.item_id });diff --git a/src/providers/codex/translate/stream.ts b/src/providers/codex/translate/stream.tsindex c642af4..568613c 100644--- a/src/providers/codex/translate/stream.ts+++ b/src/providers/codex/translate/stream.ts@@ -3,8 +3,10 @@ import { join } from "node:path";import { stateDir } from "../../../paths.ts";import { encodeSseEvent } from "../../../sse.ts";import type { Logger } from "../../../log.ts";+import type { TrafficCapture } from "../../types.ts";import type { CodexRequestSizeSummary } from "../request-summary.ts";import {+ attachTrafficCapture,createUpstreamStreamDiagnostics,mapUsageToAnthropic,reduceUpstream,@@ -31,6 +33,7 @@ export function translateStream(reqId?: string;signal?: AbortSignal;upstreamHeaders?: Headers;+ traffic?: TrafficCapture;requestSize?: CodexRequestSizeSummary;onFinish?: (finish: {stopReason: "end_turn" | "tool_use" | "max_tokens";@@ -42,7 +45,7 @@ export function translateStream(return new ReadableStream<Uint8Array>({async start(controller) {const openBlocks = new Map<number, { type: "text" | "tool"; id?: string; name?: string }>();- const diagnostics = createUpstreamStreamDiagnostics();+ const diagnostics = attachTrafficCapture(createUpstreamStreamDiagnostics(), opts.traffic);let closed = false;let messageStarted = false;let lastEmitAt = 0;@@ -61,6 +64,7 @@ export function translateStream(const emit = (event: string, data: unknown) => {if (closed || opts.signal?.aborted || controller.desiredSize === null) return false;try {+ opts.traffic?.writeJson("050-downstream-event", { event, data });controller.enqueue(encoder.encode(encodeSseEvent(event, data)));lastEmitAt = Date.now();lastEmitEvent = event;diff --git a/src/providers/kimi/client.ts b/src/providers/kimi/client.tsindex 541e59b..3bf9c2c 100644--- a/src/providers/kimi/client.ts+++ b/src/providers/kimi/client.ts@@ -2,6 +2,7 @@ import { apiBaseUrl } from "./auth/constants.ts";import { commonHeaders } from "./auth/headers.ts";import { forceRefresh, getAuth, KimiAuthUnauthorizedError } from "./auth/manager.ts";import type { Logger } from "../../log.ts";+import { headersToRecord } from "../../traffic.ts";import type { RequestContext } from "../types.ts";import type { KimiChatRequest } from "./translate/request.ts";import { retryOn429 } from "../retry.ts";@@ -44,13 +45,13 @@ async function attemptPostKimi(): Promise<KimiResponse> {let auth = await getAuth();const requestStartTime = Date.now();- let resp = await doFetch(auth.access, body, log, ctx.signal);+ let resp = await doFetch(auth.access, body, ctx, log);if (resp.status === 401) {log.warn("got 401, refreshing token", {});try {auth = await forceRefresh();- resp = await doFetch(auth.access, body, log, ctx.signal);+ resp = await doFetch(auth.access, body, ctx, log);} catch (err) {if (err instanceof KimiAuthUnauthorizedError) {throw new KimiError(401, "Unauthorized", err.message);@@ -62,20 +63,29 @@ async function attemptPostKimi(if (resp.status === 429) {const retryAfter = resp.headers.get("retry-after") || undefined;const text = await safeText(resp);+ ctx.traffic?.writeText("031-upstream-error-body", text);throw new KimiError(429, "Rate limited", text, { retryAfter });}if (!resp.ok) {const text = await safeText(resp);+ ctx.traffic?.writeText("031-upstream-error-body", text);const type = resp.status === 401 || resp.status === 403 ? "Unauthorized" : "Upstream error";throw new KimiError(resp.status, type, text);}if (!resp.body) throw new KimiError(500, "Upstream returned no body");+ const timeToHeadersMs = Date.now() - requestStartTime;+ ctx.traffic?.writeJson("030-upstream-response-headers", {+ status: resp.status,+ statusText: resp.statusText,+ timeToHeadersMs,+ headers: headersToRecord(resp.headers),+ });log.debug("upstream response", {status: resp.status,- timeToHeadersMs: Date.now() - requestStartTime,+ timeToHeadersMs,});return { body: resp.body, status: resp.status, headers: resp.headers, requestStartTime };@@ -84,8 +94,8 @@ async function attemptPostKimi(async function doFetch(accessToken: string,body: KimiChatRequest,+ ctx: RequestContext,log: Logger,- signal?: AbortSignal,): Promise<Response> {const fp = await commonHeaders();const headers = new Headers({@@ -95,20 +105,30 @@ async function doFetch(...fp,});+ const url = `${apiBaseUrl()}/chat/completions`;const bodyJson = JSON.stringify(body);+ const requestBodyBytes = new TextEncoder().encode(bodyJson).length;+ ctx.traffic?.writeJson("020-upstream-request", body);+ ctx.traffic?.writeJson("021-upstream-request-metadata", {+ provider: "kimi",+ url,+ method: "POST",+ headers: headersToRecord(headers),+ requestBodyBytes,+ });log.debug("posting to kimi", {- url: `${apiBaseUrl()}/chat/completions`,+ url,model: body.model,messageCount: body.messages.length,toolCount: body.tools?.length ?? 0,- requestBodyBytes: new TextEncoder().encode(bodyJson).length,+ requestBodyBytes,});- return fetch(`${apiBaseUrl()}/chat/completions`, {+ return fetch(url, {method: "POST",headers,body: bodyJson,- signal,+ signal: ctx.signal,});}diff --git a/src/providers/kimi/index.ts b/src/providers/kimi/index.tsindex 61c9c49..087fcc6 100644--- a/src/providers/kimi/index.ts+++ b/src/providers/kimi/index.ts@@ -114,6 +114,7 @@ async function handleMessages(body: AnthropicRequest, ctx: RequestContext): Prommodel: body.model,log: ctx.childLogger("kimi.stream"),requestStartTime: upstream.requestStartTime,+ traffic: ctx.traffic,onFinish: (finish) => {const mappedUsage = finish.usage ? mapUsageToAnthropic(finish.usage) : undefined;log.debug("stream finish", {@@ -144,6 +145,7 @@ async function handleMessages(body: AnthropicRequest, ctx: RequestContext): PrommessageId,model: body.model,log: ctx.childLogger("kimi.accumulate"),+ traffic: ctx.traffic,});return new Response(JSON.stringify(result.response), {headers: { "content-type": "application/json" },diff --git a/src/providers/kimi/translate/accumulate.ts b/src/providers/kimi/translate/accumulate.tsindex 6ed7981..8708470 100644--- a/src/providers/kimi/translate/accumulate.ts+++ b/src/providers/kimi/translate/accumulate.ts@@ -1,5 +1,6 @@import { mapUsageToAnthropic, reduceUpstream, type KimiUsage } from "./reducer.ts";import { makeThinkingSignature } from "./signature.ts";+import type { TrafficCapture } from "../../types.ts";export { UpstreamStreamError } from "./reducer.ts";@@ -32,7 +33,7 @@ import type { Logger } from "../../../log.ts";export async function accumulateResponse(upstream: ReadableStream<Uint8Array>,- opts: { messageId: string; model: string; log: Logger },+ opts: { messageId: string; model: string; log: Logger; traffic?: TrafficCapture },): Promise<AccumulatedResponse> {type Block =| { kind: "thinking"; text: string }@@ -47,7 +48,7 @@ export async function accumulateResponse(let reasoningChars = 0;let contentChars = 0;let toolCount = 0;- const stats = { chunkCount: 0 };+ const stats = { chunkCount: 0, traffic: opts.traffic };for await (const e of reduceUpstream(upstream, stats, opts.log)) {switch (e.kind) {diff --git a/src/providers/kimi/translate/reducer.ts b/src/providers/kimi/translate/reducer.tsindex 511936a..83efe89 100644--- a/src/providers/kimi/translate/reducer.ts+++ b/src/providers/kimi/translate/reducer.ts@@ -1,5 +1,6 @@import { parseSseStream } from "../../../sse.ts";import type { Logger } from "../../../log.ts";+import type { TrafficCapture } from "../../types.ts";export class UpstreamStreamError extends Error {constructor(@@ -67,6 +68,7 @@ interface ToolSlot {*/export interface ReducerStats {chunkCount: number;+ traffic?: TrafficCapture;}export async function* reduceUpstream(@@ -117,7 +119,10 @@ export async function* reduceUpstream(continue;}- if (stats) stats.chunkCount++;+ if (stats) {+ stats.chunkCount++;+ stats.traffic?.writeJson("040-upstream-event", chunk);+ }if (chunk.error) {throw new UpstreamStreamError("failed", chunk.error.message || "Upstream error");diff --git a/src/providers/kimi/translate/stream.ts b/src/providers/kimi/translate/stream.tsindex 16b1b2b..bd037c7 100644--- a/src/providers/kimi/translate/stream.ts+++ b/src/providers/kimi/translate/stream.ts@@ -1,5 +1,6 @@import { encodeSseEvent } from "../../../sse.ts";import type { Logger } from "../../../log.ts";+import type { TrafficCapture } from "../../types.ts";import {mapUsageToAnthropic,reduceUpstream,@@ -25,6 +26,7 @@ export function translateStream(model: string;log: Logger;requestStartTime?: number;+ traffic?: TrafficCapture;onFinish?: (finish: {stopReason: "end_turn" | "tool_use" | "max_tokens";usage?: Parameters<typeof mapUsageToAnthropic>[0];@@ -35,6 +37,7 @@ export function translateStream(return new ReadableStream<Uint8Array>({async start(controller) {const emit = (event: string, data: unknown) => {+ opts.traffic?.writeJson("050-downstream-event", { event, data });controller.enqueue(encoder.encode(encodeSseEvent(event, data)));};const activeTools = new Map<number, { id: string; name: string }>();@@ -70,7 +73,7 @@ export function translateStream(let toolCount = 0;let finishUsage: KimiUsage | undefined;let finishStopReason: string | undefined;- const stats = { chunkCount: 0 };+ const stats = { chunkCount: 0, traffic: opts.traffic };try {for await (const e of reduceUpstream(upstream, stats, opts.log)) {diff --git a/src/providers/types.ts b/src/providers/types.tsindex d2e86a6..bafec63 100644--- a/src/providers/types.ts+++ b/src/providers/types.ts@@ -2,11 +2,18 @@ import type { AnthropicRequest } from "../anthropic/schema.ts";import type { Logger } from "../log.ts";+export interface TrafficCapture {+ writeJson(name: string, value: unknown): void;+ writeText(name: string, value: string): void;+ writeBytes(name: string, value: Uint8Array): void;+}+export interface RequestContext {reqId: string;sessionId?: string;sessionSeq?: number;signal: AbortSignal;+ traffic?: TrafficCapture;childLogger(service: string): Logger;}diff --git a/src/server.ts b/src/server.tsindex a7c314e..4e532cc 100644--- a/src/server.ts+++ b/src/server.ts@@ -1,4 +1,5 @@import { createLogger, logDir, REDACT_KEYS } from "./log.ts";+import { createTrafficCapture, headersToRecord } from "./traffic.ts";import type { AnthropicRequest } from "./anthropic/schema.ts";import type { AliasProvider } from "./config.ts";@@ -116,34 +117,37 @@ async function route(req: Request, url: URL, reqId: string): Promise<Response> {}if (req.method === "POST" && url.pathname === "/v1/messages/count_tokens") {- const body = await parseJsonBody(req);- if (body instanceof Response) return body;- const sessionId = req.headers.get("x-claude-code-session-id") || undefined;- const session = existingSession(sessionId);- const provider = routeProvider(body, reqId, session?.affinityProvider);- if (provider instanceof Response) return provider;- const current = recordSessionRequest(sessionId, session, provider.name, body.model);- const ctx = buildCtx(req, reqId, provider.name, sessionId, current);- ctx.childLogger("server").info("dispatch", { model: body.model });- return provider.handleCountTokens(body, ctx);+ return routeAnthropicPost(req, url, reqId, "count_tokens");}if (req.method === "POST" && url.pathname === "/v1/messages") {- const body = await parseJsonBody(req);- if (body instanceof Response) return body;- const sessionId = req.headers.get("x-claude-code-session-id") || undefined;- const session = existingSession(sessionId);- const provider = routeProvider(body, reqId, session?.affinityProvider);- if (provider instanceof Response) return provider;- const current = recordSessionRequest(sessionId, session, provider.name, body.model);- const ctx = buildCtx(req, reqId, provider.name, sessionId, current);- ctx.childLogger("server").info("dispatch", { model: body.model });- return provider.handleMessages(body, ctx);+ return routeAnthropicPost(req, url, reqId, "messages");}return jsonError(404, "not_found", `No route for ${req.method} ${url.pathname}`);}+async function routeAnthropicPost(+ req: Request,+ url: URL,+ reqId: string,+ kind: "messages" | "count_tokens",+): Promise<Response> {+ const body = await parseJsonBody(req);+ if (body instanceof Response) return body;+ const sessionId = req.headers.get("x-claude-code-session-id") || undefined;+ const session = existingSession(sessionId);+ const provider = routeProvider(body, reqId, session?.affinityProvider);+ if (provider instanceof Response) return provider;+ const current = recordSessionRequest(sessionId, session, provider.name, body.model);+ const ctx = buildCtx(req, reqId, provider.name, sessionId, current);+ captureInboundTraffic(ctx, req, url, body, kind, provider.name);+ ctx.childLogger("server").info("dispatch", { model: body.model });+ return kind === "messages"+ ? provider.handleMessages(body, ctx)+ : provider.handleCountTokens(body, ctx);+}+function buildCtx(req: Request,reqId: string,@@ -158,10 +162,35 @@ function buildCtx(sessionId,sessionSeq,signal: req.signal,+ traffic: createTrafficCapture({ reqId, sessionId, sessionSeq, provider: providerName }),childLogger: (service) => createLogger(service, bindings),};}+function captureInboundTraffic(+ ctx: RequestContext,+ req: Request,+ url: URL,+ body: AnthropicRequest,+ kind: "messages" | "count_tokens",+ provider: string,+): void {+ if (!ctx.traffic) return;+ ctx.traffic.writeJson("000-metadata", {+ reqId: ctx.reqId,+ sessionId: ctx.sessionId,+ sessionSeq: ctx.sessionSeq,+ kind,+ provider,+ model: body.model,+ method: req.method,+ path: url.pathname,+ query: redactedQuery(url),+ headers: headersToRecord(req.headers),+ });+ ctx.traffic.writeJson("010-anthropic-request", body);+}+// Claude Code uses a [1m] suffix convention (e.g. "gpt-5.4[1m]") to// signal that the model should be treated as having a 1M-token context// window. Claude Code normalizes this away before sending requests todiff --git a/src/traffic.ts b/src/traffic.tsnew file mode 100644index 0000000..0e07d71--- /dev/null+++ b/src/traffic.ts@@ -0,0 +1,92 @@+import { mkdir, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { stateDir } from "./paths.ts";+import { REDACT_KEYS } from "./log.ts";+import type { TrafficCapture } from "./providers/types.ts";++const encoder = new TextEncoder();++export function trafficCaptureEnabled(env = process.env): boolean {+ const value = env.CCP_TRAFFIC_LOG;+ return value === "1" || value === "true" || value === "yes";+}++export function createTrafficCapture(opts: {+ reqId: string;+ sessionId?: string;+ sessionSeq?: number;+ provider?: string;+}): TrafficCapture | undefined {+ if (!trafficCaptureEnabled()) return undefined;+ const sessionPart = sanitizePathPart(opts.sessionId || "no-session");+ const seqPart = String(opts.sessionSeq ?? 0).padStart(6, "0");+ const providerPart = sanitizePathPart(opts.provider || "unknown-provider");+ const reqPart = sanitizePathPart(opts.reqId);+ const dir = join(stateDir(), "traffic", sessionPart, `${seqPart}-${providerPart}-${reqPart}`);+ let counter = 0;++ const filePath = (name: string) => {+ counter += 1;+ return join(dir, `${String(counter).padStart(3, "0")}-${sanitizePathPart(name)}`);+ };++ return {+ writeJson(name, value) {+ const path = filePath(ensureExtension(name, ".json"));+ void writeCaptureFile(path, JSON.stringify(redactTraffic(value), null, 2));+ },+ writeText(name, value) {+ const path = filePath(ensureExtension(name, ".txt"));+ void writeCaptureFile(path, value);+ },+ writeBytes(name, value) {+ const path = filePath(name);+ void writeCaptureFile(path, value);+ },+ };+}++export function headersToRecord(headers: Headers): Record<string, string> {+ const out: Record<string, string> = {};+ for (const [key, value] of headers) out[key] = value;+ return out;+}++function redactTraffic(value: unknown, depth = 0): unknown {+ if (depth > 100) return "[depth-limit]";+ if (value == null) return value;+ if (typeof value !== "object") return value;+ if (Array.isArray(value)) return value.map((item) => redactTraffic(item, depth + 1));+ const out: Record<string, unknown> = {};+ for (const [key, child] of Object.entries(value as Record<string, unknown>)) {+ out[key] = REDACT_KEYS.has(key.toLowerCase())+ ? redactValue(child)+ : redactTraffic(child, depth + 1);+ }+ return out;+}++function redactValue(value: unknown): string {+ if (typeof value === "string") return `[redacted len=${value.length}]`;+ return "[redacted]";+}++async function writeCaptureFile(path: string, value: string | Uint8Array): Promise<void> {+ try {+ await mkdir(dirname(path), { recursive: true });+ await writeFile(path, typeof value === "string" ? encoder.encode(value) : value, {+ mode: 0o600,+ });+ } catch {+ // Traffic capture must not affect request handling.+ }+}++function sanitizePathPart(value: string): string {+ const sanitized = value.replace(/[^a-zA-Z0-9._-]/g, "_");+ return sanitized.slice(0, 160) || "unknown";+}++function ensureExtension(name: string, extension: string): string {+ return name.endsWith(extension) ? name : `${name}${extension}`;+}