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
6872ROUTE SHAPE (config.json "routes" object)
6973-----------------------------------------
146150DIRECTIVES = {"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+
189241try :
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 ))
0 commit comments