Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: front SGLang Qwen3.8-27B as a Hopper/Blackwell local runtime for CoS agents (#4776)
[._.]/ Adam Eivy5eccb5334300
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsxindex 38ad1e61be..c174bae7e4 100644--- a/client/src/components/providers/ProviderCard.jsx+++ b/client/src/components/providers/ProviderCard.jsx@@ -130,6 +130,11 @@ export default function ProviderCard({vLLM / DFLASH2</span>)}+ {provider.sglangBacked && (+ <span className="text-xs px-2 py-0.5 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">+ SGLANG+ </span>+ )}{provider.mtplxBacked && (<span className="text-xs px-2 py-0.5 rounded bg-blue-500/20 text-blue-300 border border-blue-500/30">MTPLX@@ -302,6 +307,11 @@ export default function ProviderCard({Local vLLM container (endpoint: <code className="text-emerald-200">{provider.endpoint}</code>) — Qwen3.8-27B with DFlash 2 drafting. It holds the whole GPU, so stop it before running local image/video generation.</p>)}+ {provider.sglangBacked && (+ <p className="text-xs text-amber-300/90">+ Local SGLang container (endpoint: <code className="text-amber-200">{provider.endpoint}</code>) — Qwen3.8-27B on a Hopper or Blackwell card. It holds the whole GPU, so stop it before running local image/video generation.+ </p>+ )}{isProcessProvider(provider) && (<p className="break-words">Command: <code className="text-gray-300 break-all">{provider.command} {provider.args?.join(' ')}</code></p>)}diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex 90c7adbaae..0b01eb7a06 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -611,6 +611,11 @@ export default function AIProviders() {vLLM / DFLASH2</span>)}+ {provider.sglangBacked && (+ <span className="text-xs px-2 py-0.5 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">+ SGLANG+ </span>+ )}{provider.mtplxBacked && (<span className="text-xs px-2 py-0.5 rounded bg-blue-500/20 text-blue-300 border border-blue-500/30">MTPLX@@ -1213,11 +1218,15 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders/></FormField>- {/* The one CLI/TUI backend that authenticates: the vLLM compose+ {/* The CLI/TUI backends that can authenticate: the vLLM composestack is started with VLLM_API_KEY, so without this fieldthere is nowhere to put it and the container 401s everymodel refresh and every run. Reads `capabilityProvider`- because `vllmBacked` is a stored marker, not a form field. */}+ because `vllmBacked` is a stored marker, not a form field.+ SGLang has its own field below — its key is OPTIONAL (only+ set when the operator ran `--api-key`), so the two cannot+ share one placeholder without telling half the operators to+ paste a secret that does not exist. */}{capabilityProvider?.vllmBacked && (<FormField label="API Key"><input@@ -1234,6 +1243,23 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders</FormField>)}+ {capabilityProvider?.sglangBacked && (+ <FormField label="API Key (optional)">+ <input+ type="password"+ value={formData.apiKey}+ onChange={(e) => setFormData(prev => ({ ...prev, apiKey: e.target.value }))}+ placeholder={provider?.hasApiKey ? 'Key set — leave blank to keep' : 'Only if you started SGLang with --api-key'}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"+ />+ <p className="text-xs text-gray-500 mt-1">+ SGLang serves unauthenticated unless you started it with <code>--api-key</code>. Leave this+ blank in that case — PortOS attaches a key only when one is set, on both the spawned OpenCode+ provider and the model-refresh probe.+ </p>+ </FormField>+ )}+{formData.type === 'cli' && (<FormField label="Headless Args (for simple prompt tasks)"><inputdiff --git a/client/src/utils/providers.js b/client/src/utils/providers.jsindex 8b158cc4e2..6324d2c448 100644--- a/client/src/utils/providers.js+++ b/client/src/utils/providers.js@@ -223,6 +223,7 @@ export const isOpencodeLocalProvider = (provider) =>|| provider?.mtplxBacked === true|| provider?.llamaBacked === true|| provider?.vllmBacked === true+ || provider?.sglangBacked === true|| provider?.orcarouterBacked === true);/**@@ -573,7 +574,7 @@ export const isToolUseModel = (id) =>* @returns {{toolCapable:boolean}|null}*/export const localToolUseHint = (id, provider, toolUseIdsByProvider = null) =>- (localBackendForProvider(provider) || isOllamaBackedProvider(provider) || provider?.mtplxBacked === true || provider?.llamaBacked === true || provider?.vllmBacked === true)+ (localBackendForProvider(provider) || isOllamaBackedProvider(provider) || provider?.mtplxBacked === true || provider?.llamaBacked === true || provider?.vllmBacked === true || provider?.sglangBacked === true)&& typeof id === 'string' && id.length > 0? { toolCapable: toolUseIdsByProvider?.[provider?.id]?.has(id) === true || isToolUseModel(id) }: null;@@ -1020,7 +1021,10 @@ export const generationControlsFor = (provider) => {const local = isOllamaBackedProvider(provider)|| provider?.llamaBacked === true|| provider?.mtplxBacked === true- || provider?.vllmBacked === true;+ || provider?.vllmBacked === true+ // SGLang takes the same `chat_template_kwargs.enable_thinking` as the other+ // local OpenAI endpoints — see THINKING_STYLE.sglang on the server.+ || provider?.sglangBacked === true;if (!local && !orcarouter) return null;if (commandBasename(provider?.command) === 'claude') {return { temperature: false, topP: false, thinking: true };diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.jsindex 49c944850f..3d30a152ba 100644--- a/client/src/utils/providers.test.js+++ b/client/src/utils/providers.test.js@@ -129,6 +129,7 @@ describe('effortLevelsForProvider (server mirror)', () => {['OpenCode llama TUI', { id: 'opencode-llama-tui', command: 'opencode', llamaBacked: true }, ['low', 'medium', 'high']],['OpenCode MTPLX', { id: 'opencode-mtplx', command: 'opencode', mtplxBacked: true }, ['low', 'medium', 'high']],['OpenCode vLLM TUI', { id: 'opencode-vllm-tui', command: 'opencode', vllmBacked: true }, ['low', 'medium', 'high']],+ ['OpenCode SGLang TUI', { id: 'opencode-sglang-tui', command: 'opencode', sglangBacked: true }, ['low', 'medium', 'high']],['OpenCode with no local backend', { id: 'opencode', command: 'opencode' }, null],['grok (no effort control)', { id: 'grok-cli', command: 'grok' }, null],['blank command is not claude', { id: 'ollama' }, null],@@ -154,6 +155,9 @@ describe('generationControlsFor', () => {// hid the whole block while the server discarded every control anyway// (#4765).['OpenCode vLLM TUI', { id: 'opencode-vllm-tui', command: 'opencode', vllmBacked: true }, { temperature: true, topP: true, thinking: true }],+ // SGLang takes the same chat-template thinking toggle, and shipped with the+ // controls wired from day one so it never repeated vLLM's hole.+ ['OpenCode SGLang TUI', { id: 'opencode-sglang-tui', command: 'opencode', sglangBacked: true }, { temperature: true, topP: true, thinking: true }],// A Claude harness on Ollama is forwarded only MAX_THINKING_TOKENS// (server/lib/cliChildEnv.js) — it owns its own sampling.['Claude Ollama TUI', { id: 'claude-ollama-tui', command: 'claude', ollamaBacked: true }, { temperature: false, topP: false, thinking: true }],@@ -936,6 +940,7 @@ describe('supportsModelRefresh', () => {'opencode-llama-tui','opencode-mtplx', 'opencode-mtplx-tui', 'opencode-ollama','opencode-ollama-tui', 'opencode-orcarouter', 'opencode-orcarouter-tui',+ 'opencode-sglang', 'opencode-sglang-tui','opencode-vllm', 'opencode-vllm-tui','orcarouter',]);diff --git a/data.reference/providers.json b/data.reference/providers.jsonindex 63a9ed0c9a..c937bbb43e 100644--- a/data.reference/providers.json+++ b/data.reference/providers.json@@ -288,6 +288,45 @@"tuiPromptDelayMs": 2500,"tuiIdleTimeoutMs": 180000},+ "opencode-sglang": {+ "id": "opencode-sglang",+ "name": "OpenCode SGLang (Qwen3.8-27B)",+ "type": "cli",+ "command": "opencode",+ "args": ["run"],+ "endpoint": "http://127.0.0.1:18021/v1",+ "apiKey": "",+ "models": ["qwen3.8-27b"],+ "defaultModel": "qwen3.8-27b",+ "sglangBacked": true,+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"sglang\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"SGLang Qwen3.8-27B (local)\",\"options\":{\"baseURL\":\"http://127.0.0.1:18021/v1\"}}}}"+ },+ "secretEnvVars": [],+ "headlessArgs": []+ },+ "opencode-sglang-tui": {+ "id": "opencode-sglang-tui",+ "name": "OpenCode SGLang TUI (Qwen3.8-27B)",+ "type": "tui",+ "command": "opencode",+ "args": [],+ "endpoint": "http://127.0.0.1:18021/v1",+ "apiKey": "",+ "models": ["qwen3.8-27b"],+ "defaultModel": "qwen3.8-27b",+ "sglangBacked": true,+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"sglang\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"SGLang Qwen3.8-27B (local)\",\"options\":{\"baseURL\":\"http://127.0.0.1:18021/v1\"}}}}"+ },+ "secretEnvVars": [],+ "tuiPromptDelayMs": 2500,+ "tuiIdleTimeoutMs": 180000+ },"orcarouter": {"id": "orcarouter","name": "OrcaRouter",diff --git a/docs/PORTS.md b/docs/PORTS.mdindex 42f5aea231..fa4505e51a 100644--- a/docs/PORTS.md+++ b/docs/PORTS.md@@ -37,6 +37,7 @@ Common port labels:| 5568 | portos-llama-server | - | Loopback llama.cpp speculative-decoding server. Optional PM2 process, started/stopped from Models → LLMs. || 8000 | portos-mtplx | - | Loopback MTPLX OpenAI-compatible API (upstream's own default, kept so the shipped provider presets match). Optional PM2 process, started/stopped from Models → LLMs. See [features/mtplx.md](./features/mtplx.md). || 18020 | vLLM (Docker) | - | Loopback vLLM Qwen3.8-27B / DFlash 2 container on an RTX 3090 host. Operator-started (`docker compose --profile single up -d`) — PortOS never brings it up on boot. See [features/qwen38-rtx3090.md](./features/qwen38-rtx3090.md). |+| 18021 | SGLang (Docker) | - | Loopback SGLang Qwen3.8-27B container on a Hopper/Blackwell host. Operator-started (`docker compose up -d`) — PortOS never brings it up on boot. See [features/sglang-qwen38.md](./features/sglang-qwen38.md). |## How `:5555`, `:5553`, and `:5554` Relate@@ -131,7 +132,9 @@ PortOS automatically detects ports from env vars:PostgreSQL in native mode listens on the system default `:5432`, outside these ranges. Two third-partylocal runtimes also sit outside them, each on its own upstream default so an unmodified install worksagainst PortOS without editing anything: MTPLX on `:8000` and the vLLM Qwen3.8-27B container on-`:18020` (`syv-ai/qwen38-27b-rtx3090`'s own compose file).+`:18020` (`syv-ai/qwen38-27b-rtx3090`'s own compose file). The SGLang Qwen3.8-27B container sits+next to it on `:18021` — that port is PortOS's own choice rather than an upstream default, since+SGLang publishes an image but no compose project (its own default is `:30000`).## Viewing Port Usagediff --git a/docs/README.md b/docs/README.mdindex 0a70db0823..86e17b7ed4 100644--- a/docs/README.md+++ b/docs/README.md@@ -34,7 +34,7 @@ Start with the [product surface map](./features/product-surfaces.md) for a complApp management: [app-wizard](./features/app-wizard.md) · [autofixer](./features/autofixer.md) · [browser](./features/browser.md) · [error-handling](./features/error-handling.md) · [jira-sprint-manager](./features/jira-sprint-manager.md)-Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [agent-context](./features/agent-context.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [mtplx](./features/mtplx.md) · [dflash2](./features/dflash2.md) ([DSpark vs DFlash 2](./research/2026-08-19-dspark-vs-dflash2.md)) · [qwen38-rtx3090](./features/qwen38-rtx3090.md) ([3090 bring-up](./research/2026-08-21-qwen38-rtx3090-vllm.md), [SGLang Hopper/Blackwell evaluation](./research/2026-08-21-sglang-qwen38-27b.md)) · [prompt-manager](./features/prompt-manager.md)+Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [agent-context](./features/agent-context.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [mtplx](./features/mtplx.md) · [dflash2](./features/dflash2.md) ([DSpark vs DFlash 2](./research/2026-08-19-dspark-vs-dflash2.md)) · [qwen38-rtx3090](./features/qwen38-rtx3090.md) ([3090 bring-up](./research/2026-08-21-qwen38-rtx3090-vllm.md)) · [sglang-qwen38](./features/sglang-qwen38.md) ([SGLang Hopper/Blackwell evaluation](./research/2026-08-21-sglang-qwen38-27b.md)) · [prompt-manager](./features/prompt-manager.md)Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system](./features/identity-system.md) · [soul-system](./features/soul-system.md) · [privacy-center](./features/privacy-center.md) · [post](./features/post.md) (insights design spike: [plans/2026-06-03](./plans/2026-06-03-cross-domain-insights-engine.md))diff --git a/docs/features/dflash2.md b/docs/features/dflash2.mdindex 1552803479..42c55950c3 100644--- a/docs/features/dflash2.md+++ b/docs/features/dflash2.md@@ -8,7 +8,7 @@ PortOS integrates both through the **OpenCode llama TUI** provider preset and th> **Which one to run:** `--spec-type draft-dspark` **merged into llama.cpp on 2026-07-28** ([#25173](https://github.com/ggml-org/llama.cpp/pull/25173)) and works on a stock `brew install llama.cpp`. DFlash 2's engine modules are **still an open PR** ([#27342](https://github.com/ggml-org/llama.cpp/pull/27342)) and need a from-source build of that branch. llama.cpp falls back **silently** on a spec-type/drafter mismatch rather than erroring, so a DFlash 2 drafter on a stock build degrades quietly. Start with DSpark unless you have built the DFlash 2 branch. Full comparison: [DSpark vs DFlash 2](../research/2026-08-19-dspark-vs-dflash2.md).-> **On an NVIDIA RTX 3090?** There is a shorter path than building llama.cpp from a branch. Upstream froze a working DFlash 2 setup for that exact card — patched vLLM 0.27.1 plus a requantized Qwen3.8-27B, shipped as a Docker compose project — and PortOS fronts it with its own OpenCode presets. You get DFlash 2 drafting and prefix caching without vendoring an unmerged engine patch, at the cost of the container holding the whole 24 GB card. See [vLLM Qwen3.8-27B on an RTX 3090](./qwen38-rtx3090.md). It is CUDA-only: Apple Silicon stays on DSpark or [MTPLX](./mtplx.md).+> **On an NVIDIA RTX 3090?** There is a shorter path than building llama.cpp from a branch. Upstream froze a working DFlash 2 setup for that exact card — patched vLLM 0.27.1 plus a requantized Qwen3.8-27B, shipped as a Docker compose project — and PortOS fronts it with its own OpenCode presets. You get DFlash 2 drafting and prefix caching without vendoring an unmerged engine patch, at the cost of the container holding the whole 24 GB card. See [vLLM Qwen3.8-27B on an RTX 3090](./qwen38-rtx3090.md). It is CUDA-only: Apple Silicon stays on DSpark or [MTPLX](./mtplx.md). On a **Hopper or Blackwell** card there is a third path — [SGLang Qwen3.8-27B](./sglang-qwen38.md), an official image with no speculative overlay by default (DFlash 2 there needs an SGLang newer than the pinned tag).---diff --git a/docs/features/qwen38-rtx3090.md b/docs/features/qwen38-rtx3090.mdindex 79431d022c..2445d81cb7 100644--- a/docs/features/qwen38-rtx3090.md+++ b/docs/features/qwen38-rtx3090.md@@ -309,8 +309,10 @@ one-shot completion.building it.- [The 3090 bring-up record](../research/2026-08-21-qwen38-rtx3090-vllm.md) — themeasurements behind the numbers above, and how each required setting was found.-- [SGLang Qwen3.8-27B on Hopper / Blackwell](../research/2026-08-21-sglang-qwen38-27b.md) —- why this 3090 container is **not** replaced by the official SGLang recipes- (no 3090 cell; different tool-parser spelling; Claude Code is available there- via native Anthropic `/v1/messages`). Follow-up issues: #4776, #4777, #4778.+- [SGLang Qwen3.8-27B](./sglang-qwen38.md) — the Hopper / Blackwell path that+ shipped from that evaluation. It does **not** replace this container: the+ SGLang cookbook publishes no 3090 cell, so Ampere 24 GB stays here. The two+ also spell the tool-call parser differently (`qwen3_xml` here,+ `qwen3_coder` there), which fails silently if crossed. Background:+ [the evaluation note](../research/2026-08-21-sglang-qwen38-27b.md).- [docs/PORTS.md](../PORTS.md) — why `:18020` sits outside the 5553–5569 range.diff --git a/docs/features/sglang-qwen38.md b/docs/features/sglang-qwen38.mdnew file mode 100644index 0000000000..db6d3a8b12--- /dev/null+++ b/docs/features/sglang-qwen38.md@@ -0,0 +1,193 @@+# SGLang Qwen3.8-27B (Hopper / Blackwell)++The third CUDA path for CoS agents, alongside the Ampere-only+[vLLM container](./qwen38-rtx3090.md) and the Apple Silicon+[MTPLX](./mtplx.md) / [DSpark](./dflash2.md) runtimes. It serves Qwen3.8-27B from+SGLang's official `lmsysorg/sglang:qwen38-27b` image on `127.0.0.1:18021`, behind+two disabled-by-default OpenCode wrappers.++**PortOS never starts this container, never pulls the image, and never downloads+the weights.** It holds the whole GPU, so local image/video generation cannot run+while it is up — see [GPU exclusivity](#gpu-exclusivity) below.++Investigation record: [2026-08-21 SGLang Qwen3.8-27B](../research/2026-08-21-sglang-qwen38-27b.md).++## Which card++| Detected card | Path |+| --- | --- |+| SM90 Hopper (H200 / H100) | **This recipe** — FP8, FlashInfer, 32k prefill chunks. The cookbook-verified cell. |+| Blackwell 96 GB (RTX PRO 6000) | This recipe's `rtx6000` cell — NVFP4, engine-default prefill sizing. |+| Blackwell 32 GB (RTX 5090) | This recipe's `rtx5090` cell — NVFP4, `--max-running-requests 1`. |+| Ampere 24 GB (RTX 3090) | **Not this.** The cookbook publishes no 3090 cell; that card stays on [vLLM](./qwen38-rtx3090.md). |+| Apple Silicon | **Not this.** Use [MTPLX](./mtplx.md) or [llama.cpp / DSpark](./dflash2.md). |+| `nvidia-smi` wouldn't answer | PortOS says the probe failed. It does **not** claim you have no GPU. |++The gate is `sglangCellForGpu` / `sglangUnsupportedReason` in+`server/lib/sglangQwenRecipe.js`, reading the compute-capability probe in+`server/lib/cudaCapability.js`. Only the H200 cell is transcribed flag-for-flag+from the cookbook; the two Blackwell cells carry what the research note records+about them and deliberately omit H200's prefill overrides rather than pinning an+unmeasured number. If you bring one up on real hardware, write a dated note in+`docs/research/` and tighten the cell.++## Set up the host++1. Docker with the NVIDIA Container Toolkit. PortOS does not install either —+ they are host decisions with driver requirements it cannot judge.+2. Create a project directory. PortOS looks in `~/sglang-qwen38` by default;+ `SGLANG_QWEN_PROJECT_DIR` overrides it.+3. Save the compose file below into it as `docker-compose.yml`.+4. Pull the image and the weights **once, yourself** — roughly 20 GB:++ ```bash+ docker pull lmsysorg/sglang:qwen38-27b+ HF_HOME=./hf-cache hf download Qwen/Qwen3.8-27B-FP8+ ```++ Gated repo? Put `HF_TOKEN=…` in a `.env` beside the compose file. Weights kept+ somewhere else entirely? Point `SGLANG_QWEN_WEIGHTS_DIR` at them, so the+ readiness check can see them.++## The compose file++Generated from `buildSglangQwenRecipe({ hw: 'h200' })` — that function is the+single source of truth, and a unit test fails if this block drifts from it. For a+Blackwell card, regenerate with `hw: 'rtx5090'` or `hw: 'rtx6000'`.++```yaml+services:+ sglang-qwen38:+ image: lmsysorg/sglang:qwen38-27b+ container_name: sglang-qwen38+ restart: "no"+ ipc: host+ shm_size: "32g"+ ports:+ - "127.0.0.1:18021:18021"+ volumes:+ - ${HF_HOME:-./hf-cache}:/root/.cache/huggingface+ environment:+ - HF_TOKEN=${HF_TOKEN:-}+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: all+ capabilities: ["gpu"]+ entrypoint: ["sglang"]+ command:+ - "serve"+ - "--trust-remote-code"+ - "--model-path"+ - "Qwen/Qwen3.8-27B-FP8"+ - "--kv-cache-dtype"+ - "fp8_e4m3"+ - "--mem-fraction-static"+ - "0.85"+ - "--attention-backend"+ - "flashinfer"+ - "--chunked-prefill-size"+ - "32768"+ - "--max-prefill-tokens"+ - "32768"+ - "--reasoning-parser"+ - "qwen3"+ - "--tool-call-parser"+ - "qwen3_coder"+ - "--mamba-radix-cache-strategy"+ - "extra_buffer"+ - "--mamba-ssm-dtype"+ - "float32"+ - "--mamba-full-memory-ratio"+ - "1.201"+ - "--host"+ - "127.0.0.1"+ - "--port"+ - "18021"+```++### Why these flags++- **`--tool-call-parser qwen3_coder`** — SGLang's spelling. vLLM's is+ `qwen3_xml`. Use the wrong one, or omit it, and the server starts, answers, and+ returns raw markup with no `tool_calls` block: the agent narrates edits it never+ makes. This is the exact failure the 3090 bring-up hit.+- **`--reasoning-parser qwen3`** — the same class of silent failure for the+ thinking block.+- **`--mamba-full-memory-ratio 1.201`** — derived, not defaulted. Qwen3.8-27B is a+ hybrid Gated DeltaNet model, so post-weight memory splits between a reserved GDN+ state pool (which sets the concurrency ceiling) and the paged KV pool. The+ cookbook formula is `(S + D) × state_bytes / (L × kv_bytes_per_token)`; at the+ CoS operating point (`extra_buffer` → S=5, speculation off → D=0, fp32 state →+ 153.9 MB, fp8 KV → 32.8 KB/token, L ≈ 20,000 from the 3090 bring-up's measured+ 17k-token agent prefix) that is **1.201**. The cookbook default `0.9` under-sizes+ the state pool here and silently clamps concurrency.++ **After boot, check the server log's `max_running_requests` line.** If it is+ capped below the concurrency you wanted, raise the ratio.+- **`restart: "no"`** — the container holds the whole GPU. A restart policy would+ bring it back on every host reboot, silently blocking local media jobs.+- **No DFLASH2.** That overlay needs an SGLang newer than this pinned image+ (PR sgl-project/sglang#35496) and is unmeasured on H200. In-checkpoint MTP+ (`--speculative-algorithm EAGLE` 3/1/4) needs no extra weights and is a+ reasonable later experiment — but it is not the first-ship default, and it+ raises the mamba ratio (D goes 0 → 4).++## Start it++Either `docker compose up -d` in the project directory, or the **Start SGLang**+button on the provider readiness checklist. That button only ever brings up an+already-prepared project: it refuses on an unsupported card before it reaches+docker, refuses when the compose file is missing, and refuses when it cannot+confirm the weights are on disk. It never pulls the image and never downloads+weights.++## Use it from an agent++Migration `290-opencode-sglang-providers` seeds two disabled presets on+**AI Providers**:++| Preset | Type | Endpoint |+| --- | --- | --- |+| `opencode-sglang` | cli | `http://127.0.0.1:18021/v1` |+| `opencode-sglang-tui` | tui | `http://127.0.0.1:18021/v1` |++Enable the one you want once the container answers. Both carry+`sglangBacked: true`, which is what routes OpenCode to the `sglang/` namespace,+skips the provider in usage/quota accounting (a local runtime costs no money), and+drives the readiness probe against `:18021/v1/models`.++**API key.** SGLang serves unauthenticated unless you started it with+`--api-key`. The presets ship a blank key and PortOS attaches one only when it is+set — unlike the vLLM stack, whose key is mandatory.++**Generation controls.** Temperature, top-p, reasoning effort, and the thinking+toggle all render for these presets and reach `agent.build` through+`OPENCODE_CONFIG_CONTENT`. Thinking rides `chat_template_kwargs.enable_thinking`,+the same shape MTPLX and llama.cpp take.++Qwen3.8-27B has thinking **on** by default. CoS coding wants it **off** — that is+what keeps the tool-call format reliable — but PortOS does not seed the setting,+so turn it off on the provider yourself.++## GPU exclusivity++An enabled `sglangBacked` provider whose endpoint answers is treated as a GPU+blocker: local image/video/3D jobs refuse up front with a message naming the stop+command, instead of spending minutes loading a model into VRAM they cannot have+and dying with an OOM that names nothing. PortOS **detects and refuses; it never+auto-stops** — nothing would restart the container, an attached CoS session dies+with it, and a cold start is minutes. See `detectGpuBlockers` in+`server/lib/localMemory.js`.++The probe is skipped entirely when no enabled `sglangBacked` provider exists, and+again when the host reports no NVIDIA GPU at all.++## Related++- [vLLM Qwen3.8-27B on an RTX 3090](./qwen38-rtx3090.md) — the Ampere path+- [MTPLX](./mtplx.md) and [DFlash 2 / DSpark](./dflash2.md) — the Apple Silicon paths+- [Ports](../PORTS.md) — why `18021`+- [Research: SGLang Qwen3.8-27B cookbook](../research/2026-08-21-sglang-qwen38-27b.md)diff --git a/ecosystem.config.cjs b/ecosystem.config.cjsindex f50f2e6a55..9c1337f72a 100644--- a/ecosystem.config.cjs+++ b/ecosystem.config.cjs@@ -50,6 +50,7 @@ const PORTS = {POSTGRES_DOCKER: 5561, // PostgreSQL Docker container (host port mapping)LLAMA_SERVER: 5568, // Loopback llama.cpp speculative-decoding serverVLLM_QWEN: 18020, // Loopback vLLM Qwen3.8-27B (DFlash 2) container — started by the operator, never by PortOS+ SGLANG_QWEN: 18021, // Loopback SGLang Qwen3.8-27B container (Hopper/Blackwell) — started by the operator, never by PortOSPOSTGRES: pgMode === 'native' ? 5432 : 5561 // Active PostgreSQL port (unused in file mode)};diff --git a/scripts/migrations/290-opencode-sglang-providers.js b/scripts/migrations/290-opencode-sglang-providers.jsnew file mode 100644index 0000000000..c146f17458--- /dev/null+++ b/scripts/migrations/290-opencode-sglang-providers.js@@ -0,0 +1,81 @@+/**+ * Ship disabled OpenCode SGLang provider presets to existing installs.+ *+ * SGLang's official `lmsysorg/sglang:qwen38-27b` image serves Qwen3.8-27B on a+ * Hopper or Blackwell card — the third CUDA path PortOS knows about, alongside+ * the Ampere-only vLLM container (migration 285) and the Apple Silicon MTPLX /+ * llama-server pair. It is an OpenAI-compatible daemon, so it is fronted the+ * same way: a headless `cli` twin and the attachable `tui` that CoS agent tasks+ * actually run in.+ *+ * No API preset, for the same reason as vLLM: a text-only record adds a third+ * place to configure for no capability the two coding harnesses lack. The+ * Anthropic `/v1/messages` pair (Claude Code without LiteLLM) is #4777, which+ * carries its own env-var contract and its own migration.+ *+ * Both presets are DISABLED, and this migration installs nothing: it does not+ * write a compose file, pull the image, download weights, start a container, or+ * contact the endpoint. The stack holds the whole GPU, so an install that also+ * runs local image/video generation must not have it come up on its own. An+ * install that already owns one of these ids is left untouched.+ *+ * `apiKey` ships blank and usually STAYS blank: SGLang authenticates only when+ * the operator started it with `--api-key`. That is the one difference from the+ * vLLM preset, whose container always requires its key.+ *+ * Kept in lockstep with data.reference/providers.json and+ * server/lib/aiToolkit/defaults/providers.sample.json. These frozen literals are+ * the historical upgrade payload; later default changes require a new migration+ * rather than rewriting this record.+ */++import { makeProviderSeedMigration } from './_lib.js';++const ENDPOINT = 'http://127.0.0.1:18021/v1';++const OPENCODE_CONFIG_CONTENT = '{"permission":"allow","provider":{"sglang":{"npm":"@ai-sdk/openai-compatible","name":"SGLang Qwen3.8-27B (local)","options":{"baseURL":"http://127.0.0.1:18021/v1"}}}}';++const OPENCODE_SGLANG_CLI = {+ id: 'opencode-sglang',+ name: 'OpenCode SGLang (Qwen3.8-27B)',+ type: 'cli',+ command: 'opencode',+ args: ['run'],+ endpoint: ENDPOINT,+ // Blank, not absent: the operator pastes a key here only if they launched+ // SGLang behind `--api-key`, and the spawner copies it onto the OpenCode+ // provider's `options.apiKey` when it is non-empty.+ apiKey: '',+ models: ['qwen3.8-27b'],+ defaultModel: 'qwen3.8-27b',+ sglangBacked: true,+ timeout: 600000,+ enabled: false,+ envVars: { OPENCODE_CONFIG_CONTENT },+ secretEnvVars: [],+ headlessArgs: [],+};++const OPENCODE_SGLANG_TUI = {+ id: 'opencode-sglang-tui',+ name: 'OpenCode SGLang TUI (Qwen3.8-27B)',+ type: 'tui',+ command: 'opencode',+ args: [],+ endpoint: ENDPOINT,+ apiKey: '',+ models: ['qwen3.8-27b'],+ defaultModel: 'qwen3.8-27b',+ sglangBacked: true,+ timeout: 600000,+ enabled: false,+ envVars: { OPENCODE_CONFIG_CONTENT },+ secretEnvVars: [],+ tuiPromptDelayMs: 2500,+ tuiIdleTimeoutMs: 180000,+};++export default makeProviderSeedMigration({+ label: 'OpenCode SGLang (Qwen3.8-27B)',+ defs: [OPENCODE_SGLANG_CLI, OPENCODE_SGLANG_TUI],+});diff --git a/scripts/migrations/290-opencode-sglang-providers.test.js b/scripts/migrations/290-opencode-sglang-providers.test.jsnew file mode 100644index 0000000000..b717a94d06--- /dev/null+++ b/scripts/migrations/290-opencode-sglang-providers.test.js@@ -0,0 +1,111 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './290-opencode-sglang-providers.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 290 — OpenCode SGLang providers', () => {+ let rootDir;+ let providersPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-290-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ providersPath = join(rootDir, 'data/providers.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('adds both OpenCode SGLang presets, disabled, without changing the active provider', async () => {+ writeJson(providersPath, {+ activeProvider: 'claude-code',+ providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },+ });++ await migration.up({ rootDir });+ const out = readJson(providersPath);++ expect(out.providers['opencode-sglang']).toMatchObject({+ name: 'OpenCode SGLang (Qwen3.8-27B)',+ type: 'cli',+ command: 'opencode',+ endpoint: 'http://127.0.0.1:18021/v1',+ models: ['qwen3.8-27b'],+ defaultModel: 'qwen3.8-27b',+ sglangBacked: true,+ enabled: false,+ });+ expect(out.providers['opencode-sglang-tui']).toMatchObject({+ type: 'tui',+ sglangBacked: true,+ enabled: false,+ tuiIdleTimeoutMs: 180000,+ });+ expect(out.activeProvider).toBe('claude-code');+ });++ it('declares the sglang namespace at the container endpoint in the OpenCode config', async () => {+ writeJson(providersPath, { providers: {} });+ await migration.up({ rootDir });++ for (const id of ['opencode-sglang', 'opencode-sglang-tui']) {+ const config = JSON.parse(readJson(providersPath).providers[id].envVars.OPENCODE_CONFIG_CONTENT);+ expect(config.provider.sglang.options.baseURL).toBe('http://127.0.0.1:18021/v1');+ }+ });++ it('never seeds a thinking default — CoS wants it off, but the operator chooses', async () => {+ writeJson(providersPath, { providers: {} });+ await migration.up({ rootDir });+ const out = readJson(providersPath);++ for (const id of ['opencode-sglang', 'opencode-sglang-tui']) {+ expect(out.providers[id].thinking).toBeUndefined();+ }+ });++ it('ships a blank apiKey — SGLang only authenticates behind --api-key', async () => {+ writeJson(providersPath, { providers: {} });+ await migration.up({ rootDir });+ const out = readJson(providersPath);++ expect(out.providers['opencode-sglang'].apiKey).toBe('');+ expect(out.providers['opencode-sglang-tui'].apiKey).toBe('');+ });++ it('leaves the vLLM presets on their own port', async () => {+ // The two CUDA stacks are complementary, not alternatives: seeding SGLang+ // must not disturb an Ampere host's existing vLLM wrappers.+ const vllm = {+ id: 'opencode-vllm-tui', type: 'tui', endpoint: 'http://127.0.0.1:18020/v1', vllmBacked: true, enabled: true,+ };+ writeJson(providersPath, { providers: { 'opencode-vllm-tui': vllm } });++ await migration.up({ rootDir });+ const out = readJson(providersPath);+ expect(out.providers['opencode-vllm-tui']).toEqual(vllm);+ expect(out.providers['opencode-sglang-tui'].endpoint).toBe('http://127.0.0.1:18021/v1');+ });++ it('preserves an existing customized SGLang provider', async () => {+ const existing = {+ id: 'opencode-sglang-tui',+ name: 'Custom SGLang TUI',+ type: 'tui',+ endpoint: 'http://127.0.0.1:19000/v1',+ apiKey: 'operator-key',+ enabled: true,+ };+ writeJson(providersPath, { providers: { 'opencode-sglang-tui': existing } });++ await migration.up({ rootDir });+ const out = readJson(providersPath);+ expect(out.providers['opencode-sglang-tui']).toEqual(existing);+ // The sibling it did not already own is still added.+ expect(out.providers['opencode-sglang']).toBeDefined();+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 695223b51d..bd12fd0cf8 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -145,6 +145,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `vllmQwenProject.js` | `resolveVllmProjectDir()` / `inspectVllmQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the operator-cloned syv-ai/qwen38-27b-rtx3090 compose project, plus `vllmStartBlockedReason(project)` → the prose refusal (or `null`), and `vllmProjectSetupState(project)` → `ready`/`empty`/`unknown` for the readiness checklist. Directory reads only — never runs docker or touches a registry. `hasWeights` is tri-state: `true` found / `false` caches read and empty / `null` no cache readable (a docker-volume cache is invisible from a native-Win32 PortOS), and `services/localRuntimeSetup.js` refuses to `docker compose up` on anything but `true` so the start button can never kick off the ~20 GB prepare. Overrides: `VLLM_QWEN_PROJECT_DIR`, `VLLM_QWEN_WEIGHTS_DIR`. || `qwenAgentParsers.js` | The tool-call / reasoning parser flags a local runtime MUST carry to serve a Qwen3-family model to a coding agent — one table PortOS owns instead of three docs. `QWEN_AGENT_PARSERS` maps runtime → `{toolCallParser, reasoningParser, enableAutoToolChoice}` (vLLM `qwen3_xml` + `--enable-auto-tool-choice`, SGLang `qwen3_coder` + `--reasoning-parser qwen3`, llama both `null` — a positive "no such flag today", not a placeholder). `parserFlagsFor(runtime)` returns the argv fragment (always an array, so no caller type-checks) and `vllmExtraArgs()` its string form for the compose project's `.env` `EXTRA_ARGS`; an unknown runtime THROWS, because the failure it prevents is silent — a parser-less server answers fluently and returns tool markup as ordinary text with `tool_calls: null`, so the agent never touches a file. Spellings are empirical (`docs/research/2026-08-21-qwen38-rtx3090-vllm.md`, `…-sglang-qwen38-27b.md`); never auto-detect one from the chat template — that is how `hermes` got picked. Pure. || `vllmQwenProvision.js` | The `.env` half of provisioning that same project: `generateVllmApiKey()`, `isWsl2Engine()` (win32 counts — Docker Desktop's engine IS a WSL2 VM), `vllmEnvDefaults({apiKey, wsl2})` → the load-bearing tool-parser/pin-memory/alloc-conf settings, and `mergeEnvFileContents(existing, defaults)` → `{contents, added, kept, effective}`. **Additive only** — an operator's existing key or tuning is never overwritten, and `effective` reports what the container will actually read. Plus `WSL2_PREPARE_MIN_BYTES` / `WSL2_PREPARE_CONFIG_HINT` for the ceiling `prepare` needs (detected and warned about, never raised). |+| `sglangQwenProject.js` | `resolveSglangProjectDir()` / `inspectSglangQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the operator's SGLang Qwen3.8-27B project, plus `sglangStartBlockedReason(project)` → the prose refusal (or `null`). Sibling of `vllmQwenProject.js` with the same tri-state `hasWeights` contract (`true` found / `false` caches read and empty / `null` no cache readable) and the same directory-reads-only rule — never docker, never a registry. Differs in that PortOS OWNS this launch line (SGLang publishes an image but no compose project), so the refusals point at the compose file in `docs/features/sglang-qwen38.md` rather than at a `git clone`. Overrides: `SGLANG_QWEN_PROJECT_DIR`, `SGLANG_QWEN_WEIGHTS_DIR`. |+| `sglangQwenRecipe.js` | The `sglang serve` launch line PortOS owns, per NVIDIA card class. `buildSglangQwenRecipe({hw, contextLength, ssmDtype, spec, radixStrategy, host, port})` → `{image, modelName, modelPath, cell, mambaRatio, stateSlots, flags, env}`, and `sglangComposeYaml(recipe)` renders the `docker-compose.yml` from it (one source of truth; a test pins the doc against it). `mambaFullMemoryRatio(...)` derives `--mamba-full-memory-ratio` from the cookbook formula `(S + D) × state_bytes / (L × kv_bytes_per_token)` — load-bearing, because the cookbook default `0.9` under-sizes the GDN state pool at CoS prompt lengths and silently clamps `max_running_requests`. Both Qwen parsers (`--reasoning-parser qwen3`, `--tool-call-parser qwen3_coder` — NOT vLLM's `qwen3_xml`) are baked into every cell: getting them wrong fails silently, with the model emitting raw markup and the agent never calling a tool. `sglangCellForGpu(gpu)` maps a `cudaCapability.js` compute-cap row to a cell (SM 9.x → `h200`, SM ≥10 → `rtx6000`/`rtx5090` by VRAM, Ampere → `null`, which is a refusal: 24 GB stays on vLLM), and `sglangUnsupportedReason({platform, status, gpus})` is the prose for every no — never collapsing a probe `'unknown'` into "no GPU". Pure: no filesystem, no docker, no network. || `openAiModelsProbe.js` | `probeOpenAiModels(baseUrl, { timeoutMs, apiKey })` → `{ reachable, models, error }` — the one `GET {base}/models` probe for the local OpenAI-compatible daemons, shared by `services/providerReadiness.js` and `services/llamaServerManager.js`. Distinguishes unreachable from reachable-but-unlistable (`models: null`) from up-with-nothing-loaded (`[]`), names the real transport failure via `describeFetchError` (undici reports every one as a bare `fetch failed`), and cancels an unread body on a non-OK response. `apiKey` attaches a Bearer header for a key-gated daemon (vLLM's compose stack), and a 401/403 answers `reachable: true` with `error: 'authentication required'` — a server that refused the request is definitively running, and calling it unreachable would send the user to start it again. Consolidated after the two copies drifted — one passed its timeout as a `timeout` key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default. || `openAiChatStream.js` | `streamOpenAiChat({ endpoint, apiKey, model, messages, temperature, maxTokens, extraBody, signal, onChunk, onStats })` → the streamed text — one streaming `POST {base}/chat/completions` against any local OpenAI-compatible daemon; `streamOllamaChat(...)` is the assessment-only native `/api/chat` transport that preserves Ollama's exact eval counts and nanosecond timings. Also exports `buildMessages`, `parseStreamFrame`, `parseOllamaStreamFrame`, `normalizeUsage` (snake/camel/Ollama token-count keys → `{completionTokens, promptTokens}`, `null` = not reported), and `resolvePartialOutput`. Registering `onStats` on the OpenAI path asks for token counts; a daemon that rejects `stream_options` is retried once without it and remembered per endpoint. Sibling of `openAiModelsProbe.js`. Shared by `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record) and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. || `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.jsonindex d1e90447dd..ca6083be56 100644--- a/server/lib/aiToolkit/defaults/providers.sample.json+++ b/server/lib/aiToolkit/defaults/providers.sample.json@@ -208,6 +208,45 @@"tuiPromptDelayMs": 2500,"tuiIdleTimeoutMs": 180000},+ "opencode-sglang": {+ "id": "opencode-sglang",+ "name": "OpenCode SGLang (Qwen3.8-27B)",+ "type": "cli",+ "command": "opencode",+ "args": ["run"],+ "endpoint": "http://127.0.0.1:18021/v1",+ "apiKey": "",+ "models": ["qwen3.8-27b"],+ "defaultModel": "qwen3.8-27b",+ "sglangBacked": true,+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"sglang\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"SGLang Qwen3.8-27B (local)\",\"options\":{\"baseURL\":\"http://127.0.0.1:18021/v1\"}}}}"+ },+ "secretEnvVars": [],+ "headlessArgs": []+ },+ "opencode-sglang-tui": {+ "id": "opencode-sglang-tui",+ "name": "OpenCode SGLang TUI (Qwen3.8-27B)",+ "type": "tui",+ "command": "opencode",+ "args": [],+ "endpoint": "http://127.0.0.1:18021/v1",+ "apiKey": "",+ "models": ["qwen3.8-27b"],+ "defaultModel": "qwen3.8-27b",+ "sglangBacked": true,+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"sglang\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"SGLang Qwen3.8-27B (local)\",\"options\":{\"baseURL\":\"http://127.0.0.1:18021/v1\"}}}}"+ },+ "secretEnvVars": [],+ "tuiPromptDelayMs": 2500,+ "tuiIdleTimeoutMs": 180000+ },"orcarouter": {"id": "orcarouter","name": "OrcaRouter",diff --git a/server/lib/aiToolkit/internal/generationOptions.js b/server/lib/aiToolkit/internal/generationOptions.jsindex 79040eff2d..f92dfda243 100644--- a/server/lib/aiToolkit/internal/generationOptions.js+++ b/server/lib/aiToolkit/internal/generationOptions.js@@ -28,7 +28,7 @@ const finiteNumber = (value, min, max) => {* top_p with it, which is how the vLLM providers shipped with every generation* control silently discarded on the OpenCode side (#4765).*- * @param {{temperature?:unknown, topP?:unknown, thinking?:unknown, llamaBacked?:boolean, mtplxBacked?:boolean, vllmBacked?:boolean}|null|undefined} provider+ * @param {{temperature?:unknown, topP?:unknown, thinking?:unknown, llamaBacked?:boolean, mtplxBacked?:boolean, vllmBacked?:boolean, sglangBacked?:boolean}|null|undefined} provider* @returns {{temperature?:number, top_p?:number, think?:boolean, chat_template_kwargs?:{enable_thinking:boolean}}}*/export function apiGenerationOptions(provider) {@@ -36,7 +36,8 @@ export function apiGenerationOptions(provider) {if (!ollama&& provider?.llamaBacked !== true&& provider?.mtplxBacked !== true- && provider?.vllmBacked !== true) return {};+ && provider?.vllmBacked !== true+ && provider?.sglangBacked !== true) return {};// Ollama API runs have defaulted to 0.6 since this control shipped; the other// local backends keep their own default until the user pins one.const temperature = finiteNumber(provider.temperature, 0, 2) ?? (ollama ? 0.6 : undefined);@@ -44,8 +45,8 @@ export function apiGenerationOptions(provider) {return {...(temperature === undefined ? {} : { temperature }),...(topP === undefined ? {} : { top_p: topP }),- // Ollama takes its own native `think` boolean; llama.cpp / MTPLX / vLLM- // route the toggle through the chat template instead.+ // Ollama takes its own native `think` boolean; llama.cpp / MTPLX / vLLM /+ // SGLang route the toggle through the chat template instead....(typeof provider.thinking !== 'boolean'? {}: ollamadiff --git a/server/lib/aiToolkit/internal/modelFetchers.js b/server/lib/aiToolkit/internal/modelFetchers.jsindex 0322bbc818..e5280d2c98 100644--- a/server/lib/aiToolkit/internal/modelFetchers.js+++ b/server/lib/aiToolkit/internal/modelFetchers.js@@ -88,6 +88,16 @@ export const MODEL_FETCHERS = [tuiMatch: (p) => p?.vllmBacked === true,fetch: '_fetchVllmModels',},+ {+ key: 'sglang',+ // Same OpenAI-compatible `/v1/models` contract as the vLLM row. SGLang only+ // authenticates when the operator started it with `--api-key`, so the+ // wrapper's `apiKey` is usually blank — `_refreshAPIProviderModels` simply+ // omits the Bearer header then.+ cliMatch: (p) => p?.sglangBacked === true,+ tuiMatch: (p) => p?.sglangBacked === true,+ fetch: '_fetchSglangModels',+ },{key: 'orcarouter',// OrcaRouter-backed OpenCode wrappers probe the sibling API provider'sdiff --git a/server/lib/aiToolkit/internal/modelFetchers.test.js b/server/lib/aiToolkit/internal/modelFetchers.test.jsindex 1838514464..ab98e5fc98 100644--- a/server/lib/aiToolkit/internal/modelFetchers.test.js+++ b/server/lib/aiToolkit/internal/modelFetchers.test.js@@ -22,6 +22,9 @@ const SHIPPED_REFRESHABLE = ['opencode-mtplx', 'opencode-mtplx-tui', 'opencode-ollama', 'opencode-ollama-tui','opencode-orcarouter', 'opencode-orcarouter-tui', 'orcarouter','opencode-vllm', 'opencode-vllm-tui',+ // SGLang publishes its served catalog through the same OpenAI-compatible+ // `/v1/models` contract as the vLLM pair, so its wrappers refresh too.+ 'opencode-sglang', 'opencode-sglang-tui',];const SHIPPED_NOT_REFRESHABLE = ['claude-code-tui', 'claude-code-tui-bedrock', 'codex', 'codex-tui',diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex 4e43a70808..c8fce21f38 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -611,6 +611,10 @@ export function createProviderService(config = {}) {// the marker so OpenCode receives the `vllm/` namespace and model// refresh probes the container rather than the OpenCode harness....(providerData.vllmBacked === true ? { vllmBacked: true } : {}),+ // The SGLang container is a fourth distinct local backend (Hopper/Blackwell,+ // PortOS-owned launch line): preserve the marker so OpenCode receives the+ // `sglang/` namespace and model refresh probes the container.+ ...(providerData.sglangBacked === true ? { sglangBacked: true } : {}),...(providerData.orcarouterBacked === true ? { orcarouterBacked: true } : {}),// Explicit opt-in to send the API key to an arbitrary (non-local,// non-allowlisted) endpoint — see internal/endpointGuard.js. Only@@ -1114,6 +1118,15 @@ export function createProviderService(config = {}) {return this._refreshAPIProviderModels(provider);},+ /**+ * Fetch the served catalog from a local SGLang container for its OpenCode+ * CLI/TUI wrappers. Refresh-only, like every other local fetcher here: it+ * never starts the container, pulls the image, or issues a completion.+ */+ async _fetchSglangModels(provider) {+ return this._refreshAPIProviderModels(provider);+ },+/** Fetch the OrcaRouter catalog for its OpenCode CLI/TUI wrappers. */async _fetchOrcaRouterModels(provider) {return this._refreshAPIProviderModels(provider);diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.jsindex c968720c79..a4d53241ce 100644--- a/server/lib/aiToolkit/validation.js+++ b/server/lib/aiToolkit/validation.js@@ -119,6 +119,11 @@ export const providerSchema = z.object({// `llamaBacked`: a different engine, a different port, and a different auth// story (vLLM is started behind an API key; llama-server is not).vllmBacked: z.boolean().optional(),+ // Marks an OpenCode CLI/TUI wrapper for a separately started local SGLang+ // container serving Qwen3.8-27B on a Hopper/Blackwell card. Distinct from+ // `vllmBacked`: a different engine, a different port, a different tool-call+ // parser, and an API key that is optional rather than required.+ sglangBacked: z.boolean().optional(),// Marks an OpenCode CLI/TUI wrapper for the OrcaRouter OpenAI-compatible// gateway. Its API key is read from the sibling `orcarouter` API record at// spawn/refresh time and is never stored in this wrapper's config.diff --git a/server/lib/cliChildEnv.js b/server/lib/cliChildEnv.jsindex 580b9a62dd..84cf9d82b4 100644--- a/server/lib/cliChildEnv.js+++ b/server/lib/cliChildEnv.js@@ -75,7 +75,7 @@ function claudeOllamaEnvDefaults(provider) {* @param {object} options* @param {object|null} [options.before] - layered first, so `provider.envVars`* overrides it (forgeTokenEnv, claudeSettingsEnv).- * @param {{command?:string, envVars?:object, models?:string[], defaultModel?:string|null, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, orcarouterBacked?:boolean, thinking?:boolean}|null} [options.provider]+ * @param {{command?:string, envVars?:object, models?:string[], defaultModel?:string|null, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, sglangBacked?:boolean, orcarouterBacked?:boolean, thinking?:boolean}|null} [options.provider]* @param {string|null} [options.model] - the model being run this invocation,* unioned into the OpenCode declared-models map. Omit when the site has no* per-call model — `provider.defaultModel` is always declared regardless.diff --git a/server/lib/index.js b/server/lib/index.jsindex ca84f4e5f3..973380c0e6 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -161,6 +161,8 @@ export * from './managedDaemon.js';export * from './vllmQwenProject.js';export * from './qwenAgentParsers.js';export * from './vllmQwenProvision.js';+export * from './sglangQwenProject.js';+export * from './sglangQwenRecipe.js';export * from './openAiModelsProbe.js';export * from './openAiChatStream.js';// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live indiff --git a/server/lib/localMemory.js b/server/lib/localMemory.jsindex fbf3130f2e..e2ddabcbc2 100644--- a/server/lib/localMemory.js+++ b/server/lib/localMemory.js@@ -10,6 +10,7 @@ import { probeOpenAiModels } from './openAiModelsProbe.js';import { getCudaCapability } from './cudaCapability.js';import { localRuntimeForProvider, LOCAL_RUNTIMES } from './localProviderRuntime.js';import { resolveVllmProjectDir } from './vllmQwenProject.js';+import { resolveSglangProjectDir } from './sglangQwenProject.js';const execFileAsync = promisify(execFile);const GB = 2 ** 30;@@ -57,20 +58,39 @@ export const GPU_BLOCKER_PROBE_TIMEOUT_MS = 1_500;const vllmBlockerReason = ({ endpoint, projectDir }) =>`${LOCAL_RUNTIMES.vllm.label} is serving at ${endpoint} and holds nearly all of this GPU's VRAM, so this job would run out of memory partway through its model load. Stop the container with \`docker compose --profile single stop\` in ${projectDir}, then start this job again. PortOS will not stop it for you: nothing would restart it, an agent session attached to it dies with it, and a cold start takes roughly 5–7 minutes.`;+/** The same refusal for the SGLang container, with its own stop command. */+const sglangBlockerReason = ({ endpoint, projectDir }) =>+ `${LOCAL_RUNTIMES.sglang.label} is serving at ${endpoint} and holds nearly all of this GPU's VRAM, so this job would run out of memory partway through its model load. Stop the container with \`docker compose stop\` in ${projectDir}, then start this job again. PortOS will not stop it for you: nothing would restart it, an agent session attached to it dies with it, and a cold start is measured in minutes.`;++/**+ * One row per GPU-exclusive local container, keyed by its `*Backed` provider+ * marker. Table-driven rather than a second copy of the probe: the two+ * containers differ only in which marker selects them, which directory holds+ * their compose file, and how the refusal is worded — everything else (the+ * enabled-provider gate, the CUDA gate, the credential-preferring endpoint+ * dedupe, the reachable-means-blocking rule) is identical, and a forked copy is+ * how the second runtime would quietly miss a fix made to the first.+ */+const GPU_EXCLUSIVE_RUNTIMES = Object.freeze([+ Object.freeze({ kind: 'vllm', marker: 'vllmBacked', resolveProjectDir: resolveVllmProjectDir, reason: vllmBlockerReason }),+ Object.freeze({ kind: 'sglang', marker: 'sglangBacked', resolveProjectDir: resolveSglangProjectDir, reason: sglangBlockerReason }),+]);+/*** GPU tenants that make a local media job unwinnable *before* it spends minutes* loading a model into VRAM it cannot have.*- * Today that is exactly one thing: the vLLM Qwen3.8-27B compose container, which- * holds ~23 GB of a 24 GB RTX 3090. `unloadResidentModels()` above cannot help —- * it evicts loopback Ollama / LM Studio, and a container is invisible to both.- * The job therefore proceeded, allocated, and died inside the model load with an- * OOM naming neither vLLM nor a remedy.+ * Today that is two things: the vLLM Qwen3.8-27B compose container (~23 GB of a+ * 24 GB RTX 3090) and the SGLang Qwen3.8-27B container on a Hopper/Blackwell+ * card. `unloadResidentModels()` above cannot help — it evicts loopback Ollama /+ * LM Studio, and a container is invisible to both. The job therefore proceeded,+ * allocated, and died inside the model load with an OOM naming neither the+ * container nor a remedy.** **Detect and refuse — never auto-stop** (#4766). An Ollama unload is- * transparent (the next request reloads); stopping this container is not.- * Nothing restarts it, an attached CoS session dies with it, and a cold start is- * ~5–7 minutes. PortOS deliberately never *starts* this container either — both+ * transparent (the next request reloads); stopping one of these containers is+ * not. Nothing restarts it, an attached CoS session dies with it, and a cold+ * start is minutes. PortOS deliberately never *starts* them either — both* directions stay operator decisions, and the refusal prose is what makes that* actionable.*@@ -78,10 +98,11 @@ const vllmBlockerReason = ({ endpoint, projectDir }) =>* container is not serving" → **no blocker, proceed**. *Couldn't check* must* never collapse into *is blocking*, or an unrelated network hiccup would refuse* every media job on the box. Only an endpoint that actually answers blocks —- * including a 401/403, which is a container up behind `VLLM_API_KEY`.+ * including a 401/403, which is a container up behind an API key.** Two cheap gates keep the common path free of latency, in cost order:- * 1. No **enabled** `vllmBacked` provider → nothing to probe, no network call.+ * 1. No **enabled** `vllmBacked` / `sglangBacked` provider → nothing to probe,+ * no network call.* 2. `getCudaCapability()` says `'absent'` → this host has no NVIDIA GPU to* contend over. `'unknown'` (nvidia-smi wedged or too old) is NOT a* negative and still probes — same sentinel rule as above, in the other@@ -94,8 +115,11 @@ const vllmBlockerReason = ({ endpoint, projectDir }) =>*/export async function detectGpuBlockers({ env = process.env, providers = null, timeoutMs = GPU_BLOCKER_PROBE_TIMEOUT_MS } = {}) {const all = Array.isArray(providers) ? providers : await getAllProviders().catch(() => []);- const candidates = (Array.isArray(all) ? all : []).filter((p) => p?.enabled === true && p?.vllmBacked === true);- if (!candidates.length) return [];+ const enabled = (Array.isArray(all) ? all : []).filter((p) => p?.enabled === true);+ const rows = GPU_EXCLUSIVE_RUNTIMES+ .map((row) => ({ row, candidates: enabled.filter((p) => p?.[row.marker] === true) }))+ .filter(({ candidates }) => candidates.length > 0);+ if (!rows.length) return [];// No custom timeout: this shares the memo the image-to-3D lane gating already// fills, and a shorter deadline here would write an 'unknown' into it that the@@ -106,29 +130,31 @@ export async function detectGpuBlockers({ env = process.env, providers = null, t// Two providers can point at one container with different credentials, and a// remote endpoint is a different machine's GPU — `localRuntimeForProvider`// drops the latter and returns null for it.- const byEndpoint = new Map();- for (const provider of candidates) {- const runtime = localRuntimeForProvider(provider);- if (runtime?.kind !== 'vllm' || !runtime.endpoint) continue;- const existing = byEndpoint.get(runtime.endpoint);- // Prefer the credentialed record: an unauthenticated probe still detects the- // container (401 ⇒ reachable), but a readable listing is the cleaner signal.- if (!existing || (!existing.apiKey && typeof provider.apiKey === 'string' && provider.apiKey !== '')) {- byEndpoint.set(runtime.endpoint, { provider, apiKey: typeof provider.apiKey === 'string' ? provider.apiKey : '' });+ const targets = new Map();+ for (const { row, candidates } of rows) {+ for (const provider of candidates) {+ const runtime = localRuntimeForProvider(provider);+ if (runtime?.kind !== row.kind || !runtime.endpoint) continue;+ const existing = targets.get(runtime.endpoint);+ // Prefer the credentialed record: an unauthenticated probe still detects+ // the container (401 ⇒ reachable), but a readable listing is the cleaner+ // signal.+ if (!existing || (!existing.apiKey && typeof provider.apiKey === 'string' && provider.apiKey !== '')) {+ targets.set(runtime.endpoint, { row, provider, apiKey: typeof provider.apiKey === 'string' ? provider.apiKey : '' });+ }}}- if (!byEndpoint.size) return [];+ if (!targets.size) return [];- const projectDir = resolveVllmProjectDir(env);- const probes = await Promise.all([...byEndpoint].map(async ([endpoint, { provider, apiKey }]) => {+ const probes = await Promise.all([...targets].map(async ([endpoint, { row, provider, apiKey }]) => {const probe = await probeOpenAiModels(endpoint, { timeoutMs, apiKey }).catch(() => null);if (!probe?.reachable) return null;return {- runtime: 'vllm',+ runtime: row.kind,providerId: provider?.id ?? null,providerName: provider?.name ?? null,endpoint,- reason: vllmBlockerReason({ endpoint, projectDir }),+ reason: row.reason({ endpoint, projectDir: row.resolveProjectDir(env) }),};}));return probes.filter(Boolean);diff --git a/server/lib/localMemory.test.js b/server/lib/localMemory.test.jsindex 79b0d0a920..2d3aefc364 100644--- a/server/lib/localMemory.test.js+++ b/server/lib/localMemory.test.js@@ -39,6 +39,11 @@ const vllmProvider = (over = {}) => ({id: 'opencode-vllm-tui', name: 'OpenCode vLLM TUI', enabled: true, vllmBacked: true,endpoint: VLLM_ENDPOINT, ...over,});+const SGLANG_ENDPOINT = 'http://127.0.0.1:18021/v1';+const sglangProvider = (over = {}) => ({+ id: 'opencode-sglang-tui', name: 'OpenCode SGLang TUI', enabled: true, sglangBacked: true,+ endpoint: SGLANG_ENDPOINT, ...over,+});const serving = { reachable: true, models: ['qwen3.8-27b'], error: null };const notServing = { reachable: false, models: null, error: 'ECONNREFUSED' };@@ -50,9 +55,10 @@ beforeEach(() => {h.ollamaUnload = vi.fn(async () => ({ unloaded: true }));h.lmUnload = vi.fn(async () => ({ success: true }));getCudaCapability.mockClear();- // A deliberately fake home so no assertion can be answered by the developer's- // real `~/qwen-serving`.+ // Deliberately fake homes so no assertion can be answered by the developer's+ // real `~/qwen-serving` or `~/sglang-qwen38`.process.env.VLLM_QWEN_PROJECT_DIR = '/srv/example/qwen-serving';+ process.env.SGLANG_QWEN_PROJECT_DIR = '/srv/example/sglang-qwen38';});describe('detectGpuBlockers', () => {@@ -158,6 +164,47 @@ describe('detectGpuBlockers', () => {await expect(detectGpuBlockers()).resolves.toEqual([]);expect(h.probe).not.toHaveBeenCalled();});++ // The SGLang container holds the GPU exactly as the vLLM one does, so the+ // guard is table-driven over both markers rather than forked per runtime.+ describe('SGLang container', () => {+ it('issues no probe when only a disabled sglangBacked provider exists', async () => {+ h.providers = [sglangProvider({ enabled: false })];+ await expect(detectGpuBlockers()).resolves.toEqual([]);+ expect(h.probe).not.toHaveBeenCalled();+ expect(getCudaCapability).not.toHaveBeenCalled();+ });++ it('names the container, its own project directory, and its own stop command', async () => {+ h.providers = [sglangProvider()];+ const [blocker] = await detectGpuBlockers({ env: { SGLANG_QWEN_PROJECT_DIR: '/opt/example/sglang' } });+ expect(blocker).toMatchObject({ runtime: 'sglang', providerId: 'opencode-sglang-tui', endpoint: SGLANG_ENDPOINT });+ expect(blocker.reason).toContain('SGLang (Qwen3.8-27B)');+ expect(blocker.reason).toContain('/opt/example/sglang');+ // NOT vLLM's `--profile single` — this compose file has no profiles.+ expect(blocker.reason).toContain('docker compose stop');+ expect(blocker.reason).not.toContain('--profile single');+ expect(blocker.reason).toMatch(/will not stop it for you/i);+ });++ it('reports both containers when both answer', async () => {+ h.providers = [vllmProvider(), sglangProvider()];+ const blockers = await detectGpuBlockers();+ expect(blockers.map((b) => b.runtime).sort()).toEqual(['sglang', 'vllm']);+ });++ it('does not block on an SGLang served from another machine', async () => {+ h.providers = [sglangProvider({ endpoint: 'http://192.0.2.10:18021/v1' })];+ await expect(detectGpuBlockers()).resolves.toEqual([]);+ expect(h.probe).not.toHaveBeenCalled();+ });++ it('does not block when its probe fails', async () => {+ h.providers = [sglangProvider()];+ h.probe = vi.fn(async () => notServing);+ await expect(detectGpuBlockers()).resolves.toEqual([]);+ });+ });});describe('gpuBlockersMessage', () => {diff --git a/server/lib/localProviderRuntime.js b/server/lib/localProviderRuntime.jsindex 66cfe0e7d0..ff5613a587 100644--- a/server/lib/localProviderRuntime.js+++ b/server/lib/localProviderRuntime.js@@ -11,7 +11,8 @@* exactly that failure.** This module is the pure half of the answer: given a provider record, which- * local runtime backs it (`llama` / `ollama` / `lmstudio` / `mtplx` / `vllm`) and what+ * local runtime backs it (`llama` / `ollama` / `lmstudio` / `mtplx` / `vllm` /+ * `sglang`) and what* base URL should be probed. `services/providerReadiness.js` does the probing.* Kept side-effect-free so both the readiness service and its tests can reason* about the mapping without a daemon on the host.@@ -192,6 +193,24 @@ export const LOCAL_RUNTIMES = Object.freeze({// compose project, so PortOS has no launch line of its own to rename.servesOneModel: true,}),+ sglang: Object.freeze({+ id: 'sglang',+ label: 'SGLang (Qwen3.8-27B)',+ // Docker again, for the same reason as vLLM: the engine ships as an official+ // image (`lmsysorg/sglang:qwen38-27b`) PortOS never builds. Unlike vLLM,+ // though, the LAUNCH LINE is ours — `lib/sglangQwenRecipe.js` owns it,+ // because SGLang publishes no compose project to inherit one from.+ command: 'docker',+ defaultBaseUrl: opencodeLocalBaseUrl('sglang'),+ // No Models → LLMs entry — the weights are an operator-owned ~20 GB+ // download, not something PortOS fetches.+ manageUrl: null,+ docsUrl: 'https://github.com/atomantic/PortOS/blob/main/docs/features/sglang-qwen38.md',+ modelsHint: 'Save the compose file from docs/features/sglang-qwen38.md and download the weights once — PortOS never pulls the image or the ~20 GB of weights.',+ // One container, one checkpoint; the recipe picks the quantized repo from+ // the card class, so there is no per-model rename for PortOS to offer.+ servesOneModel: true,+ }),mtplx: Object.freeze({id: 'mtplx',label: 'MTPLX',@@ -227,7 +246,7 @@ export const LOCAL_RUNTIMES = Object.freeze({* launcher) started. Its "installed models" are whatever `GET /v1/models`* reports right now, and a measurement talks to the endpoint directly.*/-export const ASSESSABLE_RUNTIMES = Object.freeze(['ollama', 'lmstudio', 'llama', 'mtplx', 'vllm']);+export const ASSESSABLE_RUNTIMES = Object.freeze(['ollama', 'lmstudio', 'llama', 'mtplx', 'vllm', 'sglang']);/** Assessable runtimes PortOS holds a provider record and model catalog for. */export const MANAGED_ASSESSMENT_BACKENDS = Object.freeze(['ollama', 'lmstudio']);@@ -287,7 +306,7 @@ function opencodeConfiguredBaseUrl(provider, namespace) {* *namespace* but a remote hosted API, so there is no local daemon to check.** @param {object|null|undefined} provider- * @returns {'llama'|'ollama'|'lmstudio'|'mtplx'|'vllm'|null}+ * @returns {'llama'|'ollama'|'lmstudio'|'mtplx'|'vllm'|'sglang'|null}*/export function localRuntimeKind(provider) {if (!provider || typeof provider !== 'object') return null;diff --git a/server/lib/localProviderRuntime.test.js b/server/lib/localProviderRuntime.test.jsindex 3b0cd3cba0..4dc3c27b07 100644--- a/server/lib/localProviderRuntime.test.js+++ b/server/lib/localProviderRuntime.test.js@@ -57,6 +57,7 @@ describe('localRuntimeKind', () => {expect(localRuntimeKind({ command: 'opencode', llamaBacked: true })).toBe('llama');expect(localRuntimeKind({ command: 'opencode', mtplxBacked: true })).toBe('mtplx');expect(localRuntimeKind({ command: 'opencode', vllmBacked: true })).toBe('vllm');+ expect(localRuntimeKind({ command: 'opencode', sglangBacked: true })).toBe('sglang');expect(localRuntimeKind({ command: 'opencode', ollamaBacked: true })).toBe('ollama');// claude-ollama is not an OpenCode provider but is still Ollama-backed.expect(localRuntimeKind({ command: 'claude', ollamaBacked: true })).toBe('ollama');diff --git a/server/lib/modelPricing.js b/server/lib/modelPricing.jsindex 25b9c05489..eabdd8775c 100644--- a/server/lib/modelPricing.js+++ b/server/lib/modelPricing.js@@ -297,7 +297,7 @@ export function isFreeProvider(providerOrId) {if (providerOrId == null) return false;if (typeof providerOrId === 'string') return FREE_ID.test(providerOrId);const p = providerOrId;- if (p.ollamaBacked === true || p.mtplxBacked === true || p.llamaBacked === true || p.vllmBacked === true) return true;+ if (p.ollamaBacked === true || p.mtplxBacked === true || p.llamaBacked === true || p.vllmBacked === true || p.sglangBacked === true) return true;if (FREE_ID.test(p.id || '') || FREE_ID.test(p.command || '')) return true;if (typeof p.endpoint === 'string' && LOCALHOST_ENDPOINT.test(p.endpoint.trim())) return true;return false;diff --git a/server/lib/opencodeConfig.js b/server/lib/opencodeConfig.jsindex 56d80c78b5..b31e9f05b8 100644--- a/server/lib/opencodeConfig.js+++ b/server/lib/opencodeConfig.js@@ -23,6 +23,7 @@ import { PORTS } from './ports.js';const LLAMA_SERVER_BASE_URL = `http://127.0.0.1:${PORTS.LLAMA_SERVER}/v1`;const VLLM_QWEN_BASE_URL = `http://127.0.0.1:${PORTS.VLLM_QWEN}/v1`;+const SGLANG_QWEN_BASE_URL = `http://127.0.0.1:${PORTS.SGLANG_QWEN}/v1`;/*** Base OpenCode provider entries for the local OpenAI-compatible daemons.@@ -50,6 +51,11 @@ const OPENCODE_LOCAL_BASE_PROVIDERS = {name: 'vLLM Qwen3.8-27B (local)',options: { baseURL: VLLM_QWEN_BASE_URL },},+ sglang: {+ npm: '@ai-sdk/openai-compatible',+ name: 'SGLang Qwen3.8-27B (local)',+ options: { baseURL: SGLANG_QWEN_BASE_URL },+ },orcarouter: {npm: '@ai-sdk/openai-compatible',name: 'OrcaRouter',@@ -62,7 +68,7 @@ const OPENCODE_LOCAL_BASE_PROVIDERS = {* — what a spawned OpenCode talks to when the provider stores no config of its* own. Read by `lib/localProviderRuntime.js` so the readiness probe and the* spawn agree on the endpoint instead of keeping two copies of these ports.- * @param {'ollama'|'mtplx'|'llama'|'vllm'|'orcarouter'} providerKey+ * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter'} providerKey* @returns {string|null}*/export const opencodeLocalBaseUrl = (providerKey) =>@@ -73,7 +79,7 @@ export const opencodeLocalBaseUrl = (providerKey) =>* else here is an unauthenticated loopback daemon, and attaching a key to those* would put a secret into a config file that never needed one.*/-const KEY_BEARING_NAMESPACES = new Set(['orcarouter', 'vllm']);+const KEY_BEARING_NAMESPACES = new Set(['orcarouter', 'vllm', 'sglang']);const localProviderBase = (providerKey) => {if (!Object.hasOwn(OPENCODE_LOCAL_BASE_PROVIDERS, providerKey)) {@@ -95,7 +101,7 @@ const stripProviderPrefix = (id, providerKey) =>* Normalize an id or list of ids to the unique, non-empty, prefix-stripped bare* model ids that key the OpenCode `models` map.* @param {string|string[]|null|undefined} models- * @param {'ollama'|'mtplx'|'llama'|'vllm'|'orcarouter'} [providerKey='ollama']+ * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter'} [providerKey='ollama']* @returns {string[]}*/export function toBareModelIds(models, providerKey = 'ollama') {@@ -126,7 +132,7 @@ export function toBareModelIds(models, providerKey = 'ollama') {* how vLLM shipped with no generation controls at all (#4765). Every local* runtime OpenCode can be pointed at needs a row here; `opencodeConfig.test.js`* walks `LOCAL_RUNTIMES` to make a missing one fail.- * @type {Record<'ollama'|'mtplx'|'llama'|'vllm'|'orcarouter', 'think'|'chatTemplate'|null>}+ * @type {Record<'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter', 'think'|'chatTemplate'|null>}*/const THINKING_STYLE = {ollama: 'think',@@ -135,6 +141,12 @@ const THINKING_STYLE = {// vLLM routes it through the chat template exactly as MTPLX and llama.cpp do// — see `server/services/voice/llm.js` for the same body shape on the HTTP side.vllm: 'chatTemplate',+ // SGLang serves Qwen3.8-27B with thinking ON by default, disabled per request+ // through the same `chat_template_kwargs.enable_thinking` the other local+ // OpenAI endpoints take. CoS coding wants it OFF (that is what keeps the+ // tool-call format reliable), so the control has to exist for the operator to+ // set — but nothing here SEEDS `thinking: false`, per #4716.+ sglang: 'chatTemplate',orcarouter: null,};@@ -162,7 +174,7 @@ const readBoolean = (value) =>* the provider.** @param {{temperature?:unknown, topP?:unknown, thinking?:unknown, effort?:unknown}|null|undefined} generation- * @param {'ollama'|'mtplx'|'llama'|'vllm'|'orcarouter'} providerKey+ * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter'} providerKey* @returns {object|null}*/export function buildAgentGeneration(generation, providerKey) {@@ -206,7 +218,7 @@ export function buildAgentGeneration(generation, providerKey) {** @param {string|string[]|null|undefined} models* @param {object|null} [base] - existing config to merge into (a fresh clone is made)- * @param {'ollama'|'mtplx'|'llama'|'vllm'|'orcarouter'} [providerKey='ollama']+ * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter'} [providerKey='ollama']* @returns {object} OpenCode config object*/export function buildOpencodeConfig(models, base = null, providerKey = 'ollama', generation = null) {@@ -245,7 +257,7 @@ export function buildOpencodeConfig(models, base = null, providerKey = 'ollama',** @param {string|string[]|null|undefined} models* @param {object|null} [base] - existing config to merge into- * @param {'ollama'|'mtplx'|'llama'|'vllm'|'orcarouter'} [providerKey='ollama']+ * @param {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter'} [providerKey='ollama']* @returns {string} JSON string for OPENCODE_CONFIG_CONTENT*/export function buildOpencodeConfigContent(models, base = null, providerKey = 'ollama', generation = null) {@@ -265,7 +277,7 @@ export function buildOpencodeConfigContent(models, base = null, providerKey = 'o* model, and the model being run this invocation — so whichever namespaced* `--model` the spawner passes is always accepted.*- * @param {{command?:string, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, orcarouterBacked?:boolean, models?:string[], defaultModel?:string|null, apiKey?:string, orcarouterApiKey?:string, envVars?:object}} provider+ * @param {{command?:string, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, sglangBacked?:boolean, orcarouterBacked?:boolean, models?:string[], defaultModel?:string|null, apiKey?:string, orcarouterApiKey?:string, envVars?:object}} provider* @param {string|null|undefined} model - the model being run (may differ from defaultModel)* @returns {{OPENCODE_CONFIG_CONTENT?: string}} env vars to merge*/diff --git a/server/lib/opencodeConfig.test.js b/server/lib/opencodeConfig.test.jsindex 511caab1e1..20262b9f0e 100644--- a/server/lib/opencodeConfig.test.js+++ b/server/lib/opencodeConfig.test.js@@ -346,15 +346,15 @@ describe('buildOpencodeEnvVars', () => {// the missing key and returns null, taking temperature, topP and// reasoningEffort with it. That is how the seeded vLLM providers shipped with// every generation control silently discarded (#4765). Walk LOCAL_RUNTIMES so a-// sixth runtime cannot land with the same hole.+// seventh runtime cannot land with the same hole.describe('every OpenCode-reachable local runtime forwards generation controls', () => {// LM Studio is skipped deliberately — nothing spawns OpenCode against it, so// it has no provider entry (and no base URL) in opencodeConfig's table.const opencodeRuntimes = Object.keys(LOCAL_RUNTIMES).filter((id) => opencodeLocalBaseUrl(id));it('actually walks the runtimes (a degenerate filter would pass vacuously)', () => {- expect(opencodeRuntimes).toContain('vllm');- expect(opencodeRuntimes.length).toBeGreaterThanOrEqual(4);+ expect(opencodeRuntimes).toEqual(expect.arrayContaining(['vllm', 'sglang']));+ expect(opencodeRuntimes.length).toBeGreaterThanOrEqual(5);});it.each(opencodeRuntimes)('%s', (id) => {@@ -362,3 +362,34 @@ describe('every OpenCode-reachable local runtime forwards generation controls',.toMatchObject({ temperature: 0.7, topP: 0.9, reasoningEffort: 'high' });});});++describe('SGLang OpenCode config', () => {+ it('declares the sglang namespace at the loopback container endpoint', () => {+ const result = buildOpencodeEnvVars(+ { command: 'opencode', sglangBacked: true, models: ['qwen3.8-27b'] },+ 'qwen3.8-27b',+ );+ const config = JSON.parse(result.OPENCODE_CONFIG_CONTENT);+ expect(config.provider.sglang.options.baseURL).toBe('http://127.0.0.1:18021/v1');+ expect(config.provider.sglang.models['qwen3.8-27b']).toEqual({ name: 'qwen3.8-27b', tool_call: true });+ });++ it('routes the thinking toggle through the chat template, like every other local endpoint', () => {+ expect(buildAgentGeneration({ thinking: false }, 'sglang'))+ .toEqual({ chat_template_kwargs: { enable_thinking: false } });+ });++ it('attaches an API key only when the operator set one', () => {+ // SGLang serves unauthenticated unless started with `--api-key`, so a blank+ // key must NOT put an empty `apiKey` into the spawned OpenCode config.+ const blank = JSON.parse(buildOpencodeEnvVars(+ { command: 'opencode', sglangBacked: true, apiKey: '', models: [] }, 'qwen3.8-27b',+ ).OPENCODE_CONFIG_CONTENT);+ expect(blank.provider.sglang.options).not.toHaveProperty('apiKey');++ const keyed = JSON.parse(buildOpencodeEnvVars(+ { command: 'opencode', sglangBacked: true, apiKey: 'operator-key', models: [] }, 'qwen3.8-27b',+ ).OPENCODE_CONFIG_CONTENT);+ expect(keyed.provider.sglang.options.apiKey).toBe('operator-key');+ });+});diff --git a/server/lib/ports.js b/server/lib/ports.jsindex 953b3c1e78..ae294c67ec 100644--- a/server/lib/ports.js+++ b/server/lib/ports.js@@ -17,6 +17,7 @@ export const PORTS = {POSTGRES_DOCKER: 5561, // PostgreSQL Docker container (host port mapping)LLAMA_SERVER: 5568, // Loopback llama.cpp speculative-decoding serverVLLM_QWEN: 18020, // Loopback vLLM Qwen3.8-27B (DFlash 2) container — operator-started, never by PortOS+ SGLANG_QWEN: 18021, // Loopback SGLang Qwen3.8-27B container (Hopper/Blackwell) — operator-started, never by PortOSPOSTGRES_NATIVE: 5432 // System PostgreSQL (PGMODE=native)};diff --git a/server/lib/providerFamilies.js b/server/lib/providerFamilies.jsindex c609f93e79..94355aeb03 100644--- a/server/lib/providerFamilies.js+++ b/server/lib/providerFamilies.js@@ -57,6 +57,6 @@ export const familyLabel = (id) => PROVIDER_FAMILIES.find((f) => f.id === id)?.l* provider's spend to the subscription that actually covered it.*/export function familyForProvider(provider) {- if (!provider || provider.ollamaBacked === true || provider.mtplxBacked === true || provider.llamaBacked === true || provider.vllmBacked === true) return null;+ if (!provider || provider.ollamaBacked === true || provider.mtplxBacked === true || provider.llamaBacked === true || provider.vllmBacked === true || provider.sglangBacked === true) return null;return PROVIDER_FAMILIES.find((f) => f.matches(provider))?.id ?? null;}diff --git a/server/lib/providerModels.js b/server/lib/providerModels.jsindex 5932749dd3..c4b50363c7 100644--- a/server/lib/providerModels.js+++ b/server/lib/providerModels.js@@ -556,7 +556,7 @@ export function isOpencodeCommand(command) {* already-qualified id (`openai/gpt-4o`, `anthropic/claude-sonnet`), and blindly* prefixing `ollama/` would route it to the wrong backend. No-op for* non-local / non-OpenCode providers and empty models.- * @param {{command?:string, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, orcarouterBacked?:boolean}} provider+ * @param {{command?:string, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, sglangBacked?:boolean, orcarouterBacked?:boolean}} provider* @param {string|null|undefined} model* @returns {string|null|undefined}*/@@ -575,14 +575,15 @@ export function prefixOpencodeModel(provider, model) {* opted into one. Structural markers avoid deriving a backend from an editable* display name or endpoint and preserve the legacy Ollama outcome if a malformed* record carries both markers.- * @param {{ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, orcarouterBacked?:boolean}|null|undefined} provider- * @returns {'ollama'|'mtplx'|'llama'|'vllm'|'orcarouter'|null}+ * @param {{ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, sglangBacked?:boolean, orcarouterBacked?:boolean}|null|undefined} provider+ * @returns {'ollama'|'mtplx'|'llama'|'vllm'|'sglang'|'orcarouter'|null}*/export function getOpencodeLocalProviderNamespace(provider) {if (provider?.ollamaBacked === true) return 'ollama';if (provider?.mtplxBacked === true) return 'mtplx';if (provider?.llamaBacked === true) return 'llama';if (provider?.vllmBacked === true) return 'vllm';+ if (provider?.sglangBacked === true) return 'sglang';if (provider?.orcarouterBacked === true) return 'orcarouter';return null;}diff --git a/server/lib/sglangQwenProject.js b/server/lib/sglangQwenProject.jsnew file mode 100644index 0000000000..b05abf0efd--- /dev/null+++ b/server/lib/sglangQwenProject.js@@ -0,0 +1,182 @@+/**+ * Where the SGLang Qwen3.8-27B compose project lives, and whether its weights+ * are already on disk.+ *+ * The sibling of `lib/vllmQwenProject.js`, for the same reason and with the same+ * hard rule: **a readiness check only reads directory entries.** It never runs+ * docker, contacts a registry, or reads a weight file. `docker compose up -d` in+ * an unprepared directory would pull a multi-gigabyte image and then ~20 GB of+ * weights — exactly the download PortOS promises never to start on its own.+ *+ * One thing differs from the vLLM path. There, the compose project is upstream's+ * (`syv-ai/qwen38-27b-rtx3090`) and the operator clones it. SGLang publishes an+ * official image and no compose project, so the launch line is PortOS's own:+ * `lib/sglangQwenRecipe.js` generates the `docker-compose.yml`, and+ * `docs/features/sglang-qwen38.md` carries it verbatim for the operator to save+ * into this directory. The refusals below therefore point at that doc rather+ * than at a `git clone`.+ *+ * **Sentinels matter here.** `hasWeights` is tri-state: `true` (a Qwen model+ * directory was found), `false` (every candidate root was readable and none held+ * one), `null` (no candidate root could be read at all). The start path treats+ * anything other than `true` as "not verified" and refuses — but the three cases+ * get different copy, because "your cache is empty" and "I cannot see your+ * cache" send the operator to different fixes. `null` is a real deployment+ * shape, not a bug: a cache kept in a docker named volume is invisible to a+ * PortOS running outside the container, and on Windows the project usually lives+ * inside a WSL2 distro. `SGLANG_QWEN_PROJECT_DIR` / `SGLANG_QWEN_WEIGHTS_DIR`+ * are the answers to those two cases respectively.+ */++import { readdir, stat } from 'fs/promises';+import { homedir } from 'os';+import { join } from 'path';++/** Operator override for where the compose project was created. */+export const SGLANG_PROJECT_DIR_ENV = 'SGLANG_QWEN_PROJECT_DIR';++/** Operator override for the HuggingFace cache holding the weights. */+export const SGLANG_WEIGHTS_DIR_ENV = 'SGLANG_QWEN_WEIGHTS_DIR';++/**+ * The user's home, read from the passed env before falling back to the OS — so+ * every path this module derives is injectable, and a test can never be answered+ * by the developer's real HuggingFace cache.+ */+const resolveHome = (env) =>+ String(env?.HOME || env?.USERPROFILE || '').trim() || homedir();++/** Where `docs/features/sglang-qwen38.md` tells the operator to create it. */+export const sglangDefaultProjectDir = (env = process.env) => join(resolveHome(env), 'sglang-qwen38');++/** Compose file names docker itself accepts, in its own precedence order. */+const COMPOSE_FILENAMES = ['docker-compose.yml', 'docker-compose.yaml', 'compose.yml', 'compose.yaml'];++/**+ * HuggingFace's hub cache names every repo directory `models--<org>--<repo>`.+ * Matching on `qwen` rather than an exact repo id is deliberate: the recipe+ * chooses between the FP8 and NVFP4 repos by card class, and an exact id would+ * report a perfectly prepared Blackwell host as empty.+ */+const QWEN_CACHE_ENTRY = /^models--.*qwen/i;++/** The `--local-dir` layout, for an operator who downloaded weights by hand. */+const QWEN_LOCAL_ENTRY = /qwen/i;++/**+ * What makes a `qwen`-named directory *weights* rather than a notes folder that+ * happens to share the name: a sharded download writes the index, a single-file+ * one writes the tensor file itself.+ */+const LOCAL_WEIGHT_MARKERS = ['model.safetensors.index.json', 'model.safetensors'];++const isDirectory = (path) => stat(path).then((s) => s.isDirectory(), () => false);+const isFile = (path) => stat(path).then((s) => s.isFile(), () => false);++/** The configured project directory, or the documented default. */+export function resolveSglangProjectDir(env = process.env) {+ const configured = String(env?.[SGLANG_PROJECT_DIR_ENV] || '').trim();+ return configured || sglangDefaultProjectDir(env);+}++/**+ * Candidate HuggingFace caches, most specific first: the operator's explicit+ * override, then the caches the compose file may bind-mount from the project+ * directory (the generated one uses `./hf-cache`), then `HF_HOME` and the+ * user-level default.+ */+function weightsCandidateRoots(projectDir, env = process.env) {+ const override = String(env?.[SGLANG_WEIGHTS_DIR_ENV] || '').trim();+ const hfHome = String(env?.HF_HOME || '').trim();+ return [+ ...(override ? [override] : []),+ join(projectDir, 'hf-cache', 'hub'),+ join(projectDir, 'hf-cache'),+ join(projectDir, 'models'),+ ...(hfHome ? [join(hfHome, 'hub')] : []),+ join(resolveHome(env), '.cache', 'huggingface', 'hub'),+ ];+}++/**+ * Whether one cache root holds Qwen weights, in either layout: a HuggingFace hub+ * entry, or a plainly-named `--local-dir` model directory.+ *+ * @param {string} root+ * @param {string[]} entries+ * @returns {Promise<boolean>}+ */+async function rootHoldsQwenWeights(root, entries) {+ if (entries.some((name) => QWEN_CACHE_ENTRY.test(name))) return true;+ for (const name of entries.filter((entry) => QWEN_LOCAL_ENTRY.test(entry))) {+ for (const marker of LOCAL_WEIGHT_MARKERS) {+ // eslint-disable-next-line no-await-in-loop -- two stats on a short, ordered candidate list+ if (await isFile(join(root, name, marker))) return true;+ }+ }+ return false;+}++/**+ * Inspect the operator's SGLang project without touching docker.+ *+ * @param {NodeJS.ProcessEnv} [env]+ * @returns {Promise<{dir:string, hasProject:boolean, composeFile:string|null,+ * hasWeights:boolean|null, weightsRoot:string|null}>}+ */+export async function inspectSglangQwenProject(env = process.env) {+ const dir = resolveSglangProjectDir(env);+ const hasProject = await isDirectory(dir);++ let composeFile = null;+ if (hasProject) {+ for (const name of COMPOSE_FILENAMES) {+ // eslint-disable-next-line no-await-in-loop -- four stats on one directory+ if (await isFile(join(dir, name))) { composeFile = name; break; }+ }+ }++ let readAnyRoot = false;+ let weightsRoot = null;+ for (const root of weightsCandidateRoots(dir, env)) {+ // eslint-disable-next-line no-await-in-loop -- short, ordered, first-match-wins+ const entries = await readdir(root).catch(() => null);+ if (entries === null) continue; // absent or unreadable — says nothing either way+ readAnyRoot = true;+ // eslint-disable-next-line no-await-in-loop -- short, ordered, first-match-wins+ if (await rootHoldsQwenWeights(root, entries)) { weightsRoot = root; break; }+ }++ return {+ dir,+ hasProject,+ composeFile,+ // `null` = no candidate cache could be read, which is NOT "no weights".+ hasWeights: weightsRoot ? true : (readAnyRoot ? false : null),+ weightsRoot,+ };+}++/**+ * Why the start button must not run compose, or `null` when it may. Prose, not a+ * code — the checklist renders it verbatim, and each case names the one thing+ * that fixes it.+ *+ * @param {{dir:string, hasProject:boolean, composeFile:string|null, hasWeights:boolean|null}} project+ * @returns {string|null}+ */+export function sglangStartBlockedReason(project) {+ if (!project?.hasProject) {+ return `no SGLang project directory was found at ${project?.dir}. Create it (or set ${SGLANG_PROJECT_DIR_ENV}), save the docker-compose.yml from docs/features/sglang-qwen38.md into it, and pull the weights once — PortOS never downloads the image or the ~20 GB of weights.`;+ }+ if (!project.composeFile) {+ return `${project.dir} exists but holds no docker-compose file. Save the one from docs/features/sglang-qwen38.md there — it carries the verified launch line, including the tool-call and reasoning parsers an agent cannot work without.`;+ }+ if (project.hasWeights === false) {+ return 'the compose file is in place but no Qwen weights are cached yet. Download them in a terminal first — starting compose now would pull roughly 20 GB, which PortOS will not do for you.';+ }+ if (project.hasWeights === null) {+ return `PortOS cannot read a HuggingFace cache for this project, so it cannot confirm the weights are already downloaded. Set ${SGLANG_WEIGHTS_DIR_ENV} to the directory holding them (a docker named volume is invisible from here), or start it yourself with \`docker compose up -d\` in ${project.dir}.`;+ }+ return null;+}diff --git a/server/lib/sglangQwenProject.test.js b/server/lib/sglangQwenProject.test.jsnew file mode 100644index 0000000000..ea49dc625f--- /dev/null+++ b/server/lib/sglangQwenProject.test.js@@ -0,0 +1,115 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import {+ inspectSglangQwenProject,+ resolveSglangProjectDir,+ sglangDefaultProjectDir,+ sglangStartBlockedReason,+ SGLANG_PROJECT_DIR_ENV,+ SGLANG_WEIGHTS_DIR_ENV,+} from './sglangQwenProject.js';++let root;+/**+ * A fully injected env — HOME/USERPROFILE included — so no assertion here can+ * ever be answered by the developer's real HuggingFace cache.+ */+const envAt = (overrides = {}) => ({ HOME: root, USERPROFILE: root, ...overrides });++beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'sglang-project-')); });+afterEach(() => rmSync(root, { recursive: true, force: true }));++describe('resolveSglangProjectDir', () => {+ it('defaults to ~/sglang-qwen38', () => {+ expect(resolveSglangProjectDir(envAt())).toBe(sglangDefaultProjectDir(envAt()));+ expect(resolveSglangProjectDir(envAt())).toBe(join(root, 'sglang-qwen38'));+ });++ it('honors the override, ignoring a blank one', () => {+ expect(resolveSglangProjectDir(envAt({ [SGLANG_PROJECT_DIR_ENV]: '/srv/sglang' }))).toBe('/srv/sglang');+ expect(resolveSglangProjectDir(envAt({ [SGLANG_PROJECT_DIR_ENV]: ' ' }))).toBe(join(root, 'sglang-qwen38'));+ });+});++describe('inspectSglangQwenProject', () => {+ it('reports an absent project without claiming anything about weights', async () => {+ const project = await inspectSglangQwenProject(envAt());+ expect(project).toMatchObject({ hasProject: false, composeFile: null, weightsRoot: null });+ // No cache root was readable, so `hasWeights` must be the null sentinel —+ // NOT `false`, which would claim the caches were read and found empty.+ expect(project.hasWeights).toBeNull();+ });++ it('finds a compose file in docker\'s own precedence order', async () => {+ const dir = join(root, 'sglang-qwen38');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'compose.yaml'), '');+ expect((await inspectSglangQwenProject(envAt())).composeFile).toBe('compose.yaml');+ writeFileSync(join(dir, 'docker-compose.yml'), '');+ expect((await inspectSglangQwenProject(envAt())).composeFile).toBe('docker-compose.yml');+ });++ it('distinguishes a readable-but-empty cache from an unreadable one', async () => {+ const dir = join(root, 'sglang-qwen38');+ mkdirSync(join(dir, 'hf-cache'), { recursive: true });+ const project = await inspectSglangQwenProject(envAt());+ expect(project.hasWeights).toBe(false);+ expect(project.weightsRoot).toBeNull();+ });++ it('detects the HuggingFace hub layout', async () => {+ const hub = join(root, 'sglang-qwen38', 'hf-cache', 'hub');+ mkdirSync(join(hub, 'models--Qwen--Qwen3.8-27B-FP8'), { recursive: true });+ const project = await inspectSglangQwenProject(envAt());+ expect(project).toMatchObject({ hasWeights: true, weightsRoot: hub });+ });++ it('detects a --local-dir download, but only with a real weight file in it', async () => {+ const models = join(root, 'sglang-qwen38', 'models');+ mkdirSync(join(models, 'Qwen3.8-27B-FP8'), { recursive: true });+ // A directory named after the model but holding no tensors is notes, not weights.+ expect((await inspectSglangQwenProject(envAt())).hasWeights).toBe(false);+ writeFileSync(join(models, 'Qwen3.8-27B-FP8', 'model.safetensors.index.json'), '{}');+ expect((await inspectSglangQwenProject(envAt())).hasWeights).toBe(true);+ });++ it('checks the explicit weights override first', async () => {+ const elsewhere = join(root, 'elsewhere');+ mkdirSync(join(elsewhere, 'models--Qwen--Qwen3.8-27B-NVFP4'), { recursive: true });+ const project = await inspectSglangQwenProject(envAt({ [SGLANG_WEIGHTS_DIR_ENV]: elsewhere }));+ expect(project).toMatchObject({ hasWeights: true, weightsRoot: elsewhere });+ });+});++describe('sglangStartBlockedReason', () => {+ const base = { dir: '/srv/sglang', hasProject: true, composeFile: 'docker-compose.yml', hasWeights: true };++ it('allows a fully prepared project', () => {+ expect(sglangStartBlockedReason(base)).toBeNull();+ });++ it('names the project dir and the doc when the directory is missing', () => {+ const reason = sglangStartBlockedReason({ ...base, hasProject: false });+ expect(reason).toContain('/srv/sglang');+ expect(reason).toContain('docs/features/sglang-qwen38.md');+ });++ it('points at the doc\'s compose file when only that is missing', () => {+ expect(sglangStartBlockedReason({ ...base, composeFile: null }))+ .toContain('docs/features/sglang-qwen38.md');+ });++ it('gives the empty-cache and unreadable-cache cases DIFFERENT copy', () => {+ // The whole point of the tri-state: "your cache is empty" and "I cannot see+ // your cache" send the operator to different fixes.+ const empty = sglangStartBlockedReason({ ...base, hasWeights: false });+ const unknown = sglangStartBlockedReason({ ...base, hasWeights: null });+ expect(empty).toMatch(/no Qwen weights are cached yet/);+ expect(unknown).toMatch(/cannot read a HuggingFace cache/);+ expect(unknown).toContain(SGLANG_WEIGHTS_DIR_ENV);+ expect(empty).not.toBe(unknown);+ });+});diff --git a/server/lib/sglangQwenRecipe.js b/server/lib/sglangQwenRecipe.jsnew file mode 100644index 0000000000..9e9636d389--- /dev/null+++ b/server/lib/sglangQwenRecipe.js@@ -0,0 +1,364 @@+/**+ * The SGLang Qwen3.8-27B launch line PortOS owns, per NVIDIA card class.+ *+ * Unlike the RTX 3090 vLLM path — where the compose project is upstream's and+ * PortOS never sees the flags (`lib/vllmQwenProject.js`) — SGLang ships as an+ * official image (`lmsysorg/sglang:qwen38-27b`) with no compose project of its+ * own. The launch line is therefore ours, and this module is it: a pure table of+ * the cookbook's verified cells plus the one derived number the cookbook says+ * actually matters.+ *+ * **Three flags are load-bearing and silent when wrong.**+ *+ * - `--tool-call-parser qwen3_coder` — SGLang's spelling. vLLM's is+ * `qwen3_xml`. Get it wrong (or omit it) and the server starts, answers, and+ * returns raw markup with no `tool_calls` block: the agent narrates edits it+ * never makes. This is the exact failure the 3090 bring-up hit, and the+ * reason both parsers are baked into every cell below rather than left to an+ * `EXTRA_ARGS` line an operator can forget.+ * - `--reasoning-parser qwen3` — same class of failure for the thinking block.+ * - `--mamba-full-memory-ratio` — see `mambaFullMemoryRatio` below. The+ * cookbook default (`0.9`) under-sizes the GDN state pool for CoS-length+ * prompts and silently clamps `max_running_requests` below the concurrency+ * you asked for. It is derived here, not defaulted.+ *+ * **What is verified and what is derived.** The `h200` cell is transcribed+ * flag-for-flag from the cookbook cell recorded in+ * `docs/research/2026-08-21-sglang-qwen38-27b.md` (`hw=h200, variant=default,+ * quant=fp8, nodes=single, spec=none, tier=low-latency, ssmDtype=float32`), and+ * `sglangQwenRecipe.test.js` pins it so changing a verified flag fails. The two+ * Blackwell cells carry only what that same note records about them (NVFP4+ * quantization; `--max-running-requests 1` on a 32 GB 5090) and deliberately+ * OMIT H200's 32k prefill overrides rather than inventing a number for a cell+ * nobody has measured here — SGLang's own defaults are the honest answer, and+ * `verified: false` says so on the record. Operator bring-up on real Blackwell+ * hardware is expected to refine them (see `docs/features/sglang-qwen38.md`).+ *+ * Speculative overlays (EAGLE/MTP, DSPARK, DFLASH2) are deliberately absent from+ * every default. DFLASH2 in particular needs an SGLang newer than the pinned+ * image; `SPEC_VERIFY_SLOTS` exists so the ratio arithmetic stays correct if a+ * later change adds one, not because one is offered today.+ *+ * Pure: no filesystem, no docker, no network. `lib/sglangQwenProject.js` owns+ * "is this host prepared", and `services/localRuntimeSetup.js` owns starting it.+ */++import { PORTS } from './ports.js';++/** The official image. PortOS never builds an engine — same bar as the vLLM path. */+export const SGLANG_QWEN_IMAGE = 'lmsysorg/sglang:qwen38-27b';++/** The model id PortOS declares to OpenCode, independent of the quantized repo. */+export const SGLANG_QWEN_MODEL_ALIAS = 'qwen3.8-27b';++/**+ * Bytes of GDN state per slot, by SSM dtype, in MB — this checkpoint's geometry+ * (64 layers: 48 Gated DeltaNet + 16 full-attention GQA).+ */+const SSM_STATE_MB = Object.freeze({ float32: 153.9, bfloat16: 78.4 });++/** Paged-attention KV bytes per token, by KV cache dtype, in KB. */+const KV_KB_PER_TOKEN = Object.freeze({ fp8_e4m3: 32.8, bfloat16: 65.5 });++/**+ * `S` in the ratio formula — GDN state slots held per running request, by radix+ * cache strategy. `extra_buffer` is the low-latency strategy CoS wants: TTFT on+ * a warm prefix is the number a TUI tool-loop lives on, and the 3090 bring-up+ * measured a 24x collapse when the prefix cache actually hits.+ */+const RADIX_STATE_SLOTS = Object.freeze({+ extra_buffer: 5,+ extra_buffer_lazy: 4,+ off: 1,+});++/** `D` — speculative verify intermediates. Zero with speculation off. */+const SPEC_VERIFY_SLOTS = Object.freeze({+ none: 0,+ eagle: 4,+ dspark: 8,+ dflash2: 8,+});++/**+ * The average total request length (input + output) PortOS sizes the GDN state+ * pool for. The 3090 bring-up's measured 17k-token agent prefix is the data+ * point; 20k rounds it up to leave room for the reply without over-reserving.+ */+export const COS_CONTEXT_LENGTH = 20_000;++/**+ * `--mamba-full-memory-ratio`: GDN state-pool memory as a ratio of paged KV-cache+ * memory, from the cookbook formula+ *+ * ratio = (S + D) x state_bytes / (L x kv_bytes_per_token)+ *+ * It is a RATIO between two pools, not a fraction of one — values above 1 are+ * normal and expected at CoS prompt lengths, where the per-request state pool+ * legitimately outweighs the KV a single 20k-token request needs.+ *+ * Concurrency deliberately does not appear: both sides of the fraction scale+ * with it, so it cancels. Concurrency is pinned separately via+ * `--max-mamba-cache-size` (`concurrency x S`), which is why `stateSlots` is+ * returned alongside — a caller sizing that flag needs `S`, not a second copy of+ * this table.+ *+ * @param {{contextLength?:number, ssmDtype?:string, kvCacheDtype?:string,+ * radixStrategy?:string, spec?:string}} [opts]+ * @returns {{ratio:number, stateSlots:number, verifySlots:number}}+ */+export function mambaFullMemoryRatio({+ contextLength = COS_CONTEXT_LENGTH,+ ssmDtype = 'float32',+ kvCacheDtype = 'fp8_e4m3',+ radixStrategy = 'extra_buffer',+ spec = 'none',+} = {}) {+ const stateMb = SSM_STATE_MB[ssmDtype];+ const kvKb = KV_KB_PER_TOKEN[kvCacheDtype];+ const stateSlots = RADIX_STATE_SLOTS[radixStrategy];+ const verifySlots = SPEC_VERIFY_SLOTS[spec];+ if (stateMb === undefined) throw new Error(`Unknown SSM dtype '${ssmDtype}'`);+ if (kvKb === undefined) throw new Error(`Unknown KV cache dtype '${kvCacheDtype}'`);+ if (stateSlots === undefined) throw new Error(`Unknown mamba radix strategy '${radixStrategy}'`);+ if (verifySlots === undefined) throw new Error(`Unknown speculative algorithm '${spec}'`);+ if (!Number.isFinite(contextLength) || contextLength <= 0) {+ throw new Error(`Context length must be a positive number, got '${contextLength}'`);+ }++ // One unit (KB) on both sides, so the MB->KB conversion is stated once.+ const stateKb = (stateSlots + verifySlots) * stateMb * 1024;+ const kvTotalKb = contextLength * kvKb;+ // Three decimals: the flag is a memory-sizing hint, and pinning more digits+ // would make the test assert floating-point noise rather than the recipe.+ return { ratio: Math.round((stateKb / kvTotalKb) * 1000) / 1000, stateSlots, verifySlots };+}++/**+ * One row per NVIDIA card class the cookbook publishes a single-GPU cell for.+ *+ * `chunkedPrefillSize` / `maxPrefillTokens` are `null` on the unverified cells —+ * absent, not zero — so `buildSglangQwenRecipe` omits the flags and SGLang picks+ * its own default. Handing a 32 GB 5090 the H200 cell's 32k prefill chunks is+ * the specific mistake this table exists to prevent.+ */+const HARDWARE_CELLS = Object.freeze({+ h200: Object.freeze({+ id: 'h200',+ label: 'NVIDIA H200 / H100 (SM90 Hopper)',+ verified: true,+ quant: 'fp8',+ modelPath: 'Qwen/Qwen3.8-27B-FP8',+ kvCacheDtype: 'fp8_e4m3',+ memFractionStatic: 0.85,+ attentionBackend: 'flashinfer',+ chunkedPrefillSize: 32768,+ maxPrefillTokens: 32768,+ maxRunningRequests: null,+ }),+ rtx6000: Object.freeze({+ id: 'rtx6000',+ label: 'NVIDIA RTX PRO 6000 Blackwell (96 GB)',+ verified: false,+ // Blackwell has FP4 tensor cores; the cookbook's Blackwell cells use NVFP4.+ quant: 'nvfp4',+ modelPath: 'Qwen/Qwen3.8-27B-NVFP4',+ kvCacheDtype: 'fp8_e4m3',+ memFractionStatic: 0.85,+ attentionBackend: 'flashinfer',+ chunkedPrefillSize: null,+ maxPrefillTokens: null,+ maxRunningRequests: null,+ }),+ rtx5090: Object.freeze({+ id: 'rtx5090',+ label: 'NVIDIA RTX 5090 Blackwell (32 GB)',+ verified: false,+ quant: 'nvfp4',+ modelPath: 'Qwen/Qwen3.8-27B-NVFP4',+ kvCacheDtype: 'fp8_e4m3',+ memFractionStatic: 0.85,+ attentionBackend: 'flashinfer',+ chunkedPrefillSize: null,+ maxPrefillTokens: null,+ // 32 GB leaves the GDN state pool as the binding constraint, so the+ // cookbook's 5090 cell serializes requests rather than clamping them later.+ maxRunningRequests: 1,+ }),+});++/** Card classes with a cell here, most capable first. */+export const SGLANG_HARDWARE_IDS = Object.freeze(Object.keys(HARDWARE_CELLS));++/** One hardware cell, or `null` for an id with no recipe. */+export const sglangHardwareCell = (hw) => HARDWARE_CELLS[hw] ?? null;++/**+ * Which cell (if any) a detected GPU should run, from `cudaCapability.js`'s+ * `parseNvidiaSmiComputeCaps` shape.+ *+ * Compute capability is the primary signal because it is the one column that+ * distinguishes the arches PortOS cares about: SM 8.x is Ampere (which stays on+ * the vLLM container — the cookbook has no 3090 cell), 9.x is Hopper, 10.x/12.x+ * is Blackwell. VRAM only splits the two Blackwell cells apart.+ *+ * Returns `null` for every card without a cell — including Ampere, which is a+ * REFUSAL rather than a gap: `sglangUnsupportedReason` names the vLLM path.+ *+ * @param {{computeCap?:string|null, vramGb?:number|null}|null|undefined} gpu+ * @returns {string|null} a key of `HARDWARE_CELLS`+ */+export function sglangCellForGpu(gpu) {+ const major = Number.parseInt(String(gpu?.computeCap ?? '').split('.')[0], 10);+ if (!Number.isFinite(major)) return null;+ if (major === 9) return 'h200';+ // Blackwell consumer (12.x) and datacenter (10.x) both take the NVFP4 cells;+ // the 96 GB card is the only one with headroom for concurrent requests.+ if (major >= 10) return Number.isFinite(gpu?.vramGb) && gpu.vramGb >= 48 ? 'rtx6000' : 'rtx5090';+ return null;+}++/**+ * Why this host cannot run the SGLang stack, or `null` when it can. Prose the+ * readiness checklist renders verbatim, so each case names where the operator+ * should go instead.+ *+ * The `'unknown'` probe status is NOT collapsed into "no GPU": a wedged or+ * ancient `nvidia-smi` says nothing about the hardware, and telling an H200+ * owner they have no NVIDIA card would send them to the wrong fix entirely.+ *+ * @param {{platform?:string, status?:string, gpus?:Array<object>}} [host]+ * @returns {string|null}+ */+export function sglangUnsupportedReason({ platform = process.platform, status, gpus = [] } = {}) {+ if (platform === 'darwin') {+ return 'The SGLang Qwen3.8-27B stack needs an NVIDIA Hopper or Blackwell GPU and a Linux container runtime. On Apple Silicon use the MTPLX or llama.cpp DSpark presets instead.';+ }+ if (status === 'absent') {+ return 'No NVIDIA GPU was detected on this host, so there is no card to give the SGLang container.';+ }+ if (status === 'unknown') {+ return 'PortOS could not read this host\'s NVIDIA GPUs (`nvidia-smi` is installed but would not answer), so it cannot tell whether the SGLang recipe fits this card. Fix the driver — or start the container yourself following docs/features/sglang-qwen38.md — rather than reading this as "no GPU".';+ }+ if (status === 'available' && !(Array.isArray(gpus) ? gpus : []).some((gpu) => sglangCellForGpu(gpu))) {+ return 'The SGLang Qwen3.8-27B cookbook publishes no recipe for this card. Ampere 24 GB (RTX 3090) is served by the vLLM container instead — see docs/features/qwen38-rtx3090.md.';+ }+ return null;+}++/** Push `--flag value` only when the value is set. Keeps the cell table's nulls honest. */+const flagIf = (flag, value) => (value === null || value === undefined ? [] : [flag, String(value)]);++/**+ * The full `sglang serve` argv for one card class.+ *+ * `host` defaults to loopback, NOT the cookbook's `0.0.0.0`: PortOS binds local+ * daemons to `127.0.0.1` and lets the peer/auth layer decide what leaves the+ * machine (`docs/PORTS.md`).+ *+ * @param {{hw?:string, contextLength?:number, ssmDtype?:string, spec?:string,+ * radixStrategy?:string, host?:string, port?:number}} [opts]+ * @returns {{image:string, modelName:string, modelPath:string, cell:object,+ * mambaRatio:number, stateSlots:number, flags:string[], env:object}}+ */+export function buildSglangQwenRecipe({+ hw = 'h200',+ contextLength = COS_CONTEXT_LENGTH,+ ssmDtype = 'float32',+ spec = 'none',+ radixStrategy = 'extra_buffer',+ host = '127.0.0.1',+ port,+} = {}) {+ const cell = sglangHardwareCell(hw);+ if (!cell) throw new Error(`No SGLang recipe for hardware '${hw}'`);+ const { ratio, stateSlots } = mambaFullMemoryRatio({+ contextLength, ssmDtype, kvCacheDtype: cell.kvCacheDtype, radixStrategy, spec,+ });++ return {+ image: SGLANG_QWEN_IMAGE,+ modelName: SGLANG_QWEN_MODEL_ALIAS,+ modelPath: cell.modelPath,+ cell,+ mambaRatio: ratio,+ stateSlots,+ flags: [+ // The checkpoint is served through the Qwen3-VL path, which needs its+ // repo-side modeling code.+ '--trust-remote-code',+ '--model-path', cell.modelPath,+ '--kv-cache-dtype', cell.kvCacheDtype,+ '--mem-fraction-static', String(cell.memFractionStatic),+ '--attention-backend', cell.attentionBackend,+ ...flagIf('--chunked-prefill-size', cell.chunkedPrefillSize),+ ...flagIf('--max-prefill-tokens', cell.maxPrefillTokens),+ ...flagIf('--max-running-requests', cell.maxRunningRequests),+ // Both parsers, always. See the file header for the silent failure.+ '--reasoning-parser', 'qwen3',+ '--tool-call-parser', 'qwen3_coder',+ '--mamba-radix-cache-strategy', radixStrategy,+ '--mamba-ssm-dtype', ssmDtype,+ '--mamba-full-memory-ratio', String(ratio),+ '--host', host,+ '--port', String(port ?? PORTS.SGLANG_QWEN),+ ],+ // Left to the operator's `.env`: HF_TOKEN for a gated repo, and SGLANG_API_KEY+ // only if they chose to run `--api-key`. PortOS ships no secret here.+ env: {},+ };+}++/** Indent a block of YAML list items under a key. */+const yamlList = (items, indent) => items.map((item) => `${indent}- ${item}`).join('\n');++/**+ * The `docker-compose.yml` for one recipe, generated rather than shipped as a+ * static asset so the launch line has exactly one source of truth. Mirrors the+ * cookbook's docker stanza (`ipc: host`, a 32 GB shm, all GPUs, an HF cache+ * volume) minus host networking — the port is published on loopback instead.+ *+ * The published port is read back out of the recipe's own `--port` flag rather+ * than taken as an argument, so the host mapping and the server's bind address+ * cannot drift into disagreeing about which port the container answers on.+ *+ * `docs/features/sglang-qwen38.md` embeds this verbatim for the H200 cell, and+ * `sglangQwenRecipe.test.js` fails if the doc and this function drift.+ *+ * @param {ReturnType<typeof buildSglangQwenRecipe>} recipe+ * @returns {string}+ */+export function sglangComposeYaml(recipe) {+ const port = recipe.flags[recipe.flags.indexOf('--port') + 1];+ const flags = recipe.flags.map((flag) => JSON.stringify(flag));+ return [+ 'services:',+ ' sglang-qwen38:',+ ` image: ${recipe.image}`,+ ' container_name: sglang-qwen38',+ ' restart: "no"',+ ' ipc: host',+ ' shm_size: "32g"',+ ' ports:',+ ` - "127.0.0.1:${port}:${port}"`,+ ' volumes:',+ ' - ${HF_HOME:-./hf-cache}:/root/.cache/huggingface',+ ' environment:',+ ' - HF_TOKEN=${HF_TOKEN:-}',+ ' deploy:',+ ' resources:',+ ' reservations:',+ ' devices:',+ ' - driver: nvidia',+ ' count: all',+ ' capabilities: ["gpu"]',+ // Split entrypoint/command rather than one argv: whether the image already+ // sets an entrypoint is not something PortOS should have to guess at, and+ // naming `sglang` explicitly makes the launch line work either way.+ ' entrypoint: ["sglang"]',+ ' command:',+ ' - "serve"',+ yamlList(flags, ' '),+ '',+ ].join('\n');+}diff --git a/server/lib/sglangQwenRecipe.test.js b/server/lib/sglangQwenRecipe.test.jsnew file mode 100644index 0000000000..5297911def--- /dev/null+++ b/server/lib/sglangQwenRecipe.test.js@@ -0,0 +1,221 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';+import { join } from 'path';+import { fileURLToPath } from 'url';++import {+ SGLANG_QWEN_IMAGE,+ buildSglangQwenRecipe,+ mambaFullMemoryRatio,+ sglangCellForGpu,+ sglangComposeYaml,+ sglangHardwareCell,+ sglangUnsupportedReason,+ SGLANG_HARDWARE_IDS,+} from './sglangQwenRecipe.js';+import { PORTS } from './ports.js';++const repoRoot = join(fileURLToPath(new URL('.', import.meta.url)), '..', '..');++describe('mambaFullMemoryRatio', () => {+ // The one number the cookbook says actually matters. Pinned arithmetic, not a+ // range: a silent change here re-sizes the GDN state pool on every host.+ it('derives the CoS operating point (L=20000, spec off, fp32 SSM, fp8 KV)', () => {+ // (5 slots + 0 verify) × 153.9 MB × 1024 KB/MB ÷ (20000 × 32.8 KB) = 1.201…+ expect(mambaFullMemoryRatio()).toEqual({ ratio: 1.201, stateSlots: 5, verifySlots: 0 });+ });++ it('is above the cookbook default of 0.9 at CoS prompt lengths', () => {+ // This is the whole reason the flag is derived rather than defaulted: 0.9+ // under-sizes the state pool here and silently clamps max_running_requests.+ expect(mambaFullMemoryRatio().ratio).toBeGreaterThan(0.9);+ });++ it('roughly halves with a bf16 SSM state, and again with a bf16 KV cache', () => {+ // Neither is exactly half — 78.4/153.9 and 32.8/65.5 are the checkpoint's+ // real geometry, not round numbers — so the values are pinned, not derived.+ expect(mambaFullMemoryRatio({ ssmDtype: 'bfloat16' }).ratio).toBe(0.612);+ expect(mambaFullMemoryRatio({ kvCacheDtype: 'bfloat16' }).ratio).toBe(0.602);+ });++ it('scales down as the sized request length grows', () => {+ expect(mambaFullMemoryRatio({ contextLength: 40_000 }).ratio)+ .toBeCloseTo(mambaFullMemoryRatio({ contextLength: 20_000 }).ratio / 2, 3);+ });++ it('adds the speculative verify slots for an MTP overlay', () => {+ expect(mambaFullMemoryRatio({ spec: 'eagle' })).toMatchObject({ stateSlots: 5, verifySlots: 4 });+ expect(mambaFullMemoryRatio({ spec: 'eagle' }).ratio)+ .toBeCloseTo(mambaFullMemoryRatio().ratio * 9 / 5, 3);+ });++ it('takes fewer state slots when the radix cache is off or lazy', () => {+ expect(mambaFullMemoryRatio({ radixStrategy: 'off' }).stateSlots).toBe(1);+ expect(mambaFullMemoryRatio({ radixStrategy: 'extra_buffer_lazy' }).stateSlots).toBe(4);+ });++ it('throws rather than guessing on an unknown dtype, strategy, or length', () => {+ expect(() => mambaFullMemoryRatio({ ssmDtype: 'fp16' })).toThrow(/SSM dtype/);+ expect(() => mambaFullMemoryRatio({ kvCacheDtype: 'int4' })).toThrow(/KV cache dtype/);+ expect(() => mambaFullMemoryRatio({ radixStrategy: 'lru' })).toThrow(/radix strategy/);+ expect(() => mambaFullMemoryRatio({ spec: 'medusa' })).toThrow(/speculative algorithm/);+ expect(() => mambaFullMemoryRatio({ contextLength: 0 })).toThrow(/positive number/);+ });+});++describe('buildSglangQwenRecipe — the verified H200 cell', () => {+ // Transcribed from the cookbook cell recorded in+ // docs/research/2026-08-21-sglang-qwen38-27b.md. Changing a verified flag must+ // fail here, not surface as a container that starts and never calls a tool.+ it('pins the whole launch line', () => {+ expect(buildSglangQwenRecipe({ hw: 'h200' })).toMatchObject({+ image: 'lmsysorg/sglang:qwen38-27b',+ modelName: 'qwen3.8-27b',+ modelPath: 'Qwen/Qwen3.8-27B-FP8',+ mambaRatio: 1.201,+ flags: [+ '--trust-remote-code',+ '--model-path', 'Qwen/Qwen3.8-27B-FP8',+ '--kv-cache-dtype', 'fp8_e4m3',+ '--mem-fraction-static', '0.85',+ '--attention-backend', 'flashinfer',+ '--chunked-prefill-size', '32768',+ '--max-prefill-tokens', '32768',+ '--reasoning-parser', 'qwen3',+ '--tool-call-parser', 'qwen3_coder',+ '--mamba-radix-cache-strategy', 'extra_buffer',+ '--mamba-ssm-dtype', 'float32',+ '--mamba-full-memory-ratio', '1.201',+ '--host', '127.0.0.1',+ '--port', '18021',+ ],+ });+ });++ it('binds loopback on the PortOS port, not the cookbook 0.0.0.0:30000', () => {+ const { flags } = buildSglangQwenRecipe();+ expect(flags[flags.indexOf('--host') + 1]).toBe('127.0.0.1');+ expect(flags[flags.indexOf('--port') + 1]).toBe(String(PORTS.SGLANG_QWEN));+ });++ it('never defaults a speculative overlay', () => {+ expect(buildSglangQwenRecipe().flags).not.toContain('--speculative-algorithm');+ });+});++describe('buildSglangQwenRecipe — every cell', () => {+ it.each(SGLANG_HARDWARE_IDS)('%s bakes in both Qwen parsers', (hw) => {+ // The silent failure this whole table exists to prevent: the wrong (or a+ // missing) tool-call parser makes the server answer with raw markup and the+ // agent never edits a file. `qwen3_xml` is vLLM's spelling, not SGLang's.+ const { flags } = buildSglangQwenRecipe({ hw });+ expect(flags[flags.indexOf('--tool-call-parser') + 1]).toBe('qwen3_coder');+ expect(flags[flags.indexOf('--reasoning-parser') + 1]).toBe('qwen3');+ expect(flags).not.toContain('qwen3_xml');+ });++ it.each(SGLANG_HARDWARE_IDS)('%s derives the mamba ratio rather than leaving 0.9', (hw) => {+ const { flags, mambaRatio } = buildSglangQwenRecipe({ hw });+ expect(flags[flags.indexOf('--mamba-full-memory-ratio') + 1]).toBe(String(mambaRatio));+ expect(mambaRatio).not.toBe(0.9);+ });++ it('does not hand a 32 GB 5090 the H200 cell\'s 32k prefill chunks', () => {+ const { flags } = buildSglangQwenRecipe({ hw: 'rtx5090' });+ expect(flags).not.toContain('--chunked-prefill-size');+ expect(flags).not.toContain('--max-prefill-tokens');+ // The 5090's binding constraint is the GDN state pool, so it serializes.+ expect(flags[flags.indexOf('--max-running-requests') + 1]).toBe('1');+ });++ it('marks only the H200 cell as cookbook-verified', () => {+ expect(sglangHardwareCell('h200').verified).toBe(true);+ expect(sglangHardwareCell('rtx5090').verified).toBe(false);+ expect(sglangHardwareCell('rtx6000').verified).toBe(false);+ });++ it('throws for a card class with no recipe', () => {+ expect(() => buildSglangQwenRecipe({ hw: 'rtx3090' })).toThrow(/No SGLang recipe/);+ });+});++describe('sglangCellForGpu', () => {+ it('routes SM90 Hopper to the H200 cell', () => {+ expect(sglangCellForGpu({ computeCap: '9.0', vramGb: 141 })).toBe('h200');+ });++ it('splits Blackwell by VRAM', () => {+ expect(sglangCellForGpu({ computeCap: '12.0', vramGb: 32 })).toBe('rtx5090');+ expect(sglangCellForGpu({ computeCap: '12.0', vramGb: 96 })).toBe('rtx6000');+ });++ it('refuses Ampere — the cookbook has no 3090 cell, and 24 GB stays on vLLM', () => {+ expect(sglangCellForGpu({ computeCap: '8.6', vramGb: 24 })).toBeNull();+ });++ it('returns null for an unreadable compute-cap column rather than guessing', () => {+ expect(sglangCellForGpu({ computeCap: null, vramGb: 141 })).toBeNull();+ expect(sglangCellForGpu(null)).toBeNull();+ });+});++describe('sglangUnsupportedReason', () => {+ it('points macOS at MTPLX / DSpark', () => {+ expect(sglangUnsupportedReason({ platform: 'darwin' })).toMatch(/MTPLX or llama\.cpp DSpark/);+ });++ it('says "could not read", never "no GPU", on an unknown probe', () => {+ const reason = sglangUnsupportedReason({ platform: 'linux', status: 'unknown' });+ expect(reason).toMatch(/could not read/i);+ expect(reason).not.toMatch(/^No NVIDIA GPU/);+ });++ it('names the vLLM path for a card the cookbook has no cell for', () => {+ const reason = sglangUnsupportedReason({+ platform: 'linux', status: 'available', gpus: [{ computeCap: '8.6', vramGb: 24 }],+ });+ expect(reason).toMatch(/qwen38-rtx3090/);+ });++ it('allows a supported card', () => {+ expect(sglangUnsupportedReason({+ platform: 'linux', status: 'available', gpus: [{ computeCap: '9.0', vramGb: 141 }],+ })).toBeNull();+ });++ it('refuses a host with no NVIDIA driver', () => {+ expect(sglangUnsupportedReason({ platform: 'linux', status: 'absent' })).toMatch(/No NVIDIA GPU/);+ });+});++describe('sglangComposeYaml', () => {+ const yaml = sglangComposeYaml(buildSglangQwenRecipe({ hw: 'h200' }));++ it('publishes the recipe\'s own port on loopback only', () => {+ expect(yaml).toContain(`- "127.0.0.1:${PORTS.SGLANG_QWEN}:${PORTS.SGLANG_QWEN}"`);+ expect(yaml).not.toContain('network_mode: host');+ });++ it('names the official image and never restarts on its own', () => {+ // `restart: "no"` is load-bearing: this container holds the whole GPU, and a+ // restart policy would bring it back on every docker/host reboot.+ expect(yaml).toContain(`image: ${SGLANG_QWEN_IMAGE}`);+ expect(yaml).toContain('restart: "no"');+ });++ it('matches the cookbook docker stanza for shm and IPC', () => {+ expect(yaml).toContain('ipc: host');+ expect(yaml).toContain('shm_size: "32g"');+ expect(yaml).toContain('driver: nvidia');+ });++ // One source of truth: the operator copies this file out of the feature doc,+ // so a launch-line change that never reaches the doc ships a compose file+ // missing the flag it was made for.+ it('is embedded verbatim in docs/features/sglang-qwen38.md', () => {+ const doc = readFileSync(join(repoRoot, 'docs/features/sglang-qwen38.md'), 'utf-8')+ .replace(/\r\n/g, '\n');+ const block = doc.match(/```yaml\n([\s\S]*?)```/)?.[1];+ expect(block).toBe(yaml);+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex b1035775d6..f0e5b6ede1 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -418,6 +418,9 @@ export const providerSchema = z.object({// Marks an OpenCode CLI/TUI wrapper for a separately started local vLLM// container (the Qwen3.8-27B DFlash 2 stack on an RTX 3090).vllmBacked: z.boolean().optional(),+ // Marks an OpenCode CLI/TUI wrapper for a separately started local SGLang+ // container (Qwen3.8-27B on a Hopper/Blackwell card).+ sglangBacked: z.boolean().optional(),// Marks an OpenCode CLI/TUI wrapper for the OrcaRouter OpenAI-compatible// gateway; the sibling API record owns its key.orcarouterBacked: z.boolean().optional(),diff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.jsindex 3d2546d10a..c2a728ea5a 100644--- a/server/services/localModelAssessments.test.js+++ b/server/services/localModelAssessments.test.js@@ -976,7 +976,7 @@ describe('tuning', () => {describe('runtime roster', () => {it('reports every assessable runtime with its knob catalog', async () => {const report = await svc.getAssessmentReport();- expect(report.runtimes.map((r) => r.id)).toEqual(['ollama', 'lmstudio', 'llama', 'mtplx', 'vllm']);+ expect(report.runtimes.map((r) => r.id)).toEqual(['ollama', 'lmstudio', 'llama', 'mtplx', 'vllm', 'sglang']);expect(report.runtimes.find((r) => r.id === 'llama').tuningSpecs.some((s) => s.id === 'ubatchSize')).toBe(true);});diff --git a/server/services/localRuntimeSetup.js b/server/services/localRuntimeSetup.jsindex a89c55ef4a..f94bea573e 100644--- a/server/services/localRuntimeSetup.js+++ b/server/services/localRuntimeSetup.js@@ -11,7 +11,8 @@* endpoint answers — from the button next to the failing check.** Every command here comes from the fixed table below. A request names a- * runtime *kind* (`mtplx` / `llama` / `ollama` / `lmstudio` / `vllm`) and nothing else —+ * runtime *kind* (`mtplx` / `llama` / `ollama` / `lmstudio` / `vllm` / `sglang`)+ * and nothing else —* no package, URL, port, or argument from the request ever reaches a shell* word, which keeps this as narrow as `providerRuntimeInstaller.js`'s CLI* install surface while removing the docs dead end.@@ -38,22 +39,27 @@* here is the same PM2 process (`portos-mtplx`) the Models → LLMs page can* stop, log, and persist across a reboot — the two surfaces cannot drift* onto different install commands or a daemon only one of them can see.- * - **The vLLM container is never provisioned by a Start.** Its start row- * brings up an already-prepared compose project and nothing else: no image- * build, no weight download, no docker/WSL2/NVIDIA-toolkit install. A- * project that is not demonstrably prepared is refused — and, since #4767,- * the checklist then offers the separate action that DOES provision it,- * "Clone, build & prepare … (~30 GB), then start", which is the same- * name-the-payload consent shape as MTPLX's `pull-start`. `install()` still- * refuses: Docker Desktop, the NVIDIA Container Toolkit and WSL2 are- * host-level operator decisions with driver requirements PortOS cannot- * judge, and this provisions the PROJECT on a host already capable of- * running it.+ * - **Neither CUDA container is ever provisioned by a Start.** Both start rows+ * bring up an already-prepared compose project and nothing else: no image+ * build or pull, no weight download, no docker/WSL2/NVIDIA-toolkit install.+ * A project that is not demonstrably prepared is refused — and, for vLLM+ * since #4767, the checklist then offers the separate action that DOES+ * provision it, "Clone, build & prepare … (~30 GB), then start", which is+ * the same name-the-payload consent shape as MTPLX's `pull-start`.+ * `install()` still refuses for both: Docker Desktop, the NVIDIA Container+ * Toolkit and WSL2 are host-level operator decisions with driver+ * requirements PortOS cannot judge, and that action provisions the PROJECT+ * on a host already capable of running it. SGLang has no such action — it+ * ships no provisioner of its own yet — and additionally refuses on a card+ * the cookbook publishes no recipe for, BEFORE it would reach docker.*/import { LOCAL_RUNTIMES, localEndpointPort } from '../lib/localProviderRuntime.js';import { describeMtplxCache, listMtplxCachedModels } from '../lib/mtplxModels.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';+import { inspectSglangQwenProject, sglangStartBlockedReason } from '../lib/sglangQwenProject.js';+import { sglangUnsupportedReason } from '../lib/sglangQwenRecipe.js';+import { getCudaCapability } from '../lib/cudaCapability.js';import { findCommandOnPath } from '../lib/processEnv.js';import { runStreamingCommand } from '../lib/streamingSpawn.js';import { installLlamaServer } from './llamaServerManager.js';@@ -106,6 +112,14 @@ const MTPLX_NO_MODEL_ERROR = 'no model weights are cached, so its server exits bconst mtplxPartialCacheError = (count) =>`its cache holds ${count} model${count === 1 ? '' : 's'}, but none passed its own file check — an interrupted download leaves a partial pack behind. Use “Download the default model & start MTPLX” on the checklist to re-fetch it, or pick another checkpoint on the MTPLX card in Models → LLMs.`;+/**+ * The `platforms` gate below is a static list, so its refusal has to be static+ * too — read from the recipe module rather than re-typed, so the platform+ * refusal and the runtime refusal cannot drift into telling an Apple Silicon+ * operator two different things.+ */+const SGLANG_PLATFORM_UNSUPPORTED_REASON = sglangUnsupportedReason({ platform: 'darwin' });+/*** The provisioning actions: the ones whose click IS the consent, because each* spends bandwidth measured in gigabytes.@@ -304,6 +318,47 @@ const SETUP_ROWS = Object.freeze({start: startVllmQwenProject,}),+ sglang: Object.freeze({+ // Same posture as vLLM: CUDA in a Linux container. The hardware gate is+ // narrower, though — the cookbook publishes single-GPU cells for Hopper and+ // Blackwell only, and an Ampere 24 GB card keeps the vLLM stack (the SGLang+ // cookbook has no 3090 cell). `sglangUnsupportedReason` reads the probe and+ // says which of those it is, never collapsing a wedged `nvidia-smi` into+ // "no GPU".+ platforms: ['linux', 'win32'],+ unsupportedReason: SGLANG_PLATFORM_UNSUPPORTED_REASON,+ async install() {+ // Deliberately never installs anything, for the same reasons as vLLM:+ // Docker / the NVIDIA Container Toolkit / WSL2 are host-level operator+ // decisions with driver requirements PortOS cannot judge.+ return {+ success: false,+ error: 'PortOS does not install this stack. On the Hopper or Blackwell host, set up Docker with the NVIDIA Container Toolkit, then follow docs/features/sglang-qwen38.md — it carries the compose file (with the verified launch line) and the one-time weight download.',+ };+ },+ async start({ emit, isCancelled }) {+ // Refuse before docker on a card with no recipe, so a wrong-hardware host+ // never reaches a `docker compose up` that would pull the image.+ const cuda = await getCudaCapability().catch(() => null);+ const unsupported = sglangUnsupportedReason({ status: cuda?.status, gpus: cuda?.gpus });+ if (unsupported) return { success: false, error: unsupported };+ // Only ever brings up an ALREADY-prepared project — see+ // `lib/sglangQwenProject.js` for why each refusal exists.+ const project = await inspectSglangQwenProject();+ const blocked = sglangStartBlockedReason(project);+ if (blocked) return { success: false, error: blocked };+ if (isCancelled()) return { success: false, error: 'Cancelled before the container was started.' };+ emit(`Starting the SGLang container from ${project.dir} (${project.composeFile}).`);+ emit('The image and weights are already on disk — this only brings the service up.');+ return runStreamingCommand(+ 'docker',+ ['compose', 'up', '-d'],+ emit,+ { timeoutMs: CONTROL_TIMEOUT_MS, cwd: project.dir },+ );+ },+ }),+ollama: Object.freeze({async install({ emit }) {// `installBackend` already registers the Homebrew service / runs the@@ -400,7 +455,7 @@ function platformSupported(row) {* every runtime with no cache to read reports — deliberately keeps the old* behavior; a cache PortOS could not read must not be treated as an empty one.*- * @param {string} kind - `mtplx` | `llama` | `ollama` | `lmstudio` | `vllm`+ * @param {string} kind - `mtplx` | `llama` | `ollama` | `lmstudio` | `vllm` | `sglang`* @param {{installed: boolean, running: boolean, weights?: 'unknown'|'empty'|'partial'|'ready'}} state*/export function describeRuntimeSetup(kind, { installed, running, weights = 'unknown' }) {diff --git a/server/services/localRuntimeSetup.test.js b/server/services/localRuntimeSetup.test.jsindex 860b34dd54..35530da0f0 100644--- a/server/services/localRuntimeSetup.test.js+++ b/server/services/localRuntimeSetup.test.js@@ -53,6 +53,15 @@ const vllmManager = vi.hoisted(() => ({startVllmQwenProject: vi.fn(async () => ({ success: true })),}));vi.mock('./vllmQwenManager.js', () => vllmManager);+// The SGLang project on disk, and the CUDA probe its start row consults BEFORE+// docker — mocked so no assertion depends on the developer's actual GPU.+const sglangProject = vi.hoisted(() => ({+ inspectSglangQwenProject: vi.fn(),+ sglangStartBlockedReason: vi.fn(() => null),+}));+vi.mock('../lib/sglangQwenProject.js', () => sglangProject);+const cuda = vi.hoisted(() => ({ getCudaCapability: vi.fn() }));+vi.mock('../lib/cudaCapability.js', () => cuda);import { describeRuntimeSetup, readRuntimeWeights, runLocalRuntimeSetup, SETUP_ACTIONS, SETUP_RUNTIME_KINDS } from './localRuntimeSetup.js';@@ -61,8 +70,13 @@ const reachable = (models = ['mtplx']) => ({ reachable: true, models, error: nulconst cachedModels = (models) => ({ models, error: null });+const preparedSglangProject = { dir: '/home/example/sglang-qwen38', hasProject: true, composeFile: 'docker-compose.yml', hasWeights: true, weightsRoot: '/home/example/sglang-qwen38/hf-cache/hub' };beforeEach(() => {+ sglangProject.inspectSglangQwenProject.mockResolvedValue(preparedSglangProject);+ sglangProject.sglangStartBlockedReason.mockReturnValue(null);+ // Default to the verified Hopper cell; the hardware cases override it.+ cuda.getCudaCapability.mockResolvedValue({ status: 'available', gpus: [{ name: 'NVIDIA H200', computeCap: '9.0', vramGb: 141 }] });// Implementations AND return values (not just call records) survive// `clearAllMocks`, so a probe implementation left over from an earlier test// would drive this module's poll loop for its full timeout.@@ -84,7 +98,7 @@ afterEach(() => {describe('describeRuntimeSetup', () => {it('covers every runtime the readiness checklist can report', () => {- expect([...SETUP_RUNTIME_KINDS].sort()).toEqual(['llama', 'lmstudio', 'mtplx', 'ollama', 'vllm']);+ expect([...SETUP_RUNTIME_KINDS].sort()).toEqual(['llama', 'lmstudio', 'mtplx', 'ollama', 'sglang', 'vllm']);});it('offers install AND start when nothing is there yet', () => {@@ -672,3 +686,105 @@ describe('vllm — the registry offers it, the manager does it', () => {restore();});});++describe('sglang — a hardware gate in front of the same never-provision posture', () => {+ const sglangEndpoint = 'http://127.0.0.1:18021/v1';+ const hopper = { status: 'available', gpus: [{ name: 'NVIDIA H200', computeCap: '9.0', vramGb: 141 }] };+ const ampere = { status: 'available', gpus: [{ name: 'NVIDIA GeForce RTX 3090', computeCap: '8.6', vramGb: 24 }] };++ const startOnLinux = async () => {+ pathLookup.findCommandOnPath.mockReturnValue('/usr/bin/docker');+ probe.probeOpenAiModels+ .mockResolvedValueOnce(unreachable)+ .mockResolvedValueOnce(unreachable)+ .mockResolvedValue(reachable(['qwen3.8-27b']));+ return runLocalRuntimeSetup('sglang', { endpoint: sglangEndpoint, emit: () => {} });+ };++ it('is unsupported on darwin, and says where Mac users should go instead', () => {+ const restore = pinPlatform('darwin');+ expect(describeRuntimeSetup('sglang', { installed: false, running: false })).toMatchObject({+ runtime: 'sglang',+ action: null,+ blockedReason: expect.stringMatching(/MTPLX or llama\.cpp DSpark/),+ });+ restore();+ });++ it('offers a start button on a Linux/Windows host with docker present', () => {+ const restore = pinPlatform('linux');+ expect(describeRuntimeSetup('sglang', { installed: true, running: false })).toMatchObject({+ runtime: 'sglang',+ action: 'start',+ blockedReason: null,+ });+ restore();+ });++ it('brings up an already-prepared compose project — no --profile, in its own directory', async () => {+ const restore = pinPlatform('linux');+ cuda.getCudaCapability.mockResolvedValue(hopper);++ const result = await startOnLinux();++ expect(result.success).toBe(true);+ expect(streaming.runStreamingCommand).toHaveBeenCalledWith(+ 'docker',+ ['compose', 'up', '-d'],+ expect.any(Function),+ expect.objectContaining({ cwd: preparedSglangProject.dir }),+ );+ restore();+ });++ it('refuses an Ampere card BEFORE docker, and names the vLLM path instead', async () => {+ // The cookbook has no 3090 cell. Refusing here — not after a `docker compose+ // up` — is what keeps a wrong-hardware host from pulling the image.+ const restore = pinPlatform('linux');+ cuda.getCudaCapability.mockResolvedValue(ampere);++ const result = await startOnLinux();++ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/qwen38-rtx3090/) });+ expect(streaming.runStreamingCommand).not.toHaveBeenCalled();+ expect(sglangProject.inspectSglangQwenProject).not.toHaveBeenCalled();+ restore();+ });++ it('says the probe failed rather than "no GPU" when nvidia-smi would not answer', async () => {+ const restore = pinPlatform('linux');+ cuda.getCudaCapability.mockResolvedValue({ status: 'unknown', gpus: [] });++ const result = await startOnLinux();++ expect(result.error).toMatch(/could not read/i);+ expect(streaming.runStreamingCommand).not.toHaveBeenCalled();+ restore();+ });++ it('refuses to run compose when the project is not demonstrably prepared', async () => {+ const restore = pinPlatform('linux');+ cuda.getCudaCapability.mockResolvedValue(hopper);+ sglangProject.sglangStartBlockedReason.mockReturnValue('no Qwen weights are cached yet');++ const result = await startOnLinux();++ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/no Qwen weights are cached/) });+ // The whole point: a 20 GB pull is never started on the user's behalf.+ expect(streaming.runStreamingCommand).not.toHaveBeenCalled();+ restore();+ });++ it('never installs docker or the container toolkit', async () => {+ const restore = pinPlatform('linux');+ cuda.getCudaCapability.mockResolvedValue(hopper);+ pathLookup.findCommandOnPath.mockReturnValue(null); // docker not on PATH+ probe.probeOpenAiModels.mockResolvedValue(unreachable);++ const result = await runLocalRuntimeSetup('sglang', { endpoint: sglangEndpoint, emit: () => {} });++ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/does not install this stack/) });+ expect(streaming.runStreamingCommand).not.toHaveBeenCalled();+ restore();+ });+});diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex 0c66fcb347..0351f7e03d 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -614,7 +614,7 @@ const FAMILIES = PROVIDER_FAMILIES.map((family) => ({ ...family, fetch: FAMILY_F* wrapper its family's card).*/export function resolveEnabledFamilies(providers) {- const enabled = (providers || []).filter((p) => p?.enabled && p.ollamaBacked !== true && p.mtplxBacked !== true && p.llamaBacked !== true && p.vllmBacked !== true);+ const enabled = (providers || []).filter((p) => p?.enabled && p.ollamaBacked !== true && p.mtplxBacked !== true && p.llamaBacked !== true && p.vllmBacked !== true && p.sglangBacked !== true);return FAMILIES.filter((family) => enabled.some((p) => family.matches(p)));}@@ -651,7 +651,7 @@ const fetchFamilyQuota = (family, { wait, providers }) =>export async function getProviderQuotas({ wait = WAIT.CACHED, family = null } = {}) {const result = await getAllProviders();const providers = Array.isArray(result) ? result : (result?.providers || []);- const enabled = providers.filter((p) => p?.enabled && p.ollamaBacked !== true && p.mtplxBacked !== true && p.llamaBacked !== true && p.vllmBacked !== true);+ const enabled = providers.filter((p) => p?.enabled && p.ollamaBacked !== true && p.mtplxBacked !== true && p.llamaBacked !== true && p.vllmBacked !== true && p.sglangBacked !== true);const families = resolveEnabledFamilies(providers).filter((f) => !family || f.id === family);const familyCards = await Promise.all(families.map((f) =>fetchFamilyQuota(f, { wait, providers: enabled.filter((p) => f.matches(p)) })));diff --git a/server/services/quotaBurnJobs/providerPick.js b/server/services/quotaBurnJobs/providerPick.jsindex fa6053e5a7..0c75055d07 100644--- a/server/services/quotaBurnJobs/providerPick.js+++ b/server/services/quotaBurnJobs/providerPick.js@@ -40,7 +40,7 @@ import { commandBasename } from '../../lib/providerModels.js';*/export function providerForFamily(providers, { familyId, providerId, prefer = 'tui' }) {const available = (providers || []).filter((provider) =>- provider?.enabled && provider.ollamaBacked !== true && provider.mtplxBacked !== true && provider.llamaBacked !== true && provider.vllmBacked !== true+ provider?.enabled && provider.ollamaBacked !== true && provider.mtplxBacked !== true && provider.llamaBacked !== true && provider.vllmBacked !== true && provider.sglangBacked !== true&& (provider.type === 'cli' || provider.type === 'tui'));if (providerId) return available.find((provider) => provider.id === providerId) || null;const inFamily = available.filter((provider) => matchesFamily(provider, familyId));