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,783 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BugXHunter backend.
|
|
3
|
+
*
|
|
4
|
+
* A thin Express server in front of OpenCode (the coding agent) and the SCX
|
|
5
|
+
* platform (the playground chat). The SCX API key stays server-side; the
|
|
6
|
+
* browser only ever talks to this server. Streams are forwarded as
|
|
7
|
+
* Server-Sent Events.
|
|
8
|
+
*/
|
|
9
|
+
import "./env.js"; // first: loads .env before the modules below read process.env
|
|
10
|
+
import express from "express";
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { SCXError } from "./scx.js";
|
|
14
|
+
import { PROVIDERS, PROXY_TOKEN, PORT, OPENROUTER_MODELS, apiKey, clients, clientFor, keySource, listModels } from "./providers.js";
|
|
15
|
+
import { KnowledgeBase, buildContextBlock } from "./rag.js";
|
|
16
|
+
import { getClient, serverUrl, resolveDirectory, listAgentModels, toUiEvent, toUiMessages, parseModelId, oc, query, httpError, DEFAULT_DIRECTORY, DEFAULT_MODEL, REMOTE_URL, REPO_ROOT, ALLOWED_ROOTS, } from "./opencode.js";
|
|
17
|
+
import { mountAuth, authRequired, issueSession } from "./auth.js";
|
|
18
|
+
import { audit, followOpencode, LOG_DIR } from "./audit.js";
|
|
19
|
+
import { saveAttachments } from "./attachments.js";
|
|
20
|
+
import * as vault from "./vault.js";
|
|
21
|
+
import * as github from "./github.js";
|
|
22
|
+
// Keys, the proxy token and the provider clients live in providers.ts, which
|
|
23
|
+
// also scrubs every secret from the environment before OpenCode is spawned.
|
|
24
|
+
const scx = clients.scx;
|
|
25
|
+
const kb = new KnowledgeBase(scx); // in-memory RAG store (POC scope)
|
|
26
|
+
const app = express();
|
|
27
|
+
app.disable("x-powered-by");
|
|
28
|
+
// Behind a reverse proxy, trust its X-Forwarded-* headers so req.ip is the
|
|
29
|
+
// real client (the login rate limit is per IP) and req.secure sees HTTPS.
|
|
30
|
+
// Express accepts a hop count ("1"), "loopback", a CIDR list, or true/false.
|
|
31
|
+
const TRUST_PROXY = process.env.TRUST_PROXY;
|
|
32
|
+
if (TRUST_PROXY) {
|
|
33
|
+
app.set("trust proxy", /^\d+$/.test(TRUST_PROXY) ? Number(TRUST_PROXY) : TRUST_PROXY === "true" ? true : TRUST_PROXY);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Key-injecting proxy for the agent, one route per provider (/scx/v1, and
|
|
37
|
+
* /openrouter/v1). The agent's OpenCode talks to these with the proxy token,
|
|
38
|
+
* and we forward chat/model calls upstream with the real key. So no provider
|
|
39
|
+
* key ever enters the container (or, locally, the process) the agent's shell
|
|
40
|
+
* runs in. Mounted before the JSON parser so request bodies pass through
|
|
41
|
+
* untouched.
|
|
42
|
+
*/
|
|
43
|
+
const PROXY_PATHS = new Set(["/chat/completions", "/models"]);
|
|
44
|
+
for (const p of Object.values(PROVIDERS)) {
|
|
45
|
+
const prefix = `/${p.id}/v1`;
|
|
46
|
+
app.all(`${prefix}/*`, async (req, res) => {
|
|
47
|
+
const sub = req.path.slice(prefix.length);
|
|
48
|
+
const auth = req.headers.authorization ?? "";
|
|
49
|
+
if (auth !== `Bearer ${PROXY_TOKEN}`)
|
|
50
|
+
return res.status(401).json({ error: { message: "bad proxy token" } });
|
|
51
|
+
if (!PROXY_PATHS.has(sub))
|
|
52
|
+
return res.status(404).json({ error: { message: `not proxied: ${sub}` } });
|
|
53
|
+
try {
|
|
54
|
+
const chunks = [];
|
|
55
|
+
for await (const c of req)
|
|
56
|
+
chunks.push(c);
|
|
57
|
+
const ctrl = new AbortController();
|
|
58
|
+
res.on("close", () => ctrl.abort());
|
|
59
|
+
const upstream = await fetch(p.baseUrl + sub + (req.url.includes("?") ? req.url.slice(req.url.indexOf("?")) : ""), {
|
|
60
|
+
method: req.method,
|
|
61
|
+
headers: {
|
|
62
|
+
Authorization: `Bearer ${apiKey(p.id)}`,
|
|
63
|
+
...(p.headers ?? {}),
|
|
64
|
+
"Content-Type": req.headers["content-type"] ?? "application/json",
|
|
65
|
+
Accept: req.headers.accept ?? "*/*",
|
|
66
|
+
},
|
|
67
|
+
body: req.method === "GET" || req.method === "HEAD" ? undefined : Buffer.concat(chunks),
|
|
68
|
+
signal: ctrl.signal,
|
|
69
|
+
});
|
|
70
|
+
res.status(upstream.status);
|
|
71
|
+
const type = upstream.headers.get("content-type");
|
|
72
|
+
if (type)
|
|
73
|
+
res.setHeader("Content-Type", type);
|
|
74
|
+
if (!upstream.body)
|
|
75
|
+
return res.end();
|
|
76
|
+
for await (const chunk of upstream.body)
|
|
77
|
+
res.write(chunk);
|
|
78
|
+
res.end();
|
|
79
|
+
}
|
|
80
|
+
catch (e) {
|
|
81
|
+
if (!res.headersSent)
|
|
82
|
+
res.status(e.status ?? 502).json({ error: { message: String(e.message ?? e) } });
|
|
83
|
+
else
|
|
84
|
+
res.end();
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* DNS-rebinding guard. A malicious page can point a hostname it controls at
|
|
90
|
+
* 127.0.0.1 and then call this API from the victim's browser; the Host header
|
|
91
|
+
* still names the attacker's domain, so refuse anything but our own names.
|
|
92
|
+
* Add the names a reverse proxy serves under via ALLOWED_HOSTS.
|
|
93
|
+
*/
|
|
94
|
+
const ALLOWED_HOSTS = new Set([
|
|
95
|
+
"localhost", "127.0.0.1", "[::1]",
|
|
96
|
+
...(process.env.ALLOWED_HOSTS ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean),
|
|
97
|
+
]);
|
|
98
|
+
app.use("/api", (req, res, next) => {
|
|
99
|
+
const host = (req.headers.host ?? "").toLowerCase().replace(/:\d+$/, "");
|
|
100
|
+
if (ALLOWED_HOSTS.has(host))
|
|
101
|
+
return next();
|
|
102
|
+
res.status(403).json({ error: { message: `Host "${host}" is not allowed. Add it to ALLOWED_HOSTS.` } });
|
|
103
|
+
});
|
|
104
|
+
// Prompts can carry attachments (base64), so allow larger bodies there.
|
|
105
|
+
app.use("/api/agent/prompt", express.json({ limit: "40mb" }));
|
|
106
|
+
app.use(express.json({ limit: "4mb" }));
|
|
107
|
+
mountAuth(app, ALLOWED_HOSTS);
|
|
108
|
+
// Any authenticated write counts as activity for the vault's auto-lock (reads
|
|
109
|
+
// don't, so the sidebar's status polling can't keep it open).
|
|
110
|
+
app.use("/api", (req, _res, next) => {
|
|
111
|
+
if (req.method !== "GET")
|
|
112
|
+
vault.touch();
|
|
113
|
+
next();
|
|
114
|
+
});
|
|
115
|
+
const sendError = (res, e) => {
|
|
116
|
+
if (e instanceof SCXError) {
|
|
117
|
+
// The provider rejecting our key is a configuration problem here, not the
|
|
118
|
+
// browser's session: report it as an upstream failure with a pointer.
|
|
119
|
+
if (e.status === 401 || e.status === 403) {
|
|
120
|
+
return res.status(502).json({ error: { message: `SCX rejected the API key (${e.status}: ${e.message}). Check the SCX_API key in the vault.`, type: e.type } });
|
|
121
|
+
}
|
|
122
|
+
return res.status(e.status).json({ error: { message: e.message, type: e.type } });
|
|
123
|
+
}
|
|
124
|
+
const status = e?.status;
|
|
125
|
+
if (status)
|
|
126
|
+
return res.status(status).json({ error: { message: e.message } });
|
|
127
|
+
console.error("[server error]", e);
|
|
128
|
+
return res.status(500).json({ error: { message: String(e?.message ?? e) } });
|
|
129
|
+
};
|
|
130
|
+
app.get("/api/health", (_req, res) => res.json({ ok: true, baseUrl: PROVIDERS.scx.baseUrl }));
|
|
131
|
+
// --- Key vault (see shared/vault.d.ts) --------------------------------------
|
|
132
|
+
// The browser does the key derivation and wrapping; these routes only store
|
|
133
|
+
// ciphertext, accept an unseal key into memory, and manage sealed items.
|
|
134
|
+
app.get("/api/vault", (_req, res) => res.json(vault.status(keySource("scx"))));
|
|
135
|
+
app.post("/api/vault/init", (req, res) => {
|
|
136
|
+
try {
|
|
137
|
+
const { doc, dek } = req.body ?? {};
|
|
138
|
+
if (!doc || typeof dek !== "string")
|
|
139
|
+
return res.status(400).json({ error: { message: "doc and dek required" } });
|
|
140
|
+
vault.initialise(doc, dek);
|
|
141
|
+
// Creating the vault turns sign-in on; the browser that created it is signed in.
|
|
142
|
+
issueSession(req, res);
|
|
143
|
+
res.json(vault.status(keySource("scx")));
|
|
144
|
+
}
|
|
145
|
+
catch (e) {
|
|
146
|
+
sendError(res, e);
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
app.post("/api/vault/unseal", (req, res) => {
|
|
150
|
+
try {
|
|
151
|
+
if (typeof req.body?.dek !== "string")
|
|
152
|
+
return res.status(400).json({ error: { message: "dek required" } });
|
|
153
|
+
vault.unseal(req.body.dek);
|
|
154
|
+
res.json(vault.status(keySource("scx")));
|
|
155
|
+
}
|
|
156
|
+
catch (e) {
|
|
157
|
+
sendError(res, e);
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
app.post("/api/vault/seal", (_req, res) => {
|
|
161
|
+
vault.sealVault();
|
|
162
|
+
res.json(vault.status(keySource("scx")));
|
|
163
|
+
});
|
|
164
|
+
app.put("/api/vault/items/:name", (req, res) => {
|
|
165
|
+
try {
|
|
166
|
+
if (typeof req.body?.value !== "string")
|
|
167
|
+
return res.status(400).json({ error: { message: "value required" } });
|
|
168
|
+
vault.setItem(req.params.name, req.body.value);
|
|
169
|
+
res.json(vault.status(keySource("scx")));
|
|
170
|
+
}
|
|
171
|
+
catch (e) {
|
|
172
|
+
sendError(res, e);
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
app.delete("/api/vault/items/:name", (req, res) => {
|
|
176
|
+
try {
|
|
177
|
+
vault.deleteItem(req.params.name);
|
|
178
|
+
res.json(vault.status(keySource("scx")));
|
|
179
|
+
}
|
|
180
|
+
catch (e) {
|
|
181
|
+
sendError(res, e);
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
/** Enrol another passkey. The browser must prove it holds the current key (it wrapped it for the new method). */
|
|
185
|
+
app.post("/api/vault/methods", (req, res) => {
|
|
186
|
+
try {
|
|
187
|
+
const { method, dek } = req.body ?? {};
|
|
188
|
+
if (!method || typeof dek !== "string")
|
|
189
|
+
return res.status(400).json({ error: { message: "method and dek required" } });
|
|
190
|
+
vault.addMethod(method, dek);
|
|
191
|
+
res.json(vault.status(keySource("scx")));
|
|
192
|
+
}
|
|
193
|
+
catch (e) {
|
|
194
|
+
sendError(res, e);
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
app.delete("/api/vault/methods/:id", (req, res) => {
|
|
198
|
+
try {
|
|
199
|
+
vault.removeMethod(req.params.id);
|
|
200
|
+
res.json(vault.status(keySource("scx")));
|
|
201
|
+
}
|
|
202
|
+
catch (e) {
|
|
203
|
+
sendError(res, e);
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
/**
|
|
207
|
+
* Delete the vault, to recreate it with new factors. Needs the current key as
|
|
208
|
+
* proof, so it is a rotation tool for the owner, not a way around the lock.
|
|
209
|
+
* Lost every factor? Reset from the server instead: `npm run vault:reset`.
|
|
210
|
+
*/
|
|
211
|
+
app.delete("/api/vault", (req, res) => {
|
|
212
|
+
try {
|
|
213
|
+
if (typeof req.body?.dek !== "string")
|
|
214
|
+
return res.status(400).json({ error: { message: "dek required" } });
|
|
215
|
+
vault.destroy(req.body.dek);
|
|
216
|
+
res.json(vault.status(keySource("scx")));
|
|
217
|
+
}
|
|
218
|
+
catch (e) {
|
|
219
|
+
sendError(res, e);
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
/** List models (with capabilities + pricing) for the playground's model picker. */
|
|
223
|
+
// --- GitHub, read-only (see shared/github.d.ts) ------------------------------
|
|
224
|
+
app.get("/api/github", async (_req, res) => {
|
|
225
|
+
try {
|
|
226
|
+
res.json(await github.status());
|
|
227
|
+
}
|
|
228
|
+
catch (e) {
|
|
229
|
+
sendError(res, e);
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
app.post("/api/github/connect/start", async (_req, res) => {
|
|
233
|
+
try {
|
|
234
|
+
res.json(await github.connectStart());
|
|
235
|
+
}
|
|
236
|
+
catch (e) {
|
|
237
|
+
sendError(res, e);
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
app.post("/api/github/connect/poll", async (req, res) => {
|
|
241
|
+
try {
|
|
242
|
+
const r = await github.connectPoll(req.body?.id);
|
|
243
|
+
if (r.status === "connected")
|
|
244
|
+
audit("github.connected", { login: r.login, storage: r.storage });
|
|
245
|
+
res.json(r);
|
|
246
|
+
}
|
|
247
|
+
catch (e) {
|
|
248
|
+
sendError(res, e);
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
app.delete("/api/github/connect", (_req, res) => {
|
|
252
|
+
try {
|
|
253
|
+
github.disconnect();
|
|
254
|
+
audit("github.disconnected");
|
|
255
|
+
res.json({ ok: true });
|
|
256
|
+
}
|
|
257
|
+
catch (e) {
|
|
258
|
+
sendError(res, e);
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
app.get("/api/github/repos", async (_req, res) => {
|
|
262
|
+
try {
|
|
263
|
+
res.json({ repos: await github.listRepos() });
|
|
264
|
+
}
|
|
265
|
+
catch (e) {
|
|
266
|
+
sendError(res, e);
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
app.get("/api/github/branches", async (req, res) => {
|
|
270
|
+
try {
|
|
271
|
+
res.json({ branches: await github.listBranches(req.query.repo) });
|
|
272
|
+
}
|
|
273
|
+
catch (e) {
|
|
274
|
+
sendError(res, e);
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
/** Clone into the workspace, or fast-forward the clone already there. Slow: a big repository takes a while. */
|
|
278
|
+
app.post("/api/github/clone", async (req, res) => {
|
|
279
|
+
try {
|
|
280
|
+
const result = await github.cloneOrUpdate({ repo: req.body?.repo, branch: req.body?.branch });
|
|
281
|
+
audit("github.clone", { repo: req.body?.repo, ...result });
|
|
282
|
+
res.json(result);
|
|
283
|
+
}
|
|
284
|
+
catch (e) {
|
|
285
|
+
audit("github.clone.failed", { repo: req.body?.repo, error: String(e.message ?? e) });
|
|
286
|
+
sendError(res, e);
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
app.get("/api/models", async (_req, res) => {
|
|
290
|
+
try {
|
|
291
|
+
res.json({ data: await listModels() });
|
|
292
|
+
}
|
|
293
|
+
catch (e) {
|
|
294
|
+
sendError(res, e);
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
/**
|
|
298
|
+
* Chat endpoint. If `stream: true`, forwards SCX's SSE stream to the client.
|
|
299
|
+
* Otherwise returns the full completion JSON.
|
|
300
|
+
*/
|
|
301
|
+
app.post("/api/chat", async (req, res) => {
|
|
302
|
+
const { rag, ragTopK, ...params } = req.body;
|
|
303
|
+
let retrieved = [];
|
|
304
|
+
try {
|
|
305
|
+
// RAG: retrieve context for the latest user turn and inject it as a system preamble.
|
|
306
|
+
if (rag && kb.size) {
|
|
307
|
+
const lastUser = [...params.messages].reverse().find((m) => m.role === "user");
|
|
308
|
+
const query = typeof lastUser?.content === "string" ? lastUser.content : "";
|
|
309
|
+
if (query) {
|
|
310
|
+
retrieved = await kb.search(query, ragTopK ?? 4);
|
|
311
|
+
const block = buildContextBlock(retrieved);
|
|
312
|
+
if (block) {
|
|
313
|
+
const sys = params.messages.find((m) => m.role === "system");
|
|
314
|
+
if (sys && typeof sys.content === "string")
|
|
315
|
+
sys.content = `${sys.content}\n\n${block}`;
|
|
316
|
+
else
|
|
317
|
+
params.messages.unshift({ role: "system", content: block });
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const { client, model } = clientFor(String(params.model ?? ""));
|
|
322
|
+
const call = { ...params, model };
|
|
323
|
+
if (params.stream) {
|
|
324
|
+
const upstream = await client.chatStreamResponse(call);
|
|
325
|
+
res.setHeader("Content-Type", "text/event-stream");
|
|
326
|
+
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
327
|
+
res.setHeader("Connection", "keep-alive");
|
|
328
|
+
res.flushHeaders?.();
|
|
329
|
+
// Surface RAG sources to the client before the model tokens stream in.
|
|
330
|
+
if (retrieved.length) {
|
|
331
|
+
const sources = retrieved.map((r) => ({ doc: r.doc, score: Number(r.score.toFixed(3)) }));
|
|
332
|
+
res.write(`data: ${JSON.stringify({ scx_sources: sources })}\n\n`);
|
|
333
|
+
}
|
|
334
|
+
const reader = upstream.body.getReader();
|
|
335
|
+
const decoder = new TextDecoder();
|
|
336
|
+
req.on("close", () => reader.cancel().catch(() => { }));
|
|
337
|
+
while (true) {
|
|
338
|
+
const { value, done } = await reader.read();
|
|
339
|
+
if (done)
|
|
340
|
+
break;
|
|
341
|
+
res.write(decoder.decode(value, { stream: true }));
|
|
342
|
+
}
|
|
343
|
+
res.end();
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
const completion = await client.chat(call);
|
|
347
|
+
res.json(retrieved.length
|
|
348
|
+
? { ...completion, scx_sources: retrieved.map((r) => ({ doc: r.doc, score: Number(r.score.toFixed(3)) })) }
|
|
349
|
+
: completion);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
catch (e) {
|
|
353
|
+
// If headers already sent (mid-stream), emit an SSE error event instead.
|
|
354
|
+
if (res.headersSent) {
|
|
355
|
+
const msg = e instanceof SCXError ? e.message : String(e?.message ?? e);
|
|
356
|
+
res.write(`data: ${JSON.stringify({ error: { message: msg } })}\n\n`);
|
|
357
|
+
res.end();
|
|
358
|
+
}
|
|
359
|
+
else {
|
|
360
|
+
sendError(res, e);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
});
|
|
364
|
+
/** Embeddings passthrough. */
|
|
365
|
+
app.post("/api/embeddings", async (req, res) => {
|
|
366
|
+
try {
|
|
367
|
+
res.json(await scx.embeddings(req.body));
|
|
368
|
+
}
|
|
369
|
+
catch (e) {
|
|
370
|
+
sendError(res, e);
|
|
371
|
+
}
|
|
372
|
+
});
|
|
373
|
+
// --- Knowledge base (embeddings-backed RAG) -------------------------------
|
|
374
|
+
app.get("/api/kb", (_req, res) => res.json({ docs: kb.list() }));
|
|
375
|
+
app.post("/api/kb", async (req, res) => {
|
|
376
|
+
try {
|
|
377
|
+
const { name, text } = req.body;
|
|
378
|
+
if (!text?.trim())
|
|
379
|
+
return res.status(400).json({ error: { message: "text is required" } });
|
|
380
|
+
const doc = await kb.addDocument(name ?? "", text);
|
|
381
|
+
res.json({ id: doc.id, name: doc.name, chunks: doc.chunks.length, chars: doc.chars, docs: kb.list() });
|
|
382
|
+
}
|
|
383
|
+
catch (e) {
|
|
384
|
+
sendError(res, e);
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
app.delete("/api/kb/:id", (req, res) => {
|
|
388
|
+
kb.remove(req.params.id);
|
|
389
|
+
res.json({ docs: kb.list() });
|
|
390
|
+
});
|
|
391
|
+
app.delete("/api/kb", (_req, res) => {
|
|
392
|
+
kb.clear();
|
|
393
|
+
res.json({ docs: kb.list() });
|
|
394
|
+
});
|
|
395
|
+
// --- OpenCode agent --------------------------------------------------------
|
|
396
|
+
// The build agent reads/writes files and runs commands in the chosen project
|
|
397
|
+
// folder, so edits flow through the permission endpoints below.
|
|
398
|
+
/** hey-api style result -> data, throwing on error. */
|
|
399
|
+
function unwrap(r) {
|
|
400
|
+
if (r?.error)
|
|
401
|
+
throw httpError(400, typeof r.error === "string" ? r.error : JSON.stringify(r.error));
|
|
402
|
+
return r.data;
|
|
403
|
+
}
|
|
404
|
+
/** Boot the agent server and report defaults + the models it can use. */
|
|
405
|
+
app.get("/api/agent/status", async (_req, res) => {
|
|
406
|
+
try {
|
|
407
|
+
const directory = await resolveDirectory(DEFAULT_DIRECTORY);
|
|
408
|
+
const client = await getClient(directory);
|
|
409
|
+
res.json({
|
|
410
|
+
ready: true,
|
|
411
|
+
url: await serverUrl(),
|
|
412
|
+
directory,
|
|
413
|
+
defaultModel: DEFAULT_MODEL,
|
|
414
|
+
models: await listAgentModels(client),
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
catch (e) {
|
|
418
|
+
sendError(res, e);
|
|
419
|
+
}
|
|
420
|
+
});
|
|
421
|
+
/** Check a project folder exists before the UI switches to it. */
|
|
422
|
+
app.get("/api/agent/directory", async (req, res) => {
|
|
423
|
+
try {
|
|
424
|
+
res.json({ directory: await resolveDirectory(req.query.directory) });
|
|
425
|
+
}
|
|
426
|
+
catch (e) {
|
|
427
|
+
sendError(res, e);
|
|
428
|
+
}
|
|
429
|
+
});
|
|
430
|
+
/** Create a fresh agent session in a project folder. */
|
|
431
|
+
app.post("/api/agent/session", async (req, res) => {
|
|
432
|
+
try {
|
|
433
|
+
const directory = await resolveDirectory(req.body?.directory);
|
|
434
|
+
const client = await getClient(directory);
|
|
435
|
+
const r = await client.session.create({
|
|
436
|
+
// No title: OpenCode then names the session from its first prompt.
|
|
437
|
+
body: req.body?.title ? { title: String(req.body.title) } : {},
|
|
438
|
+
query: { directory },
|
|
439
|
+
});
|
|
440
|
+
const session = unwrap(r);
|
|
441
|
+
res.json({ id: session.id, directory });
|
|
442
|
+
}
|
|
443
|
+
catch (e) {
|
|
444
|
+
sendError(res, e);
|
|
445
|
+
}
|
|
446
|
+
});
|
|
447
|
+
/** Send a prompt to an agent (default: build). Output streams via /events. */
|
|
448
|
+
app.post("/api/agent/prompt", async (req, res) => {
|
|
449
|
+
try {
|
|
450
|
+
const { sessionID, text = "", agent = "build", model, directory: dir, files = [], inlineImages = true } = req.body;
|
|
451
|
+
if (!sessionID || (!text.trim() && !files.length)) {
|
|
452
|
+
return res.status(400).json({ error: { message: "sessionID and text (or files) are required" } });
|
|
453
|
+
}
|
|
454
|
+
const directory = await resolveDirectory(dir);
|
|
455
|
+
const client = await getClient(directory);
|
|
456
|
+
const attached = files.length ? saveAttachments(directory, files, inlineImages) : null;
|
|
457
|
+
const prompt = (text.trim() || "See the attached file(s).") + (attached?.note ?? "");
|
|
458
|
+
await client.session.promptAsync({
|
|
459
|
+
path: { id: sessionID },
|
|
460
|
+
query: { directory },
|
|
461
|
+
body: {
|
|
462
|
+
agent,
|
|
463
|
+
model: parseModelId(model ?? DEFAULT_MODEL),
|
|
464
|
+
parts: [{ type: "text", text: prompt }, ...(attached?.parts ?? [])],
|
|
465
|
+
},
|
|
466
|
+
});
|
|
467
|
+
audit("prompt", { directory, session: sessionID, agent, model: model ?? DEFAULT_MODEL, text, attachments: attached?.saved });
|
|
468
|
+
res.json({ ok: true, attachments: attached?.saved ?? [] });
|
|
469
|
+
}
|
|
470
|
+
catch (e) {
|
|
471
|
+
sendError(res, e);
|
|
472
|
+
}
|
|
473
|
+
});
|
|
474
|
+
/** Past sessions in a project folder, newest first. */
|
|
475
|
+
app.get("/api/agent/sessions", async (req, res) => {
|
|
476
|
+
try {
|
|
477
|
+
const directory = await resolveDirectory(req.query.directory);
|
|
478
|
+
const raw = await oc(`/session${query({ directory, roots: true, limit: 100 })}`);
|
|
479
|
+
const sessions = raw
|
|
480
|
+
.filter((s) => !s.parentID && s.directory === directory)
|
|
481
|
+
.map((s) => ({
|
|
482
|
+
id: s.id, title: s.title, created: s.time?.created, updated: s.time?.updated ?? s.time?.created,
|
|
483
|
+
files: s.summary?.files ?? 0, additions: s.summary?.additions ?? 0, deletions: s.summary?.deletions ?? 0,
|
|
484
|
+
}))
|
|
485
|
+
.sort((a, b) => (b.updated ?? 0) - (a.updated ?? 0));
|
|
486
|
+
res.json({ sessions });
|
|
487
|
+
}
|
|
488
|
+
catch (e) {
|
|
489
|
+
sendError(res, e);
|
|
490
|
+
}
|
|
491
|
+
});
|
|
492
|
+
/** A session's full history, shaped like the live event stream. */
|
|
493
|
+
app.get("/api/agent/session/:id/messages", async (req, res) => {
|
|
494
|
+
try {
|
|
495
|
+
const directory = await resolveDirectory(req.query.directory);
|
|
496
|
+
const client = await getClient(directory);
|
|
497
|
+
const msgs = unwrap(await client.session.messages({ path: { id: req.params.id }, query: { directory } }));
|
|
498
|
+
const todos = await oc(`/session/${encodeURIComponent(req.params.id)}/todo${query({ directory })}`).catch(() => []);
|
|
499
|
+
const messages = toUiMessages(msgs ?? []);
|
|
500
|
+
res.json({ messages, todos });
|
|
501
|
+
}
|
|
502
|
+
catch (e) {
|
|
503
|
+
sendError(res, e);
|
|
504
|
+
}
|
|
505
|
+
});
|
|
506
|
+
app.delete("/api/agent/session/:id", async (req, res) => {
|
|
507
|
+
try {
|
|
508
|
+
const directory = await resolveDirectory(req.query.directory);
|
|
509
|
+
const client = await getClient(directory);
|
|
510
|
+
unwrap(await client.session.delete({ path: { id: req.params.id }, query: { directory } }));
|
|
511
|
+
audit("session.deleted", { directory, session: req.params.id });
|
|
512
|
+
res.json({ ok: true });
|
|
513
|
+
}
|
|
514
|
+
catch (e) {
|
|
515
|
+
sendError(res, e);
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
/** OpenCode's slash commands (built-in + the project's own). */
|
|
519
|
+
app.get("/api/agent/commands", async (req, res) => {
|
|
520
|
+
try {
|
|
521
|
+
const directory = await resolveDirectory(req.query.directory);
|
|
522
|
+
const list = await oc(`/command${query({ directory })}`).catch(() => []);
|
|
523
|
+
const commands = list
|
|
524
|
+
.filter((c) => c.source !== "skill")
|
|
525
|
+
.map((c) => ({ name: c.name, description: c.description ?? "", hint: (c.hints ?? []).includes("$ARGUMENTS") ? "[arguments]" : "" }));
|
|
526
|
+
res.json({ commands });
|
|
527
|
+
}
|
|
528
|
+
catch (e) {
|
|
529
|
+
sendError(res, e);
|
|
530
|
+
}
|
|
531
|
+
});
|
|
532
|
+
/** Run an OpenCode slash command (e.g. /init, /review). Output streams via /events. */
|
|
533
|
+
app.post("/api/agent/command", async (req, res) => {
|
|
534
|
+
try {
|
|
535
|
+
const { sessionID, command, arguments: args = "", agent = "build", model, directory: dir } = req.body;
|
|
536
|
+
if (!sessionID || !command)
|
|
537
|
+
return res.status(400).json({ error: { message: "sessionID and command required" } });
|
|
538
|
+
const directory = await resolveDirectory(dir);
|
|
539
|
+
audit("command", { directory, session: sessionID, command, arguments: args, agent, model: model ?? DEFAULT_MODEL });
|
|
540
|
+
// The command runs a full agent turn; don't hold the HTTP request open for it.
|
|
541
|
+
oc(`/session/${encodeURIComponent(sessionID)}/command${query({ directory })}`, {
|
|
542
|
+
method: "POST",
|
|
543
|
+
json: { command, arguments: args, agent, model: model ?? DEFAULT_MODEL },
|
|
544
|
+
}).catch((e) => audit("error", { directory, session: sessionID, command, error: String(e.message ?? e) }));
|
|
545
|
+
res.json({ ok: true });
|
|
546
|
+
}
|
|
547
|
+
catch (e) {
|
|
548
|
+
sendError(res, e);
|
|
549
|
+
}
|
|
550
|
+
});
|
|
551
|
+
/** Compact the conversation (summarise it to free up context). */
|
|
552
|
+
app.post("/api/agent/compact", async (req, res) => {
|
|
553
|
+
try {
|
|
554
|
+
const { sessionID, model, directory: dir } = req.body;
|
|
555
|
+
if (!sessionID)
|
|
556
|
+
return res.status(400).json({ error: { message: "sessionID required" } });
|
|
557
|
+
const directory = await resolveDirectory(dir);
|
|
558
|
+
const m = parseModelId(model ?? DEFAULT_MODEL);
|
|
559
|
+
audit("compact", { directory, session: sessionID });
|
|
560
|
+
oc(`/session/${encodeURIComponent(sessionID)}/summarize${query({ directory })}`, {
|
|
561
|
+
method: "POST",
|
|
562
|
+
json: { providerID: m.providerID, modelID: m.modelID },
|
|
563
|
+
}).catch((e) => audit("error", { directory, session: sessionID, command: "compact", error: String(e.message ?? e) }));
|
|
564
|
+
res.json({ ok: true });
|
|
565
|
+
}
|
|
566
|
+
catch (e) {
|
|
567
|
+
sendError(res, e);
|
|
568
|
+
}
|
|
569
|
+
});
|
|
570
|
+
/**
|
|
571
|
+
* Approvals and questions currently waiting on a session. The browser fetches
|
|
572
|
+
* this when it (re)attaches to a session, so a prompt raised before the page
|
|
573
|
+
* loaded — or while the event stream was briefly down — still shows up instead
|
|
574
|
+
* of leaving the agent silently blocked.
|
|
575
|
+
*/
|
|
576
|
+
app.get("/api/agent/pending", async (req, res) => {
|
|
577
|
+
try {
|
|
578
|
+
const sessionID = String(req.query.sessionID || "");
|
|
579
|
+
const directory = await resolveDirectory(req.query.directory);
|
|
580
|
+
const permsRaw = await oc(`/permission${query({ directory })}`).catch(() => []);
|
|
581
|
+
// GET /question lists every pending question request (same shape as the
|
|
582
|
+
// question.asked event); filter to this session like the permissions.
|
|
583
|
+
const qRaw = await oc(`/question${query({ directory })}`).catch(() => []);
|
|
584
|
+
const pending = {
|
|
585
|
+
permissions: permsRaw
|
|
586
|
+
.filter((p) => !sessionID || p.sessionID === sessionID)
|
|
587
|
+
.map((p) => ({
|
|
588
|
+
kind: "permission",
|
|
589
|
+
sessionID: p.sessionID,
|
|
590
|
+
permissionID: p.id,
|
|
591
|
+
permType: p.permission ?? p.type,
|
|
592
|
+
title: p.metadata?.command ?? p.title,
|
|
593
|
+
pattern: p.patterns ?? p.pattern,
|
|
594
|
+
callID: p.callID,
|
|
595
|
+
})),
|
|
596
|
+
questions: qRaw
|
|
597
|
+
.filter((q) => !sessionID || q.sessionID === sessionID)
|
|
598
|
+
.map((q) => ({
|
|
599
|
+
kind: "question",
|
|
600
|
+
sessionID: q.sessionID,
|
|
601
|
+
requestID: q.id,
|
|
602
|
+
questions: q.questions ?? [],
|
|
603
|
+
callID: q.tool?.callID,
|
|
604
|
+
})),
|
|
605
|
+
};
|
|
606
|
+
res.json(pending);
|
|
607
|
+
}
|
|
608
|
+
catch (e) {
|
|
609
|
+
sendError(res, e);
|
|
610
|
+
}
|
|
611
|
+
});
|
|
612
|
+
/** Reply to a pending permission request (once | always | reject). */
|
|
613
|
+
app.post("/api/agent/permission", async (req, res) => {
|
|
614
|
+
try {
|
|
615
|
+
const { sessionID, permissionID, response, directory: dir } = req.body;
|
|
616
|
+
if (!sessionID || !permissionID || !response) {
|
|
617
|
+
return res.status(400).json({ error: { message: "sessionID, permissionID, response required" } });
|
|
618
|
+
}
|
|
619
|
+
const directory = await resolveDirectory(dir);
|
|
620
|
+
const client = await getClient(directory);
|
|
621
|
+
unwrap(await client.postSessionIdPermissionsPermissionId({
|
|
622
|
+
path: { id: sessionID, permissionID },
|
|
623
|
+
query: { directory },
|
|
624
|
+
body: { response },
|
|
625
|
+
}));
|
|
626
|
+
res.json({ ok: true });
|
|
627
|
+
}
|
|
628
|
+
catch (e) {
|
|
629
|
+
sendError(res, e);
|
|
630
|
+
}
|
|
631
|
+
});
|
|
632
|
+
// Audit log of agent activity (see audit.ts), fed by OpenCode's event stream.
|
|
633
|
+
if (LOG_DIR)
|
|
634
|
+
serverUrl().then(followOpencode).catch((e) => console.error("[audit] not following OpenCode:", e));
|
|
635
|
+
/**
|
|
636
|
+
* Answer (or dismiss) a question the agent asked with its `question` tool.
|
|
637
|
+
* `answers` holds one array of chosen labels / typed text per question.
|
|
638
|
+
*/
|
|
639
|
+
app.post("/api/agent/question", async (req, res) => {
|
|
640
|
+
try {
|
|
641
|
+
const { requestID, answers, reject, directory: dir } = req.body;
|
|
642
|
+
if (!requestID || (!reject && !Array.isArray(answers))) {
|
|
643
|
+
return res.status(400).json({ error: { message: "requestID and answers (or reject) required" } });
|
|
644
|
+
}
|
|
645
|
+
const directory = await resolveDirectory(dir);
|
|
646
|
+
const action = reject ? "reject" : "reply";
|
|
647
|
+
await oc(`/question/${encodeURIComponent(requestID)}/${action}${query({ directory })}`, {
|
|
648
|
+
method: "POST",
|
|
649
|
+
json: reject ? {} : { answers },
|
|
650
|
+
});
|
|
651
|
+
res.json({ ok: true });
|
|
652
|
+
}
|
|
653
|
+
catch (e) {
|
|
654
|
+
sendError(res, e);
|
|
655
|
+
}
|
|
656
|
+
});
|
|
657
|
+
/** Abort the current agent turn. */
|
|
658
|
+
app.post("/api/agent/abort", async (req, res) => {
|
|
659
|
+
try {
|
|
660
|
+
const directory = await resolveDirectory(req.body?.directory);
|
|
661
|
+
const client = await getClient(directory);
|
|
662
|
+
await client.session.abort({ path: { id: req.body?.sessionID }, query: { directory } });
|
|
663
|
+
res.json({ ok: true });
|
|
664
|
+
}
|
|
665
|
+
catch (e) {
|
|
666
|
+
sendError(res, e);
|
|
667
|
+
}
|
|
668
|
+
});
|
|
669
|
+
/**
|
|
670
|
+
* Per-file changes the agent made in this session. OpenCode records them on
|
|
671
|
+
* each user message (one entry per file per prompt, as a unified patch).
|
|
672
|
+
*/
|
|
673
|
+
app.get("/api/agent/diff", async (req, res) => {
|
|
674
|
+
try {
|
|
675
|
+
const directory = await resolveDirectory(req.query.directory);
|
|
676
|
+
const client = await getClient(directory);
|
|
677
|
+
const r = await client.session.messages({
|
|
678
|
+
path: { id: String(req.query.sessionID) },
|
|
679
|
+
query: { directory },
|
|
680
|
+
});
|
|
681
|
+
const messages = unwrap(r) ?? [];
|
|
682
|
+
const diff = messages
|
|
683
|
+
.filter((m) => m?.info?.role === "user")
|
|
684
|
+
.flatMap((m, turn) => (m.info.summary?.diffs ?? []).map((d) => ({ ...d, turn: turn + 1 })));
|
|
685
|
+
res.json({ diff });
|
|
686
|
+
}
|
|
687
|
+
catch (e) {
|
|
688
|
+
sendError(res, e);
|
|
689
|
+
}
|
|
690
|
+
});
|
|
691
|
+
/** SSE stream of compact agent events for one session. */
|
|
692
|
+
app.get("/api/agent/events", async (req, res) => {
|
|
693
|
+
const sessionID = String(req.query.sessionID || "");
|
|
694
|
+
try {
|
|
695
|
+
const directory = await resolveDirectory(req.query.directory);
|
|
696
|
+
const client = await getClient(directory);
|
|
697
|
+
res.setHeader("Content-Type", "text/event-stream");
|
|
698
|
+
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
699
|
+
res.setHeader("Connection", "keep-alive");
|
|
700
|
+
res.flushHeaders?.();
|
|
701
|
+
res.write(`data: ${JSON.stringify({ kind: "open" })}\n\n`);
|
|
702
|
+
// Comment lines keep proxies (Vite, a TLS reverse proxy) from cutting an
|
|
703
|
+
// idle stream during a long tool call.
|
|
704
|
+
const keepAlive = setInterval(() => res.write(": ping\n\n"), 25_000);
|
|
705
|
+
const sub = await client.event.subscribe({ query: { directory } });
|
|
706
|
+
let closed = false;
|
|
707
|
+
req.on("close", () => { closed = true; clearInterval(keepAlive); sub.stream.return?.(undefined); });
|
|
708
|
+
for await (const evt of sub.stream) {
|
|
709
|
+
if (closed)
|
|
710
|
+
break;
|
|
711
|
+
// Filter to this session (events carry the id in different spots).
|
|
712
|
+
const sid = evt?.properties?.part?.sessionID ??
|
|
713
|
+
evt?.properties?.sessionID ??
|
|
714
|
+
evt?.properties?.info?.sessionID;
|
|
715
|
+
if (sessionID && sid && sid !== sessionID)
|
|
716
|
+
continue;
|
|
717
|
+
const ui = toUiEvent(evt);
|
|
718
|
+
if (ui)
|
|
719
|
+
res.write(`data: ${JSON.stringify(ui)}\n\n`);
|
|
720
|
+
}
|
|
721
|
+
clearInterval(keepAlive);
|
|
722
|
+
res.end();
|
|
723
|
+
}
|
|
724
|
+
catch (e) {
|
|
725
|
+
if (res.headersSent) {
|
|
726
|
+
res.write(`data: ${JSON.stringify({ kind: "error", message: String(e?.message ?? e) })}\n\n`);
|
|
727
|
+
res.end();
|
|
728
|
+
}
|
|
729
|
+
else {
|
|
730
|
+
sendError(res, e);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
});
|
|
734
|
+
// Production (Docker): serve the built web app from the same origin.
|
|
735
|
+
const WEB_DIST = path.join(REPO_ROOT, "web", "dist");
|
|
736
|
+
if (process.env.NODE_ENV === "production" && fs.existsSync(WEB_DIST)) {
|
|
737
|
+
app.use(express.static(WEB_DIST, { index: false }));
|
|
738
|
+
app.get(/^(?!\/api\/|\/scx\/).*/, (_req, res) => res.sendFile(path.join(WEB_DIST, "index.html")));
|
|
739
|
+
}
|
|
740
|
+
// Body-parser failures (oversized attachment payloads, malformed JSON) and
|
|
741
|
+
// anything a route threw synchronously: answer in JSON like every other error.
|
|
742
|
+
app.use((err, _req, res, _next) => {
|
|
743
|
+
const status = Number(err?.status ?? err?.statusCode ?? 500);
|
|
744
|
+
const message = err?.type === "entity.too.large"
|
|
745
|
+
? "Request too large: attachments are limited to 25 MB each and about 30 MB per message."
|
|
746
|
+
: err?.type === "entity.parse.failed" ? "Malformed JSON body." : String(err?.message ?? err);
|
|
747
|
+
if (status >= 500)
|
|
748
|
+
console.error("[server error]", err);
|
|
749
|
+
res.status(status).json({ error: { message } });
|
|
750
|
+
});
|
|
751
|
+
const server = app.listen(PORT, process.env.HOST ?? "127.0.0.1", () => {
|
|
752
|
+
console.log(`\n BugXHunter backend`);
|
|
753
|
+
console.log(` listening on http://${process.env.HOST ?? "127.0.0.1"}:${PORT}`);
|
|
754
|
+
for (const p of Object.values(PROVIDERS)) {
|
|
755
|
+
const src = keySource(p.id);
|
|
756
|
+
const where = {
|
|
757
|
+
vault: "vault",
|
|
758
|
+
env: ".env — consider moving it into the vault",
|
|
759
|
+
"opencode-auth": "OpenCode's auth.json — consider moving it into the vault",
|
|
760
|
+
none: p.id === "scx" ? "none yet — set up the vault in the sidebar" : "not configured (optional)",
|
|
761
|
+
}[src];
|
|
762
|
+
console.log(` ${p.name} key: ${where}`);
|
|
763
|
+
}
|
|
764
|
+
if (vault.isInitialised())
|
|
765
|
+
console.log(` vault: ${vault.VAULT_FILE} (${vault.isUnsealed() ? "unsealed" : "sealed — unlock it in the UI"})`);
|
|
766
|
+
if (OPENROUTER_MODELS.length)
|
|
767
|
+
console.log(` OpenRouter models for the agent: ${OPENROUTER_MODELS.join(", ")}`);
|
|
768
|
+
console.log(` agent: ${REMOTE_URL ? `remote OpenCode at ${REMOTE_URL}` : "local OpenCode"}`);
|
|
769
|
+
if (!REMOTE_URL)
|
|
770
|
+
console.log(` project roots: ${ALLOWED_ROOTS.length ? ALLOWED_ROOTS.join(", ") : "any folder (set OPEN_RUNNER_ALLOWED_ROOTS to restrict)"}`);
|
|
771
|
+
console.log(` sign-in: ${authRequired() ? "passkey (the vault's)" : "open — set up the vault in the sidebar to require a passkey"}`);
|
|
772
|
+
if (TRUST_PROXY)
|
|
773
|
+
console.log(` trust proxy: ${TRUST_PROXY}`);
|
|
774
|
+
console.log(` audit log: ${LOG_DIR || "off (set OPEN_RUNNER_LOG_DIR)"}`);
|
|
775
|
+
console.log(` default project: ${DEFAULT_DIRECTORY}\n`);
|
|
776
|
+
});
|
|
777
|
+
server.on("error", (e) => {
|
|
778
|
+
console.error(e.code === "EADDRINUSE"
|
|
779
|
+
? `\n[fatal] Port ${PORT} is already in use (another backend running?). Set PORT to use a different one.\n`
|
|
780
|
+
: `\n[fatal] Could not listen on port ${PORT}: ${e.message}\n`);
|
|
781
|
+
process.exit(1);
|
|
782
|
+
});
|
|
783
|
+
//# sourceMappingURL=index.js.map
|