Spaces:
Sleeping
Sleeping
Download server.js from ExocoreAi/Exocore-gateway: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/spaces/ExocoreAi/Exocore-gateway/resolve/main/server.js
- Command line
-
hf download hf://spaces/ExocoreAi/Exocore-gateway/server.js
-
curl -L -o server.js https://huggingface.co/spaces/ExocoreAi/Exocore-gateway/resolve/main/server.js
10.8 kB
| import { server, logger } from "@exocore/multi"; | |
| import { readFileSync, writeFileSync } from "fs"; | |
| import { fileURLToPath } from "url"; | |
| import path from "path"; | |
| import { | |
| DEFAULT_OPENCODE_MODEL, | |
| OPENCODE_MODELS, | |
| isOpenCodeModel, | |
| openCodeAnthropicModelObjects, | |
| openCodeContent, | |
| openCodeModelObjects, | |
| opencodeChat, | |
| } from "./src/core/opencode.js"; | |
| const __dirname = path.dirname(fileURLToPath(import.meta.url)); | |
| const DOCS_HTML = readFileSync(path.join(__dirname, "src/static/index.html"), "utf8"); | |
| const LOG_V1 = path.join(__dirname, "logs-v1.txt"); | |
| const PORT = process.env.PORT || 3000; | |
| const app = server.create({ | |
| port: PORT, | |
| prettyPrint: true, | |
| jiglet: "EXOCORE", | |
| cors: true, | |
| helmet: true, | |
| bodyParser: true, | |
| cookieParser: true, | |
| compression: true, | |
| rateLimit: { | |
| enabled: true, | |
| windowMs: 15 * 60 * 1000, | |
| max: 100, | |
| message: "Too many requests", | |
| }, | |
| }); | |
| function logV1(body, response) { | |
| const now = new Date().toISOString().replace("T", " ").slice(0, 19); | |
| const entry = `ββββββββββββββββββββββββββββββββββββββββββββββββββ\n${now}\nββ REQ ββ\n${JSON.stringify(body, null, 2)}\nββ RES ββ\n${JSON.stringify(response, null, 2)}\n\n`; | |
| writeFileSync(LOG_V1, entry, { flag: "a" }); | |
| } | |
| app.use((req, res, next) => { | |
| const origJson = res.json.bind(res); | |
| res.json = (data) => { | |
| origJson(data); | |
| if (req.method === "POST" && req.url?.startsWith("/v1/")) { | |
| logV1(req.body, data); | |
| } | |
| }; | |
| next(); | |
| }); | |
| app.get("/", (_req, res) => { | |
| res.setHeader("Content-Type", "text/html; charset=utf-8"); | |
| res.end(DOCS_HTML); | |
| }); | |
| app.get("/health", (_req, res) => { | |
| res.json({ | |
| status: "ok", | |
| provider: "opencode", | |
| models: OPENCODE_MODELS, | |
| }); | |
| }); | |
| function getAnthropicKey(req) { | |
| return req.headers["x-api-key"] || req.headers.authorization?.replace(/^Bearer\s+/i, ""); | |
| } | |
| function requireAnthroKey(req, res) { | |
| const key = getAnthropicKey(req); | |
| if (!key || !key.startsWith("sk-ant-")) { | |
| res.status(401).json({ | |
| error: { | |
| type: "authentication_error", | |
| message: "Invalid API key - use any sk-ant-* key", | |
| }, | |
| }); | |
| return false; | |
| } | |
| return true; | |
| } | |
| function normalizeTool(tool) { | |
| const source = tool.function ?? tool; | |
| return { | |
| name: source.name, | |
| description: source.description, | |
| schema: source.parameters ?? source.input_schema, | |
| }; | |
| } | |
| function buildToolPrompt(tools) { | |
| if (!Array.isArray(tools) || tools.length === 0) return ""; | |
| const lines = [ | |
| "", | |
| "## TOOL USE INSTRUCTIONS", | |
| "You have tools available. When a task requires a tool, output a tool call using exactly this format with no markdown and no extra text around it:", | |
| '[TOOL_CALL: tool_name] { "arg1": "value" } [/TOOL_CALL]', | |
| "", | |
| "Use tools only for tasks that need them. For greetings or simple answers, respond normally.", | |
| "", | |
| "### Available Tools:", | |
| ]; | |
| for (const raw of tools) { | |
| const tool = normalizeTool(raw); | |
| if (!tool.name) continue; | |
| lines.push("", `#### ${tool.name}`); | |
| if (tool.description) lines.push(`> ${tool.description}`); | |
| if (tool.schema?.properties) { | |
| const props = Object.entries(tool.schema.properties).map(([key, value]) => { | |
| const required = tool.schema.required?.includes(key) ? " (required)" : ""; | |
| return ` - ${key}${required}: ${value.description || value.type || "any"}`; | |
| }); | |
| lines.push(`Arguments:\n${props.join("\n")}`); | |
| } | |
| } | |
| return `\n\n${lines.join("\n")}`; | |
| } | |
| function contentToText(content) { | |
| if (typeof content === "string") return content; | |
| if (!Array.isArray(content)) return ""; | |
| return content | |
| .map((item) => { | |
| if (item.type === "text") return item.text ?? ""; | |
| if (item.type === "tool_use") return `[Tool Use: ${item.name}] ${JSON.stringify(item.input ?? {})}`; | |
| if (item.type === "tool_result") { | |
| const result = typeof item.content === "string" | |
| ? item.content | |
| : (item.content ?? []).map((part) => part.text || "").join(""); | |
| return `[Tool Result: ${item.tool_use_id}]\n${result}`; | |
| } | |
| if (item.type === "image_url") return "[Image omitted]"; | |
| return ""; | |
| }) | |
| .filter(Boolean) | |
| .join("\n"); | |
| } | |
| function messagesToPrompt(messages, system = "") { | |
| const parts = []; | |
| if (system) parts.push(`[System]: ${system}`); | |
| for (const msg of messages ?? []) { | |
| const text = contentToText(msg.content); | |
| if (!text) continue; | |
| if (msg.role === "system") parts.push(`[System]: ${text}`); | |
| else if (msg.role === "assistant" && msg.tool_calls) { | |
| const calls = msg.tool_calls | |
| .map((tc) => `[Tool Call: ${tc.function.name}] ${tc.function.arguments} [/Tool Call]`) | |
| .join("\n"); | |
| parts.push(`[Assistant]: ${text ? `${text}\n` : ""}${calls}`); | |
| } else if (msg.role === "assistant") parts.push(`[Assistant]: ${text}`); | |
| else if (msg.role === "tool") parts.push(`[Tool Result: ${msg.tool_call_id}]\n${text}`); | |
| else parts.push(`[User]: ${text}`); | |
| } | |
| return parts.join("\n\n"); | |
| } | |
| function parseToolCalls(text) { | |
| const calls = []; | |
| const re = /\[TOOL_CALL:\s*([A-Za-z0-9_-]+)\]\s*(\{.*?\})\s*\[\/TOOL_CALL\]/gs; | |
| let match; | |
| while ((match = re.exec(text)) !== null) { | |
| calls.push({ | |
| id: `call_${Date.now()}_${calls.length}`, | |
| type: "function", | |
| function: { name: match[1], arguments: match[2] }, | |
| }); | |
| } | |
| return calls; | |
| } | |
| function unsupportedModel(res, model) { | |
| res.status(400).json({ | |
| error: { | |
| message: `Model ${model} is not supported. Supported models: ${OPENCODE_MODELS.join(", ")}`, | |
| type: "invalid_request_error", | |
| }, | |
| }); | |
| } | |
| function getSupportedModel(raw, fallback = DEFAULT_OPENCODE_MODEL) { | |
| const model = raw || fallback; | |
| return isOpenCodeModel(model) ? model : null; | |
| } | |
| app.get("/v1/models", (req, res) => { | |
| const key = getAnthropicKey(req); | |
| if (key?.startsWith("sk-ant-")) { | |
| res.json({ data: openCodeAnthropicModelObjects() }); | |
| return; | |
| } | |
| res.json({ object: "list", data: openCodeModelObjects() }); | |
| }); | |
| app.post("/v1/chat/completions", async (req, res) => { | |
| const { messages, model, tools, max_tokens } = req.body ?? {}; | |
| if (!Array.isArray(messages) || messages.length === 0) { | |
| res.status(400).json({ | |
| error: { message: "`messages` array is required", type: "invalid_request_error" }, | |
| }); | |
| return; | |
| } | |
| const targetModel = getSupportedModel(model); | |
| if (!targetModel) { | |
| unsupportedModel(res, model); | |
| return; | |
| } | |
| const prompt = messagesToPrompt(messages) + buildToolPrompt(tools); | |
| if (!prompt.trim()) { | |
| res.status(400).json({ | |
| error: { message: "No content found", type: "invalid_request_error" }, | |
| }); | |
| return; | |
| } | |
| try { | |
| const upstream = await opencodeChat({ | |
| model: targetModel, | |
| messages: [{ role: "user", content: prompt }], | |
| maxTokens: max_tokens ?? 200, | |
| }); | |
| const choice = upstream?.choices?.[0]; | |
| const content = openCodeContent(upstream); | |
| const upstreamToolCalls = choice?.message?.tool_calls ?? []; | |
| const parsedToolCalls = upstreamToolCalls.length ? upstreamToolCalls : parseToolCalls(content); | |
| const message = { role: "assistant", content }; | |
| let finishReason = choice?.finish_reason || "stop"; | |
| if (parsedToolCalls.length) { | |
| message.tool_calls = parsedToolCalls; | |
| finishReason = "tool_calls"; | |
| } | |
| const result = { | |
| id: upstream?.id || `chatcmpl-${Date.now()}`, | |
| object: "chat.completion", | |
| created: upstream?.created || Math.floor(Date.now() / 1000), | |
| model: targetModel, | |
| choices: [{ index: 0, message, finish_reason: finishReason }], | |
| usage: upstream?.usage ?? { prompt_tokens: -1, completion_tokens: -1, total_tokens: -1 }, | |
| }; | |
| logger.info(`AI ${JSON.stringify({ model: targetModel, finish_reason: finishReason })}`); | |
| res.json(result); | |
| } catch (err) { | |
| const status = err.code === "auth_error" ? 401 : 500; | |
| res.status(status).json({ | |
| error: { | |
| message: err.message, | |
| type: status === 401 ? "authentication_error" : "api_error", | |
| }, | |
| }); | |
| } | |
| }); | |
| async function handleMessages(req, res, modelOverride) { | |
| if (!requireAnthroKey(req, res)) return; | |
| const { model, messages, system, max_tokens, tools } = req.body ?? {}; | |
| if (!Array.isArray(messages) || messages.length === 0) { | |
| res.status(400).json({ | |
| error: { type: "invalid_request_error", message: "messages required" }, | |
| }); | |
| return; | |
| } | |
| const targetModel = getSupportedModel(modelOverride || model); | |
| if (!targetModel) { | |
| unsupportedModel(res, modelOverride || model); | |
| return; | |
| } | |
| const systemText = Array.isArray(system) | |
| ? system.map((item) => item.type === "text" ? item.text : "").filter(Boolean).join("\n") | |
| : (system || ""); | |
| const prompt = messagesToPrompt(messages, systemText) + buildToolPrompt(tools); | |
| try { | |
| const upstream = await opencodeChat({ | |
| model: targetModel, | |
| messages: [{ role: "user", content: prompt }], | |
| maxTokens: max_tokens ?? 200, | |
| }); | |
| const content = openCodeContent(upstream); | |
| const textToolCalls = parseToolCalls(content); | |
| const responseContent = []; | |
| if (textToolCalls.length) { | |
| responseContent.push({ type: "text", text: "I will use the available tools to help you." }); | |
| for (const call of textToolCalls) { | |
| let input = {}; | |
| try { input = JSON.parse(call.function.arguments); } catch {} | |
| responseContent.push({ | |
| type: "tool_use", | |
| id: call.id, | |
| name: call.function.name, | |
| input, | |
| }); | |
| } | |
| } else { | |
| responseContent.push({ type: "text", text: content }); | |
| } | |
| res.json({ | |
| id: upstream?.id || `msg_${Date.now()}`, | |
| type: "message", | |
| role: "assistant", | |
| content: responseContent, | |
| model: targetModel, | |
| stop_reason: textToolCalls.length ? "tool_use" : "end_turn", | |
| stop_sequence: null, | |
| usage: { | |
| input_tokens: upstream?.usage?.prompt_tokens ?? -1, | |
| output_tokens: upstream?.usage?.completion_tokens ?? -1, | |
| }, | |
| }); | |
| } catch (err) { | |
| const status = err.code === "auth_error" ? 401 : 500; | |
| res.status(status).json({ | |
| error: { | |
| type: status === 401 ? "authentication_error" : "api_error", | |
| message: err.message, | |
| }, | |
| }); | |
| } | |
| } | |
| app.post("/v1/messages", (req, res) => handleMessages(req, res)); | |
| app.post("/:model/v1/messages", (req, res) => handleMessages(req, res, req.params.model)); | |
| try { writeFileSync(LOG_V1, ""); } catch {} | |
| await new Promise((resolve) => app.listen(PORT, resolve)); | |
| logger.info(`exocore gateway on :${PORT}`); | |
| logger.info(`opencode models: ${OPENCODE_MODELS.join(", ")}`); | |