coderouter-cli 2.17.0__py3-none-any.whl → 2.19.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -46,6 +46,7 @@ from coderouter.adapters.base import (
46
46
  StreamChunk,
47
47
  StreamTruncatedError,
48
48
  )
49
+ from coderouter.adapters.slot_affinity import apply_slot_affinity
49
50
  from coderouter.credentials import resolve_provider_credential
50
51
  from coderouter.logging import (
51
52
  get_logger,
@@ -243,6 +244,9 @@ class AnthropicAdapter(BaseAdapter):
243
244
  body.update(dumped)
244
245
  body["model"] = self.config.model
245
246
  body["stream"] = stream
247
+ apply_slot_affinity(
248
+ body, slots=self.config.slot_affinity_slots, key=req.session_key
249
+ )
246
250
  return body
247
251
 
248
252
  # ------------------------------------------------------------------
@@ -65,6 +65,9 @@ class ChatRequest(BaseModel):
65
65
 
66
66
  # CodeRouter-specific extension (not sent upstream)
67
67
  profile: str | None = Field(default=None, exclude=True)
68
+ # v2.18.0: conversation key for KV-slot affinity (see
69
+ # ``ProviderConfig.slot_affinity_slots``). Never serialized.
70
+ session_key: str | None = Field(default=None, exclude=True)
68
71
 
69
72
 
70
73
  class ChatResponse(BaseModel):
@@ -30,6 +30,7 @@ from coderouter.adapters.base import (
30
30
  StreamChunk,
31
31
  StreamTruncatedError,
32
32
  )
33
+ from coderouter.adapters.slot_affinity import apply_slot_affinity
33
34
  from coderouter.credentials import resolve_provider_credential
34
35
  from coderouter.logging import (
35
36
  get_logger,
@@ -182,6 +183,11 @@ class OpenAICompatAdapter(BaseAdapter):
182
183
  value = getattr(request, field, None)
183
184
  if value is not None:
184
185
  body[field] = value
186
+ apply_slot_affinity(
187
+ body,
188
+ slots=self.config.slot_affinity_slots,
189
+ key=getattr(request, "session_key", None),
190
+ )
185
191
  if stream:
186
192
  # Request a terminal usage chunk. Providers that honor this
187
193
  # (OpenAI, OpenRouter, Ollama >=0.x) will send one extra chunk
@@ -0,0 +1,54 @@
1
+ """v2.18.0: KV-slot affinity for llama-server (``id_slot``).
2
+
3
+ llama-server started with ``--parallel N`` serves N slots, each holding its
4
+ own prompt cache. Without a hint it picks a free slot, so consecutive turns
5
+ of one conversation can land on different slots and re-prefill the whole
6
+ prompt. Sending ``id_slot`` pins a conversation to one slot.
7
+
8
+ The slot is ``sha256(key) % N`` — stable across processes and restarts
9
+ (Python's ``hash`` is salted per process).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ from collections.abc import Mapping
16
+ from typing import Any
17
+
18
+ # Request classes whose prompt shares the main conversation's prefix: they
19
+ # belong on the main conversation's slot. Everything else (sub-agents,
20
+ # auxiliary calls such as the auto-mode classifier or titles, workflows) has
21
+ # its own prompt and gets its own key, so it neither waits on the main slot
22
+ # nor evicts its cache.
23
+ _MAIN_CLASSES = frozenset({"", "main", "compaction"})
24
+
25
+
26
+ def affinity_key(hints: Mapping[str, str]) -> str | None:
27
+ """Conversation key for slot affinity, from Claude Code's hint headers.
28
+
29
+ ``None`` when there is no session id. ``main`` / ``compaction`` (and a
30
+ missing class) share ``<session>``; other classes get
31
+ ``<session>:<class>:<agent_type>``.
32
+ """
33
+ session = hints.get("session_id")
34
+ if not session:
35
+ return None
36
+ request_class = hints.get("request_class", "").lower()
37
+ if request_class in _MAIN_CLASSES:
38
+ return session
39
+ return f"{session}:{request_class}:{hints.get('agent_type', '').lower()}"
40
+
41
+
42
+ def slot_for(key: str, slots: int) -> int:
43
+ digest = hashlib.sha256(key.encode("utf-8")).digest()
44
+ return int.from_bytes(digest[:8], "big") % slots
45
+
46
+
47
+ def apply_slot_affinity(body: dict[str, Any], *, slots: int | None, key: str | None) -> None:
48
+ """Set ``body["id_slot"]`` when affinity is configured and a key exists.
49
+
50
+ An ``id_slot`` already present (e.g. from ``extra_body``) wins.
51
+ """
52
+ if not slots or not key or "id_slot" in body:
53
+ return
54
+ body["id_slot"] = slot_for(key, slots)
coderouter/cli.py CHANGED
@@ -483,7 +483,8 @@ def _build_parser() -> argparse.ArgumentParser:
483
483
  help=(
484
484
  "v2.16.0: do not write the Claude Code gateway settings "
485
485
  "(ENABLE_TOOL_SEARCH=false, CLAUDE_CODE_AUTO_MODE_SERVER=0, "
486
- "and --max-context-tokens). Use when the chain is "
486
+ "CLAUDE_CODE_GATEWAY_HINT_HEADERS=1 and --max-context-tokens). "
487
+ "Use when the chain is "
487
488
  "api.anthropic.com only."
488
489
  ),
489
490
  )
@@ -562,6 +562,23 @@ class ProviderConfig(BaseModel):
562
562
  # withholds those opening events from the client. ``None`` (default)
563
563
  # disables it. Typical use: a local llama-server still loading a model
564
564
  # or chewing through a long prompt while a cloud fallback could answer.
565
+ # v2.18.0: KV-slot affinity for llama-server started with
566
+ # ``--parallel N``. When set to N and the request carries a conversation
567
+ # key (Claude Code's ``x-claude-code-session-id`` hint header), the body
568
+ # gets ``id_slot = stable_hash(key) % N`` so every turn of a conversation
569
+ # lands on the same slot and reuses its prompt cache instead of
570
+ # re-prefilling on whichever slot is free. llama.cpp only (other servers
571
+ # ignore or reject ``id_slot``); ``None`` (default) sends nothing.
572
+ slot_affinity_slots: int | None = Field(
573
+ default=None,
574
+ ge=1,
575
+ le=256,
576
+ description=(
577
+ "v2.18.0: llama-server --parallel N. Pins each conversation to "
578
+ "slot hash(session) % N via id_slot so its KV cache is reused. "
579
+ "llama.cpp only. None disables."
580
+ ),
581
+ )
565
582
  ttft_timeout_s: float | None = Field(
566
583
  default=None,
567
584
  gt=0.0,
@@ -1639,6 +1656,21 @@ class RuleMatcher(BaseModel):
1639
1656
  # declares any tools); ``False`` is rejected by ``_exactly_one``
1640
1657
  # since a "no-tools" rule would shadow the default fall-through.
1641
1658
  has_tools: bool | None = None
1659
+ # v2.18.0: Claude Code gateway hint headers. Claude Code 2.1.273+ sends
1660
+ # these to a custom ANTHROPIC_BASE_URL when
1661
+ # ``CLAUDE_CODE_GATEWAY_HINT_HEADERS=1`` is set (``coderouter
1662
+ # vscode-init`` sets it). They say what a request *is* — something the
1663
+ # body heuristics above can only guess:
1664
+ # * ``request_class`` — ``x-claude-code-request-class``: ``main`` /
1665
+ # ``subagent`` / ``workflow`` / ``compaction`` / ``auxiliary``
1666
+ # (auto-mode classifier, titles, …). Case-insensitive exact match.
1667
+ # * ``agent_type`` — ``x-claude-code-agent-type`` (e.g. ``Explore``),
1668
+ # case-insensitive exact match.
1669
+ # * ``compaction: True`` — ``x-claude-code-compaction`` is truthy.
1670
+ # Without the headers these matchers simply never match.
1671
+ request_class: str | None = None
1672
+ agent_type: str | None = None
1673
+ compaction: bool | None = None
1642
1674
 
1643
1675
  _MATCHER_FIELDS: tuple[str, ...] = (
1644
1676
  "has_image",
@@ -1649,12 +1681,15 @@ class RuleMatcher(BaseModel):
1649
1681
  "content_token_count_min",
1650
1682
  "has_tools",
1651
1683
  "cjk_ratio_min",
1684
+ "request_class",
1685
+ "agent_type",
1686
+ "compaction",
1652
1687
  )
1653
1688
 
1654
1689
  # Boolean matcher fields carry meaning only at ``True`` — the runtime
1655
1690
  # evaluator uses ``is True`` — so a ``False`` value is a dead rule that
1656
1691
  # never matches. ``_exactly_one`` rejects it explicitly (see below).
1657
- _BOOL_MATCHER_FIELDS: tuple[str, ...] = ("has_image", "has_tools")
1692
+ _BOOL_MATCHER_FIELDS: tuple[str, ...] = ("has_image", "has_tools", "compaction")
1658
1693
 
1659
1694
  @model_validator(mode="after")
1660
1695
  def _exactly_one(self) -> Self:
@@ -125,6 +125,18 @@ def check(version: Version | None, env: Mapping[str, str]) -> list[ClaudeCodeFin
125
125
  )
126
126
  )
127
127
 
128
+ if env.get("CLAUDE_CODE_GATEWAY_HINT_HEADERS", "").lower() in ("1", "true"):
129
+ out.append(ClaudeCodeFinding("ok", "CLAUDE_CODE_GATEWAY_HINT_HEADERS=1"))
130
+ else:
131
+ out.append(
132
+ ClaudeCodeFinding(
133
+ "info",
134
+ "CLAUDE_CODE_GATEWAY_HINT_HEADERS is not set: auto_router rules "
135
+ "on request_class / agent_type / compaction (v2.18.0) never "
136
+ "match without it.",
137
+ )
138
+ )
139
+
128
140
  if env.get("CLAUDE_CODE_AUTO_MODE_SERVER") == "0":
129
141
  out.append(ClaudeCodeFinding("ok", "CLAUDE_CODE_AUTO_MODE_SERVER=0"))
130
142
  else:
@@ -31,6 +31,7 @@ from fastapi import APIRouter, Header, HTTPException, Request
31
31
  from fastapi.responses import JSONResponse, Response, StreamingResponse
32
32
 
33
33
  from coderouter.adapters.base import StreamTruncatedError
34
+ from coderouter.adapters.slot_affinity import affinity_key
34
35
  from coderouter.guards.context_budget import ContextBudgetRejectError
35
36
  from coderouter.guards.tool_loop import ToolCountExceededError, ToolLoopBreakError
36
37
  from coderouter.ingress.anthropic_errors import (
@@ -49,7 +50,7 @@ from coderouter.routing import (
49
50
  MidStreamError,
50
51
  NoProvidersAvailableError,
51
52
  )
52
- from coderouter.routing.auto_router import RESERVED_PROFILE_NAME, classify
53
+ from coderouter.routing.auto_router import RESERVED_PROFILE_NAME, classify, extract_gateway_hints
53
54
  from coderouter.routing.fallback_trace import (
54
55
  SSE_FALLBACK_EVENT,
55
56
  current_fallback_trace,
@@ -226,6 +227,11 @@ async def messages(
226
227
  if anthropic_beta:
227
228
  anth_req.anthropic_beta = anthropic_beta
228
229
 
230
+ # v2.18.0: Claude Code gateway hint headers — routing matchers below,
231
+ # and the conversation key for llama-server KV-slot affinity.
232
+ gateway_hints = extract_gateway_hints(request.headers)
233
+ anth_req.session_key = affinity_key(gateway_hints)
234
+
229
235
  # Profile selection — body field wins over header (same policy as OpenAI route).
230
236
  if anth_req.profile is None and x_coderouter_profile:
231
237
  anth_req.profile = x_coderouter_profile
@@ -253,7 +259,7 @@ async def messages(
253
259
  # AnthropicRequest), so both OpenAI and Anthropic ingress use the same
254
260
  # classifier without a shared request shim.
255
261
  if anth_req.profile is None and config.default_profile == RESERVED_PROFILE_NAME:
256
- anth_req.profile = classify(payload, config)
262
+ anth_req.profile = classify(payload, config, gateway_hints)
257
263
 
258
264
  if anth_req.profile is not None:
259
265
  try:
coderouter/ingress/app.py CHANGED
@@ -19,6 +19,7 @@ from coderouter.ingress.dashboard_routes import router as dashboard_router
19
19
  from coderouter.ingress.launcher_routes import router as launcher_router
20
20
  from coderouter.ingress.metrics_routes import router as metrics_router
21
21
  from coderouter.ingress.openai_routes import router as openai_router
22
+ from coderouter.ingress.responses_routes import router as responses_router
22
23
  from coderouter.logging import configure_logging, get_logger
23
24
  from coderouter.metrics import install_collector
24
25
  from coderouter.plugins import discover_and_load
@@ -491,6 +492,8 @@ def create_app(config_path: str | None = None) -> FastAPI:
491
492
 
492
493
  app.include_router(openai_router, prefix="/v1", tags=["openai-compat"])
493
494
  app.include_router(anthropic_router, prefix="/v1", tags=["anthropic-compat"])
495
+ # v2.19.0: OpenAI Responses API (Codex CLI).
496
+ app.include_router(responses_router, prefix="/v1", tags=["openai-responses"])
494
497
  # v1.5-A: /metrics.json sits at the root (no /v1 prefix) — metrics are not
495
498
  # part of the OpenAI / Anthropic API surface, and Prometheus-style
496
499
  # endpoints conventionally live at the root in v1.5-B.
@@ -32,9 +32,10 @@ from fastapi import APIRouter, Header, HTTPException, Request
32
32
  from fastapi.responses import JSONResponse, StreamingResponse
33
33
 
34
34
  from coderouter.adapters.base import ChatRequest
35
+ from coderouter.adapters.slot_affinity import affinity_key
35
36
  from coderouter.logging import get_logger
36
37
  from coderouter.routing import FallbackEngine, NoProvidersAvailableError
37
- from coderouter.routing.auto_router import RESERVED_PROFILE_NAME, classify
38
+ from coderouter.routing.auto_router import RESERVED_PROFILE_NAME, classify, extract_gateway_hints
38
39
  from coderouter.routing.fallback_trace import current_fallback_trace
39
40
 
40
41
  router = APIRouter()
@@ -199,6 +200,10 @@ async def chat_completions(
199
200
  except Exception as exc: # pydantic.ValidationError, etc.
200
201
  raise HTTPException(status_code=422, detail=str(exc)) from exc
201
202
 
203
+ # v2.18.0: gateway hint headers (routing matchers + KV-slot affinity key).
204
+ gateway_hints = extract_gateway_hints(request.headers)
205
+ chat_req.session_key = affinity_key(gateway_hints)
206
+
202
207
  # Header-based override (body wins if both are set — see module docstring)
203
208
  if chat_req.profile is None and x_coderouter_profile:
204
209
  chat_req.profile = x_coderouter_profile
@@ -226,7 +231,7 @@ async def chat_completions(
226
231
  # When inactive, the engine still falls through to
227
232
  # ``config.default_profile`` on its own — same semantics as pre-v1.6.
228
233
  if chat_req.profile is None and config.default_profile == RESERVED_PROFILE_NAME:
229
- chat_req.profile = classify(payload, config)
234
+ chat_req.profile = classify(payload, config, gateway_hints)
230
235
 
231
236
  # Validate profile exists before we kick off any upstream call
232
237
  if chat_req.profile is not None:
@@ -0,0 +1,269 @@
1
+ """OpenAI Responses API route: ``POST /v1/responses`` (v2.19.0).
2
+
3
+ Lets the OpenAI Codex CLI (Responses-only since 2026-02) use CodeRouter as a
4
+ custom provider::
5
+
6
+ [model_providers.coderouter]
7
+ name = "CodeRouter"
8
+ base_url = "http://127.0.0.1:8088/v1"
9
+ wire_api = "responses"
10
+
11
+ The request is translated to an Anthropic Messages request
12
+ (:mod:`coderouter.translation.responses`) and run through the same fallback
13
+ engine as ``/v1/messages`` — tool-call repair, guards, fallback and the
14
+ v2.16.0 error mapping all apply. Profile selection mirrors the other
15
+ routes: body ``profile`` > ``X-CodeRouter-Profile`` > ``X-CodeRouter-Mode``
16
+ > auto router > default.
17
+
18
+ Failures are reported the way Codex reads them:
19
+
20
+ - before the response commits: an OpenAI-style error body with a real
21
+ HTTP status (400 non-retryable / 429 with ``Retry-After`` / 502);
22
+ - a context overflow on a streaming request: ``response.failed`` with code
23
+ ``context_length_exceeded`` — the only overflow signal Codex recognizes
24
+ (an HTTP 400 is treated as a plain invalid request);
25
+ - after the stream started: ``response.failed`` (``server_error``), then end
26
+ of stream, which Codex retries.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import asyncio
32
+ import contextlib
33
+ import json
34
+ from collections.abc import AsyncIterator
35
+
36
+ from fastapi import APIRouter, Header, Request
37
+ from fastapi.responses import JSONResponse, Response, StreamingResponse
38
+
39
+ from coderouter.adapters.slot_affinity import affinity_key
40
+ from coderouter.guards.context_budget import ContextBudgetRejectError
41
+ from coderouter.guards.tool_loop import ToolCountExceededError, ToolLoopBreakError
42
+ from coderouter.ingress.anthropic_errors import (
43
+ PROMPT_TOO_LONG_PREFIX,
44
+ AnthropicErrorResponse,
45
+ map_no_providers_error,
46
+ )
47
+ from coderouter.ingress.anthropic_routes import (
48
+ _DisconnectWatcher,
49
+ _resolve_stream_timeout_s,
50
+ )
51
+ from coderouter.logging import get_logger
52
+ from coderouter.routing import FallbackEngine, MidStreamError, NoProvidersAvailableError
53
+ from coderouter.routing.auto_router import (
54
+ RESERVED_PROFILE_NAME,
55
+ classify,
56
+ extract_gateway_hints,
57
+ )
58
+ from coderouter.translation import AnthropicStreamEvent
59
+ from coderouter.translation.responses import (
60
+ ResponsesStreamTranslator,
61
+ anthropic_response_to_responses,
62
+ format_sse,
63
+ responses_to_anthropic,
64
+ )
65
+
66
+ router = APIRouter()
67
+ logger = get_logger(__name__)
68
+
69
+ _PROFILE_HEADER = "x-coderouter-profile"
70
+ _MODE_HEADER = "x-coderouter-mode"
71
+
72
+ _OPENAI_TYPE = {
73
+ "invalid_request_error": "invalid_request_error",
74
+ "request_too_large": "invalid_request_error",
75
+ "rate_limit_error": "rate_limit_error",
76
+ "timeout_error": "server_error",
77
+ "api_error": "server_error",
78
+ }
79
+
80
+
81
+ def _openai_error(
82
+ status: int,
83
+ message: str,
84
+ *,
85
+ etype: str,
86
+ code: str | None = None,
87
+ headers: dict[str, str] | None = None,
88
+ ) -> JSONResponse:
89
+ return JSONResponse(
90
+ status_code=status,
91
+ content={"error": {"message": message, "type": etype, "param": None, "code": code}},
92
+ headers=headers or None,
93
+ )
94
+
95
+
96
+ def _is_overflow(mapped: AnthropicErrorResponse) -> bool:
97
+ return mapped.status_code == 400 and mapped.message.lower().startswith(PROMPT_TOO_LONG_PREFIX)
98
+
99
+
100
+ def _mapped_to_http(mapped: AnthropicErrorResponse) -> JSONResponse:
101
+ code = None
102
+ if _is_overflow(mapped):
103
+ code = "context_length_exceeded"
104
+ elif mapped.status_code == 429:
105
+ code = "rate_limit_exceeded"
106
+ return _openai_error(
107
+ mapped.status_code,
108
+ mapped.message,
109
+ etype=_OPENAI_TYPE.get(mapped.error_type, "server_error"),
110
+ code=code,
111
+ headers=dict(mapped.headers),
112
+ )
113
+
114
+
115
+ def _failed_stream(translator: ResponsesStreamTranslator, code: str, message: str) -> StreamingResponse:
116
+ async def gen() -> AsyncIterator[str]:
117
+ for ev in translator.start():
118
+ yield format_sse(ev)
119
+ for ev in translator.failed(code, message):
120
+ yield format_sse(ev)
121
+
122
+ return StreamingResponse(gen(), media_type="text/event-stream", headers={"Cache-Control": "no-cache"})
123
+
124
+
125
+ @router.post("/responses", response_model=None)
126
+ async def responses(
127
+ request: Request,
128
+ x_coderouter_profile: str | None = Header(default=None, alias=_PROFILE_HEADER),
129
+ x_coderouter_mode: str | None = Header(default=None, alias=_MODE_HEADER),
130
+ ) -> Response:
131
+ """OpenAI Responses API endpoint (streaming and non-streaming)."""
132
+ engine: FallbackEngine = request.app.state.engine
133
+ config = request.app.state.config
134
+
135
+ try:
136
+ body = await request.json()
137
+ except (json.JSONDecodeError, ValueError):
138
+ return _openai_error(400, "request body must be JSON", etype="invalid_request_error")
139
+ if not isinstance(body, dict):
140
+ return _openai_error(400, "request body must be a JSON object", etype="invalid_request_error")
141
+
142
+ try:
143
+ anth_req, tool_map = responses_to_anthropic(body)
144
+ except Exception as exc: # pydantic ValidationError and shape errors
145
+ return _openai_error(400, f"could not translate request: {exc}", etype="invalid_request_error")
146
+
147
+ model = body.get("model") if isinstance(body.get("model"), str) else "coderouter"
148
+
149
+ # Conversation key for llama-server slot affinity: Claude-style hint
150
+ # headers when present, else Codex's own ``session-id`` header.
151
+ hints = extract_gateway_hints(request.headers)
152
+ anth_req.session_key = affinity_key(hints) or request.headers.get("session-id") or None
153
+
154
+ if anth_req.profile is None and x_coderouter_profile:
155
+ anth_req.profile = x_coderouter_profile
156
+ if anth_req.profile is None and x_coderouter_mode:
157
+ try:
158
+ anth_req.profile = config.resolve_mode(x_coderouter_mode)
159
+ except KeyError:
160
+ return _openai_error(
161
+ 400, f"unknown mode {x_coderouter_mode!r}", etype="invalid_request_error"
162
+ )
163
+ if anth_req.profile is None and config.default_profile == RESERVED_PROFILE_NAME:
164
+ anth_req.profile = classify(anth_req.model_dump(), config, hints)
165
+ if anth_req.profile is not None:
166
+ try:
167
+ config.profile_by_name(anth_req.profile)
168
+ except KeyError:
169
+ return _openai_error(
170
+ 400, f"unknown profile {anth_req.profile!r}", etype="invalid_request_error"
171
+ )
172
+
173
+ translator = ResponsesStreamTranslator(tool_map, model=model)
174
+
175
+ try:
176
+ anth_req, _ctx = engine.apply_context_budget(anth_req)
177
+ except ContextBudgetRejectError as exc:
178
+ if anth_req.stream:
179
+ return _failed_stream(translator, "context_length_exceeded", str(exc))
180
+ return _openai_error(400, str(exc), etype="invalid_request_error", code="context_length_exceeded")
181
+
182
+ if not anth_req.stream:
183
+ try:
184
+ resp = await engine.generate_anthropic(anth_req)
185
+ except NoProvidersAvailableError as exc:
186
+ return _mapped_to_http(map_no_providers_error(exc))
187
+ except ContextBudgetRejectError as exc:
188
+ return _openai_error(400, str(exc), etype="invalid_request_error", code="context_length_exceeded")
189
+ except (ToolLoopBreakError, ToolCountExceededError) as exc:
190
+ return _openai_error(400, str(exc), etype="invalid_request_error")
191
+ return JSONResponse(
192
+ anthropic_response_to_responses(resp.model_dump(exclude_none=True), tool_map, model=model)
193
+ )
194
+
195
+ # Streaming: pull the first engine event before committing, like
196
+ # /v1/messages (v2.16.0), so pre-content failures get a real status.
197
+ timeout_s = _resolve_stream_timeout_s(engine, anth_req.profile)
198
+ deadline = asyncio.get_running_loop().time() + timeout_s
199
+ source = engine.stream_anthropic(anth_req)
200
+ first: AnthropicStreamEvent | None = None
201
+ watcher = _DisconnectWatcher(request)
202
+ watcher.start()
203
+
204
+ async def _close() -> None:
205
+ with contextlib.suppress(Exception):
206
+ await source.aclose() # type: ignore[attr-defined]
207
+
208
+ try:
209
+ async with asyncio.timeout_at(deadline) as scope:
210
+ first = await anext(source)
211
+ except StopAsyncIteration:
212
+ first = None
213
+ except NoProvidersAvailableError as exc:
214
+ await _close()
215
+ mapped = map_no_providers_error(exc)
216
+ if _is_overflow(mapped):
217
+ return _failed_stream(translator, "context_length_exceeded", mapped.message)
218
+ return _mapped_to_http(mapped)
219
+ except ContextBudgetRejectError as exc:
220
+ await _close()
221
+ return _failed_stream(translator, "context_length_exceeded", str(exc))
222
+ except (ToolLoopBreakError, ToolCountExceededError) as exc:
223
+ await _close()
224
+ return _openai_error(400, str(exc), etype="invalid_request_error")
225
+ except MidStreamError as exc:
226
+ await _close()
227
+ return _failed_stream(translator, "server_error", str(exc))
228
+ except TimeoutError:
229
+ await _close()
230
+ if not scope.expired():
231
+ raise
232
+ return _openai_error(504, f"no upstream event within {timeout_s:.0f}s", etype="server_error")
233
+ except asyncio.CancelledError:
234
+ await _close()
235
+ if watcher.fired:
236
+ watcher.uncancel()
237
+ return Response(status_code=499)
238
+ raise
239
+ except BaseException:
240
+ await _close()
241
+ raise
242
+ finally:
243
+ await watcher.stop()
244
+
245
+ async def gen() -> AsyncIterator[str]:
246
+ try:
247
+ async with asyncio.timeout_at(deadline):
248
+ for ev in translator.start():
249
+ yield format_sse(ev)
250
+ if first is not None:
251
+ for out in translator.feed(first):
252
+ yield format_sse(out)
253
+ async for ev in source:
254
+ for out in translator.feed(ev):
255
+ yield format_sse(out)
256
+ for out in translator.finish():
257
+ yield format_sse(out)
258
+ except TimeoutError:
259
+ logger.warning("responses-stream-timeout", extra={"timeout_s": timeout_s})
260
+ for out in translator.failed("server_error", f"stream exceeded {timeout_s:.0f}s ceiling"):
261
+ yield format_sse(out)
262
+ except (MidStreamError, NoProvidersAvailableError) as exc:
263
+ logger.warning("responses-stream-failed", extra={"error": str(exc)[:300]})
264
+ for out in translator.failed("server_error", str(exc)):
265
+ yield format_sse(out)
266
+ finally:
267
+ await _close()
268
+
269
+ return StreamingResponse(gen(), media_type="text/event-stream", headers={"Cache-Control": "no-cache"})
@@ -36,6 +36,7 @@ from __future__ import annotations
36
36
 
37
37
  import logging
38
38
  import re
39
+ from collections.abc import Mapping
39
40
  from typing import TYPE_CHECKING, Any
40
41
 
41
42
  from coderouter.config.schemas import AutoRouterConfig, AutoRouteRule, RuleMatcher
@@ -169,6 +170,32 @@ def _has_tools_in_body(body: dict[str, Any]) -> bool:
169
170
  return isinstance(functions, list) and len(functions) > 0
170
171
 
171
172
 
173
+ # v2.18.0: Claude Code gateway hint headers → hint keys.
174
+ _HINT_HEADERS: dict[str, str] = {
175
+ "x-claude-code-request-class": "request_class",
176
+ "x-claude-code-agent-type": "agent_type",
177
+ "x-claude-code-compaction": "compaction",
178
+ "x-claude-code-session-id": "session_id",
179
+ "x-claude-code-prompt-id": "prompt_id",
180
+ }
181
+ _TRUTHY = frozenset({"1", "true", "yes", "on"})
182
+
183
+
184
+ def extract_gateway_hints(headers: Mapping[str, str]) -> dict[str, str]:
185
+ """Pull Claude Code's gateway hint headers out of a request.
186
+
187
+ Returns only the hints that are present (lower-cased keys from
188
+ :data:`_HINT_HEADERS`). Header lookup is case-insensitive whenever the
189
+ mapping is (Starlette's ``Headers`` is).
190
+ """
191
+ out: dict[str, str] = {}
192
+ for header, key in _HINT_HEADERS.items():
193
+ value = headers.get(header)
194
+ if value:
195
+ out[key] = value.strip()
196
+ return out
197
+
198
+
172
199
  def _match_rule(
173
200
  rule: AutoRouteRule,
174
201
  message: dict[str, Any] | None,
@@ -176,8 +203,17 @@ def _match_rule(
176
203
  model: str | None,
177
204
  estimated_tokens: int,
178
205
  has_tools: bool,
206
+ hints: Mapping[str, str] | None = None,
179
207
  ) -> bool:
180
208
  m = rule.match
209
+ if m.request_class is not None:
210
+ value = (hints or {}).get("request_class")
211
+ return value is not None and value.lower() == m.request_class.lower()
212
+ if m.agent_type is not None:
213
+ value = (hints or {}).get("agent_type")
214
+ return value is not None and value.lower() == m.agent_type.lower()
215
+ if m.compaction is True:
216
+ return (hints or {}).get("compaction", "").lower() in _TRUTHY
181
217
  if m.has_image is True:
182
218
  return message is not None and _has_image(message)
183
219
  if m.code_fence_ratio_min is not None:
@@ -237,7 +273,11 @@ def _extract_model(body: dict[str, Any]) -> str | None:
237
273
  return None
238
274
 
239
275
 
240
- def classify(body: dict[str, Any], config: CodeRouterConfig) -> str:
276
+ def classify(
277
+ body: dict[str, Any],
278
+ config: CodeRouterConfig,
279
+ hints: Mapping[str, str] | None = None,
280
+ ) -> str:
241
281
  """Resolve an incoming request body to a profile name.
242
282
 
243
283
  Rule order (first match wins) is determined by:
@@ -252,6 +292,10 @@ def classify(body: dict[str, Any], config: CodeRouterConfig) -> str:
252
292
 
253
293
  Emits one of two log events: ``auto-router-resolved`` on match, or
254
294
  ``auto-router-fallthrough`` on default-rule fall.
295
+
296
+ v2.18.0: ``hints`` carries Claude Code's gateway hint headers (see
297
+ :func:`extract_gateway_hints`) for the ``request_class`` /
298
+ ``agent_type`` / ``compaction`` matchers.
255
299
  """
256
300
  user_msg = _latest_user_message(body)
257
301
  text = _extract_text(user_msg) if user_msg is not None else ""
@@ -294,7 +338,7 @@ def classify(body: dict[str, Any], config: CodeRouterConfig) -> str:
294
338
  # present — they short out via ``_match_rule``'s message-None
295
339
  # handling.
296
340
  for rule in rules:
297
- if _match_rule(rule, user_msg, text, model, estimated_tokens, has_tools):
341
+ if _match_rule(rule, user_msg, text, model, estimated_tokens, has_tools, hints):
298
342
  _emit_resolved(rule, user_msg, text, model, estimated_tokens, has_tools)
299
343
  return rule.profile
300
344
 
@@ -194,12 +194,13 @@ def strip_thinking(request: AnthropicRequest) -> AnthropicRequest:
194
194
 
195
195
  # model_dump() serializes extras; roundtripping via validate rebuilds a
196
196
  # clean instance without the dropped key. exclude=True fields (profile,
197
- # anthropic_beta) are omitted by model_dump, so we reassign them.
197
+ # anthropic_beta, session_key) are omitted by model_dump, so we reassign them.
198
198
  dumped = request.model_dump()
199
199
  dumped.pop("thinking", None)
200
200
  stripped = AnthropicRequest.model_validate(dumped)
201
201
  stripped.profile = request.profile
202
202
  stripped.anthropic_beta = request.anthropic_beta
203
+ stripped.session_key = request.session_key
203
204
  return stripped
204
205
 
205
206
 
@@ -450,6 +451,7 @@ def emulate_tool_choice(request: AnthropicRequest) -> AnthropicRequest:
450
451
  emulated = AnthropicRequest.model_validate(dumped)
451
452
  emulated.profile = request.profile
452
453
  emulated.anthropic_beta = request.anthropic_beta
454
+ emulated.session_key = request.session_key
453
455
  return emulated
454
456
 
455
457
 
@@ -522,6 +524,7 @@ def strip_cache_control(request: AnthropicRequest) -> tuple[AnthropicRequest, in
522
524
  stripped = AnthropicRequest.model_validate(dumped)
523
525
  stripped.profile = request.profile
524
526
  stripped.anthropic_beta = request.anthropic_beta
527
+ stripped.session_key = request.session_key
525
528
  return stripped, removed
526
529
 
527
530