Skip to content

Commit 53ed029

Browse files
authored
Merge pull request #11 from payne0420/feat/advertise-1m
Advertise [1m] so configured 1M-capable Claude routes get the 1M window
2 parents b9d4c42 + cd7ce23 commit 53ed029

5 files changed

Lines changed: 94 additions & 37 deletions

File tree

‎bin/ultracode‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ BASE_URL="http://127.0.0.1:${PORT}"
6161
# append [1m] to 1M-capable Claude base ids before launch. Disable with
6262
# UC_FORCE_1M=0; override the capable set with UC_1M_MODELS (comma-separated).
6363
UC_FORCE_1M="${UC_FORCE_1M:-1}"
64-
UC_1M_MODELS="${UC_1M_MODELS:-claude-opus-4-8,claude-opus-4-7,claude-opus-4-6,claude-sonnet-4-6}"
64+
UC_1M_MODELS="${UC_1M_MODELS:-claude-opus-4-8,claude-opus-4-7,claude-opus-4-6,claude-sonnet-4-6,claude-opus}"
6565
uc_add_1m() {
6666
# Echo $1 with a [1m] suffix iff it is a bare, 1M-capable Claude id. Anything
6767
# else (Auto Router, Gemini/GPT/Composer, Haiku, already-suffixed, empty) is

‎docs/TROUBLESHOOTING.md‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -296,15 +296,24 @@ the 200k window even though Opus 4.8 / Opus 4.7 / Opus 4.6 / Sonnet 4.6 serve 1M
296296
natively on the Anthropic API. Nothing is actually lost upstream — the window is
297297
just mis-sized in the client.
298298

299-
**Fix.** The launcher now appends `[1m]` automatically when the chosen
300-
orchestrator is a 1M-capable Claude model. Relaunch, pick the model, and confirm
299+
**Fix.** Two parts work together. (1) The **launcher** appends `[1m]` to a
300+
1M-capable Claude model chosen at launch. (2) The **proxy** also *advertises* the
301+
`[1m]` suffix on `/v1/models` + `/healthz` for any **configured real-Claude
302+
passthrough route** whose upstream model is 1M-capable (e.g. a `claude-opus` route
303+
mapping to `claude-opus-4-8`) — so even an **in-session `/model` switch** (not just
304+
the launch-time pick) gets the 1M window. The proxy strips the `[1m]` again before
305+
routing, so it never reaches the backend. Relaunch, pick the model, and confirm
301306
`/context` reads `/ 1M`.
302307

303-
- **Disable it** (back to bare ids): set `UC_FORCE_1M=0`.
304-
- **Change the capable set:** set `UC_1M_MODELS` to a comma-separated list of base
305-
ids (default `claude-opus-4-8,claude-opus-4-7,claude-opus-4-6,claude-sonnet-4-6`).
306-
- **Not affected:** Haiku 4.5 (200k only), `claude-auto`, and non-Claude routes
307-
(Gemini / GPT / Composer) are never given a `[1m]` suffix.
308+
- **Disable launcher suffixing** (back to bare ids): set `UC_FORCE_1M=0`.
309+
- **Change the launcher's capable set:** set `UC_1M_MODELS` to a comma-separated
310+
list of base ids (default `claude-opus-4-8,claude-opus-4-7,claude-opus-4-6,claude-sonnet-4-6,claude-opus`).
311+
- **Disable proxy advertising:** set `UC_ADVERTISE_1M=0`. Change which upstream
312+
models count as 1M with `UC_1M_UPSTREAM` (comma-separated upstream model ids;
313+
default the Opus 4.6–4.8 + Sonnet 4.6 family).
314+
- **Not affected:** Haiku 4.5 (200k only), `claude-auto`, worker (`Worker → …`)
315+
entries, and non-Claude routes (Gemini / GPT / Composer) never get a `[1m]`
316+
suffix.
308317
- **Caveat:** if your Anthropic-passthrough hop can fall back to a backend that
309318
only supports 200k, a conversation that grows past 200k may then fail there —
310319
make sure that fallback also honors 1M.

‎proxy.py‎

Lines changed: 55 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,46 @@
146146
DIRECTIVES = {"planner": None, "strip": True} # filled from config in main()
147147
_ROUTE_ALIASES = {} # normalized token -> concrete route id
148148

149+
# 1M context window: Claude Code sizes its context meter (and auto-compaction) to
150+
# 1M only when the model id it holds carries a "[1m]" suffix. For a real-Claude
151+
# passthrough route whose upstream model is 1M-capable, we ADVERTISE the picker id
152+
# with that suffix on /v1/models + /healthz, so even an in-session /model switch
153+
# (not just a launch-time pick) gets the 1M window. The suffix is a client-side
154+
# convention, not an Anthropic model id: it is stripped before routing and
155+
# normalized off the sticky orchestrator/worker selection, so internal ids stay
156+
# clean. Disable with UC_ADVERTISE_1M=0. See docs/DIRECTIVES.md / PR #8 + #10.
157+
_ONEM_SUFFIX = "[1m]"
158+
ADVERTISE_1M = os.environ.get("UC_ADVERTISE_1M", "1") != "0"
159+
_CONTEXT_1M_UPSTREAM = set(t.strip() for t in os.environ.get(
160+
"UC_1M_UPSTREAM",
161+
"claude-opus-4-8,claude-opus-4-7,claude-opus-4-6,claude-sonnet-4-6").split(",") if t.strip())
162+
163+
164+
def _strip_1m(mid):
165+
"""Model id without a trailing [1m] window suffix (the client convention)."""
166+
if isinstance(mid, str) and mid.endswith(_ONEM_SUFFIX):
167+
return mid[:-len(_ONEM_SUFFIX)]
168+
return mid
169+
170+
171+
def _advertise_id(model_entry):
172+
"""The id to advertise for a configured model on /v1/models + /healthz. Appends
173+
[1m] when ADVERTISE_1M is on and the model is a real-Claude PASSTHROUGH route to
174+
a 1M-capable upstream model, so Claude Code renders the 1M window for it (incl.
175+
in-session /model picks). Worker entries and non-passthrough routes are returned
176+
unchanged. Never raises."""
177+
mid = model_entry.get("id") if isinstance(model_entry, dict) else None
178+
if not (ADVERTISE_1M and isinstance(mid, str)):
179+
return mid
180+
if mid.endswith(_ONEM_SUFFIX) or mid.startswith(WORKER_ID_PREFIX):
181+
return mid
182+
slot = UC_SLOT_MAP.get(mid)
183+
if not isinstance(slot, dict) or slot.get("type") not in (None, "anthropic"):
184+
return mid # passthrough (real Claude) only
185+
if (slot.get("model") or mid) in _CONTEXT_1M_UPSTREAM:
186+
return mid + _ONEM_SUFFIX
187+
return mid
188+
149189
try:
150190
UC_MODEL_MAP = json.loads(os.environ.get("UC_MODEL_MAP", "") or "{}")
151191
if not isinstance(UC_MODEL_MAP, dict):
@@ -566,6 +606,7 @@ def _set_selection(orch=None, worker=None):
566606
"""Directly pre-set the sticky orchestrator/worker selection (used by the
567607
two-column pre-launch selector via POST /uc/select). Either may be None to
568608
leave that tier unchanged. Returns the resolved active selection dict."""
609+
orch, worker = _strip_1m(orch), _strip_1m(worker) # selections store clean ids
569610
with _SEL_LOCK:
570611
if orch is not None:
571612
_ACTIVE["orch"] = orch or None
@@ -584,6 +625,7 @@ def _select_target(mid, tier: str):
584625
fresh sessions behave exactly as before."""
585626
if not ORCH_WORKER:
586627
return mid
628+
mid = _strip_1m(mid) # a [1m]-suffixed pick maps to its clean route id
587629
with _SEL_LOCK:
588630
if mid in _WORKER_MAP:
589631
_ACTIVE["worker"] = _WORKER_MAP[mid]
@@ -893,14 +935,14 @@ def transform_messages_body(raw: bytes):
893935
route = {}
894936

895937
# 1M context window: Claude Code appends a "[1m]" suffix to a model id to ask
896-
# the client for the 1M window (it also sends the context-1m beta header; see
897-
# the launchers' UC_FORCE_1M / [1m] handling). That suffix is a client-side
898-
# convention, not an Anthropic model id, so it must not reach routing (it would
899-
# not match a configured route or an orchestrator/worker pick) or the upstream.
900-
# Strip it up front so "<id>[1m]" behaves exactly like "<id>" everywhere below;
901-
# the 1M window is unaffected because it rides the beta header, left untouched.
902-
if isinstance(model_before, str) and model_before.endswith("[1m]"):
903-
model_before = model_before[:-len("[1m]")]
938+
# the client for the 1M window (it also sends the context-1m beta header). That
939+
# suffix is a client-side convention, not an Anthropic model id, so it must not
940+
# reach routing (it wouldn't match a route) or the upstream. Strip it up front
941+
# so "<id>[1m]" behaves exactly like "<id>" everywhere below; the 1M window is
942+
# unaffected because it comes from the beta header, which we leave untouched.
943+
stripped = _strip_1m(model_before)
944+
if stripped != model_before:
945+
model_before = stripped
904946
body["model"] = model_before
905947
changed = True
906948

@@ -1918,7 +1960,7 @@ def _maybe_health(self) -> bool:
19181960
"candidates": [{"id": c["id"], "cost": c.get("cost")}
19191961
for c in _router_available_candidates()],
19201962
},
1921-
"custom_models": [{"id": m["id"], "display_name": m["display_name"]}
1963+
"custom_models": [{"id": _advertise_id(m), "display_name": m["display_name"]}
19221964
for m in UC_MODELS],
19231965
"stock_models": [{"id": m["id"], "display_name": m["display_name"]}
19241966
for m in _stock_models()],
@@ -2036,9 +2078,10 @@ def _handle_models(self) -> bool:
20362078
existing.add(m["id"])
20372079
stock_families.add(fam)
20382080
for m in UC_MODELS:
2039-
if m["id"] not in existing:
2040-
data.append(dict(m))
2041-
existing.add(m["id"])
2081+
adv = _advertise_id(m)
2082+
if adv not in existing:
2083+
data.append({**m, "id": adv})
2084+
existing.add(adv)
20422085
self._raw(200, "application/json", json.dumps(base).encode("utf-8"))
20432086
return True
20442087

‎test_proxy.py‎

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -263,21 +263,6 @@ def main():
263263
assert up._expand_env("Bearer ${MOCK_KEY}") == "Bearer secret123"
264264
print("[ok] ${ENV} expansion in route auth")
265265

266-
# PR #8 companion: Claude Code's [1m] context-window suffix on the model id
267-
# is stripped before routing, so "<id>[1m]" still matches "<id>"'s route
268-
# (the 1M window itself rides the context-1m beta header, not the id). A
269-
# naive exact-match lookup would otherwise miss the route once the launcher
270-
# appends [1m] to a 1M-capable Claude pick.
271-
_saved_slots = up.UC_SLOT_MAP
272-
up.UC_SLOT_MAP = {"claude-big": {"type": "openai_compat", "model": "big-real",
273-
"upstream": mock + "/v1", "auth": "Bearer ${MOCK_KEY}"}}
274-
out_1m, _ = up.transform_messages_body(json.dumps({
275-
"model": "claude-big[1m]", "max_tokens": 8,
276-
"messages": [{"role": "user", "content": "hi"}]}).encode())
277-
assert json.loads(out_1m)["model"] == "big-real", json.loads(out_1m)["model"]
278-
up.UC_SLOT_MAP = _saved_slots
279-
print("[ok] 1M [1m] window suffix stripped before routing")
280-
281266
# Stock Claude models: the built-in fallback so real Claude stays in
282267
# /model even with no upstream list. Toggle + override are honored, and
283268
# every advertised id obeys Claude Code's /^(claude|anthropic)/i rule.
@@ -457,6 +442,26 @@ def _pin(text):
457442
# plan-mode detection drives the optional planner auto-route
458443
assert up._is_plan_mode({"tools": [{"name": "ExitPlanMode"}]}) is True
459444
assert up._is_plan_mode({"tools": [{"name": "Bash"}]}) is False
445+
# 1M context-window suffix: "<id>[1m]" is stripped before routing, so it
446+
# resolves to "<id>"'s route (the 1M window itself rides the beta header).
447+
out1m, _ = up.transform_messages_body(json.dumps({
448+
"model": "claude-composer[1m]", "max_tokens": 16,
449+
"messages": [{"role": "user", "content": "hi"}]}).encode())
450+
assert json.loads(out1m)["model"] == "cursor/composer-2.5", json.loads(out1m)["model"]
451+
# advertise [1m] on a real-Claude PASSTHROUGH route to a 1M model, so the
452+
# /model picker id carries it and Claude Code renders 1M even on in-session
453+
# switches; worker + non-passthrough entries are left untouched
454+
assert up._advertise_id({"id": "claude-opus"}) == "claude-opus[1m]"
455+
assert up._advertise_id({"id": "claude-composer"}) == "claude-composer" # openai_compat
456+
assert up._advertise_id({"id": "claude-worker-opus"}) == "claude-worker-opus"
457+
assert up._strip_1m("claude-opus[1m]") == "claude-opus"
458+
# a [1m]-suffixed pick still routes to its clean route (selection normalized)
459+
up._ACTIVE.update({"orch": None, "worker": None, "worker_explicit": False})
460+
out_adv, _ = up.transform_messages_body(json.dumps({
461+
"model": "claude-opus[1m]", "max_tokens": 16,
462+
"messages": [{"role": "user", "content": "hi"}]}).encode())
463+
assert json.loads(out_adv)["model"] == "claude-opus-4-8", json.loads(out_adv)["model"]
464+
up._ACTIVE.update({"orch": None, "worker": None, "worker_explicit": False})
460465
# a name that maps to TWO routes (gpt-5.5 head AND a gpt-oss model head) is
461466
# dropped as ambiguous -> resolves to nothing (regression for the docs/gpt gap)
462467
_slots0, _models0 = up.UC_SLOT_MAP, up.UC_MODELS
@@ -485,7 +490,7 @@ def _pin(text):
485490
assert _pin("@composer do it")[0] is None
486491
up.UC_SLOT_MAP, up.UC_MODELS, up._ROUTE_ALIASES, up.DIRECTIVES = (
487492
_saved[0], _saved[1], _saved[2], _saved[3])
488-
print("[ok] routing directives: opt-in default-off / NL opt-in / surgical strip / planner-gated / gpt-collision / dispatch")
493+
print("[ok] routing directives: opt-in default-off / NL opt-in / surgical strip / planner-gated / gpt-collision / dispatch / [1m] strip + advertise")
489494

490495
# issue #3: a rejected tool call (with or without a comment) must not leave
491496
# an assistant tool_calls message unanswered, and tool replies must come

‎windows/Start-UltraCode.ps1‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ function Add-Uc1m {
9898
if ([string]::IsNullOrEmpty($ModelId)) { return $ModelId }
9999
if ($ModelId.Contains("[1m]")) { return $ModelId }
100100
$set = if ($env:UC_1M_MODELS) { $env:UC_1M_MODELS }
101-
else { "claude-opus-4-8,claude-opus-4-7,claude-opus-4-6,claude-sonnet-4-6" }
101+
else { "claude-opus-4-8,claude-opus-4-7,claude-opus-4-6,claude-sonnet-4-6,claude-opus" }
102102
foreach ($id in $set.Split(",")) {
103103
if ($ModelId -eq $id.Trim()) { return "${ModelId}[1m]" }
104104
}

0 commit comments

Comments
 (0)