bugxhunter 0.9.7 → 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.
@@ -11,7 +11,8 @@ 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, isRetiredStatus, keySource, listModels, proxyPaths, proxyTokenOk, upstreamHeaders, } from "./providers.js";
14
+ import { PROVIDERS, PROXY_TOKEN, PORT, OPENROUTER_MODELS, clients, clientFor, configured, isRetiredStatus, keySource, listModels, proxyBody, proxyHeaders, proxyPaths, proxyRefusal, proxyTokenOk, } from "./providers.js";
15
+ import { REASONING_EFFORT as bedrockEffort, settings as bedrockSettings } from "./bedrock.js";
15
16
  import { KnowledgeBase, buildContextBlock } from "./rag.js";
16
17
  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
18
  import { mountAuth, authRequired, issueSession } from "./auth.js";
@@ -25,6 +26,8 @@ import { VERSION } from "./version.js";
25
26
  import { apiLimiter, fileLimiter, staticLimiter } from "./ratelimit.js";
26
27
  import { createWorkspace, deleteWorkspace, listFiles, listWorkspaces, saveUpload, WORKSPACES_ROOT } from "./workspaces.js";
27
28
  import * as github from "./github.js";
29
+ import { parseReconHarness, setAnthropicAvailable } from "./recon.js";
30
+ import { EXECUTOR_AGENT, inRunningRecon, parseEnvFidelity, reconState, startRecon, stopRecon, } from "./recon-run.js";
28
31
  // Keys, the proxy token and the provider clients live in providers.ts, which
29
32
  // also scrubs every secret from the environment before OpenCode is spawned.
30
33
  const scx = clients.scx;
@@ -61,10 +64,16 @@ for (const p of Object.values(PROVIDERS)) {
61
64
  chunks.push(c);
62
65
  const ctrl = new AbortController();
63
66
  res.on("close", () => ctrl.abort());
64
- const upstream = await fetch(p.baseUrl + sub + (req.url.includes("?") ? req.url.slice(req.url.indexOf("?")) : ""), {
67
+ const url = p.baseUrl + sub + (req.url.includes("?") ? req.url.slice(req.url.indexOf("?")) : "");
68
+ const received = Buffer.concat(chunks);
69
+ const refusal = req.method === "POST" ? proxyRefusal(p, received) : null;
70
+ if (refusal)
71
+ return res.status(403).json({ error: { message: refusal, type: "model_not_offered" } });
72
+ const body = req.method === "GET" || req.method === "HEAD" ? undefined : proxyBody(p, received);
73
+ const upstream = await fetch(url, {
65
74
  method: req.method,
66
- headers: upstreamHeaders(p, req.headers, apiKey(p.id)),
67
- body: req.method === "GET" || req.method === "HEAD" ? undefined : Buffer.concat(chunks),
75
+ headers: await proxyHeaders(p, req.headers, { method: req.method, url, body }),
76
+ body,
68
77
  signal: ctrl.signal,
69
78
  });
70
79
  res.status(upstream.status);
@@ -795,10 +804,14 @@ app.post("/api/agent/permission", async (req, res) => {
795
804
  }
796
805
  const directory = await resolveDirectory(dir);
797
806
  const client = await getClient(directory);
807
+ // During a recon run every approval is for one command: "always" would make
808
+ // OpenCode stop asking for that command pattern, and the gate would never
809
+ // see it again.
810
+ const reply = response === "always" && inRunningRecon(sessionID) ? "once" : response;
798
811
  unwrap(await client.postSessionIdPermissionsPermissionId({
799
812
  path: { id: sessionID, permissionID },
800
813
  query: { directory },
801
- body: { response },
814
+ body: { response: reply },
802
815
  }));
803
816
  res.json({ ok: true });
804
817
  }
@@ -806,6 +819,82 @@ app.post("/api/agent/permission", async (req, res) => {
806
819
  sendError(res, e);
807
820
  }
808
821
  });
822
+ // --- Supervised recon (recon-run.ts) ---------------------------------------------
823
+ /** The recon runner's view of OpenCode for one project folder. */
824
+ async function reconBackend(directory) {
825
+ const client = await getClient(directory);
826
+ return {
827
+ async events() {
828
+ const sub = await client.event.subscribe({ query: { directory } });
829
+ return { stream: sub.stream, close: () => { void sub.stream.return?.(undefined); } };
830
+ },
831
+ async prompt({ sessionID, agent, model, text }) {
832
+ unwrap(await client.session.promptAsync({
833
+ path: { id: sessionID }, query: { directory },
834
+ body: { agent, model: parseModelId(model), parts: [{ type: "text", text }] },
835
+ }));
836
+ },
837
+ async replyPermission(sessionID, permissionID, response) {
838
+ unwrap(await client.postSessionIdPermissionsPermissionId({ path: { id: sessionID, permissionID }, query: { directory }, body: { response } }));
839
+ },
840
+ async abort(sessionID) {
841
+ await client.session.abort({ path: { id: sessionID }, query: { directory } });
842
+ },
843
+ };
844
+ }
845
+ /**
846
+ * Start a supervised recon run on a session: the driver loop prompts the
847
+ * `recon` agent round after round, answers the approvals the gate clears and
848
+ * leaves the rest for the person. Needs the operator's statement that they are
849
+ * authorised to test the scope.
850
+ */
851
+ app.post("/api/agent/recon", async (req, res) => {
852
+ try {
853
+ const b = (req.body ?? {});
854
+ if (!b.sessionID)
855
+ return res.status(400).json({ error: { message: "sessionID required" } });
856
+ if (b.authorised !== true)
857
+ return res.status(400).json({ error: { message: "Confirm that you are authorised to test this target." } });
858
+ const directory = await resolveDirectory(b.directory);
859
+ // The agents come from the agent's own config: an image or server from
860
+ // before recon was wired in doesn't have them.
861
+ const agents = await oc(`/agent${query({ directory })}`).catch(() => []);
862
+ if (!agents.some((a) => a?.name === EXECUTOR_AGENT)) {
863
+ return res.status(409).json({ error: { message: REMOTE_URL
864
+ ? "The agent container has no recon agent. Rebuild or pull the agent image for this version."
865
+ : "OpenCode has no recon agent. Restart BugXHunter." } });
866
+ }
867
+ setAnthropicAvailable(configured("anthropic"));
868
+ const state = await startRecon({
869
+ sessionID: b.sessionID,
870
+ scope: String(b.scope ?? ""),
871
+ objective: String(b.objective ?? ""),
872
+ env: parseEnvFidelity(b.env),
873
+ harness: parseReconHarness({ maxRounds: b.maxRounds, budgetTokens: b.budgetTokens }),
874
+ backend: await reconBackend(directory),
875
+ log: (event, data) => audit(event, { directory, ...data }),
876
+ });
877
+ res.json({ recon: state });
878
+ }
879
+ catch (e) {
880
+ sendError(res, e);
881
+ }
882
+ });
883
+ app.get("/api/agent/recon", (req, res) => {
884
+ res.json({ recon: reconState(String(req.query.sessionID || "")) });
885
+ });
886
+ app.post("/api/agent/recon/stop", async (req, res) => {
887
+ try {
888
+ const sessionID = String(req.body?.sessionID || "");
889
+ const state = await stopRecon(sessionID);
890
+ if (state)
891
+ audit("recon.stop", { session: sessionID });
892
+ res.json({ recon: state });
893
+ }
894
+ catch (e) {
895
+ sendError(res, e);
896
+ }
897
+ });
809
898
  // Audit log of agent activity (see audit.ts), fed by OpenCode's event stream.
810
899
  if (LOG_DIR)
811
900
  serverUrl().then(followOpencode).catch((e) => console.error("[audit] not following OpenCode:", e));
@@ -933,13 +1022,16 @@ const server = app.listen(PORT, process.env.HOST ?? "127.0.0.1", () => {
933
1022
  vault: "vault",
934
1023
  file: "a key file (not in the clear in the environment)",
935
1024
  env: ".env — consider moving it into the vault",
1025
+ aws: `AWS credentials (${bedrockSettings.describe}), region ${bedrockSettings.region}`,
936
1026
  "opencode-auth": "OpenCode's auth.json — consider moving it into the vault",
937
1027
  none: p.id === "scx" ? "none yet — set up the vault in the sidebar" : "not configured (optional)",
938
1028
  }[src];
939
- console.log(` ${p.name} key: ${where}`);
1029
+ console.log(` ${p.name} ${src === "aws" ? "sign-in" : "key"}: ${where}`);
940
1030
  }
941
1031
  if (vault.isInitialised())
942
1032
  console.log(` vault: ${vault.VAULT_FILE} (${vault.isUnsealed() ? "unsealed" : "sealed — unlock it in the UI"})`);
1033
+ if (bedrockEffort && keySource("bedrock") !== "none")
1034
+ console.log(` Amazon Bedrock reasoning effort: ${bedrockEffort} (unless a call sets its own)`);
943
1035
  if (OPENROUTER_MODELS.length)
944
1036
  console.log(` OpenRouter models for the agent: ${OPENROUTER_MODELS.join(", ")}`);
945
1037
  console.log(` agent: ${REMOTE_URL ? `remote OpenCode at ${REMOTE_URL}` : "local OpenCode"}`);
@@ -20,8 +20,8 @@ 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 { anthropicOpencodeProvider, openrouterOpencodeProvider, nvidiaOpencodeProvider, ANTHROPIC_MODELS, OPENROUTER_MODELS, PORT } from "./providers.js";
24
- import { RECON_AGENTS, withScrubbedEnv } from "./recon.js";
23
+ import { anthropicOpencodeProvider, bedrockOpencodeProvider, openrouterOpencodeProvider, nvidiaOpencodeProvider, ANTHROPIC_MODELS, OPENROUTER_MODELS, PORT } from "./providers.js";
24
+ import { reconAgents, setAnthropicAvailable, tierOrder, withScrubbedEnv } from "./recon.js";
25
25
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
26
26
  /** BugXHunter's own folder: the default project when none is chosen. */
27
27
  export const REPO_ROOT = path.resolve(__dirname, "../..");
@@ -50,7 +50,7 @@ export const VISION_AGENT = {
50
50
  /**
51
51
  * Config layered on the user's own OpenCode setup. With OPENROUTER_MODELS set,
52
52
  * it adds an `openrouter` provider that calls back through this server's
53
- * key-injecting proxy, so the OpenRouter key stays in the vault. NVIDIA and
53
+ * key-injecting proxy, so the OpenRouter key stays in the vault. NVIDIA, Bedrock and
54
54
  * Anthropic work the same way when their keys are configured (Claude through
55
55
  * OpenCode's native Anthropic client, the ids in ANTHROPIC_MODELS).
56
56
  */
@@ -58,16 +58,33 @@ async function inlineConfig() {
58
58
  const openrouter = await openrouterOpencodeProvider(`http://127.0.0.1:${PORT}/openrouter/v1`);
59
59
  const nvidia = await nvidiaOpencodeProvider(`http://127.0.0.1:${PORT}/nvidia/v1`);
60
60
  const anthropic = await anthropicOpencodeProvider(`http://127.0.0.1:${PORT}/anthropic/v1`);
61
- const provider = { ...(openrouter ? { openrouter } : {}), ...(nvidia ? { nvidia } : {}), ...(anthropic ? { anthropic } : {}) };
61
+ // Recon: without an Anthropic key the default profile falls back to the
62
+ // open-weight one; with a key, every Claude model a recon role names is
63
+ // registered (the picker still shows only ANTHROPIC_MODELS, see listAgentModels).
64
+ setAnthropicAvailable(Boolean(anthropic));
65
+ if (anthropic) {
66
+ const models = anthropic.models;
67
+ for (const id of tierOrder()) {
68
+ const m = parseModelId(id);
69
+ if (m?.providerID !== "anthropic" || Object.hasOwn(models, m.modelID))
70
+ continue;
71
+ models[m.modelID] = {
72
+ name: m.modelID, limit: { context: 1_000_000, output: 128_000 },
73
+ attachment: true, modalities: { input: ["text", "image"], output: ["text"] },
74
+ };
75
+ }
76
+ }
77
+ const bedrock = bedrockOpencodeProvider(`http://127.0.0.1:${PORT}/bedrock/v1`);
78
+ const provider = { ...(openrouter ? { openrouter } : {}), ...(nvidia ? { nvidia } : {}), ...(anthropic ? { anthropic } : {}), ...(bedrock ? { bedrock } : {}) };
62
79
  return {
63
80
  model: DEFAULT_MODEL,
64
81
  agent: {
65
82
  build: { model: DEFAULT_MODEL },
66
83
  plan: { model: DEFAULT_MODEL },
67
84
  vision: VISION_AGENT,
68
- // Supervised recon/autopwn: executor (GLM) + triage (Haiku) + verify
69
- // (Sonnet) + escalate (Mythos), each on the job it is good at. See recon.ts.
70
- ...RECON_AGENTS,
85
+ // Supervised recon: executor + triage + verify + escalate, each on the
86
+ // model the active profile gives it. See recon.ts and recon-run.ts.
87
+ ...reconAgents(),
71
88
  },
72
89
  permission: { edit: "ask", bash: "ask" },
73
90
  ...(Object.keys(provider).length ? { provider } : {}),
@@ -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
@@ -17,7 +17,7 @@
17
17
  * decision has to ride the event stream. The runner is handed `gate` and calls
18
18
  * it on each permission as it arrives.
19
19
  */
20
- import { routeModel, harnessFor, classifyCommand, commandHazard, allCapped, originOf, escalateAfter, } from "./recon.js";
20
+ import { routeModel, harnessFor, classifyCommand, commandHazard, allCapped, originOf, escalateAfter, STATUS_LINE, } from "./recon.js";
21
21
  const SEVERITY_RANK = { low: 0, medium: 1, high: 2, critical: 3 };
22
22
  const worstSeverity = (fs) => {
23
23
  let best;
@@ -35,7 +35,7 @@ const DEFAULT_RECON_HARNESS = {
35
35
  const posInt = (v, d) => (typeof v === "number" && Number.isInteger(v) && v >= 1 ? v : d);
36
36
  /** Merge harness overrides over the profile and hard defaults WITHOUT letting an
37
37
  * undefined/NaN/Infinity override erase a cap — the loop is never unbounded. */
38
- function resolveHarness(override) {
38
+ export function resolveHarness(override) {
39
39
  const merged = { ...DEFAULT_RECON_HARNESS, ...harnessFor("executor"), ...override };
40
40
  return {
41
41
  ...merged,
@@ -123,6 +123,7 @@ export class ReconRun {
123
123
  return { attempts: this.attempts, budgetRemaining: this.budgetRemaining(), ...extra };
124
124
  }
125
125
  }
126
+ const STATUS_REMINDER = `End your turn with one final line: "${STATUS_LINE}: continue", "${STATUS_LINE}: stuck" or "${STATUS_LINE}: done".`;
126
127
  /** Build the executor's seed prompt: scope fence + env-fidelity gate + objective. */
127
128
  export function buildReconKickoff(opts) {
128
129
  const { objective, scope, env } = opts;
@@ -132,10 +133,93 @@ export function buildReconKickoff(opts) {
132
133
  `ENVIRONMENT FIDELITY: this is a ${env.kind} instance. ${env.divergences}${nonProd} Tag every finding with this environment; if a finding depends on a setting that differs from production, mark it config-dependent and say what to re-test against production — never report it as a clean production bug.`,
133
134
  `OBJECTIVE: ${objective}`,
134
135
  `Work one hypothesis at a time with the smallest low-impact probe. Read-only probes run freely; anything that changes state pauses for human approval. When you have a candidate, hand it to the recon-verify subagent — do not promote it yourself.`,
136
+ STATUS_REMINDER,
135
137
  ].join("\n\n");
136
138
  }
137
139
  /** Prompt that nudges the executor forward after a turn goes idle with work left. */
138
- export const RECON_CONTINUE = "Continue: take the next untested hypothesis within scope. If the in-scope surface is genuinely exhausted, stop and say so rather than widening scope. Hand any new candidate to recon-verify.";
140
+ export const RECON_CONTINUE = "Continue: take the next untested hypothesis within scope. If the in-scope surface is genuinely exhausted, stop and say so rather than widening scope. Hand any new candidate to recon-verify. " + STATUS_REMINDER;
141
+ /* ─────────────── reading a turn back (pure; the session runner calls these) ─────────────── */
142
+ /**
143
+ * What the executor said about its own turn, from its final `RECON-STATUS:` line
144
+ * (the last one wins). Without the line, a turn that completed at least one tool
145
+ * call is taken to have made progress, and one that did nothing is idle.
146
+ */
147
+ export function parseTurnStatus(text, toolsCompleted) {
148
+ const all = [...text.matchAll(new RegExp(`${STATUS_LINE}:\\s*\\**\\s*(continue|stuck|done)\\b`, "gi"))];
149
+ const status = all.length ? all[all.length - 1][1].toLowerCase() : undefined;
150
+ if (status === "done")
151
+ return { madeProgress: true, done: true };
152
+ if (status === "stuck")
153
+ return { madeProgress: false, stuck: true };
154
+ if (status === "continue")
155
+ return { madeProgress: true };
156
+ return { madeProgress: toolsCompleted > 0 };
157
+ }
158
+ const VERDICTS = ["real", "config-dependent", "rejected"];
159
+ const SEVERITIES = ["low", "medium", "high", "critical"];
160
+ const clipText = (v, n) => {
161
+ const s = str(v)?.trim();
162
+ return s ? (s.length > n ? s.slice(0, n) + "…" : s) : undefined;
163
+ };
164
+ /** Every top-level `{…}` span in `text` (string-aware brace matching). */
165
+ function jsonObjects(text) {
166
+ const out = [];
167
+ let depth = 0, start = -1, inStr = false, esc = false;
168
+ for (let i = 0; i < text.length; i++) {
169
+ const c = text[i];
170
+ if (inStr) {
171
+ if (esc)
172
+ esc = false;
173
+ else if (c === "\\")
174
+ esc = true;
175
+ else if (c === '"')
176
+ inStr = false;
177
+ continue;
178
+ }
179
+ if (c === '"') {
180
+ if (depth)
181
+ inStr = true;
182
+ continue;
183
+ }
184
+ if (c === "{") {
185
+ if (depth++ === 0)
186
+ start = i;
187
+ }
188
+ else if (c === "}" && depth && --depth === 0)
189
+ out.push(text.slice(start, i + 1));
190
+ }
191
+ return out;
192
+ }
193
+ /**
194
+ * The verifier's verdicts, parsed from its reply (the JSON block its prompt asks
195
+ * for). Anything that is not valid JSON with a known verdict AND severity is
196
+ * dropped: an unparseable verdict is never promoted to a finding. The text is
197
+ * model output about an adversarial target, so it is clipped and stays data.
198
+ */
199
+ export function parseVerifierFindings(text, env) {
200
+ const out = [];
201
+ for (const raw of jsonObjects(text ?? "")) {
202
+ let o;
203
+ try {
204
+ o = JSON.parse(raw);
205
+ }
206
+ catch {
207
+ continue;
208
+ }
209
+ const verdict = VERDICTS.find((v) => v === String(get(o, "verdict")).toLowerCase());
210
+ const severity = SEVERITIES.find((s) => s === String(get(o, "severity")).toLowerCase());
211
+ const repro = clipText(get(o, "repro"), 4000);
212
+ if (!verdict || !severity || !repro)
213
+ continue;
214
+ out.push({
215
+ title: clipText(get(o, "title"), 200) ?? repro.slice(0, 80),
216
+ severity, verdict, repro, env,
217
+ standardId: clipText(get(o, "standard_id") ?? get(o, "standardId"), 60),
218
+ prodCaveat: clipText(get(o, "prod_caveat") ?? get(o, "prodCaveat"), 1000),
219
+ });
220
+ }
221
+ return out;
222
+ }
139
223
  /**
140
224
  * Drive one supervised recon run to completion. Pure control flow over the
141
225
  * injected runner: route (and escalate) the executor model each round, run a