|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * OpenAI-compatible HTTP surface for Qwen Code CLI (knowledge corpus at /corpus). |
| 4 | + * Used by mcp-server with QWEN_MODE=http and QWEN_API_URL=http://qwen-search:8790 |
| 5 | + */ |
| 6 | +import http from "node:http"; |
| 7 | +import { spawn } from "node:child_process"; |
| 8 | + |
| 9 | +const PORT = parseInt(process.env.QWEN_HTTP_PORT || "8790", 10); |
| 10 | +const TIMEOUT_MS = parseInt(process.env.QWEN_TIMEOUT_MS || "120000", 10); |
| 11 | +const MAX_STDOUT = parseInt(process.env.QWEN_SEARCH_MAX_STDOUT || "524288", 10); |
| 12 | +const LISTEN = process.env.QWEN_HTTP_BIND || "0.0.0.0"; |
| 13 | + |
| 14 | +function extractQwenCliResult(stdout) { |
| 15 | + const trimmed = stdout.trim(); |
| 16 | + if (!trimmed) { |
| 17 | + throw new Error("Qwen returned empty output"); |
| 18 | + } |
| 19 | + const parsed = JSON.parse(trimmed); |
| 20 | + if (!Array.isArray(parsed)) { |
| 21 | + throw new Error("Qwen output is not a JSON array"); |
| 22 | + } |
| 23 | + const resultEvent = parsed.find((entry) => entry?.type === "result") ?? null; |
| 24 | + if (resultEvent === null || typeof resultEvent.result !== "string") { |
| 25 | + throw new Error("Qwen output is missing a final result event"); |
| 26 | + } |
| 27 | + let text = resultEvent.result.trim(); |
| 28 | + text = text |
| 29 | + .replace(/^```json\s*/i, "") |
| 30 | + .replace(/^```\s*/i, "") |
| 31 | + .replace(/\s*```$/, "") |
| 32 | + .trim(); |
| 33 | + return text; |
| 34 | +} |
| 35 | + |
| 36 | +function messagesToPrompt(messages) { |
| 37 | + if (!Array.isArray(messages)) { |
| 38 | + return ""; |
| 39 | + } |
| 40 | + return messages |
| 41 | + .map((m) => { |
| 42 | + const role = typeof m.role === "string" ? m.role : "user"; |
| 43 | + const content = typeof m.content === "string" ? m.content : JSON.stringify(m.content ?? ""); |
| 44 | + return `${role}:\n${content}`; |
| 45 | + }) |
| 46 | + .join("\n\n---\n\n"); |
| 47 | +} |
| 48 | + |
| 49 | +function runQwenPrompt(prompt) { |
| 50 | + return new Promise((resolve, reject) => { |
| 51 | + const child = spawn("qwen", ["--output-format", "json", "--prompt", prompt], { |
| 52 | + env: { |
| 53 | + ...process.env, |
| 54 | + QWEN_OAUTH: process.env.QWEN_OAUTH || "true", |
| 55 | + }, |
| 56 | + stdio: ["ignore", "pipe", "pipe"], |
| 57 | + }); |
| 58 | + const chunks = []; |
| 59 | + let stderr = ""; |
| 60 | + let size = 0; |
| 61 | + const timer = setTimeout(() => { |
| 62 | + try { |
| 63 | + child.kill("SIGKILL"); |
| 64 | + } catch { |
| 65 | + /* ignore */ |
| 66 | + } |
| 67 | + reject(new Error("Qwen search timeout")); |
| 68 | + }, TIMEOUT_MS); |
| 69 | + |
| 70 | + child.stdout?.on("data", (buf) => { |
| 71 | + size += buf.length; |
| 72 | + if (size > MAX_STDOUT) { |
| 73 | + clearTimeout(timer); |
| 74 | + try { |
| 75 | + child.kill("SIGKILL"); |
| 76 | + } catch { |
| 77 | + /* ignore */ |
| 78 | + } |
| 79 | + reject(new Error("Qwen stdout exceeded max size")); |
| 80 | + return; |
| 81 | + } |
| 82 | + chunks.push(buf); |
| 83 | + }); |
| 84 | + child.stderr?.on("data", (buf) => { |
| 85 | + stderr += buf.toString(); |
| 86 | + }); |
| 87 | + child.on("error", (err) => { |
| 88 | + clearTimeout(timer); |
| 89 | + reject(err); |
| 90 | + }); |
| 91 | + child.on("close", (code) => { |
| 92 | + clearTimeout(timer); |
| 93 | + if (code !== 0) { |
| 94 | + reject(new Error(stderr.trim() || `Qwen exited with status ${code}`)); |
| 95 | + return; |
| 96 | + } |
| 97 | + resolve(Buffer.concat(chunks).toString("utf8")); |
| 98 | + }); |
| 99 | + }); |
| 100 | +} |
| 101 | + |
| 102 | +function openAiChatCompletion(content) { |
| 103 | + return JSON.stringify({ |
| 104 | + id: "qwen-search", |
| 105 | + object: "chat.completion", |
| 106 | + model: "qwen-search", |
| 107 | + choices: [{ message: { role: "assistant", content } }], |
| 108 | + }); |
| 109 | +} |
| 110 | + |
| 111 | +async function handleRequest(req, res) { |
| 112 | + const url = req.url ?? "/"; |
| 113 | + |
| 114 | + if (req.method === "GET" && url.startsWith("/health")) { |
| 115 | + res.writeHead(200, { "content-type": "application/json" }); |
| 116 | + res.end(JSON.stringify({ status: "ok", service: "qwen-search" })); |
| 117 | + return; |
| 118 | + } |
| 119 | + |
| 120 | + if (req.method === "POST" && url.startsWith("/v1/chat/completions")) { |
| 121 | + let body = ""; |
| 122 | + for await (const chunk of req) { |
| 123 | + body += chunk; |
| 124 | + } |
| 125 | + try { |
| 126 | + const json = JSON.parse(body || "{}"); |
| 127 | + const prompt = messagesToPrompt(json.messages); |
| 128 | + if (!prompt.trim()) { |
| 129 | + res.writeHead(400, { "content-type": "application/json" }); |
| 130 | + res.end(JSON.stringify({ error: "messages required" })); |
| 131 | + return; |
| 132 | + } |
| 133 | + const stdout = await runQwenPrompt(prompt); |
| 134 | + const assistantContent = extractQwenCliResult(stdout); |
| 135 | + res.writeHead(200, { "content-type": "application/json" }); |
| 136 | + res.end(openAiChatCompletion(assistantContent)); |
| 137 | + } catch (err) { |
| 138 | + const message = err instanceof Error ? err.message : String(err); |
| 139 | + res.writeHead(502, { "content-type": "application/json" }); |
| 140 | + res.end(JSON.stringify({ error: message })); |
| 141 | + } |
| 142 | + return; |
| 143 | + } |
| 144 | + |
| 145 | + res.writeHead(404, { "content-type": "application/json" }); |
| 146 | + res.end(JSON.stringify({ error: "not_found" })); |
| 147 | +} |
| 148 | + |
| 149 | +http |
| 150 | + .createServer((req, res) => { |
| 151 | + handleRequest(req, res).catch((err) => { |
| 152 | + const message = err instanceof Error ? err.message : String(err); |
| 153 | + if (!res.headersSent) { |
| 154 | + res.writeHead(500, { "content-type": "application/json" }); |
| 155 | + } |
| 156 | + res.end(JSON.stringify({ error: message })); |
| 157 | + }); |
| 158 | + }) |
| 159 | + .listen(PORT, LISTEN, () => { |
| 160 | + console.error(`qwen-search HTTP listening on http://${LISTEN}:${PORT}`); |
| 161 | + }); |
0 commit comments