Initial commit: OpenCode vLLM autostart plugin and launchers
- Desktop plugin: on-demand vLLM model start, eject, media budgets - WSL-native twin plugin for WSL project sessions - Launchers for Qwen3.6 35B-A3B, Qwen3.8 27B (uncensored/fast), Agents-A1 - Config templates, diagnostics, video-processor workaround
This commit is contained in:
commit
40656fd046
27 files changed
+6710
No files matched your search
@@ -0,0 +1,8 @@
|
||||
* text=auto eol=lf
|
||||
*.sh text eol=lf
|
||||
*.py text eol=lf
|
||||
*.ts text eol=lf
|
||||
*.tsx text eol=lf
|
||||
*.json text eol=lf
|
||||
*.md text eol=lf
|
||||
*.cjs text eol=lf
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
*.log
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -0,0 +1,188 @@
|
||||
# opencode-vllm-autostart
|
||||
|
||||
OpenCode Desktop plugin and launcher set for local [vLLM](https://github.com/vllm-project/vllm)
|
||||
models running in WSL2, tuned for a single RTX 5090 (32 GB).
|
||||
|
||||
The plugin starts the model you pick the moment you send a request, stops the
|
||||
previous one first, and adds an **Eject** button that unloads the model and
|
||||
frees the GPU. It also keeps prompt media within each model's image/video
|
||||
budget so a long session does not get stuck on vLLM's per-prompt limits.
|
||||
|
||||
## What it does
|
||||
|
||||
- **Auto-start** — before a request to a `vllm` model, the plugin stops the
|
||||
running server, waits for VRAM to be released, and launches the selected
|
||||
model through its launcher script.
|
||||
- **Eject** — a titlebar pill and the command-palette action
|
||||
**vLLM: Eject loaded model**. It only stops a server this plugin started
|
||||
(tracked through `~/.vllm-autostart-owner`).
|
||||
- **Media budgets** — old images/videos are replaced with text in the outgoing
|
||||
request only (history is untouched) to stay under
|
||||
`--limit-mm-per-prompt`. This prevents the "At most N image(s) may be
|
||||
provided" hard lock in long sessions.
|
||||
- **WSL twin** — Desktop runs a second OpenCode server for WSL projects that
|
||||
cannot invoke Windows launchers. `wsl-plugin/` is a native Linux variant that
|
||||
starts the same models directly.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
plugin/ OpenCode Desktop plugin (server + GUI)
|
||||
src/index.ts auto-start hook, media trimming, RPC, ownership
|
||||
src/rpc.ts RPC contract shared by server and GUI
|
||||
src/gui.tsx titlebar pill + command-palette action
|
||||
dist/ built GUI bundle (gui-experimental.cjs)
|
||||
wsl-plugin/index.ts WSL-native server plugin (fetch-based, no GUI)
|
||||
launchers/
|
||||
launch_*.sh vLLM commands (model path, flags, VRAM heuristic)
|
||||
run_*.sh logging wrappers used by the plugins
|
||||
kill_vllm.sh stop the server and report free VRAM
|
||||
video_preprocessor_config.json
|
||||
config/
|
||||
opencode.windows.example.json
|
||||
opencode.wsl.example.json
|
||||
scripts/
|
||||
quickcheck.py is the API up, and which model is served?
|
||||
bench_generic.py chat / code / JSON throughput check
|
||||
check-syntax.sh bash -n over every launcher
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
- Windows 10/11 with OpenCode Desktop (V2)
|
||||
- WSL2 Ubuntu with an NVIDIA driver that exposes `nvidia-smi`
|
||||
- A Python venv with vLLM (`VLLM_ENV`, default `/home/dfj/vllm-env`)
|
||||
- Models in HF format under `MODELS` (default `/home/dfj/models`)
|
||||
- The launch scripts must be reachable from WSL through `/mnt/c/...`
|
||||
|
||||
The defaults in this repo match `/home/dfj`; override them when your layout is
|
||||
different:
|
||||
|
||||
| Variable | Default | Used by |
|
||||
|---|---|---|
|
||||
| `VLLM_ENV` | `/home/dfj/vllm-env` | launchers |
|
||||
| `MODELS` | `/home/dfj/models` | launchers |
|
||||
| `VLLM_LAUNCHER_DIR` | `/mnt/c/Users/dfj/projects/vllm-autostart/launchers` | plugins |
|
||||
| `MODEL_DIR` | `$MODELS/THe-Plague/...` | `launch_qwen36_unc.sh` only |
|
||||
|
||||
## Install
|
||||
|
||||
1. Clone this repository next to your home directory, e.g.
|
||||
`C:\Users\dfj\projects\vllm-autostart`.
|
||||
2. Build the plugin once (or use the committed `dist/`):
|
||||
|
||||
```powershell
|
||||
cd C:\Users\dfj\projects\vllm-autostart\plugin
|
||||
npm ci
|
||||
npm run build
|
||||
```
|
||||
|
||||
3. Merge `config/opencode.windows.example.json` into
|
||||
`%USERPROFILE%\.config\opencode\opencode.json`. Point `plugins` at the
|
||||
absolute plugin directory:
|
||||
|
||||
```json
|
||||
"plugins": ["C:/Users/dfj/projects/vllm-autostart/plugin"]
|
||||
```
|
||||
|
||||
4. In the WSL sidecar config (`~/.config/opencode/opencode.json`), point
|
||||
`plugins` at the WSL plugin directory:
|
||||
|
||||
```json
|
||||
"plugins": ["/mnt/c/Users/dfj/projects/vllm-autostart/wsl-plugin"]
|
||||
```
|
||||
|
||||
5. Make the launchers executable (WSL usually mounts `/mnt/c` as `0777`, so
|
||||
this is normally unnecessary):
|
||||
|
||||
```bash
|
||||
chmod +x /mnt/c/Users/dfj/projects/vllm-autostart/launchers/*.sh
|
||||
```
|
||||
|
||||
OpenCode reloads configuration and plugins on save. If the GUI bundle changed,
|
||||
restart the Desktop app.
|
||||
|
||||
## Models
|
||||
|
||||
| Served name | Hugging Face repo | Context | Notes |
|
||||
|---|---|---|---|
|
||||
| `qwen3.6-35b-uncensored` | `THe-Plague/Qwen3.6-35B-A3B-abliterated-NVFP4-MTP` | 262,144 | Primary. Abliterated, NVFP4, vision + video. ~117–137 tok/s. MTP disabled. |
|
||||
| `qwen3.8-uncensored` | `preetpatel/Qwen3.8-27B-Uncensored-NVFP4` | 163,840 | Uncensored 27B. 8 images, 2 MP each. |
|
||||
| `qwen3.8-fast` | `unsloth/Qwen3.8-27B-NVFP4` | 65,536 | Speculative MTP=3, no media. Fastest 27B. |
|
||||
| `agents-a1` | `protoLabsAI/Agents-A1-NVFP4` | 131,072 | 35B-A3B agent model. ~139 tok/s. |
|
||||
|
||||
Only one model can be resident at a time. The plugins enforce this by stopping
|
||||
the current server before starting the next one.
|
||||
|
||||
### Qwen3.6 video fix
|
||||
|
||||
vLLM 0.27.x was built against an older transformers where the video-processor
|
||||
mapping stores a class-name string. transformers 5.x stores a dict per backend,
|
||||
which vLLM feeds into a dict lookup and crashes with
|
||||
`unhashable type: 'dict'` on every video request.
|
||||
|
||||
`launch_qwen36_unc.sh` writes a local `video_preprocessor_config.json` into the
|
||||
model directory:
|
||||
|
||||
```json
|
||||
{ "video_processor_type": "Qwen3VLVideoProcessor" }
|
||||
```
|
||||
|
||||
This makes vLLM resolve the processor name itself. The file is recreated on
|
||||
start if missing.
|
||||
|
||||
### MTP on Qwen3.6
|
||||
|
||||
The checkpoint ships an MTP draft layer. With the BF16 draft on Triton it
|
||||
accepted 2.5–3.5 tokens/step but measured **~50 tok/s** versus **117–137 tok/s**
|
||||
without speculative decoding on this stack, so it stays off. MTP is enabled for
|
||||
`qwen3.8-fast`, where it is a net win.
|
||||
|
||||
## VRAM behavior
|
||||
|
||||
Launchers that need a large model compute utilization from current free VRAM:
|
||||
|
||||
```
|
||||
util = min(0.92, (free - 1024 MiB) / total)
|
||||
```
|
||||
|
||||
The floor is 0.62 so a busy desktop does not make the model unloadable. The
|
||||
Qwen3.6 launcher uses this adaptive value; smaller models use a fixed value.
|
||||
|
||||
## Media support
|
||||
|
||||
| Model | Images/prompt | Videos/prompt | Plugin budget |
|
||||
|---|---|---|---|
|
||||
| `qwen3.6-35b-uncensored` | 8 | 1 | 8 images, 1 video |
|
||||
| `qwen3.8-uncensored` | 8 | 0 | 6 images |
|
||||
| `qwen3.8-fast`, `agents-a1` | 0 | 0 | 0 |
|
||||
|
||||
Image resolution is capped with `--mm-processor-kwargs '{"max_pixels": ...}'`
|
||||
(1 MP for Qwen3.6, 2 MP for the 27B).
|
||||
|
||||
Notes:
|
||||
|
||||
- The OpenCode server/API forwards video attachments correctly; the model sees
|
||||
the frames (verified with a blue test clip). Desktop drag-and-drop uses the
|
||||
same path.
|
||||
- The OpenCode **CLI** (`opencode run --file`) has a hardcoded extension
|
||||
allowlist without video types, so it silently drops `.mp4`. Use the Desktop
|
||||
UI or the HTTP API for video.
|
||||
- vLLM counts every image/video in the prompt, including tool results from the
|
||||
session history. The plugin trims the oldest ones per request.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **Model does not start**: check the log named in `run_*.sh`
|
||||
(`/home/dfj/qwen36_unc.log`, etc.) and `nvidia-smi`.
|
||||
- **Stale "running" state**: the plugin polls `http://127.0.0.1:8000/v1/models`;
|
||||
a server started manually is treated as not owned and will not be ejected.
|
||||
- **Plugin not loading**: verify the `plugins` path is absolute, contains
|
||||
`package.json` (Windows plugin) or `index.ts` (WSL plugin), and check
|
||||
`~/.local/share/opencode/log/opencode.log`.
|
||||
- **Video returns `unhashable type: 'dict'`**: the per-model
|
||||
`video_preprocessor_config.json` is missing; restart the Qwen3.6 launcher.
|
||||
|
||||
## License
|
||||
|
||||
Private repository. No license granted unless added explicitly.
|
||||
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"plugins": ["C:/Users/dfj/projects/vllm-autostart/plugin"],
|
||||
"provider": {
|
||||
"vllm": {
|
||||
"npm": "@ai-sdk/openai-compatible",
|
||||
"name": "vLLM (local)",
|
||||
"options": {
|
||||
"baseURL": "http://127.0.0.1:8000/v1"
|
||||
},
|
||||
"models": {
|
||||
"qwen3.8-uncensored": {
|
||||
"name": "Qwen3.8 27B Uncensored (NVFP4)",
|
||||
"tool_call": true,
|
||||
"reasoning": true,
|
||||
"temperature": true,
|
||||
"limit": {
|
||||
"context": 163840,
|
||||
"output": 16384
|
||||
}
|
||||
},
|
||||
"qwen3.8-fast": {
|
||||
"name": "Qwen3.8 27B Fast (MTP-3)",
|
||||
"tool_call": true,
|
||||
"reasoning": true,
|
||||
"temperature": true,
|
||||
"limit": {
|
||||
"context": 65536,
|
||||
"output": 16384
|
||||
}
|
||||
},
|
||||
"agents-a1": {
|
||||
"name": "Agents-A1 35B-A3B (NVFP4)",
|
||||
"tool_call": true,
|
||||
"reasoning": true,
|
||||
"temperature": true,
|
||||
"limit": {
|
||||
"context": 131072,
|
||||
"output": 16384
|
||||
}
|
||||
},
|
||||
"qwen3.6-35b-uncensored": {
|
||||
"name": "Qwen3.6 35B A3B Uncensored (NVFP4)",
|
||||
"tool_call": true,
|
||||
"reasoning": true,
|
||||
"modalities": {
|
||||
"input": ["text", "image", "video"]
|
||||
},
|
||||
"limit": {
|
||||
"context": 262144,
|
||||
"output": 16384
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"plugins": ["/mnt/c/Users/dfj/projects/vllm-autostart/wsl-plugin"],
|
||||
"provider": {
|
||||
"vllm": {
|
||||
"npm": "@ai-sdk/openai-compatible",
|
||||
"name": "vllm (local)",
|
||||
"options": {
|
||||
"baseURL": "http://127.0.0.1:8000/v1"
|
||||
},
|
||||
"models": {
|
||||
"qwen3.8-uncensored": {
|
||||
"name": "Qwen3.8 27B Uncensored (NVFP4)",
|
||||
"tool_call": true,
|
||||
"limit": {
|
||||
"context": 163840,
|
||||
"output": 16384
|
||||
}
|
||||
},
|
||||
"qwen3.8-fast": {
|
||||
"name": "Qwen3.8 27B Fast (MTP-3)",
|
||||
"tool_call": true,
|
||||
"limit": {
|
||||
"context": 65536,
|
||||
"output": 16384
|
||||
}
|
||||
},
|
||||
"agents-a1": {
|
||||
"name": "Agents-A1 35B-A3B (NVFP4)",
|
||||
"tool_call": true,
|
||||
"limit": {
|
||||
"context": 131072,
|
||||
"output": 16384
|
||||
}
|
||||
},
|
||||
"qwen3.6-35b-uncensored": {
|
||||
"name": "Qwen3.6 35B A3B Uncensored (NVFP4)",
|
||||
"tool_call": true,
|
||||
"modalities": {
|
||||
"input": ["text", "image", "video"]
|
||||
},
|
||||
"limit": {
|
||||
"context": 262144,
|
||||
"output": 16384
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
pkill -9 -f 'vllm serve' || true
|
||||
pkill -9 -f 'VLLM::EngineCore' || true
|
||||
sleep 4
|
||||
pgrep -af 'vllm serve' || echo "none"
|
||||
nvidia-smi --query-gpu=memory.used,memory.free --format=csv,noheader
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/bin/bash
|
||||
# Agents-A1 35B-A3B NVFP4 on RTX 5090 / WSL.
|
||||
# NOTE: --moe-backend marlin crashes during load on this stack
|
||||
# (marlin_utils_fp4 _nvfp4_compute_scale_factor -> "device not ready").
|
||||
# vLLM CUTLASS is the stable sm120 path; ~139 tok/s single stream.
|
||||
VLLM_ENV=${VLLM_ENV:-/home/dfj/vllm-env}
|
||||
MODELS=${MODELS:-/home/dfj/models}
|
||||
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
|
||||
export PATH="$VLLM_ENV/bin:$VLLM_ENV/lib/python3.12/site-packages/nvidia/cu13/bin:$PATH"
|
||||
export CUDA_HOME="$VLLM_ENV/lib/python3.12/site-packages/nvidia/cu13"
|
||||
export MAX_JOBS=4
|
||||
unset FLASHINFER_JIT_VERBOSE
|
||||
unset FLASHINFER_JIT_DEBUG
|
||||
export VLLM_USE_FLASHINFER_SAMPLER=0
|
||||
|
||||
# Pick a utilization that leaves headroom for whatever the desktop is using.
|
||||
read TOTAL FREE < <(nvidia-smi --query-gpu=memory.total,memory.free --format=csv,noheader,nounits | awk -F',' '{gsub(/ /,""); print $1, $2}')
|
||||
if [ -n "$TOTAL" ] && [ -n "$FREE" ]; then
|
||||
UTIL=$(awk -v t="$TOTAL" -v f="$FREE" 'BEGIN { u=(f-1024)/t; if (u>0.90) u=0.90; if (u<0.60) u=0.62; printf "%.2f", u }')
|
||||
echo "agents-a1: ${FREE} MiB free / ${TOTAL} MiB total -> gpu-memory-utilization ${UTIL}"
|
||||
else
|
||||
UTIL=0.82
|
||||
fi
|
||||
|
||||
exec "$VLLM_ENV/bin/vllm" serve "$MODELS/protoLabsAI/Agents-A1-NVFP4" \
|
||||
--served-model-name agents-a1 \
|
||||
--host 0.0.0.0 \
|
||||
--port 8000 \
|
||||
--moe-backend cutlass \
|
||||
--language-model-only \
|
||||
--max-model-len 131072 \
|
||||
--gpu-memory-utilization "$UTIL" \
|
||||
--max-num-seqs 8 \
|
||||
--max-num-batched-tokens 8192 \
|
||||
--kv-cache-dtype fp8 \
|
||||
--enable-auto-tool-choice \
|
||||
--tool-call-parser qwen3_coder \
|
||||
--reasoning-parser qwen3
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/bin/bash
|
||||
# Qwen3.8 27B NVFP4 (unsloth) with MTP=3 on RTX 5090 / WSL.
|
||||
VLLM_ENV=${VLLM_ENV:-/home/dfj/vllm-env}
|
||||
MODELS=${MODELS:-/home/dfj/models}
|
||||
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
|
||||
export PATH="$VLLM_ENV/bin:$VLLM_ENV/lib/python3.12/site-packages/nvidia/cu13/bin:$PATH"
|
||||
export CUDA_HOME="$VLLM_ENV/lib/python3.12/site-packages/nvidia/cu13"
|
||||
export MAX_JOBS=4
|
||||
unset FLASHINFER_JIT_VERBOSE
|
||||
unset FLASHINFER_JIT_DEBUG
|
||||
export VLLM_USE_FLASHINFER_SAMPLER=0
|
||||
exec "$VLLM_ENV/bin/vllm" serve "$MODELS/unsloth/Qwen3.8-27B-NVFP4" \
|
||||
--served-model-name qwen3.8-fast \
|
||||
--host 0.0.0.0 --port 8000 \
|
||||
--max-model-len 65536 \
|
||||
--kv-cache-dtype fp8 \
|
||||
--gpu-memory-utilization 0.87 \
|
||||
--max-num-seqs 1 \
|
||||
--max-num-batched-tokens 4096 \
|
||||
--limit-mm-per-prompt '{"image": 0, "video": 0}' \
|
||||
--speculative-config '{"method":"mtp","num_speculative_tokens":3}' \
|
||||
--enable-auto-tool-choice --tool-call-parser qwen3_coder --reasoning-parser qwen3
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/bin/bash
|
||||
# Qwen3.8 27B Uncensored (preetpatel) NVFP4 on RTX 5090 / WSL.
|
||||
VLLM_ENV=${VLLM_ENV:-/home/dfj/vllm-env}
|
||||
MODELS=${MODELS:-/home/dfj/models}
|
||||
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
|
||||
export PATH="$VLLM_ENV/bin:$VLLM_ENV/lib/python3.12/site-packages/nvidia/cu13/bin:$PATH"
|
||||
export CUDA_HOME="$VLLM_ENV/lib/python3.12/site-packages/nvidia/cu13"
|
||||
export MAX_JOBS=4
|
||||
unset FLASHINFER_JIT_VERBOSE
|
||||
unset FLASHINFER_JIT_DEBUG
|
||||
export VLLM_USE_FLASHINFER_SAMPLER=0
|
||||
exec "$VLLM_ENV/bin/vllm" serve "$MODELS/preetpatel/Qwen3.8-27B-Uncensored-NVFP4" \
|
||||
--served-model-name qwen3.8-uncensored \
|
||||
--host 0.0.0.0 \
|
||||
--port 8000 \
|
||||
--max-model-len 163840 \
|
||||
--kv-cache-dtype fp8 \
|
||||
--gpu-memory-utilization 0.87 \
|
||||
--max-num-seqs 8 \
|
||||
--max-num-batched-tokens 8192 \
|
||||
--limit-mm-per-prompt '{"image": 8, "video": 0}' \
|
||||
--mm-processor-kwargs '{"max_pixels": 2097152}' \
|
||||
--enable-auto-tool-choice \
|
||||
--tool-call-parser qwen3_coder \
|
||||
--reasoning-parser qwen3
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/bin/bash
|
||||
# Qwen3.6-35B-A3B abliterated, NVFP4 on RTX 5090 / WSL.
|
||||
# MTP is present in the checkpoint but disabled: with the BF16 draft on Triton
|
||||
# it measured ~50 tok/s vs ~117-131 tok/s without speculative decoding.
|
||||
# Based on THe-Plague/Qwen3.6-35B-A3B-abliterated-NVFP4-MTP.
|
||||
#
|
||||
# Video: vLLM 0.27.1 is built against an older transformers where the video
|
||||
# processor mapping holds a class-name string. transformers 5.x stores a dict
|
||||
# per backend ({"torchvision": "Qwen3VLVideoProcessor"}), which vLLM feeds into
|
||||
# a dict lookup and crashes with "unhashable type: 'dict'". Shipping a local
|
||||
# video_preprocessor_config.json makes vLLM resolve the name itself.
|
||||
MODEL_DIR=${MODEL_DIR:-${MODELS:-/home/dfj/models}/THe-Plague/Qwen3.6-35B-A3B-abliterated-NVFP4-MTP}
|
||||
VLLM_ENV=${VLLM_ENV:-/home/dfj/vllm-env}
|
||||
VPC="$MODEL_DIR/video_preprocessor_config.json"
|
||||
if [ ! -f "$VPC" ]; then
|
||||
echo '{"video_processor_type": "Qwen3VLVideoProcessor"}' > "$VPC" && echo "qwen3.6-35b: wrote $VPC"
|
||||
fi
|
||||
|
||||
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
|
||||
export PATH="$VLLM_ENV/bin:$VLLM_ENV/lib/python3.12/site-packages/nvidia/cu13/bin:$PATH"
|
||||
export CUDA_HOME="$VLLM_ENV/lib/python3.12/site-packages/nvidia/cu13"
|
||||
export MAX_JOBS=4
|
||||
export VLLM_USE_FLASHINFER_SAMPLER=0
|
||||
export VLLM_MARLIN_USE_ATOMIC_ADD=1
|
||||
export TORCH_MATMUL_PRECISION=high
|
||||
unset FLASHINFER_JIT_VERBOSE
|
||||
unset FLASHINFER_JIT_DEBUG
|
||||
|
||||
read TOTAL FREE < <(nvidia-smi --query-gpu=memory.total,memory.free --format=csv,noheader,nounits | awk -F',' '{gsub(/ /,""); print $1, $2}')
|
||||
if [ -n "$TOTAL" ] && [ -n "$FREE" ]; then
|
||||
UTIL=$(awk -v t="$TOTAL" -v f="$FREE" 'BEGIN { u=(f-1024)/t; if (u>0.92) u=0.92; if (u<0.60) u=0.62; printf "%.2f", u }')
|
||||
echo "qwen3.6-35b: ${FREE} MiB free / ${TOTAL} MiB total -> gpu-memory-utilization ${UTIL}"
|
||||
else
|
||||
UTIL=0.85
|
||||
fi
|
||||
|
||||
exec "$VLLM_ENV/bin/vllm" serve "$MODEL_DIR" \
|
||||
--served-model-name qwen3.6-35b-uncensored \
|
||||
--host 0.0.0.0 \
|
||||
--port 8000 \
|
||||
--moe-backend cutlass \
|
||||
--max-model-len 262144 \
|
||||
--limit-mm-per-prompt '{"image": 8, "video": 1}' \
|
||||
--mm-processor-kwargs '{"max_pixels": 1048576}' \
|
||||
--gpu-memory-utilization "$UTIL" \
|
||||
--max-num-seqs 1 \
|
||||
--max-num-batched-tokens 8192 \
|
||||
--kv-cache-dtype fp8 \
|
||||
--enable-auto-tool-choice \
|
||||
--tool-call-parser qwen3_coder \
|
||||
--reasoning-parser qwen3
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
cd /home/dfj
|
||||
bash "$DIR/launch_agents_a1.sh" > /home/dfj/agents_a1.log 2>&1
|
||||
echo "EXIT=$?" >> /home/dfj/agents_a1.log
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
cd /home/dfj
|
||||
bash "$DIR/launch_fast_unsloth.sh" > /home/dfj/fast_unsloth.log 2>&1
|
||||
echo "EXIT=$?" >> /home/dfj/fast_unsloth.log
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
cd /home/dfj
|
||||
bash "$DIR/launch_qwen36_unc.sh" > /home/dfj/qwen36_unc.log 2>&1
|
||||
echo "EXIT=$?" >> /home/dfj/qwen36_unc.log
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
cd /home/dfj
|
||||
bash "$DIR/launch_inner.sh" > /home/dfj/uncensored.log 2>&1
|
||||
echo "EXIT=$?" >> /home/dfj/uncensored.log
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"video_processor_type": "Qwen3VLVideoProcessor"
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
# vllm-autostart (server + GUI part)
|
||||
|
||||
OpenCode Desktop plugin that starts the local vLLM model on demand and adds an
|
||||
eject button.
|
||||
|
||||
See the [repository README](../README.md) for installation, launchers, and the
|
||||
model configuration.
|
||||
|
||||
## What it does
|
||||
|
||||
- **Auto-start** — before a request to a `vllm` model, unloads the other model,
|
||||
waits for its VRAM to be released, and launches the one you picked.
|
||||
- **Eject button** — a pill in the window titlebar, shown only while the
|
||||
running server was started by this plugin. Clicking it stops vLLM and clears
|
||||
the GPU. It is also available in the command palette as
|
||||
**vLLM: Eject loaded model**.
|
||||
- A server started any other way is left alone; eject reports `not-owned` and
|
||||
does nothing.
|
||||
- **Media budgets** — old images/videos are trimmed from the outgoing request
|
||||
to stay under each launcher's `--limit-mm-per-prompt`.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
src/index.ts server part: auto-start hook, media trimming, RPC
|
||||
src/rpc.ts RPC contract shared by server and GUI
|
||||
src/gui.tsx Desktop GUI: titlebar pill + palette command
|
||||
dist/ built GUI bundle (gui-experimental.cjs)
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
```powershell
|
||||
cd C:\Users\dfj\projects\vllm-autostart\plugin
|
||||
npm ci
|
||||
npm run build
|
||||
```
|
||||
|
||||
`npm run watch` rebuilds on change and reloads the GUI in every window.
|
||||
|
||||
## Config
|
||||
|
||||
Listed in `~/.config/opencode/opencode.json`:
|
||||
|
||||
```json
|
||||
{ "plugins": ["C:/Users/dfj/projects/vllm-autostart/plugin"] }
|
||||
```
|
||||
|
||||
Ownership is stored in plugin storage under the `owner` key and mirrored to
|
||||
`~/.vllm-autostart-owner`, so eject also works for models started by the WSL
|
||||
twin plugin.
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const o=require("solid-js"),i=require("@opencode/plugin/gui"),y=require("@opencode/plugin/rpc"),m={type:"object",properties:{},additionalProperties:!1},v=y.Rpc.define({id:"vllm-autostart",methods:{status:{input:m,output:{type:"object",properties:{running:{type:"boolean"},owned:{type:"boolean"},starting:{type:"boolean"},model:{type:"string"}},required:["running","owned","starting","model"],additionalProperties:!1}},eject:{input:m,output:{type:"object",properties:{stopped:{type:"boolean"},reason:{type:"string"}},required:["stopped","reason"],additionalProperties:!1}}},events:{}}),w=i.Plugin.define({i18n:{en:{"titlebar.stop":"Stop vLLM","titlebar.stopping":"Stopping vLLM","titlebar.title":"Eject the loaded model and stop the vLLM server","command.eject":"vLLM: Eject loaded model","command.ejectDescription":"Stop the local vLLM server this plugin started","command.group":"vLLM","toast.stopped":"vLLM stopped","toast.stoppedDescription":"The model was unloaded and the server stopped.","toast.notOwned":"vLLM was not started by this plugin","toast.notOwnedDescription":"The server was left running.","toast.error":"Could not stop vLLM"}},setup(e){const[a,d]=o.createSignal(!1),[l,p]=o.createSignal(!1),[f,u]=o.createSignal(!1),[s,c]=o.createSignal(!1);let n=!1;const r=async()=>{try{const t=await e.client.rpc(v).status({});if(n)return;d(!!t.running),p(!!t.owned),u(!!t.starting)}catch{if(n)return;d(!1),p(!1),u(!1)}};r();const b=setInterval(()=>{r()},5e3);e.signal.addEventListener("abort",()=>{n=!0,clearInterval(b)});const g=async()=>{if(!s()){c(!0);try{const t=await e.client.rpc(v).eject({});t.stopped?e.toast.show({title:e.t("toast.stopped"),description:e.t("toast.stoppedDescription"),variant:"success"}):t.reason==="not-owned"&&e.toast.show({title:e.t("toast.notOwned"),description:e.t("toast.notOwnedDescription")})}catch(t){e.toast.show({title:e.t("toast.error"),description:t instanceof Error?t.message:String(t),variant:"error"})}finally{c(!1),r()}}};e.add(i.TitlebarItem,()=>{if(!(!a()||!l()))return{id:"eject",label:s()||f()?e.t("titlebar.stopping"):e.t("titlebar.stop"),title:e.t("titlebar.title"),icon:"stop",busy:s(),run:()=>{g()}}}),e.add(i.Command,()=>({id:"eject",title:e.t("command.eject"),description:e.t("command.ejectDescription"),keywords:"vllm stop unload eject gpu model",group:e.t("command.group"),section:"model",enabled:a()&&l(),run:()=>{g()}}))}});exports.default=w;
|
||||
Generated
+5420
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "opencode-vllm-autostart",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./rpc": "./src/rpc.ts",
|
||||
"./gui-experimental": "./dist/gui-experimental.cjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@opencode/plugin": "2.2.4"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
"watch": "vite build --watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"solid-js": "^1.9.0",
|
||||
"vite": "^7.0.0",
|
||||
"vite-plugin-solid": "^2.11.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { createSignal } from "solid-js"
|
||||
import { Command, Plugin, TitlebarItem } from "@opencode/plugin/gui"
|
||||
import { Vllm } from "./rpc.js"
|
||||
|
||||
/**
|
||||
* Desktop GUI: a titlebar pill that ejects the loaded model and stops the
|
||||
* vLLM server, but only when this plugin started it. Also exposed as a
|
||||
* command-palette action.
|
||||
*/
|
||||
export default Plugin.define({
|
||||
i18n: {
|
||||
en: {
|
||||
"titlebar.stop": "Stop vLLM",
|
||||
"titlebar.stopping": "Stopping vLLM",
|
||||
"titlebar.title": "Eject the loaded model and stop the vLLM server",
|
||||
"command.eject": "vLLM: Eject loaded model",
|
||||
"command.ejectDescription": "Stop the local vLLM server this plugin started",
|
||||
"command.group": "vLLM",
|
||||
"toast.stopped": "vLLM stopped",
|
||||
"toast.stoppedDescription": "The model was unloaded and the server stopped.",
|
||||
"toast.notOwned": "vLLM was not started by this plugin",
|
||||
"toast.notOwnedDescription": "The server was left running.",
|
||||
"toast.error": "Could not stop vLLM",
|
||||
},
|
||||
},
|
||||
setup(ctx) {
|
||||
const [running, setRunning] = createSignal(false)
|
||||
const [owned, setOwned] = createSignal(false)
|
||||
const [starting, setStarting] = createSignal(false)
|
||||
const [busy, setBusy] = createSignal(false)
|
||||
let closed = false
|
||||
|
||||
const refresh = async () => {
|
||||
try {
|
||||
const status = await ctx.client.rpc(Vllm).status({})
|
||||
if (closed) return
|
||||
setRunning(!!status.running)
|
||||
setOwned(!!status.owned)
|
||||
setStarting(!!status.starting)
|
||||
} catch {
|
||||
if (closed) return
|
||||
setRunning(false)
|
||||
setOwned(false)
|
||||
setStarting(false)
|
||||
}
|
||||
}
|
||||
|
||||
void refresh()
|
||||
const timer = setInterval(() => void refresh(), 5000)
|
||||
ctx.signal.addEventListener("abort", () => {
|
||||
closed = true
|
||||
clearInterval(timer)
|
||||
})
|
||||
|
||||
const eject = async () => {
|
||||
if (busy()) return
|
||||
setBusy(true)
|
||||
try {
|
||||
const result = await ctx.client.rpc(Vllm).eject({})
|
||||
if (result.stopped) {
|
||||
ctx.toast.show({
|
||||
title: ctx.t("toast.stopped"),
|
||||
description: ctx.t("toast.stoppedDescription"),
|
||||
variant: "success",
|
||||
})
|
||||
} else if (result.reason === "not-owned") {
|
||||
ctx.toast.show({
|
||||
title: ctx.t("toast.notOwned"),
|
||||
description: ctx.t("toast.notOwnedDescription"),
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.toast.show({
|
||||
title: ctx.t("toast.error"),
|
||||
description: error instanceof Error ? error.message : String(error),
|
||||
variant: "error",
|
||||
})
|
||||
} finally {
|
||||
setBusy(false)
|
||||
void refresh()
|
||||
}
|
||||
}
|
||||
|
||||
ctx.add(TitlebarItem, (): TitlebarItem | undefined => {
|
||||
if (!running() || !owned()) return undefined
|
||||
return {
|
||||
id: "eject",
|
||||
label: busy() || starting() ? ctx.t("titlebar.stopping") : ctx.t("titlebar.stop"),
|
||||
title: ctx.t("titlebar.title"),
|
||||
icon: "stop",
|
||||
busy: busy(),
|
||||
run: () => void eject(),
|
||||
}
|
||||
})
|
||||
|
||||
ctx.add(Command, (): Command => ({
|
||||
id: "eject",
|
||||
title: ctx.t("command.eject"),
|
||||
description: ctx.t("command.ejectDescription"),
|
||||
keywords: "vllm stop unload eject gpu model",
|
||||
group: ctx.t("command.group"),
|
||||
section: "model",
|
||||
enabled: running() && owned(),
|
||||
run: () => void eject(),
|
||||
}))
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,319 @@
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { promisify } from "node:util"
|
||||
import { readFile, writeFile, unlink } from "node:fs/promises"
|
||||
import { homedir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { Plugin } from "@opencode/plugin"
|
||||
import { Vllm } from "./rpc.js"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
/**
|
||||
* Auto-start the local vLLM endpoint for the selected model, and expose an
|
||||
* RPC so the Desktop GUI can eject (stop) a server this plugin started.
|
||||
*
|
||||
* Only one 27B model fits in the GPU at a time, so switching models stops the
|
||||
* previous server and waits for its VRAM to be released before launching.
|
||||
*/
|
||||
|
||||
const LAUNCHER_DIR =
|
||||
process.env.VLLM_LAUNCHER_DIR ?? "/mnt/c/Users/dfj/projects/vllm-autostart/launchers"
|
||||
|
||||
const LAUNCHERS: Record<string, string> = {
|
||||
"qwen3.8-fast": `${LAUNCHER_DIR}/run_fast_unsloth.sh`,
|
||||
"qwen3.8-uncensored": `${LAUNCHER_DIR}/run_uncensored.sh`,
|
||||
"agents-a1": `${LAUNCHER_DIR}/run_agents_a1.sh`,
|
||||
"qwen3.6-35b-uncensored": `${LAUNCHER_DIR}/run_qwen36_unc.sh`,
|
||||
}
|
||||
|
||||
const READY_TIMEOUT_MS = 6 * 60 * 1000
|
||||
const POLL_MS = 3000
|
||||
|
||||
/**
|
||||
* Images allowed per model in one request. vLLM counts every image in the
|
||||
* prompt (history included), so old tool screenshots can exhaust the limit.
|
||||
* Keep these at or below the launchers' --limit-mm-per-prompt values.
|
||||
*/
|
||||
const IMAGE_BUDGET: Record<string, number> = {
|
||||
"qwen3.8-uncensored": 6,
|
||||
"qwen3.8-fast": 0,
|
||||
"agents-a1": 0,
|
||||
"qwen3.6-35b-uncensored": 8,
|
||||
}
|
||||
|
||||
/** Videos allowed per model in one request; vLLM counts the whole prompt. */
|
||||
const VIDEO_BUDGET: Record<string, number> = {
|
||||
"qwen3.6-35b-uncensored": 1,
|
||||
}
|
||||
|
||||
function mediaKind(node: any): "image" | "video" | null {
|
||||
if (!node || typeof node !== "object") return null
|
||||
let mime = ""
|
||||
if (node.type === "media") {
|
||||
mime = node.media?.source?.mediaType ?? node.media?.mediaType ?? ""
|
||||
} else if (node.type === "file") {
|
||||
mime = node.mime ?? ""
|
||||
}
|
||||
if (typeof mime !== "string") return null
|
||||
if (mime.startsWith("image/")) return "image"
|
||||
if (mime.startsWith("video/")) return "video"
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the oldest media parts of one kind with text so the outgoing request
|
||||
* fits the model's budget. The stored session history is left untouched.
|
||||
*/
|
||||
function trimMedia(messages: any, kind: "image" | "video", budget: number): number {
|
||||
if (!Array.isArray(messages)) return 0
|
||||
const found: Array<{ parent: any[]; index: number }> = []
|
||||
const walk = (node: any): void => {
|
||||
if (!node || typeof node !== "object" || ArrayBuffer.isView(node)) return
|
||||
if (Array.isArray(node)) {
|
||||
for (let i = 0; i < node.length; i++) {
|
||||
if (mediaKind(node[i]) === kind) found.push({ parent: node, index: i })
|
||||
else walk(node[i])
|
||||
}
|
||||
return
|
||||
}
|
||||
for (const value of Object.values(node)) walk(value)
|
||||
}
|
||||
walk(messages)
|
||||
|
||||
const excess = found.length - Math.max(0, budget)
|
||||
if (excess <= 0) return 0
|
||||
for (const { parent, index } of found.slice(0, excess)) {
|
||||
parent[index] = { type: "text", text: `[${kind} omitted: local model ${kind} limit reached]` }
|
||||
}
|
||||
return excess
|
||||
}
|
||||
|
||||
/** Durable marker: the model this plugin launched and still owns. */
|
||||
const OWNER_KEY = "owner"
|
||||
/** Shared marker so a model started by the WSL server is still ejectable here. */
|
||||
const OWNER_FILE = join(homedir(), ".vllm-autostart-owner")
|
||||
|
||||
let pending: Promise<void> | null = null
|
||||
let pendingTarget: string | null = null
|
||||
let pendingGeneration = 0
|
||||
let startingModel: string | null = null
|
||||
let startToken = 0
|
||||
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
async function servedModels(): Promise<string[]> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
"curl.exe",
|
||||
["-s", "-m", "3", "--noproxy", "*", "http://localhost:8000/v1/models"],
|
||||
{ timeout: 6000, windowsHide: true },
|
||||
)
|
||||
if (typeof stdout !== "string" || !stdout.trim()) return []
|
||||
const body = JSON.parse(stdout) as { data?: Array<{ id?: unknown }> }
|
||||
return (body.data ?? []).map((entry) => String(entry.id ?? "")).filter(Boolean)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
async function isServing(model: string): Promise<boolean> {
|
||||
return (await servedModels()).includes(model)
|
||||
}
|
||||
|
||||
async function gpuFreeMiB(): Promise<number> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
"nvidia-smi",
|
||||
["--query-gpu=memory.free", "--format=csv,noheader,nounits"],
|
||||
{ timeout: 5000, windowsHide: true },
|
||||
)
|
||||
const n = parseInt(String(stdout).trim().split(/\r?\n/)[0], 10)
|
||||
return Number.isFinite(n) ? n : 0
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
/** Wait until the previous model's VRAM is actually released before loading the next. */
|
||||
async function waitForVram(minFreeMiB = 24000, timeoutMs = 30000): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs
|
||||
while (Date.now() < deadline) {
|
||||
if ((await gpuFreeMiB()) >= minFreeMiB) return
|
||||
await sleep(1000)
|
||||
}
|
||||
}
|
||||
|
||||
async function stopAll(): Promise<void> {
|
||||
try {
|
||||
await execFileAsync(
|
||||
"wsl.exe",
|
||||
[
|
||||
"-d",
|
||||
"Ubuntu",
|
||||
"--",
|
||||
"bash",
|
||||
"-lc",
|
||||
"pkill -f 'vllm serve' >/dev/null 2>&1 || true; pkill -f 'VLLM::EngineCore' >/dev/null 2>&1 || true; sleep 3",
|
||||
],
|
||||
{ timeout: 25000, windowsHide: true },
|
||||
)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
function launch(launcher: string): void {
|
||||
const child = spawn(
|
||||
"cmd.exe",
|
||||
["/c", "start", "", "/min", "wsl.exe", "-d", "Ubuntu", "--", "bash", launcher],
|
||||
{ detached: true, stdio: "ignore", windowsHide: true },
|
||||
)
|
||||
child.unref()
|
||||
}
|
||||
|
||||
async function readOwner(ctx: any): Promise<{ model: string } | undefined> {
|
||||
try {
|
||||
const value = (await ctx.storage.get(OWNER_KEY)) as { model?: unknown } | undefined
|
||||
if (value && typeof value.model === "string") return { model: value.model }
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
try {
|
||||
const model = (await readFile(OWNER_FILE, "utf8")).trim()
|
||||
if (model) return { model }
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
async function writeOwner(ctx: any, model: string): Promise<void> {
|
||||
try {
|
||||
await ctx.storage.set(OWNER_KEY, { model, startedAt: Date.now() })
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
await writeFile(OWNER_FILE, model, "utf8").catch(() => {})
|
||||
}
|
||||
|
||||
async function clearOwner(ctx: any): Promise<void> {
|
||||
try {
|
||||
await ctx.storage.remove(OWNER_KEY)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
await unlink(OWNER_FILE).catch(() => {})
|
||||
}
|
||||
|
||||
async function ensure(ctx: any, model: string): Promise<void> {
|
||||
if (await isServing(model)) return
|
||||
|
||||
await stopAll()
|
||||
await waitForVram()
|
||||
|
||||
const launcher = LAUNCHERS[model]
|
||||
if (!launcher) throw new Error(`vllm-autostart: no launcher for model ${model}`)
|
||||
|
||||
const token = ++startToken
|
||||
startingModel = model
|
||||
try {
|
||||
launch(launcher)
|
||||
// Owned from the moment we launch: eject must be able to stop a server
|
||||
// that is still loading.
|
||||
await writeOwner(ctx, model)
|
||||
|
||||
const deadline = Date.now() + READY_TIMEOUT_MS
|
||||
while (Date.now() < deadline) {
|
||||
if (token !== startToken) throw new Error("vllm-autostart: start cancelled")
|
||||
if (await isServing(model)) return
|
||||
await sleep(POLL_MS)
|
||||
}
|
||||
throw new Error(`vllm-autostart: server did not become ready for ${model} in time`)
|
||||
} finally {
|
||||
if (token === startToken) startingModel = null
|
||||
}
|
||||
}
|
||||
|
||||
async function onModel(ctx: any, model: any): Promise<void> {
|
||||
if (!model || model.providerID !== "vllm") return
|
||||
if (!(model.id in LAUNCHERS)) return
|
||||
if (await isServing(model.id)) return
|
||||
|
||||
if (!pending || pendingTarget !== model.id) {
|
||||
pendingTarget = model.id
|
||||
const generation = ++pendingGeneration
|
||||
pending = ensure(ctx, model.id).finally(() => {
|
||||
if (pendingGeneration === generation) {
|
||||
pending = null
|
||||
pendingTarget = null
|
||||
}
|
||||
})
|
||||
}
|
||||
await pending
|
||||
}
|
||||
|
||||
export default Plugin.define({
|
||||
id: "vllm-autostart",
|
||||
async setup(ctx) {
|
||||
await ctx.session.hook(
|
||||
"context",
|
||||
async (event: any) => {
|
||||
const modelID = event?.model?.id ?? ""
|
||||
const imageBudget = IMAGE_BUDGET[modelID] ?? 6
|
||||
const imageDropped = trimMedia(event?.messages, "image", imageBudget)
|
||||
if (imageDropped > 0) {
|
||||
console.error(`[vllm-autostart] trimmed ${imageDropped} image(s) for ${modelID} (budget ${imageBudget})`)
|
||||
}
|
||||
const videoBudget = VIDEO_BUDGET[modelID] ?? 1
|
||||
const videoDropped = trimMedia(event?.messages, "video", videoBudget)
|
||||
if (videoDropped > 0) {
|
||||
console.error(`[vllm-autostart] trimmed ${videoDropped} video(s) for ${modelID} (budget ${videoBudget})`)
|
||||
}
|
||||
await onModel(ctx, event?.model)
|
||||
},
|
||||
{ providerID: "vllm" },
|
||||
)
|
||||
|
||||
// A server can load this plugin for more than one location; the first
|
||||
// registration serves every window, so a duplicate is harmless.
|
||||
try {
|
||||
await ctx.rpc.register(Vllm, {
|
||||
status: async () => {
|
||||
const running = await servedModels()
|
||||
const owner = await readOwner(ctx)
|
||||
return {
|
||||
running: running.length > 0,
|
||||
owned: !!owner && running.includes(owner.model),
|
||||
starting: startingModel !== null,
|
||||
model: running[0] ?? "",
|
||||
}
|
||||
},
|
||||
eject: async () => {
|
||||
const owner = await readOwner(ctx)
|
||||
const running = await servedModels()
|
||||
const active = startingModel !== null || running.length > 0
|
||||
|
||||
if (!active) return { stopped: false, reason: "not-running" }
|
||||
// Refuse to stop a server this plugin did not start.
|
||||
if (!owner) return { stopped: false, reason: "not-owned" }
|
||||
if (running.length > 0 && !running.includes(owner.model)) {
|
||||
return { stopped: false, reason: "not-owned" }
|
||||
}
|
||||
|
||||
// Cancel any in-flight start so its poll loop stops waiting.
|
||||
startToken++
|
||||
startingModel = null
|
||||
pendingGeneration++
|
||||
pending = null
|
||||
pendingTarget = null
|
||||
|
||||
await stopAll()
|
||||
await clearOwner(ctx)
|
||||
return { stopped: true, reason: "stopped" }
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
if (!String(error).toLowerCase().includes("already")) throw error
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Rpc } from "@opencode/plugin/rpc"
|
||||
|
||||
const empty = {
|
||||
type: "object",
|
||||
properties: {},
|
||||
additionalProperties: false,
|
||||
} as const
|
||||
|
||||
/**
|
||||
* RPC between the server part (which owns the vLLM processes) and the Desktop
|
||||
* GUI (which shows the eject button).
|
||||
*/
|
||||
export const Vllm = Rpc.define({
|
||||
id: "vllm-autostart",
|
||||
methods: {
|
||||
status: {
|
||||
input: empty,
|
||||
output: {
|
||||
type: "object",
|
||||
properties: {
|
||||
running: { type: "boolean" },
|
||||
owned: { type: "boolean" },
|
||||
starting: { type: "boolean" },
|
||||
model: { type: "string" },
|
||||
},
|
||||
required: ["running", "owned", "starting", "model"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
eject: {
|
||||
input: empty,
|
||||
output: {
|
||||
type: "object",
|
||||
properties: {
|
||||
stopped: { type: "boolean" },
|
||||
reason: { type: "string" },
|
||||
},
|
||||
required: ["stopped", "reason"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
events: {},
|
||||
})
|
||||
@@ -0,0 +1,4 @@
|
||||
import { defineConfig } from "vite"
|
||||
import { gui } from "@opencode/plugin/gui/vite"
|
||||
|
||||
export default defineConfig({ plugins: [gui()] })
|
||||
@@ -0,0 +1,33 @@
|
||||
import json, urllib.request, time, sys
|
||||
BASE = "http://127.0.0.1:8000"
|
||||
|
||||
# discover served model
|
||||
m = json.loads(urllib.request.urlopen(BASE + "/v1/models", timeout=15).read())
|
||||
MODEL = m["data"][0]["id"]
|
||||
print("model:", MODEL)
|
||||
|
||||
def ask(prompt, n=128, temperature=0.7):
|
||||
body = json.dumps({
|
||||
"model": MODEL, "messages": [{"role": "user", "content": prompt}],
|
||||
"max_tokens": n, "temperature": temperature,
|
||||
"chat_template_kwargs": {"enable_thinking": False},
|
||||
}).encode()
|
||||
req = urllib.request.Request(BASE + "/v1/chat/completions", data=body,
|
||||
headers={"Content-Type": "application/json"})
|
||||
t0 = time.time()
|
||||
r = urllib.request.urlopen(req, timeout=300)
|
||||
dt = time.time() - t0
|
||||
j = json.loads(r.read())
|
||||
return dt, j["usage"]["completion_tokens"], j["choices"][0]["message"].get("content")
|
||||
|
||||
# warm
|
||||
dt, tok, _ = ask("Hi", 8)
|
||||
print(f"warmup : {dt:.2f}s {tok}tok")
|
||||
for label, prompt, n in [
|
||||
("chat ", "Write a short paragraph about why the sky is blue.", 120),
|
||||
("code ", "Write a Python function `fib(n)` with a docstring and a usage example. Concise.", 200),
|
||||
("json ", 'Return JSON only: {"name": "...", "age": 0, "city": "..."} for a fictional person named Ada.', 120),
|
||||
]:
|
||||
dt, tok, txt = ask(prompt, n)
|
||||
print(f"{label}: {dt:5.2f}s {tok:3d}tok -> {tok/dt:6.1f} tok/s")
|
||||
print(" ", (txt or "")[:160].replace("\n", " "))
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/bin/bash
|
||||
fail=0
|
||||
for f in /mnt/c/Users/dfj/projects/vllm-autostart/launchers/*.sh; do
|
||||
if ! bash -n "$f"; then
|
||||
echo "FAIL $f"
|
||||
fail=1
|
||||
fi
|
||||
done
|
||||
if [ "$fail" -eq 0 ]; then
|
||||
echo "all launcher scripts parse OK"
|
||||
fi
|
||||
exit "$fail"
|
||||
@@ -0,0 +1,13 @@
|
||||
import socket, urllib.request, json
|
||||
s = socket.socket(); s.settimeout(3)
|
||||
try:
|
||||
s.connect(("127.0.0.1", 8000)); print("PORT_OPEN")
|
||||
except Exception as e:
|
||||
print("PORT_CLOSED", repr(e))
|
||||
finally:
|
||||
s.close()
|
||||
try:
|
||||
r = urllib.request.urlopen("http://127.0.0.1:8000/v1/models", timeout=5)
|
||||
print("MODELS", json.loads(r.read())["data"][0]["id"])
|
||||
except Exception as e:
|
||||
print("NO_API", repr(e))
|
||||
@@ -0,0 +1,211 @@
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { promisify } from "node:util"
|
||||
import { writeFile, unlink } from "node:fs/promises"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
/**
|
||||
* WSL-side twin of the Windows vllm-autostart plugin.
|
||||
*
|
||||
* The Desktop runs a second server for WSL projects, and that server cannot
|
||||
* execute the Windows launchers (wsl.exe/cmd.exe). This one starts the same
|
||||
* models with the Linux launchers directly, so switching models works from a
|
||||
* WSL session too.
|
||||
*/
|
||||
|
||||
const LAUNCHER_DIR =
|
||||
process.env.VLLM_LAUNCHER_DIR ?? "/mnt/c/Users/dfj/projects/vllm-autostart/launchers"
|
||||
|
||||
const LAUNCHERS: Record<string, string> = {
|
||||
"qwen3.8-fast": `${LAUNCHER_DIR}/run_fast_unsloth.sh`,
|
||||
"qwen3.8-uncensored": `${LAUNCHER_DIR}/run_uncensored.sh`,
|
||||
"agents-a1": `${LAUNCHER_DIR}/run_agents_a1.sh`,
|
||||
"qwen3.6-35b-uncensored": `${LAUNCHER_DIR}/run_qwen36_unc.sh`,
|
||||
}
|
||||
|
||||
/** Shared with the Windows plugin so its eject button sees WSL-started models. */
|
||||
const OWNER_FILE = "/mnt/c/Users/dfj/.vllm-autostart-owner"
|
||||
|
||||
const READY_TIMEOUT_MS = 8 * 60 * 1000
|
||||
const POLL_MS = 3000
|
||||
|
||||
/**
|
||||
* Images allowed per model in one request. vLLM counts every image in the
|
||||
* prompt (history included), so old tool screenshots can exhaust the limit.
|
||||
* Keep these at or below the launchers' --limit-mm-per-prompt values.
|
||||
*/
|
||||
const IMAGE_BUDGET: Record<string, number> = {
|
||||
"qwen3.8-uncensored": 6,
|
||||
"qwen3.8-fast": 0,
|
||||
"agents-a1": 0,
|
||||
"qwen3.6-35b-uncensored": 8,
|
||||
}
|
||||
|
||||
/** Videos allowed per model in one request; vLLM counts the whole prompt. */
|
||||
const VIDEO_BUDGET: Record<string, number> = {
|
||||
"qwen3.6-35b-uncensored": 1,
|
||||
}
|
||||
|
||||
function mediaKind(node: any): "image" | "video" | null {
|
||||
if (!node || typeof node !== "object") return null
|
||||
let mime = ""
|
||||
if (node.type === "media") {
|
||||
mime = node.media?.source?.mediaType ?? node.media?.mediaType ?? ""
|
||||
} else if (node.type === "file") {
|
||||
mime = node.mime ?? ""
|
||||
}
|
||||
if (typeof mime !== "string") return null
|
||||
if (mime.startsWith("image/")) return "image"
|
||||
if (mime.startsWith("video/")) return "video"
|
||||
return null
|
||||
}
|
||||
|
||||
/** Replace the oldest media of one kind so the request fits the budget. */
|
||||
function trimMedia(messages: any, kind: "image" | "video", budget: number): number {
|
||||
if (!Array.isArray(messages)) return 0
|
||||
const found: Array<{ parent: any[]; index: number }> = []
|
||||
const walk = (node: any): void => {
|
||||
if (!node || typeof node !== "object" || ArrayBuffer.isView(node)) return
|
||||
if (Array.isArray(node)) {
|
||||
for (let i = 0; i < node.length; i++) {
|
||||
if (mediaKind(node[i]) === kind) found.push({ parent: node, index: i })
|
||||
else walk(node[i])
|
||||
}
|
||||
return
|
||||
}
|
||||
for (const value of Object.values(node)) walk(value)
|
||||
}
|
||||
walk(messages)
|
||||
|
||||
const excess = found.length - Math.max(0, budget)
|
||||
if (excess <= 0) return 0
|
||||
for (const { parent, index } of found.slice(0, excess)) {
|
||||
parent[index] = { type: "text", text: `[${kind} omitted: local model ${kind} limit reached]` }
|
||||
}
|
||||
return excess
|
||||
}
|
||||
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
async function servedModels(): Promise<string[]> {
|
||||
try {
|
||||
const res = await fetch("http://127.0.0.1:8000/v1/models", { signal: AbortSignal.timeout(3000) })
|
||||
const body = (await res.json()) as { data?: Array<{ id?: unknown }> }
|
||||
return (body.data ?? []).map((entry) => String(entry.id ?? "")).filter(Boolean)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
async function isServing(model: string): Promise<boolean> {
|
||||
return (await servedModels()).includes(model)
|
||||
}
|
||||
|
||||
async function gpuFreeMiB(): Promise<number> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
"nvidia-smi",
|
||||
["--query-gpu=memory.free", "--format=csv,noheader,nounits"],
|
||||
{ timeout: 5000 },
|
||||
)
|
||||
const n = parseInt(String(stdout).trim().split(/\r?\n/)[0], 10)
|
||||
return Number.isFinite(n) ? n : 0
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForVram(minFreeMiB = 24000, timeoutMs = 30000): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs
|
||||
while (Date.now() < deadline) {
|
||||
if ((await gpuFreeMiB()) >= minFreeMiB) return
|
||||
await sleep(1000)
|
||||
}
|
||||
}
|
||||
|
||||
async function stopAll(): Promise<void> {
|
||||
try {
|
||||
await execFileAsync(
|
||||
"bash",
|
||||
[
|
||||
"-lc",
|
||||
"pkill -f 'vllm serve' >/dev/null 2>&1 || true; pkill -f 'VLLM::EngineCore' >/dev/null 2>&1 || true; sleep 3",
|
||||
],
|
||||
{ timeout: 25000 },
|
||||
)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
function launch(script: string): void {
|
||||
const child = spawn("bash", [script], { detached: true, stdio: "ignore" })
|
||||
child.unref()
|
||||
}
|
||||
|
||||
let pending: Promise<void> | null = null
|
||||
let pendingTarget: string | null = null
|
||||
|
||||
async function ensure(model: string): Promise<void> {
|
||||
if (await isServing(model)) return
|
||||
|
||||
await unlink(OWNER_FILE).catch(() => {})
|
||||
await stopAll()
|
||||
await waitForVram()
|
||||
|
||||
const script = LAUNCHERS[model]
|
||||
if (!script) throw new Error(`vllm-autostart-wsl: no launcher for ${model}`)
|
||||
|
||||
launch(script)
|
||||
await writeFile(OWNER_FILE, model, "utf8").catch(() => {})
|
||||
|
||||
const deadline = Date.now() + READY_TIMEOUT_MS
|
||||
while (Date.now() < deadline) {
|
||||
if (await isServing(model)) return
|
||||
await sleep(POLL_MS)
|
||||
}
|
||||
throw new Error(`vllm-autostart-wsl: server did not become ready for ${model} in time`)
|
||||
}
|
||||
|
||||
async function onModel(model: any): Promise<void> {
|
||||
if (!model || model.providerID !== "vllm") return
|
||||
if (!(model.id in LAUNCHERS)) return
|
||||
if (await isServing(model.id)) return
|
||||
|
||||
if (!pending || pendingTarget !== model.id) {
|
||||
pendingTarget = model.id
|
||||
pending = ensure(model.id).finally(() => {
|
||||
pending = null
|
||||
pendingTarget = null
|
||||
})
|
||||
}
|
||||
await pending
|
||||
}
|
||||
|
||||
export default {
|
||||
id: "vllm-autostart-wsl",
|
||||
async setup(ctx: any) {
|
||||
await ctx.session.hook(
|
||||
"context",
|
||||
async (event: any) => {
|
||||
const modelID = event?.model?.id ?? ""
|
||||
const imageBudget = IMAGE_BUDGET[modelID] ?? 6
|
||||
const imageDropped = trimMedia(event?.messages, "image", imageBudget)
|
||||
if (imageDropped > 0) {
|
||||
console.error(`[vllm-autostart-wsl] trimmed ${imageDropped} image(s) for ${modelID} (budget ${imageBudget})`)
|
||||
}
|
||||
const videoBudget = VIDEO_BUDGET[modelID] ?? 1
|
||||
const videoDropped = trimMedia(event?.messages, "video", videoBudget)
|
||||
if (videoDropped > 0) {
|
||||
console.error(`[vllm-autostart-wsl] trimmed ${videoDropped} video(s) for ${modelID} (budget ${videoBudget})`)
|
||||
}
|
||||
try {
|
||||
await onModel(event?.model)
|
||||
} catch (error) {
|
||||
console.error("[vllm-autostart-wsl] " + String(error))
|
||||
}
|
||||
},
|
||||
{ providerID: "vllm" },
|
||||
)
|
||||
},
|
||||
}
|
||||
Reference in new issue
Block a user