bugxhunter 0.9.3 → 0.9.4
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 +8 -0
- package/README.md +31 -2
- package/docker-compose.yml +4 -0
- package/package.json +2 -1
- package/server/dist/anthropic.js +344 -0
- package/server/dist/index.js +13 -19
- package/server/dist/opencode.js +10 -3
- package/server/dist/providers.js +136 -10
- package/web/dist/assets/{index-DziQn-Nk.js → index-D_KMKSAo.js} +16 -16
- package/web/dist/index.html +1 -1
package/.env.example
CHANGED
|
@@ -14,6 +14,14 @@
|
|
|
14
14
|
# Runner's model picker). The Playground sees the whole catalogue regardless.
|
|
15
15
|
# OPENROUTER_MODELS=anthropic/claude-sonnet-4.5,openai/gpt-6.1-sol
|
|
16
16
|
|
|
17
|
+
# Optional: Anthropic (Claude) directly (https://platform.claude.com).
|
|
18
|
+
# Put the key in the vault as ANTHROPIC_API_KEY (keys dialog) rather than here.
|
|
19
|
+
# ANTHROPIC_API_KEY=sk-ant-...
|
|
20
|
+
# Comma list of Claude model ids the AGENT's picker shows (default below). The
|
|
21
|
+
# Playground lists every model the key can use. In Docker the agent's Claude
|
|
22
|
+
# models are set in docker/opencode.json.
|
|
23
|
+
# ANTHROPIC_MODELS=claude-opus-5-5,claude-sonnet-5-5,claude-haiku-5-5
|
|
24
|
+
|
|
17
25
|
# GitHub needs nothing here: "Connect GitHub" in the sidebar signs in to the
|
|
18
26
|
# public BugXHunter GitHub App (read-only). A fork that registers its own app
|
|
19
27
|
# sets its Client ID and slug:
|
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ green accents) and Fira Code throughout. Started from the `sovgov-poc` chatbot d
|
|
|
15
15
|
`plan` (read-only) agent. Every file edit and shell command waits for your approval.
|
|
16
16
|
Markdown replies, collapsible tool calls and reasoning, per-turn token counts, and a
|
|
17
17
|
**Changes** view of what the agent edited (git repos only — OpenCode tracks changes via git).
|
|
18
|
-
- **Playground** — chat with any SCX, NVIDIA or OpenRouter model directly (no agent), with
|
|
18
|
+
- **Playground** — chat with any SCX, Anthropic (Claude), NVIDIA or OpenRouter model directly (no agent), with
|
|
19
19
|
tool-calling, JSON mode, an embeddings-backed knowledge base and browser voice. Also:
|
|
20
20
|
- **Security presets** (code review, threat modelling, AI system review, pentest planning,
|
|
21
21
|
diagram review, diagram drawing, tabletop exercises, CTF coaching, phishing, log triage,
|
|
@@ -215,6 +215,30 @@ The agent never holds the key: its calls go to the runner's `/openrouter/v1` pro
|
|
|
215
215
|
token, exactly like SCX, in both local and Docker modes. Pricing is OpenRouter's; the Playground
|
|
216
216
|
shows each model's per-token rates.
|
|
217
217
|
|
|
218
|
+
## Claude via the Anthropic API
|
|
219
|
+
|
|
220
|
+
1. Add your Anthropic key to the vault as `ANTHROPIC_API_KEY` (keys dialog). The **Playground**
|
|
221
|
+
then lists every Claude model the key can use under an **Anthropic** heading, addressed as
|
|
222
|
+
`anthropic/<id>` (for example `anthropic/claude-opus-5-5`).
|
|
223
|
+
2. The **agent** gets Claude Opus 5.5, Sonnet 5.5 and Haiku 5.5 in the Runner's model picker.
|
|
224
|
+
Locally, `ANTHROPIC_MODELS` (comma-separated model ids) changes that list; in Docker the list
|
|
225
|
+
is in `docker/opencode.json`.
|
|
226
|
+
|
|
227
|
+
As with the other providers, the agent never holds the key: OpenCode's own Anthropic client calls
|
|
228
|
+
the runner's `/anthropic/v1` proxy with the proxy token, and the runner adds the key.
|
|
229
|
+
|
|
230
|
+
Things that differ from the OpenAI-style providers:
|
|
231
|
+
|
|
232
|
+
- **Sampling settings are not sent.** Current Claude models reject temperature and top-p, so the
|
|
233
|
+
Playground's sliders don't apply to them. Forced tool use is sent as "auto" for the same reason.
|
|
234
|
+
- **Safety classifiers.** Claude's classifiers can decline some security requests. On models that
|
|
235
|
+
support it, the Playground asks for Anthropic's server-side fallback, so a declined request is
|
|
236
|
+
retried on the model Anthropic recommends for that category. A decline that still stands shows
|
|
237
|
+
as an error naming the category. For authorised security work, Anthropic's
|
|
238
|
+
[Cyber Verification Program](https://support.claude.com/en/articles/14604842-real-time-cyber-safeguards-on-claude-opus-and-sonnet)
|
|
239
|
+
can lift cyber-category declines.
|
|
240
|
+
- **Prompt caching** is on, so repeated history in a long chat is billed at the cached rate.
|
|
241
|
+
|
|
218
242
|
## GitHub repositories (read-only)
|
|
219
243
|
|
|
220
244
|
To review a repository, clone it into the workspace from the sidebar (**clone from GitHub** under
|
|
@@ -307,6 +331,10 @@ nobody is there to unlock.
|
|
|
307
331
|
| `OPENROUTER_API_KEY` | the vault, else unset | OpenRouter key in the clear; prefer the vault item of the same name |
|
|
308
332
|
| `OPENROUTER_MODELS` | unset | Comma list of OpenRouter model ids the agent may use; becomes an OpenCode provider through the proxy |
|
|
309
333
|
| `OPENROUTER_BASE_URL` | `https://openrouter.ai/api/v1` | OpenRouter endpoint |
|
|
334
|
+
| `ANTHROPIC_API_KEY_FILE` | unset | A file holding the Anthropic key, as `SCX_API_FILE` |
|
|
335
|
+
| `ANTHROPIC_API_KEY` | the vault, else unset | Anthropic key in the clear; prefer the vault item of the same name |
|
|
336
|
+
| `ANTHROPIC_MODELS` | `claude-opus-5-5,claude-sonnet-5-5,claude-haiku-5-5` | Claude model ids in the agent's picker (local mode; Docker: `docker/opencode.json`) |
|
|
337
|
+
| `ANTHROPIC_BASE_URL` | `https://api.anthropic.com/v1` | Anthropic endpoint |
|
|
310
338
|
| `GITHUB_CLIENT_ID` | the BugXHunter app | A fork's own GitHub App (device flow); `GITHUB_APP_SLUG` names its install page |
|
|
311
339
|
| `OPEN_RUNNER_VAULT_FILE` | `~/.config/bugxhunter/vault.json` | The sealed vault (Docker: `/data/vault.json` on the `runner-data` volume) |
|
|
312
340
|
| `OPEN_RUNNER_VAULT_IDLE_MINUTES` | `120` | Auto-lock after this long without a model call or API write; `0` = never |
|
|
@@ -336,6 +364,7 @@ GHCR images by digest) and the signed `checksums.txt` that covers them all.
|
|
|
336
364
|
<!-- releases:start -->
|
|
337
365
|
| Release | Published | Checksums | Signature | Signature check | Build |
|
|
338
366
|
| --- | --- | --- | --- | --- | --- |
|
|
367
|
+
| [v0.9.3](https://github.com/cintelis/bugxhunter-runner/releases/tag/v0.9.3) | 2026-10-29 | [checksums.txt](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.9.3/checksums.txt) | [checksums.txt.sig](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.9.3/checksums.txt.sig) | ✅ release key | [workflow run](https://github.com/cintelis/bugxhunter-runner/actions/runs/40817756725) |
|
|
339
368
|
| [v0.9.2](https://github.com/cintelis/bugxhunter-runner/releases/tag/v0.9.2) | 2026-10-28 | [checksums.txt](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.9.2/checksums.txt) | [checksums.txt.sig](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.9.2/checksums.txt.sig) | ✅ release key | [workflow run](https://github.com/cintelis/bugxhunter-runner/actions/runs/40789797062) |
|
|
340
369
|
| [v0.9.1](https://github.com/cintelis/bugxhunter-runner/releases/tag/v0.9.1) | 2026-10-28 | [checksums.txt](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.9.1/checksums.txt) | [checksums.txt.sig](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.9.1/checksums.txt.sig) | ✅ release key | [workflow run](https://github.com/cintelis/bugxhunter-runner/actions/runs/40783886380) |
|
|
341
370
|
| [v0.9.0](https://github.com/cintelis/bugxhunter-runner/releases/tag/v0.9.0) | 2026-10-28 | [checksums.txt](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.9.0/checksums.txt) | [checksums.txt.sig](https://github.com/cintelis/bugxhunter-runner/releases/download/v0.9.0/checksums.txt.sig) | ✅ release key | [workflow run](https://github.com/cintelis/bugxhunter-runner/actions/runs/40700626754) |
|
|
@@ -417,7 +446,7 @@ publisher** on npmjs.com set to this repository and `release.yml`, once; no npm
|
|
|
417
446
|
| `server/src/opencode.ts` | Starts/stops the OpenCode server, one SDK client per project folder, event mapping |
|
|
418
447
|
| `server/src/index.ts` | Express: `/api/agent/*` (OpenCode) and `/api/chat`, `/api/models`, `/api/kb` (SCX) |
|
|
419
448
|
| `server/src/scx.ts`, `rag.ts` | SCX client and in-memory knowledge base (Playground) |
|
|
420
|
-
| `server/src/providers.ts`, `nvidia-health.ts` | NVIDIA / OpenRouter providers; hides NVIDIA models whose endpoints are retired |
|
|
449
|
+
| `server/src/providers.ts`, `anthropic.ts`, `nvidia-health.ts` | Anthropic / NVIDIA / OpenRouter providers (Claude via the official SDK); hides NVIDIA models whose endpoints are retired |
|
|
421
450
|
| `server/src/playground-store.ts` | Saved Playground sessions, sealed with the vault key |
|
|
422
451
|
| `server/src/render.ts`, `docker/render-server.py`, `docker/drawio_outline.py` | The render service (diagrams, `.drawio` outlines) and the runner's client for it |
|
|
423
452
|
| `web/src/Canvas.tsx`, `web/src/canvas/` | The threat-model canvas |
|
package/docker-compose.yml
CHANGED
|
@@ -37,6 +37,10 @@ services:
|
|
|
37
37
|
# (OPENROUTER_API_KEY) or here; OPENROUTER_MODELS lists the ids the agent may use.
|
|
38
38
|
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
|
|
39
39
|
OPENROUTER_MODELS: ${OPENROUTER_MODELS:-}
|
|
40
|
+
# Optional: Claude models (https://platform.claude.com). Key in the vault
|
|
41
|
+
# (ANTHROPIC_API_KEY) or here; ANTHROPIC_MODELS lists the ids the agent's picker shows.
|
|
42
|
+
ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
|
|
43
|
+
ANTHROPIC_MODELS: ${ANTHROPIC_MODELS:-}
|
|
40
44
|
OPEN_RUNNER_VAULT_FILE: /data/vault.json
|
|
41
45
|
OPEN_RUNNER_VAULT_IDLE_MINUTES: ${OPEN_RUNNER_VAULT_IDLE_MINUTES:-120}
|
|
42
46
|
OPEN_RUNNER_SECRET: ${OPEN_RUNNER_SECRET:-}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bugxhunter",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.4",
|
|
4
4
|
"description": "BugXHunter: an AI security-testing agent with a sandboxed runner, a passkey-sealed key vault and read-only GitHub access. `npx bugxhunter` runs it on your machine.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://bugxhunter.com",
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
"node": ">=22"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
+
"@anthropic-ai/sdk": "^1.3.0",
|
|
31
32
|
"@opencode-ai/sdk": "^1.17.11",
|
|
32
33
|
"dotenv": "^18.0.6",
|
|
33
34
|
"express": "^5.2.1",
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anthropic (Claude) for the Playground, through the official SDK.
|
|
3
|
+
*
|
|
4
|
+
* The Playground speaks the OpenAI chat shape to every provider. This module turns
|
|
5
|
+
* that request into a Claude Messages request and the answer back into OpenAI-style
|
|
6
|
+
* chunks, so the browser and the /api/chat route need no Claude-specific code.
|
|
7
|
+
* `AnthropicChatClient` has the same `chat` / `chatStreamResponse` surface as
|
|
8
|
+
* `SCXClient`.
|
|
9
|
+
*
|
|
10
|
+
* Claude-specific behaviour:
|
|
11
|
+
* - Sampling settings (temperature, top_p, penalties, seed) are not sent: current
|
|
12
|
+
* Claude models reject them.
|
|
13
|
+
* - Forced tool use ("required" or a named tool) becomes "auto": current models
|
|
14
|
+
* reject forced tool use.
|
|
15
|
+
* - Models with safety classifiers that can decline security work get server-side
|
|
16
|
+
* fallback (`fallbacks: "default"`), so a declined request is re-run on the model
|
|
17
|
+
* Anthropic recommends for that category instead of just failing. A decline that
|
|
18
|
+
* still stands is reported as an error that names the category.
|
|
19
|
+
* - Prompt caching is on (top-level `cache_control`), so a long conversation's
|
|
20
|
+
* history is not billed in full on every turn.
|
|
21
|
+
*
|
|
22
|
+
* The agent does not use this module: OpenCode talks to Claude natively, through
|
|
23
|
+
* the runner's key-injecting proxy (see index.ts and providers.ts).
|
|
24
|
+
*/
|
|
25
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
26
|
+
import { SCXError } from "./scx.js";
|
|
27
|
+
/** Playground ids for Claude models: `anthropic/<model id>`. */
|
|
28
|
+
export const ANTHROPIC_PREFIX = "anthropic/";
|
|
29
|
+
/** Output budget when the caller sets none (streamed, so a long answer cannot time out). */
|
|
30
|
+
const DEFAULT_MAX_TOKENS = 64_000;
|
|
31
|
+
/** Models that take server-side fallback in its "default" form. */
|
|
32
|
+
const FALLBACK_MODELS = new Set(["claude-fable-5-1", "claude-opus-5-5", "claude-opus-5", "claude-sonnet-5-5"]);
|
|
33
|
+
const FALLBACK_BETA = "server-side-fallback-2026-07-01";
|
|
34
|
+
/** Image types the Messages API accepts. */
|
|
35
|
+
const IMAGE_TYPES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
|
|
36
|
+
const JSON_ONLY = "Reply with one valid JSON object and nothing else: no prose before or after it, no code fences.";
|
|
37
|
+
/** The text of an OpenAI message's content (a string, or the text parts of a part list). */
|
|
38
|
+
function textOf(content) {
|
|
39
|
+
if (typeof content === "string")
|
|
40
|
+
return content;
|
|
41
|
+
if (!Array.isArray(content))
|
|
42
|
+
return "";
|
|
43
|
+
return content
|
|
44
|
+
.map((p) => (p && typeof p === "object" && p.type === "text" ? String(p.text ?? "") : ""))
|
|
45
|
+
.filter(Boolean)
|
|
46
|
+
.join("\n");
|
|
47
|
+
}
|
|
48
|
+
/** An OpenAI `image_url` part as a Claude image block, or a note if Claude cannot take it. */
|
|
49
|
+
function imageBlock(url) {
|
|
50
|
+
const m = /^data:([^;,]+);base64,(.*)$/s.exec(url);
|
|
51
|
+
if (m) {
|
|
52
|
+
const media = m[1].toLowerCase();
|
|
53
|
+
if (!IMAGE_TYPES.has(media))
|
|
54
|
+
return { type: "text", text: `[An attached ${media} image was not sent: Claude accepts JPEG, PNG, GIF and WebP.]` };
|
|
55
|
+
return { type: "image", source: { type: "base64", media_type: media, data: m[2] } };
|
|
56
|
+
}
|
|
57
|
+
if (/^https?:\/\//i.test(url))
|
|
58
|
+
return { type: "image", source: { type: "url", url } };
|
|
59
|
+
return { type: "text", text: "[An attached image was not sent: unsupported address.]" };
|
|
60
|
+
}
|
|
61
|
+
/** A user message's content as Claude blocks: text parts and images, empty text dropped. */
|
|
62
|
+
function userBlocks(content) {
|
|
63
|
+
if (typeof content === "string")
|
|
64
|
+
return content.trim() ? [{ type: "text", text: content }] : [];
|
|
65
|
+
if (!Array.isArray(content))
|
|
66
|
+
return [];
|
|
67
|
+
const out = [];
|
|
68
|
+
for (const part of content) {
|
|
69
|
+
if (part?.type === "text" && String(part.text ?? "").trim())
|
|
70
|
+
out.push({ type: "text", text: String(part.text) });
|
|
71
|
+
else if (part?.type === "image_url") {
|
|
72
|
+
const url = typeof part.image_url === "string" ? part.image_url : part.image_url?.url;
|
|
73
|
+
if (url)
|
|
74
|
+
out.push(imageBlock(url));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
/** Tool-call arguments as an object (Claude takes the input parsed; bad JSON becomes {}). */
|
|
80
|
+
function parseArgs(args) {
|
|
81
|
+
try {
|
|
82
|
+
const v = JSON.parse(args || "{}");
|
|
83
|
+
return v && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return {};
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* An OpenAI-shaped Playground request as a Claude Messages request.
|
|
91
|
+
* `model` is the bare Claude id; `modelMax` is its output limit, if known.
|
|
92
|
+
*/
|
|
93
|
+
export function toAnthropicRequest(params, model, modelMax) {
|
|
94
|
+
const system = [];
|
|
95
|
+
const messages = [];
|
|
96
|
+
// Claude wants user and assistant turns to alternate; merge neighbours with the same role.
|
|
97
|
+
const push = (role, blocks) => {
|
|
98
|
+
if (!blocks.length)
|
|
99
|
+
return;
|
|
100
|
+
const last = messages[messages.length - 1];
|
|
101
|
+
if (last?.role === role)
|
|
102
|
+
last.content.push(...blocks);
|
|
103
|
+
else
|
|
104
|
+
messages.push({ role, content: blocks });
|
|
105
|
+
};
|
|
106
|
+
for (const m of params.messages) {
|
|
107
|
+
switch (m.role) {
|
|
108
|
+
case "system": {
|
|
109
|
+
const t = textOf(m.content);
|
|
110
|
+
if (t.trim())
|
|
111
|
+
system.push(t);
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
case "user":
|
|
115
|
+
push("user", userBlocks(m.content));
|
|
116
|
+
break;
|
|
117
|
+
case "assistant": {
|
|
118
|
+
const blocks = [];
|
|
119
|
+
const t = textOf(m.content);
|
|
120
|
+
if (t.trim())
|
|
121
|
+
blocks.push({ type: "text", text: t });
|
|
122
|
+
for (const tc of m.tool_calls ?? []) {
|
|
123
|
+
blocks.push({ type: "tool_use", id: tc.id, name: tc.function.name, input: parseArgs(tc.function.arguments) });
|
|
124
|
+
}
|
|
125
|
+
push("assistant", blocks);
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
case "tool":
|
|
129
|
+
push("user", [{ type: "tool_result", tool_use_id: m.tool_call_id ?? "", content: textOf(m.content) || "(no output)" }]);
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// The conversation must open with a user turn (a Playground chat can open with a greeting).
|
|
134
|
+
if (messages[0]?.role === "assistant")
|
|
135
|
+
messages.unshift({ role: "user", content: [{ type: "text", text: "(conversation start)" }] });
|
|
136
|
+
if (params.response_format?.type === "json_object")
|
|
137
|
+
system.push(JSON_ONLY);
|
|
138
|
+
const tools = params.tools?.map((t) => ({
|
|
139
|
+
name: t.function.name,
|
|
140
|
+
...(t.function.description ? { description: t.function.description } : {}),
|
|
141
|
+
input_schema: { type: "object", ...(t.function.parameters ?? {}) },
|
|
142
|
+
}));
|
|
143
|
+
const stops = (Array.isArray(params.stop) ? params.stop : params.stop ? [params.stop] : []).filter((s) => typeof s === "string" && s.trim());
|
|
144
|
+
const cap = modelMax && modelMax > 0 ? modelMax : 128_000;
|
|
145
|
+
const maxTokens = Math.max(1, Math.min(params.max_tokens && params.max_tokens > 0 ? params.max_tokens : DEFAULT_MAX_TOKENS, cap));
|
|
146
|
+
return {
|
|
147
|
+
model,
|
|
148
|
+
max_tokens: maxTokens,
|
|
149
|
+
messages,
|
|
150
|
+
stream: true,
|
|
151
|
+
cache_control: { type: "ephemeral" },
|
|
152
|
+
...(system.length ? { system: system.join("\n\n") } : {}),
|
|
153
|
+
...(tools?.length ? { tools, tool_choice: params.tool_choice === "none" ? { type: "none" } : { type: "auto" } } : {}),
|
|
154
|
+
...(stops.length ? { stop_sequences: stops } : {}),
|
|
155
|
+
...(FALLBACK_MODELS.has(model) ? { betas: [FALLBACK_BETA], fallbacks: "default" } : {}),
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
/** Claude's stop reason as an OpenAI finish reason. */
|
|
159
|
+
export function finishReason(stop) {
|
|
160
|
+
switch (stop) {
|
|
161
|
+
case "end_turn":
|
|
162
|
+
case "stop_sequence":
|
|
163
|
+
case "pause_turn": return "stop";
|
|
164
|
+
case "max_tokens":
|
|
165
|
+
case "model_context_window_exceeded": return "length";
|
|
166
|
+
case "tool_use": return "tool_calls";
|
|
167
|
+
case "refusal": return "content_filter";
|
|
168
|
+
default: return stop ?? null;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/** The error to show when Claude (and any fallback) declined the request. */
|
|
172
|
+
export function refusalMessage(msg) {
|
|
173
|
+
const details = msg.stop_details;
|
|
174
|
+
const cat = details?.category;
|
|
175
|
+
const why = details?.explanation ? ` ${details.explanation}` : "";
|
|
176
|
+
const cyber = cat === "cyber"
|
|
177
|
+
? " For authorised security work, Anthropic's Cyber Verification Program can lift this: https://support.claude.com/en/articles/14604842-real-time-cyber-safeguards-on-claude-opus-and-sonnet"
|
|
178
|
+
: "";
|
|
179
|
+
return `Claude declined this request${cat ? ` (safety category: ${cat})` : ""}.${why} Rephrase it, or try another model.${cyber}`;
|
|
180
|
+
}
|
|
181
|
+
/** The blocks after the last fallback marker: what the model that finished the turn wrote. */
|
|
182
|
+
function servedBlocks(msg) {
|
|
183
|
+
const content = msg.content;
|
|
184
|
+
let start = 0;
|
|
185
|
+
content.forEach((b, i) => { if (b.type === "fallback")
|
|
186
|
+
start = i + 1; });
|
|
187
|
+
return { all: content, served: content.slice(start) };
|
|
188
|
+
}
|
|
189
|
+
/** Text of the whole turn (text before a mid-answer fallback is the start the fallback continued). */
|
|
190
|
+
const turnText = (msg) => servedBlocks(msg).all.filter((b) => b.type === "text").map((b) => b.text).join("");
|
|
191
|
+
/** Tool calls from the model that finished the turn, in OpenAI form. */
|
|
192
|
+
function turnToolCalls(msg) {
|
|
193
|
+
return servedBlocks(msg).served
|
|
194
|
+
.filter((b) => b.type === "tool_use")
|
|
195
|
+
.map((t) => ({ id: t.id, type: "function", function: { name: t.name, arguments: JSON.stringify(t.input ?? {}) } }));
|
|
196
|
+
}
|
|
197
|
+
function usageOf(u) {
|
|
198
|
+
const prompt = (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
|
|
199
|
+
return { prompt_tokens: prompt, completion_tokens: u.output_tokens ?? 0, total_tokens: prompt + (u.output_tokens ?? 0) };
|
|
200
|
+
}
|
|
201
|
+
/** An SDK error as an SCXError the routes already know how to report. */
|
|
202
|
+
export function toSCXError(e) {
|
|
203
|
+
if (e instanceof Anthropic.APIError) {
|
|
204
|
+
const body = e.error;
|
|
205
|
+
const message = body?.error?.message ?? e.message;
|
|
206
|
+
if (e.status === 401 || e.status === 403) {
|
|
207
|
+
return new SCXError(502, `Anthropic rejected the API key (${e.status}: ${message}). Check ANTHROPIC_API_KEY in the vault.`, body?.error?.type);
|
|
208
|
+
}
|
|
209
|
+
if (e instanceof Anthropic.APIConnectionError)
|
|
210
|
+
return new SCXError(502, `Could not reach Anthropic: ${message}`, "connection");
|
|
211
|
+
return new SCXError(e.status ?? 502, message, body?.error?.type);
|
|
212
|
+
}
|
|
213
|
+
return e;
|
|
214
|
+
}
|
|
215
|
+
/** Claude behind the same surface as SCXClient: `chat` and `chatStreamResponse`. */
|
|
216
|
+
export class AnthropicChatClient {
|
|
217
|
+
opts;
|
|
218
|
+
constructor(opts) {
|
|
219
|
+
this.opts = opts;
|
|
220
|
+
}
|
|
221
|
+
/** A fresh SDK client per call: the key comes from the vault and can change. */
|
|
222
|
+
client() {
|
|
223
|
+
return new Anthropic({
|
|
224
|
+
apiKey: this.opts.apiKey(),
|
|
225
|
+
...(this.opts.baseUrl ? { baseURL: this.opts.baseUrl } : {}),
|
|
226
|
+
...(this.opts.fetch ? { fetch: this.opts.fetch } : {}),
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
/** Start a streamed request; resolves once Claude has answered (so HTTP errors throw here). */
|
|
230
|
+
async start(params) {
|
|
231
|
+
const req = toAnthropicRequest(params, params.model, this.opts.maxOutput?.(params.model));
|
|
232
|
+
const stream = this.client().beta.messages.stream(req);
|
|
233
|
+
try {
|
|
234
|
+
await stream.withResponse();
|
|
235
|
+
}
|
|
236
|
+
catch (e) {
|
|
237
|
+
throw toSCXError(e);
|
|
238
|
+
}
|
|
239
|
+
return stream;
|
|
240
|
+
}
|
|
241
|
+
/** One whole completion (streamed underneath, so a long answer cannot hit a request timeout). */
|
|
242
|
+
async chat(params) {
|
|
243
|
+
const stream = await this.start(params);
|
|
244
|
+
let msg;
|
|
245
|
+
try {
|
|
246
|
+
msg = await stream.finalMessage();
|
|
247
|
+
}
|
|
248
|
+
catch (e) {
|
|
249
|
+
throw toSCXError(e);
|
|
250
|
+
}
|
|
251
|
+
if (msg.stop_reason === "refusal")
|
|
252
|
+
throw new SCXError(422, refusalMessage(msg), "refusal");
|
|
253
|
+
const calls = turnToolCalls(msg);
|
|
254
|
+
return {
|
|
255
|
+
id: msg.id,
|
|
256
|
+
model: msg.model,
|
|
257
|
+
created: Math.floor(Date.now() / 1000),
|
|
258
|
+
choices: [{
|
|
259
|
+
index: 0,
|
|
260
|
+
finish_reason: finishReason(msg.stop_reason),
|
|
261
|
+
message: { role: "assistant", content: turnText(msg), ...(calls.length ? { tool_calls: calls } : {}) },
|
|
262
|
+
}],
|
|
263
|
+
usage: usageOf(msg.usage),
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* A streamed completion as an OpenAI-style SSE Response. Text streams as it is
|
|
268
|
+
* written; tool calls are sent once the turn is complete, so calls from a model
|
|
269
|
+
* that was declined mid-answer (and replaced by a fallback) never reach the browser.
|
|
270
|
+
*/
|
|
271
|
+
async chatStreamResponse(params) {
|
|
272
|
+
const stream = await this.start(params);
|
|
273
|
+
const enc = new TextEncoder();
|
|
274
|
+
const created = Math.floor(Date.now() / 1000);
|
|
275
|
+
const chunk = (delta, finish = null, extra = {}) => enc.encode(`data: ${JSON.stringify({ id: "", object: "chat.completion.chunk", created, model: params.model, choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`);
|
|
276
|
+
async function* events() {
|
|
277
|
+
try {
|
|
278
|
+
for await (const ev of stream) {
|
|
279
|
+
if (ev.type === "content_block_delta" && ev.delta.type === "text_delta" && ev.delta.text)
|
|
280
|
+
yield chunk({ content: ev.delta.text });
|
|
281
|
+
}
|
|
282
|
+
const msg = await stream.finalMessage();
|
|
283
|
+
if (msg.stop_reason === "refusal")
|
|
284
|
+
throw new SCXError(422, refusalMessage(msg), "refusal");
|
|
285
|
+
const calls = turnToolCalls(msg);
|
|
286
|
+
if (calls.length)
|
|
287
|
+
yield chunk({ tool_calls: calls.map((c, index) => ({ index, ...c })) });
|
|
288
|
+
yield chunk({}, finishReason(msg.stop_reason), { usage: usageOf(msg.usage) });
|
|
289
|
+
yield enc.encode("data: [DONE]\n\n");
|
|
290
|
+
}
|
|
291
|
+
catch (e) {
|
|
292
|
+
throw toSCXError(e);
|
|
293
|
+
}
|
|
294
|
+
finally {
|
|
295
|
+
if (!stream.ended)
|
|
296
|
+
stream.abort(); // the browser went away mid-answer: stop the upstream request
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
const it = events();
|
|
300
|
+
const body = new ReadableStream({
|
|
301
|
+
async pull(ctrl) {
|
|
302
|
+
const { value, done } = await it.next();
|
|
303
|
+
if (done)
|
|
304
|
+
ctrl.close();
|
|
305
|
+
else
|
|
306
|
+
ctrl.enqueue(value);
|
|
307
|
+
},
|
|
308
|
+
async cancel() {
|
|
309
|
+
if (!stream.ended)
|
|
310
|
+
stream.abort(); // now, not after the generator's pending read
|
|
311
|
+
await it.return(undefined).catch(() => { });
|
|
312
|
+
},
|
|
313
|
+
});
|
|
314
|
+
return new Response(body, { headers: { "Content-Type": "text/event-stream" } });
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
/** A Claude model from the Models API, in the shape the Playground understands. */
|
|
318
|
+
export function normaliseAnthropic(m) {
|
|
319
|
+
const images = m.capabilities?.image_input?.supported ?? true;
|
|
320
|
+
return {
|
|
321
|
+
id: `${ANTHROPIC_PREFIX}${m.id}`,
|
|
322
|
+
name: m.display_name || m.id,
|
|
323
|
+
created: Math.floor(Date.parse(m.created_at) / 1000) || 0,
|
|
324
|
+
input_modalities: images ? ["text", "image"] : ["text"],
|
|
325
|
+
output_modalities: ["text"],
|
|
326
|
+
context_length: m.max_input_tokens,
|
|
327
|
+
max_output_length: m.max_tokens,
|
|
328
|
+
pricing: {},
|
|
329
|
+
supported_sampling_parameters: ["max_tokens", "stop"],
|
|
330
|
+
supported_features: ["tools", "json_mode", "reasoning"],
|
|
331
|
+
description: m.lifecycle === "deprecated" ? "Anthropic Claude model (deprecated: still served, being retired)." : "Anthropic Claude model.",
|
|
332
|
+
provider: "anthropic",
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
/** The Claude models the key can use (active and deprecated; retired ones are gone). */
|
|
336
|
+
export async function listAnthropicModels(apiKey, baseUrl) {
|
|
337
|
+
const client = new Anthropic({ apiKey, ...(baseUrl ? { baseURL: baseUrl } : {}), timeout: 10_000, maxRetries: 1 });
|
|
338
|
+
const out = [];
|
|
339
|
+
for await (const m of client.models.list({ limit: 100 }))
|
|
340
|
+
if (m.lifecycle !== "retired")
|
|
341
|
+
out.push(m);
|
|
342
|
+
return out;
|
|
343
|
+
}
|
|
344
|
+
//# sourceMappingURL=anthropic.js.map
|
package/server/dist/index.js
CHANGED
|
@@ -11,7 +11,7 @@ import express from "express";
|
|
|
11
11
|
import fs from "node:fs";
|
|
12
12
|
import path from "node:path";
|
|
13
13
|
import { SCXError } from "./scx.js";
|
|
14
|
-
import { PROVIDERS, PROXY_TOKEN, PORT, OPENROUTER_MODELS, apiKey, clients, clientFor, keySource, listModels } from "./providers.js";
|
|
14
|
+
import { PROVIDERS, PROXY_TOKEN, PORT, OPENROUTER_MODELS, apiKey, clients, clientFor, isRetiredStatus, keySource, listModels, proxyPaths, proxyTokenOk, upstreamHeaders, } from "./providers.js";
|
|
15
15
|
import { KnowledgeBase, buildContextBlock } from "./rag.js";
|
|
16
16
|
import { getClient, serverUrl, resolveDirectory, projectFile, listAgentModels, toUiEvent, toUiMessages, parseModelId, oc, query, httpError, SessionFamily, childSessions, markInterrupted, DEFAULT_DIRECTORY, DEFAULT_MODEL, REMOTE_URL, REPO_ROOT, ALLOWED_ROOTS, } from "./opencode.js";
|
|
17
17
|
import { mountAuth, authRequired, issueSession } from "./auth.js";
|
|
@@ -39,22 +39,21 @@ if (TRUST_PROXY) {
|
|
|
39
39
|
app.set("trust proxy", /^\d+$/.test(TRUST_PROXY) ? Number(TRUST_PROXY) : TRUST_PROXY === "true" ? true : TRUST_PROXY);
|
|
40
40
|
}
|
|
41
41
|
/**
|
|
42
|
-
* Key-injecting proxy for the agent, one route per provider (/scx/v1,
|
|
43
|
-
* /openrouter/v1). The agent's OpenCode talks to
|
|
44
|
-
* and we forward
|
|
45
|
-
* key ever enters the container (or, locally, the process)
|
|
46
|
-
* runs in. Mounted before the JSON parser so request bodies
|
|
47
|
-
* untouched.
|
|
42
|
+
* Key-injecting proxy for the agent, one route per provider (/scx/v1,
|
|
43
|
+
* /openrouter/v1, /nvidia/v1, /anthropic/v1). The agent's OpenCode talks to
|
|
44
|
+
* these with the proxy token, and we forward model calls upstream with the real
|
|
45
|
+
* key. So no provider key ever enters the container (or, locally, the process)
|
|
46
|
+
* the agent's shell runs in. Mounted before the JSON parser so request bodies
|
|
47
|
+
* pass through untouched. Anthropic's API takes its key in `x-api-key`, so the
|
|
48
|
+
* proxy token arrives there too for that route (see proxyTokenOk).
|
|
48
49
|
*/
|
|
49
|
-
const PROXY_PATHS = new Set(["/chat/completions", "/models"]);
|
|
50
50
|
for (const p of Object.values(PROVIDERS)) {
|
|
51
51
|
const prefix = `/${p.id}/v1`;
|
|
52
52
|
app.all(`${prefix}/*path`, async (req, res) => {
|
|
53
53
|
const sub = req.path.slice(prefix.length);
|
|
54
|
-
|
|
55
|
-
if (auth !== `Bearer ${PROXY_TOKEN}`)
|
|
54
|
+
if (!proxyTokenOk(p, req.headers, PROXY_TOKEN))
|
|
56
55
|
return res.status(401).json({ error: { message: "bad proxy token" } });
|
|
57
|
-
if (!
|
|
56
|
+
if (!proxyPaths(p).has(sub))
|
|
58
57
|
return res.status(404).json({ error: { message: `not proxied: ${sub}` } });
|
|
59
58
|
try {
|
|
60
59
|
const chunks = [];
|
|
@@ -64,12 +63,7 @@ for (const p of Object.values(PROVIDERS)) {
|
|
|
64
63
|
res.on("close", () => ctrl.abort());
|
|
65
64
|
const upstream = await fetch(p.baseUrl + sub + (req.url.includes("?") ? req.url.slice(req.url.indexOf("?")) : ""), {
|
|
66
65
|
method: req.method,
|
|
67
|
-
headers:
|
|
68
|
-
Authorization: `Bearer ${apiKey(p.id)}`,
|
|
69
|
-
...(p.headers ?? {}),
|
|
70
|
-
"Content-Type": req.headers["content-type"] ?? "application/json",
|
|
71
|
-
Accept: req.headers.accept ?? "*/*",
|
|
72
|
-
},
|
|
66
|
+
headers: upstreamHeaders(p, req.headers, apiKey(p.id)),
|
|
73
67
|
body: req.method === "GET" || req.method === "HEAD" ? undefined : Buffer.concat(chunks),
|
|
74
68
|
signal: ctrl.signal,
|
|
75
69
|
});
|
|
@@ -400,8 +394,8 @@ app.post("/api/chat", async (req, res) => {
|
|
|
400
394
|
}
|
|
401
395
|
const { client, model, provider } = clientFor(String(params.model ?? ""));
|
|
402
396
|
const call = { ...params, model };
|
|
403
|
-
// Keep the NVIDIA list honest: a 404 means the model was retired upstream.
|
|
404
|
-
const track = (p) => provider !== "nvidia" ? p : p.then((v) => { nvidiaHealth.markAlive(model); return v; }, (e) => { if (e instanceof SCXError && e.status
|
|
397
|
+
// Keep the NVIDIA list honest: a 404 or 410 means the model was retired upstream.
|
|
398
|
+
const track = (p) => provider !== "nvidia" ? p : p.then((v) => { nvidiaHealth.markAlive(model); return v; }, (e) => { if (e instanceof SCXError && isRetiredStatus(e.status))
|
|
405
399
|
nvidiaHealth.markRetired(model); throw e; });
|
|
406
400
|
if (params.stream) {
|
|
407
401
|
const upstream = await track(client.chatStreamResponse(call));
|
package/server/dist/opencode.js
CHANGED
|
@@ -20,7 +20,7 @@ import { execFileSync } from "node:child_process";
|
|
|
20
20
|
import { fileURLToPath } from "node:url";
|
|
21
21
|
import { createOpencodeServer, createOpencodeClient } from "@opencode-ai/sdk";
|
|
22
22
|
import { httpError } from "./errors.js";
|
|
23
|
-
import { openrouterOpencodeProvider, nvidiaOpencodeProvider, OPENROUTER_MODELS, PORT } from "./providers.js";
|
|
23
|
+
import { anthropicOpencodeProvider, openrouterOpencodeProvider, nvidiaOpencodeProvider, ANTHROPIC_MODELS, OPENROUTER_MODELS, PORT } from "./providers.js";
|
|
24
24
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
25
25
|
/** BugXHunter's own folder: the default project when none is chosen. */
|
|
26
26
|
export const REPO_ROOT = path.resolve(__dirname, "../..");
|
|
@@ -49,12 +49,15 @@ export const VISION_AGENT = {
|
|
|
49
49
|
/**
|
|
50
50
|
* Config layered on the user's own OpenCode setup. With OPENROUTER_MODELS set,
|
|
51
51
|
* it adds an `openrouter` provider that calls back through this server's
|
|
52
|
-
* key-injecting proxy, so the OpenRouter key stays in the vault.
|
|
52
|
+
* key-injecting proxy, so the OpenRouter key stays in the vault. NVIDIA and
|
|
53
|
+
* Anthropic work the same way when their keys are configured (Claude through
|
|
54
|
+
* OpenCode's native Anthropic client, the ids in ANTHROPIC_MODELS).
|
|
53
55
|
*/
|
|
54
56
|
async function inlineConfig() {
|
|
55
57
|
const openrouter = await openrouterOpencodeProvider(`http://127.0.0.1:${PORT}/openrouter/v1`);
|
|
56
58
|
const nvidia = await nvidiaOpencodeProvider(`http://127.0.0.1:${PORT}/nvidia/v1`);
|
|
57
|
-
const
|
|
59
|
+
const anthropic = await anthropicOpencodeProvider(`http://127.0.0.1:${PORT}/anthropic/v1`);
|
|
60
|
+
const provider = { ...(openrouter ? { openrouter } : {}), ...(nvidia ? { nvidia } : {}), ...(anthropic ? { anthropic } : {}) };
|
|
58
61
|
return {
|
|
59
62
|
model: DEFAULT_MODEL,
|
|
60
63
|
agent: {
|
|
@@ -310,10 +313,14 @@ export async function listAgentModels(client) {
|
|
|
310
313
|
const providers = r?.data?.providers ?? [];
|
|
311
314
|
const out = [];
|
|
312
315
|
const allowed = new Set(OPENROUTER_MODELS);
|
|
316
|
+
const claude = new Set(ANTHROPIC_MODELS);
|
|
313
317
|
for (const p of providers) {
|
|
314
318
|
for (const [mid, m] of Object.entries(p.models ?? {})) {
|
|
315
319
|
if (p.id === "openrouter" && allowed.size && !allowed.has(mid))
|
|
316
320
|
continue;
|
|
321
|
+
// OpenCode merges its own Anthropic catalogue in too; show only the configured Claude models.
|
|
322
|
+
if (p.id === "anthropic" && !claude.has(mid))
|
|
323
|
+
continue;
|
|
317
324
|
out.push({
|
|
318
325
|
id: `${p.id}/${mid}`,
|
|
319
326
|
name: m.name ?? mid,
|