coderouter-cli 2.15.0__py3-none-any.whl → 2.16.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.
- coderouter/adapters/anthropic_native.py +4 -0
- coderouter/adapters/base.py +20 -0
- coderouter/adapters/openai_compat.py +4 -0
- coderouter/cli.py +67 -2
- coderouter/config/schemas.py +36 -2
- coderouter/doctor.py +48 -1
- coderouter/doctor_claude_code.py +181 -0
- coderouter/guards/context_budget.py +19 -0
- coderouter/ingress/anthropic_errors.py +185 -0
- coderouter/ingress/anthropic_routes.py +213 -8
- coderouter/ingress/tool_search.py +100 -0
- coderouter/routing/fallback.py +10 -0
- coderouter/vscode_init.py +56 -6
- {coderouter_cli-2.15.0.dist-info → coderouter_cli-2.16.0.dist-info}/METADATA +16 -4
- {coderouter_cli-2.15.0.dist-info → coderouter_cli-2.16.0.dist-info}/RECORD +18 -15
- {coderouter_cli-2.15.0.dist-info → coderouter_cli-2.16.0.dist-info}/WHEEL +1 -1
- {coderouter_cli-2.15.0.dist-info → coderouter_cli-2.16.0.dist-info}/entry_points.txt +0 -0
- {coderouter_cli-2.15.0.dist-info → coderouter_cli-2.16.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -458,6 +458,8 @@ class AnthropicAdapter(BaseAdapter):
|
|
|
458
458
|
provider=self.name,
|
|
459
459
|
status_code=resp.status_code,
|
|
460
460
|
retryable=resp.status_code in _RETRYABLE_STATUSES,
|
|
461
|
+
upstream_body=resp.text,
|
|
462
|
+
retry_after=resp.headers.get("retry-after"),
|
|
461
463
|
)
|
|
462
464
|
|
|
463
465
|
try:
|
|
@@ -570,6 +572,8 @@ class AnthropicAdapter(BaseAdapter):
|
|
|
570
572
|
provider=self.name,
|
|
571
573
|
status_code=resp.status_code,
|
|
572
574
|
retryable=resp.status_code in _RETRYABLE_STATUSES,
|
|
575
|
+
upstream_body=body.decode("utf-8", errors="replace"),
|
|
576
|
+
retry_after=resp.headers.get("retry-after"),
|
|
573
577
|
)
|
|
574
578
|
|
|
575
579
|
# Anthropic SSE block shape:
|
coderouter/adapters/base.py
CHANGED
|
@@ -101,6 +101,12 @@ class StreamChunk(BaseModel):
|
|
|
101
101
|
usage: dict[str, Any] | None = None
|
|
102
102
|
|
|
103
103
|
|
|
104
|
+
#: v2.16.0: max chars of an upstream error body an :class:`AdapterError`
|
|
105
|
+
#: keeps. Error bodies are small; the cap only bounds a misbehaving upstream
|
|
106
|
+
#: that answers an error status with a large HTML page.
|
|
107
|
+
UPSTREAM_BODY_CAP = 4096
|
|
108
|
+
|
|
109
|
+
|
|
104
110
|
class AdapterError(CodeRouterError):
|
|
105
111
|
"""Raised when a provider call fails in a way the fallback engine should retry on."""
|
|
106
112
|
|
|
@@ -111,6 +117,8 @@ class AdapterError(CodeRouterError):
|
|
|
111
117
|
provider: str,
|
|
112
118
|
status_code: int | None = None,
|
|
113
119
|
retryable: bool = True,
|
|
120
|
+
upstream_body: str | None = None,
|
|
121
|
+
retry_after: str | None = None,
|
|
114
122
|
) -> None:
|
|
115
123
|
"""Construct an AdapterError.
|
|
116
124
|
|
|
@@ -125,11 +133,23 @@ class AdapterError(CodeRouterError):
|
|
|
125
133
|
retryable: When True, the fallback engine may try the next
|
|
126
134
|
provider in the chain. When False, the engine stops
|
|
127
135
|
and surfaces the error as a terminal failure.
|
|
136
|
+
upstream_body: v2.16.0 — the upstream's error body (capped at
|
|
137
|
+
:data:`UPSTREAM_BODY_CAP` chars), kept so the ingress can
|
|
138
|
+
hand the upstream's own wording back to the client.
|
|
139
|
+
Claude Code recovers from several 400s (rejected beta
|
|
140
|
+
headers, tool search, context overflow) only when it can
|
|
141
|
+
read the upstream message. Never logged by this class.
|
|
142
|
+
retry_after: v2.16.0 — the upstream's ``Retry-After`` header
|
|
143
|
+
value, verbatim, when it sent one.
|
|
128
144
|
"""
|
|
129
145
|
super().__init__(message)
|
|
130
146
|
self.provider = provider
|
|
131
147
|
self.status_code = status_code
|
|
132
148
|
self.retryable = retryable
|
|
149
|
+
self.upstream_body = (
|
|
150
|
+
upstream_body[:UPSTREAM_BODY_CAP] if upstream_body is not None else None
|
|
151
|
+
)
|
|
152
|
+
self.retry_after = retry_after
|
|
133
153
|
|
|
134
154
|
def __str__(self) -> str:
|
|
135
155
|
"""Render as ``[provider status=NNN] message`` for log trails."""
|
|
@@ -244,6 +244,8 @@ class OpenAICompatAdapter(BaseAdapter):
|
|
|
244
244
|
provider=self.name,
|
|
245
245
|
status_code=resp.status_code,
|
|
246
246
|
retryable=resp.status_code in _RETRYABLE_STATUSES,
|
|
247
|
+
upstream_body=resp.text,
|
|
248
|
+
retry_after=resp.headers.get("retry-after"),
|
|
247
249
|
)
|
|
248
250
|
|
|
249
251
|
try:
|
|
@@ -381,6 +383,8 @@ class OpenAICompatAdapter(BaseAdapter):
|
|
|
381
383
|
provider=self.name,
|
|
382
384
|
status_code=resp.status_code,
|
|
383
385
|
retryable=resp.status_code in _RETRYABLE_STATUSES,
|
|
386
|
+
upstream_body=body.decode("utf-8", errors="replace"),
|
|
387
|
+
retry_after=resp.headers.get("retry-after"),
|
|
384
388
|
)
|
|
385
389
|
async for line in resp.aiter_lines():
|
|
386
390
|
if not line:
|
coderouter/cli.py
CHANGED
|
@@ -165,6 +165,17 @@ def _build_parser() -> argparse.ArgumentParser:
|
|
|
165
165
|
"for live key values. Exit 0 clean / 2 needs attention / 1 leak."
|
|
166
166
|
),
|
|
167
167
|
)
|
|
168
|
+
doctor.add_argument(
|
|
169
|
+
"--check-claude-code",
|
|
170
|
+
action="store_true",
|
|
171
|
+
help=(
|
|
172
|
+
"v2.16.0: check the local Claude Code install for gateway use — "
|
|
173
|
+
"known-bad versions (<2.1.301, 2.1.304) and the env vars that "
|
|
174
|
+
"matter behind a non-Anthropic gateway (ENABLE_TOOL_SEARCH, "
|
|
175
|
+
"CLAUDE_CODE_MAX_CONTEXT_TOKENS, CLAUDE_CODE_AUTO_MODE_SERVER). "
|
|
176
|
+
"No network. Exit 0 OK / 2 needs attention."
|
|
177
|
+
),
|
|
178
|
+
)
|
|
168
179
|
doctor.add_argument(
|
|
169
180
|
"--config",
|
|
170
181
|
default=None,
|
|
@@ -454,6 +465,28 @@ def _build_parser() -> argparse.ArgumentParser:
|
|
|
454
465
|
"generation. Tip: keep secrets in a separate .envrc.local."
|
|
455
466
|
),
|
|
456
467
|
)
|
|
468
|
+
vscode_init.add_argument(
|
|
469
|
+
"--max-context-tokens",
|
|
470
|
+
type=int,
|
|
471
|
+
default=None,
|
|
472
|
+
metavar="N",
|
|
473
|
+
help=(
|
|
474
|
+
"v2.16.0: also write CLAUDE_CODE_MAX_CONTEXT_TOKENS=N so Claude "
|
|
475
|
+
"Code compacts before your local model's context fills up "
|
|
476
|
+
"(since 2.1.285 it assumes 1M behind a gateway). Use the "
|
|
477
|
+
"smallest context window in the profile's chain."
|
|
478
|
+
),
|
|
479
|
+
)
|
|
480
|
+
vscode_init.add_argument(
|
|
481
|
+
"--no-claude-code-env",
|
|
482
|
+
action="store_true",
|
|
483
|
+
help=(
|
|
484
|
+
"v2.16.0: do not write the Claude Code gateway settings "
|
|
485
|
+
"(ENABLE_TOOL_SEARCH=false, CLAUDE_CODE_AUTO_MODE_SERVER=0, "
|
|
486
|
+
"and --max-context-tokens). Use when the chain is "
|
|
487
|
+
"api.anthropic.com only."
|
|
488
|
+
),
|
|
489
|
+
)
|
|
457
490
|
vscode_init.add_argument(
|
|
458
491
|
"--dry-run",
|
|
459
492
|
action="store_true",
|
|
@@ -595,10 +628,16 @@ def _run_doctor(args: argparse.Namespace) -> int:
|
|
|
595
628
|
risks AND broken providers can use a single command.
|
|
596
629
|
"""
|
|
597
630
|
check_secrets = bool(getattr(args, "check_secrets", False))
|
|
598
|
-
|
|
631
|
+
check_claude_code = bool(getattr(args, "check_claude_code", False))
|
|
632
|
+
if (
|
|
633
|
+
args.check_model is None
|
|
634
|
+
and args.check_env is None
|
|
635
|
+
and not check_secrets
|
|
636
|
+
and not check_claude_code
|
|
637
|
+
):
|
|
599
638
|
print(
|
|
600
639
|
"doctor: provide --check-model PROVIDER, --check-env [PATH], "
|
|
601
|
-
"and/or --check-
|
|
640
|
+
"--check-secrets and/or --check-claude-code",
|
|
602
641
|
file=sys.stderr,
|
|
603
642
|
)
|
|
604
643
|
return 1
|
|
@@ -614,6 +653,14 @@ def _run_doctor(args: argparse.Namespace) -> int:
|
|
|
614
653
|
if check_secrets:
|
|
615
654
|
worst_exit = max(worst_exit, _run_check_secrets(args.config))
|
|
616
655
|
|
|
656
|
+
if check_claude_code:
|
|
657
|
+
from coderouter.doctor_claude_code import format_report as _cc_format
|
|
658
|
+
from coderouter.doctor_claude_code import run_check as _cc_run
|
|
659
|
+
|
|
660
|
+
cc_report = _cc_run()
|
|
661
|
+
print(_cc_format(cc_report))
|
|
662
|
+
worst_exit = max(worst_exit, cc_report.exit_code)
|
|
663
|
+
|
|
617
664
|
if args.check_model is not None:
|
|
618
665
|
worst_exit = max(worst_exit, _run_check_model(args))
|
|
619
666
|
|
|
@@ -976,6 +1023,7 @@ def _run_vscode_init(args: argparse.Namespace) -> int:
|
|
|
976
1023
|
"""
|
|
977
1024
|
from coderouter.vscode_init import (
|
|
978
1025
|
DEFAULT_PORT,
|
|
1026
|
+
claude_code_env,
|
|
979
1027
|
exit_code_for,
|
|
980
1028
|
format_result,
|
|
981
1029
|
run_vscode_init,
|
|
@@ -991,6 +1039,22 @@ def _run_vscode_init(args: argparse.Namespace) -> int:
|
|
|
991
1039
|
|
|
992
1040
|
port = args.port if args.port is not None else DEFAULT_PORT
|
|
993
1041
|
|
|
1042
|
+
extra_env: dict[str, str] | None = None
|
|
1043
|
+
max_ctx = getattr(args, "max_context_tokens", None)
|
|
1044
|
+
if getattr(args, "no_claude_code_env", False):
|
|
1045
|
+
if max_ctx is not None:
|
|
1046
|
+
print(
|
|
1047
|
+
"vscode-init: --max-context-tokens has no effect with --no-claude-code-env",
|
|
1048
|
+
file=sys.stderr,
|
|
1049
|
+
)
|
|
1050
|
+
return 2
|
|
1051
|
+
else:
|
|
1052
|
+
try:
|
|
1053
|
+
extra_env = claude_code_env(max_context_tokens=max_ctx)
|
|
1054
|
+
except ValueError as exc:
|
|
1055
|
+
print(f"vscode-init: {exc}", file=sys.stderr)
|
|
1056
|
+
return 2
|
|
1057
|
+
|
|
994
1058
|
try:
|
|
995
1059
|
result = run_vscode_init(
|
|
996
1060
|
target,
|
|
@@ -999,6 +1063,7 @@ def _run_vscode_init(args: argparse.Namespace) -> int:
|
|
|
999
1063
|
with_envrc=args.with_envrc,
|
|
1000
1064
|
dry_run=args.dry_run,
|
|
1001
1065
|
force=args.force,
|
|
1066
|
+
extra_env=extra_env,
|
|
1002
1067
|
)
|
|
1003
1068
|
except FileNotFoundError as exc:
|
|
1004
1069
|
# Raised only when target vanishes between the pre-check above
|
coderouter/config/schemas.py
CHANGED
|
@@ -1089,7 +1089,13 @@ class FallbackChain(BaseModel):
|
|
|
1089
1089
|
# (``context_budget_preserve_last_n``) are always
|
|
1090
1090
|
# kept, and tool_use / tool_result pairs are preserved
|
|
1091
1091
|
# atomically to avoid breaking agent loops.
|
|
1092
|
-
|
|
1092
|
+
# * ``reject`` — v2.16.0: ``warn`` + at ``context_budget_trim_threshold``
|
|
1093
|
+
# refuse the request with Anthropic's own overflow error
|
|
1094
|
+
# (HTTP 400, ``prompt is too long: ...``). Claude Code
|
|
1095
|
+
# answers that by compacting the conversation itself
|
|
1096
|
+
# (a summary, not a silent cut), so this is the
|
|
1097
|
+
# recommended action for Claude Code sessions.
|
|
1098
|
+
context_budget_action: Literal["off", "warn", "trim", "reject"] = Field(
|
|
1093
1099
|
default="off",
|
|
1094
1100
|
description=(
|
|
1095
1101
|
"v2.0-F (L1): action when estimated request tokens approach "
|
|
@@ -1097,7 +1103,10 @@ class FallbackChain(BaseModel):
|
|
|
1097
1103
|
"disables the guard entirely. ``warn`` emits a log and "
|
|
1098
1104
|
"response header at ``context_budget_warn_threshold``. "
|
|
1099
1105
|
"``trim`` additionally removes old messages at "
|
|
1100
|
-
"``context_budget_trim_threshold`` to reclaim context space."
|
|
1106
|
+
"``context_budget_trim_threshold`` to reclaim context space. "
|
|
1107
|
+
"``reject`` (v2.16.0) instead answers HTTP 400 "
|
|
1108
|
+
"``prompt is too long`` at that threshold so the client "
|
|
1109
|
+
"compacts the conversation itself (Claude Code does)."
|
|
1101
1110
|
),
|
|
1102
1111
|
)
|
|
1103
1112
|
context_budget_warn_threshold: float = Field(
|
|
@@ -1222,6 +1231,31 @@ class FallbackChain(BaseModel):
|
|
|
1222
1231
|
# --- v2.0-H (L6): Mid-stream partial stitching --------------------------
|
|
1223
1232
|
# * ``off`` — discard partial content on mid-stream failure (legacy).
|
|
1224
1233
|
# * ``surface`` — return partial content as a truncated-but-valid response.
|
|
1234
|
+
# v2.16.0 (tool search): Claude Code 2.1.304+ turns tool search on behind
|
|
1235
|
+
# a custom ANTHROPIC_BASE_URL. The request then carries a server-side
|
|
1236
|
+
# tool-search tool (``type: tool_search_tool_*``) and tools marked
|
|
1237
|
+
# ``defer_loading: true``, which only api.anthropic.com executes. A
|
|
1238
|
+
# local model sees the search tool as an ordinary function (and may
|
|
1239
|
+
# "call" it), while every deferred MCP tool lands in its context anyway.
|
|
1240
|
+
# Claude Code retries without tool search when the gateway answers 400.
|
|
1241
|
+
# * ``auto`` — ``passthrough`` when every provider in the chain
|
|
1242
|
+
# is ``kind: anthropic`` on api.anthropic.com,
|
|
1243
|
+
# otherwise ``reject`` (default).
|
|
1244
|
+
# * ``reject`` — answer 400 so the client turns tool search off.
|
|
1245
|
+
# * ``expand`` — drop the search tool and the ``defer_loading``
|
|
1246
|
+
# flags; every tool is sent up front.
|
|
1247
|
+
# * ``passthrough`` — forward unchanged (pre-v2.16.0 behaviour).
|
|
1248
|
+
deferred_tools_action: Literal["auto", "reject", "expand", "passthrough"] = Field(
|
|
1249
|
+
default="auto",
|
|
1250
|
+
description=(
|
|
1251
|
+
"v2.16.0: what to do with Claude Code tool search "
|
|
1252
|
+
"(``defer_loading`` tools / ``tool_search_tool_*``). ``auto`` "
|
|
1253
|
+
"passes it through only for chains made entirely of "
|
|
1254
|
+
"api.anthropic.com providers and rejects it (HTTP 400, which "
|
|
1255
|
+
"makes Claude Code retry without tool search) otherwise."
|
|
1256
|
+
),
|
|
1257
|
+
)
|
|
1258
|
+
|
|
1225
1259
|
partial_stitch_action: Literal["off", "surface"] = Field(
|
|
1226
1260
|
default="off",
|
|
1227
1261
|
description=(
|
coderouter/doctor.py
CHANGED
|
@@ -635,6 +635,49 @@ _PROBE_TOOL_SPEC_ANTHROPIC = {
|
|
|
635
635
|
}
|
|
636
636
|
|
|
637
637
|
|
|
638
|
+
# v2.15.1: llama.cpp changed ``llama-server``'s default listen port from
|
|
639
|
+
# 8080 to 9931 (ggml-org/llama.cpp#30159, build b11521, 2026-10-09). A server
|
|
640
|
+
# started without ``--port`` on a new build is invisible to a provider that
|
|
641
|
+
# still points at :8080, and the reverse holds for configs written against
|
|
642
|
+
# the new default. When the basic probe cannot connect to one of those two
|
|
643
|
+
# ports on a loopback host, check the other one so the transport error can
|
|
644
|
+
# name the likely cause instead of looking like "server not running".
|
|
645
|
+
_LLAMACPP_PORT_PAIR: dict[int, int] = {8080: 9931, 9931: 8080}
|
|
646
|
+
_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
async def _llamacpp_port_hint(base_url: object) -> str | None:
|
|
650
|
+
"""Return a hint when the other llama.cpp default port answers.
|
|
651
|
+
|
|
652
|
+
Only fires for loopback hosts on port 8080 or 9931. The alternate
|
|
653
|
+
port is probed at ``GET /health`` (llama-server's readiness route)
|
|
654
|
+
with a short timeout on the IPv4 literal — ``localhost`` can resolve
|
|
655
|
+
to ``::1`` first on macOS, where llama-server is not listening. The
|
|
656
|
+
config is never rewritten; the operator decides.
|
|
657
|
+
"""
|
|
658
|
+
try:
|
|
659
|
+
parsed = httpx.URL(str(base_url))
|
|
660
|
+
except (httpx.InvalidURL, TypeError):
|
|
661
|
+
return None
|
|
662
|
+
if parsed.host not in _LOOPBACK_HOSTS or parsed.port not in _LLAMACPP_PORT_PAIR:
|
|
663
|
+
return None
|
|
664
|
+
other = _LLAMACPP_PORT_PAIR[parsed.port]
|
|
665
|
+
try:
|
|
666
|
+
async with httpx.AsyncClient(timeout=1.5) as client:
|
|
667
|
+
resp = await client.get(f"http://127.0.0.1:{other}/health")
|
|
668
|
+
except httpx.HTTPError:
|
|
669
|
+
return None
|
|
670
|
+
if resp.status_code >= 500:
|
|
671
|
+
return None
|
|
672
|
+
return (
|
|
673
|
+
f"Something is answering on port {other} instead. llama.cpp "
|
|
674
|
+
f"builds b11521+ listen on 9931 when started without --port "
|
|
675
|
+
f"(older builds: 8080). Either start llama-server with "
|
|
676
|
+
f"--port {parsed.port}, or change this provider's base_url to "
|
|
677
|
+
f"port {other}"
|
|
678
|
+
)
|
|
679
|
+
|
|
680
|
+
|
|
638
681
|
async def _probe_auth_and_basic_chat(
|
|
639
682
|
provider: ProviderConfig,
|
|
640
683
|
) -> ProbeResult:
|
|
@@ -670,10 +713,14 @@ async def _probe_auth_and_basic_chat(
|
|
|
670
713
|
)
|
|
671
714
|
|
|
672
715
|
if status is None:
|
|
716
|
+
detail = f"could not reach {url}: {raw}"
|
|
717
|
+
hint = await _llamacpp_port_hint(provider.base_url)
|
|
718
|
+
if hint:
|
|
719
|
+
detail = f"{detail}. {hint}"
|
|
673
720
|
return ProbeResult(
|
|
674
721
|
name="auth+basic-chat",
|
|
675
722
|
verdict=ProbeVerdict.TRANSPORT_ERROR,
|
|
676
|
-
detail=
|
|
723
|
+
detail=detail,
|
|
677
724
|
)
|
|
678
725
|
|
|
679
726
|
if status in (401, 403):
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""``coderouter doctor --check-claude-code`` (v2.16.0).
|
|
2
|
+
|
|
3
|
+
Local-only checks for a Claude Code install that talks to CodeRouter:
|
|
4
|
+
|
|
5
|
+
1. **Version.** Known gateway-relevant regressions:
|
|
6
|
+
|
|
7
|
+
- before 2.1.301: compaction could repeat when the response's ``model``
|
|
8
|
+
name differs from the requested one (every translating gateway);
|
|
9
|
+
- exactly 2.1.304: every request failed behind a gateway that rejects
|
|
10
|
+
tool search (fixed in 2.1.305).
|
|
11
|
+
|
|
12
|
+
2. **Environment.** Variables that matter behind a non-Anthropic gateway
|
|
13
|
+
(see ``coderouter vscode-init``):
|
|
14
|
+
|
|
15
|
+
- ``ENABLE_TOOL_SEARCH`` unset → tool search is on by default since
|
|
16
|
+
2.1.304; CodeRouter refuses it (``deferred_tools_action``) and Claude
|
|
17
|
+
Code retries without it — works, but costs a round trip per session;
|
|
18
|
+
- ``CLAUDE_CODE_MAX_CONTEXT_TOKENS`` unset on 2.1.285+ → Claude Code may
|
|
19
|
+
assume a 1M window and compact far too late for a local model;
|
|
20
|
+
- ``CLAUDE_CODE_AUTO_MODE_SERVER`` unset → auto mode asks the gateway
|
|
21
|
+
for a server-side classifier a local backend does not have.
|
|
22
|
+
|
|
23
|
+
No network, no config file. Exit codes follow the other doctor checks:
|
|
24
|
+
0 = OK, 2 = needs attention, 1 = could not run.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import os
|
|
30
|
+
import re
|
|
31
|
+
import shutil
|
|
32
|
+
import subprocess
|
|
33
|
+
from collections.abc import Callable, Mapping
|
|
34
|
+
from dataclasses import dataclass, field
|
|
35
|
+
|
|
36
|
+
_VERSION_RE = re.compile(r"(\d+)\.(\d+)\.(\d+)")
|
|
37
|
+
|
|
38
|
+
Version = tuple[int, int, int]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class ClaudeCodeFinding:
|
|
43
|
+
level: str # "ok" | "warn" | "info"
|
|
44
|
+
message: str
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class ClaudeCodeReport:
|
|
49
|
+
version: Version | None
|
|
50
|
+
findings: list[ClaudeCodeFinding] = field(default_factory=list)
|
|
51
|
+
error: str | None = None
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def exit_code(self) -> int:
|
|
55
|
+
if self.error is not None:
|
|
56
|
+
return 1
|
|
57
|
+
return 2 if any(f.level == "warn" for f in self.findings) else 0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def parse_version(text: str) -> Version | None:
|
|
61
|
+
m = _VERSION_RE.search(text)
|
|
62
|
+
if m is None:
|
|
63
|
+
return None
|
|
64
|
+
return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _fmt(v: Version) -> str:
|
|
68
|
+
return ".".join(str(p) for p in v)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def check(version: Version | None, env: Mapping[str, str]) -> list[ClaudeCodeFinding]:
|
|
72
|
+
"""Pure check: findings for a Claude Code version and an environment."""
|
|
73
|
+
out: list[ClaudeCodeFinding] = []
|
|
74
|
+
if version is not None:
|
|
75
|
+
if version < (2, 1, 301):
|
|
76
|
+
out.append(
|
|
77
|
+
ClaudeCodeFinding(
|
|
78
|
+
"warn",
|
|
79
|
+
f"Claude Code {_fmt(version)} is older than 2.1.301: compaction can "
|
|
80
|
+
"repeat behind a gateway that reports a different model name. "
|
|
81
|
+
"Update Claude Code.",
|
|
82
|
+
)
|
|
83
|
+
)
|
|
84
|
+
elif version == (2, 1, 304):
|
|
85
|
+
out.append(
|
|
86
|
+
ClaudeCodeFinding(
|
|
87
|
+
"warn",
|
|
88
|
+
"Claude Code 2.1.304 fails every request behind a gateway that "
|
|
89
|
+
"rejects tool search (fixed in 2.1.305). Update Claude Code, or "
|
|
90
|
+
"set ENABLE_TOOL_SEARCH=false.",
|
|
91
|
+
)
|
|
92
|
+
)
|
|
93
|
+
else:
|
|
94
|
+
out.append(ClaudeCodeFinding("ok", f"Claude Code {_fmt(version)}"))
|
|
95
|
+
|
|
96
|
+
if env.get("ENABLE_TOOL_SEARCH", "").lower() in ("false", "0"):
|
|
97
|
+
out.append(ClaudeCodeFinding("ok", "ENABLE_TOOL_SEARCH=false"))
|
|
98
|
+
else:
|
|
99
|
+
out.append(
|
|
100
|
+
ClaudeCodeFinding(
|
|
101
|
+
"warn",
|
|
102
|
+
"ENABLE_TOOL_SEARCH is not false: Claude Code 2.1.304+ starts each "
|
|
103
|
+
"session with tool search, which only api.anthropic.com runs. "
|
|
104
|
+
"CodeRouter refuses it and Claude Code retries without it. Set "
|
|
105
|
+
"ENABLE_TOOL_SEARCH=false (coderouter vscode-init does) to skip "
|
|
106
|
+
"that round trip.",
|
|
107
|
+
)
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
if "CLAUDE_CODE_MAX_CONTEXT_TOKENS" in env:
|
|
111
|
+
out.append(
|
|
112
|
+
ClaudeCodeFinding(
|
|
113
|
+
"ok", f"CLAUDE_CODE_MAX_CONTEXT_TOKENS={env['CLAUDE_CODE_MAX_CONTEXT_TOKENS']}"
|
|
114
|
+
)
|
|
115
|
+
)
|
|
116
|
+
elif version is None or version >= (2, 1, 285):
|
|
117
|
+
out.append(
|
|
118
|
+
ClaudeCodeFinding(
|
|
119
|
+
"warn",
|
|
120
|
+
"CLAUDE_CODE_MAX_CONTEXT_TOKENS is not set: since 2.1.285 Claude Code "
|
|
121
|
+
"may assume a 1M window behind a gateway and compact long after a "
|
|
122
|
+
"local model has overflowed. Set it to your smallest local context "
|
|
123
|
+
"window (coderouter vscode-init --max-context-tokens N), and/or use "
|
|
124
|
+
"context_budget_action: reject in the profile.",
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
if env.get("CLAUDE_CODE_AUTO_MODE_SERVER") == "0":
|
|
129
|
+
out.append(ClaudeCodeFinding("ok", "CLAUDE_CODE_AUTO_MODE_SERVER=0"))
|
|
130
|
+
else:
|
|
131
|
+
out.append(
|
|
132
|
+
ClaudeCodeFinding(
|
|
133
|
+
"warn",
|
|
134
|
+
"CLAUDE_CODE_AUTO_MODE_SERVER is not 0: on a gateway, auto mode "
|
|
135
|
+
"defaults to a server-side classifier that a local backend does not "
|
|
136
|
+
"provide. Set CLAUDE_CODE_AUTO_MODE_SERVER=0.",
|
|
137
|
+
)
|
|
138
|
+
)
|
|
139
|
+
return out
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _claude_version(run: Callable[[list[str]], str] | None = None) -> tuple[Version | None, str | None]:
|
|
143
|
+
if run is None:
|
|
144
|
+
exe = shutil.which("claude")
|
|
145
|
+
if exe is None:
|
|
146
|
+
return None, "`claude` not found on PATH (version checks skipped)"
|
|
147
|
+
|
|
148
|
+
def run(cmd: list[str]) -> str:
|
|
149
|
+
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=15, check=False)
|
|
150
|
+
return proc.stdout + proc.stderr
|
|
151
|
+
|
|
152
|
+
cmd = [exe, "--version"]
|
|
153
|
+
else:
|
|
154
|
+
cmd = ["claude", "--version"]
|
|
155
|
+
try:
|
|
156
|
+
text = run(cmd)
|
|
157
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
158
|
+
return None, f"could not run `claude --version`: {exc}"
|
|
159
|
+
version = parse_version(text)
|
|
160
|
+
if version is None:
|
|
161
|
+
return None, f"could not parse `claude --version` output: {text.strip()[:80]!r}"
|
|
162
|
+
return version, None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def run_check(
|
|
166
|
+
env: Mapping[str, str] | None = None,
|
|
167
|
+
run: Callable[[list[str]], str] | None = None,
|
|
168
|
+
) -> ClaudeCodeReport:
|
|
169
|
+
version, note = _claude_version(run)
|
|
170
|
+
findings = check(version, os.environ if env is None else env)
|
|
171
|
+
if note:
|
|
172
|
+
findings.insert(0, ClaudeCodeFinding("info", note))
|
|
173
|
+
return ClaudeCodeReport(version=version, findings=findings)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def format_report(report: ClaudeCodeReport) -> str:
|
|
177
|
+
lines = ["Claude Code (behind CodeRouter)"]
|
|
178
|
+
for f in report.findings:
|
|
179
|
+
mark = {"ok": "OK ", "warn": "WARN", "info": "INFO"}.get(f.level, f.level.upper())
|
|
180
|
+
lines.append(f" [{mark}] {f.message}")
|
|
181
|
+
return "\n".join(lines)
|
|
@@ -87,6 +87,25 @@ if TYPE_CHECKING:
|
|
|
87
87
|
# ---------------------------------------------------------------------------
|
|
88
88
|
|
|
89
89
|
|
|
90
|
+
class ContextBudgetRejectError(Exception):
|
|
91
|
+
"""v2.16.0: ``context_budget_action: reject`` refused an oversized request.
|
|
92
|
+
|
|
93
|
+
The ingress answers with Anthropic's overflow error (HTTP 400,
|
|
94
|
+
``prompt is too long: ...``) so the client compacts the conversation
|
|
95
|
+
itself. Carries the numbers for the message and the log line.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
def __init__(self, *, estimated_tokens: int, max_context_tokens: int, profile: str) -> None:
|
|
99
|
+
self.estimated_tokens = estimated_tokens
|
|
100
|
+
self.max_context_tokens = max_context_tokens
|
|
101
|
+
self.profile = profile
|
|
102
|
+
super().__init__(
|
|
103
|
+
f"prompt is too long: ~{estimated_tokens} tokens > "
|
|
104
|
+
f"{max_context_tokens} maximum (CodeRouter profile {profile!r}, "
|
|
105
|
+
"estimated)"
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
90
109
|
@dataclass(frozen=True, slots=True)
|
|
91
110
|
class ContextBudgetEstimate:
|
|
92
111
|
"""Result of a context-budget estimation check."""
|