Skip to content

Commit 45ec0bc

Browse files
authored
Merge pull request #16 from OnlyTerp/integrate/open-prs-and-issues
fix: PR #13 browser UA + issues #14/#15 (remaining delta after #11/#12)
2 parents 3919a12 + 691ba02 commit 45ec0bc

6 files changed

Lines changed: 196 additions & 4 deletions

File tree

‎bin/ultracode‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,40 @@ PY
175175
rm -f "$SAVED_MODEL_FILE"
176176
}
177177

178+
uc_status() {
179+
if ! health_ok; then
180+
echo "UltraCode proxy is not running on $BASE_URL" >&2
181+
echo "Start it with: ultracode" >&2
182+
exit 1
183+
fi
184+
"$PY" - "$BASE_URL" <<'PY'
185+
import json,sys,urllib.request
186+
base=sys.argv[1].rstrip('/')
187+
with urllib.request.urlopen(base+'/healthz',timeout=3) as r:
188+
h=json.loads(r.read().decode())
189+
ow=h.get('orchestrator_worker') or {}
190+
orch=ow.get('orchestrator') or {}
191+
worker=ow.get('worker') or {}
192+
print('UltraCode proxy:', base)
193+
print('Orchestrator/worker routing:', 'on' if ow.get('enabled') else 'off')
194+
if ow.get('enabled'):
195+
o=orch.get('display_name') or orch.get('id') or '(not set)'
196+
w=worker.get('display_name') or worker.get('id') or '(not set)'
197+
print(' Orchestrator:', o, ('('+orch.get('id')+')') if orch.get('id') else '')
198+
print(' Worker: ', w, ('('+worker.get('id')+')') if worker.get('id') else '')
199+
if ow.get('worker_explicit'):
200+
print(' (worker was set explicitly — plain /model picks change orchestrator only)')
201+
elif ow.get('same_model'):
202+
print(' (same model runs orchestrator and all workers)')
203+
print('Live detail: curl -s', base+'/healthz', '| python3 -m json.tool')
204+
PY
205+
}
206+
207+
if [[ "${1:-}" == "status" ]]; then
208+
uc_status
209+
exit 0
210+
fi
211+
178212
start_proxy() {
179213
mkdir -p "$REF_DIR"
180214
: > "$OWNER_REF"

‎docs/HOW_IT_WORKS.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,17 @@ Selection rules:
141141
background traffic) never change the selection; they're **remapped** to it. That
142142
is what makes "use MiniMax" mean MiniMax for the whole workflow.
143143

144+
**Seeing the active tiers.** Claude Code's UI doesn't show orchestrator vs worker
145+
separately. While the proxy is running:
146+
147+
- `ultracode status` (or `.\windows\Start-UltraCode.ps1 -Status` on Windows)
148+
- `GET /healthz` → `orchestrator_worker`
149+
- `GET /uc/select` → `active`
150+
151+
If a worker model hits a rate limit mid-task, pick **`Worker → <other>`** in
152+
`/model` — only the worker tier changes. Role-targeted slash commands like
153+
`/model worker` are not available (that's Claude Code's picker, not the proxy).
154+
144155
The selection lives in the proxy process (one `claude` session), guarded by a
145156
lock, and resets when the proxy restarts. Disable tier routing with
146157
`UC_ORCH_WORKER=0` (then a pick routes 1:1 and stock ids pass through untouched).

‎docs/TROUBLESHOOTING.md‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,50 @@ the rest of `settings.json` is left intact.
8181
- **Keep a pick for this session only without saving (even with the guard off):**
8282
press `s` in the `/model` picker instead of Enter.
8383

84+
### Which model is orchestrator vs worker right now?
85+
86+
Orchestrator/worker routing is sticky inside the proxy process, but Claude Code's
87+
UI doesn't show the two tiers separately.
88+
89+
- **Quick status:** `ultracode status` (mac/Linux/WSL) or
90+
`.\windows\Start-UltraCode.ps1 -Status` (Windows). Shows the active
91+
orchestrator and worker ids + display names.
92+
- **JSON:** `curl -s http://127.0.0.1:8141/healthz | python3 -m json.tool` →
93+
`orchestrator_worker`.
94+
- **Also:** `curl -s http://127.0.0.1:8141/uc/select` returns the same
95+
`active` block while the proxy is running.
96+
97+
**Changing models mid-session:**
98+
99+
| What you pick in `/model` | What changes |
100+
|---------------------------|--------------|
101+
| A plain model (e.g. `claude-minimax-m3`) | **Both** orchestrator and worker → that model runs everything |
102+
| `Worker → <model>` | **Worker only** — orchestrator stays as-is |
103+
| Stock ids (`claude-opus-4-8`, sonnet, haiku) | **Neither tier** — they're remapped to your picks for background traffic |
104+
105+
**Worker hit a rate limit mid-task?** Open `/model`, pick `Worker → <other model>`.
106+
The orchestrator tier is unchanged; only parallel workers/sub-agents switch.
107+
108+
**`/model orchestrator` / `/model worker`?** Not available — `/model` is Claude
109+
Code's built-in picker; the proxy only sees the resulting model id on the next
110+
request. Use the plain vs `Worker →` entries above.
111+
112+
### OpenAI-compat backend errors on long sessions (context length / 400)
113+
114+
The proxy forwards the **entire** Anthropic transcript to `openai_compat` backends
115+
with no automatic trimming. On long multi-tool workflows a backend may return
116+
`context length exceeded`, `maximum context`, or similar 400s.
117+
118+
- **First:** compact the session (`/compact` in Claude Code) or start a fresh
119+
session and carry over only what you need.
120+
- **Switch worker only:** if the orchestrator is fine but workers are failing,
121+
`/model` → `Worker → <model with a larger window>`.
122+
- **Proxy hint:** when the upstream error looks context-related, the proxy log
123+
and error message include a short note explaining that the full history was sent.
124+
125+
Strict backends also require `content: null` (not `""`) on tool-only assistant
126+
turns; the proxy handles that automatically.
127+
84128
### The pre-launch selector doesn't open / says it cannot reach `/uc/select`
85129

86130
- **Proxy not healthy yet or wrong port.** The launcher starts the proxy before

‎proxy.py‎

Lines changed: 68 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,10 @@
6464
UC_MODEL_MAP optional JSON, e.g. {"claude-opus-4-8":"my-model"}
6565
UC_LOG optional log file path (default stderr)
6666
UC_VERBOSE default 0
67+
UC_BROWSER_UA User-Agent for openai_compat upstreams (default: modern
68+
Chrome UA). Fixes CF 403 "browser_signature_banned" on
69+
providers like crof.ai. Override with env or per-route
70+
"headers".
6771
6872
ROUTE SHAPE (config.json "routes" object)
6973
-----------------------------------------
@@ -146,6 +150,16 @@
146150
DIRECTIVES = {"planner": None, "strip": True} # filled from config in main()
147151
_ROUTE_ALIASES = {} # normalized token -> concrete route id
148152

153+
# BROWSER_UA: browser UA for openai_compat (and classifier) calls.
154+
# CF-protected providers (e.g. crof.ai) ban Python-urllib (error 1010
155+
# "browser_signature_banned"). Matches droid/factory clients.
156+
# Override: UC_BROWSER_UA=... or route "headers".
157+
BROWSER_UA = os.environ.get(
158+
"UC_BROWSER_UA",
159+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
160+
"(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
161+
)
162+
149163
# 1M context window: Claude Code sizes its context meter (and auto-compaction) to
150164
# 1M only when the model id it holds carries a "[1m]" suffix. For a real-Claude
151165
# passthrough route whose upstream model is 1M-capable, we ADVERTISE the picker id
@@ -186,6 +200,44 @@ def _advertise_id(model_entry):
186200
return mid + _ONEM_SUFFIX
187201
return mid
188202

203+
204+
def _display_name_for_id(mid):
205+
if not mid:
206+
return None
207+
for m in UC_MODELS:
208+
if m.get("id") == mid:
209+
return m.get("display_name", mid)
210+
for m in _stock_models():
211+
if m.get("id") == mid:
212+
return m.get("display_name", mid)
213+
return mid
214+
215+
216+
def _orchestrator_worker_status():
217+
with _SEL_LOCK:
218+
active = dict(_ACTIVE)
219+
orch = active.get("orch")
220+
worker = active.get("worker")
221+
return {
222+
"enabled": ORCH_WORKER,
223+
"orchestrator": {"id": orch, "display_name": _display_name_for_id(orch)},
224+
"worker": {"id": worker, "display_name": _display_name_for_id(worker)},
225+
"worker_explicit": active.get("worker_explicit", False),
226+
"same_model": bool(orch and worker and orch == worker),
227+
}
228+
229+
230+
def _context_length_hint(detail):
231+
low = (detail or "").lower()
232+
if any(x in low for x in ("context", "token", "maximum context",
233+
"too long", "too many tokens", "length exceeded")):
234+
return (" (This backend rejected the full conversation history — the proxy "
235+
"forwards the entire transcript with no trimming. Try compacting the "
236+
"session, switching to a backend with a larger context window, or "
237+
"starting a fresh session.)")
238+
return ""
239+
240+
189241
try:
190242
UC_MODEL_MAP = json.loads(os.environ.get("UC_MODEL_MAP", "") or "{}")
191243
if not isinstance(UC_MODEL_MAP, dict):
@@ -1288,10 +1340,14 @@ def _flush_tool_replies(by_id):
12881340
"arguments": json.dumps(block.get("input") or {}, ensure_ascii=False),
12891341
},
12901342
})
1291-
entry = {"role": "assistant", "content": "\n".join(p for p in text_parts if p)}
1343+
text = "\n".join(p for p in text_parts if p)
1344+
entry = {"role": "assistant"}
12921345
if tool_calls:
12931346
entry["tool_calls"] = tool_calls
1347+
entry["content"] = text if text else None
12941348
pending_tool_ids[:] = [tc["id"] for tc in tool_calls]
1349+
else:
1350+
entry["content"] = text
12951351
messages.append(entry)
12961352
continue
12971353

@@ -1736,7 +1792,8 @@ def _classifier_complete(slot, system_prompt, user_content, timeout):
17361792
payload[bk] = _expand_env(bv) if isinstance(bv, str) else bv
17371793
data = json.dumps(payload).encode("utf-8")
17381794
headers = {"Content-Type": "application/json", "Accept": "application/json",
1739-
"Content-Length": str(len(data))}
1795+
"Content-Length": str(len(data)), "User-Agent": BROWSER_UA,
1796+
"Accept-Language": "en-US,en;q=0.9"}
17401797
auth = slot.get("auth")
17411798
if auth and auth != "passthrough":
17421799
Handler._apply_auth_header(headers, auth)
@@ -1757,7 +1814,7 @@ def _classifier_complete(slot, system_prompt, user_content, timeout):
17571814
"messages": [{"role": "user", "content": user_content}]}
17581815
data = json.dumps(payload).encode("utf-8")
17591816
headers = {"Content-Type": "application/json", "Content-Length": str(len(data)),
1760-
"anthropic-version": "2023-06-01"}
1817+
"anthropic-version": "2023-06-01", "User-Agent": BROWSER_UA}
17611818
auth = slot.get("auth")
17621819
if auth and auth != "passthrough":
17631820
Handler._apply_auth_header(headers, auth)
@@ -1960,6 +2017,7 @@ def _maybe_health(self) -> bool:
19602017
"candidates": [{"id": c["id"], "cost": c.get("cost")}
19612018
for c in _router_available_candidates()],
19622019
},
2020+
"orchestrator_worker": _orchestrator_worker_status(),
19632021
"custom_models": [{"id": _advertise_id(m), "display_name": m["display_name"]}
19642022
for m in UC_MODELS],
19652023
"stock_models": [{"id": m["id"], "display_name": m["display_name"]}
@@ -2041,6 +2099,7 @@ def _handle_models(self) -> bool:
20412099
fwd_headers = {k: v for k, v in self.headers.items()
20422100
if k.lower() not in _HOP_BY_HOP}
20432101
fwd_headers["Accept-Encoding"] = "identity"
2102+
fwd_headers.setdefault("User-Agent", BROWSER_UA)
20442103
url = UPSTREAM + self.path
20452104
base = {"data": [], "has_more": False, "first_id": None, "last_id": None}
20462105
try:
@@ -2126,6 +2185,7 @@ def _proxy(self, method: str):
21262185
for hk, hv in (route.get("headers") or {}).items():
21272186
fwd_headers[hk] = hv
21282187
fwd_headers["Accept-Encoding"] = "identity"
2188+
fwd_headers.setdefault("User-Agent", BROWSER_UA)
21292189
if body:
21302190
fwd_headers["Content-Length"] = str(len(body))
21312191
req = urllib.request.Request(url, data=body or None,
@@ -2183,6 +2243,8 @@ def _handle_openai_compat(self, body: bytes, route: dict):
21832243
"Content-Type": "application/json",
21842244
"Accept": "text/event-stream" if want_stream else "application/json",
21852245
"Content-Length": str(len(payload)),
2246+
"User-Agent": BROWSER_UA,
2247+
"Accept-Language": "en-US,en;q=0.9",
21862248
}
21872249
auth_override = route.get("auth")
21882250
if auth_override and auth_override != "passthrough":
@@ -2204,9 +2266,11 @@ def _mk_events():
22042266
detail = e.read().decode("utf-8", "replace")[:800]
22052267
except Exception:
22062268
pass
2269+
hint = _context_length_hint(detail)
22072270
log("openai_compat upstream HTTP %s for %s: %s" % (e.code, url, detail))
22082271
yield {"type": "error", "status": e.code,
2209-
"message": "openai_compat upstream %s: %s" % (e.code, detail)}
2272+
"message": "openai_compat upstream %s: %s%s"
2273+
% (e.code, detail, hint)}
22102274
return
22112275
except Exception as e:
22122276
log("openai_compat upstream error %s for %s" % (e, url))

‎test_proxy.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,20 @@ def _pin(text):
492492
_saved[0], _saved[1], _saved[2], _saved[3])
493493
print("[ok] routing directives: opt-in default-off / NL opt-in / surgical strip / planner-gated / gpt-collision / dispatch / [1m] strip + advertise")
494494

495+
# issue #14: tool-only assistant turns must use content=null (not "") for
496+
# strict OpenAI-compat backends on long multi-tool transcripts.
497+
oai_tool_only = up.anthropic_to_openai({"model": "x", "messages": [
498+
{"role": "assistant", "content": [{"type": "tool_use", "id": "call_1",
499+
"name": "Bash", "input": {}}]},
500+
{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1",
501+
"content": "ok"}]},
502+
]})
503+
assert oai_tool_only["messages"][0]["content"] is None
504+
assert oai_tool_only["messages"][0]["tool_calls"]
505+
assert up._context_length_hint("context length exceeded") != ""
506+
assert up._context_length_hint("unrelated error") == ""
507+
print("[ok] openai_compat long-context hygiene: tool-only content=null + context hint")
508+
495509
# issue #3: a rejected tool call (with or without a comment) must not leave
496510
# an assistant tool_calls message unanswered, and tool replies must come
497511
# BEFORE the user's text — otherwise strict backends (DeepSeek) 400 with

‎windows/Start-UltraCode.ps1‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
#>
2727
param(
2828
[switch]$ProxyOnly,
29+
[switch]$Status,
2930
[int]$Port = 0,
3031
[string]$Upstream = ""
3132
)
@@ -216,6 +217,30 @@ function Stop-ProxyIfLast {
216217
}
217218
}
218219

220+
if ($Status) {
221+
if (-not (Test-ProxyHealthy)) {
222+
Write-Error "UltraCode proxy is not running on $BaseUrl. Start it with: .\windows\Start-UltraCode.ps1"
223+
exit 1
224+
}
225+
$health = Invoke-RestMethod -Uri "$BaseUrl/healthz" -TimeoutSec 3
226+
$ow = $health.orchestrator_worker
227+
Write-Host "UltraCode proxy: $BaseUrl"
228+
if ($ow.enabled) {
229+
Write-Host "Orchestrator/worker routing: on"
230+
Write-Host (" Orchestrator: {0} ({1})" -f $ow.orchestrator.display_name, $ow.orchestrator.id)
231+
Write-Host (" Worker: {0} ({1})" -f $ow.worker.display_name, $ow.worker.id)
232+
if ($ow.worker_explicit) {
233+
Write-Host " (worker set explicitly — plain /model picks change orchestrator only)"
234+
} elseif ($ow.same_model) {
235+
Write-Host " (same model runs orchestrator and all workers)"
236+
}
237+
} else {
238+
Write-Host "Orchestrator/worker routing: off"
239+
}
240+
Write-Host "Live detail: curl -s $BaseUrl/healthz | python -m json.tool"
241+
exit 0
242+
}
243+
219244
New-Item -ItemType Directory -Force -Path $RefDir | Out-Null
220245
Save-GlobalModel
221246
New-Item -ItemType File -Force -Path $OwnerRef | Out-Null

0 commit comments

Comments
 (0)