bugxhunter 0.9.3 → 0.9.5

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.
@@ -22,6 +22,7 @@ import fs from "node:fs";
22
22
  import os from "node:os";
23
23
  import path from "node:path";
24
24
  import { SCXClient, SCXError } from "./scx.js";
25
+ import { ANTHROPIC_PREFIX, AnthropicChatClient, listAnthropicModels, normaliseAnthropic } from "./anthropic.js";
25
26
  import { httpError } from "./errors.js";
26
27
  import * as vault from "./vault.js";
27
28
  import * as nvidiaHealth from "./nvidia-health.js";
@@ -41,7 +42,19 @@ export const PROVIDERS = {
41
42
  // `NVIDI_NGC_POC` is the name the NGC proof-of-concept key already uses in .env; `NVIDIA_API_KEY` is the tidy one.
42
43
  vaultItem: "NVIDIA_API_KEY", envVars: ["NVIDIA_API_KEY", "NVIDI_NGC_POC"], fileVar: "NVIDIA_API_KEY_FILE", authId: "nvidia",
43
44
  },
45
+ anthropic: {
46
+ id: "anthropic", name: "Anthropic", baseUrl: process.env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com/v1",
47
+ // Scrubbed from the environment like the others, so the agent's shell never inherits it.
48
+ vaultItem: "ANTHROPIC_API_KEY", envVars: ["ANTHROPIC_API_KEY"], fileVar: "ANTHROPIC_API_KEY_FILE", authId: "anthropic",
49
+ kind: "anthropic",
50
+ },
44
51
  };
52
+ /**
53
+ * Claude models the agent may use (ANTHROPIC_MODELS, comma list of Anthropic model ids).
54
+ * The Playground lists every model the key can use; the agent's picker only these.
55
+ */
56
+ export const ANTHROPIC_MODELS = (process.env.ANTHROPIC_MODELS?.trim() || "claude-opus-5-5,claude-sonnet-5-5,claude-haiku-5-5")
57
+ .split(",").map((s) => s.trim()).filter(Boolean);
45
58
  /** OpenRouter ids the agent may use (OPENROUTER_MODELS=anthropic/claude-sonnet-4.5,openai/gpt-6.1-sol). */
46
59
  export const OPENROUTER_MODELS = (process.env.OPENROUTER_MODELS ?? "").split(",").map((s) => s.trim()).filter(Boolean);
47
60
  const NVIDIA_CATALOGUE = {
@@ -53,7 +66,7 @@ const NVIDIA_CATALOGUE = {
53
66
  "nvidia/nemotron-3.5-super-vl-120b-a12b": { name: "Nemotron 3.5 Super VL 120B", context: 128_000, output: 16_000, image: true, features: ["tools", "json_mode"], description: "Vision-language Nemotron; reads images (good for the vision subagent)." },
54
67
  };
55
68
  /** Upstream NVIDIA ids the Playground and agent may use (default = the curated set above). */
56
- export const NVIDIA_MODELS = (process.env.NVIDIA_MODELS ?? Object.keys(NVIDIA_CATALOGUE).join(","))
69
+ export const NVIDIA_MODELS = (process.env.NVIDIA_MODELS?.trim() || Object.keys(NVIDIA_CATALOGUE).join(","))
57
70
  .split(",").map((s) => s.trim()).filter(Boolean);
58
71
  export const PORT = Number(process.env.PORT ?? 8790);
59
72
  /**
@@ -140,8 +153,19 @@ export const clients = {
140
153
  openrouter: new SCXClient({ apiKey: () => apiKey("openrouter"), baseUrl: PROVIDERS.openrouter.baseUrl, headers: PROVIDERS.openrouter.headers }),
141
154
  nvidia: new SCXClient({ apiKey: () => apiKey("nvidia"), baseUrl: PROVIDERS.nvidia.baseUrl }),
142
155
  };
143
- /** Playground model ids: SCX ids as-is, OpenRouter ids prefixed `openrouter/`, NVIDIA NIM ids `nim/`. */
156
+ /** Output limits of the Claude models seen in the last model list, to cap max_tokens. */
157
+ const anthropicLimits = new Map();
158
+ /** The Anthropic SDK wants the API root; PROVIDERS keeps the /v1 base the proxy forwards to. */
159
+ const anthropicRoot = () => PROVIDERS.anthropic.baseUrl.replace(/\/v1\/?$/, "");
160
+ const anthropicClient = new AnthropicChatClient({
161
+ apiKey: () => apiKey("anthropic"),
162
+ baseUrl: anthropicRoot(),
163
+ maxOutput: (model) => anthropicLimits.get(model),
164
+ });
165
+ /** Playground model ids: SCX ids as-is, OpenRouter ids prefixed `openrouter/`, NVIDIA NIM ids `nim/`, Claude `anthropic/`. */
144
166
  export function clientFor(model) {
167
+ if (model.startsWith(ANTHROPIC_PREFIX))
168
+ return { client: anthropicClient, model: model.slice(ANTHROPIC_PREFIX.length), provider: "anthropic" };
145
169
  if (model.startsWith("openrouter/"))
146
170
  return { client: clients.openrouter, model: model.slice("openrouter/".length), provider: "openrouter" };
147
171
  if (model.startsWith("nim/"))
@@ -252,8 +276,12 @@ async function nvidiaModels() {
252
276
  return curated();
253
277
  }
254
278
  }
255
- /** One tiny chat to see whether an NVIDIA model's endpoint still exists (404 = retired). */
256
- // A retired model answers 404 at once; a slow or queued one is just "unknown", so keep this short.
279
+ /** Upstream statuses that mean the model is gone for good, not momentarily unavailable:
280
+ * 404 (endpoint removed) and 410 Gone (NVIDIA's end-of-life response, with a note like
281
+ * "model '...' has reached its end of life"). */
282
+ export const isRetiredStatus = (status) => status === 404 || status === 410;
283
+ /** One tiny chat to see whether an NVIDIA model's endpoint still exists (404/410 = retired). */
284
+ // A retired model answers 404 or 410 at once; a slow or queued one is just "unknown", so keep this short.
257
285
  const probeClient = new SCXClient({ apiKey: () => apiKey("nvidia"), baseUrl: PROVIDERS.nvidia.baseUrl, timeoutMs: 15_000 });
258
286
  export async function probeNvidia(id) {
259
287
  try {
@@ -261,24 +289,51 @@ export async function probeNvidia(id) {
261
289
  return "ok";
262
290
  }
263
291
  catch (e) {
264
- return e instanceof SCXError && e.status === 404 ? "missing" : "unknown";
292
+ return e instanceof SCXError && isRetiredStatus(e.status) ? "missing" : "unknown";
293
+ }
294
+ }
295
+ const oneLineMessage = (e) => String(e?.message ?? e).replace(/\s+/g, " ").slice(0, 300);
296
+ /** Claude models for the Playground, when an Anthropic key is configured (and readable: the vault open). */
297
+ async function anthropicModels() {
298
+ if (!configured("anthropic"))
299
+ return [];
300
+ try {
301
+ const models = await listAnthropicModels(apiKey("anthropic"), anthropicRoot());
302
+ for (const m of models)
303
+ anthropicLimits.set(m.id, m.max_tokens);
304
+ return models.map(normaliseAnthropic);
305
+ }
306
+ catch (e) {
307
+ console.error("[anthropic] model list failed:", oneLineMessage(e));
308
+ return [];
265
309
  }
266
310
  }
267
- /** Every model the Playground can use: SCX's, plus OpenRouter's and NVIDIA's when their keys are configured. */
311
+ /** Every model the Playground can use: SCX's, plus Anthropic's, NVIDIA's and OpenRouter's when their keys are configured. */
268
312
  export async function listModels() {
269
- const scx = (await clients.scx.listModels()).map((m) => ({ ...m, provider: "scx" }));
270
- const nvidia = await nvidiaModels();
313
+ const [scxResult, anthropic, nvidia] = await Promise.all([
314
+ clients.scx.listModels().then((list) => ({ list }), (error) => ({ error })),
315
+ anthropicModels(),
316
+ nvidiaModels(),
317
+ ]);
318
+ // Without a working SCX key, still offer the other providers' models (a runner may use only
319
+ // Claude, say); the SCX error stands only when there is nothing else to show.
320
+ if ("error" in scxResult) {
321
+ if (!anthropic.length && !nvidia.length && !configured("openrouter"))
322
+ throw scxResult.error;
323
+ console.error("[scx] model list failed:", oneLineMessage(scxResult.error));
324
+ }
325
+ const scx = ("list" in scxResult ? scxResult.list : []).map((m) => ({ ...m, provider: "scx" }));
271
326
  if (!configured("openrouter"))
272
- return [...scx, ...nvidia];
327
+ return [...scx, ...anthropic, ...nvidia];
273
328
  try {
274
329
  const all = (await openRouterCatalogue()).map(normaliseOpenRouter);
275
330
  const allow = new Set(OPENROUTER_MODELS.map((id) => `openrouter/${id}`));
276
331
  const picked = allow.size ? all.filter((m) => allow.has(m.id)) : all;
277
- return [...scx, ...nvidia, ...picked.sort((a, b) => a.name.localeCompare(b.name))];
332
+ return [...scx, ...anthropic, ...nvidia, ...picked.sort((a, b) => a.name.localeCompare(b.name))];
278
333
  }
279
334
  catch (e) {
280
335
  console.error("[openrouter] model list failed:", e.message);
281
- return [...scx, ...nvidia];
336
+ return [...scx, ...anthropic, ...nvidia];
282
337
  }
283
338
  }
284
339
  /**
@@ -343,4 +398,75 @@ export async function nvidiaOpencodeProvider(proxyBaseUrl) {
343
398
  models,
344
399
  };
345
400
  }
401
+ /** Limits the agent assumes for Claude models when the Models API cannot be asked (vault sealed). */
402
+ const CLAUDE_DEFAULT_LIMIT = { context: 1_000_000, output: 128_000 };
403
+ /**
404
+ * An OpenCode provider for the agent: Claude through OpenCode's native Anthropic
405
+ * client, calling back through the runner's proxy (/anthropic/v1) with the proxy
406
+ * token, so the Anthropic key never reaches the agent. Only when a key is
407
+ * configured; limits from the Models API when the vault is open.
408
+ */
409
+ export async function anthropicOpencodeProvider(proxyBaseUrl) {
410
+ if (!ANTHROPIC_MODELS.length || !configured("anthropic"))
411
+ return null;
412
+ const info = new Map();
413
+ try {
414
+ for (const m of await listAnthropicModels(apiKey("anthropic"), anthropicRoot())) {
415
+ info.set(m.id, { name: m.display_name, context: m.max_input_tokens, output: m.max_tokens });
416
+ }
417
+ }
418
+ catch (e) {
419
+ console.error("[anthropic] could not fetch model limits, using defaults:", oneLineMessage(e));
420
+ }
421
+ const models = {};
422
+ for (const id of ANTHROPIC_MODELS) {
423
+ const m = info.get(id);
424
+ models[id] = {
425
+ name: m?.name ?? id,
426
+ limit: { context: m?.context ?? CLAUDE_DEFAULT_LIMIT.context, output: m?.output ?? CLAUDE_DEFAULT_LIMIT.output },
427
+ attachment: true,
428
+ modalities: { input: ["text", "image"], output: ["text"] },
429
+ };
430
+ }
431
+ return {
432
+ npm: "@ai-sdk/anthropic",
433
+ name: "Anthropic",
434
+ options: { baseURL: proxyBaseUrl, apiKey: PROXY_TOKEN },
435
+ models,
436
+ };
437
+ }
438
+ const header = (h, name) => { const v = h[name]; return Array.isArray(v) ? v[0] : v; };
439
+ /** Upstream paths the proxy forwards for a provider (everything else is a 404). */
440
+ export function proxyPaths(p) {
441
+ return p.kind === "anthropic"
442
+ ? new Set(["/messages", "/messages/count_tokens", "/models"])
443
+ : new Set(["/chat/completions", "/models"]);
444
+ }
445
+ const sameSecret = (a, b) => {
446
+ const x = Buffer.from(a), y = Buffer.from(b);
447
+ return x.length === y.length && crypto.timingSafeEqual(x, y);
448
+ };
449
+ /** Whether a proxy call carries the proxy token: as a Bearer token, or (Anthropic clients) in x-api-key. */
450
+ export function proxyTokenOk(p, h, token) {
451
+ const bearer = header(h, "authorization") ?? "";
452
+ if (sameSecret(bearer, `Bearer ${token}`))
453
+ return true;
454
+ return p.kind === "anthropic" && sameSecret(header(h, "x-api-key") ?? "", token);
455
+ }
456
+ /** Headers for the upstream call: the real key in the provider's own scheme, plus what the client negotiated. */
457
+ export function upstreamHeaders(p, h, key) {
458
+ const common = {
459
+ "Content-Type": header(h, "content-type") ?? "application/json",
460
+ Accept: header(h, "accept") ?? "*/*",
461
+ };
462
+ if (p.kind !== "anthropic")
463
+ return { Authorization: `Bearer ${key}`, ...(p.headers ?? {}), ...common };
464
+ const beta = header(h, "anthropic-beta");
465
+ return {
466
+ "x-api-key": key,
467
+ "anthropic-version": header(h, "anthropic-version") ?? "2023-06-01",
468
+ ...(beta ? { "anthropic-beta": beta } : {}),
469
+ ...common,
470
+ };
471
+ }
346
472
  //# sourceMappingURL=providers.js.map