Repository navigation
refactor(sse): extract request guards, failure handling and post-translation finalize out of chatCore (slice 2) - #16901
Merged
Conversation
Move the managed exclusive-connection lease fence (assert + LEASE_* error-code mapping + 409 lease-error result) from handleChatCore into chatCore/managedLeaseFence.ts. Byte-identical behaviour; the handler destructures the same three helpers it passed to the response legs. chatCore slice 2, design after #15709 (HouMinXi). Co-authored-by: Minxi Hou <houminxi@gmail.com>
Move the per-endpoint custom system prompt injection (#2063 port) into chatCore/customSystemPrompt.ts. The handler still resolves the settings snapshot (cachedSettings, else getCachedSettings()) at the same point and passes it in, so the leaf adds no open-sse -> src import edge. Byte-identical behaviour. chatCore slice 2, design after #15709 (HouMinXi). Co-authored-by: Minxi Hou <houminxi@gmail.com>
Move the handler-side outcome of the plugin onRequest hook (labelled 403 plugin_block result on block, truthy body rewrite) into chatCore/pluginRequestGate.ts. Byte-identical behaviour. chatCore slice 2, design after #15709 (HouMinXi). Co-authored-by: Minxi Hou <houminxi@gmail.com>
Move the per-API-key device/connection tracking call (9router#931 port) into chatCore/deviceTracking.ts. Byte-identical behaviour. chatCore slice 2, design after #15709 (HouMinXi). Co-authored-by: Minxi Hou <houminxi@gmail.com>
… chatCore Move the capture of the client's own tool names (taken before the web-search / web-fetch fallback preparers inject synthetic tools) into chatCore/clientToolNames.ts. Byte-identical behaviour. chatCore slice 2.
…atCore Move the translation catch body (plugin onError hook, defensive status/message/type derivation from hostile thrown values, translation-failure result + warn log) into chatCore/requestTranslationError.ts. The handler keeps the pending-request finalization and the early return. Byte-identical behaviour. chatCore slice 2.
…Core Move the isClaudeCodeCompatible translation branch into chatCore/claudeCodeBridgeBody.ts; it returns the dispatch body and the resolved bridge session id. The model flag lookups and the reasoning-rule directive helper are injected by the handler, so the leaf adds no open-sse -> src import edge. Byte-identical behaviour. chatCore slice 2.
Move the pure Claude -> Claude passthrough translation branch (#1359: deferred-tool hoist, Anthropic history sanitation, system-role handling, output_format migration, output_config.format strip) into chatCore/claudePassthroughBody.ts. The reasoning-rule directive helper is injected. Byte-identical behaviour. chatCore slice 2.
…chatCore Move the deferred post-translation OmniGlyph stage into chatCore/postTranslationCompression.ts. The handler keeps the 'if (runPostTranslationCompression ...)' gate and hands the four request-scope bindings (translatedBody, tokensCompressed, compressionResponseMeta, compressionAnalyticsWritePromise) in a state object the stage updates in place, so even a partial failure leaves the same state as the inline block. Fail-open as before. chatCore slice 2, design after #15709 (HouMinXi). Co-authored-by: Minxi Hou <houminxi@gmail.com>
…hatCore Move the post-translation finalization (request tool metadata, OpenRouter / Kiro / Claude tool-schema dispatch fixes, response tool-name map, side-channel strip, upstream model id, previous_response_id policy, Codex effort-suffix guard) into chatCore/translatedRequestFinalize.ts. Byte-identical behaviour. chatCore slice 2, design after #15709 (HouMinXi). Co-authored-by: Minxi Hou <houminxi@gmail.com>
…atCore Move the max_tokens / max_completion_tokens reconciliation (#1961, #6912), store strip, Responses stream_options drop and provider output caps (#711) into chatCore/upstreamRequestParams.ts. supportsMaxTokens() is still evaluated by the handler at the same point and passed in. Byte-identical behaviour. chatCore slice 2.
Move the Quota Share enforcement pre-hook (B/F7, fail-open) and its combo soft-penalty propagation (G2) into chatCore/quotaSharePreHook.ts; it returns the 429 response on block. The pending-request finalization is injected by the handler. Byte-identical behaviour. chatCore slice 2.
Move the body of the applyCompressionComboConfig closure (fold a runtime compression combo's pipeline, language packs and output mode into the request CompressionConfig) into the pure chatCore/compressionComboConfig.ts. The closure keeps the config rebinding and the compressionComboApplied flag. Byte-identical behaviour. chatCore slice 2.
Move the compression.step (F3.3) and compression.completed (U5) event emission into chatCore/compressionLiveEvents.ts. The typed event-bus emit is injected by the handler, so the leaf adds no open-sse -> src import edge. Best-effort semantics unchanged. chatCore slice 2.
Move the enforceOutputTokenBudget call against the concrete target plus its reject message and adjusted-fields log into chatCore/finalOutputBudget.ts. The handler keeps the model output cap / input cap resolution, the pending-request finalization and the 400 context_length_exceeded return. Byte-identical behaviour. chatCore slice 2.
Move the createStreamController wiring (disconnect finalizer chain, 499 client_disconnected fallback, caller onDisconnect) into chatCore/chatStreamController.ts. The two late-bound handlers are read through getters at event time and finalizePendingScope is injected. Byte-identical behaviour. chatCore slice 2.
Move the reasoning input policy application (OpenAI Chat / Responses inbound bodies, #11178 combo-step fallback resolution) into chatCore/reasoningInputGate.ts; it reports an incompatible target and the handler returns the 400. Byte-identical behaviour. chatCore slice 2.
…hatCore Move the pending-scope provider-request snapshot builder and the cross-wire-shape message count into chatCore/providerRequestRegistration.ts. Byte-identical behaviour. chatCore slice 2.
Move the live-zone prompt-compression lane (session id resolution + applyLiveZoneCompression dispatch, still lazily imported) into chatCore/liveZoneCompression.ts. Byte-identical behaviour. chatCore slice 2.
Move the connection-level custom User-Agent and #8369 custom upstream headers resolution into chatCore/connectionUpstreamOverrides.ts. Byte-identical behaviour. chatCore slice 2.
chatCore.ts measures 3287 (split("\n").length) after slice 2, down from
3949 on the tip. Lower its frozen ceiling by hand 4732 -> 3945 =
ceil(3287 x 1.2), keeping the #16831 20% headroom on the new size, and
record it as _rebaseline_2026_10_16_chatcore_slice_2. Only this entry is
touched; check:file-size --update was not run. Adds the maintenance
changelog fragment.
Co-authored-by: Minxi Hou <houminxi@gmail.com>
Contributor
CI Coverage Report
Coverage artifact was not available for this run. PR Test PolicyThis PR changes production code in |
This was referenced Oct 18, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Slice 2 of the
chatCore.tsdecomposition (#3501). Twenty request-path blocks move out ofhandleChatCoreInnerinto leaves underopen-sse/handlers/chatCore/. Each one is lifted mechanically and called from the same point, so behaviour, side-effect order, logs and messages do not change.chatCore.tsgoes from 3,948 to 3,286 lines (wc -l; the gate'ssplit("\n").lengthreads 3,949 → 3,287), which meets the ≤ 3,300 target.Design after #15709 (HouMinXi), which the author closed on 2026-10-15 after the branch drifted. Commits that reuse its module design or code carry
Co-authored-by: Minxi Hou <houminxi@gmail.com>.Root cause / design
any. Where a block mutated several handler bindings, the leaf gets a typed state object and updates it in place exactly where the inline code assigned it (postTranslationCompression). Late-bound handlers are read through getters at event time (chatStreamController). With this, even a part-way failure leaves the same state the inline block did.open-sse → srcimport edges. The new boundary ratchet (ci(quality): ratchet the open-sse → src boundary (check:boundary:ratchet) #16874) counts unique file→file edges. Leaves therefore receive theirsrc/dependencies from the handler instead of importing them:getCachedSettings,applyReasoningRuleDirective,getModelNormalizeToolCallId/getModelPreserveOpenAIDeveloperRole,supportsMaxTokens()result,trackPendingRequestcallback, typed event-busemit,finalizePendingScope. The five edges that did move (lease DB, quota enforce/types, plugin hooks, CC request defaults) were removed fromchatCore.tsat the same time. The measured count is 773 on both the base tip and this branch.chatCore.ts(refactor(sse): split chatCore request guards and failure handling #15709 had to edit one). This slice leaves those regions inline: the credential-refresh closures (token-refresh-race-comprehensive,hard-session-lease-bypass-inventory),applyProviderFailureClassification(upstream-status-restatementR10,api-key-429-cooldown,antigravity-429-quota-cooldown, theerror-public-boundariesfixture'slastError: persistentMessage ≥ 9count), the dedup hash (request-dedup-tenant-isolation), the Tier-2/Gemini TPM guards (pre-dispatch-error-route-meta), the compression gating expressions and theif (runPostTranslationCompression/translatedBody = translateRequest(anchors.What changed
open-sse/handlers/chatCore/)managedLeaseFence.ts¹customSystemPrompt.ts¹pluginRequestGate.ts¹deviceTracking.ts¹clientToolNames.tsrequestTranslationError.tsclaudeCodeBridgeBody.tsclaudePassthroughBody.tspostTranslationCompression.ts¹translatedRequestFinalize.ts¹ (incl. #16867 OpenRouter step)upstreamRequestParams.tsquotaSharePreHook.tscompressionComboConfig.tscompressionLiveEvents.tsfinalOutputBudget.tschatStreamController.tsreasoningInputGate.tsproviderRequestRegistration.tsliveZoneCompression.tsconnectionUpstreamOverrides.ts¹ design/code after #15709 (co-authored).
Also:
config/quality/file-size-baseline.jsonlowersfrozen["open-sse/handlers/chatCore.ts"]by hand from 4732 to 3945 (= ⌈3287 × 1.2⌉, keeping the #16831 headroom), with the note_rebaseline_2026_10_16_chatcore_slice_2. No other entry changes, and--updatewas not run. The changelog fragment ischangelog.d/maintenance/0000-chatcore-slice-2.md.Validation
chatCore.ts, every source guard reading it,chatcore-*,chatcore/*, g13 golden),DATA_DIRisolatedcall-logs-id-collision; 2 are the base-red reactive-compaction source guards broken on the tip by #16627npm run typecheck:corenode scripts/check/check-open-sse-typecheck.mjs(covers chatCore + leaves)npm run check:cycles:ratchetnode --import tsx scripts/check/check-known-symbols.tsnpm run check:file-sizenode scripts/quality/measure-boundary.mjs --ratchetnpx eslint/npx prettier --checkon touched filesNot done
credentialRefreshRetry,providerFailureClassification,persistFailureUsage,requestDedup). Moving them requires editing source-guard tests that pin their text inchatCore.ts, and this slice edits no tests. A follow-up can re-point those guards first.coverage.chatCore.linesinquality-baseline.jsonmay move because lines left the file; the CI ratchet re-measures it.