bugxhunter 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +41 -0
- package/LICENSE +21 -0
- package/README.md +345 -2
- package/SECURITY.md +121 -0
- package/bin/bugxhunter.mjs +154 -0
- package/docker-compose.yml +118 -0
- package/package.json +37 -4
- package/scripts/vault-reset.mjs +30 -0
- package/server/dist/attachments.js +67 -0
- package/server/dist/audit.js +123 -0
- package/server/dist/auth.js +248 -0
- package/server/dist/env.js +15 -0
- package/server/dist/errors.js +3 -0
- package/server/dist/github.js +462 -0
- package/server/dist/index.js +783 -0
- package/server/dist/opencode.js +421 -0
- package/server/dist/providers.js +187 -0
- package/server/dist/rag.js +100 -0
- package/server/dist/scx.js +146 -0
- package/server/dist/vault.js +286 -0
- package/web/dist/assets/index-CqhtWJfv.css +1 -0
- package/web/dist/assets/index-DFfqRBl8.js +118 -0
- package/web/dist/claude-logo-ivory.svg +17 -0
- package/web/dist/example-tools.json +1 -0
- package/web/dist/favicon.png +0 -0
- package/web/dist/index.html +20 -0
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode bridge.
|
|
3
|
+
* -----------------------------------------------------------------------------
|
|
4
|
+
* Boots one OpenCode server via the official SDK and drives it on behalf of the
|
|
5
|
+
* browser. The SCX provider, its models and the API key come from the user's
|
|
6
|
+
* global OpenCode setup (~/.config/opencode + `opencode auth login`), so
|
|
7
|
+
* BugXHunter and the `opencode` CLI always agree on what's available.
|
|
8
|
+
*
|
|
9
|
+
* Inline config layered on top sets the BugXHunter defaults: GLM-5.3 for both
|
|
10
|
+
* agents and `ask` permissions for edits and shell commands, so every change
|
|
11
|
+
* the build agent makes is approved in the UI rather than running blind.
|
|
12
|
+
*
|
|
13
|
+
* Each request names the project folder it works in; one SDK client is kept
|
|
14
|
+
* per folder.
|
|
15
|
+
*/
|
|
16
|
+
import fs from "node:fs";
|
|
17
|
+
import os from "node:os";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { execFileSync } from "node:child_process";
|
|
20
|
+
import { fileURLToPath } from "node:url";
|
|
21
|
+
import { createOpencodeServer, createOpencodeClient } from "@opencode-ai/sdk";
|
|
22
|
+
import { httpError } from "./errors.js";
|
|
23
|
+
import { openrouterOpencodeProvider, OPENROUTER_MODELS, PORT } from "./providers.js";
|
|
24
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
25
|
+
/** BugXHunter's own folder: the default project when none is chosen. */
|
|
26
|
+
export const REPO_ROOT = path.resolve(__dirname, "../..");
|
|
27
|
+
/**
|
|
28
|
+
* Remote mode (Docker): OpenCode runs in its own sandboxed container and we
|
|
29
|
+
* talk to it over the network instead of spawning it. Project folders then
|
|
30
|
+
* live in that container, under WORKSPACE_ROOT.
|
|
31
|
+
*/
|
|
32
|
+
export const REMOTE_URL = process.env.OPENCODE_URL?.replace(/\/$/, "");
|
|
33
|
+
export const WORKSPACE_ROOT = process.env.OPEN_RUNNER_WORKSPACE ?? "/workspace";
|
|
34
|
+
export const DEFAULT_DIRECTORY = process.env.OPEN_RUNNER_DIR ?? (REMOTE_URL ? WORKSPACE_ROOT : REPO_ROOT);
|
|
35
|
+
export const DEFAULT_MODEL = process.env.OPEN_RUNNER_MODEL ?? "scx/GLM-5.3";
|
|
36
|
+
/**
|
|
37
|
+
* Config layered on the user's own OpenCode setup. With OPENROUTER_MODELS set,
|
|
38
|
+
* it adds an `openrouter` provider that calls back through this server's
|
|
39
|
+
* key-injecting proxy, so the OpenRouter key stays in the vault.
|
|
40
|
+
*/
|
|
41
|
+
async function inlineConfig() {
|
|
42
|
+
const openrouter = await openrouterOpencodeProvider(`http://127.0.0.1:${PORT}/openrouter/v1`);
|
|
43
|
+
return {
|
|
44
|
+
model: DEFAULT_MODEL,
|
|
45
|
+
agent: {
|
|
46
|
+
build: { model: DEFAULT_MODEL },
|
|
47
|
+
plan: { model: DEFAULT_MODEL },
|
|
48
|
+
},
|
|
49
|
+
permission: { edit: "ask", bash: "ask" },
|
|
50
|
+
...(openrouter ? { provider: { openrouter } } : {}),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** Fixed port, so a server orphaned by a hard restart can be found and stopped. */
|
|
54
|
+
const AGENT_PORT = Number(process.env.OPEN_RUNNER_AGENT_PORT ?? 8791);
|
|
55
|
+
let server = null;
|
|
56
|
+
const clients = new Map();
|
|
57
|
+
/** Stop the OpenCode child with us on a clean exit (Ctrl+C). */
|
|
58
|
+
let closeServer = null;
|
|
59
|
+
process.on("exit", () => closeServer?.());
|
|
60
|
+
for (const sig of ["SIGINT", "SIGTERM", "SIGHUP", "SIGBREAK"]) {
|
|
61
|
+
process.on(sig, () => {
|
|
62
|
+
closeServer?.();
|
|
63
|
+
process.exit(0);
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* A hard kill of this process (e.g. `tsx watch` restarting on Windows) skips
|
|
68
|
+
* the exit hooks and orphans the OpenCode child on AGENT_PORT. Before booting,
|
|
69
|
+
* stop whatever OpenCode server is still listening there.
|
|
70
|
+
*/
|
|
71
|
+
async function stopStaleServer() {
|
|
72
|
+
try {
|
|
73
|
+
const r = await fetch(`http://127.0.0.1:${AGENT_PORT}/global/health`, { signal: AbortSignal.timeout(1500) });
|
|
74
|
+
if (!(await r.json())?.healthy)
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return; // nothing (or nothing OpenCode) on the port
|
|
79
|
+
}
|
|
80
|
+
for (const pid of listenerPids(AGENT_PORT)) {
|
|
81
|
+
if (!isOpencodeProcess(pid))
|
|
82
|
+
continue;
|
|
83
|
+
try {
|
|
84
|
+
process.kill(pid);
|
|
85
|
+
console.log(` stopped stale OpenCode server (pid ${pid}) on port ${AGENT_PORT}`);
|
|
86
|
+
}
|
|
87
|
+
catch { /* already gone */ }
|
|
88
|
+
}
|
|
89
|
+
// Give the port a moment to free up.
|
|
90
|
+
for (let i = 0; i < 20; i++) {
|
|
91
|
+
try {
|
|
92
|
+
await fetch(`http://127.0.0.1:${AGENT_PORT}/global/health`, { signal: AbortSignal.timeout(300) });
|
|
93
|
+
await new Promise((r) => setTimeout(r, 150));
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function listenerPids(port) {
|
|
101
|
+
try {
|
|
102
|
+
if (process.platform === "win32") {
|
|
103
|
+
const out = execFileSync("netstat", ["-ano", "-p", "TCP"], { encoding: "utf8" });
|
|
104
|
+
return [...new Set(out.split(/\r?\n/)
|
|
105
|
+
.map((l) => l.trim().split(/\s+/))
|
|
106
|
+
.filter((c) => c[3] === "LISTENING" && c[1]?.endsWith(`:${port}`))
|
|
107
|
+
.map((c) => Number(c[4])))];
|
|
108
|
+
}
|
|
109
|
+
return execFileSync("lsof", ["-ti", `tcp:${port}`, "-sTCP:LISTEN"], { encoding: "utf8" })
|
|
110
|
+
.split(/\s+/).filter(Boolean).map(Number);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return [];
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function isOpencodeProcess(pid) {
|
|
117
|
+
try {
|
|
118
|
+
const name = process.platform === "win32"
|
|
119
|
+
? execFileSync("tasklist", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], { encoding: "utf8" })
|
|
120
|
+
: execFileSync("ps", ["-p", String(pid), "-o", "comm="], { encoding: "utf8" });
|
|
121
|
+
return /opencode/i.test(name);
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/** Boot (once) the OpenCode server, or point at the remote one. */
|
|
128
|
+
function getServer() {
|
|
129
|
+
if (REMOTE_URL)
|
|
130
|
+
return Promise.resolve({ url: REMOTE_URL, close() { } });
|
|
131
|
+
if (!server) {
|
|
132
|
+
server = stopStaleServer()
|
|
133
|
+
.then(inlineConfig)
|
|
134
|
+
.then((config) => createOpencodeServer({ hostname: "127.0.0.1", port: AGENT_PORT, timeout: 15000, config: config }))
|
|
135
|
+
.then((s) => {
|
|
136
|
+
closeServer = () => {
|
|
137
|
+
try {
|
|
138
|
+
s.close();
|
|
139
|
+
}
|
|
140
|
+
catch { /* already gone */ }
|
|
141
|
+
};
|
|
142
|
+
console.log(` OpenCode agent server: ${s.url}`);
|
|
143
|
+
return s;
|
|
144
|
+
})
|
|
145
|
+
.catch((e) => {
|
|
146
|
+
server = null; // allow retry on next request
|
|
147
|
+
throw e;
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
return server;
|
|
151
|
+
}
|
|
152
|
+
export { httpError };
|
|
153
|
+
const notFound = (dir) => httpError(400, `Folder not found: ${dir}`);
|
|
154
|
+
/**
|
|
155
|
+
* Local mode: folders the browser may open, from OPEN_RUNNER_ALLOWED_ROOTS
|
|
156
|
+
* (a PATH-style list). Unset means any folder on this machine, which is fine
|
|
157
|
+
* for a single user on localhost but not once a password + reverse proxy
|
|
158
|
+
* expose the app to others.
|
|
159
|
+
*/
|
|
160
|
+
export const ALLOWED_ROOTS = (process.env.OPEN_RUNNER_ALLOWED_ROOTS ?? "")
|
|
161
|
+
.split(path.delimiter).map((s) => s.trim()).filter(Boolean).map((r) => path.resolve(r));
|
|
162
|
+
const isInside = (abs, root) => {
|
|
163
|
+
const [a, r] = process.platform === "win32" ? [abs.toLowerCase(), root.toLowerCase()] : [abs, root];
|
|
164
|
+
return a === r || a.startsWith(r.endsWith(path.sep) ? r : r + path.sep);
|
|
165
|
+
};
|
|
166
|
+
/**
|
|
167
|
+
* Where GitHub clones land (github.ts): `<CLONE_ROOT>/<owner>/<repo>`. In
|
|
168
|
+
* Docker that is the workspace volume, which the agent mounts at the same
|
|
169
|
+
* path. Locally it is OPEN_RUNNER_WORKSPACE, else ~/bugxhunter/repos, and a
|
|
170
|
+
* restricted install (OPEN_RUNNER_ALLOWED_ROOTS) may always open what it cloned.
|
|
171
|
+
*/
|
|
172
|
+
export const CLONE_ROOT = REMOTE_URL
|
|
173
|
+
? WORKSPACE_ROOT
|
|
174
|
+
: path.resolve(process.env.OPEN_RUNNER_WORKSPACE ?? path.join(os.homedir(), "bugxhunter", "repos"));
|
|
175
|
+
if (!REMOTE_URL && ALLOWED_ROOTS.length && !ALLOWED_ROOTS.some((r) => isInside(CLONE_ROOT, r)))
|
|
176
|
+
ALLOWED_ROOTS.push(CLONE_ROOT);
|
|
177
|
+
/** Normalise and validate a project folder from the browser. */
|
|
178
|
+
export async function resolveDirectory(dir) {
|
|
179
|
+
const raw = typeof dir === "string" && dir.trim() ? dir.trim() : DEFAULT_DIRECTORY;
|
|
180
|
+
if (REMOTE_URL) {
|
|
181
|
+
// The folder lives in the agent container: keep it inside the workspace
|
|
182
|
+
// and ask OpenCode whether it exists (listing a missing folder fails).
|
|
183
|
+
const abs = path.posix.resolve(WORKSPACE_ROOT, raw.replace(/\\/g, "/"));
|
|
184
|
+
if (abs !== WORKSPACE_ROOT && !abs.startsWith(WORKSPACE_ROOT + "/")) {
|
|
185
|
+
throw httpError(400, `Projects must be inside ${WORKSPACE_ROOT}`);
|
|
186
|
+
}
|
|
187
|
+
const r = await fetch(`${REMOTE_URL}/file?path=.&directory=${encodeURIComponent(abs)}`).catch(() => null);
|
|
188
|
+
if (!r?.ok)
|
|
189
|
+
throw notFound(abs);
|
|
190
|
+
return abs;
|
|
191
|
+
}
|
|
192
|
+
const abs = path.resolve(raw);
|
|
193
|
+
if (ALLOWED_ROOTS.length && !ALLOWED_ROOTS.some((root) => isInside(abs, root))) {
|
|
194
|
+
throw httpError(400, `Projects must be inside: ${ALLOWED_ROOTS.join(", ")}`);
|
|
195
|
+
}
|
|
196
|
+
if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory())
|
|
197
|
+
throw notFound(abs);
|
|
198
|
+
return abs;
|
|
199
|
+
}
|
|
200
|
+
/** SDK client scoped to one project folder. */
|
|
201
|
+
export async function getClient(directory) {
|
|
202
|
+
const { url } = await getServer();
|
|
203
|
+
let c = clients.get(directory);
|
|
204
|
+
if (!c) {
|
|
205
|
+
c = createOpencodeClient({ baseUrl: url, directory });
|
|
206
|
+
clients.set(directory, c);
|
|
207
|
+
}
|
|
208
|
+
return c;
|
|
209
|
+
}
|
|
210
|
+
export async function serverUrl() {
|
|
211
|
+
return (await getServer()).url;
|
|
212
|
+
}
|
|
213
|
+
/** Query string from an object, skipping undefined values. */
|
|
214
|
+
export function query(params) {
|
|
215
|
+
const q = new URLSearchParams();
|
|
216
|
+
for (const [k, v] of Object.entries(params))
|
|
217
|
+
if (v !== undefined)
|
|
218
|
+
q.set(k, String(v));
|
|
219
|
+
const s = q.toString();
|
|
220
|
+
return s ? `?${s}` : "";
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Call an OpenCode route the SDK doesn't wrap (or wraps awkwardly). A non-2xx
|
|
224
|
+
* reply becomes an error carrying the status, which sendError() forwards.
|
|
225
|
+
*/
|
|
226
|
+
export async function oc(path, init = {}) {
|
|
227
|
+
const { json, headers, ...rest } = init;
|
|
228
|
+
const r = await fetch(`${await serverUrl()}${path}`, {
|
|
229
|
+
...rest,
|
|
230
|
+
headers: { ...(json !== undefined ? { "Content-Type": "application/json" } : {}), ...headers },
|
|
231
|
+
body: json !== undefined ? JSON.stringify(json) : rest.body,
|
|
232
|
+
});
|
|
233
|
+
const text = await r.text().catch(() => "");
|
|
234
|
+
if (!r.ok)
|
|
235
|
+
throw httpError(r.status, text.slice(0, 500) || `OpenCode replied ${r.status}`);
|
|
236
|
+
return (text ? JSON.parse(text) : undefined);
|
|
237
|
+
}
|
|
238
|
+
/** "scx/GLM-5.3" -> { providerID: "scx", modelID: "GLM-5.3" }. */
|
|
239
|
+
export function parseModelId(id) {
|
|
240
|
+
if (!id)
|
|
241
|
+
return undefined;
|
|
242
|
+
const i = id.indexOf("/");
|
|
243
|
+
if (i === -1)
|
|
244
|
+
return undefined;
|
|
245
|
+
return { providerID: id.slice(0, i), modelID: id.slice(i + 1) };
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Every model OpenCode can use, as "provider/model" ids. OpenCode merges our
|
|
249
|
+
* `openrouter` provider with its own catalogue of that provider (hundreds of
|
|
250
|
+
* models, all routed through the proxy); the picker shows only the ids in
|
|
251
|
+
* OPENROUTER_MODELS so it stays usable.
|
|
252
|
+
*/
|
|
253
|
+
export async function listAgentModels(client) {
|
|
254
|
+
const r = await client.config.providers();
|
|
255
|
+
const providers = r?.data?.providers ?? [];
|
|
256
|
+
const out = [];
|
|
257
|
+
const allowed = new Set(OPENROUTER_MODELS);
|
|
258
|
+
for (const p of providers) {
|
|
259
|
+
for (const [mid, m] of Object.entries(p.models ?? {})) {
|
|
260
|
+
if (p.id === "openrouter" && allowed.size && !allowed.has(mid))
|
|
261
|
+
continue;
|
|
262
|
+
out.push({
|
|
263
|
+
id: `${p.id}/${mid}`,
|
|
264
|
+
name: m.name ?? mid,
|
|
265
|
+
provider: p.name ?? p.id,
|
|
266
|
+
context: m.limit?.context,
|
|
267
|
+
output: m.limit?.output,
|
|
268
|
+
images: Boolean(m.attachment || m.modalities?.input?.includes?.("image") || m.capabilities?.input?.image),
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return out;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Collapse a raw OpenCode event into the compact shape the browser renders.
|
|
276
|
+
* Returns null for events the UI doesn't care about.
|
|
277
|
+
*/
|
|
278
|
+
export function toUiEvent(evt) {
|
|
279
|
+
const type = evt?.type;
|
|
280
|
+
const p = evt?.properties;
|
|
281
|
+
if (!type)
|
|
282
|
+
return null;
|
|
283
|
+
switch (type) {
|
|
284
|
+
case "message.updated": {
|
|
285
|
+
// Lets the UI attribute text parts (the user's own prompt streams back
|
|
286
|
+
// as a text part too) to the right role.
|
|
287
|
+
const info = p?.info;
|
|
288
|
+
if (!info?.id)
|
|
289
|
+
return null;
|
|
290
|
+
return {
|
|
291
|
+
kind: "message",
|
|
292
|
+
messageID: info.id,
|
|
293
|
+
role: info.role,
|
|
294
|
+
tokens: info.tokens,
|
|
295
|
+
cost: info.cost,
|
|
296
|
+
model: info.modelID ? `${info.providerID}/${info.modelID}` : undefined,
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
case "message.part.updated": {
|
|
300
|
+
const part = p?.part;
|
|
301
|
+
if (!part)
|
|
302
|
+
return null;
|
|
303
|
+
if (part.type === "text" && part.text) {
|
|
304
|
+
return { kind: "text", messageID: part.messageID, partID: part.id, text: part.text };
|
|
305
|
+
}
|
|
306
|
+
if (part.type === "reasoning" && part.text) {
|
|
307
|
+
return { kind: "reasoning", messageID: part.messageID, partID: part.id, text: part.text };
|
|
308
|
+
}
|
|
309
|
+
if (part.type === "tool") {
|
|
310
|
+
const st = part.state ?? {};
|
|
311
|
+
return {
|
|
312
|
+
kind: "tool",
|
|
313
|
+
messageID: part.messageID,
|
|
314
|
+
callID: part.callID,
|
|
315
|
+
tool: part.tool,
|
|
316
|
+
status: st.status,
|
|
317
|
+
title: st.title,
|
|
318
|
+
input: st.input,
|
|
319
|
+
output: typeof st.output === "string" ? st.output.slice(0, 20000) : undefined,
|
|
320
|
+
error: st.error,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
case "permission.updated":
|
|
326
|
+
case "permission.asked": {
|
|
327
|
+
// Older servers put the request in `properties`, newer ones may nest it.
|
|
328
|
+
const perm = p?.id ? p : p?.permission ?? p;
|
|
329
|
+
if (!perm?.id)
|
|
330
|
+
return null;
|
|
331
|
+
return {
|
|
332
|
+
kind: "permission",
|
|
333
|
+
sessionID: perm.sessionID,
|
|
334
|
+
permissionID: perm.id,
|
|
335
|
+
permType: perm.type ?? (typeof perm.permission === "string" ? perm.permission : undefined),
|
|
336
|
+
title: perm.title,
|
|
337
|
+
pattern: perm.pattern ?? perm.patterns,
|
|
338
|
+
callID: perm.callID ?? perm.tool?.callID,
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
case "todo.updated":
|
|
342
|
+
return { kind: "todo", sessionID: p?.sessionID, todos: p?.todos ?? [] };
|
|
343
|
+
case "session.updated": {
|
|
344
|
+
const info = p?.info;
|
|
345
|
+
return info?.id ? { kind: "session", sessionID: info.id, title: info.title } : null;
|
|
346
|
+
}
|
|
347
|
+
case "question.asked":
|
|
348
|
+
case "question.v2.asked": {
|
|
349
|
+
if (!p?.id)
|
|
350
|
+
return null;
|
|
351
|
+
return {
|
|
352
|
+
kind: "question",
|
|
353
|
+
sessionID: p.sessionID,
|
|
354
|
+
requestID: p.id,
|
|
355
|
+
questions: p.questions ?? [],
|
|
356
|
+
callID: p.tool?.callID,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
case "question.replied":
|
|
360
|
+
case "question.rejected":
|
|
361
|
+
case "question.v2.replied":
|
|
362
|
+
case "question.v2.rejected":
|
|
363
|
+
return { kind: "question-closed", requestID: p?.requestID };
|
|
364
|
+
case "permission.replied":
|
|
365
|
+
return { kind: "permission-replied", permissionID: p?.permissionID ?? p?.requestID ?? p?.id };
|
|
366
|
+
case "session.error":
|
|
367
|
+
return { kind: "error", message: errorText(p?.error) };
|
|
368
|
+
case "session.idle":
|
|
369
|
+
return { kind: "idle", sessionID: p?.sessionID };
|
|
370
|
+
default:
|
|
371
|
+
return null;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Stored messages (GET /session/:id/message) -> the same shape the browser
|
|
376
|
+
* builds from live events, so a resumed chat renders like a live one.
|
|
377
|
+
*/
|
|
378
|
+
export function toUiMessages(raw) {
|
|
379
|
+
return raw.map((m) => {
|
|
380
|
+
const info = m.info ?? {};
|
|
381
|
+
const parts = [];
|
|
382
|
+
for (const p of m.parts ?? []) {
|
|
383
|
+
if (p.type === "text" && p.text && !p.synthetic)
|
|
384
|
+
parts.push({ type: "text", id: p.id, text: p.text });
|
|
385
|
+
else if (p.type === "reasoning" && p.text)
|
|
386
|
+
parts.push({ type: "reasoning", id: p.id, text: p.text });
|
|
387
|
+
else if (p.type === "tool") {
|
|
388
|
+
const st = p.state ?? {};
|
|
389
|
+
parts.push({
|
|
390
|
+
type: "tool", callID: p.callID, tool: p.tool, status: st.status, title: st.title, input: st.input,
|
|
391
|
+
output: typeof st.output === "string" ? st.output.slice(0, 20000) : undefined, error: st.error,
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
else if (p.type === "file") {
|
|
395
|
+
parts.push({
|
|
396
|
+
type: "file", id: p.id, filename: p.filename, mime: p.mime,
|
|
397
|
+
// Keep inline images for thumbnails; drop file:// URLs (meaningless to the browser).
|
|
398
|
+
url: typeof p.url === "string" && p.url.startsWith("data:image/") ? p.url : undefined,
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
return {
|
|
403
|
+
id: info.id,
|
|
404
|
+
role: info.role,
|
|
405
|
+
parts,
|
|
406
|
+
tokens: info.tokens,
|
|
407
|
+
cost: info.cost,
|
|
408
|
+
model: info.modelID ? `${info.providerID}/${info.modelID}` : undefined,
|
|
409
|
+
error: info.error ? errorText(info.error) : undefined,
|
|
410
|
+
};
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
/** Pull a readable message out of an OpenCode error payload. */
|
|
414
|
+
function errorText(err) {
|
|
415
|
+
const msg = err?.data?.message ?? err?.message ?? err?.name;
|
|
416
|
+
const status = err?.data?.statusCode;
|
|
417
|
+
if (msg)
|
|
418
|
+
return status ? `${msg} (HTTP ${status})` : String(msg);
|
|
419
|
+
return JSON.stringify(err ?? {}).slice(0, 600);
|
|
420
|
+
}
|
|
421
|
+
//# sourceMappingURL=opencode.js.map
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model providers. SCX.ai is the default; OpenRouter is optional and opens up
|
|
3
|
+
* its catalogue (https://openrouter.ai/models). Both speak the OpenAI API, so
|
|
4
|
+
* one client class and one key-injecting proxy serve both.
|
|
5
|
+
*
|
|
6
|
+
* Keys: the vault item (SCX_API, OPENROUTER_API_KEY) first, then .env, then
|
|
7
|
+
* OpenCode's own auth store. They are read once here and scrubbed from the
|
|
8
|
+
* environment: the OpenCode server is spawned with a copy of our environment,
|
|
9
|
+
* and the agent's shell inherits that.
|
|
10
|
+
*
|
|
11
|
+
* In the Playground, OpenRouter models are addressed as `openrouter/<id>`.
|
|
12
|
+
* For the agent, OPENROUTER_MODELS (comma list of OpenRouter ids) is turned
|
|
13
|
+
* into an OpenCode provider that calls back through the runner's proxy, so
|
|
14
|
+
* the key stays here in both local and Docker modes.
|
|
15
|
+
*/
|
|
16
|
+
import crypto from "node:crypto";
|
|
17
|
+
import fs from "node:fs";
|
|
18
|
+
import os from "node:os";
|
|
19
|
+
import path from "node:path";
|
|
20
|
+
import { SCXClient } from "./scx.js";
|
|
21
|
+
import { httpError } from "./errors.js";
|
|
22
|
+
import * as vault from "./vault.js";
|
|
23
|
+
export const PROVIDERS = {
|
|
24
|
+
scx: {
|
|
25
|
+
id: "scx", name: "SCX.ai", baseUrl: process.env.SCX_BASE_URL ?? "https://api.scx.ai/v1",
|
|
26
|
+
vaultItem: "SCX_API", envVars: ["SCX_API", "SCX_API_KEY"], authId: "scx",
|
|
27
|
+
},
|
|
28
|
+
openrouter: {
|
|
29
|
+
id: "openrouter", name: "OpenRouter", baseUrl: process.env.OPENROUTER_BASE_URL ?? "https://openrouter.ai/api/v1",
|
|
30
|
+
vaultItem: "OPENROUTER_API_KEY", envVars: ["OPENROUTER_API_KEY"], authId: "openrouter",
|
|
31
|
+
// Attribution headers OpenRouter asks apps to send.
|
|
32
|
+
headers: { "HTTP-Referer": "https://bugxhunter.com", "X-Title": "BugXHunter" },
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
/** OpenRouter ids the agent may use (OPENROUTER_MODELS=anthropic/claude-sonnet-4.5,openai/gpt-5). */
|
|
36
|
+
export const OPENROUTER_MODELS = (process.env.OPENROUTER_MODELS ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
37
|
+
export const PORT = Number(process.env.PORT ?? 8790);
|
|
38
|
+
/**
|
|
39
|
+
* The token the agent presents to the proxy. From .env in Docker (both
|
|
40
|
+
* containers read it); random per process in local mode, where it is handed
|
|
41
|
+
* to the OpenCode child inside its inline config rather than the environment.
|
|
42
|
+
*/
|
|
43
|
+
export const PROXY_TOKEN = process.env.SCX_PROXY_TOKEN || crypto.randomBytes(24).toString("base64url");
|
|
44
|
+
function readAuthStore() {
|
|
45
|
+
try {
|
|
46
|
+
const file = path.join(os.homedir(), ".local", "share", "opencode", "auth.json");
|
|
47
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
48
|
+
return Object.fromEntries(Object.entries(parsed).map(([k, v]) => [k, v?.key ?? ""]));
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return {};
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const envKeys = {};
|
|
55
|
+
const authKeys = readAuthStore();
|
|
56
|
+
for (const p of Object.values(PROVIDERS)) {
|
|
57
|
+
for (const v of p.envVars)
|
|
58
|
+
if (process.env[v]) {
|
|
59
|
+
envKeys[p.id] = process.env[v];
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
for (const v of p.envVars)
|
|
63
|
+
delete process.env[v];
|
|
64
|
+
}
|
|
65
|
+
for (const k of ["SCX_PROXY_TOKEN", "OPEN_RUNNER_SECRET"])
|
|
66
|
+
delete process.env[k];
|
|
67
|
+
/** Where a provider's key comes from right now. */
|
|
68
|
+
export function keySource(id) {
|
|
69
|
+
const p = PROVIDERS[id];
|
|
70
|
+
if (vault.isInitialised() && vault.status("none").items.includes(p.vaultItem))
|
|
71
|
+
return "vault";
|
|
72
|
+
if (envKeys[id])
|
|
73
|
+
return "env";
|
|
74
|
+
if (authKeys[p.authId])
|
|
75
|
+
return "opencode-auth";
|
|
76
|
+
return "none";
|
|
77
|
+
}
|
|
78
|
+
export const configured = (id) => keySource(id) !== "none";
|
|
79
|
+
/** The key for this call. Throws a 503 the client can explain (vault sealed, no key). */
|
|
80
|
+
export function apiKey(id) {
|
|
81
|
+
const p = PROVIDERS[id];
|
|
82
|
+
switch (keySource(id)) {
|
|
83
|
+
case "vault": return vault.getItem(p.vaultItem); // throws 503 while sealed
|
|
84
|
+
case "env": return envKeys[id];
|
|
85
|
+
case "opencode-auth": return authKeys[p.authId];
|
|
86
|
+
default:
|
|
87
|
+
throw httpError(503, id === "scx"
|
|
88
|
+
? "No SCX API key. Set up the vault in the sidebar, or run `opencode auth login` (provider id: scx)."
|
|
89
|
+
: "No OpenRouter key. Add OPENROUTER_API_KEY to the vault (keys dialog) to use OpenRouter models.");
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export const clients = {
|
|
93
|
+
scx: new SCXClient({ apiKey: () => apiKey("scx"), baseUrl: PROVIDERS.scx.baseUrl }),
|
|
94
|
+
openrouter: new SCXClient({ apiKey: () => apiKey("openrouter"), baseUrl: PROVIDERS.openrouter.baseUrl, headers: PROVIDERS.openrouter.headers }),
|
|
95
|
+
};
|
|
96
|
+
/** Playground model ids: SCX ids as-is, OpenRouter ids prefixed `openrouter/`. */
|
|
97
|
+
export function clientFor(model) {
|
|
98
|
+
if (model.startsWith("openrouter/"))
|
|
99
|
+
return { client: clients.openrouter, model: model.slice("openrouter/".length), provider: "openrouter" };
|
|
100
|
+
return { client: clients.scx, model, provider: "scx" };
|
|
101
|
+
}
|
|
102
|
+
const SAMPLING = new Set(["temperature", "top_p", "top_k", "max_tokens", "stop", "frequency_penalty", "presence_penalty", "repetition_penalty", "seed", "min_p", "top_a"]);
|
|
103
|
+
export function normaliseOpenRouter(m) {
|
|
104
|
+
const params = m.supported_parameters ?? [];
|
|
105
|
+
const features = [];
|
|
106
|
+
if (params.includes("tools") || params.includes("tool_choice"))
|
|
107
|
+
features.push("tools");
|
|
108
|
+
if (params.includes("response_format") || params.includes("structured_outputs"))
|
|
109
|
+
features.push("json_mode");
|
|
110
|
+
if (params.includes("reasoning") || params.includes("include_reasoning"))
|
|
111
|
+
features.push("reasoning");
|
|
112
|
+
return {
|
|
113
|
+
id: `openrouter/${m.id}`,
|
|
114
|
+
name: m.name ?? m.id,
|
|
115
|
+
created: m.created ?? 0,
|
|
116
|
+
input_modalities: m.architecture?.input_modalities ?? ["text"],
|
|
117
|
+
output_modalities: m.architecture?.output_modalities ?? ["text"],
|
|
118
|
+
context_length: m.context_length ?? null,
|
|
119
|
+
max_output_length: m.top_provider?.max_completion_tokens ?? null,
|
|
120
|
+
pricing: m.pricing ?? {},
|
|
121
|
+
supported_sampling_parameters: params.filter((p) => SAMPLING.has(p)),
|
|
122
|
+
supported_features: features,
|
|
123
|
+
description: m.description,
|
|
124
|
+
provider: "openrouter",
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/** OpenRouter's catalogue is public: no key needed, so limits are known even while the vault is sealed. */
|
|
128
|
+
async function openRouterCatalogue() {
|
|
129
|
+
const r = await fetch(`${PROVIDERS.openrouter.baseUrl}/models`, { headers: PROVIDERS.openrouter.headers, signal: AbortSignal.timeout(10_000) });
|
|
130
|
+
if (!r.ok)
|
|
131
|
+
throw new Error(`OpenRouter /models replied ${r.status}`);
|
|
132
|
+
return (await r.json()).data ?? [];
|
|
133
|
+
}
|
|
134
|
+
/** Every model the Playground can use: SCX's, plus OpenRouter's when a key is configured. */
|
|
135
|
+
export async function listModels() {
|
|
136
|
+
const scx = (await clients.scx.listModels()).map((m) => ({ ...m, provider: "scx" }));
|
|
137
|
+
if (!configured("openrouter"))
|
|
138
|
+
return scx;
|
|
139
|
+
try {
|
|
140
|
+
const all = (await openRouterCatalogue()).map(normaliseOpenRouter);
|
|
141
|
+
const allow = new Set(OPENROUTER_MODELS.map((id) => `openrouter/${id}`));
|
|
142
|
+
const picked = allow.size ? all.filter((m) => allow.has(m.id)) : all;
|
|
143
|
+
return [...scx, ...picked.sort((a, b) => a.name.localeCompare(b.name))];
|
|
144
|
+
}
|
|
145
|
+
catch (e) {
|
|
146
|
+
console.error("[openrouter] model list failed:", e.message);
|
|
147
|
+
return scx;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* An OpenCode provider for the agent, calling back through the runner's
|
|
152
|
+
* proxy with the proxy token, for the models in OPENROUTER_MODELS. Context
|
|
153
|
+
* and output limits come from OpenRouter's public catalogue; defaults if it
|
|
154
|
+
* is unreachable.
|
|
155
|
+
*/
|
|
156
|
+
export async function openrouterOpencodeProvider(proxyBaseUrl) {
|
|
157
|
+
if (!OPENROUTER_MODELS.length)
|
|
158
|
+
return null;
|
|
159
|
+
const limits = new Map();
|
|
160
|
+
try {
|
|
161
|
+
for (const m of await openRouterCatalogue()) {
|
|
162
|
+
limits.set(m.id, { context: m.context_length, output: m.top_provider?.max_completion_tokens, images: m.architecture?.input_modalities?.includes("image") });
|
|
163
|
+
}
|
|
164
|
+
for (const id of OPENROUTER_MODELS)
|
|
165
|
+
if (!limits.has(id))
|
|
166
|
+
console.error(`[openrouter] OPENROUTER_MODELS: "${id}" is not in OpenRouter's catalogue (check the id)`);
|
|
167
|
+
}
|
|
168
|
+
catch (e) {
|
|
169
|
+
console.error("[openrouter] could not fetch model limits, using defaults:", e.message);
|
|
170
|
+
}
|
|
171
|
+
const models = {};
|
|
172
|
+
for (const id of OPENROUTER_MODELS) {
|
|
173
|
+
const l = limits.get(id);
|
|
174
|
+
models[id] = {
|
|
175
|
+
name: id,
|
|
176
|
+
limit: { context: l?.context ?? 128_000, output: l?.output ?? 16_000 },
|
|
177
|
+
...(l?.images ? { attachment: true, modalities: { input: ["text", "image"], output: ["text"] } } : {}),
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
npm: "@ai-sdk/openai-compatible",
|
|
182
|
+
name: "OpenRouter",
|
|
183
|
+
options: { baseURL: proxyBaseUrl, apiKey: PROXY_TOKEN },
|
|
184
|
+
models,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
//# sourceMappingURL=providers.js.map
|