bugxhunter 0.10.0 → 0.11.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.
@@ -16,6 +16,10 @@
16
16
  * For the agent, OPENROUTER_MODELS (comma list of OpenRouter ids) is turned
17
17
  * into an OpenCode provider that calls back through the runner's proxy, so
18
18
  * the key stays here in both local and Docker modes.
19
+ *
20
+ * Amazon Bedrock (`bedrock/<id>`) is the one provider that need not have a key:
21
+ * it also takes AWS credentials (an OIDC role, an SSO profile, the compute's
22
+ * role), with which the runner signs each call. See bedrock.ts.
19
23
  */
20
24
  import crypto from "node:crypto";
21
25
  import fs from "node:fs";
@@ -23,6 +27,8 @@ import os from "node:os";
23
27
  import path from "node:path";
24
28
  import { SCXClient, SCXError } from "./scx.js";
25
29
  import { ANTHROPIC_PREFIX, AnthropicChatClient, listAnthropicModels, normaliseAnthropic } from "./anthropic.js";
30
+ import * as bedrock from "./bedrock.js";
31
+ import { BEDROCK_CATALOGUE, BEDROCK_MODELS, BEDROCK_PREFIX } from "./bedrock.js";
26
32
  import { httpError } from "./errors.js";
27
33
  import * as vault from "./vault.js";
28
34
  import * as nvidiaHealth from "./nvidia-health.js";
@@ -48,6 +54,11 @@ export const PROVIDERS = {
48
54
  vaultItem: "ANTHROPIC_API_KEY", envVars: ["ANTHROPIC_API_KEY"], fileVar: "ANTHROPIC_API_KEY_FILE", authId: "anthropic",
49
55
  kind: "anthropic",
50
56
  },
57
+ bedrock: {
58
+ id: "bedrock", name: "Amazon Bedrock", baseUrl: bedrock.settings.baseUrl,
59
+ // A Bedrock API key, under the name AWS's own tools use. Optional: AWS credentials do instead (bedrock.ts).
60
+ vaultItem: "AWS_BEARER_TOKEN_BEDROCK", envVars: ["AWS_BEARER_TOKEN_BEDROCK"], fileVar: "AWS_BEARER_TOKEN_BEDROCK_FILE", authId: "bedrock",
61
+ },
51
62
  };
52
63
  /**
53
64
  * Claude models the agent may use (ANTHROPIC_MODELS, comma list of Anthropic model ids).
@@ -114,7 +125,6 @@ function fileKey(id) {
114
125
  }
115
126
  for (const k of ["SCX_PROXY_TOKEN", "OPEN_RUNNER_SECRET"])
116
127
  delete process.env[k];
117
- /** Where a provider's key comes from right now. */
118
128
  export function keySource(id) {
119
129
  const p = PROVIDERS[id];
120
130
  if (vault.isInitialised() && vault.status("none").items.includes(p.vaultItem))
@@ -123,6 +133,8 @@ export function keySource(id) {
123
133
  return "file";
124
134
  if (envKeys[id])
125
135
  return "env";
136
+ if (id === "bedrock" && bedrock.awsConfigured())
137
+ return "aws";
126
138
  if (authKeys[p.authId])
127
139
  return "opencode-auth";
128
140
  return "none";
@@ -141,6 +153,7 @@ export function apiKey(id) {
141
153
  return key;
142
154
  }
143
155
  case "env": return envKeys[id];
156
+ case "aws": throw httpError(500, `${p.name} is signed with AWS credentials here, not a key.`); // callers use authHeaders
144
157
  case "opencode-auth": return authKeys[p.authId];
145
158
  default:
146
159
  throw httpError(503, id === "scx"
@@ -148,10 +161,36 @@ export function apiKey(id) {
148
161
  : `No ${p.name} key. Add ${p.vaultItem} to the vault (keys dialog) to use ${p.name} models.`);
149
162
  }
150
163
  }
164
+ /**
165
+ * The headers that authenticate one upstream call. A bearer key for every
166
+ * provider but Bedrock on AWS credentials, where the call is signed (SigV4
167
+ * covers the method, URL, body and `headers`, so they must be the ones sent).
168
+ */
169
+ export async function authHeaders(id, request) {
170
+ if (id === "bedrock" && keySource(id) === "aws") {
171
+ // AWS credentials live outside the vault, but a locked vault must mean no model calls at
172
+ // all: once a vault exists, nothing is signed while it is sealed. A signed call counts as
173
+ // activity, like reading a key does. A runner with no vault (unattended) signs freely.
174
+ if (vault.isInitialised()) {
175
+ if (!vault.isUnsealed())
176
+ throw httpError(503, "The vault is sealed (locked). Unlock it in the sidebar.");
177
+ vault.touch();
178
+ }
179
+ return bedrock.sign(request);
180
+ }
181
+ return { Authorization: `Bearer ${apiKey(id)}` };
182
+ }
183
+ // Locking the vault also drops the AWS credentials held in memory.
184
+ vault.onSealed(bedrock.forget);
151
185
  export const clients = {
152
186
  scx: new SCXClient({ apiKey: () => apiKey("scx"), baseUrl: PROVIDERS.scx.baseUrl }),
153
187
  openrouter: new SCXClient({ apiKey: () => apiKey("openrouter"), baseUrl: PROVIDERS.openrouter.baseUrl, headers: PROVIDERS.openrouter.headers }),
154
188
  nvidia: new SCXClient({ apiKey: () => apiKey("nvidia"), baseUrl: PROVIDERS.nvidia.baseUrl }),
189
+ // Bedrock sends a stream's token usage only when asked, and its reasoning models spend much of a budget unseen.
190
+ bedrock: new SCXClient({
191
+ auth: (request) => authHeaders("bedrock", request), baseUrl: PROVIDERS.bedrock.baseUrl, streamUsage: true,
192
+ prepare: (params) => bedrock.prepareRequest(bedrock.withoutRefusedTools(params)),
193
+ }),
155
194
  };
156
195
  /** Output limits of the Claude models seen in the last model list, to cap max_tokens. */
157
196
  const anthropicLimits = new Map();
@@ -168,6 +207,8 @@ export function clientFor(model) {
168
207
  return { client: anthropicClient, model: model.slice(ANTHROPIC_PREFIX.length), provider: "anthropic" };
169
208
  if (model.startsWith("openrouter/"))
170
209
  return { client: clients.openrouter, model: model.slice("openrouter/".length), provider: "openrouter" };
210
+ if (model.startsWith(BEDROCK_PREFIX))
211
+ return { client: clients.bedrock, model: model.slice(BEDROCK_PREFIX.length), provider: "bedrock" };
171
212
  if (model.startsWith("nim/"))
172
213
  return { client: clients.nvidia, model: model.slice("nim/".length), provider: "nvidia" };
173
214
  return { client: clients.scx, model, provider: "scx" };
@@ -308,15 +349,47 @@ async function anthropicModels() {
308
349
  return [];
309
350
  }
310
351
  }
311
- /** Every model the Playground can use: SCX's, plus Anthropic's, NVIDIA's and OpenRouter's when their keys are configured. */
352
+ /** Limits assumed for a Bedrock id we hold no metadata for (an application inference profile, another model). */
353
+ const BEDROCK_DEFAULT_LIMIT = { context: 128_000, output: 16_000 };
354
+ /** A Bedrock model or inference profile as an SCXModel (Playground id `bedrock/<id>`). */
355
+ export function bedrockModel(id) {
356
+ const meta = BEDROCK_CATALOGUE[id];
357
+ return {
358
+ id: `${BEDROCK_PREFIX}${id}`,
359
+ name: meta?.name ?? id,
360
+ created: 0,
361
+ input_modalities: meta?.image ? ["text", "image"] : ["text"],
362
+ output_modalities: ["text"],
363
+ context_length: meta?.context ?? null,
364
+ max_output_length: meta?.output ?? null,
365
+ pricing: {},
366
+ // The hosted GPT models take sampling settings only at their defaults (bedrock.ts drops them).
367
+ supported_sampling_parameters: bedrock.isOpenAiGpt(id) ? ["max_tokens"] : ["temperature", "top_p", "max_tokens", "stop"],
368
+ supported_features: meta?.features ?? ["tools"],
369
+ description: meta?.description ?? "Amazon Bedrock model named in BEDROCK_MODELS (metadata not curated).",
370
+ provider: "bedrock",
371
+ };
372
+ }
373
+ /** Bedrock models for the Playground: the ids in BEDROCK_MODELS, once a key or AWS credentials are configured. */
374
+ const bedrockModels = () => (configured("bedrock") ? BEDROCK_MODELS.map(bedrockModel) : []);
375
+ /** Every model the Playground can use: SCX's, plus Anthropic's, NVIDIA's, Bedrock's and OpenRouter's when they are configured. */
312
376
  export async function listModels() {
313
- const [scxResult, anthropic, nvidia] = await Promise.all([
314
- clients.scx.listModels().then((list) => ({ list }), (error) => ({ error })),
377
+ // SCX is asked only when it has a key, like every other provider: a runner may use only
378
+ // Bedrock or Claude, and then SCX is neither called nor reported as failing.
379
+ const scxKeyed = configured("scx");
380
+ const [scxResult, anthropic, nvidiaOnly] = await Promise.all([
381
+ scxKeyed
382
+ ? clients.scx.listModels().then((list) => ({ list }), (error) => ({ error }))
383
+ : Promise.resolve({ list: [] }),
315
384
  anthropicModels(),
316
385
  nvidiaModels(),
317
386
  ]);
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.
387
+ const nvidia = [...nvidiaOnly, ...bedrockModels()]; // Bedrock sits with NVIDIA in the list: after Claude, before OpenRouter
388
+ // With no provider set up at all, say how to set up the default one.
389
+ if (!scxKeyed && !anthropic.length && !nvidia.length && !configured("openrouter"))
390
+ apiKey("scx");
391
+ // With an SCX key that does not work, still offer the other providers' models; the SCX
392
+ // error stands only when there is nothing else to show.
320
393
  if ("error" in scxResult) {
321
394
  if (!anthropic.length && !nvidia.length && !configured("openrouter"))
322
395
  throw scxResult.error;
@@ -398,6 +471,31 @@ export async function nvidiaOpencodeProvider(proxyBaseUrl) {
398
471
  models,
399
472
  };
400
473
  }
474
+ /**
475
+ * An OpenCode provider for the agent: the Bedrock models in BEDROCK_MODELS,
476
+ * calling back through the runner's proxy with the proxy token. The agent holds
477
+ * no AWS credential and no Bedrock key: the runner signs the upstream call.
478
+ */
479
+ export function bedrockOpencodeProvider(proxyBaseUrl) {
480
+ const ids = bedrock.agentModels(); // without the models that cannot call tools on this route
481
+ if (!ids.length || !configured("bedrock"))
482
+ return null;
483
+ const models = {};
484
+ for (const id of ids) {
485
+ const meta = BEDROCK_CATALOGUE[id];
486
+ models[id] = {
487
+ name: meta?.name ?? id,
488
+ limit: { context: meta?.context ?? BEDROCK_DEFAULT_LIMIT.context, output: meta?.output ?? BEDROCK_DEFAULT_LIMIT.output },
489
+ ...(meta?.image ? { attachment: true, modalities: { input: ["text", "image"], output: ["text"] } } : {}),
490
+ };
491
+ }
492
+ return {
493
+ npm: "@ai-sdk/openai-compatible",
494
+ name: "Amazon Bedrock",
495
+ options: { baseURL: proxyBaseUrl, apiKey: PROXY_TOKEN },
496
+ models,
497
+ };
498
+ }
401
499
  /** Limits the agent assumes for Claude models when the Models API cannot be asked (vault sealed). */
402
500
  const CLAUDE_DEFAULT_LIMIT = { context: 1_000_000, output: 128_000 };
403
501
  /**
@@ -438,6 +536,8 @@ export async function anthropicOpencodeProvider(proxyBaseUrl) {
438
536
  const header = (h, name) => { const v = h[name]; return Array.isArray(v) ? v[0] : v; };
439
537
  /** Upstream paths the proxy forwards for a provider (everything else is a 404). */
440
538
  export function proxyPaths(p) {
539
+ if (p.id === "bedrock")
540
+ return new Set(["/chat/completions"]); // bedrock-runtime has no OpenAI-style model list
441
541
  return p.kind === "anthropic"
442
542
  ? new Set(["/messages", "/messages/count_tokens", "/models"])
443
543
  : new Set(["/chat/completions", "/models"]);
@@ -453,20 +553,47 @@ export function proxyTokenOk(p, h, token) {
453
553
  return true;
454
554
  return p.kind === "anthropic" && sameSecret(header(h, "x-api-key") ?? "", token);
455
555
  }
456
- /** Headers for the upstream call: the real key in the provider's own scheme, plus what the client negotiated. */
556
+ /**
557
+ * Headers for the upstream call: the real key in the provider's own scheme, plus what the client negotiated.
558
+ * With no `key` there is no Authorization header: the call is signed instead (see proxyHeaders).
559
+ */
457
560
  export function upstreamHeaders(p, h, key) {
458
561
  const common = {
459
562
  "Content-Type": header(h, "content-type") ?? "application/json",
460
563
  Accept: header(h, "accept") ?? "*/*",
461
564
  };
462
565
  if (p.kind !== "anthropic")
463
- return { Authorization: `Bearer ${key}`, ...(p.headers ?? {}), ...common };
566
+ return { ...(key === undefined ? {} : { Authorization: `Bearer ${key}` }), ...(p.headers ?? {}), ...common };
464
567
  const beta = header(h, "anthropic-beta");
465
568
  return {
466
- "x-api-key": key,
569
+ "x-api-key": key ?? "",
467
570
  "anthropic-version": header(h, "anthropic-version") ?? "2023-06-01",
468
571
  ...(beta ? { "anthropic-beta": beta } : {}),
469
572
  ...common,
470
573
  };
471
574
  }
575
+ /** The body the proxy sends upstream: the agent's own, with a provider-wide default added where one is set. */
576
+ export function proxyBody(p, body) {
577
+ return p.id === "bedrock" ? bedrock.prepareBody(body) : body;
578
+ }
579
+ /**
580
+ * Why the proxy will not forward this call, or null when it will. Bedrock is reached with the
581
+ * runner's AWS identity, which can usually invoke far more than the runner means to offer, so
582
+ * the agent may name only the models in BEDROCK_MODELS.
583
+ */
584
+ export function proxyRefusal(p, body) {
585
+ if (p.id !== "bedrock")
586
+ return null;
587
+ const model = bedrock.bodyModel(body);
588
+ if (bedrock.allowsModel(model))
589
+ return null;
590
+ return `Model ${typeof model === "string" ? `"${model.slice(0, 120)}"` : "(none named)"} is not offered by this runner. Its Bedrock models are listed in BEDROCK_MODELS.`;
591
+ }
592
+ /** Everything the proxy sends upstream for one agent call, authenticated: the key injected, or the call signed. */
593
+ export async function proxyHeaders(p, h, request) {
594
+ if (keySource(p.id) !== "aws")
595
+ return upstreamHeaders(p, h, apiKey(p.id));
596
+ const headers = upstreamHeaders(p, h);
597
+ return { ...headers, ...(await authHeaders(p.id, { ...request, headers })) };
598
+ }
472
599
  //# sourceMappingURL=providers.js.map
@@ -574,7 +574,7 @@ export function commandHazard(command) {
574
574
  /** Operator / provider secrets that must never reach the executor's subprocess env,
575
575
  * so a prompt-injected agent (fed adversarial target output) has nothing to exfil. */
576
576
  export const SENSITIVE_ENV = [
577
- "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "GITHUB_TOKEN", "GH_TOKEN", "NPM_TOKEN",
577
+ "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_BEARER_TOKEN_BEDROCK", "AWS_WEB_IDENTITY_TOKEN_FILE", "GITHUB_TOKEN", "GH_TOKEN", "NPM_TOKEN",
578
578
  "ANTHROPIC_API_KEY", "OPENAI_API_KEY", "SCX_API", "SCX_API_KEY", "OPENROUTER_API_KEY", "NVIDIA_API_KEY",
579
579
  "AZURE_CLIENT_SECRET", "GCP_SERVICE_ACCOUNT", "OPEN_RUNNER_SECRET", "GITHUB_CLIENT_SECRET", "TURNSTILE_SECRET_KEY",
580
580
  ];
@@ -27,12 +27,18 @@ export class SCXError extends Error {
27
27
  export class SCXClient {
28
28
  baseUrl;
29
29
  key;
30
+ auth;
31
+ streamUsage;
32
+ prepare;
30
33
  timeoutMs;
31
34
  extraHeaders;
32
35
  constructor(opts) {
33
- if (!opts.apiKey)
36
+ if (!opts.apiKey && !opts.auth)
34
37
  throw new Error("SCXClient: apiKey is required");
35
38
  this.key = typeof opts.apiKey === "function" ? opts.apiKey : () => opts.apiKey;
39
+ this.auth = opts.auth;
40
+ this.streamUsage = opts.streamUsage ?? false;
41
+ this.prepare = opts.prepare ?? ((params) => params);
36
42
  this.baseUrl = (opts.baseUrl ?? SCX_DEFAULT_BASE_URL).replace(/\/$/, "");
37
43
  this.timeoutMs = opts.timeoutMs ?? 120_000;
38
44
  this.extraHeaders = opts.headers ?? {};
@@ -40,21 +46,21 @@ export class SCXClient {
40
46
  /** Low-level fetch that injects auth, JSON headers, and a timeout. */
41
47
  async request(path, init = {}) {
42
48
  const { json, headers, timeoutMs = this.timeoutMs, ...rest } = init;
43
- const apiKey = this.key(); // may throw (vault sealed): before any network call
49
+ const url = `${this.baseUrl}${path}`;
50
+ const body = json !== undefined ? JSON.stringify(json) : rest.body;
51
+ const plain = {
52
+ ...this.extraHeaders,
53
+ ...(json !== undefined ? { "Content-Type": "application/json" } : {}),
54
+ ...headers,
55
+ };
56
+ // Either may throw (vault sealed, no AWS session): before any network call.
57
+ const authed = this.auth
58
+ ? { ...plain, ...(await this.auth({ method: rest.method ?? "GET", url, headers: plain, body: typeof body === "string" ? body : undefined })) }
59
+ : { Authorization: `Bearer ${this.key()}`, ...plain };
44
60
  const ctrl = new AbortController();
45
61
  const t = setTimeout(() => ctrl.abort(), timeoutMs);
46
62
  try {
47
- return await fetch(`${this.baseUrl}${path}`, {
48
- ...rest,
49
- signal: ctrl.signal,
50
- headers: {
51
- Authorization: `Bearer ${apiKey}`,
52
- ...this.extraHeaders,
53
- ...(json !== undefined ? { "Content-Type": "application/json" } : {}),
54
- ...headers,
55
- },
56
- body: json !== undefined ? JSON.stringify(json) : rest.body,
57
- });
63
+ return await fetch(url, { ...rest, signal: ctrl.signal, headers: authed, body });
58
64
  }
59
65
  catch (e) {
60
66
  if (ctrl.signal.aborted) {
@@ -106,7 +112,7 @@ export class SCXClient {
106
112
  // can take minutes over, so allow longer than the "started answering" limit for streams.
107
113
  const res = await this.request("/chat/completions", {
108
114
  method: "POST",
109
- json: { ...params, stream: false },
115
+ json: this.prepare({ ...params, stream: false }),
110
116
  timeoutMs: opts.timeoutMs ?? Math.max(this.timeoutMs, NON_STREAM_TIMEOUT_MS),
111
117
  });
112
118
  return this.json(res);
@@ -119,7 +125,10 @@ export class SCXClient {
119
125
  async chatStreamResponse(params) {
120
126
  const res = await this.request("/chat/completions", {
121
127
  method: "POST",
122
- json: { ...params, stream: true },
128
+ json: this.prepare({
129
+ ...params, stream: true,
130
+ ...(this.streamUsage && params.stream_options === undefined ? { stream_options: { include_usage: true } } : {}),
131
+ }),
123
132
  });
124
133
  if (!res.ok)
125
134
  throw await this.toError(res);
@@ -239,11 +239,18 @@ export function unseal(dekB64) {
239
239
  lastUse = Date.now();
240
240
  audit("vault.unsealed", {});
241
241
  }
242
+ const sealListeners = [];
243
+ /** Run `listener` whenever the vault is sealed: for secrets held outside it that a lock must drop too. */
244
+ export function onSealed(listener) {
245
+ sealListeners.push(listener);
246
+ }
242
247
  export function sealVault(reason = "user") {
243
248
  const was = dek !== null;
244
249
  if (dek)
245
250
  dek.fill(0);
246
251
  dek = null;
252
+ for (const listener of sealListeners)
253
+ listener();
247
254
  if (was)
248
255
  audit("vault.sealed", { reason });
249
256
  }