HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
feat: add custom OpenAI/Anthropic-compatible integration
taoke2785559feb76
diff --git a/gateway/app.py b/gateway/app.pyindex ac07a244..c3ca4103 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -763,7 +763,7 @@ def _policy_chain(raw: str) -> list[str]:_AUTH_FIELDS = ("api_key", "base_url", "aws_region", "aws_access_key_id", "aws_secret_access_key","aws_session_token", "aws_bearer_token", "gcp_project", "gcp_region",- "gcp_sa_json", "wire_api")+ "gcp_sa_json", "wire_api", "api_format", "full_url")# ── LLM egress broker ────────────────────────────────────────────────────────────────────────@@ -783,7 +783,7 @@ _BROKER_TTL_S = int(os.environ.get("HR_LLM_BROKER_TTL_S", str(6 * 3600))) # ># transparent to the CLI. bedrock/vertex sign with the cloud SDK and are handled separately# (see _auth_from_conn) — they keep their own credential until their signing path is brokered._BROKERABLE_PROVIDERS = {"anthropic", "tokenrouter", "openai", "azure", "azure-foundry",- "openrouter", "openai-api"}+ "openrouter", "openai-api", "custom"}def _mint_turn_cred(sid: str, conn_name: str) -> str:@@ -948,6 +948,12 @@ _INTEGRATION_WIRING: dict[tuple[str, str], str] = {("openrouter", "opencode"): "openai-api",("tokenrouter", "opencode"): "tokenrouter", ("vercel", "opencode"): "tokenrouter",("llmtr", "opencode"): "tokenrouter",+ # custom: user-supplied endpoint + model + key. Maps to runner providers that can actually+ # drive a bring-your-own OpenAI/Anthropic endpoint — NOT codex, whose current releases speak+ # only the OpenAI Responses API and so cannot reach a custom chat/completions endpoint.+ ("custom", "claude"): "tokenrouter",+ ("custom", "hermes"): "openai-api", ("custom", "opencode"): "tokenrouter",+ ("custom", "pi"): "tokenrouter", ("custom", "dsh"): "tokenrouter",}@@ -1048,7 +1054,17 @@ def _integration_models(integ: dict) -> dict[str, str]:whole derived list, which would otherwise re-add exactly the models later found unreachable(a stale snapshot is indistinguishable from a deliberate override, so it cannot be trustedto introduce models). Nothing is lost: only canonicals in the catalog can be requested.++ The "custom" provider is the exception: it has no vendor table. The model comes from the+ integration's own config — the user-supplied model_id. That is the one model this integration+ serves, and it is its own provider-native id (the user's endpoint calls it whatever they named+ it, and the runner sends that name verbatim)."""+ provider = str(integ.get("provider") or "").lower()+ if provider == "custom":+ cfg = integ.get("config") or {}+ model_id = str(cfg.get("model_id") or "").strip()+ return {model_id: model_id} if model_id else {}models = dict(_vendor_models(str(integ.get("provider") or "").lower()))for m in (integ.get("models") or []):canonical = str(m.get("canonical") or "").strip()@@ -1137,6 +1153,8 @@ async def _mapped_integration_conn(backend: str, canonical: str) -> dict | None:integ = next((i for i in await _integrations_doc() if (i.get("name") or "") == iname), None)if not integ:return None+ if not _integration_serves_backend(integ, backend):+ return Noneprovider = _INTEGRATION_WIRING.get(((integ.get("provider") or "").lower(), backend))if not provider:return None@@ -3522,6 +3540,19 @@ _PROVIDER_CATALOG: dict[str, dict] = {"secret": "aws_bearer_token","secret_label": "API Key (bearer token)",},+ "custom": {+ "label": "Custom",+ "base_url": None, # user provides+ "fields": [+ {"key": "api_format", "label": "API Format"},+ {"key": "base_url", "label": "Endpoint URL",+ "placeholder": "https://your-api.example.com"},+ {"key": "full_url", "label": "完整URL(Use Full URL)"},+ {"key": "model_id", "label": "Model ID", "placeholder": "your-model-name"},+ ],+ "secret": "api_key",+ "secret_label": "API Key",+ },}@@ -3551,6 +3582,38 @@ def _provider_backends(provider: str) -> list[str]:return sorted({b for (p, b) in _INTEGRATION_WIRING if p == provider})+# Which agent backends can drive a CUSTOM integration at a given API format. A custom endpoint+# speaks exactly one wire protocol, and each agent CLI speaks a fixed subset of them:+# claude (Claude Code) — Anthropic Messages only+# codex (Codex) — OpenAI Responses API ONLY (current codex releases removed+# `wire_api = "chat"`, so it can no longer reach a chat/completions-+# only endpoint at all)+# hermes (Hermes) — OpenAI chat/completions only (via the openai-api loopback relay)+# opencode, pi, dsh — BOTH (api_format is passed straight to the CLI/model-map)+# An "openai" custom endpoint cannot drive claude (Anthropic-only), and it cannot drive codex+# (chat/completions dropped). An "anthropic" custom endpoint cannot drive codex or hermes. So+# codex is offered for NO custom integration — it only works against first-party OpenAI/Azure+# Responses endpoints. Listing a custom model as available on a backend whose protocol it can't+# speak is a promise the router breaks at the first call, so these sets drive the picker's+# grey-out.+_CUSTOM_FORMAT_BACKENDS = {+ "openai": {"hermes", "opencode", "pi", "dsh"},+ "anthropic": {"claude", "opencode", "pi", "dsh"},+}+++def _integration_serves_backend(integ: dict, backend: str) -> bool:+ """Can this integration actually run a turn on `backend`? For a custom provider this is+ gated by its api_format (see _CUSTOM_FORMAT_BACKENDS); every other provider just needs a+ wiring entry. This is the ONE place the picker's availability and the router's permission+ agree, so a model shown as available is a model that can actually run."""+ provider = str(integ.get("provider") or "").lower()+ if provider == "custom":+ fmt = str((integ.get("config") or {}).get("api_format") or "").strip().lower()+ return fmt in _CUSTOM_FORMAT_BACKENDS and backend in _CUSTOM_FORMAT_BACKENDS[fmt]+ return bool(_INTEGRATION_WIRING.get((provider, backend)))++def _provider_catalog_public() -> list[dict]:"""The catalog the console renders its Add-Integration form from."""return [{"id": pid,@@ -3673,6 +3736,19 @@ async def admin_integrations_put(body: IntegrationsBody, request: Request) -> diknown_base = (_PROVIDER_CATALOG.get(provider) or {}).get("base_url")if known_base and not cfg.get("base_url"):cfg["base_url"] = known_base+ # Custom provider URL normalisation. The user's base_url is the literal prefix their+ # endpoint wants the resource path joined against — for "openai" that's /chat/completions+ # and for "anthropic" /v1/messages, with NOTHING inserted in between (a custom endpoint+ # like https://host/api/coding/v3 already carries its own version path, so a heuristic+ # that appends /v1 makes a /v3 base into /v3/v1 and 404s). We only trim the trailing+ # slash; the runner appends the wire path itself. When full_url is on, nothing at all is+ # touched — the stored value is already the complete request URL.+ if provider == "custom" and cfg.get("base_url"):+ full = str(cfg.get("full_url") or "").strip().lower() in ("1", "true", "on", "yes")+ # Only trim the trailing slash either way — never insert or strip a version path.+ cfg["base_url"] = cfg["base_url"].rstrip("/")+ # Store full_url as "1" / "" so it round-trips cleanly through the config.+ cfg["full_url"] = "1" if full else ""# Store ONLY what the source table doesn't already say: an id this instance overrides# (a custom deployment name, say). Everything else is derived on read by# _integration_models, so the catalog in source stays the single source of truth and a@@ -4664,11 +4740,35 @@ def _model_authorized(requested: str, backend: str) -> bool:return False+async def _model_authorized_async(requested: str, backend: str, org: str) -> bool:+ """Like _model_authorized, but also admits models from custom integrations. Custom models+ are not in the hardcoded catalog — they come from the integration's own model_id config.++ Two sources for "can this backend serve it", checked because EITHER can be true:+ - _servable_models: the explicit servable set, when NO chain exists. A chain makes it+ return None, which is "no restriction" — but that must not fall through to False for a+ custom model, or the model the user picked silently runs on the default.+ - the effective model map: a model mapped to an integration whose provider is wired to+ this backend is routable REGARDLESS of whether a chain also exists. This is the+ decisive check for custom integrations when a chain is configured."""+ if _model_authorized(requested, backend):+ return True+ r = (requested or "").strip().lower()+ integrations = {str(i.get("name") or ""): i for i in await _integrations_doc()}+ for canonical, iname in (await _effective_model_map()).items():+ if canonical.lower() != r:+ continue+ integ = integrations.get(iname)+ if integ and _integration_serves_backend(integ, backend):+ return True+ return False++def _harness_model_default(hv: dict | None, backend: str) -> str:return str((hv or {}).get("default_model") or _MODEL_CATALOG.get(backend, {}).get("default") or "")-def _resolve_model_policy(requested: str, hv: dict | None, backend: str) -> tuple[str, str, bool, str]:+async def _resolve_model_policy(requested: str, hv: dict | None, backend: str, org: str = "") -> tuple[str, str, bool, str]:"""Server-side model permission for a turn. Returns (effective, requested, fallback?, reason).Empty/bare request -> the harness default (not a fallback). An unauthorized model is replaced bythe authorized fallback (the harness default) and flagged."""@@ -4676,12 +4776,10 @@ def _resolve_model_policy(requested: str, hv: dict | None, backend: str) -> tuplreq = (requested or "").strip()if not req or req.lower() in _BARE_MODELS:return default, req, False, ""- if _model_authorized(req, backend):+ if await _model_authorized_async(req, backend, org):return req, req, False, ""return default, req, True, (f"model '{req}' is not available for this harness's backend "f"'{backend}'; used the authorized default '{default}'")--async def _servable_models(org: str | None, backend: str) -> set[str] | None:"""Canonical models something can actually run on this backend.@@ -4700,12 +4798,12 @@ async def _servable_models(org: str | None, backend: str) -> set[str] | None:integ = integrations.get(iname)if not integ:continue- if _INTEGRATION_WIRING.get((str(integ.get("provider") or "").lower(), backend)):+ if _integration_serves_backend(integ, backend):servable.add(canonical)return servable-def _harness_models_view(hv: dict | None, backend: str, servable: set[str] | None = None) -> dict:+async def _harness_models_view(hv: dict | None, backend: str, servable: set[str] | None = None) -> dict:"""The per-harness model capability view: allowed models, default, and authorized fallback.`servable` (from _servable_models) marks the ones a provider is actually configured for."""cat = _MODEL_CATALOG.get(backend, {})@@ -4714,7 +4812,35 @@ def _harness_models_view(hv: dict | None, backend: str, servable: set[str] | Nonok = (lambda m: True) if servable is None else (lambda m: m in servable)models = [{"id": m, "label": m, "backend": backend, "available": ok(m), "default": m == default}for m in curated]- if default and default not in curated: # a custom default outside the curated list+ # Custom integrations bring their own model ids that are not in the curated catalog.+ # They must still appear in the picker — a model that is servable and absent from the+ # list is a silent dead end, and the harness page offers no other way to select it.+ # Check both the explicit servable set AND the effective model map, because when a+ # chain exists (servable=None) the chain is the fallback for unmapped models — a model+ # WITH a mapping is still routable and must still be shown.+ eff_map = await _effective_model_map()+ integrations = {str(i.get("name") or ""): i for i in await _integrations_doc()}+ seen = set(curated)+ for canonical, iname in eff_map.items():+ if canonical in seen:+ continue+ integ = integrations.get(iname)+ if integ and _integration_serves_backend(integ, backend):+ models.append({"id": canonical, "label": canonical, "backend": backend,+ "available": True, "default": canonical == default})+ seen.add(canonical)+ # A custom model whose api_format this backend can't speak is still LISTED so the operator+ # can see it exists, but greyed out (available=False) rather than silently omitted — the+ # picker must not offer a choice that fails at the first call.+ for canonical, iname in eff_map.items():+ if canonical in seen:+ continue+ integ = integrations.get(iname)+ if integ and str(integ.get("provider") or "").lower() == "custom":+ models.append({"id": canonical, "label": canonical, "backend": backend,+ "available": False, "default": canonical == default})+ seen.add(canonical)+ if default and default not in seen:models.insert(0, {"id": default, "label": default, "backend": backend,"available": ok(default), "default": True})return {"backend": backend, "default": default, "fallback": default, "models": models}@@ -5589,8 +5715,8 @@ async def create_response(body: CreateResponseBody, request: Request):or _route_backend(model_req or body.model, body.backend))# Server-side model permission (CT-124): an unauthorized model for this backend is replaced by# the harness's authorized default and the substitution is recorded in the run metadata.- model_req, requested_model, model_fallback, model_fallback_reason = _resolve_model_policy(- model_req, hv, backend)+ model_req, requested_model, model_fallback, model_fallback_reason = await _resolve_model_policy(+ model_req, hv, backend, org)# Token-level streaming (CT-127): opt in globally via env HARNESS_STREAM_PARTIAL=1, or per-request# via metadata.stream_partial (for testing). Claude uses --include-partial-messages; codex diffs# item.updated (self-healing → batch if it doesn't emit updates). Default off = current batch@@ -11340,7 +11466,7 @@ async def get_harness_models(org: str, hid: str, request: Request) -> dict:backend = (_backend_of_harness(v) or _backend_of_builtin(hid)or _route_backend(str(v.get("default_model") or ""), None))return {"harness_id": hid,- **_harness_models_view(v, backend, await _servable_models(org, backend))}+ **await _harness_models_view(v, backend, await _servable_models(org, backend))}@app.get("/v1/orgs/{org}/harnesses/{hid}/skills/{skill_id}/files")@@ -12168,12 +12294,36 @@ async def list_models(request: Request) -> dict:# `available` is computed, not asserted: a model with no provider behind it is listed as# unavailable so a picker can disable it, instead of offering a choice that fails at run time.out = {}+ # Custom integration models: pulled from the effective model map so they appear in the+ # picker for every backend that can serve them. A chain (servable=None) is the FALLBACK+ # for models without a mapping; a model WITH a mapping (custom or otherwise) is still+ # routable, so it must still be shown.+ eff_map = await _effective_model_map()+ integrations = {str(i.get("name") or ""): i for i in await _integrations_doc()}for b, c in _MODEL_CATALOG.items():servable = await _servable_models(org, b)ok = (lambda m: True) if servable is None else (lambda m: m in servable)- out[b] = {"default": c["default"],- "models": [{"id": m, "label": m, "backend": b, "available": ok(m),- "default": m == c["default"]} for m in c["models"]]}+ models = [{"id": m, "label": m, "backend": b, "available": ok(m),+ "default": m == c["default"]} for m in c["models"]]+ seen = set(c["models"])+ # Add models from the effective map that are not already in the catalog.+ # A model serves this backend only if its integration's api_format is compatible;+ # on an incompatible backend it is still LISTED (so the operator sees it exists) but+ # greyed out (available=False) rather than silently omitted.+ for canonical, iname in eff_map.items():+ if canonical in seen:+ continue+ integ = integrations.get(iname)+ if not integ:+ continue+ if _integration_serves_backend(integ, b):+ models.append({"id": canonical, "label": canonical, "backend": b,+ "available": True, "default": False})+ elif str(integ.get("provider") or "").lower() == "custom":+ models.append({"id": canonical, "label": canonical, "backend": b,+ "available": False, "default": False})+ seen.add(canonical)+ out[b] = {"default": c["default"], "models": models}return {"backends": out}@@ -12188,7 +12338,7 @@ async def get_harness_models_public(hid: str, request: Request) -> dict:backend = (_backend_of_harness(v) or _backend_of_builtin(hid)or _route_backend(str(v.get("default_model") or ""), None))return {"harness_id": hid,- **_harness_models_view(v, backend, await _servable_models(org, backend))}+ **await _harness_models_view(v, backend, await _servable_models(org, backend))}@app.get("/v1/harnesses/{hid}/skills/{skill_id}/files")diff --git a/runner/server.py b/runner/server.pyindex 62f814ab..e931a1b1 100644--- a/runner/server.py+++ b/runner/server.py@@ -832,6 +832,9 @@ class Auth(BaseModel):gcp_sa_json: str | None = None # service-account JSON (string) → file# Codex provider tuningwire_api: str | None = None # responses | chat (default responses)+ # Custom provider+ api_format: str | None = None # "openai" | "anthropic" (custom integration)+ full_url: str | None = None # "1" when the URL is a complete request URL# ── canonical-event normalizers ──────────────────────────────────────────────────@@ -1158,6 +1161,11 @@ def _build_claude(provider: str, auth: Auth, model: str, prompt: str, max_turns:sa.write_text(auth.gcp_sa_json)env["GOOGLE_APPLICATION_CREDENTIALS"] = str(sa)elif p == "tokenrouter":+ # tokenrouter speaks Anthropic on the claude backend. A custom integration with+ # api_format=openai cannot be served here — the CLI only speaks Anthropic Messages.+ if auth.api_format == "openai":+ raise HTTPException(400, "claude backend cannot serve an OpenAI-format custom integration "+ "(use a backend that supports openai-api, like hermes or opencode)")if auth.base_url:# Claude Code appends /v1/messages itself — a base_url stored with /v1 (the# OpenAI-compat form) would double the segment and 404 every call.@@ -1260,6 +1268,11 @@ def _codex_prepare_env(provider: str, auth: Auth, model: str, cwd: str,# why codex state used to vanish. (auth.json inside is still creds-excluded.)cfg_dir = pathlib.Path(env.get("HOME") or cwd) / ".codex"cfg_dir.mkdir(parents=True, exist_ok=True)+ # codex only speaks the OpenAI Responses API now — current releases removed+ # `wire_api = "chat"` entirely, so a custom chat-completions endpoint cannot be driven by+ # codex at all (the gateway greys codex out for those integrations). Always the supported+ # "responses" value; a custom-endpoint turn against chat-only would 404 clearly rather than+ # crash on config load.cfg = _CODEX_CONFIG_TMPL.format(model=model, provider=f"hr-{p}", effort=CODEX_REASONING_EFFORT, ctx=CODEX_CONTEXT_WINDOW,name=spec["name"], base_url=base_url, env_key=spec["env_key"],@@ -1426,7 +1439,10 @@ def _build_dsh(provider: str, auth: Auth, model: str, prompt: str, cwd: str, envbase = auth.base_url or _DSH_DEFAULT_BASE.get(pr, "")if not base:raise HTTPException(400, f"dsh provider '{pr}' needs a base_url (none configured)")- if not base.rstrip("/").endswith("/v1"):+ # The relay joins upstream paths against a /v1 base for known providers. But a CUSTOM+ # openai endpoint carries its own version path (https://host/api/coding/v3) — appending+ # /v1 would make /v3/v1 and 404, so a custom base is used as-is.+ if auth.api_format != "openai" and not base.rstrip("/").endswith("/v1"):base = base.rstrip("/") + "/v1" # the relay joins upstream paths against a /v1 base# HR_DSH_*: consumed and scrubbed by the driver before the runtime starts. The runtime gets# a loopback relay URL and a placeholder key — the credential never enters its environment.@@ -1441,8 +1457,13 @@ def _build_dsh(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env# Family decides the route, not the integration's name: deepseek models keep the# verified dsh-llm-deepseek launch path whichever endpoint serves them; every other# family rides the pi-ai route. api by family — the same routing the pi backend- # live-verified on these channels.- if pr == "anthropic" or _PI_CLAUDE_MODEL.search(model or ""):+ # live-verified on these channels. When api_format is set (custom integration), the+ # user's explicit choice wins.+ if auth.api_format == "anthropic":+ api = "anthropic-messages"+ elif auth.api_format == "openai":+ api = "openai-completions"+ elif pr == "anthropic" or _PI_CLAUDE_MODEL.search(model or ""):api = "anthropic-messages"elif pr == "azure" or _HERMES_RESPONSES_API_MODEL.search(model or ""):api = "openai-responses"@@ -1583,7 +1604,7 @@ _PI_CLAUDE_MODEL = re.compile(r"(?:^|/)(?:us\.anthropic\.)?claude", re.I)def _pi_models_json(api: str, base_url: str, api_key: str, model: str,- vision: bool = True) -> str:+ vision: bool = True, custom_openai: bool = False) -> str:"""A one-provider ~/.pi/agent/models.json ("hr") for a custom endpoint. Pi's anthropic clientappends /v1/messages to baseUrl while its openai clients expect the /v1 to already be there(both read straight off pi's own docs/models.md examples), so the /v1 suffix is normalized@@ -1594,11 +1615,15 @@ def _pi_models_json(api: str, base_url: str, api_key: str, model: str,message with an image part — verified against a capturing sink. Declared text-only, pi dropsthe image and the turn runs; declared vision on a model whose channel refuses images, thewhole turn dies on the provider's 400. The gateway says which models are text-only, from- live probes, so vision stays the default."""+ live probes, so vision stays the default.++ `custom_openai`: a CUSTOM OpenAI endpoint carries its own version path (e.g. https://host/+ api/coding/v3) — appending our own /v1 would make /v3/v1 and 404. So for a custom endpoint+ the base_url is used as-is and only /chat/completions is joined."""base = (base_url or "").rstrip("/")if api == "anthropic-messages":base = base.removesuffix("/v1")- elif not base.endswith("/v1"):+ elif not custom_openai and not base.endswith("/v1"):base += "/v1"return json.dumps({"providers": {"hr": {"baseUrl": base, "api": api, "apiKey": api_key,@@ -1652,14 +1677,21 @@ def _build_pi(provider: str, auth: Auth, model: str, prompt: str, cwd: str, env:if use_custom:if not auth.base_url:raise HTTPException(400, f"pi provider '{pr}' needs a base_url (none configured)")- if pr == "anthropic" or (pr == "tokenrouter" and _PI_CLAUDE_MODEL.search(model or "")):+ # When api_format is set (custom integration), use the user's explicit choice. Otherwise+ # pick by model family — the same routing the hermes backend already proved.+ if auth.api_format == "anthropic":+ api = "anthropic-messages"+ elif auth.api_format == "openai":+ api = "openai-completions"+ elif pr == "anthropic" or (pr == "tokenrouter" and _PI_CLAUDE_MODEL.search(model or "")):api = "anthropic-messages"elif pr == "azure" or _HERMES_RESPONSES_API_MODEL.search(model or ""):api = "openai-responses"else:api = "openai-completions"(home / ".pi" / "agent" / "models.json").write_text(- _pi_models_json(api, auth.base_url, auth.api_key or "", model, vision=vision))+ _pi_models_json(api, auth.base_url, auth.api_key or "", model, vision=vision,+ custom_openai=bool(auth.api_format)))pname = "hr"else:pname = pr@@ -2191,7 +2223,13 @@ def _opencode_config(auth: Auth, model: str, cwd: str, mcp_servers: list[dict] |# The split MIRRORS _pi_models_json, because both reach the same relays over the same wire# formats: a claude model on an anthropic-native connection speaks Messages, not# chat/completions, and sending it to the openai-compatible package fails at the first call.- if pr == "anthropic" or (pr == "tokenrouter" and _PI_CLAUDE_MODEL.search(model or "")):+ # When api_format is set (custom integration), the user's explicit choice wins over any+ # model-family heuristic — the endpoint is the one they told us to reach.+ if auth.api_format == "anthropic":+ npm = "@ai-sdk/anthropic"+ elif auth.api_format == "openai":+ npm = "@ai-sdk/openai-compatible"+ elif pr == "anthropic" or (pr == "tokenrouter" and _PI_CLAUDE_MODEL.search(model or "")):npm = "@ai-sdk/anthropic"elif pr == "azure" or _HERMES_RESPONSES_API_MODEL.search(model or ""):npm = "@ai-sdk/openai" # /v1/responsesdiff --git a/ui/src/app/(app)/integrations/page.tsx b/ui/src/app/(app)/integrations/page.tsxindex 3fde67f5..5db64dbf 100644--- a/ui/src/app/(app)/integrations/page.tsx+++ b/ui/src/app/(app)/integrations/page.tsx@@ -261,6 +261,7 @@ export default function IntegrationsPage() {{(() => {const meta = metaFor(editing.provider);if (!meta) return null;+ const isCustom = editing.provider === 'custom';// Only what varies by deployment. A provider with a known endpoint never// shows a Base URL field — the server fills it in.const fields = [...meta.fields,@@ -271,12 +272,72 @@ export default function IntegrationsPage() {{fields.map((f) => {const secret = f.key === meta.secret;const saved = secret && editing.config[f.key] === SECRET;+ // Special rendering for custom provider fields+ if (isCustom && f.key === 'api_format') {+ return (+ <div className="field" key={f.key}>+ <label htmlFor={`itg-${f.key}`}>{f.label}</label>+ <select id={`itg-${f.key}`} className="select"+ value={editing.config[f.key] || ''}+ onChange={(e) => setEditing({+ ...editing,+ config: { ...editing.config, [f.key]: e.target.value },+ })}>+ <option value="openai">OpenAI Chat Completions</option>+ <option value="anthropic">Anthropic Messages</option>+ </select>+ <p className="field-help">+ {editing.config['api_format'] === 'anthropic'+ ? 'Anthropic Messages format works with Claude Code, OpenCode, Pi, and DSH backends.'+ : editing.config['api_format'] === 'openai'+ ? 'OpenAI Chat Completions format works with Codex, Hermes, OpenCode, Pi, and DSH backends. Note: Claude Code does not support OpenAI format.'+ : 'If you use Claude Code, choose Anthropic Messages format.'}+ </p>+ </div>+ );+ }+ if (isCustom && f.key === 'full_url') {+ const fullUrlOn = editing.config[f.key] === '1' || editing.config[f.key] === 'true';+ return (+ <div className="field" key={f.key}>+ <label>{f.label}</label>+ <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>+ <button type="button" role="switch" aria-checked={fullUrlOn}+ className="toggle-button"+ onClick={() => setEditing({+ ...editing,+ config: { ...editing.config, [f.key]: fullUrlOn ? '' : '1' },+ })}+ style={{ minWidth: 44, minHeight: 26, padding: 0, borderRadius: 999,+ border: fullUrlOn ? '1px solid var(--accent)' : '1px solid var(--line)',+ background: fullUrlOn ? 'var(--accent)' : 'var(--surface-subtle)',+ cursor: 'pointer', position: 'relative', transition: 'background .15s' }}>+ <span style={{ display: 'block', width: 18, height: 18, borderRadius: 999,+ background: fullUrlOn ? '#fff' : 'var(--line)',+ position: 'absolute', top: 3, left: fullUrlOn ? 21 : 3,+ transition: 'left .15s' }} />+ </button>+ <span style={{ fontSize: 13, color: fullUrlOn ? 'var(--ink)' : 'var(--muted)' }}>+ {fullUrlOn ? 'On — the URL is used as-is' : 'Off — /chat/completions is appended'}+ </span>+ </div>+ </div>+ );+ }+ // Dynamic placeholder for base_url based on full_url toggle+ let placeholder = f.placeholder || '';+ if (isCustom && f.key === 'base_url') {+ const fullUrl = editing.config['full_url'] === '1' || editing.config['full_url'] === 'true';+ placeholder = fullUrl+ ? 'Enter the full request URL, including the path. The request will use this URL directly.'+ : 'Enter an OpenAI-compatible API endpoint, without a trailing slash. /chat/completions will be appended to your endpoint.';+ }return (<div className="field" key={f.key}><label htmlFor={`itg-${f.key}`}>{f.label}</label><input id={`itg-${f.key}`} type={secret ? 'password' : 'text'}value={saved ? '' : (editing.config[f.key] || '')}- placeholder={saved ? '•••••••• (saved, leave blank to keep)' : f.placeholder || ''}+ placeholder={saved ? '•••••••• (saved, leave blank to keep)' : placeholder}autoComplete="off"onChange={(e) => setEditing({...editing,@@ -292,7 +353,20 @@ export default function IntegrationsPage() {);})()}{(() => {- const models = metaFor(editing.provider)?.models || [];+ const meta = metaFor(editing.provider);+ const isCustom = editing.provider === 'custom';+ const models = meta?.models || [];+ if (isCustom) {+ return (+ <div className="field">+ <label>Model</label>+ <p className="field-help">+ This integration serves the model ID you entered above. Add it in the+ mapping table below after saving.+ </p>+ </div>+ );+ }return (<div className="field"><label>Supported models</label>