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 = { "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 = { "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 = { "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((resolve) => setTimeout(resolve, ms)) async function servedModels(): Promise { 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 { return (await servedModels()).includes(model) } async function gpuFreeMiB(): Promise { 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 { const deadline = Date.now() + timeoutMs while (Date.now() < deadline) { if ((await gpuFreeMiB()) >= minFreeMiB) return await sleep(1000) } } async function stopAll(): Promise { 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 | null = null let pendingTarget: string | null = null async function ensure(model: string): Promise { 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 { 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" }, ) }, }