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:
dfj committed 2026-11-01 00:18:38 +01:00
commit 40656fd046
27 files changed
+6710

No files matched your search

+51
View File
@@ -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.
+1
View File
@@ -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;
+5420
View File
File diff suppressed because it is too large. Load diff
+23
View File
@@ -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"
}
}
+107
View File
@@ -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(),
}))
},
})
+319
View File
@@ -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
}
},
})
+44
View File
@@ -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: {},
})
+4
View File
@@ -0,0 +1,4 @@
import { defineConfig } from "vite"
import { gui } from "@opencode/plugin/gui/vite"
export default defineConfig({ plugins: [gui()] })