Files
claude-code/src/cli/transports/SSETransport.ts
Dosion c2ac9a74c1 fix: resolve dependency audit findings precisely (#361)
* fix: harden ACP communication boundaries

Harden ACP communication boundaries

Remote ACP sessions now cannot widen permission mode through untrusted
metadata or client payloads. WebSocket ACP ingress measures payloads by bytes
before binary decode, and prompt queue handoff keeps exactly one prompt active
while queued prompts are drained FIFO.

Constraint: ACP remote clients must not be able to open bypassPermissions without local launch intent
Constraint: WebSocket payload limits must be byte-based and checked before binary decode
Rejected: Keep promptToQueryContent wrapper | no production consumers remained after prompt conversion single-sourcing
Confidence: high
Scope-risk: moderate
Directive: Do not re-enable remote bypassPermissions from _meta unless a local launch gate is verified in both acp-link and agent
Tested: targeted ACP/RCS/acp-link prompt queue, bridge, permission, payload, and prompt conversion tests; bun run typecheck; bun run build
Not-tested: Manual live ACP/RCS session against an external client

* fix: restore repository verification gates

Keep the full repository test, typecheck, build, and Biome lint gates usable
after the ACP fix pass. This commit is intentionally separate from the ACP
behavior change: it fixes Windows-safe Langfuse home redaction, removes stale
lint suppressions, resolves Biome warning/info diagnostics, and keeps env
expansion tests explicit without template-placeholder lint noise.

Constraint: The project completion contract requires full typecheck, lint, test, and build evidence
Rejected: Leave warning/info diagnostics as historical noise | they obscure future gate regressions and weaken flow-impact claims
Confidence: high
Scope-risk: narrow
Directive: Keep repository gate cleanup separate from feature fixes when it is not part of the same runtime path
Tested: bunx biome lint src/; bunx tsc --noEmit; bun test src/services/mcp/__tests__/envExpansion.test.ts src/utils/__tests__/sliceAnsi.test.ts src/utils/__tests__/stringUtils.test.ts; bun test; bun run build
Not-tested: Manual Langfuse export against a real external Langfuse service

* fix: harden ACP failure boundaries after review

Deep review found several paths that made ACP communication failures look normal: prompt errors could finish as end_turn, permission pipeline exceptions could fall through to client approval, tool rawInput was deep-copied with JSON, and acp-link accepted unbounded or unvalidated WebSocket payloads. This keeps the behavior fail-closed, validates WS payloads before dispatch, caps payload size before JSON parse, and preserves cancellation intent with a generation counter.

Constraint: User explicitly rejected pseudo-fixes, fallback behavior, and unbounded payload handling

Rejected: Keep JSON stringify/parse rawInput copy | duplicates large payloads and silently drops non-JSON inputs

Rejected: Delegate permission pipeline errors to client approval | allows a broken local permission check to be bypassed

Confidence: high

Scope-risk: moderate

Directive: Do not convert ACP errors into normal end_turn responses without a protocol-level reason and regression tests

Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts

Tested: bun test packages/acp-link/src/__tests__/server.test.ts

Tested: bunx tsc --noEmit

Tested: bunx biome lint src/ packages/acp-link/src/

Tested: bun run test:all

Tested: bun run build

Not-tested: Manual end-to-end ACP client session over a real editor WebSocket

* fix: prevent ACP coverage runs from seeing partial mocks

GitHub Actions failed under bun test --coverage because permissions.test.ts replaced ../bridge.js with a partial mock that omitted forwardSessionUpdates. Coverage worker ordering on Linux let sibling tests observe that incomplete module.

This isolates ACP test mocks by snapshotting real exports, overriding only requested symbols, and restoring mocks in LIFO order. The shared helper also keeps the same behavior in agent.test.ts without duplicating mock infrastructure.

Constraint: bun:test mock.module is process-global inside a worker.

Rejected: Add fallback exports or production guards | the bridge export exists; the failure was test mock pollution.

Rejected: Keep per-file helper copies | duplication would let restore semantics drift again.

Confidence: high

Scope-risk: narrow

Directive: Prefer safeMockModule for partial mocks of real modules in ACP tests; plain mock.module is only appropriate for fully synthetic modules or isolated tests.

Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts

Tested: bun test --coverage --coverage-reporter=lcov

Tested: bunx tsc --noEmit

Tested: bun run lint

Tested: git diff --check

Not-tested: Linux runner directly before push

* fix: normalize ACP bypass requests without warning noise

The previous CI repair removed the failing partial bridge mock, but it also added a shared safeMockModule helper and left the acp-link bypass normalization warning in the real new_session path.

This tightens the fix: acp-link now treats an unauthorized client bypass request as normal permission-mode normalization without emitting a warning, and the ACP permission test explicitly preserves the real bridge and permission exports instead of using a shared helper. The agent test keeps its local mock preservation but names it by behavior and restores mocks in LIFO order.

Constraint: CI output should not contain expected warning noise for covered policy branches.

Rejected: Silence the test only | the normal new_session path would still warn for an expected normalization branch.

Rejected: Keep the shared safeMockModule helper | the failing module was specific and should be fixed by preserving real exports at the mocking site.

Confidence: high

Scope-risk: narrow

Directive: Treat client-requested bypassPermissions as data to normalize unless the local default explicitly enables bypass.

Tested: bun test packages/acp-link/src/__tests__/server.test.ts

Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts

Tested: bun test --coverage --coverage-reporter=lcov with UPPER_WARN_COUNT=0

Tested: bun run test:all

Tested: bun run lint

Tested: bunx tsc --noEmit

Tested: git diff --check

* fix: harden ACP bypass and CI warning gates

ACP clients must not be able to enter bypassPermissions unless the local ACP gate and process environment both allow it. The same gate now controls session creation, explicit mode changes, and the ExitPlanMode option list, while session setup restores process.cwd so coverage and later work do not inherit ACP session state.

Constraint: CI must stay warning-clean without hiding real ACP permission failures

Rejected: Logging rejected bypass requests on the normal new_session path | it preserves audit text but reintroduces warning noise the runtime should not emit

Rejected: Broad CI=true postinstall skip | it hides explicit Chrome MCP setup checks outside the install path

Confidence: high

Scope-risk: moderate

Directive: Keep bypassPermissions gated through one ACP availability decision before exposing it to clients

Tested: bun test src/services/acp/__tests__/permissions.test.ts src/services/acp/__tests__/agent.test.ts packages/acp-link/src/__tests__/server.test.ts

Tested: bun run test:all

Tested: bun run lint

Tested: bun run build:vite with zero warning matches

Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage produced non-empty lcov with SF records and zero filtered warning matches

Not-tested: GitHub Actions result after this push

* fix: remove remaining CI warning noise

The CI log still had three non-failing warnings after the ACP hardening commit: git init default-branch advice from checkout, a Node 20 action-runtime deprecation, and one additional known Vite dynamic-import diagnostic that only surfaced on Linux. The workflow now provides explicit git config and opts actions into Node 24, while Vite keeps a narrow allowlist for acknowledged optimizer diagnostics.

Constraint: Do not use shell log filtering to hide warnings after they happen

Rejected: Grep warning lines out of CI output | it would make future diagnostics harder to find

Confidence: high

Scope-risk: narrow

Directive: Add new Vite warning allowlist entries only after checking that they are existing optimizer diagnostics, not new application defects

Tested: bunx tsc --noEmit --pretty false

Tested: bunx biome lint .github/workflows/ci.yml vite.config.ts

Tested: bun run build:vite with zero warning matches

Not-tested: GitHub Actions result after this push

* fix: reject unauthorized ACP bypass and harden CI actions

ACP clients now fail closed when permissionMode is malformed, unknown, or requests bypass without a local bypass opt-in. acp-link validates new_session input before forwarding to the agent and returns client error frames for expected unauthorized requests without logging create-failed noise. The direct AcpAgent path independently rejects invalid _meta.permissionMode and unauthorized bypass instead of falling back to settings.

CI workflows and generated GitHub App templates now use Node 24-compatible actions pinned to immutable commit SHAs, and acp-link startup output no longer prints the auth token.

Constraint: Must not hide warnings with test isolation or log filtering

Rejected: Silent fallback to local permission mode | accepts invalid client intent and masks boundary behavior

Rejected: Broad dependency churn from bun update | audit remained failing while package and lockfile churn expanded scope

Confidence: high

Scope-risk: moderate

Directive: Client-provided permissionMode must stay fail-closed before reaching AcpAgent; only local settings.defaultMode may fall back to default on invalid local config

Tested: bun test packages/acp-link/src/__tests__/server.test.ts src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/permissions.test.ts src/services/skillLearning/__tests__/skillLifecycle.test.ts src/utils/settings/__tests__/config.test.ts

Tested: bunx tsc -p packages/acp-link/tsconfig.json --noEmit --pretty false

Tested: bunx tsc --noEmit --pretty false

Tested: bun run lint

Tested: bun run test:all

Tested: local CI equivalent install/typecheck/coverage/build with warning_scan=0

Not-tested: Pre-existing bun audit vulnerabilities require a separate dependency-hardening PR

* fix: resolve dependency audit findings precisely

Use dependency-native upgrades and lockfile resolution to close the audit findings without suppressions. Keep the chrome MCP setup aligned with the new dependency graph and add real integration coverage so the override behavior stays verified.

Constraint: no audit ignores or warning suppression
Rejected: broad google-auth/protobuf overrides | replaced with upstream-compatible resolution
Confidence: high
Scope-risk: moderate
Directive: keep dependency fixes upstream-compatible; do not reintroduce blanket overrides unless the audit surface changes materially
Tested: bun audit; bun audit --json; bun install --frozen-lockfile with CLAUDE_CODE_SKIP_CHROME_MCP_SETUP=1; bunx tsc --noEmit --pretty false; bun run lint; targeted tests; bun run test:all; bun test --coverage --coverage-reporter lcov --coverage-dir coverage; bun run build:vite
Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks

* fix: keep ACP auth tokens out of URLs

Replace the ad hoc URL-token flow with crypto UUID-backed transport identifiers so the bearer token stays in structured request data instead of query strings. Keep the server, web client, and transport helpers aligned so the ACP/RCS handshake remains compatible after the API shape change.

Constraint: token must not be embedded in the URL
Rejected: token-as-uuid query fallback | leaked bearer tokens in URLs
Confidence: high
Scope-risk: moderate
Directive: preserve the structured auth path; do not reintroduce query-token fallback when adjusting ACP transport code
Tested: targeted ACP/RCS transport tests
Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks

* fix: normalize WebFetch request headers

Normalize WebFetch headers before dispatch so canonicalization preserves auth semantics and duplicate forms do not slip through. Keep the behavior locked with a focused header test instead of broadening the request pipeline.

Constraint: preserve header semantics without widening the fetch surface
Rejected: ad hoc caller-side normalization | too easy to bypass in future call sites
Confidence: high
Scope-risk: narrow
Directive: keep header normalization close to the WebFetch utility so future callers inherit the same behavior automatically
Tested: targeted WebFetch header tests
Not-tested: unrelated fetch backend behavior beyond header normalization

* fix: harden ACP remote auth surfaces

Tighten the remaining Claude security artifact items by requiring API keys on ACP global reads and relay upgrades, moving WebSocket tokens out of URLs, and replacing open web CORS with an explicit allowlist.

Constraint: Browser WebSocket clients cannot set arbitrary Authorization headers, so the token is carried in a selected subprotocol instead of a query string.
Rejected: Keep UUID auth for ACP channel groups | any caller can mint a UUID and read global ACP data.
Rejected: Preserve ?token= compatibility | secrets leak into logs, history, referrers, and intermediaries.
Confidence: high
Scope-risk: moderate
Directive: Do not reintroduce query-string bearer tokens; use Authorization or rcs.auth.<base64url-token>.
Tested: bunx tsc --noEmit --pretty false
Tested: bun run typecheck in packages/remote-control-server
Tested: bun run build in packages/acp-link
Tested: bun run lint
Tested: bun audit
Tested: focused RCS/acp-link/web tests, 160 pass
Tested: Edge headless browser WebSocket subprotocol handshake
Tested: bun run test:all, 3669 pass
Tested: bun run build:vite
Tested: bun run build
Not-tested: Manual end-to-end relay with a live external ACP agent

* fix: resolve CI dependency override lookup

The CI runner does not expose @grpc/proto-loader as a root-resolvable package, and the test was relying on local hoisting rather than the real dependency owner. Resolve proto-loader through @opentelemetry/exporter-trace-otlp-grpc and @grpc/grpc-js so the smoke test follows the package graph it is validating.

Constraint: Do not add a new root dependency for a transitive smoke test.

Rejected: Skip or weaken the test | the test protects the protobuf 7 override path and should keep exercising loadSync.

Rejected: Add @grpc/proto-loader directly to root package.json | that hides the owning-package resolution issue and broadens dependency surface.

Confidence: high

Scope-risk: narrow

Directive: Dependency override smoke tests should resolve from the package that actually owns the dependency, not from incidental root hoisting.

Tested: bun test tests/integration/dependency-overrides.test.ts; bunx tsc --noEmit --pretty false; bun run lint; bun audit; bun run test:all; git diff --check

---------

Co-authored-by: unraid <local@unraid.local>
2026-04-26 19:49:54 +08:00

735 lines
24 KiB
TypeScript

import axios, { type AxiosError } from 'axios'
import type { StdoutMessage } from 'src/entrypoints/sdk/controlTypes.js'
import { logForDebugging } from '../../utils/debug.js'
import { rcLog } from '../../bridge/rcDebugLog.js'
import { logForDiagnosticsNoPII } from '../../utils/diagLogs.js'
import { errorMessage } from '../../utils/errors.js'
import { getSessionIngressAuthHeaders } from '../../utils/sessionIngressAuth.js'
import { sleep } from '../../utils/sleep.js'
import { jsonParse, jsonStringify } from '../../utils/slowOperations.js'
import { getClaudeCodeUserAgent } from '../../utils/userAgent.js'
import type { Transport } from './Transport.js'
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
const RECONNECT_BASE_DELAY_MS = 1000
const RECONNECT_MAX_DELAY_MS = 30_000
/** Time budget for reconnection attempts before giving up (10 minutes). */
const RECONNECT_GIVE_UP_MS = 600_000
/** Server sends keepalives every 15s; treat connection as dead after 45s of silence. */
const LIVENESS_TIMEOUT_MS = 45_000
/**
* HTTP status codes that indicate a permanent server-side rejection.
* The transport transitions to 'closed' immediately without retrying.
*/
const PERMANENT_HTTP_CODES = new Set([401, 403, 404])
// POST retry configuration (matches HybridTransport)
const POST_MAX_RETRIES = 10
const POST_BASE_DELAY_MS = 500
const POST_MAX_DELAY_MS = 8000
/** Hoisted TextDecoder options to avoid per-chunk allocation in readStream. */
const STREAM_DECODE_OPTS: TextDecodeOptions = { stream: true }
/** Hoisted axios validateStatus callback to avoid per-request closure allocation. */
function alwaysValidStatus(): boolean {
return true
}
// ---------------------------------------------------------------------------
// SSE Frame Parser
// ---------------------------------------------------------------------------
type SSEFrame = {
event?: string
id?: string
data?: string
}
/**
* Incrementally parse SSE frames from a text buffer.
* Returns parsed frames and the remaining (incomplete) buffer.
*
* @internal exported for testing
*/
export function parseSSEFrames(buffer: string): {
frames: SSEFrame[]
remaining: string
} {
const frames: SSEFrame[] = []
let pos = 0
// SSE frames are delimited by an empty line. Support LF and CRLF streams.
const frameDelimiter = /\r?\n\r?\n/g
frameDelimiter.lastIndex = pos
let delimiterMatch: RegExpExecArray | null
while ((delimiterMatch = frameDelimiter.exec(buffer)) !== null) {
const frameEnd = delimiterMatch.index
const rawFrame = buffer.slice(pos, frameEnd)
pos = frameEnd + delimiterMatch[0].length
// Skip empty frames
if (!rawFrame.trim()) continue
const frame: SSEFrame = {}
let isComment = false
for (const rawLine of rawFrame.split('\n')) {
// Normalize CRLF lines in mixed-line-ending streams.
const line =
rawLine[rawLine.length - 1] === '\r'
? rawLine.slice(0, -1)
: rawLine
if (line.startsWith(':')) {
// SSE comment (e.g., `:keepalive`)
isComment = true
continue
}
const colonIdx = line.indexOf(':')
if (colonIdx === -1) continue
const field = line.slice(0, colonIdx)
// Per SSE spec, strip one leading space after colon if present
const value =
line[colonIdx + 1] === ' '
? line.slice(colonIdx + 2)
: line.slice(colonIdx + 1)
switch (field) {
case 'event':
frame.event = value
break
case 'id':
frame.id = value
break
case 'data':
// Per SSE spec, multiple data: lines are concatenated with \n
frame.data = frame.data ? frame.data + '\n' + value : value
break
// Ignore other fields (retry:, etc.)
}
}
// Only emit frames that have data (or are pure comments which reset liveness)
if (frame.data || isComment) {
frames.push(frame)
}
}
return { frames, remaining: buffer.slice(pos) }
}
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
type SSETransportState =
| 'idle'
| 'connected'
| 'reconnecting'
| 'closing'
| 'closed'
/**
* Payload for `event: client_event` frames, matching the StreamClientEvent
* proto message in session_stream.proto. This is the only event type sent
* to worker subscribers — delivery_update, session_update, ephemeral_event,
* and catch_up_truncated are client-channel-only (see notifier.go and
* event_stream.go SubscriberClient guard).
*/
export type StreamClientEvent = {
event_id: string
sequence_num: number
event_type: string
source: string
payload: Record<string, unknown>
created_at: string
}
// ---------------------------------------------------------------------------
// SSETransport
// ---------------------------------------------------------------------------
/**
* Transport that uses SSE for reading and HTTP POST for writing.
*
* Reads events via Server-Sent Events from the CCR v2 event stream endpoint.
* Writes events via HTTP POST with retry logic (same pattern as HybridTransport).
*
* Each `event: client_event` frame carries a StreamClientEvent proto JSON
* directly in `data:`. The transport extracts `payload` and passes it to
* `onData` as newline-delimited JSON for StructuredIO consumers.
*
* Supports automatic reconnection with exponential backoff and Last-Event-ID
* for resumption after disconnection.
*/
export class SSETransport implements Transport {
private state: SSETransportState = 'idle'
private onData?: (data: string) => void
private onCloseCallback?: (closeCode?: number) => void
private onEventCallback?: (event: StreamClientEvent) => void
private headers: Record<string, string>
private sessionId?: string
private refreshHeaders?: () => Record<string, string>
private readonly getAuthHeaders: () => Record<string, string>
// SSE connection state
private abortController: AbortController | null = null
private lastSequenceNum = 0
private seenSequenceNums = new Set<number>()
// Reconnection state
private reconnectAttempts = 0
private reconnectStartTime: number | null = null
private reconnectTimer: NodeJS.Timeout | null = null
// Liveness detection
private livenessTimer: NodeJS.Timeout | null = null
private lastActivityTime = 0
// POST URL (derived from SSE URL)
private postUrl: string
// Runtime epoch for CCR v2 event format
constructor(
private readonly url: URL,
headers: Record<string, string> = {},
sessionId?: string,
refreshHeaders?: () => Record<string, string>,
initialSequenceNum?: number,
/**
* Per-instance auth header source. Omit to read the process-wide
* CLAUDE_CODE_SESSION_ACCESS_TOKEN (single-session callers). Required
* for concurrent multi-session callers — the env-var path is a process
* global and would stomp across sessions.
*/
getAuthHeaders?: () => Record<string, string>,
) {
this.headers = headers
this.sessionId = sessionId
this.refreshHeaders = refreshHeaders
this.getAuthHeaders = getAuthHeaders ?? getSessionIngressAuthHeaders
this.postUrl = convertSSEUrlToPostUrl(url)
// Seed with a caller-provided high-water mark so the first connect()
// sends from_sequence_num / Last-Event-ID. Without this, a fresh
// SSETransport always asks the server to replay from sequence 0 —
// the entire session history on every transport swap.
if (initialSequenceNum !== undefined && initialSequenceNum > 0) {
this.lastSequenceNum = initialSequenceNum
}
logForDebugging(`SSETransport: SSE URL = ${url.href}`)
logForDebugging(`SSETransport: POST URL = ${this.postUrl}`)
logForDiagnosticsNoPII('info', 'cli_sse_transport_initialized')
}
/**
* High-water mark of sequence numbers seen on this stream. Callers that
* recreate the transport (e.g. replBridge onWorkReceived) read this before
* close() and pass it as `initialSequenceNum` to the next instance so the
* server resumes from the right point instead of replaying everything.
*/
getLastSequenceNum(): number {
return this.lastSequenceNum
}
async connect(): Promise<void> {
if (this.state !== 'idle' && this.state !== 'reconnecting') {
logForDebugging(
`SSETransport: Cannot connect, current state is ${this.state}`,
{ level: 'error' },
)
logForDiagnosticsNoPII('error', 'cli_sse_connect_failed')
return
}
this.state = 'reconnecting'
const connectStartTime = Date.now()
// Build SSE URL with sequence number for resumption
const sseUrl = new URL(this.url.href)
if (this.lastSequenceNum > 0) {
sseUrl.searchParams.set('from_sequence_num', String(this.lastSequenceNum))
}
// Build headers -- use fresh auth headers (supports Cookie for session keys).
// Remove stale Authorization header from this.headers when Cookie auth is used,
// since sending both confuses the auth interceptor.
const authHeaders = this.getAuthHeaders()
const headers: Record<string, string> = {
...this.headers,
...authHeaders,
Accept: 'text/event-stream',
'anthropic-version': '2023-06-01',
'User-Agent': getClaudeCodeUserAgent(),
}
if (authHeaders['Cookie']) {
delete headers['Authorization']
}
if (this.lastSequenceNum > 0) {
headers['Last-Event-ID'] = String(this.lastSequenceNum)
}
logForDebugging(`SSETransport: Opening ${sseUrl.href}`)
logForDiagnosticsNoPII('info', 'cli_sse_connect_opening')
this.abortController = new AbortController()
try {
// eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins
const response = await fetch(sseUrl.href, {
headers,
signal: this.abortController.signal,
})
if (!response.ok) {
const isPermanent = PERMANENT_HTTP_CODES.has(response.status)
logForDebugging(
`SSETransport: HTTP ${response.status}${isPermanent ? ' (permanent)' : ''}`,
{ level: 'error' },
)
logForDiagnosticsNoPII('error', 'cli_sse_connect_http_error', {
status: response.status,
})
if (isPermanent) {
this.state = 'closed'
this.onCloseCallback?.(response.status)
return
}
this.handleConnectionError()
return
}
if (!response.body) {
logForDebugging('SSETransport: No response body')
this.handleConnectionError()
return
}
// Successfully connected
const connectDuration = Date.now() - connectStartTime
logForDebugging('SSETransport: Connected')
logForDiagnosticsNoPII('info', 'cli_sse_connect_connected', {
duration_ms: connectDuration,
})
this.state = 'connected'
this.reconnectAttempts = 0
this.reconnectStartTime = null
this.resetLivenessTimer()
// Read the SSE stream
await this.readStream(response.body)
} catch (error) {
if (this.abortController?.signal.aborted) {
// Intentional close
return
}
logForDebugging(
`SSETransport: Connection error: ${errorMessage(error)}`,
{ level: 'error' },
)
logForDiagnosticsNoPII('error', 'cli_sse_connect_error')
this.handleConnectionError()
}
}
/**
* Read and process the SSE stream body.
*/
// eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins
private async readStream(body: ReadableStream<Uint8Array>): Promise<void> {
const reader = body.getReader()
const decoder = new TextDecoder()
let buffer = ''
try {
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, STREAM_DECODE_OPTS)
const { frames, remaining } = parseSSEFrames(buffer)
buffer = remaining
for (const frame of frames) {
// Any frame (including keepalive comments) proves the connection is alive
this.resetLivenessTimer()
if (frame.id) {
const seqNum = parseInt(frame.id, 10)
if (!isNaN(seqNum)) {
if (this.seenSequenceNums.has(seqNum)) {
logForDebugging(
`SSETransport: DUPLICATE frame seq=${seqNum} (lastSequenceNum=${this.lastSequenceNum}, seenCount=${this.seenSequenceNums.size})`,
{ level: 'warn' },
)
logForDiagnosticsNoPII('warn', 'cli_sse_duplicate_sequence')
} else {
this.seenSequenceNums.add(seqNum)
// Prevent unbounded growth: once we have many entries, prune
// old sequence numbers that are well below the high-water mark.
// Only sequence numbers near lastSequenceNum matter for dedup.
if (this.seenSequenceNums.size > 1000) {
const threshold = this.lastSequenceNum - 200
for (const s of this.seenSequenceNums) {
if (s < threshold) {
this.seenSequenceNums.delete(s)
}
}
}
}
if (seqNum > this.lastSequenceNum) {
this.lastSequenceNum = seqNum
}
}
}
if (frame.event && frame.data) {
this.handleSSEFrame(frame.event, frame.data)
} else if (frame.data) {
// data: without event: — server is emitting the old envelope format
// or a bug. Log so incidents show as a signal instead of silent drops.
logForDebugging(
'SSETransport: Frame has data: but no event: field — dropped',
{ level: 'warn' },
)
logForDiagnosticsNoPII('warn', 'cli_sse_frame_missing_event_field')
}
}
}
} catch (error) {
if (this.abortController?.signal.aborted) return
logForDebugging(
`SSETransport: Stream read error: ${errorMessage(error)}`,
{ level: 'error' },
)
logForDiagnosticsNoPII('error', 'cli_sse_stream_read_error')
} finally {
reader.releaseLock()
}
// Stream ended — reconnect unless we're closing
if (this.state !== 'closing' && this.state !== 'closed') {
logForDebugging('SSETransport: Stream ended, reconnecting')
this.handleConnectionError()
}
}
/**
* Handle a single SSE frame. The event: field names the variant; data:
* carries the inner proto JSON directly (no envelope).
*
* Worker subscribers only receive client_event frames (see notifier.go) —
* any other event type indicates a server-side change that CC doesn't yet
* understand. Log a diagnostic so we notice in telemetry.
*/
private handleSSEFrame(eventType: string, data: string): void {
if (eventType !== 'client_event') {
logForDebugging(
`SSETransport: Unexpected SSE event type '${eventType}' on worker stream`,
{ level: 'warn' },
)
logForDiagnosticsNoPII('warn', 'cli_sse_unexpected_event_type', {
event_type: eventType,
})
return
}
let ev: StreamClientEvent
try {
ev = jsonParse(data) as StreamClientEvent
} catch (error) {
logForDebugging(
`SSETransport: Failed to parse client_event data: ${errorMessage(error)}`,
{ level: 'error' },
)
return
}
const payload = ev.payload
if (payload && typeof payload === 'object' && 'type' in payload) {
const sessionLabel = this.sessionId ? ` session=${this.sessionId}` : ''
logForDebugging(
`SSETransport: Event seq=${ev.sequence_num} event_id=${ev.event_id} event_type=${ev.event_type} payload_type=${String(payload.type)}${sessionLabel}`,
)
logForDiagnosticsNoPII('info', 'cli_sse_message_received')
// Pass the unwrapped payload as newline-delimited JSON,
// matching the format that StructuredIO/WebSocketTransport consumers expect
this.onData?.(jsonStringify(payload) + '\n')
} else {
logForDebugging(
`SSETransport: Ignoring client_event with no type in payload: event_id=${ev.event_id}`,
)
}
this.onEventCallback?.(ev)
}
/**
* Handle connection errors with exponential backoff and time budget.
*/
private handleConnectionError(): void {
rcLog(
`SSE handleConnectionError: state=${this.state}` +
` lastSeqNum=${this.getLastSequenceNum()}` +
` reconnectAttempts=${this.reconnectAttempts}` +
` msSinceLastActivity=${this.lastActivityTime > 0 ? Date.now() - this.lastActivityTime : -1}`,
)
this.clearLivenessTimer()
if (this.state === 'closing' || this.state === 'closed') return
// Abort any in-flight SSE fetch
this.abortController?.abort()
this.abortController = null
const now = Date.now()
if (!this.reconnectStartTime) {
this.reconnectStartTime = now
}
const elapsed = now - this.reconnectStartTime
if (elapsed < RECONNECT_GIVE_UP_MS) {
// Clear any existing timer
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer)
this.reconnectTimer = null
}
// Refresh headers before reconnecting
if (this.refreshHeaders) {
const freshHeaders = this.refreshHeaders()
Object.assign(this.headers, freshHeaders)
logForDebugging('SSETransport: Refreshed headers for reconnect')
}
this.state = 'reconnecting'
this.reconnectAttempts++
const baseDelay = Math.min(
RECONNECT_BASE_DELAY_MS * 2 ** (this.reconnectAttempts - 1),
RECONNECT_MAX_DELAY_MS,
)
// Add ±25% jitter
const delay = Math.max(
0,
baseDelay + baseDelay * 0.25 * (2 * Math.random() - 1),
)
logForDebugging(
`SSETransport: Reconnecting in ${Math.round(delay)}ms (attempt ${this.reconnectAttempts}, ${Math.round(elapsed / 1000)}s elapsed)`,
)
logForDiagnosticsNoPII('error', 'cli_sse_reconnect_attempt', {
reconnectAttempts: this.reconnectAttempts,
})
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null
void this.connect()
}, delay)
} else {
logForDebugging(
`SSETransport: Reconnection time budget exhausted after ${Math.round(elapsed / 1000)}s`,
{ level: 'error' },
)
logForDiagnosticsNoPII('error', 'cli_sse_reconnect_exhausted', {
reconnectAttempts: this.reconnectAttempts,
elapsedMs: elapsed,
})
this.state = 'closed'
this.onCloseCallback?.()
}
}
/**
* Bound timeout callback. Hoisted from an inline closure so that
* resetLivenessTimer (called per-frame) does not allocate a new closure
* on every SSE frame.
*/
private readonly onLivenessTimeout = (): void => {
this.livenessTimer = null
rcLog(
`SSE liveness timeout (${LIVENESS_TIMEOUT_MS}ms)` +
` lastSeqNum=${this.getLastSequenceNum()}` +
` state=${this.state}`,
)
logForDebugging('SSETransport: Liveness timeout, reconnecting', {
level: 'error',
})
logForDiagnosticsNoPII('error', 'cli_sse_liveness_timeout')
this.abortController?.abort()
this.handleConnectionError()
}
/**
* Reset the liveness timer. If no SSE frame arrives within the timeout,
* treat the connection as dead and reconnect.
*/
private resetLivenessTimer(): void {
this.clearLivenessTimer()
this.livenessTimer = setTimeout(this.onLivenessTimeout, LIVENESS_TIMEOUT_MS)
}
private clearLivenessTimer(): void {
if (this.livenessTimer) {
clearTimeout(this.livenessTimer)
this.livenessTimer = null
}
}
// -----------------------------------------------------------------------
// Write (HTTP POST) — same pattern as HybridTransport
// -----------------------------------------------------------------------
async write(message: StdoutMessage): Promise<void> {
const authHeaders = this.getAuthHeaders()
if (Object.keys(authHeaders).length === 0) {
logForDebugging('SSETransport: No session token available for POST')
logForDiagnosticsNoPII('warn', 'cli_sse_post_no_token')
return
}
const headers: Record<string, string> = {
...authHeaders,
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01',
'User-Agent': getClaudeCodeUserAgent(),
}
logForDebugging(
`SSETransport: POST body keys=${Object.keys(message as Record<string, unknown>).join(',')}`,
)
for (let attempt = 1; attempt <= POST_MAX_RETRIES; attempt++) {
try {
const response = await axios.post(this.postUrl, message, {
headers,
validateStatus: alwaysValidStatus,
})
if (response.status === 200 || response.status === 201) {
logForDebugging(`SSETransport: POST success type=${message.type}`)
return
}
logForDebugging(
`SSETransport: POST ${response.status} body=${jsonStringify(response.data).slice(0, 200)}`,
)
// 4xx errors (except 429) are permanent - don't retry
if (
response.status >= 400 &&
response.status < 500 &&
response.status !== 429
) {
logForDebugging(
`SSETransport: POST returned ${response.status} (client error), not retrying`,
)
logForDiagnosticsNoPII('warn', 'cli_sse_post_client_error', {
status: response.status,
})
return
}
// 429 or 5xx - retry
logForDebugging(
`SSETransport: POST returned ${response.status}, attempt ${attempt}/${POST_MAX_RETRIES}`,
)
logForDiagnosticsNoPII('warn', 'cli_sse_post_retryable_error', {
status: response.status,
attempt,
})
} catch (error) {
const axiosError = error as AxiosError
logForDebugging(
`SSETransport: POST error: ${axiosError.message}, attempt ${attempt}/${POST_MAX_RETRIES}`,
)
logForDiagnosticsNoPII('warn', 'cli_sse_post_network_error', {
attempt,
})
}
if (attempt === POST_MAX_RETRIES) {
logForDebugging(
`SSETransport: POST failed after ${POST_MAX_RETRIES} attempts, continuing`,
)
logForDiagnosticsNoPII('warn', 'cli_sse_post_retries_exhausted')
return
}
const delayMs = Math.min(
POST_BASE_DELAY_MS * 2 ** (attempt - 1),
POST_MAX_DELAY_MS,
)
await sleep(delayMs)
}
}
// -----------------------------------------------------------------------
// Transport interface
// -----------------------------------------------------------------------
isConnectedStatus(): boolean {
return this.state === 'connected'
}
isClosedStatus(): boolean {
return this.state === 'closed'
}
setOnData(callback: (data: string) => void): void {
this.onData = callback
}
setOnClose(callback: (closeCode?: number) => void): void {
this.onCloseCallback = callback
}
setOnEvent(callback: (event: StreamClientEvent) => void): void {
this.onEventCallback = callback
}
close(): void {
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer)
this.reconnectTimer = null
}
this.clearLivenessTimer()
this.state = 'closing'
this.abortController?.abort()
this.abortController = null
}
}
// ---------------------------------------------------------------------------
// URL Conversion
// ---------------------------------------------------------------------------
/**
* Convert an SSE URL to the HTTP POST endpoint URL.
* The SSE stream URL and POST URL share the same base; the POST endpoint
* is at `/events` (without `/stream`).
*
* From: https://api.example.com/v2/session_ingress/session/<session_id>/events/stream
* To: https://api.example.com/v2/session_ingress/session/<session_id>/events
*/
function convertSSEUrlToPostUrl(sseUrl: URL): string {
let pathname = sseUrl.pathname
// Remove /stream suffix to get the POST events endpoint
if (pathname.endsWith('/stream')) {
pathname = pathname.slice(0, -'/stream'.length)
}
return `${sseUrl.protocol}//${sseUrl.host}${pathname}`
}