Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
docs: accept RFC-0003 and document named endpoints
trohitg9283ada1b4a3
diff --git a/CLAUDE.md b/CLAUDE.mdindex c68f2d16..acd2a637 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -59,8 +59,8 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Onboarding Service](./docs-internal/onboarding.md)** | First-launch welcome wizard with 4 steps, database persistence, and replay from Settings || **[CLI Services Integration](./docs-internal/cli_services_integration.md)** | Guide for integrating CLI-based services (Temporal, etc.) with proper lifecycle management || **[Temporal Architecture](./docs-internal/TEMPORAL_ARCHITECTURE.md)** | Distributed workflow execution: activities, FIRST_COMPLETED scheduling, horizontal scaling |-| **[Native LLM SDK](./docs-internal/native_llm_sdk.md)** | Native SDK layer in `services/llm/`: protocol-based providers, config-driven base URLs, and 13 providers (11 cloud plus Ollama / LM Studio; xAI is agent-selectable without a standalone chat-model node). A JSON-driven `supports_model_listing: false` flag covers endpoints that speak the OpenAI chat wire format but ship no `/v1/models` route (Sarvam) — `OpenAIProvider.fetch_models` then serves the curated list and probes the key with a one-token completion. Every provider is native; `tests/llm/test_langchain_removed.py` locks the retired-dependency end state. |-| **[RFC-0003 — OpenAI-Compatible Provider Contract](./RFC-0003-OPENAI-COMPATIBLE-PROVIDER-CONTRACT.md)** | Draft. "OpenAI-compatible" is a family of divergent shapes with no spec behind it, and the client currently *guesses* per-provider facts it cannot infer. Twelve decisions (D1–D12) with acceptance gates: a configured `base_url` is copied **verbatim** from vendor docs and never rewritten (`/v1` is neither universal nor positionally predictable — DeepSeek is root-mounted, Groq is `/openai/v1`, Sarvam is `/v1` *and* `/v2`); a **user-supplied** URL is resolved by **probing** `GET {base}/models` then `{base}/v1/models` at save time, because a path-less URL is indistinguishable from a deliberately root-mounted server without probing; 401/403 counts as rooted at probe time and as a credential failure at runtime; the credential is resolved by one function and no provider hardcodes a placeholder key (the `api_key="ollama"` overwrite in `OpenAIProvider.__init__` applies to *every* provider with a proxy row); `api_key=None` must never reach the SDK, since it falls back to `OPENAI_API_KEY` and ships the operator's key to a third-party `base_url`; capabilities are declared, never sniffed, and a flag ships only with a consumer; a 2xx with no `choices` and an error body raises `PROTOCOL` naming the URL called. Five revertible phases, `ProviderSpec` gains no field, `_strip_v1_path` survives scoped to the native probe. Also records that `native_llm_sdk.md`'s DeepSeek `/v1` claim is wrong and the path-less JSON entry is correct. |+| **[Native LLM SDK](./docs-internal/native_llm_sdk.md)** | Native SDK layer in `services/llm/`: protocol-based providers, config-driven base URLs, and 14 registered providers (11 cloud, Ollama / LM Studio, and `openai_compatible`, which serves any number of user-named endpoints — llama.cpp, vLLM, a LiteLLM proxy — added in the Credentials Modal with no code; xAI is agent-selectable without a standalone chat-model node). A JSON-driven `supports_model_listing: false` flag covers endpoints that speak the OpenAI chat wire format but ship no `/v1/models` route (Sarvam) — `OpenAIProvider.fetch_models` then serves the curated list and probes the key with a one-token completion. Every provider is native; `tests/llm/test_langchain_removed.py` locks the retired-dependency end state. |+| **[RFC-0003 — OpenAI-Compatible Provider Contract](./RFC-0003-OPENAI-COMPATIBLE-PROVIDER-CONTRACT.md)** | Accepted, implemented. "OpenAI-compatible" is a family of divergent shapes with no spec behind it, so per-provider facts are **resolved at save time or declared**, never guessed. A configured `base_url` is copied **verbatim** from vendor docs and never rewritten (`/v1` is neither universal nor positionally predictable — DeepSeek is root-mounted, Groq is `/openai/v1`); a **user-supplied** URL is rooted by `services/llm/endpoints.py::resolve_base_url`, which sends the SDK's own `models.list()` to the URL then to it plus `/v1` and adopts only a body that **is an OpenAI list** — a status alone proves nothing, because LM Studio answers HTTP 200 to routes it does not serve. A failed save writes and broadcasts nothing. One `resolve_credential` sends the stored key or the vendor-documented placeholder (`auth.placeholder_key`) and never `None` (which would make the SDK read `OPENAI_API_KEY` and ship it to a third-party URL); no provider rewrites a key. A 2xx with no `choices` and an error body raises `PROTOCOL` naming the redacted URL. **Named endpoints (D13–D17)**: any server is a provider reference `openai_compatible:<slug>` stored exactly like Ollama (`{ref}` + `{ref}_proxy`), selectable from every agent (the `provider` field is a loader-driven `ProviderRef`, not a `Literal`), from the `openaiCompatibleChatModel` node (its field is `endpoint`, not `provider`, to dodge the panel's stored-key effect) and the global default picker; kind detected once from native routes by body shape; context and price from the server first (Ollama/LM Studio SDK probes, llama.cpp `/props`, vLLM `max_model_len`), then LiteLLM's table for generic servers only, then conservative defaults; local-model entries and the LiteLLM cache live under DATA_DIR, never in the tracked `config/model_registry.json`. RLM cannot route an endpoint and refuses one loudly. Gates AG1–AG20, `ProviderSpec` gains no field. || **[Event Waiter System](./docs-internal/event_waiter_system.md)** | In-memory asyncio.Future waiter for push-based trigger nodes on the canvas-Run path (WhatsApp, Telegram, Webhook, Chat, Task completion). Deployed triggers ride the Temporal canary path; the Redis-Streams backend was retired in Wave 15.3 || **[Credentials Encryption](./docs-internal/credentials_encryption.md)** | Fernet + PBKDF2 encryption pipeline, separate credentials.db, two credential systems (OAuth vs API keys), multi-backend abstraction || **[Status Broadcaster](./docs-internal/status_broadcaster.md)** | WebSocket-first communication: StatusBroadcaster singleton, live count via `len(MESSAGE_HANDLERS) + len(get_ws_handlers())`, broadcast message types, Android two-state model |@@ -1142,7 +1142,7 @@ deploy_workflow() -> Sets up triggers, returns immediately### AI Chat Model System (5-Layer Architecture)-Chat-model nodes (`openaiChatModel`, `anthropicChatModel`, ...) render through `SquareNode` from the backend NodeSpec. Direct chat and every new agent execution route through the native SDK facade (`ChatUnifier` in `services/llm/`); the 13-provider surface is 11 cloud providers plus Ollama and LM Studio. Twelve providers have standalone chat-model nodes under `server/nodes/model/`, while xAI is selected directly from agent parameters. Model params (max output, context length, thinking type, temperature range) come from `ModelRegistryService`. The provider architecture, proxy/local-LLM routing, and the per-provider model + thinking/reasoning matrix (budget / effort / format) all live in **[Native LLM SDK](./docs-internal/native_llm_sdk.md)**. There is one wire standard (`MessageWire`) and no `llm_engine` / `message_wire_version` discriminator: the cutover-era markers and the `InvalidAgentLLMEngine` refusal path were purged (`tests/llm/test_single_wire_standard.py` fails the build if they reappear), and pre-cutover deployments are handled by Reset. The runtime output schema (`thinking` field for downstream nodes) is backend-served via `register_output_schema` (see [Plugin System](./docs-internal/plugin_system.md)).+Chat-model nodes (`openaiChatModel`, `anthropicChatModel`, ...) render through `SquareNode` from the backend NodeSpec. Direct chat and every new agent execution route through the native SDK facade (`ChatUnifier` in `services/llm/`); the provider surface is 11 cloud providers, Ollama and LM Studio, plus any number of user-named OpenAI-compatible endpoints (RFC-0003). Thirteen standalone chat-model nodes live under `server/nodes/model/` (one per fixed provider except xAI, which is selected directly from agent parameters, plus `openaiCompatibleChatModel` for a named endpoint). Model params (max output, context length, thinking type, temperature range) come from `ModelRegistryService`. The provider architecture, proxy/local-LLM routing, and the per-provider model + thinking/reasoning matrix (budget / effort / format) all live in **[Native LLM SDK](./docs-internal/native_llm_sdk.md)**. There is one wire standard (`MessageWire`) and no `llm_engine` / `message_wire_version` discriminator: the cutover-era markers and the `InvalidAgentLLMEngine` refusal path were purged (`tests/llm/test_single_wire_standard.py` fails the build if they reappear), and pre-cutover deployments are handled by Reset. The runtime output schema (`thinking` field for downstream nodes) is backend-served via `register_output_schema` (see [Plugin System](./docs-internal/plugin_system.md)).## AI Agent Node Architecture@@ -2765,7 +2765,7 @@ This function:- **`outputMode: "terminal"` uiHint — spec-driven CLI output rendering**: the output panel (`components/output/OutputPanel.tsx`, the active renderer — `ui/OutputDisplayPanel.tsx` is legacy/unimported) renders string responses through ReactMarkdown by default, which whitespace-collapses CLI text. CLI-wrapper plugins (`githubAction`, `vercelAction`, `shell`) declare `ui_hints = {"outputMode": "terminal"}`; the panel resolves the spec via `useNodeSpec(selectedNode?.type)` and renders their text in a `<pre>` on the per-theme `--code-*` surface, routes wholly-JSON strings to the JSON tree via the shared `tryParseJson` (`utils/formatters.ts`), and surfaces object/array `result` payloads (server-side-parsed CLI JSON; arrays survive `unwrap` un-peeled) in the Response section. Pair with the `_shape` convention: parsed JSON in `result` OR text in `stdout` — never both — empty keys omitted. Locked by `client/src/components/__tests__/OutputPanel.test.tsx` (render tests: real `\n`/`\t` preserved) + the uiHints known-set in `test_node_spec.py`. Cache note: nodeSpecs are session-sticky (`staleTime: FOREVER`, revision-busted at page load) — after a backend restart a hard browser reload is needed before new uiHints reach an open canvas.- **`--action-X-hover` triplet + ActionButton zero-arithmetic**: each of the 6 action roles (`run`/`stop`/`save`/`config`/`secret`/`tools`) now exposes a `-hover` variant (0.25 alpha) alongside the existing `-soft` (0.15) and `-border` (0.6). ActionButton's CVA reads `hover:bg-action-X-hover` directly; disabled state is the shadcn-idiomatic `disabled:opacity-50` on the base class. No per-token `/25`, `/40`, `/10` opacity arithmetic at any call site. Credential-modal panels (`OAuthConnect`, `EmailPanel`, `QrPairingPanel`) and the skill editor (`MasterSkillEditor`) consume `<ActionButton intent="...">` directly. `ActionDef` carries an `intent` key; the catalogue adapter maps server-sent `theme_color` palette strings to intents via `SERVER_COLOR_TO_INTENT`.- **Credentials: DB as single source of truth + symmetric broadcasts + cache dedup**: `CredentialsDatabase` (encrypted SQLite) is canonical; every other layer is a derived cache with explicit invalidation. Backend `AuthService._memory_cache + _models_cache` collapsed into one `_api_key_cache: Dict[str, ApiKeyCacheEntry]` dataclass — single write/evict site. Per RFC 9700 (OAuth 2.0 BCP, 2024) the `_oauth_cache` no longer carries `refresh_token`; new `get_oauth_refresh_token(provider, customer)` reads from the encrypted DB on every call. `validate_api_key`, `save_api_key`, `delete_api_key`, `twitter_logout`, `google_logout` now broadcast symmetrically: `update_api_key_status` (in-memory map) + `broadcast_credential_event(...)` (refetch signal) wrapping `WorkflowEvent` (CloudEvents v1.0 from `services/events/envelope.py`, the same envelope the Wave 12 EventSource framework uses). The dead-letter `credential_catalogue_updated` event is finally emitted by the backend. Frontend retired the 200-LOC `client/src/components/credentials/providers.tsx` static fallback — `useCatalogueQuery` is the only source; cold-boot renders `<Skeleton>`, server-unreachable shows an explicit error state. `ApiKeyStatus.hasKey` mirror dropped (duplicated catalogue's `provider.stored`); two new selector hooks (`useProviderStored`, `useStoredProviderCount`) read the catalogue. Pytest invariant `test_credential_broadcasts.py` (17 tests) locks the broadcast contract via `inspect.getsource` introspection + the CloudEvents v1.0 envelope shape + AuthService DB-write-then-cache-update ordering + the no-refresh-token-in-cache rule.-- **Local-LLM provider routing + per-model context**: Ollama and LM Studio are first-class providers (13 total for agents: 11 cloud + 2 local). Provider detection is driven by `detect_ai_provider` in `server/constants.py` plus the `provider` Literal in `nodes/agent/{ai_agent,chat_agent,_specialized}.py` — both MUST list `ollama` / `lmstudio` or chat-model nodes / agent dropdowns silently fall through to `'openai'` and `execute_chat` calls api.openai.com with the placeholder key. The validator at `nodes/model/_local_validator.py` probes via the official SDKs (`ollama.AsyncClient.ps()` for typed `ProcessResponse.Model`, `lmstudio.AsyncClient.llm.list_loaded()` for typed `LlmInstanceInfo`) — reads only typed fields (`context_length`, `max_context_length`, `vision`, `trained_for_tool_use`, `architecture`, `params_string`, `format`, plus Ollama's `details.{family,parameter_size,quantization_level}`). No regex, no Modelfile-parameters parsing, no `/api/show` modelinfo dict-key hunting. Per-model params persist in `EncryptedAPIKey.models["model_params"]` (via `save_api_key(model_params=...)`) AND in `model_registry.json` via `register_local_model()` — sync `get_context_length()` / `get_max_output_tokens()` find real values without async DB lookups, and entries survive process restart. `is_model_valid_for_provider` returns `True` for open-world providers (`openrouter` / `ollama` / `lmstudio`) so local model names like `qwen/qwen3.6-27b` aren't rejected by the cloud-style pattern check. Runtime path uses `OpenAIProvider(base_url={user_proxy_url}, api_key="ollama")` — traffic stays on `localhost`.+- **Local-LLM provider routing + per-model context**: Ollama and LM Studio are first-class providers. Chat-model node detection is `detect_ai_provider` in `server/constants.py`, which MUST list `ollama` / `lmstudio` or those nodes silently fall through to `'openai'`; agents need no edit, because their `provider` field is the loader-driven `ProviderRef` (`nodes/agent/_provider.py`, `aiProviders` loader). Saving (`nodes/model/_local_validator.py::save_llm_server`, shared with named endpoints) first roots the URL through the OpenAI surface (`services/llm/endpoints.py::resolve_base_url`, body must be an OpenAI list), writes nothing on failure, and then probes via the official SDKs (`ollama.AsyncClient.ps()` for typed `ProcessResponse.Model`, `lmstudio.AsyncClient.llm.list_loaded()` for typed `LlmInstanceInfo`) — reads only typed fields (`context_length`, `max_context_length`, `vision`, `trained_for_tool_use`, `architecture`, `params_string`, `format`, plus Ollama's `details.{family,parameter_size,quantization_level}`). No regex, no Modelfile-parameters parsing, no `/api/show` modelinfo dict-key hunting. Per-model params persist in `EncryptedAPIKey.models["model_params"]` (via `store_api_key(model_params=...)`) AND via `register_local_model()`, which keeps them apart from the OpenRouter snapshot and persists them under DATA_DIR (`local_models.json`) — sync `get_context_length()` / `get_max_output_tokens()` find real values without async DB lookups, entries survive process restart, an OpenRouter refresh cannot wipe them, and user model names never land in the tracked `config/model_registry.json`. `is_model_valid_for_provider` returns `True` for providers that declare `"open_world_models": true` (openrouter / groq / ollama / lmstudio / openai_compatible) so local model names like `qwen/qwen3.6-27b` aren't rejected by the cloud-style pattern check. Runtime path is `OpenAIProvider(base_url={resolved URL})` with the stored key or the vendor's declared placeholder (`resolve_credential`) — no provider rewrites a key, and traffic stays on `localhost`.- **Typed SDK error → `LLMError` → `NodeUserError`**: Native providers normalize SDK failures into structured `LLMError` values carrying category, retryability, HTTP status, provider code, request ID, and retry-after metadata. `ChatUnifier` translates them at the execution boundary into a user-safe `NodeUserError`; `BaseNode.execute()` logs that at WARN with one line and no stack trace. Unexpected exceptions retain the full-traceback path. In-process agent turns retry only errors marked retryable, while Temporal owns activity retries and disables the inner retry loop.- **Plugin extraction (Wave 11.I)**: every plugin's WS handlers, OAuth client, FastAPI router, and lifecycle service live entirely under `nodes/<plugin>/`. Eight plugin domains migrated this round (whatsapp / twitter / google-workspace / android / browser / email / code / credential-validation-scaffold for maps+apify+ollama+lmstudio) follow the telegram pattern. `routers/websocket.py` shrunk from ~3,785 to ~2,977 LOC (-808). Three plugin routers (`routers/twitter.py`, `routers/google.py`, `routers/android.py`) moved into `nodes/<plugin>/_router.py` and mount via the plugin-router loop in `main.py`; the explicit `app.include_router(<plugin>.router)` calls and `from routers import <plugin>` imports in `main.py` are gone. **`register_router(router, name=...)` is the new sibling helper to `register_ws_handlers` (same file: `services/ws_handler_registry.py`)** — the generic registry set has since grown to 18 (see the Plugin System row at the top of this file). **`Credential.validate(data) -> dict` + `Credential._probe(api_key) -> ProbeResult` is the new shared validator scaffold** in `services/plugin/credential.py` — replaces the per-router `_SPECIAL_PROVIDER_VALIDATORS` dict; one `_LLMApiKey._probe` method serves all 10 cloud LLM providers, dedicated `_probe` overrides handle Maps + Apify, `_LocalLLM.validate` overrides for Ollama / LM Studio's 2-storage edge case. **`tests/test_plugin_self_containment.py` locks the contract** with 10 invariant classes (forbidden-imports / no-router-outside-nodes / per-plugin self-registration / registry-API sanity / stale-paths-absent / main.py-does-not-mount / WS_HANDLERS-non-empty / plugin-folder-has-node-file / typed-event-factories / package-imports-cleanly); same `inspect.getsource` introspection style as `test_credential_broadcasts.py`. Wire format unchanged — frontend WS message-type strings (`whatsapp_status`, `twitter_oauth_login`, `google_oauth_status`, `android_relay_connect`, etc.) and HTTP route paths (`/api/twitter/callback`, `/api/google/callback`, `/api/android/*`) are byte-identical post-migration.- **Typed CloudEvents factory pattern for new broadcasts** (b6aecd3): every new server→FE lifecycle broadcast follows the recipe locked by `broadcast_credential_event`, `broadcast_agent_progress`, and `broadcast_agent_capability`. (1) Add a typed factory — convention: `source = "opencompany://services/<area>"`, reverse-DNS `type = "com.opencompany.<area>.<event>"`, and `subject = <exact primary entity id>`. Put snake_case workflow/execution scope inside `data`; CloudEvents extension attribute names MUST be lowercase-alphanumeric, so the historical top-level `workflow_id`/`trigger_node_id`/`correlation_id` fields are compatibility debt and are forbidden on new contracts. (2) Add a broadcaster wrapper that emits `broadcast({type: "<wire_key>", data: event.model_dump(mode="json", exclude_none=True)})`. (3) FE validates `specversion`, ID/source/type, subject ownership, and event-specific payload invariants, deduplicates by `(source,id)`, then writes only the exact scoped entity. (4) Add contract tests in `test_events.py` and keep `tests/test_status_broadcasts.py`'s raw-callsite allowlist empty. Raw `node_status` remains allowed only as the established high-frequency latest-state/reconnect projection paired with a typed lifecycle occurrence; it is not the event of record.diff --git a/RFC-0003-OPENAI-COMPATIBLE-PROVIDER-CONTRACT.md b/RFC-0003-OPENAI-COMPATIBLE-PROVIDER-CONTRACT.mdindex c4065da1..7dd9f7d4 100644--- a/RFC-0003-OPENAI-COMPATIBLE-PROVIDER-CONTRACT.md+++ b/RFC-0003-OPENAI-COMPATIBLE-PROVIDER-CONTRACT.md@@ -1,30 +1,44 @@# RFC-0003 — OpenAI-Compatible Provider Contract-Status: Draft+Status: AcceptedCreated: 2026-09-01-Scope: `server/services/llm/`, `server/nodes/model/`+Updated: 2026-09-24 (named endpoints, LiteLLM table, body-shape probe; implemented)+Scope: `server/services/llm/`, `server/nodes/model/`, `server/nodes/agent/`, `server/services/model_registry.py`, the credentials panelRelationship: independent of RFC-0002 (Context/Memory). Touches no agent state.## How to read this-If you are **adding a provider**, read §9. If you are **implementing**, read §3-(decisions) then §10 (phases). If you are **reviewing**, §3 and §11 are the-whole normative surface; everything else is rationale.+If you are **adding a provider**, read §11. If you are **adding a server you+run**, you need no code: §8 says what the credentials panel does. If you are+**reviewing**, §3 and §13 are the whole normative surface; everything else is+rationale.-Files this RFC changes, by phase:+Files this RFC changes:-| File | Phase | Change |-|---|---|---|-| `services/llm/protocol.py` | 1 | `LLMError` gains `public_message`; new `PROTOCOL` category |-| `services/llm/config.py` | 1 | `resolve_credential()`; capability accessors |-| `services/llm/providers/openai.py` | 2 | drop `api_key="ollama"`; drop `proxy_url` param |-| `services/llm/providers/anthropic.py` | 2 | drop the duplicate placeholder hardcode |-| `services/llm/unifier.py` | 2 | collapse proxy/base into one effective URL + `url_source` |-| `services/llm/endpoints.py` | 3 | **new** — save-time base-URL resolver |-| `nodes/model/_local_validator.py` | 3 | resolve before persist; drop the `/v1` 404 hint |-| `config/llm_defaults.json` | 1, 4 | `auth` block; capability flags |-| `services/llm/providers/openai.py` | 5 | 2xx-with-error-body guard |-| `docs-internal/native_llm_sdk.md` | 1 | fix the DeepSeek `/v1` claim (§13) |+| File | Change |+|---|---|+| `services/llm/config.py` | provider references (`split_provider_ref`, `endpoint_ref`); `resolve_credential()`; every `llm_defaults` lookup resolves a reference to its base block; `open_world_models` replaces a hardcoded tuple |+| `services/llm/protocol.py` | `LLMErrorCategory.PROTOCOL`; `LLMError.public_message` |+| `services/llm/endpoints.py` | **new** — save-time base-URL resolver; `redact_url`; endpoint listing |+| `services/llm/unifier.py` | provider lookup by reference; URL row read by reference; empty-key and missing-endpoint guards; `except LLMError`; failure logs carry `url` + `url_source` |+| `services/llm/providers/openai.py` | drop `api_key="ollama"`; `url_source`; 2xx-with-error-body guard |+| `services/llm/providers/anthropic.py` | drop the duplicate placeholder hardcode |+| `services/llm/providers/_compat.py` | one `openai_compatible` registration with no `base_url` |+| `nodes/model/_local_validator.py` | one save path for Ollama, LM Studio and every named endpoint |+| `nodes/model/_credentials.py` | `OpenAICompatibleCredential`; `_LocalLLM.resolve` uses `resolve_credential` |+| `nodes/model/_option_loaders.py`, `nodes/model/__init__.py` | **new** — `aiProviders`, `openaiCompatibleEndpoints`, `openaiCompatibleModels` loaders |+| `nodes/model/openai_compatible_chat_model/` | **new** — chat-model node for a named endpoint |+| `nodes/agent/_provider.py` + three agent Params | one loader-driven `ProviderRef` field replaces three `Literal` lists |+| `services/plugin/credential.py`, `routers/websocket.py` | optional `Credential.catalogue_extras()` hook, merged into the catalogue |+| `services/credentials/handlers.py` | `delete_api_key` also clears `{provider}_proxy` and registered models |+| `services/model_registry.py` | local models kept apart and persisted under DATA_DIR; LiteLLM table |+| `services/pricing.py` | reference-aware lookup; a named endpoint's recorded price |+| `services/settings/handlers.py` | each endpoint is a row in the global default-model picker |+| `services/rlm/service.py` | refuse a provider RLM cannot route |+| `constants.py` | new chat-model type; `detect_ai_provider` reads the node's endpoint |+| `config/llm_defaults.json` | `auth.placeholder_key`, `open_world_models`, the `openai_compatible` block |+| `config/credential_providers.json`, `config/pricing.json` | `openai_compatible` entries |+| `client/.../credentials/panels/ApiKeyPanel.tsx`, `EndpointList.tsx` | add / refresh / remove endpoints |## 1. Summary@@ -33,24 +47,26 @@ divergent shapes with **no specification behind it**, and the divergences areinvisible from a successful response.There are only two ways to hold a per-provider fact: declare it, or guess it.-Today the client guesses — that a stored base URL is correctly rooted, that the-credential belongs in `Authorization: Bearer`, that a provider with a-`{provider}_proxy` row wants the literal key `"ollama"`, and that HTTP 200 means-the request was understood. It also validates two providers against a different-wire surface than the one execution uses, so a credential can read green while-the runtime is dead.+The client used to guess — that a stored base URL is correctly rooted, that a+provider with a `{provider}_proxy` row wants the literal key `"ollama"`, and+that HTTP 200 means the request was understood. It also validated two+providers against a different wire surface than the one execution uses, so a+credential could read green while the runtime was dead.This RFC makes the endpoint and the credential **resolved facts** — computed-once, at save time, with evidence — and makes capability variance **declared**,-extending the `supports_model_listing` precedent the repo already ships. The-error contract is handled behaviourally, not by declaration (§8.4).+once, at save time, with evidence — and makes capability variance+**declared**. It then uses that contract to let a user add **any number of+named OpenAI-compatible servers** (llama.cpp, vLLM, a LiteLLM proxy, a second+Ollama host) with no code: the LiteLLM `model_list` idea of a label, a base+URL and an optional key, each selectable from every agent.## 2. Problem### 2.1 The failure chain (normative; other sections cross-reference here)A stored LM Studio base URL without `/v1`. The panel read **Connected** with-models discovered. Every run failed with `AI generated empty response`.+models discovered. Every run failed with `AI generated empty response`. Line+references are to the code as the draft of this RFC found it.| # | Step | Site ||---|---|---|@@ -64,13 +80,15 @@ models discovered. Every run failed with `AI generated empty response`.| 8 | SDK raises only on 4xx/5xx. `choices` is absent, so it coerces to `None` | `openai/_models.py` || 9 | Empty content becomes `AI generated empty response` | `services/ai.py` |-Two structural defects compound. **Validation exercises a surface execution+Two structural defects compound. **Validation exercised a surface executionnever touches** — LM Studio serves OpenAI-compat at `/v1/*`, native REST at`/api/v1/*`, and a WebSocket SDK at `ws://{host}/{namespace}`, all on one port;-Ollama likewise serves `/api/*` beside `/v1/*`. A green Fetch proves host+Ollama likewise serves `/api/*` beside `/v1/*`. A green Fetch proved hostliveness on the *native* surface and nothing about the prefix the runtime uses.-And **a 2xx is treated as an understood request**, which for this class of-server it is not.+And **a 2xx was treated as an understood request**, which for this class of+server it is not: LM Studio answers HTTP 200 to routes it does not serve+([lmstudio-bug-tracker#1323](https://github.com/lmstudio-ai/lmstudio-bug-tracker/issues/1323),+[#2085](https://github.com/lmstudio-ai/lmstudio-bug-tracker/issues/2085)).### 2.2 Why the endpoint cannot be inferred@@ -101,9 +119,12 @@ and it fails in the opposite direction for path-prefix deployments — vLLMdeliberately root-mounted server without probing. No string rule resolves it.That is why §6 probes.-`AzureOpenAI` is the shape of the fix: it takes `azure_endpoint` (host, no-path), builds `f"{endpoint}/openai"` itself, and rejects `base_url` as mutually-exclusive. Where the prefix is knowable, the library supplies it.+### 2.3 No way to add a server++Pointing an agent at llama.cpp, vLLM, a LiteLLM proxy or a second Ollama host+needed a Python edit: a provider id, a JSON block, a registration, three agent+`Literal` lists, a credential class. Each server the user runs is data, not+code.## 3. Decisions@@ -111,30 +132,37 @@ exclusive. Where the prefix is knowable, the library supplies it.|---|---|---|| D1 | A configured provider's `base_url` is copied verbatim from vendor docs. The runtime never appends, strips, or rewrites a path segment. | AG1, AG2 || D2 | A user-supplied base URL is **resolved by probing at save time**, once, and the resolved value is persisted. The runtime consumes it verbatim. | AG3, AG4 |-| D3 | Probe order is `{base}/models` then `{base}/v1/models`. First success wins. 401/403 counts as rooted. | AG3 |-| D4 | The probe verdict is three-state: `verified`, `rooted-unverified`, `failed`. | AG5 |-| D5 | On probe failure nothing is written to `{provider}_proxy`. The verdict lands on the credential row. | AG6 |+| D3 | The probe is the call execution makes (`models.list()` through the openai SDK), against `{base}` then `{base}/v1`. A candidate counts only when the **body is an OpenAI list** (a `data` array): a status code alone proves nothing (§2.1). A connection-level failure stops at the first candidate. | AG3 |+| D4 | Two outcomes: adopted, or failed with a reason in words the user can act on. A 401/403 is a failure reason ("server found at X, key rejected"), not a stored third state. | AG3 |+| D5 | A failed save **writes nothing and broadcasts nothing**. The previous working configuration stays in force. A save that yields no models is a failed save. | AG6 || D6 | The credential is resolved by one function. No provider hardcodes a placeholder key. | AG7, AG8 || D7 | No code path hands the SDK an unresolved credential — `api_key=None` makes the SDK read `OPENAI_API_KEY` and ship the operator's OpenAI key to a third party. | AG8 |-| D8 | A capability is **declared**, never sniffed. A flag ships only with a v1 consumer. | AG9 |-| D9 | A 2xx chat response with no `choices` and an error-shaped body raises `PROTOCOL`, naming the URL called. | AG10 |+| D8 | A capability is **declared**, never sniffed. A flag ships only with a consumer. This change ships two: `auth.placeholder_key` and `open_world_models`. | AG9 |+| D9 | A 2xx chat response with no `choices` and an error-shaped body raises `PROTOCOL`, naming the redacted URL called. | AG10 || D10 | Every provider-call failure logs the effective URL and `url_source`, redacted. Never the key. | AG11 || D11 | `ProviderSpec` gains no field. | AG12 |-| D12 | `_strip_v1_path` survives, scoped to the native enrichment probe only. | AG2 |+| D12 | `_strip_v1_path` survives, scoped to the native enrichment probes only. | AG2 |+| D13 | A named endpoint **is** a provider reference, `openai_compatible:<slug>`, with the same two credential rows Ollama uses: `{ref}` (key, models, per-model params) and `{ref}_proxy` (resolved URL). The reference travels as the ordinary `provider` string through key injection, Temporal payloads and the unifier. | AG15, AG16, AG17 |+| D14 | An endpoint's kind (`ollama`, `lmstudio`, `llamacpp`, `generic`) is **declared** for the Ollama and LM Studio providers and **detected once at save** for endpoints, from native routes by body shape. It is stored and never re-sniffed at run time. | AG13 |+| D15 | Per-model context, output budget and price come from the server first (Ollama and LM Studio SDK probes, llama.cpp `/props`, vLLM `max_model_len`), then the LiteLLM table for `generic` servers only, then the declared default. | AG14, AG18 |+| D16 | Runtime caches live under DATA_DIR, never in the tracked `server/config/`. A model registered from the user's own server survives an OpenRouter refresh. | AG18 |+| D17 | The shape is LiteLLM's and OpenRouter's, not a new one (§8.4). | — |## 4. Goals and non-goals-**Goals.** One connected verdict across panel and palette. A stored URL that-works keeps working with no operator action. A routing mistake is-distinguishable from a model failure in the message the user sees. Adding a-compatible provider is a JSON edit plus one name in a tuple.+**Goals.** One connected verdict across panel and palette. A URL that works+keeps working. A routing mistake is distinguishable from a model failure in the+message the user sees. Adding a compatible *vendor* is a JSON edit plus one+name in a tuple; adding a compatible *server* is a form in the credentials+panel.**Non-goals.** Not a universal LLM abstraction — `ChatUnifier` stays the singlefacade. Not a provider-registry rewrite. Not Anthropic's or Gemini's native wireformat; D6 and D7 apply to their credential handling only, because they share-the defect. Not per-model *discovery* — per-model declaration is permitted via-the existing `CapabilityConfig` precedence and required only where vendor docs-document a divergence.+the defect. Not a parameter-dropping layer: LiteLLM's `drop_params` exists+because LiteLLM passes caller parameters through, and `OpenAIProvider.chat`+sends none of the parameters local servers reject, so a drop list would have+nothing to drop (D8). Not RLM routing (§15).## 5. The base URL contract@@ -144,209 +172,339 @@ synthesized, completed, or normalized by the runtime.This is why `deepseek: "https://api.deepseek.com"` is **correct** — DeepSeekdocuments exactly that, with routes at `/chat/completions`. It is not a missing-`/v1` (§13).+`/v1` (§15).++The `base_url` values of the dedicated Anthropic and Gemini blocks are **REST+documentation, not SDK arguments**: the Anthropic SDK appends `/v1` itself, so+feeding it `https://api.anthropic.com/v1` would request `/v1/v1/messages`. The+unifier passes a URL only from the user's `{provider}_proxy` row or from a+compat registration's `client_kwargs`; it never reads `llm_defaults.json`+`base_url` for those two.Trailing slashes are irrelevant: `_enforce_trailing_slash`-(`openai/_base_client.py:414`) normalizes the base on assignment. Defensive-stripping or appending in our code is dead weight.+(`openai/_base_client.py:414`) normalizes the base on assignment.## 6. Endpoint resolution-Applies **only** to user-supplied URLs for self-hosted providers (`ollama`,-`lmstudio`). Configured providers are covered by §5.--```python-# services/llm/endpoints.py -- save-time only. Async, does IO.-async def resolve_base_url(candidate: str, *, api_key: str) -> ResolvedBaseUrl:- """Probe which prefix actually roots the OpenAI surface.+Applies to every user-supplied URL: the `ollama` and `lmstudio` providers and+every named endpoint. Configured providers are covered by §5.- A path-less URL is ambiguous: LiteLLM/llama.cpp/Jan serve at root,- LM Studio/Ollama/vLLM only under /v1. Probing is the only way to tell.+### 6.1 Rooting- GET /models is the one endpoint every compatible server implements and- the only side-effect-free one -- /chat/completions loads a model and- bills. Where a provider declares model_listing.path: null (Sarvam), the- declared fallback is one max_tokens=1 completion; that fallback is- itself a declared fact, not a guess.- """-```+`services/llm/endpoints.py::resolve_base_url(candidate, api_key)` is async and+save-time only. It sends `AsyncOpenAI(base_url=c, api_key=k, max_retries=0,+timeout=10).models.list()` — the exact call `OpenAIProvider.fetch_models`+makes — to `c = candidate`, then `candidate + "/v1"` unless the input already+ends there.-Order, first success wins:--| Candidate | Outcome |+| Answer at a candidate | Outcome ||---|---|-| `{base}/models` returns 2xx | `verified`, adopt `{base}` |-| `{base}/models` returns 401/403 | `rooted-unverified`, adopt `{base}` |-| `{base}/v1/models` returns 2xx | `verified`, adopt `{base}/v1`, `rewritten=True` |-| `{base}/v1/models` returns 401/403 | `rooted-unverified`, adopt `{base}/v1`, `rewritten=True` |-| neither | `failed`; nothing persisted to `{provider}_proxy` (D5) |+| a page whose `data` is a list | adopt it (INFO log when `/v1` was appended) |+| 401 / 403 | remember "server found here, key rejected"; try the next |+| connection refused / DNS / timeout | fail now: the other candidate is the same host |+| 404, or a 200 whose body is not a list | try the next |+| nothing adopted | fail, with the most specific reason |-401/403 means **routing succeeded, credentials did not** — vLLM's `--api-key`-protects the whole `/v1` prefix. At probe time that is a success signal. At-runtime the same status is a failure (§8.3). The two rules are deliberately-different, and both are stated here so neither is mistaken for the other.+A scheme-less value (`localhost:8080`) is refused with instructions, not+guessed at. The key sent with the probe is already resolved (§7), never+`None`.This handles path-prefix deployments correctly: `https://host/vllm` probes-`/vllm/models` then `/vllm/v1/models`. A has-a-path heuristic gets that-backwards.--`rewritten=True` logs at INFO naming both candidates. An operator who typed one-thing and got another must be able to find out why.+`/vllm/models` then `/vllm/v1/models`.**Two layers, different rules.** Save-time resolution is async and does IO.-Call-time consumption is synchronous and pure — it reads the resolved value and-nothing else. The AG1 tripwire excludes `endpoints.py` for exactly this reason,-and that exclusion is the module's justification for existing.+Call-time consumption reads the stored value and nothing else. The AG1+tripwire allowlists `endpoints.py` for exactly this reason, and that exclusion+is the module's justification for existing.-## 7. Credential resolution+### 6.2 Kind (D14)-`OpenAIProvider.__init__` currently does `if proxy_url: kwargs["api_key"] =-"ollama"` (`providers/openai.py:49`), duplicated at `anthropic.py:41`. That-hardcodes a dummy key for **any** provider with a proxy row, not just local-ones, and it is why a cloud proxy cannot work today.+For a named endpoint only, detected against the host (the resolved base with a+trailing `/v1` stripped), 3 s per route, each route accepted **by body shape**:++| Route | Accepted when the body | Kind |+|---|---|---|+| `GET /props` | has a `default_generation_settings` object | `llamacpp` (asked first: llama.cpp also mimics some Ollama routes) |+| `GET /api/v1/models` | has a `models` list | `lmstudio` (LM Studio's current native REST API; v0 is legacy) |+| `GET /api/version` | has a `version` string | `ollama` |+| otherwise | | `generic` |++### 6.3 Models and metadata (D15)++| Kind | Model ids | Context and output budget | Price |+|---|---|---|---|+| `ollama` | loaded models, official SDK `ps()` | the live `context_length` the server loaded | 0 |+| `lmstudio` | loaded models, official SDK `list_loaded()` + `get_info()` | live `context_length` | 0 |+| `llamacpp` | `/models` ids from §6.1 | `/props` `default_generation_settings.n_ctx` | 0 |+| `generic` | `/models` ids from §6.1 | vLLM `max_model_len` on the entry; else LiteLLM `max_input_tokens` / `max_output_tokens`; else the declared `_default` | LiteLLM per-token cost × 10⁶; else 0 |++LiteLLM never feeds a local kind: the bound that matters there is the context+the server was started with (Ollama silently truncates past it), not the+model's trained maximum, and a local run costs nothing. The official+`ollama` / `lmstudio` SDKs stay — `pyproject.toml` records choosing them over+hand-rolled probes, and `ollama` also serves embeddings.++### 6.4 Persisting++Only after rooting and describing succeed: write `{ref}_proxy` (the resolved+URL), then `{ref}` (key or placeholder, model ids, per-model params, and a+reserved `_endpoint` entry holding the label, the **redacted** URL and the+kind — that JSON column is not encrypted), then register the models, then+broadcast. Otherwise nothing (D5).-It is replaced by one resolver, in `config.py`:+## 7. Credential resolution-```python-def resolve_credential(provider: str, stored: str | None) -> str:- """Return the key to send. Never None, never a hardcoded vendor name."""-```+`OpenAIProvider.__init__` used to do `if proxy_url: kwargs["api_key"] =+"ollama"`, duplicated in `anthropic.py`: a dummy key for **any** provider with+a proxy row, which is why a cloud proxy could not work. Both are gone.-Providers that require a placeholder declare it:+One resolver, `services/llm/config.py::resolve_credential(provider, stored)`,+returns the stored key, else the placeholder the vendor documents, declared as+`providers.<name>.auth.placeholder_key`:-```json-"lmstudio": { "auth": { "scheme": "bearer", "placeholder_key": "lm-studio" } }-```+| Provider | Placeholder | Source |+|---|---|---|+| `ollama` | `ollama` | Ollama's OpenAI-compatibility docs: "required but ignored" |+| `lmstudio` | `lm-studio` | LM Studio's OpenAI-compatibility docs |+| `openai_compatible` | `sk-no-key-required` | llama.cpp server README's OpenAI client example |-Ollama's own docs say `api_key='ollama'` is "required but ignored", so the-placeholder is a **declared vendor fact**, not an invention.+Else it raises. The unifier turns that into a `NodeUserError` before any client+exists.**D7 is a security rule, not hygiene.** `AsyncOpenAI(api_key=None)` falls backto `os.environ["OPENAI_API_KEY"]`. Combined with a third-party `base_url`, that-ships the operator's OpenAI key to another vendor. No path may reach the SDK-with an unresolved credential; AG8 asserts zero requests are issued in that-state.+ships the operator's OpenAI key to another vendor. AG8 asserts zero requests+are issued without a resolved key.++## 8. Named endpoints (D13)++### 8.1 Identity and storage++`split_provider_ref(ref) -> (name, slug)` is the only parser. The slug comes+from the label via `python-slugify` (`[a-z0-9-]`, at most 24 characters, so+`openai_compatible:<slug>_proxy` fits the 50-character provider column), or+from the URL's host and port when no label is given. An existing label is+rejected, not auto-suffixed.++The reference is keyed like any provider, which is why endpoints do not use the+Discord `session_id` scoping: every LLM key lookup in the tree is keyed by+`provider` alone (node executor, delegated agents, the Temporal credential+resolver, RLM, the stored-key and provider-defaults handlers). A reference+passes through all of them unchanged; a scope would need each one edited, and+a missed one would silently send the placeholder instead of the user's key.++Everything read from `llm_defaults.json` or `pricing.json` resolves a reference+to the `openai_compatible` block through `split_provider_ref`, so an unsized+endpoint model gets the block's conservative defaults (8192 context, 2048+output: an overestimate overflows, an underestimate only compacts early),+never an unknown provider's fallbacks.++### 8.2 Where an endpoint appears++| Surface | How |+|---|---|+| Every agent's provider dropdown | the `provider` field is a loader-driven `ProviderRef` (`aiProviders`): registered providers in `llm_defaults.json` order, then one option per endpoint |+| The OpenAI-compatible chat-model node | an `endpoint` field (`openaiCompatibleEndpoints`) and a `model` field that depends on it (`openaiCompatibleModels`). Named `endpoint`, not `provider`: a `provider` sibling of `model` triggers the parameter panel's stored-key effect, which would copy the key into the node |+| The model dropdown | unchanged: `get_stored_api_key {provider: ref}` reads the endpoint's row |+| The global default-model picker | one row per endpoint |+| The credentials panel | the catalogue entry's `catalogue_extras()` adds `endpoints` and `stored`; the fields become an add form |-## 8. Capabilities and the error contract+Adding and refreshing go through `validate_api_key` (the Base URL in+`api_key`, the other fields under their catalogue keys, `ref` for a refresh,+which re-reads the stored URL and key); removing goes through `delete_api_key`,+which also clears the `{ref}_proxy` row and the registered models. No new+WebSocket handler, no new registry.-### 8.1 Declared, never sniffed+### 8.3 At run time-This extends `supports_model_listing` (`config.py:179-189`) rather than adding-a parallel mechanism. **A flag ships only with a consumer.** A declaration with-no reader is how `models_endpoint` and `build_headers` became dead config.+The unifier looks the provider up by `split_provider_ref(ref)[0]`, reads the+URL row by the full reference, and refuses an `openai_compatible` reference+with no URL row ("not configured") rather than let the SDK default to+api.openai.com. The client cache already keys on the URL and the key+fingerprint, so two endpoints never share a client unless they share both.-v1 flags and their consumers:+### 8.4 Alignment (D17)++| LiteLLM | OpenRouter | Here |+|---|---|---|+| `api_base` (a prefix, `/v1` included: "make sure your api_base has the /v1 postfix") | base `https://openrouter.ai/api/v1` | `base_url`, resolved once (§6.1) |+| a `model_list` entry (`model_name`, `litellm_params`) | — | an endpoint's two rows |+| `custom_llm_provider` | — | `kind` (§6.2) |+| `model_prices_and_context_window.json` | `GET /api/v1/models` (`context_length`, `top_provider.max_completion_tokens`, `pricing`) | the model registry's two feeds (§9) |++## 9. Model metadata (D15, D16)++`services/model_registry.py` holds three sources:++- **OpenRouter**, cached in the tracked `config/model_registry.json`, refreshed+ on a 24 h gate as before.+- **Models from the user's own servers**, registered at save time, kept in their+ own dict and persisted at `DATA_DIR/local_models.json`. They win lookups (they+ carry the loaded context), an OpenRouter refresh never replaces them, and they+ no longer write user model names into a tracked file.+- **LiteLLM's table**, fetched on the same 24 h gate (and on the first endpoint+ save if absent), trimmed to chat-mode entries and the four fields anything+ reads, cached at `DATA_DIR/litellm_models.json`. A failed fetch keeps the old+ copy. A lookup matches the exact key, else a key whose part after the first+ `/` equals the id, **only when exactly one does**: hosts size and price the+ same model differently, so an ambiguous match is no match.++`PricingService.get_pricing` resolves a reference to its block and, for a named+endpoint only, uses the price recorded at save time before the block's zero+default. Every other provider keeps its curated `pricing.json` behaviour.++## 10. Capabilities and the error contract++### 10.1 Declared, never sniffed++This extends `supports_model_listing` rather than adding a parallel mechanism.+**A flag ships only with a consumer.** The flags this change ships:| Flag | Consumer ||---|---|-| `model_listing.path` (null = no route) | existing `fetch_models` branch |-| `surface.responses` | replaces the `provider_name == "openai"` hardcode in `openai.py` |-| `auth.scheme`, `auth.placeholder_key` | `resolve_credential` (§7) |+| `auth.placeholder_key` | `resolve_credential` (§7) |+| `open_world_models` | `is_model_valid_for_provider` (replaces a hardcoded tuple) |+| `supports_model_listing` (existing) | `OpenAIProvider.fetch_models` |-Everything else — tool calling, structured outputs, embeddings, streaming usage-— is **declared next, not now**. Naming them here without a reader would repeat-the mistake this section exists to prevent.+`surface.responses` is deferred: nothing on the compat path needs it, and+`_model_policy`'s `provider_name == "openai"` branches are OpenAI's own+semantics, not compat quirks. Tool calling, structured outputs, embeddings and+streaming usage are **declared next, not now**.-### 8.2 The 2xx guard+### 10.2 The 2xx guardA 2xx chat response with **no `choices`** and an error-shaped body is a routing-failure, not an empty completion. It raises `LLMErrorCategory.PROTOCOL` with a-message naming the URL actually called. This is the single change that would-have made the original bug self-diagnosing.--### 8.3 Runtime errors+failure, not an empty completion. `OpenAIProvider._normalize` raises+`LLMErrorCategory.PROTOCOL` with a `public_message` naming the redacted URL,+and the unifier translates it to one `NodeUserError`. This is the single change+that would have made the original bug self-diagnosing.-401/403 at runtime is a credential failure and says so, quoting the effective-URL. Every failure logs `url_source` (one of `proxy`, `llm_defaults`,-`factory_default`), computed in `_get_or_create_entry` where the override is-chosen and carried into the exception. URLs pass through `redact_url()` — which-strips userinfo and the query string — before reaching a log or a user-facing-message. The key is never logged in any form.+### 10.3 Runtime errors-Per the repo's `NodeUserError` contract, a routing or credential failure is-user-correctable: one WARN line, no traceback.+Every failure logs `url` (redacted by `redact_url`: no userinfo, query or+fragment) and `url_source` (`proxy`, `llm_defaults` or `sdk_default`, recorded+by `OpenAIProvider` when it is built). The key is never logged. Per the repo's+`NodeUserError` contract, a routing or credential failure is user-correctable:+one WARN line, no traceback.-### 8.4 No declared error block+### 10.4 No declared error blockThe four per-provider facts are rooting, auth, capability, and error contract.The first three are declared; the **error contract is handled behaviourally** —-tolerant parsing plus the §8.2 guard. Declaring per-provider error shapes would+tolerant parsing plus the §10.2 guard. Declaring per-provider error shapes wouldbe a table with one entry and no way to keep it honest.-## 9. Adding an OpenAI-compatible provider+## 11. Adding++**A compatible vendor** (a fixed, public API):1. Copy `base_url` **verbatim** from the vendor's docs. Do not normalize it.-2. Add a `providers.<name>` block to `llm_defaults.json` with `base_url`, an- `auth` block, and any capability flag that differs from the permissive- default. Add a `_note` citing the doc URL for each non-default flag.+2. Add a `providers.<name>` block to `llm_defaults.json` with `base_url` and any+ flag that differs from the permissive default, with a `_note` citing the doc+ URL for each non-default flag.3. Add the name to `_COMPAT_PROVIDERS` in `providers/_compat.py`.-4. If the vendor documents no model-list route, set `model_listing.path: null`.-5. Nothing else. No provider subclass, no `ProviderSpec` field (D11), no Python.--## 10. Migration+4. If the vendor documents no model-list route, set `supports_model_listing: false`.+5. Nothing else. No provider subclass, no `ProviderSpec` field (D11).-Backward compatible throughout: an existing stored URL that works keeps working-with no operator action.+**A server you run**: Credentials, OpenAI-compatible, Base URL (with or+without `/v1`), an optional label and key, Add endpoint. No code.-| Phase | Change | Rollback |-|---|---|---|-| 1 | `LLMError.public_message`, `PROTOCOL`, `resolve_credential`, `auth` blocks. Additive, no reader. | revert alone |-| 2 | Constructors consume `resolve_credential`; unifier collapses to one effective URL plus `url_source`. Touches `openai.py`, `anthropic.py`, `unifier.py`. | revert alone |-| 3 | `endpoints.py` plus validator resolves before persist. Gated by `LLM_ENDPOINT_CONTRACT_ENABLED`, shipping **false**; flipped in a separate commit. | flag |-| 4 | Capability flags with consumers (§8.1). | revert alone |-| 5 | 2xx guard. Depends on Phase 2 for `url_source`. | revert alone |+## 12. Phases-Phase 2 preserves behaviour exactly for every currently-working install: a local-provider with a placeholder row resolves to the same key it sends today. Phase 3-is where a previously-broken URL starts working.+Each a revertible commit; no feature flag. Save-time probing is idempotent and+records nothing in Temporal history, so there is nothing to replay-protect.-## 11. Acceptance gates--| # | Assertion | Style |+| Phase | Change |+|---|---|+| 0 | this RFC |+| 1 | contract primitives: provider references, `resolve_credential`, `PROTOCOL`, JSON declarations |+| 2 | runtime: unifier guards, constructors, 2xx guard, reference-aware fallbacks and pricing |+| 3 | save-time rooting and the shared save path for Ollama and LM Studio |+| 4 | registry caches and the LiteLLM table |+| 5 | the `openai_compatible` provider: registration, credential, catalogue hook, loaders, node, agent field, settings, RLM guard |+| 6 | the credentials panel |+| 7 | docs |++No data migration. An existing Ollama or LM Studio row keeps working as+stored; the next Fetch re-roots it through §6 and replaces the old `"ollama"`+key on the LM Studio row with LM Studio's own placeholder.++## 13. Acceptance gates++| # | Assertion | Test ||---|---|---|-| AG1 | No `"/v1"` literal and no `.rstrip("/")` under `services/llm/` or `nodes/model/`, except the AG2 allowlist | AST scan |-| AG2 | The allowlist is exactly `endpoints.py` (save-time resolver) and `_local_validator._strip_v1_path` (native probe only) | source introspection |-| AG3 | The resolver probes `{base}/models` then `{base}/v1/models`, adopting on 2xx or 401/403 | async unit |-| AG4 | Runtime client construction contains no probe and no `await` on a URL | AST |-| AG5 | All three verdict states render distinctly on both panel and palette | FE + BE unit |-| AG6 | A failed probe writes nothing to `{provider}_proxy` | async unit |-| AG7 | No literal `"ollama"` or `"lm-studio"` appears in any provider `__init__` | source scan |-| AG8 | With `OPENAI_API_KEY` set and no stored key, every provider raises `NodeUserError` and issues **zero** requests | async unit |-| AG9 | Every flag in `llm_defaults.json` has a reader in `services/llm/` | AST cross-check |-| AG10 | 2xx with no `choices` and an error body raises `PROTOCOL` naming the URL | unit |-| AG11 | No log line or `public_message` contains userinfo, a query string, or `Bearer` | unit |-| AG12 | The `ProviderSpec` field set is unchanged | source introspection |--## 12. What this RFC does not change+| AG1 | No code appends, strips or rewrites a `/v1` fragment, and no `rstrip("/")`, under `services/llm/` or `nodes/model/` outside the AG2 allowlist | `tests/llm/test_rfc0003_source_contract.py` (AST) |+| AG2 | The allowlist is exactly `endpoints.py` and `_local_validator._strip_v1_path` | same |+| AG3 | Rooting adopts only an OpenAI list; order, rewrite, rejected-key and connection-failure outcomes | `tests/llm/test_endpoint_resolution.py` (respx, real SDK) |+| AG4 | Client construction does no IO; only the save path calls `resolve_base_url` | `test_rfc0003_source_contract.py` |+| AG6 | A failed save writes no row and broadcasts nothing | `tests/nodes/test_local_llm_save.py` |+| AG7 | No placeholder literal in any provider `__init__` | `test_rfc0003_source_contract.py` |+| AG8 | With `OPENAI_API_KEY` set and no key, keyed providers raise `NodeUserError` and issue zero requests | `tests/llm/test_provider_refs.py` |+| AG9 | Every `llm_defaults.json` provider key has a reader; the known-dead keys are an explicit list | `test_rfc0003_source_contract.py` |+| AG10 | 2xx with no `choices` and an error body raises `PROTOCOL` naming the redacted URL | `tests/llm/test_protocol_guard.py` |+| AG11 | No public message carries userinfo, a query string or `Bearer`; `redact_url` cases | `test_protocol_guard.py`, `test_endpoint_resolution.py` |+| AG12 | `ProviderSpec`'s field set is unchanged | `test_rfc0003_source_contract.py` |+| AG13 | Kind detection by body shape, including an LM Studio 200-with-error that is not Ollama | `test_local_llm_save.py` |+| AG14 | Metadata per kind; LiteLLM never consulted for a local kind; the SDK probes still called | `test_local_llm_save.py` |+| AG15 | Endpoint add / refresh / remove / catalogue, against the real encrypted store | `tests/credentials/test_openai_compatible_credential.py` |+| AG16 | A reference resolves config, registry and pricing fallbacks to its block and is open-world; the unifier reads its URL row and refuses a missing one | `test_provider_refs.py` |+| AG17 | `openai_compatible` is registered once, `OpenAIProvider`, no `base_url` | `tests/llm/test_provider_self_registration.py` |+| AG18 | Refresh keeps local models; caches under DATA_DIR only; LiteLLM trimming and matching | `tests/services/test_model_registry_caches.py` |+| AG19 | Every agent `provider` field is loader-driven and offers every registered provider except the bare endpoint id | `tests/llm/test_plugin_shape.py` |+| AG20 | RLM refuses a provider it cannot route; the node, loaders and `ProviderRef` validation | `tests/nodes/test_openai_compatible_node.py` |+| FE | The endpoint list renders rows and hands the clicked row back | `client/.../panels/__tests__/EndpointList.test.tsx` |++AG5 (three verdict states rendered) is retired with D4.++## 14. What this RFC does not change`ChatUnifier` stays the single facade. `ProviderSpec` keeps its shape (D11).`sdk_exception_refs` stay lazy `"module:ClassName"` strings — no SDK import atregistration, per `tests/llm/test_lazy_sdk_imports.py`. `OpenRouterProvider`keeps its own `__init__` and its hardcoded base; it is correct per vendor docs.-The dead JSON fields (`models_endpoint`, `api_key_format`, `extra_headers`) are-**not deleted here** — that is a subtractive change with its own risk, tracked-separately.+Temporal workflow code is untouched: a provider reference is an ordinary+string in existing payload fields.++The JSON keys nothing reads are `api_key_param` and `max_tokens_param` (the+draft of this RFC named `models_endpoint`, `api_key_format` and+`extra_headers`; the first and last do have readers, and `api_key_format` is+not a JSON key). They are **not deleted here** — a subtractive change with its+own risk, tracked separately; AG9 lists them so no new one appears.++## 15. Compatibility audit++All nine compat `base_url` values in `llm_defaults.json` match their vendor+docs and need no change; in particular `deepseek` is path-less and correct.+Any future change that "corrects" the JSON toward `/v1` is a regression.++Servers the user runs:-## 13. Compatibility audit of the nine compat providers+| Server | Rooted at | Kind | Notes |+|---|---|---|---|+| Ollama | `/v1` | `ollama` | placeholder key `ollama`; only loaded models are listed, with their live context |+| LM Studio | `/v1` | `lmstudio` | answers 200 to unknown routes (§2.1); its optional API tokens cannot be used yet, because its panel has no key field |+| llama.cpp | root and `/v1` | `llamacpp` | tool calling needs the server started with `--jinja` (stated in the panel instructions) |+| vLLM | `/v1` | `generic` | `--api-key` protects `/v1`, so a wrong key reads "key rejected at …/v1"; `max_model_len` sizes each model |+| LiteLLM proxy | root and `/v1` | `generic` | a virtual key goes in the API key field; bare model names (`gpt-4o`) are sized and priced from LiteLLM's own table |-All nine `base_url` values in `llm_defaults.json` match their vendor docs and-need no change; in particular `deepseek` is path-less and correct.-`native_llm_sdk.md` already documents it as root-mounted with no `/v1`; the doc-defect this section originally recorded has been fixed. Any future change that-"corrects" the JSON toward `/v1` is a regression.+**RLM** builds its own clients from `services/rlm/constants.py` for six+providers and never reads a user base URL, so it cannot use a local server or+a named endpoint. It now refuses such a provider with a clear message instead+of sending the request to api.openai.com; routing it properly is separate work.-## 14. References+## 16. References- openai-python `_base_client.py` — `_prepare_url:496`, `_enforce_trailing_slash:414`- openai-python `lib/azure.py` — `azure_endpoint` / `base_url` mutual exclusion- DeepSeek https://api-docs.deepseek.com/ — base `https://api.deepseek.com`- Groq https://console.groq.com/docs/openai — `/openai/v1`-- OpenRouter https://openrouter.ai/docs/quickstart — `/api/v1`+- OpenRouter https://openrouter.ai/docs/quickstart — `/api/v1`; models API https://openrouter.ai/api/v1/models- Fireworks https://docs.fireworks.ai/tools-sdks/openai-compatibility — `/inference/v1`- Sarvam https://docs.sarvam.ai/api/getting-started/models/open-source — `/v1` and `/v2`-- LM Studio https://lmstudio.ai/docs/app/api/endpoints/openai-- Ollama https://docs.ollama.com/api/openai-compatibility+- LM Studio https://lmstudio.ai/docs/app/api/endpoints/openai; native list https://lmstudio.ai/docs/developer/rest/list+- LM Studio 200 on unknown routes https://github.com/lmstudio-ai/lmstudio-bug-tracker/issues/1323, https://github.com/lmstudio-ai/lmstudio-bug-tracker/issues/2085+- Ollama https://docs.ollama.com/openai- vLLM https://docs.vllm.ai/en/latest/cli/serve.html — `--root-path`-- llama.cpp https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md — `--api-prefix`-- LiteLLM https://docs.litellm.ai/docs/proxy/user_keys+- llama.cpp https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md — `--api-prefix`, `/props`, `sk-no-key-required`+- LiteLLM https://docs.litellm.ai/docs/providers/openai_compatible; https://docs.litellm.ai/docs/proxy/user_keys; table https://github.com/BerriAI/litellm (`model_prices_and_context_window.json`)- Open WebUI https://docs.openwebui.com/reference/api-endpoints/diff --git a/docs-internal/native_llm_sdk.md b/docs-internal/native_llm_sdk.mdindex f5b5bf50..ec891f35 100644--- a/docs-internal/native_llm_sdk.md+++ b/docs-internal/native_llm_sdk.md@@ -15,7 +15,8 @@ Talking to each vendor SDK directly avoids three problems a translation layer ke3. **Endpoint control**: OpenAI-compatible endpoint URLs are declared in`server/config/llm_defaults.json` and registered through `_compat.py`.Adding one requires the JSON entry plus one `_COMPAT_PROVIDERS` entry, not a- provider-specific adapter class.+ provider-specific adapter class. A server the user runs needs no code at+ all: it is a named endpoint (see "Named OpenAI-compatible endpoints").The native layer also gives a single normalized response shape (`LLMResponse`) across providers, which simplifies downstream code for token tracking, cost calculation, and thinking extraction.@@ -25,7 +26,10 @@ The native layer also gives a single normalized response shape (`LLMResponse`) aserver/services/llm/|-- __init__.py Public API exports|-- protocol.py Message, ToolDef, ToolCall, Usage, LLMResponse, LLMProvider (Protocol)-|-- config.py ProviderConfig, PROVIDER_CONFIGS (built from llm_defaults.json)+|-- config.py ProviderConfig, PROVIDER_CONFIGS (built from llm_defaults.json);+| provider references (split_provider_ref) and resolve_credential+|-- endpoints.py Save-time only: resolve_base_url (roots a user URL by asking the+| server), redact_url, list_endpoints (RFC-0003)|-- registry.py ProviderSpec + register_provider() — the live provider entry point;| sdk_exception_refs are lazy "module:Class" strings resolved at except time.| THIN SHIM since the speech work: the mechanism lives in@@ -45,7 +49,8 @@ server/services/llm/|-- gemini.py GeminiProvider (google-genai SDK)|-- openrouter.py OpenRouterProvider (extends OpenAIProvider with headers)`-- _compat.py Registers the 9 OpenAI-compatible providers (xai, deepseek, kimi,- mistral, groq, cerebras, ollama, lmstudio, sarvam) via base_url specs+ mistral, groq, cerebras, ollama, lmstudio, sarvam) via base_url specs,+ plus openai_compatible (no base_url) for every named endpoint```Each provider module calls `register_provider(ProviderSpec(...))` at module@@ -55,7 +60,9 @@ providers share `_compat.py` and its explicit `_COMPAT_PROVIDERS` tuple.## Supported Providers-The native layer currently supports **13 providers**, grouped by implementation:+The native layer currently registers **14 providers**, grouped by implementation.+The last, `openai_compatible`, is not one server: it serves any number of+user-named endpoints, each its own provider reference `openai_compatible:<slug>`.| Provider | Implementation | SDK | Notes ||---|---|---|---|@@ -67,8 +74,9 @@ The native layer currently supports **13 providers**, grouped by implementation:| `deepseek` | `providers/_compat.py` + base_url | `openai` | OpenAI-compatible at `api.deepseek.com` (root-mounted, no `/v1`) || `kimi` | `providers/_compat.py` + base_url | `openai` | Moonshot AI, OpenAI-compatible || `mistral` | `providers/_compat.py` + base_url | `openai` | OpenAI-compatible |-| `ollama` | `providers/_compat.py` + `{provider}_proxy` URL | `openai` (chat) + `ollama` (probe) | Local server. Validator probes via `ollama.AsyncClient.ps()` for typed `context_length` per loaded model. Runtime uses `OpenAIProvider` with `base_url={user URL}` so traffic stays on `localhost`. |-| `lmstudio` | `providers/_compat.py` + `{provider}_proxy` URL | `openai` (chat) + `lmstudio` (probe) | Local server. Validator probes via `lmstudio.AsyncClient.llm.list_loaded()` for typed `LlmInstanceInfo.context_length`. Same OpenAI-compat runtime path as Ollama. |+| `ollama` | `providers/_compat.py` + `{provider}_proxy` URL | `openai` (chat) + `ollama` (probe) | Local server. Saving roots the URL through the OpenAI surface, then `ollama.AsyncClient.ps()` gives the typed `context_length` of each loaded model. Runtime uses `OpenAIProvider` with `base_url={resolved URL}` so traffic stays on `localhost`. |+| `lmstudio` | `providers/_compat.py` + `{provider}_proxy` URL | `openai` (chat) + `lmstudio` (probe) | Local server. Same save path; `lmstudio.AsyncClient.llm.list_loaded()` gives the typed `LlmInstanceInfo.context_length`. Same OpenAI-compat runtime path as Ollama. |+| `openai_compatible` | `providers/_compat.py` (no `base_url`) + one `{ref}_proxy` URL per endpoint | `openai` | Named endpoints: llama.cpp, vLLM, a LiteLLM proxy, a second Ollama host. Added in the Credentials Modal; see "Named OpenAI-compatible endpoints". || `groq` | `providers/_compat.py` + base_url | `openai` | OpenAI-compatible || `cerebras` | `providers/_compat.py` + base_url | `openai` | OpenAI-compatible || `sarvam` | `providers/_compat.py` + base_url | `openai` | Indic-first (`sarvam-105b` 128K, `sarvam-30b` 64K) at `api.sarvam.ai/v1`. Ships **no model-list route**, so it sets `supports_model_listing: false` — see below. Reasoning is on by default and returns in `reasoning_content`, which `OpenAIProvider._normalize` already reads. |@@ -77,13 +85,15 @@ Source of truth for this list: `server/config/llm_defaults.json` (the `providers### Native chat path vs agent dropdown — two different counts-- **Native chat path (`execute_chat` / `fetch_models`) supports 13 providers, all native** — Anthropic and Gemini via their own SDKs; OpenAI and OpenRouter via the openai SDK; and 9 more through the shared OpenAI-compatible client with a per-provider `base_url` (xai, deepseek, kimi, mistral, groq, cerebras, ollama, lmstudio, sarvam — registered in `providers/_compat.py`). `execute_chat` delegates every provider to `ChatUnifier.chat`; there is no per-provider branch. `xai` lives here.-- **The agent dropdown exposes the same 13 providers** for `aiAgent`,- `chatAgent` (Zeenie), and all specialized agents, including `xai`.- `test_plugin_shape.py` asserts exact set equality between the registry and- the `provider` Literal in all three agent Params classes, so registering a- provider without updating `nodes/agent/ai_agent`, `nodes/agent/chat_agent`- and `nodes/agent/_specialized` fails CI immediately.+- **Native chat path (`execute_chat` / `fetch_models`) supports every registered provider, all native** — Anthropic and Gemini via their own SDKs; OpenAI and OpenRouter via the openai SDK; and the rest through the shared OpenAI-compatible client (xai, deepseek, kimi, mistral, groq, cerebras, ollama, lmstudio, sarvam with a per-provider `base_url`, and every named endpoint with its own resolved URL — all registered in `providers/_compat.py`). `execute_chat` delegates every provider to `ChatUnifier.chat`; there is no per-provider branch. `xai` lives here.+- **The agent dropdown offers every registered provider, then each saved+ endpoint**, for `aiAgent`, `chatAgent` (Zeenie) and all specialized agents.+ The `provider` field is one loader-driven `ProviderRef`+ (`nodes/agent/_provider.py`, options from the `aiProviders` loader in+ `nodes/model/_option_loaders.py`, ordered as `llm_defaults.json` lists the+ providers), so registering a provider needs no agent edit.+ `test_plugin_shape.py` asserts the loader offers exactly the registry minus+ the bare `openai_compatible` id.- Groq, Cerebras, xAI, and the other compatible endpoints use the same nativeOpenAI SDK adapter for both standalone chat and agent tool calls.@@ -109,6 +119,7 @@ Source of truth for this list: `server/config/llm_defaults.json` (the `providers| **Cerebras** | GPT-OSS-120b (default), qwen-3.8-27b — the only two public-endpoint models | 131K | 40K | none (`thinking_models` empty since zai-glm-4.7 left the public endpoints) | 0-1.5 || **Ollama** | Whatever the user has pulled (qwen2.5, llama3.x, phi-3, deepseek-r1, ...) | per-loaded-model (typed via `ps()`) | ctx ÷ 4 (capped 4096) | none (per-model) | 0-2 || **LM Studio** | Whatever the user has loaded in the LM Studio UI | per-loaded-model (typed via `LlmInstanceInfo.context_length`) | ctx ÷ 4 (capped 4096) | none (per-model) | 0-2 |+| **Named endpoints** | Whatever each server lists at `/models` | llama.cpp `/props` `n_ctx`; vLLM `max_model_len`; else the LiteLLM table; else 8192 | LiteLLM figure, else ctx ÷ 4 (capped 4096), else 2048 | none (per-model) | 0-2 |`_resolve_max_tokens()` in `server/services/ai.py` (a thin wrapper over `services/llm/config.py::resolve_max_tokens`) clamps user-requested `max_tokens` to the model's actual limit.@@ -116,27 +127,59 @@ Source of truth for this list: `server/config/llm_defaults.json` (the `providersOllama and LM Studio expose an OpenAI-compatible `/v1` HTTP API, so they ride the same `OpenAIProvider` runtime path used by every other OpenAI-compat backend (DeepSeek, Kimi, Mistral). The differences are the **base URL** (the user enters their server's address, e.g. `http://localhost:11434/v1`) and the **per-model parameters** (which depend on what the user has loaded in the local server's UI, not a JSON default).-**Probe layer** ([`server/nodes/model/_local_validator.py`](../server/nodes/model/_local_validator.py)) — when the user clicks "Fetch" in the Credentials Modal:+**Save path** ([`server/nodes/model/_local_validator.py`](../server/nodes/model/_local_validator.py), RFC-0003 §6) — when the user clicks "Fetch" in the Credentials Modal:-1. The user's URL is persisted under the existing `{provider}_proxy` credential — same key the OpenAI-style auth-delegation pattern already uses to override `base_url` at runtime.-2. The validator probes via the **official SDK** (`ollama>=0.6.0`, `lmstudio>=1.5.0`) — never raw httpx, never Modelfile-parameters parsing:+1. **Root the URL** through the OpenAI surface the runtime uses: `services/llm/endpoints.py::resolve_base_url` sends the SDK's own `models.list()` to the entered URL, then to it plus `/v1`, and adopts the first answer whose body is an OpenAI list. A status code alone proves nothing — LM Studio answers HTTP 200 to routes it does not serve — so a URL entered without `/v1` is resolved rather than saved broken. This replaces the old order (persist, then probe the *native* API), which let a `/v1`-less LM Studio URL read Connected and fail every run.+2. **Describe the loaded models** via the **official SDK** (`ollama>=0.6.0`, `lmstudio>=1.5.0`) — never raw httpx, never Modelfile-parameters parsing:- **Ollama**: `ollama.AsyncClient.ps()` returns `ProcessResponse.Model` per loaded model with typed `context_length` + typed `ModelDetails` (`family`, `parameter_size`, `quantization_level`, `format`).- **LM Studio**: `lmstudio.AsyncClient.llm.list_loaded()` returns `AsyncModelHandle` per loaded model; `handle.get_info()` is a typed `LlmInstanceInfo` (`context_length`, `max_context_length`, `vision`, `trained_for_tool_use`, `architecture`, `params_string`, `format`).-3. The probed params are persisted in two places:- - `EncryptedAPIKey.models["model_params"]` — the same JSON column as the model list, sibling key. Survives DB-backed restart of the validator state.- - `model_registry.register_local_model()` — populates a `ModelInfo` entry under `<provider>/<model_id>` and writes through to `model_registry.json`. The sync `get_context_length()` / `get_max_output_tokens()` lookups find this entry first, so chat / agent execution honour the **real n_ctx the server is currently serving** instead of a JSON guess. Capability flags (`tools`, `vision`) flow through `ModelInfo.supported_parameters`.--**Both servers must have a model loaded** for the probe to return entries. The validator's "no models loaded" message is symmetric across providers.--**Runtime path** — `ChatUnifier` resolves `{provider}_proxy` and passes it to-the registered provider factory. `OpenAIProvider` overrides `base_url` with the-user's URL and uses the documented placeholder key for unauthenticated local-servers. The OpenAI SDK then sends to the configured local endpoint — traffic-never reaches api.openai.com.--**Provider detection** ([`server/constants.py:detect_ai_provider`](../server/constants.py)) MUST list `ollama` / `lmstudio` substrings, and the agent dropdown's `provider` Literal in [`ai_agent/__init__.py`](../server/nodes/agent/ai_agent/__init__.py) / [`chat_agent/__init__.py`](../server/nodes/agent/chat_agent/__init__.py) / [`_specialized.py`](../server/nodes/agent/_specialized.py) MUST include `"ollama"` / `"lmstudio"` — otherwise the chat-model node silently falls through to `'openai'` and the runtime calls the OpenAI cloud with the local-server placeholder key.--**Open-world skip in `is_model_valid_for_provider`** — local model names like `qwen/qwen3.6-27b` don't contain provider substrings, so the cloud-style pattern check would always reject them. The function returns `True` for `openrouter` / `ollama` / `lmstudio` without consulting `detection_patterns`. The upstream server still rejects genuinely missing models with a clear 404.+3. **Persist only on success**: `{provider}_proxy` gets the resolved URL, then `{provider}` gets the vendor's documented placeholder key (`auth.placeholder_key` in `llm_defaults.json`, resolved by `services/llm/config.py::resolve_credential`), the model list and `model_params`. The params are also registered with `model_registry.register_local_model()`, which keeps them apart from the OpenRouter snapshot and persists them under DATA_DIR (`local_models.json`), so the sync `get_context_length()` / `get_max_output_tokens()` lookups honour the **real n_ctx the server is currently serving**, an OpenRouter refresh cannot wipe them, and user model names never land in the tracked `config/model_registry.json`.++A failed save writes nothing and broadcasts nothing: a typo in a re-Fetch leaves a working configuration in force. **Both servers must have a model loaded** for the probe to return entries; "no models loaded" is a failed save.++**Runtime path** — `ChatUnifier` reads `{provider}_proxy` and passes it to the+registered provider factory. `OpenAIProvider` uses it as `base_url` and sends+the stored key as stored (no provider rewrites a key any more). The OpenAI SDK+then sends to the configured local endpoint — traffic never reaches+api.openai.com.++**Provider detection** ([`server/constants.py:detect_ai_provider`](../server/constants.py)) MUST list `ollama` / `lmstudio` substrings, or a chat-model node falls through to `'openai'`. Agents need no edit: their `provider` field is loader-driven.++**Open-world providers** — local model names like `qwen/qwen3.6-27b` don't contain provider substrings, so the cloud-style pattern check would always reject them. A provider block declares `"open_world_models": true` (openrouter, groq, ollama, lmstudio, openai_compatible) and `is_model_valid_for_provider` accepts any id for it. The upstream server still rejects genuinely missing models with a clear 404.++## Named OpenAI-compatible endpoints++Any server that speaks the OpenAI API — llama.cpp, vLLM, a LiteLLM proxy,+SGLang, LocalAI, another Ollama or LM Studio host — is added in the Credentials+Modal under **OpenAI-compatible** with a Base URL (with or without `/v1`), an+optional label and an optional key. No code. RFC-0003 D13–D17 is the contract.++- **Identity.** Each endpoint is the provider reference+ `openai_compatible:<slug>` (slug from the label, else from the host and port).+ It is stored exactly like Ollama: `{ref}` holds the key (or the placeholder+ `sk-no-key-required`), the model list and per-model params; `{ref}_proxy`+ holds the resolved URL. The reference travels as the ordinary `provider`+ string, so key injection, Temporal payloads and the unifier need nothing new;+ everything read from `llm_defaults.json` or `pricing.json` resolves it to the+ shared `openai_compatible` block through `split_provider_ref`.+- **Saving** runs the same path as Ollama, plus a one-time kind detection from+ native routes by body shape (`/props` → llama.cpp, `/api/v1/models` → LM+ Studio, `/api/version` → Ollama, else generic). Context and price come from the+ server first (Ollama / LM Studio SDK probes, llama.cpp `/props` `n_ctx`, vLLM+ `max_model_len`), then — for generic servers only — LiteLLM's+ `model_prices_and_context_window.json` (fetched by `ModelRegistryService` on+ the OpenRouter refresh gate, trimmed, cached under DATA_DIR, matched only when+ unambiguous), then the block's conservative defaults (8192 / 2048).+- **Selecting.** Every agent's provider dropdown lists each endpoint after the+ registered providers. The `openaiCompatibleChatModel` node picks one in its+ `endpoint` field — deliberately not `provider`, which would trigger the+ parameter panel's stored-key effect — and its `model` dropdown lists that+ endpoint's models. The global default-model picker lists each endpoint too.+- **Removing** goes through `delete_api_key` with the reference, which also+ clears the URL row and the registered models. A workflow still pointing at a+ removed endpoint fails with "not configured", never a call to OpenAI.+- **RLM** builds its own clients and cannot use an endpoint (or a local+ server); it refuses one with a clear message.## Provider Protocol@@ -250,7 +293,13 @@ At client creation, a stored `{provider}_proxy` URL takes precedence over thatconfigured compat URL. Plain OpenAI uses the SDK default endpoint unless`openai_proxy` is set. OpenRouter uses its adapter's built-in endpoint unless`openrouter_proxy` is set. Ollama and LM Studio rely on their stored proxy URL-at runtime so requests go to the selected local server.+at runtime so requests go to the selected local server; `openai_compatible`+has no configured URL at all, and the unifier refuses an endpoint whose URL row+is missing rather than let the SDK default to api.openai.com.++The `base_url` values in the dedicated `anthropic` and `gemini` blocks are REST+documentation, not SDK arguments (the Anthropic SDK appends `/v1` itself), so+nothing passes them to those SDKs.## Unified Native Execution Path@@ -378,8 +427,11 @@ AI providers support optional proxy-based authentication — requests route thro**How it works:**1. User configures a proxy URL in the Credentials Modal (e.g., `http://localhost:11434`).2. Requests route through the proxy instead of directly to the provider API.-3. Proxy handles authentication (token set to `"ollama"` automatically).-4. No API key storage needed in OpenCompany — auth delegated to proxy.+3. The stored key is sent as stored. A keyless server gets the placeholder its+ vendor documents (`auth.placeholder_key`); no provider rewrites a key, and an+ empty key never reaches an SDK (it would read `OPENAI_API_KEY` and send it to+ the proxy — RFC-0003 D7).+4. Auth can be delegated to the proxy; OpenCompany then stores no real key.**Configuration:** proxy URLs are stored in the credentials DB under the `{provider}_proxy` pattern (e.g., `anthropic_proxy`, `openai_proxy`). Falls back to direct API key if no proxy configured. This is the SAME mechanism the native Ollama / LM Studio path uses (see "Local LLM Providers" above) — the validator persists the user's server URL under `{provider}_proxy`, and at runtime it carries into `OpenAIProvider`'s `base_url`.@@ -460,7 +512,9 @@ the plugin folder or add a `visuals.json` entry (`"openrouterChatModel":3. **Credentials + agent exposure:**- Add a `Credential` subclass in `server/nodes/model/_credentials.py` — surfaces in the Credentials Modal automatically.- - To expose the provider in the **agent dropdown**, add its name to the `provider` Literal in `nodes/agent/ai_agent/__init__.py`, `nodes/agent/chat_agent/__init__.py`, AND `nodes/agent/_specialized.py`, and add the substring to `detect_ai_provider` in `server/constants.py` — otherwise an agent using it silently falls back to `'openai'`.+ - The **agent dropdown** picks it up with no edit: the `aiProviders` loader lists every registered provider. Add its substring to `detect_ai_provider` in `server/constants.py` for its chat-model node — otherwise that node silently falls back to `'openai'`.++A **server the user runs** is not a new provider: add it as a named endpoint in the Credentials Modal (see "Named OpenAI-compatible endpoints").### Key implementation filesdiff --git a/docs-internal/node-logic-flows/ai_agents/aiAgent.md b/docs-internal/node-logic-flows/ai_agents/aiAgent.mdindex 8b3567ba..79bf0e00 100644--- a/docs-internal/node-logic-flows/ai_agents/aiAgent.md+++ b/docs-internal/node-logic-flows/ai_agents/aiAgent.md@@ -38,7 +38,7 @@ Source: `AIAgentParams` in [`ai_agent/__init__.py`](../../../server/nodes/agent/| Name | Type | Default | Required | Group | Description ||------|------|---------|----------|-------|-------------|| `prompt` | string (textarea, rows 4) | `""` | no | - | User prompt; may reference upstream node outputs via templates. Empty -> auto-prompt fallback from `input-main`. |-| `provider` | Literal | `openai` | no | - | One of openai, anthropic, gemini, openrouter, xai, groq, cerebras, deepseek, kimi, mistral, ollama, lmstudio. |+| `provider` | string (`ProviderRef`) | `openai` | no | - | A provider reference: any registered provider id, or a saved named endpoint `openai_compatible:<slug>`. Options come from the `aiProviders` loader, so a new endpoint appears without a schema change; `nodes/agent/_provider.py` validates the value. || `model` | string | `""` | no | - | Model id; loaded dynamically from the provider. || `system_message` | string (rows 3) | `You are a helpful assistant` | no | - | System prompt prepended to the conversation. || `temperature` | number (optional) | `None` | no | options | 0-2, step 0.1. Unset falls through to `agent.default_temperature` in `llm_defaults.json`. |@@ -134,12 +134,12 @@ flowchart TDand potentially `compaction_starting` / `compaction_completed` events.`BaseNode.execute()` additionally wraps the body in a `node.aiAgent.execute`OpenTelemetry span + `log_context(node_id, node_type, workflow_id)`.-- **External API calls**: all 13 providers run through `ChatUnifier` and the- native provider layer: Anthropic uses `anthropic`, Gemini uses+- **External API calls**: every registered provider runs through `ChatUnifier`+ and the native provider layer: Anthropic uses `anthropic`, Gemini uses`google-genai`, and OpenAI plus the OpenAI-compatible providers (OpenRouter,- Groq, Cerebras, xAI, DeepSeek, Kimi, Mistral, Ollama, and LM Studio) use- `openai` with the configured endpoint. Tool nodes may spawn their own HTTP- or subprocess calls via `execute_tool`.+ Groq, Cerebras, xAI, DeepSeek, Kimi, Mistral, Sarvam, Ollama, LM Studio and+ named endpoints) use `openai` with the configured or saved endpoint. Tool+ nodes may spawn their own HTTP or subprocess calls via `execute_tool`.- **File I/O**: none in `execute_op`. Filesystem tool nodes may read/write theper-workflow workspace (`context.workspace_dir`).- **Subprocess**: none directly. Tool executors (shell, process manager,diff --git a/docs-internal/node-logic-flows/ai_agents/chatAgent.md b/docs-internal/node-logic-flows/ai_agents/chatAgent.mdindex ca773172..c1590124 100644--- a/docs-internal/node-logic-flows/ai_agents/chatAgent.md+++ b/docs-internal/node-logic-flows/ai_agents/chatAgent.md@@ -38,8 +38,9 @@ own plugin folder; there is no `functools.partial` wiring anymore.## Parameters`ChatAgentParams` mirrors [`aiAgent`](./aiAgent.md)'s `AIAgentParams`-(`provider` Literal, `model`, `prompt`, `system_message`, `temperature` /-`max_tokens` in the `options` group). Differences:+(`provider` as the loader-driven `ProviderRef`, `model`, `prompt`,+`system_message`, `temperature` / `max_tokens` in the `options` group).+Differences:- `prompt` default `""` (empty) — Zeenie relies on the auto-prompt fallbackwhen wired to a chat trigger (placeholder: "Optional: leave empty to usediff --git a/docs-internal/node-logic-flows/ai_chat_models/lmstudioChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/lmstudioChatModel.mdindex 3faa0af8..5f5cd8d1 100644--- a/docs-internal/node-logic-flows/ai_chat_models/lmstudioChatModel.md+++ b/docs-internal/node-logic-flows/ai_chat_models/lmstudioChatModel.md@@ -11,7 +11,7 @@## Purpose-Run local LLMs through LM Studio's OpenAI-compatible server (default `http://localhost:1234/v1`). The OpenAI-compatible spec registered in `services/llm/providers/_compat.py` routes it through `OpenAIProvider` with `base_url` from `llm_defaults.json` — same path as deepseek/kimi/mistral/ollama. The user's custom server URL is stored as the `lmstudio_proxy` credential. `LMStudioChatModelNode` uses the shared `ChatModelParams` unchanged. The `ChatModelBase.chat` operation calls `AIService.execute_chat`.+Run local LLMs through LM Studio's OpenAI-compatible server (default `http://localhost:1234/v1`). The OpenAI-compatible spec registered in `services/llm/providers/_compat.py` routes it through `OpenAIProvider` — same path as deepseek/kimi/mistral/ollama. The server URL the user saves under Credentials is rooted at save time (`http://localhost:1234` is stored as `http://localhost:1234/v1`, RFC-0003) and kept as the `lmstudio_proxy` credential; the unifier passes it as `proxy_url`, which wins over the `base_url` in `llm_defaults.json`. `LMStudioChatModelNode` uses the shared `ChatModelParams` unchanged. The `ChatModelBase.chat` operation calls `AIService.execute_chat`.## Inputs (handles)@@ -29,7 +29,7 @@ Run local LLMs through LM Studio's OpenAI-compatible server (default `http://loc| `temperature` | number\|null | `null` | no | - | 0-2 || `max_tokens` | number\|null | `null` | no | - | 1-200000; default per-loaded-model ctx ÷ 4 (capped 4096) || `top_p` | number\|null | `1.0` | no | - | |-| `api_key` | string\|null | `null` -> placeholder `"ollama"` | no | - | Optional; local servers usually run with no auth. `LMStudioCredential.resolve()` returns `"ollama"` when none stored |+| `api_key` | string\|null | `null` (injected) | no | - | Optional; local servers usually run with no auth. Without a stored key the declared placeholder is sent (`auth.placeholder_key` in `llm_defaults.json`: `"lm-studio"`, the value LM Studio's docs use) |(LM Studio uses the shared `ChatModelParams` unchanged; field names are snake_case, unknown keys ignored.)@@ -66,7 +66,7 @@ flowchart TDD -- no --> X[error envelope]D -- yes --> E[detect_ai_provider -> 'lmstudio']E --> F[Lookup lmstudio_proxy credential -> base_url override]- F --> G[ChatUnifier.chat -> registry.get_provider lmstudio -> OpenAIProvider<br/>base_url=user server, api_key='ollama']+ F --> G[ChatUnifier.chat -> registry.get_provider lmstudio -> OpenAIProvider<br/>base_url=resolved URL, key=stored key or placeholder]G --> H[provider.chat]H --> I[success envelope]G -- Exception --> X@@ -74,14 +74,14 @@ flowchart TD## Decision Logic-- **Validation**: empty prompt -> error envelope. `api_key` is never the blocker — `LMStudioCredential.resolve()` returns the placeholder `"ollama"` when no key is stored, so the central "API key required" check in `execute_chat` passes.+- **Validation**: empty prompt -> error envelope. Once the server is saved, `api_key` is never the blocker: saving stores the user's key or the declared placeholder (`"lm-studio"`) in the `lmstudio` row, so the central "API key required" check in `execute_chat` passes. `LMStudioCredential.resolve()` falls back to the same placeholder.- **Provider routing**: `detect_ai_provider` MUST list `lmstudio` (in `server/constants.py`) or the node falls through to `'openai'` and `execute_chat` hits api.openai.com with the placeholder key.-- **Open-world model name**: `is_model_valid_for_provider` returns `True` for `lmstudio` so local model names are not rejected by the cloud-style pattern check.-- **Base URL routing**: `lmstudio_proxy` credential carries the user's server URL into `OpenAIProvider.base_url`; traffic stays on `localhost`.+- **Open-world model name**: `lmstudio` declares `open_world_models: true` in `llm_defaults.json`, so `is_model_valid_for_provider` does not reject local model names with the cloud-style pattern check.+- **Base URL routing**: the `lmstudio_proxy` credential carries the resolved server URL into the client; nothing is probed at call time, and traffic stays on `localhost`.## Side Effects-- **Database writes**: per-model context params persist in `EncryptedAPIKey.models["model_params"]` and `model_registry.json` at credential-validation time (via `_local_validator.py` + `model_registry.register_local_model()`), not on the bare chat path.+- **Database writes**: per-model context params persist in `EncryptedAPIKey.models["model_params"]` and in `DATA_DIR/local_models.json` at save time (via `_local_validator.save_llm_server` + `ModelRegistryService.register_local_model()`), never in the tracked `config/model_registry.json`, and not on the bare chat path.- **Broadcasts**: none on the bare chat path.- **External API calls**: `POST {user_server}/v1/chat/completions` via the `openai` SDK with overridden `base_url` (default `http://localhost:1234/v1`).- **File I/O**: none.@@ -90,14 +90,16 @@ flowchart TD## External Dependencies- **Credentials**: optional `auth_service.get_api_key('lmstudio')`; user server URL stored as `lmstudio_proxy`.-- **Services**: `services/llm/providers/openai.py` (reused with LM Studio base_url); `nodes/model/_local_validator.py` (SDK probe via `lmstudio.AsyncClient.llm.list_loaded()`).+- **Services**: `services/llm/providers/openai.py` (reused with LM Studio base_url); `services/llm/endpoints.py` (roots the URL at save time); `nodes/model/_local_validator.py` (the save path; SDK probe via `lmstudio.AsyncClient.llm.list_loaded()`).- **Python packages**: `openai`, `lmstudio>=1.5.0` (validation only).- **Environment variables**: none.## Edge cases & known limits-- **Server must be running with a model loaded**: LM Studio reports loaded models via `list_loaded()`; if nothing is loaded the probe returns no models.-- **Provider routing dependency**: `lmstudio` must be present in `detect_ai_provider` AND in each agent's `provider` Literal, or the node silently falls back to OpenAI cloud.+- **Server must be running with a model loaded**: LM Studio reports loaded models via `list_loaded()`; if nothing is loaded the probe returns no models and the save writes nothing.+- **Saving checks the URL first**: LM Studio answers HTTP 200 even to routes it does not serve, so a URL saved without `/v1` used to validate and then fail every run with an empty response (RFC-0003 §2.1). The URL entered is now tried as given, then with `/v1` appended, and adopted only where `GET /models` returns an OpenAI list; a failed save writes nothing and keeps the previous server.+- **API token**: LM Studio can require an API token, but its Credentials panel has only the Base URL field, so a token-protected server cannot be used yet.+- **Provider routing dependency**: `lmstudio` must be present in `detect_ai_provider`, or the node silently falls back to OpenAI cloud. Agents need no edit: their `provider` field lists every registered provider through the `aiProviders` loader.- **Max output default**: ctx ÷ 4, capped at 4096, unless the user overrides `max_tokens`. Typed `LlmInstanceInfo.context_length` drives this.- **Error boundary**: typed OpenAI SDK connection/API failures become user-safe `NodeUserError` values in `ChatUnifier` and are re-raised to `BaseNode.execute()`, which produces the standard failure envelope. Unexpected failures are logged and returned by `execute_chat`.diff --git a/docs-internal/node-logic-flows/ai_chat_models/ollamaChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/ollamaChatModel.mdindex 34bd066f..6515ca2e 100644--- a/docs-internal/node-logic-flows/ai_chat_models/ollamaChatModel.md+++ b/docs-internal/node-logic-flows/ai_chat_models/ollamaChatModel.md@@ -11,7 +11,7 @@## Purpose-Run local LLMs (llama, mistral, qwen, deepseek-r1, ...) through a locally-running Ollama server. Ollama exposes an OpenAI-shaped `/v1` endpoint, so the OpenAI-compatible spec registered in `services/llm/providers/_compat.py` hands it to `OpenAIProvider` with `base_url` from `llm_defaults.json` — same path as deepseek/kimi/mistral. The user's custom server URL (if not localhost) is stored as the `ollama_proxy` credential and flows through the same `proxy_url` parameter cloud providers already use for Ollama-style auth delegation. `OllamaChatModelNode` uses the shared `ChatModelParams` unchanged. The `ChatModelBase.chat` operation calls `AIService.execute_chat`.+Run local LLMs (llama, mistral, qwen, deepseek-r1, ...) through a locally-running Ollama server. Ollama exposes an OpenAI-shaped `/v1` endpoint, so the OpenAI-compatible spec registered in `services/llm/providers/_compat.py` hands it to `OpenAIProvider` — same path as deepseek/kimi/mistral. The server URL the user saves under Credentials is rooted at save time (`http://localhost:11434` is stored as `http://localhost:11434/v1`, RFC-0003) and kept as the `ollama_proxy` credential; the unifier passes it as `proxy_url`, which wins over the `base_url` in `llm_defaults.json`. `OllamaChatModelNode` uses the shared `ChatModelParams` unchanged. The `ChatModelBase.chat` operation calls `AIService.execute_chat`.## Inputs (handles)@@ -29,7 +29,7 @@ Run local LLMs (llama, mistral, qwen, deepseek-r1, ...) through a locally-runnin| `temperature` | number\|null | `null` | no | - | 0-2 || `max_tokens` | number\|null | `null` | no | - | 1-200000; default per-loaded-model ctx ÷ 4 (capped 4096) || `top_p` | number\|null | `1.0` | no | - | |-| `api_key` | string\|null | `null` -> placeholder `"ollama"` | no | - | Optional; local servers usually run with no auth. `OllamaCredential.resolve()` returns `"ollama"` when none stored |+| `api_key` | string\|null | `null` (injected) | no | - | Optional; local servers usually run with no auth. Without a stored key the declared placeholder is sent (`auth.placeholder_key` in `llm_defaults.json`: `"ollama"`, the value Ollama's docs use) |(Ollama uses the shared `ChatModelParams` unchanged; field names are snake_case, unknown keys ignored.)@@ -66,7 +66,7 @@ flowchart TDD -- no --> X[error envelope]D -- yes --> E[detect_ai_provider -> 'ollama']E --> F[Lookup ollama_proxy credential -> base_url override]- F --> G[ChatUnifier.chat -> registry.get_provider ollama -> OpenAIProvider<br/>base_url=user server, api_key='ollama']+ F --> G[ChatUnifier.chat -> registry.get_provider ollama -> OpenAIProvider<br/>base_url=resolved URL, key=stored key or placeholder]G --> H[provider.chat]H --> I[success envelope]G -- Exception --> X@@ -74,15 +74,15 @@ flowchart TD## Decision Logic-- **Validation**: empty prompt -> error envelope. `api_key` is never the blocker — `OllamaCredential.resolve()` returns the placeholder `"ollama"` when no key is stored, so the central "API key required" check in `execute_chat` passes.+- **Validation**: empty prompt -> error envelope. Once the server is saved, `api_key` is never the blocker: saving stores the user's key or the declared placeholder (`"ollama"`) in the `ollama` row, so the central "API key required" check in `execute_chat` passes. `OllamaCredential.resolve()` falls back to the same placeholder.- **Provider routing**: `detect_ai_provider` MUST list `ollama` (in `server/constants.py`) or the node falls through to `'openai'` and `execute_chat` hits api.openai.com with the placeholder key.-- **Open-world model name**: `is_model_valid_for_provider` returns `True` for `ollama` so local model names like `qwen/qwen3.6-27b` are not rejected by the cloud-style pattern check.-- **Base URL routing**: `ollama_proxy` credential carries the user's server URL into `OpenAIProvider.base_url`; traffic stays on `localhost`.+- **Open-world model name**: `ollama` declares `open_world_models: true` in `llm_defaults.json`, so `is_model_valid_for_provider` does not reject local model names like `qwen/qwen3.6-27b` with the cloud-style pattern check.+- **Base URL routing**: the `ollama_proxy` credential carries the resolved server URL into the client; nothing is probed at call time, and traffic stays on `localhost`.- **No thinking knob**: the shared `thinking_enabled` field is present but generic Ollama has no per-call thinking parameter; reasoning is per-model.## Side Effects-- **Database writes**: per-model context params persist in `EncryptedAPIKey.models["model_params"]` and `model_registry.json` at credential-validation time (via `_local_validator.py` + `model_registry.register_local_model()`), not on the bare chat path.+- **Database writes**: per-model context params persist in `EncryptedAPIKey.models["model_params"]` and in `DATA_DIR/local_models.json` at save time (via `_local_validator.save_llm_server` + `ModelRegistryService.register_local_model()`), never in the tracked `config/model_registry.json`, and not on the bare chat path.- **Broadcasts**: none on the bare chat path.- **External API calls**: `POST {user_server}/v1/chat/completions` via the `openai` SDK with overridden `base_url` (default `http://localhost:11434/v1`).- **File I/O**: none.@@ -91,16 +91,17 @@ flowchart TD## External Dependencies- **Credentials**: optional `auth_service.get_api_key('ollama')`; user server URL stored as `ollama_proxy`.-- **Services**: `services/llm/providers/openai.py` (reused with Ollama base_url); `nodes/model/_local_validator.py` (SDK probe via `ollama.AsyncClient.ps()`).+- **Services**: `services/llm/providers/openai.py` (reused with Ollama base_url); `services/llm/endpoints.py` (roots the URL at save time); `nodes/model/_local_validator.py` (the save path; SDK probe via `ollama.AsyncClient.ps()`).- **Python packages**: `openai`, `ollama>=0.6.0` (validation only).- **Environment variables**: none.## Edge cases & known limits- **Server must be running**: requests go to the user's local Ollama server; if it is down the request surfaces as a connection error in the envelope.-- **Provider routing dependency**: `ollama` must be present in `detect_ai_provider` AND in each agent's `provider` Literal, or the node silently falls back to OpenAI cloud.+- **Saving checks the URL first**: the URL entered is tried as given, then with `/v1` appended, and adopted only where `GET /models` returns an OpenAI list. A save that finds no such list, or no loaded model, writes nothing and keeps the previous server.+- **Provider routing dependency**: `ollama` must be present in `detect_ai_provider`, or the node silently falls back to OpenAI cloud. Agents need no edit: their `provider` field lists every registered provider through the `aiProviders` loader.- **Max output default**: ctx ÷ 4, capped at 4096, unless the user overrides `max_tokens`.-- **Per-model params survive restart**: written through to `model_registry.json` so context length is known without re-clicking Fetch.+- **Per-model params survive restart**: written through to `DATA_DIR/local_models.json`, which an OpenRouter refresh does not touch, so context length is known without re-clicking Fetch.- **Error boundary**: typed OpenAI SDK connection/API failures become user-safe `NodeUserError` values in `ChatUnifier` and are re-raised to `BaseNode.execute()`, which produces the standard failure envelope. Unexpected failures are logged and returned by `execute_chat`.## Relateddiff --git a/docs-internal/node-logic-flows/specialized_agents/_pattern.md b/docs-internal/node-logic-flows/specialized_agents/_pattern.mdindex 7b398d0a..0e24d80b 100644--- a/docs-internal/node-logic-flows/specialized_agents/_pattern.md+++ b/docs-internal/node-logic-flows/specialized_agents/_pattern.md@@ -72,7 +72,7 @@ There are **no** per-agent parameter extras: `orchestrator_agent` and| Name | Type | Default | Required | displayOptions.show | Description ||------|------|---------|----------|---------------------|-------------|| `prompt` | string | `""` | no | - | User prompt; falls back to upstream output when empty (4 rows) |-| `provider` | enum | `openai` | no | - | `openai` / `anthropic` / `gemini` / `openrouter` / `xai` / `groq` / `cerebras` / `deepseek` / `kimi` / `mistral` / `ollama` / `lmstudio` |+| `provider` | string (`ProviderRef`) | `openai` | no | - | Any registered provider id, or a saved named endpoint `openai_compatible:<slug>`; options come from the `aiProviders` loader || `model` | string | `""` | no | - | Model ID (resolved against the provider; empty falls through to default) || `system_message` | string\|null | `"You are a helpful assistant"` | no | - | System instructions (3 rows) || `temperature` | float\|null | `None` | no | group `options` | 0.0-2.0; `None` -> `agent.default_temperature` in `llm_defaults.json` |diff --git a/docs-internal/node-logic-flows/specialized_agents/rlm_agent.md b/docs-internal/node-logic-flows/specialized_agents/rlm_agent.mdindex f22ca351..6bdebce4 100644--- a/docs-internal/node-logic-flows/specialized_agents/rlm_agent.md+++ b/docs-internal/node-logic-flows/specialized_agents/rlm_agent.md@@ -31,7 +31,7 @@ params; REPL iteration bounding lives inside `RLMService` /| Name | Type | Default | Required | displayOptions.show | Description ||------|------|---------|----------|---------------------|-------------|| `prompt` | string | `""` | no | - | Reasoning task; falls back to upstream input |-| `provider` | enum | `openai` | no | - | Big-LM provider |+| `provider` | string (`ProviderRef`) | `openai` | no | - | Big-LM provider. RLM builds its own clients and ignores user base URLs, so only `openai`, `anthropic`, `gemini`, `groq`, `openrouter` and `cerebras` run; any other provider, including Ollama, LM Studio and named endpoints, is refused at run time || `model` | string | `""` | no | - | Big-LM model ID || `system_message` | string\|null | `"You are a helpful assistant"` | no | - | System instructions || `temperature` | float\|null | `None` | no | group `options` | 0.0-2.0 |diff --git a/server/nodes/README.md b/server/nodes/README.mdindex 40621ac2..2caa07be 100644--- a/server/nodes/README.md+++ b/server/nodes/README.md@@ -112,7 +112,8 @@ Match the palette group. Current folders (seeagent/ — AI agents (ai_agent, chat_agent + specialized/variant folders incl. 2 team leads,CLI agents (claude_code, codex, rlm) and Vertex agents; SSOT: AI_AGENT_TYPESin server/constants.py + the folder glob)-model/ — LLM chat models (openai, anthropic, gemini, …)+model/ — LLM chat models (openai, anthropic, gemini, …, and openai_compatible for+ a user-named endpoint); also owns the LLM provider dropdown loadersandroid/ — Android device servicesgoogle/ — Google Workspace (gmail / calendar / drive / sheets / …)twitter/ — Twitter/X (send / search / user / receive)@@ -172,7 +173,7 @@ these first before writing new code:|---|---|---|| `agent/` | `_inline.prepare_agent_call` | One-shot pre-dispatch for every agent (memory + skill + tool + teammate collection) || `agent/` | `_specialized.SpecializedAgentBase` | Base for 13 specialized agents |-| `model/` | `_base.ChatModelBase` | 12 chat models inherit → same `@Operation("chat")` body that calls `ai_service.execute_chat` |+| `model/` | `_base.ChatModelBase` | 13 chat models inherit → same `@Operation("chat")` body that calls `ai_service.execute_chat` || `speech/` + `translate/` | `_config` / `_registry` / `_unifier` / `_providers/` | The multi-vendor shape. Capability data is JSON (`services/plugin/capabilities.CapabilityConfig`), registration is `services/provider_registry`, and each `_providers/<vendor>.py` owns that vendor's auth scheme, request transport and response shape || `android/` | `_base.AndroidServiceBase` | 16 Android services inherit; payload translation + `SERVICE_ID_MAP` lives on this base || `android/` | `_base.execute_android_service_tool` | AI-tool dispatcher — called from `services/handlers/tools.py` for direct service tools (the `androidTool` aggregator + `execute_android_toolkit` were retired) |@@ -215,7 +216,7 @@ from ._credentials import TwitterCredential # shared with 3 sibling| `nodes/telegram/` | `TelegramCredential` (bot token + owner chat id) | telegram_send / _receive || `nodes/discord/` | `DiscordBotCredential` (bot token; overrides `inject()` because Discord uses `Bot <token>`, not the inherited `Bearer `) + `DiscordUserCredential` (OAuth2 user context, separate id so connecting a user never overwrites the bot) | discord_send / _action / _receive / _interaction || `nodes/scraper/` | `ApifyCredential` (Bearer, SDK probe) + `TikHubCredential` (Bearer, declarative httpx probe against `tikhub/user/get_user_info` — kept SDK-free so the modal validates even if the `tikhub` import fails) | apify_actor / tikhub_action |-| `nodes/model/` | 13 LLM credential classes: 11 cloud (`OpenAI / Anthropic / Gemini / OpenRouter / Groq / Cerebras / DeepSeek / Kimi / Mistral / xAI / Sarvam`) plus Ollama / LM Studio | 12 chat models (xAI has no standalone chat-model node) **plus the 5 `nodes/sarvam/` service nodes**, which import `SarvamCredential` from here — one stored key serves Sarvam's OpenAI-compatible chat endpoint *and* its `api-subscription-key` REST APIs |+| `nodes/model/` | 14 LLM credential classes: 11 cloud (`OpenAI / Anthropic / Gemini / OpenRouter / Groq / Cerebras / DeepSeek / Kimi / Mistral / xAI / Sarvam`), Ollama / LM Studio, and `OpenAICompatibleCredential` (any number of named endpoints, RFC-0003) | 13 chat models (xAI has no standalone chat-model node) **plus the `nodes/speech/` and `nodes/translate/` Sarvam providers**, which import `SarvamCredential` from here — one stored key serves Sarvam's OpenAI-compatible chat endpoint *and* its `api-subscription-key` REST APIs || `nodes/search/` | `BraveSearch / Serper / Perplexity` inlined in each plugin file | single-use per plugin |Declare inline only when genuinely single-use (see