Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion scripts/test-layout/layout.json
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@
"claude-manual-env.test.ts": "gui",
"claude-messages-endpoint.test.ts": "claude-integration",
"claude-messages-thread.test.ts": "claude-integration",
"messages-native.test.ts": "claude-integration",
"messages-native.test.ts": "claude-integration", "messages-shared-sse.test.ts": "claude-integration",
"messages-native-decline-trace.test.ts": "claude-integration",
"messages-native-oauth.test.ts": "claude-integration",
"messages-native-opaque-state.test.ts": "claude-integration",
Expand Down
74 changes: 57 additions & 17 deletions src/server/messages-shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,31 @@ export function tapAnthropicSseForLog(
): ReadableStream<Uint8Array> {
const decoder = new TextDecoder();
const encoder = new TextEncoder();
let buffer = "";
let frameParts: string[] = [];
let pendingParts: string[] = [];
let pendingChars = 0;
let heldCr = false;
let heldLf = false;
const appendPart = (part: string) => {
if (!part) return;
pendingParts.push(part);
pendingChars += part.length;
// Coalesce tiny transport fragments: a one-byte feed must not retain one array
// entry per byte for the entire event. Each character is joined at most twice.
if (pendingChars >= 4096) {
frameParts.push(pendingParts.join(""));
pendingParts = [];
pendingChars = 0;
}
};
const takeFrame = () => {
if (pendingParts.length) frameParts.push(pendingParts.join(""));
const frame = frameParts.join("");
frameParts = [];
pendingParts = [];
pendingChars = 0;
return frame;
};
let usageAcc: Rec = {};
// message_stop or an upstream error event: the turn's own terminal already went through.
let terminalSeen = false;
Expand Down Expand Up @@ -156,17 +180,29 @@ export function tapAnthropicSseForLog(
}
};
const inspect = (chunk: Uint8Array) => {
buffer += decoder.decode(chunk, { stream: true });
// SSE lines may end in CRLF, LF or CR. Normalize the inspection copy to LF (the forwarded
// bytes are untouched), holding a trailing CR until the next chunk shows whether an LF
// follows it, so a CRLF split across chunks stays one line ending.
const heldCr = buffer.endsWith("\r");
buffer = (heldCr ? buffer.slice(0, -1) : buffer).replace(/\r\n?/g, "\n") + (heldCr ? "\r" : "");
// Normalize and scan only new text. Keep an unfinished frame in fragments so a long
// SSE event arriving in small chunks is never flattened or rescanned on each read.
let text = (heldCr ? "\r" : "") + decoder.decode(chunk, { stream: true });
heldCr = text.endsWith("\r");
text = (heldCr ? text.slice(0, -1) : text).replace(/\r\n?/g, "\n");
let start = 0;
if (text && heldLf) {
heldLf = false;
if (text[0] === "\n") {
inspectFrame(takeFrame());
start = 1;
} else appendPart("\n");
}
let sep: number;
while ((sep = buffer.indexOf("\n\n")) !== -1) {
const frame = buffer.slice(0, sep);
buffer = buffer.slice(sep + 2);
inspectFrame(frame);
while ((sep = text.indexOf("\n\n", start)) !== -1) {
appendPart(text.slice(start, sep));
inspectFrame(takeFrame());
start = sep + 2;
}
if (start < text.length) {
heldLf = text.endsWith("\n");
const end = text.length - (heldLf ? 1 : 0);
appendPart(text.slice(start, end));
}
};
// The last block can sit in the buffer without its blank line: an upstream that stopped after
Expand All @@ -175,14 +211,18 @@ export function tapAnthropicSseForLog(
// client has not seen a blank line after, so the caller restores one. tailClean: nothing but
// comments or a ping is left undelimited, so no message event was cut off.
const flushTail = (): { terminalInTail: boolean; tailClean: boolean } => {
// At EOF a held CR is a line ending, so it can complete a frame the client already has.
let tail = (buffer + decoder.decode()).replace(/\r\n?/g, "\n");
buffer = "";
// Rebuild the unscanned text in wire order (fragments, held LF, held CR). At EOF a held CR is
// a line ending, so it can complete a frame the client already has.
const rest = (takeFrame() + (heldLf ? "\n" : "") + (heldCr ? "\r" : "") + decoder.decode()).replace(/\r\n?/g, "\n");
heldCr = false;
heldLf = false;
let start = 0;
let sep: number;
while ((sep = tail.indexOf("\n\n")) !== -1) {
inspectFrame(tail.slice(0, sep));
tail = tail.slice(sep + 2);
while ((sep = rest.indexOf("\n\n", start)) !== -1) {
inspectFrame(rest.slice(start, sep));
start = sep + 2;
}
const tail = rest.slice(start);
const terminalBefore = terminalSeen;
if (tail) inspectFrame(tail, false);
return {
Expand Down
2 changes: 1 addition & 1 deletion structure/clients/claude-desktop.md
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,7 @@ Native Anthropic passthrough in `src/server/claude-messages.ts` forwards the cal

Native passthrough retains upstream `anthropic-ratelimit-*` response headers for Claude Code quota/statusLine consumers on SSE, JSON and upstream errors. `src/server/anthropic-rate-limit-headers.ts` selects only that family instead of copying all upstream headers, so cookies and unrelated metadata are not relayed. Missing rate-limit headers are not fabricated; body, status, content type and existing non-stream `Retry-After` behavior stay unchanged. `tests/claude-integration/claude-native-rate-limit-headers.test.ts` exercises the production ingress against a synthetic upstream for all four response shapes (SSE, JSON, upstream error and count_tokens).

`tapAnthropicSseForLog` in `src/server/messages-shared.ts` (re-exported by `src/server/claude-messages.ts`) relays the streamed body of both the native passthrough and the managed native Messages lane (`src/server/messages-native.ts`). The response headers are already sent, so a stall, a byte-cap overflow, or an upstream read failure ends the body with an Anthropic `event: error` frame after a blank-line boundary and a clean close: `timeout_error` for an idle stall, `api_error` for the byte cap, and `api_error` when an upstream read fails mid-stream (a socket reset). The mid-stream reset is logged like the Responses relay's read error: status 502, `terminalStatus: "failed"`, `closeReason: "terminal"`, `transportPhase: "mid_stream"`, a synthetic terminal source, the attempt marked `streamAborted`, the redacted reason in `upstreamError`, and the usage seen before the reset. The non-streaming fold in the managed lane closes its row with the tap's meta for a reset, a stall or the byte cap, so its row matches the streaming lane's. The request is not replayed. Every one of these frames logs status 502. A stall is `terminalStatus: "incomplete"` with `closeReason: "body_stall"`, the status the Responses relay gives a stall-timeout incomplete. The byte cap is `incomplete` with `closeReason: "body_overflow"`, the same 502 the non-stream passthrough answers for it. Both carry the proxy's message in `upstreamError`, and a reset is `terminalStatus: "failed"`. Either way the row keeps its failure diagnostics in usage.jsonl. A stall or overflow after the turn's own terminal (`message_stop` or an upstream `error` event) is a finished turn: it logs 200 and closes without an error frame, as the read-error branch does. The tap finds frames in a copy normalized to LF, because SSE lines may end in CRLF, LF or CR; it holds a trailing CR until the next chunk so a split CRLF stays one line ending, and forwards the original bytes unchanged. Some read failures are not upstream failures. When the cancel signal is already aborted, the rejection is a `499` client cancel, because Bun can reject the read before it dispatches the abort listener. The managed lane passes its upstream controller's signal, so shutdown and turn release count as cancels too. When `message_stop` or an upstream `error` event has been seen, including one still in the buffer without its blank-line delimiter, the turn is complete: it logs 200 and closes with no error frame. A terminal found only in that unterminated tail gets its blank line restored, because an SSE parser drops an event that EOF cuts off. A translator budget overflow is a local cap, so it still errors the stream, and the non-streaming fold answers it with 413. `tests/claude-integration/claude-native-passthrough.test.ts` and `tests/claude-integration/messages-native.test.ts` cover both lanes against an upstream that resets after a partial or a complete body, plus both cancel paths. A clean upstream EOF (no reset) ends the turn only when the client already has its terminal (`message_stop` or an upstream `error` event), or when the last message event it received as a complete SSE event was a `message_delta` with a non-error `stop_reason` and nothing but whitespace, comments or a ping follows it undelimited: compatible providers may omit `message_stop`, and the translated adapter accepts the same shape. Those bytes are relayed unchanged and log 200. Every other clean EOF is a cut turn and fails exactly like a mid-stream reset (502, `terminalStatus: "failed"`, `transportPhase: "mid_stream"`, `streamAborted`, an `api_error` frame): a partial body, an EOF after `stop_reason: "error"`, a stop reason left undelimited in the tail, or a message event cut off after an earlier stop reason (later content clears an earlier stop reason). A frame counts as evidence only when its payload `type` and its `event` name agree or the event line is absent, so a `ping`-named frame carrying a `message_stop` payload is not a terminal. In the managed lane, a routed provider with `anthropicEofTolerance` keeps a content-only EOF (no stop reason, nothing cut) as a finished turn, while caller-forward passthrough treats it as a failed turn; an error stop reason or a cut tail fails on both lanes. A done read after the cancel signal aborted is a 499 client cancel, the same rule as a rejected read. The non-streaming fold (`collectAnthropicMessage` in `src/claude/outbound.ts`) frames on a CRLF/CR-normalized copy and names a data-only frame by its payload type, so CRLF and data-only streams fold with their content. `tests/claude-integration/messages-native-clean-eof.test.ts` covers the tap's verdict for each EOF shape, the cancel race, the fold, and the managed lane end to end.
`tapAnthropicSseForLog` in `src/server/messages-shared.ts` (re-exported by `src/server/claude-messages.ts`) relays the streamed body of both the native passthrough and the managed native Messages lane (`src/server/messages-native.ts`). The response headers are already sent, so a stall, a byte-cap overflow, or an upstream read failure ends the body with an Anthropic `event: error` frame after a blank-line boundary and a clean close: `timeout_error` for an idle stall, `api_error` for the byte cap, and `api_error` when an upstream read fails mid-stream (a socket reset). The mid-stream reset is logged like the Responses relay's read error: status 502, `terminalStatus: "failed"`, `closeReason: "terminal"`, `transportPhase: "mid_stream"`, a synthetic terminal source, the attempt marked `streamAborted`, the redacted reason in `upstreamError`, and the usage seen before the reset. The non-streaming fold in the managed lane closes its row with the tap's meta for a reset, a stall or the byte cap, so its row matches the streaming lane's. The request is not replayed. Every one of these frames logs status 502. A stall is `terminalStatus: "incomplete"` with `closeReason: "body_stall"`, the status the Responses relay gives a stall-timeout incomplete. The byte cap is `incomplete` with `closeReason: "body_overflow"`, the same 502 the non-stream passthrough answers for it. Both carry the proxy's message in `upstreamError`, and a reset is `terminalStatus: "failed"`. Either way the row keeps its failure diagnostics in usage.jsonl. A stall or overflow after the turn's own terminal (`message_stop` or an upstream `error` event) is a finished turn: it logs 200 and closes without an error frame, as the read-error branch does. The tap normalizes and scans only newly decoded text, holding a trailing CR and LF across reads so split CRLF and blank-line delimiters stay intact; it forwards the original bytes unchanged. Unfinished frames remain in fragments and are joined only at a frame boundary or tail flush. Tiny fragments are coalesced after at least 4096 code units, avoiding one retained array entry per byte on one-byte feeds. Each code unit is normalized once and joined at most twice; `tests/claude-integration/messages-shared-sse.test.ts` checks the linear work budget, tiny-fragment coalescing, split UTF-8 and line endings, usage, terminal-tail repair, byte caps and cancellation. At a clean EOF or a stall/reset flush, the held LF and CR rejoin the fragments in wire order and a held CR counts as a line ending; every frame that completes there is inspected as a complete event, and only the remainder after the last blank line is the undelimited tail. Some read failures are not upstream failures. When the cancel signal is already aborted, the rejection is a `499` client cancel, because Bun can reject the read before it dispatches the abort listener. The managed lane passes its upstream controller's signal, so shutdown and turn release count as cancels too. When `message_stop` or an upstream `error` event has been seen, including one still in the buffer without its blank-line delimiter, the turn is complete: it logs 200 and closes with no error frame. A terminal found only in that unterminated tail gets its blank line restored, because an SSE parser drops an event that EOF cuts off. A translator budget overflow is a local cap, so it still errors the stream, and the non-streaming fold answers it with 413. `tests/claude-integration/claude-native-passthrough.test.ts` and `tests/claude-integration/messages-native.test.ts` cover both lanes against an upstream that resets after a partial or a complete body, plus both cancel paths. A clean upstream EOF (no reset) ends the turn only when the client already has its terminal (`message_stop` or an upstream `error` event), or when the last message event it received as a complete SSE event was a `message_delta` with a non-error `stop_reason` and nothing but whitespace, comments or a ping follows it undelimited: compatible providers may omit `message_stop`, and the translated adapter accepts the same shape. Those bytes are relayed unchanged and log 200. Every other clean EOF is a cut turn and fails exactly like a mid-stream reset (502, `terminalStatus: "failed"`, `transportPhase: "mid_stream"`, `streamAborted`, an `api_error` frame): a partial body, an EOF after `stop_reason: "error"`, a stop reason left undelimited in the tail, or a message event cut off after an earlier stop reason (later content clears an earlier stop reason). A frame counts as evidence only when its payload `type` and its `event` name agree or the event line is absent, so a `ping`-named frame carrying a `message_stop` payload is not a terminal. In the managed lane, a routed provider with `anthropicEofTolerance` keeps a content-only EOF (no stop reason, nothing cut) as a finished turn, while caller-forward passthrough treats it as a failed turn; an error stop reason or a cut tail fails on both lanes. A done read after the cancel signal aborted is a 499 client cancel, the same rule as a rejected read. The non-streaming fold (`collectAnthropicMessage` in `src/claude/outbound.ts`) frames on a CRLF/CR-normalized copy and names a data-only frame by its payload type, so CRLF and data-only streams fold with their content. `tests/claude-integration/messages-native-clean-eof.test.ts` covers the tap's verdict for each EOF shape, the cancel race, the fold, and the managed lane end to end.

A native passthrough answered without a stream records its reason in `upstreamError`, so the row and the failure diagnostics in usage.jsonl name the cause. An upstream error response (status 400 or above) is relayed verbatim; the stored diagnostic is `Provider error <status>: <type>` only for a valid Anthropic error envelope with one of the closed types `invalid_request_error`, `authentication_error`, `permission_error`, `not_found_error`, `rate_limit_error`, `api_error`, `overloaded_error` or `request_too_large`. Upstream messages and arbitrary type strings never enter this diagnostic. Unknown or malformed envelopes, non-JSON bodies and bodies over 64 Ki characters log `Provider error <status>`. Local header timeout, body stall, byte-cap overflow and cancel diagnostics contain fixed text plus validated guard limits. Fetch failures log the fixed reason `anthropic passthrough failed: upstream connection error`; the existing redacted client response is preserved. Classification uses these stored reasons and HTTP status, so a `permission_error` at 403 is `permission_denied` regardless of upstream message wording. `tests/claude-integration/claude-native-passthrough.test.ts` covers these cases and checks that echoed account identifiers and request content are absent from both history sinks.

Expand Down
Loading
Loading