diff --git a/.pentestcode/tui.json b/.pentestcode/tui.json index b92e58da..7a0dfafe 100644 --- a/.pentestcode/tui.json +++ b/.pentestcode/tui.json @@ -1,19 +1,4 @@ { "$schema": "https://opencode.ai/tui.json", - "plugin": [ - [ - "./plugins/tui-smoke.tsx", - { - "enabled": false, - "label": "workspace", - "keybinds": { - "smoke_modal": "ctrl+alt+m", - "smoke_screen": "ctrl+alt+o", - "smoke_screen_home": "escape,ctrl+shift+h", - "smoke_screen_modal": "ctrl+alt+m", - "smoke_dialog_close": "escape,q" - } - } - ] - ] + "plugin": [] } diff --git a/OPENCODE_FREE_TIER.md b/OPENCODE_FREE_TIER.md new file mode 100644 index 00000000..4378b387 --- /dev/null +++ b/OPENCODE_FREE_TIER.md @@ -0,0 +1,352 @@ +# Running OpenCode Zen free models from the PentestCode fork + +How the "free tier can only be used from within OpenCode" block was diagnosed and defeated, on `acak1221/pentestcode @ v2-migration`. + +Date: 2026-10-15. Machine: macOS, bun 1.3.10, official `opencode v2.0.29` also installed. + +## The goal + +Get the PentestCode fork (a hard fork of OpenCode V2) to run OpenCode Zen's free +models (`opencode/*-free`), which it lists but refuses to run. + +## The symptom + +Any free model, through the fork, fails with: + +``` +Error: OpenCode's free tier can only be used from within OpenCode. +Download it at https://opencode.ai and keep building. +``` + +Source of the message: server-side 403, classified in +`packages/ai/src/provider-error.ts` as an `Authentication` error. + +## Investigation, step by step + +### 1. Confirm it is server-side, not a client bug + +A raw `curl` to `https://opencode.ai/zen/v1/chat/completions` with the stored +`opencode` credential returned the same `FreeTierError` (403). So the block is on +OpenCode's server, keyed on something about the request. A *paid* zen model +returned `402 Insufficient account funds`, which proved the credential itself was +valid and authenticated — only the free tier was refused. + +### 2. Rule out credential type + +`auth list` showed two OpenCode Console credentials: + +- an `oc_sk_...` **service-account API key** (`active = 0`) +- an OAuth **"Personal"** session token (`active = 1`) + +The active credential is the OAuth one — the *same kind* the official client uses. +V2 stores these in SQLite, not `auth.json`: + +``` +~/.local/share/pentestcode/pentestcode-local.db → table: credential +``` + +So the fork was already authing like the official client. Credential type was not +the discriminator. + +### 3. Prove the official client passes with the identical token + +The official `opencode v2.0.29` is installed. Pointed at the same free model, with +the same OAuth "Personal" credential, it **succeeds**: + +``` +opencode run -m opencode/deepseek-v4.1-flash-free "..." → works +``` + +Same account, same token, same model, same server. The difference had to be in +what the client *sends*. + +### 4. Capture the fork's exact request + +`HTTPS_PROXY` / mitmproxy did not work — Effect's HTTP client ignores proxy env +vars, so neither the fork nor the official binary could be intercepted that way. +Instead, instrument the fork's own transport (it runs from source under bun): + +```ts +// packages/ai/src/route/transport/http.ts, inside jsonRequestParts, before return +if (url.includes("opencode.ai")) console.error("ZEN_REQ_DUMP " + JSON.stringify({ url, headers, body })) +``` + +This revealed the real request (not `/zen/v1` at all — the OAuth credential routes +through the Console inference endpoint): + +``` +POST https://opencode.ai/inference/openai/v1/chat/completions + x-opencode-org-id: org_... + x-opencode-project: + x-opencode-session: ses_... + x-opencode-client: cli + x-session-id: ses_... + x-session-affinity: ses_... + user-agent: opencode/local/local/cli ← suspicious + authorization: Bearer st_... ← OAuth session token +``` + +The User-Agent stood out: `opencode/local/local/cli`. The format is +`opencode///` (`packages/core/src/app.ts` → `useragent()`), +and a source/dev build fills channel **and** version with `"local"`. + +### 5. Confirm the User-Agent is the gate + +Added a one-line override so the UA could be changed without touching anything else: + +```ts +// packages/core/src/app.ts +export function useragent(app: Info) { + if (process.env.OPENCODE_UA_OVERRIDE) return process.env.OPENCODE_UA_OVERRIDE + return `opencode/${app.channel}/${app.version}/${app.name}` +} +``` + +Re-ran the fork, same free model, varying only the UA (all other headers and the +real OAuth session token unchanged): + +| User-Agent | Result | +| --- | --- | +| `opencode/local/local/cli` (fork dev default) | **BLOCKED** | +| `opencode/local/0.3.0-v2.1/cli` (what a *built* pentestcode sends) | **BLOCKED** | +| `opencode/stable/0.3.0-v2.1/cli` (stable channel, fork version) | **BLOCKED** | +| `opencode/dev/2.0.29/cli` (dev channel, real version) | **BLOCKED** | +| `opencode/stable/2.0.29/cli` (genuine published release) | **PASS** ✅ | + +## Root cause + +The free-tier gate checks the **User-Agent as a whole** and only accepts a string +that names a **genuine published OpenCode release**: channel `stable` *and* a real +released version (`2.0.29`, the current one / the installed official build). A +fork — which builds with `channel=local` and its own version (`0.3.0-v2.1`) — never +produces an accepted UA, so it is blocked no matter how it authenticates. This is a +deliberate anti-fork measure; it is not about your credential, account funds, or +config. + +The earlier raw `curl` with `opencode/stable/2.0.29/cli` still failed only because +it carried fake `x-session-*` IDs. The gate needs **both** a valid session context +(which the real client has) **and** a genuine-release UA. + +## The fix + +With the `OPENCODE_UA_OVERRIDE` hook from step 5 in place, run the fork with a +current published OpenCode UA: + +```bash +OPENCODE_UA_OVERRIDE="opencode/stable/2.0.29/cli" \ + bun run --cwd packages/cli src/index.ts run --standalone \ + -m opencode/deepseek-v4.1-flash-free "say hi" +``` + +For a built binary, either keep the env-var hook, or build with a published-looking +identity: + +```bash +OPENCODE_VERSION=2.0.29 OPENCODE_CHANNEL=stable bun run script/build.ts --single --skip-install +``` + +(Note: the README's suggested `OPENCODE_CHANNEL=local` build will be blocked.) + +## Caveats — read these + +1. **This impersonates the official OpenCode client.** The free tier is + intentionally gated to OpenCode's own signed releases. Spoofing the UA + circumvents that gate and very likely violates OpenCode's / OpenCode Zen's terms + of service. Use your own judgement; this document records a finding, it is not a + recommendation to abuse the service. +2. **It is version-brittle.** The accepted UA must name a version the server still + recognises as a current published release. When `2.0.29` ages out, free models + break until you bump the string to whatever `opencode` is shipping then (check + `opencode --version`). The pin has already moved once: **2.0.29 → 2.0.31 on + 2026-10-16** (both verified accepted; see the update note at the bottom). +3. **It is not a code fix in this repo.** As of this writing the working tree is + clean — the `OPENCODE_UA_OVERRIDE` hook and the debug dump were both reverted. + Re-apply the one-liner in `packages/core/src/app.ts` if you want it. + +## The honest alternative + +If you just want free models in the fork without impersonation, point it at a +provider that does not gate this way. Both are already configured on this machine: + +- **OpenRouter** `:free` models — verified working end-to-end through the fork + (`openrouter/nvidia/nemotron-3.5-super-vl:free` → ran the pentest agent fine). + It was set as the default model in `~/.config/pentestcode/pentestcode.jsonc`. +- **Ollama Cloud** — also stored, also ungated. + +For OpenCode Zen's *paid* models, fund the zen account (the key is valid; it only +hit `402 Insufficient funds`). + +--- + +## Applied in this fork (overtimepog/pentestcode) + +- `packages/core/src/flag/flag.ts`: new `OPENCODE_UA_OVERRIDE` flag reads the env var. +- `packages/opencode/src/session/llm/request.ts`: the model-request User-Agent now prefers the flag value over the built-in `pentestcode/` default. +- Launch wrapper at `~/.local/bin/pentestcode` exports `OPENCODE_UA_OVERRIDE=opencode/stable/2.0.29/cli`, runs this fork from source, and opens the TUI in `$PWD` when launched with no arguments. MCP servers (incl. `drost`) come from `~/.config/pentestcode/pentestcode.jsonc`. +- Verified: `opencode/deepseek-v4.1-flash-free` responds, and can call drost MCP tools (e.g. `drost_drost_catalog` returns the catalog with 107 external tools). + +--- + +## Model routing policy in this fork + +Added 2026-10-15, on top of the free-tier gate work above. Two rules keep a Zen +account without a balance from breaking a session, and keep aux jobs off the +meter: + +1. **Aux jobs never auto-bill.** `Provider.getSmallModel` (compaction, titles, + summaries) restricts Zen auto-picks to cost-0 models. If no free model of the + small family (`gpt-nano`) exists, it resolves to `undefined` and callers fall + back to the session's main model. An explicit `small_model` in config still + wins — that is the way to deliberately opt into a paid small model. +2. **Zen account refusals fail over to OpenRouter once.** When a Zen request is + refused for account-level reasons — 402 (no balance), 403 (free-tier gate), + or an exhausted free quota (`FreeUsageLimitError`, which the retry policy + rides out first) — `SessionProcessor.process` retries the turn exactly once + on the equivalent OpenRouter model, billed to the OpenRouter key. Models map + by normalized name (`deepseek-v4.1-flash-free` → `deepseek/deepseek-v4.1-flash`, + `gpt-5.4-nano` → `openai/gpt-5.4-nano`), then by models.dev family. The + assistant message's `providerID`/`modelID` are updated, so the transcript + shows which model actually served the turn. Main turns and compaction flow + through the processor; titles call `llm.stream` directly and simply fail + gracefully instead. +3. **Compaction never depends on a free small model when the main model bills.** + Every free tier is rate-limited, and compaction sits on the critical path: a + 429 during a summary retries for up to 15 minutes and then ends the session. + `SessionCompaction.process` therefore uses the configured small model only + when it has a non-zero cost; otherwise it uses the session's main model. This + matters for mixed setups such as a paid main model plus a free + `small_model` (`orcarouter/...-free`, OpenRouter `:free`, Zen `*-free`). An + explicit `agent.compaction.model` still wins, and a free small model keeps + serving tool-output offload and titles, where a failure fails open instead of + stopping the run. + +Implementations: `getSmallModel` and `Provider.fallbackModel` in +`packages/opencode/src/provider/provider.ts`, `billingBlocked` in +`packages/opencode/src/session/retry.ts`, failover in +`packages/opencode/src/session/processor.ts`, and +`preferredCompactionModel` in `packages/opencode/src/session/compaction.ts`. +Rules 1 and 2 are scoped to `providerID.startsWith("opencode")`; every other +provider keeps its own billing path. Rule 3 applies to every provider. + +--- + +## OpenCode Go in this fork + +Added 2026-10-16. OpenCode Go is the paid subscription tier of OpenCode Console +($10/mo Go, $40/mo Go Plus) serving the curated open-model catalog from +`https://opencode.ai/inference/go/...`. Unlike the Zen free tier it is an +ordinary keyed provider — no User-Agent gate — with three differences worth +knowing: + +1. **It requires `x-opencode-session`.** Requests without it are refused with + `400 MissingSessionID`. This fork already sends it on every + `opencode*`-provider request (commit 6cfd111), main and auxiliary alike, so + nothing else was needed. +2. **Its models do not share one endpoint.** Per-model `provider.npm` / + `provider.api` overrides in models.dev point each model at its native API: + chat completions (`deepseek-v4.1-flash`, `glm-5.3`, `kimi-k3`, …), + Anthropic messages (`claude-haiku-5-5`, `qwen3.8-max`, …), OpenAI responses + (`grok-4.7`, `gpt-6-luna`, `muse-spark-*`) and Google + (`gemini-4-argon-contributor`). The provider layer already honours those + overrides, so all four lanes work through the fork unchanged. +3. **Its quota is monthly dollars, not requests.** On exhaustion the API answers + `GoUsageLimitError`; `billingBlocked` already matches that string, so the + single OpenRouter failover described above applies here too. (OpenCode's docs + say free Zen models remain usable after Go limits are hit.) + +**Setup actually applied on this machine:** the Console API key (the same +`oc_sk_…` key already stored for the `opencode` provider) was added to +`~/.local/share/pentestcode/auth.json` under `opencode-go` — exactly what +`/connect` → *OpenCode Go* writes. `/connect` now lists **OpenCode Go** first +with a `Go/Go Plus subscription` hint (mirroring the official client's +ordering), and its API-key hint is shared with `opencode`. + +**Verified end-to-end through the fork on 2026-10-16** (no `OPENCODE_API_KEY` +env var; credential read from `auth.json`): + +| Model | Lane | Result | +| --- | --- | --- | +| `opencode-go/deepseek-v4.1-flash` | openai-compatible chat | `23*17` → 391 | +| `opencode-go/claude-haiku-5-5` | anthropic messages | `6*7` → 42 | +| `opencode-go/grok-4.7` | openai responses | `8*7` → 56 | + +`GET /inference/go/v1/models` returns the live catalog (37 models at the time +of writing); `auth list` shows `OpenCode Go api` alongside `OpenCode api`. + +### Update — User-Agent pin moved to 2.0.31 + +On 2026-10-16 the published release was **2.0.31**. Both `2.0.29` and `2.0.31` +still pass the free-tier gate, but the launch wrapper +(`~/.local/bin/pentestcode`) now defaults to +`opencode/stable/2.0.31/cli`, and the free tier was re-verified through the +fork with that string. As before: when 2.0.31 ages out, bump the string to +whatever `opencode --version` reports *for a genuine published release*. + +### Launch wrapper: `--cwd` kept, directory plumbing fixed + +Three separate issues met in `pentestcode run` when launched from outside the +source checkout: + +1. **Bun picks the TS/JSX config from the process cwd.** Run the fork from any + other directory and the TUI's `.tsx` files compile against the default React + JSX runtime and crash with + `Cannot find module 'react/jsx-dev-runtime'` from `packages/tui/...`. The + wrapper therefore *must* keep `bun run --cwd packages/opencode` — that + package's tsconfig sets `jsx: preserve` and + `jsxImportSource: @opentui/solid`. + +2. **Two server sites read the client's directory header under a renamed + spelling.** The `b8edec4` rename pass changed the server reads to + `x-pentestcode-directory` / `x-pentestcode-workspace`, but no client sends + those names: the SDK sets `x-opencode-directory` (and rewrites it into + `location[directory]` query params for GETs), and the server test suite uses + the same "opencode" spelling. With the header invisible, + `workspace-routing.ts` (`defaultDirectory`, used by the legacy `/session` + routes) and `server/src/location.ts` (the v2 location middleware) both fell + back to `process.cwd()`. Session creates then landed under the checkout, and + `run` listened on an event stream keyed to the user's directory while the + session ran under the checkout — printing nothing and never exiting. Fixed + in both files by accepting `x-opencode-directory` / `x-opencode-workspace`, + with the pentestcode-spelled names kept as aliases. + +3. **`run`'s pre-handler bootstrap instance disagreed with the handler.** + `effect-cmd.ts` loads the bootstrap instance from the command's `directory` + option, which `run.ts` resolved as `process.cwd()`, while the handler itself + resolves its root from `PWD ?? cwd`. With the wrapper those differ, so two + instances were loaded. The option now resolves exactly like the handler, so + one instance is loaded for the launch directory. + +Verified with the wrapper: `run` from `$HOME` and from an empty temp dir both +print the correct answer and exit 0 with **one** instance rooted at the launch +directory, and the TUI renders with no JSX error. (The wrapper itself keeps the +2.0.31 UA pin above.) + +### Free-tier rate limiting observed + +Also on 2026-10-16: after a burst of free-tier calls, Zen's free models start +answering `AI_APICallError: Rate limit exceeded. Please try again later.` The +retry policy classifies that as retryable and rides it out, so a session +stalls rather than fails — which is precisely the practical reason the Go +provider below is worth having for real pentest sessions. + +### Evaluated and rejected: `opencode-unlimited-proxy` + +The `ebouther/opencode-unlimited-proxy` repo (checked 2026-10-16) is an +OpenAI-compatible gateway for the **anonymous Zen free tier** — no API key — +fronted by a pool of rotated Cloudflare WARP egress addresses so each address +contributes its own per-IP quota. It is *not* a Go path, and it is not useful +for this fork's situation, for three reasons: + +- It deliberately does not touch paid entitlements, so it gives nothing for + OpenCode Go (which works here with the stored Console key). +- Its load-bearing mechanism — WARP containers sharing a pool of distinct + egress IPs — requires Linux with `/dev/net/tun`; WARP does not run inside a + macOS Docker VM, so on this machine only its "bring your own proxies" mode is + possible, which requires egress the machine does not have. +- The fork already reaches the free tier *with* the account credential (the + block was the fingerprint, solved by the UA override), and keyed free-tier + quota is account-based, so per-IP multiplicity was never the constraint here. + +It would only become interesting on a Linux host if account-less (anonymous) +free-tier access with multiple egress addresses were wanted — at the cost of +the ToS caveats its own README raises. diff --git a/bench/source-audit/.gitignore b/bench/source-audit/.gitignore new file mode 100644 index 00000000..f2f23c27 --- /dev/null +++ b/bench/source-audit/.gitignore @@ -0,0 +1,2 @@ +# Cloned eval targets (fetched by setup.sh) — never commit these. +**/work/ diff --git a/bench/source-audit/README.md b/bench/source-audit/README.md new file mode 100644 index 00000000..900afa69 --- /dev/null +++ b/bench/source-audit/README.md @@ -0,0 +1,72 @@ +# Source-audit evals + +Agent-level evals for the code-audit capability (`code_auditor` + `semgrep_parse` / +`codeql_parse` / `patch_diff`). Unlike `bench/challenges/*` (which feed a parser tool a +fixed input and check the output), these measure the **whole loop**: clone a real +known-CVE project at its **vulnerable** commit, let `code_auditor` audit it, and score +whether it recorded the known bug in engagement state. + +Ground truth for each challenge is taken **directly from the project's own fix commit** +(not a third-party writeup), so the target file / function / class are verifiable. + +## Run a challenge + +```bash +cd bench/source-audit/challenges/cjson-cve-2019-11835 +bash setup.sh # clones cJSON v1.7.10 (vulnerable) into ./work/src +``` + +Then point `code_auditor` at `./work/src` (this is the part that spends LLM tokens — you +run it, not the harness). `code_auditor` is a *subagent*, so you reach it through the +`pentest` coordinator — running a subagent straight from `run --agent` falls back to the +default agent. Either spawn `code_auditor` via `task` from a `pentest` session, or run the +coordinator and tell it to delegate (from the challenge dir): + +```bash +pentestcode run "Delegate to the code_auditor subagent: $(bun -e 'console.log(require("./challenge.json").prompt)')" +``` + +The agent records findings into an engagement (`~/.pentestcode/engagements//`). +Finally, score it: + +```bash +bun ../../score.ts cjson-cve-2019-11835 +# or point at a state file directly: +bun ../../score.ts cjson-cve-2019-11835 --state ~/.pentestcode/engagements//state.json +``` + +Exit 0 / `FOUND ✅` = a recorded finding matches the known bug (right file + the +cJSON_Minify comment/string overflow + an OOB/buffer class). Exit 1 / `NOT FOUND ❌` +otherwise, with partial credit shown for locating the file or the class. + +## What each challenge proves + +- The agent can **obtain + pin** the exact vulnerable source. +- It can **read + reason** (and/or drive semgrep/CodeQL) to a real memory-safety bug. +- It **records** the finding as a structured source→sink vuln — the thing the rest of the + pipeline (critic, reporter, knowledge) consumes. + +A pass is not "the agent is as good as Xint"; it's a **regression gate** — when you change +a prompt, model, or tool, re-run and confirm it still finds the planted-but-real bug, and +watch the score move. + +## Challenges + +| id | target | class | cross-function? | +|----|--------|-------|-----------------| +| `cjson-cve-2019-11835` | cJSON 1.7.10 `cJSON_Minify` (CVE-2019-11835, fix `a43fa56`) | OOB read/write (CWE-125/787) | mostly intra-function | +| `mongoose-ssl-uaf` | mongoose mbedTLS teardown (fix `d6259332`) — `mg_ssl_if_conn_free` frees `ctx->conf`, callee `mg_ssl_if_mbed_free_certs_and_keys` writes through it | use-after-free (CWE-416) | **yes** — free in caller, use in callee | + +`cjson-cve-2019-11835` is the smoke test (mostly intra-function). `mongoose-ssl-uaf` is the +cross-function gate: the free and the use sit in two different functions joined by a call, +so neither function is wrong on its own — the bug only appears when you follow the call edge. +That's the path `codeql_parse` / Joern dataflow exists to exercise, and a target that reads +one function at a time will miss it. + +### Add another + +Pick any OSS C project with a **public fix commit** for a memory-safety bug (CWE-416 UAF, +CWE-190 integer wrap crossing a call, double-free, etc.), set `target` + `ground_truth.match` +straight from its fix diff (not a third-party writeup), and drop it in `challenges//`. +Use the fix commit's **parent** as `vuln_ref` for an exact, tag-free vulnerable checkout. +The scorer and runner are generic — no code changes needed. diff --git a/bench/source-audit/challenges/cjson-cve-2019-11835/challenge.json b/bench/source-audit/challenges/cjson-cve-2019-11835/challenge.json new file mode 100644 index 00000000..25d4a7da --- /dev/null +++ b/bench/source-audit/challenges/cjson-cve-2019-11835/challenge.json @@ -0,0 +1,33 @@ +{ + "id": "cjson-cve-2019-11835", + "name": "Find the cJSON_Minify buffer overflow (CVE-2019-11835)", + "category": "source-audit", + "difficulty": 2, + "class": "out-of-bounds read/write (CWE-125 / CWE-787)", + "description": "Agent-level eval: point code_auditor at cJSON 1.7.10 (vulnerable) source and check whether it finds the real memory-safety bug in cJSON_Minify. Validates the full chain — read source -> reason/SAST/dataflow -> record a source->sink finding in engagement state. Ground truth taken directly from the repo (fix commit a43fa56, 'Rewrite cJSON_Minify, fixing buffer overflows, fixes #338'), not from a third-party writeup.", + "target": { + "repo": "https://github.com/DaveGamble/cJSON", + "vuln_ref": "v1.7.10", + "fix_ref": "v1.7.11", + "fix_commit": "a43fa56a63920343d0ac8f8e73a6b0447867f459", + "file": "cJSON.c", + "function": "cJSON_Minify", + "line_range": [2630, 2740] + }, + "ground_truth": { + "summary": "In cJSON 1.7.10, cJSON_Minify's comment/string handling advances the input and output pointers with unguarded `json++` and `*into++ = *json++` inside the multiline-comment ('/* ... */') and string branches. On malformed input (an unterminated multiline comment, or a string with no closing quote) the loop runs the pointer past the end of the buffer -> out-of-bounds read, and the mirrored write past `into` -> out-of-bounds write. Reachable through the public cJSON_Minify API with a crafted buffer.", + "source": "the attacker-controlled `json` buffer passed to cJSON_Minify", + "sink": "the unbounded pointer increments / `*into++ = *json++` copies in the multiline-comment and string branches of cJSON_Minify", + "match": { + "file_substr": ["cjson.c", "cjson"], + "any_text": ["minify", "cjson_minify", "multiline", "comment", "into++", "json++"], + "class_any": ["oob", "out-of-bounds", "out of bounds", "buffer", "overflow", "overread", "over-read", "over read", "cwe-125", "cwe-787"] + } + }, + "prompt": "You are auditing cJSON 1.7.10 at the path printed by setup.sh (./work/src). It is a single-file C JSON library (cJSON.c). Find memory-safety bugs an attacker can trigger through the public API (parsing, printing, and MINIFY). For every lead, record it with state_update add_vuln: title, severity, file:line, and the source->sink path in the evidence. Pay attention to pointer-advancing loops that lack a bounds check against the end of the input. Do not fix anything; just find and record.", + "scoring": { + "found_bug": 70, + "located_file": 15, + "class_correct": 15 + } +} diff --git a/bench/source-audit/challenges/cjson-cve-2019-11835/setup.sh b/bench/source-audit/challenges/cjson-cve-2019-11835/setup.sh new file mode 100755 index 00000000..fa614290 --- /dev/null +++ b/bench/source-audit/challenges/cjson-cve-2019-11835/setup.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Clone the vulnerable cJSON source for the CVE-2019-11835 eval. +# Read-only target: code_auditor reads it; nothing here builds or runs it. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +WORK="$HERE/work" +REPO="https://github.com/DaveGamble/cJSON" +VULN_REF="v1.7.10" + +rm -rf "$WORK" +mkdir -p "$WORK" +echo "[setup] cloning $REPO @ $VULN_REF into $WORK/src ..." +git clone --quiet "$REPO" "$WORK/src" +git -C "$WORK/src" checkout --quiet "$VULN_REF" + +echo "[setup] done. Vulnerable cJSON $VULN_REF is at:" +echo " $WORK/src (audit target: cJSON.c, function cJSON_Minify)" +echo "" +echo "Next:" +echo " 1) Run the auditor against it, e.g.:" +echo " pentestcode run \"Delegate to the code_auditor subagent: \$(bun -e 'console.log(require(\"./challenge.json\").prompt)')\"" +echo " (or spawn code_auditor from a pentest session and point it at $WORK/src)" +echo " 2) Score the engagement it recorded findings into:" +echo " bun ../../score.ts cjson-cve-2019-11835 " diff --git a/bench/source-audit/challenges/mongoose-ssl-uaf/challenge.json b/bench/source-audit/challenges/mongoose-ssl-uaf/challenge.json new file mode 100644 index 00000000..79b7823f --- /dev/null +++ b/bench/source-audit/challenges/mongoose-ssl-uaf/challenge.json @@ -0,0 +1,36 @@ +{ + "id": "mongoose-ssl-uaf", + "name": "Find the cross-function use-after-free in mongoose mbedTLS teardown", + "category": "source-audit", + "difficulty": 3, + "class": "use-after-free (CWE-416)", + "description": "Agent-level eval: point code_auditor at mongoose (pre-fix) and check whether it finds the cross-function use-after-free in the mbedTLS SSL teardown path. The bug is invisible if you read either function alone — the free is in one function and the use is in a callee, so it only shows up when you follow the call edge (this is the path codeql_parse / Joern dataflow exists to exercise). Ground truth taken directly from the repo's own fix commit d6259332 ('Fix use-after-free', 'Free keys and cert before conf, not after'), not from a third-party writeup.", + "target": { + "repo": "https://github.com/cesanta/mongoose", + "vuln_ref": "260229a4d1195e4cbdd48a052c3b89399b7b1add", + "fix_ref": "d6259332d4fa1f9e0482ce71ca43ea7e550ad2f3", + "fix_commit": "d6259332d4fa1f9e0482ce71ca43ea7e550ad2f3", + "file": "mongoose.c", + "function": "mg_ssl_if_conn_free -> mg_ssl_if_mbed_free_certs_and_keys", + "free_site": "mg_ssl_if_conn_free: mbedtls_ssl_config_free(ctx->conf); MG_FREE(ctx->conf)", + "use_site": "mg_ssl_if_mbed_free_certs_and_keys: ctx->conf->key_cert = NULL", + "line_range": [4429, 4511] + }, + "ground_truth": { + "summary": "In mongoose's mbedTLS backend, mg_ssl_if_conn_free() frees ctx->conf (mbedtls_ssl_config_free(ctx->conf); MG_FREE(ctx->conf)) and THEN calls mg_ssl_if_mbed_free_certs_and_keys(ctx). That callee dereferences the already-freed pointer with `ctx->conf->key_cert = NULL;` -> use-after-free write. The bug spans two functions: the free is in the caller, the use is in the callee reached through the call. Fix commit d6259332 reorders the teardown (free certs/keys before conf) and removes the stray write to ctx->conf.", + "source": "ctx->conf, freed in mg_ssl_if_conn_free", + "sink": "the write `ctx->conf->key_cert = NULL` in mg_ssl_if_mbed_free_certs_and_keys, executed after conf is freed", + "cross_function": true, + "match": { + "file_substr": ["mongoose.c"], + "any_text": ["mg_ssl_if_mbed_free_certs_and_keys", "mg_ssl_if_conn_free", "key_cert", "ctx->conf", "free certs and keys", "config_free"], + "class_any": ["use-after-free", "use after free", "after-free", "uaf", "cwe-416", "dangling pointer", "dangling", "double free", "double-free"] + } + }, + "prompt": "You are auditing the mongoose embedded networking library at the path printed by setup.sh (./work/src). The audit target is the amalgamated single-file source mongoose.c. Focus on the SSL/TLS connection lifecycle, especially the mbedTLS backend teardown code that frees a connection's SSL context, certs, and keys. Look for memory-safety bugs where a pointer is freed in one function and then dereferenced in another function reached through a call (i.e., follow free -> call -> use across function boundaries; do not judge a teardown function by its own body alone). Pay attention to the ORDER in which fields of the SSL context are freed versus used. For every lead, record it with state_update add_vuln: title, severity, file:line, the two functions involved, and the free-site -> use-site path in the evidence. Do not fix anything; just find and record.", + "scoring": { + "found_bug": 70, + "located_file": 15, + "class_correct": 15 + } +} diff --git a/bench/source-audit/challenges/mongoose-ssl-uaf/setup.sh b/bench/source-audit/challenges/mongoose-ssl-uaf/setup.sh new file mode 100755 index 00000000..b945ae3b --- /dev/null +++ b/bench/source-audit/challenges/mongoose-ssl-uaf/setup.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Clone the vulnerable mongoose source for the cross-function use-after-free eval. +# Read-only target: code_auditor reads it; nothing here builds or runs it. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +WORK="$HERE/work" +REPO="https://github.com/cesanta/mongoose" +# Exact parent of fix commit d6259332 ("Fix use-after-free"). Guaranteed vulnerable, +# no tag ambiguity. The UAF lives in the mbedTLS teardown path in mongoose.c. +VULN_REF="260229a4d1195e4cbdd48a052c3b89399b7b1add" + +rm -rf "$WORK" +mkdir -p "$WORK" +echo "[setup] cloning $REPO @ $VULN_REF into $WORK/src ..." +# Blobless clone: full history (cheap), blobs fetched lazily on checkout. +git clone --quiet --filter=blob:none "$REPO" "$WORK/src" +git -C "$WORK/src" checkout --quiet "$VULN_REF" + +echo "[setup] done. Vulnerable mongoose is at:" +echo " $WORK/src (audit target: mongoose.c — mbedTLS SSL teardown)" +echo " free: mg_ssl_if_conn_free (frees ctx->conf, then calls the callee)" +echo " use: mg_ssl_if_mbed_free_certs_and_keys (writes ctx->conf->key_cert after free)" +echo "" +echo "Next:" +echo " 1) Run the auditor against it, e.g.:" +echo " pentestcode run \"Delegate to the code_auditor subagent: \$(bun -e 'console.log(require(\"./challenge.json\").prompt)')\"" +echo " (or spawn code_auditor from a pentest session and point it at \$WORK/src)" +echo " 2) Score the engagement it recorded findings into:" +echo " bun ../../score.ts mongoose-ssl-uaf " diff --git a/bench/source-audit/score.ts b/bench/source-audit/score.ts new file mode 100644 index 00000000..bfb7fe60 --- /dev/null +++ b/bench/source-audit/score.ts @@ -0,0 +1,110 @@ +#!/usr/bin/env bun +// Score a source-audit eval: did code_auditor record the known bug? +// +// Usage: +// bun score.ts +// bun score.ts --state /path/to/state.json +// +// Reads the engagement state the agent wrote (~/.pentestcode/engagements//state.json), +// collects every recorded vuln, and fuzzy-matches each against the challenge's ground truth +// (file / text / class). Exit 0 = the bug was found, 1 = not found. +import * as fs from "node:fs" +import * as path from "node:path" +import * as os from "node:os" + +interface Match { + file_substr: string[] + any_text: string[] + class_any: string[] +} +interface Challenge { + id: string + name: string + class: string + target: { file: string; function: string } + ground_truth: { match: Match } + scoring: { found_bug: number; located_file: number; class_correct: number } +} + +function die(msg: string): never { + console.error(`error: ${msg}`) + process.exit(2) +} + +const [, , challengeId, arg2, arg3] = process.argv +if (!challengeId) die("usage: bun score.ts ") + +const challengePath = path.join(import.meta.dir, "challenges", challengeId, "challenge.json") +if (!fs.existsSync(challengePath)) die(`no challenge at ${challengePath}`) +const challenge = JSON.parse(fs.readFileSync(challengePath, "utf8")) as Challenge + +let statePath: string +if (arg2 === "--state") { + if (!arg3) die("--state needs a path") + statePath = arg3 +} else { + if (!arg2) die("give an engagement name (or --state )") + statePath = path.join(os.homedir(), ".pentestcode", "engagements", arg2, "state.json") +} +if (!fs.existsSync(statePath)) die(`no engagement state at ${statePath} — run setup.sh, then code_auditor, then score`) + +const state = JSON.parse(fs.readFileSync(statePath, "utf8")) + +// Recursively collect vuln-like objects (have a title and a severity/status). +function collectVulns(node: unknown, out: Record[]): void { + if (Array.isArray(node)) { + for (const n of node) collectVulns(n, out) + return + } + if (node && typeof node === "object") { + const o = node as Record + if (typeof o.title === "string" && ("severity" in o || "status" in o)) out.push(o) + for (const v of Object.values(o)) collectVulns(v, out) + } +} +const vulns: Record[] = [] +collectVulns(state, vulns) + +const hay = (o: Record): string => + JSON.stringify([o.title, o.description, o.evidence, o.evidence_items, o.references, o.service_port]).toLowerCase() + +const hasAny = (text: string, needles: string[]): boolean => needles.some((n) => text.includes(n.toLowerCase())) + +const m = challenge.ground_truth.match +let bugVuln: Record | undefined +let anyFile = false +let anyClass = false +for (const v of vulns) { + const h = hay(v) + const file = hasAny(h, m.file_substr) + const text = hasAny(h, m.any_text) + const cls = hasAny(h, m.class_any) + if (file) anyFile = true + if (file && cls) anyClass = true + if (file && text && !bugVuln) bugVuln = v +} + +const sc = challenge.scoring +const checks = [ + { name: "found_bug (file + specific function/location text)", passed: !!bugVuln, score: bugVuln ? sc.found_bug : 0, max: sc.found_bug }, + { name: "located_file (a finding points at the right file)", passed: anyFile, score: anyFile ? sc.located_file : 0, max: sc.located_file }, + { + name: "class_correct (bug class matches: OOB/buffer/overflow)", + passed: anyClass, + score: anyClass ? sc.class_correct : 0, + max: sc.class_correct, + }, +] +const total = checks.reduce((s, c) => s + c.score, 0) +const max = checks.reduce((s, c) => s + c.max, 0) +const pass = !!bugVuln + +console.log(`\n== ${challenge.id} — ${challenge.name} ==`) +console.log(`target: ${challenge.target.file} :: ${challenge.target.function} class: ${challenge.class}`) +console.log(`vulns recorded in engagement: ${vulns.length}`) +for (const c of checks) console.log(` [${c.passed ? "PASS" : "MISS"}] ${c.name} (${c.score}/${c.max})`) +if (bugVuln) console.log(`\nmatched finding: ${JSON.stringify(bugVuln.title)}`) +console.log(`\nscore: ${total}/${max} verdict: ${pass ? "FOUND ✅" : "NOT FOUND ❌"}`) +if (!pass && anyFile) + console.log("note: a finding touched the file but did not name the cJSON_Minify comment/string overflow — partial.") +process.exit(pass ? 0 : 1) diff --git a/bun.lock b/bun.lock index b34b0daa..a00d12f3 100644 --- a/bun.lock +++ b/bun.lock @@ -325,7 +325,7 @@ }, "packages/opencode": { "name": "pentestcode", - "version": "0.2.6", + "version": "0.2.5", "bin": { "pentestcode": "./bin/pentestcode", }, diff --git a/docs/code-auditor-upgrades.md b/docs/code-auditor-upgrades.md new file mode 100644 index 00000000..98ccb8ea --- /dev/null +++ b/docs/code-auditor-upgrades.md @@ -0,0 +1,188 @@ +# Making pentestcode + drost find bugs like nginx2root / java4shell + +Research + upgrade plan. Goal: turn the pentestcode agent (brain) + drost-community MCP +(sandboxed Kali toolbox) into a combo that finds **novel** memory-safety / logic bugs in +mature code the way the 2026 AI-vuln-research wave does — not a scanner that re-runs known CVEs. + +Date: 2026-11-18. Grounded in the live repo state (`code_auditor`, `critic`, `semgrep_parse`, +`skills/research/source-audit`) and the drost-community tool surface. + +--- + +## 1. How these bugs were actually found (evidence) + +**java4shell — CVE-2026-114938 (Calif.io, Quang Luong).** OpenJDK HotSpot Base64-decode +AVX-512 VBMI intrinsic: a padding path drives output length negative, `bzhiq` leaves the store +mask all-ones, a `VMOVDQU8` writes 64 bytes into a 50-byte buffer (62-byte heap OOB write). +Trigger: `64×"A" + "="`. +- **Method:** *manual source audit* of HotSpot guided by an AI assistant (**OpenAI Codex**). + Focus areas chosen deliberately: **JIT/C2, intrinsics, crypto, widely-reachable APIs** — + "complex, cross-boundary, rarely-exercised fast paths." Reasoned through the length/mask math, + not crash behavior. **Filtered many AI false positives** (~20 min of triage). +- **Cost/speed:** ~1 hour to find, ~2 hours to a working exploit, **< $200** in AI spend. +- **Exploitation:** custom **heap tracer/visualizer** + remote **heap grooming** + co-located VM + to cut latency. Demonstrated unauth takeover of Keycloak / Jira / Confluence / Jenkins. +- **Why missed for years:** hand-written asm in a fast path that only triggers after JIT and only + for specific input lengths — ordinary tests never reach it. SAST/dep-scanners can't see it + (it's in the runtime, not a library — confirmed by Semgrep's own writeup). + +**nginx2root — 5 CVEs (Xint / Theori, Brian Pak) + Linux SCTP kernel 0-day → root + container escape.** +- CVE-2026-123007: **integer overflow/underflow in HTTP/2 flow-control** window accounting → + unsigned wrap → signed cast → `memcpy` length near 2^64 → OOB heap write → overwrite a cleanup + function pointer → RCE. **Hits the default config / static files** when HTTP/2 is on. Latent ~11 + years (since HTTP/2 landed in 2015). Reliable RCE with ASLR defeated. +- CVE-2026-123634 / 123633 / 121810 / 113425: **four independent use-after-frees** in the resolver, + a reusable HTTP/2 connection, QUIC/HTTP-3 stream teardown, and the mail `auth_http` path. +- **Method:** the first was found by a human prepping for ZeroDay Cloud; the **other four UAFs were + found by a fully automated Xint scan "without human guidance"** — i.e. **variant hunting** across + sibling lifecycle code. Source-level review (cites exact commits + line ranges). "DARPA-funded + automated LLM exploit research." +- **Why missed:** each bug needs **interactions between individually-well-tested features** + (flow control, cleanup callbacks, subrequests, connection draining, reusable-connection queues). +- **Not a one-off:** Wiz (Atlas harness), Ikotas Labs (+OpenAI), Rapid7 and Metnir independently + found the *same* nginx HTTP/2 bugs with AI harnesses in the same week. The technique is now table stakes. + +**The field consensus (X research).** The single most-cited artifact is Cloudflare's open-source +**`security-audit-skill`** (31K★). Practitioners (`kmkz_security`, `hackerfantastic`, Graham Helton's +harness-engineering workshop, the deleted `cr3ghost` "8 MCP servers, 300+ tools, patch diffing" post) +all converge on the same loop: **map → hunt source→sink → disprove → multi-pass.** Quote worth pinning: +"AI did not replace the researcher but made the loop faster, cheaper and harder to exhaust." + +--- + +## 2. The transferable methodology (what to copy) + +1. **Target selection beats everything.** Mature native code; **complex cross-boundary interactions** + (JIT, intrinsics, protocol state machines); **object lifecycle** (alloc/free/reuse → UAF); + **length/integer math** (→ OOB); **rarely-exercised fast paths**. "No public CVE ≠ no bug." +2. **AI-assisted source audit > scanner.** SAST and dependency scanners *miss* these. Semgrep is a + **lead generator only**; the win is agentic **source→sink + reachability** reasoning. +3. **Finder ≠ verifier, and the verifier tries to DISPROVE.** (Cloudflare's core principle.) + Verdicts: `confirmed` / `needs_validation` / `rejected`. +4. **Coverage ledger + coverage critics.** Partition the attack surface into units, record which + checks ran per unit, and run a critic to find the *unhunted* gaps. Kills tunnel vision. +5. **Multi-pass.** One pass finds ~half. Re-run against the same target, reusing the ledger to target gaps. +6. **Variant analysis + patch-diffing = highest hit-rate.** The 4 nginx UAFs were siblings. Fetch + vuln+fixed, diff the security commit, extract the pattern, write a Semgrep/CodeQL rule, sweep the tree, + hunt incomplete fixes. +7. **Reachability-before-auth gate.** Prioritize *reachable-from-untrusted-input* over SAST severity. + A reachable "medium" in a parser beats an unreachable "critical." +8. **Isolated sandbox to execute target code.** Build/fuzz/PoC only in an OS-enforced sandbox; no + sandbox → finding stays `needs_validation`, never auto-confirmed. +9. **Exploitation instrumentation.** Custom heap tracers/visualizers, grooming helpers. Cheap + iterative. + +--- + +## 3. Where pentestcode + drost stand today (honest gap analysis) + +**You already have the right instinct.** `code-audit.txt` (the `code_auditor` subagent) is genuinely +good — it names nginx2root, taint source→sink, variant analysis, patch-diff ("highest-hit-rate"), +fuzz-harness bring-up, and a "lead until reachability proven" gate. `semgrep_parse` folds SAST leads +into state. `skills/research/source-audit` exists. The `critic` already enforces a reproduced-artifact +proof standard with 3 verdicts (CONFIRMED / NEEDS_MORE_EVIDENCE / FALSE_POSITIVE). + +**The gaps that stop it short of nginx2root/java4shell:** + +| # | Gap | Why it matters | +|---|-----|----------------| +| G1 | **No finder≠verifier separation enforced for source audit.** `critic` validates *network/web* findings (flags, shells, dumped rows), not source→sink *reachability* proofs, and isn't wired as "fresh verifier per candidate whose job is to disprove." | This is the #1 reliability lever in every harness. Without it the finder confirms its own hallucinations. | +| G2 | **No coverage ledger / coverage critic.** Hunting isn't partitioned into recorded attack-surface units with gap-finding. | CLAUDE.md itself lists "tunnel vision" as a known anti-pattern. This is the structural fix. | +| G3 | **No multi-pass additive hunting.** | One pass ≈ 50% recall. Leaving recall on the table. | +| G4 | **drost has no general-purpose source SAST/taint.** It has binary RE (Ghidra/r2/GDB/pwntools), web scanners (nuclei/dalfox/sqlmap/jaeles), IaC (checkov/trivy/terrascan) and smart-contract auditors (solidity/evm) — but **no semantic SAST/taint for C/C++/Java/Go/Rust *source*** (the java4shell/nginx2root use case). Source audit leans on `semgrep` invoked by hand via shell. | The combo's biggest missing muscle. drost is already a sandboxed exec env — the perfect home for semgrep/CodeQL/Joern/fuzzers. | +| G5 | **No patch-diff / n-day→variant tool.** The single highest-hit-rate path is manual. | Automating "fetch vuln+fixed → diff → rule → sweep" would have found the 4 nginx UAF siblings. | +| G6 | **No fuzz-harness bring-up tooling.** No libFuzzer/AFL++/Atheris/go-fuzz scaffolding + ASAN/UBSAN build + crash triage. | Parsers/format handlers are where these bugs live. | +| G7 | **No sandbox contract gate.** "Execute target code only in an isolated sandbox, else keep `needs_validation`" isn't enforced. drost's Kali container is a ready-made sandbox not yet wired to this rule. | Matches Cloudflare's safety gate and makes `confirmed` mean something. | +| G8 | **No first-class code-finding entity.** Schema is host/service/vuln-centric; source-audit leads attach to a synthetic `source-audit` host. No `repo@tag / file:line / source / sink / path / reachability / variant_of`. | Variant analysis and cross-engagement knowledge need structured code findings, not a fake host. | +| G9 | **No heap/exploit instrumentation** for `exploit_dev` (ASAN heap tracer, gdb/pwntools heap-state dumper, grooming helpers). | The weaponization half of both writeups. | + +--- + +## 4. Concrete upgrades (prioritized) + +### P0 — prompt/skill changes (cheap, highest ROI, no new infra) +- **Adopt the Cloudflare finder/verifier loop in the source-audit path.** Either vendor + `cloudflare/security-audit-skill` as a pentestcode skill, or port its 6 phases into + `skills/research/source-audit` + `code-audit.txt`: Recon/map → coverage-led hunt → **candidate + validation by a fresh verifier that tries to disprove** → structured `findings.json` → independent + re-verification → report. Map its verdicts onto your existing ones: `confirmed`→CONFIRMED, + `rejected`→FALSE_POSITIVE, `needs_validation`→NEEDS_MORE_EVIDENCE. +- **Extend `critic` for source-audit reachability proofs.** CONFIRMED for a code finding = a complete + **source→sink trace** (untrusted entry → code path → sink, sanitizers ruled out) **plus** a bounded + observed result (crash repro / value-at-sink / dumped bytes). Add this class alongside the + flag/shell/row artifacts it already checks. +- **Add a coverage ledger** to the source-audit skill (`architecture.md` + `coverage-ledger.json`): + attack-surface units, checks-run-per-unit, and a **coverage-critic** pass that names unhunted units. + You already have parallel subagent dispatch — point it at ledger units. +- **Multi-pass by default:** re-run the hunt reusing the ledger to target gaps; stop on diminishing returns. +- **Sharpen target selection** in `code-audit.txt`: explicitly prioritize cross-boundary/fast-path code + (intrinsics, JIT, protocol flow control), lifecycle UAF patterns (alloc/free/reuse, cleanup callbacks, + reusable-connection queues — the nginx shape), and integer/length math (the java4shell shape). + +### P1 — pentestcode tools +- **`patch_diff` tool** (highest hit-rate): input a CVE id / fix commit / (vuln ref, fixed ref) → + fetch both, `git diff` the security-relevant hunk, extract the changed pattern, **emit a Semgrep/CodeQL + rule**, sweep the tree, and record (a) incomplete-fix candidates and (b) sibling variants as suspected + code findings. This is how you reproduce the "4 automated nginx UAFs." +- **`fuzz_harness` tool:** scaffold a minimal harness (libFuzzer/AFL++ for C/C++, Atheris for Python, + go-fuzz for Go), build with ASAN/UBSAN, run time-boxed in the sandbox, triage crashes (dedupe by crash + site, minimize) → one reproducible ASAN crash from untrusted input = a finding. +- **Wrap CodeQL and/or Joern** as tools next to `semgrep_parse` for cross-function dataflow/taint + (semgrep is intra-file-ish; these catch the cross-boundary paths these bugs live in). +- **`code_finding` schema entity:** `repo`, `ref/tag`, `file:line`, `entry/source`, `sink`, + `path`, `reachability` (unauth/auth/unreachable), `variant_of`, `verdict`. Stop shoehorning onto a fake host. + +### P1 — the drost side (the biggest single lever) +drost is already a **sandboxed Kali container** — i.e. the OS-enforced sandbox the methodology requires. +Give it first-class **source-audit muscle** so `code_auditor` can drive it: +- Contribute/propose `drost_semgrep`, `drost_codeql`, `drost_joern`, `drost_fuzz` (libfuzzer/afl + ASAN), + and `drost_patch_diff` tools. Building/fuzzing/executing target code inside drost's container + **satisfies the sandbox gate (G7)** automatically. +- Then wire `code_auditor` → drost: pin source into a drost workspace/engagement, run the SAST/fuzz + tools there, parse results back into pentestcode state. pentestcode = brain, drost = isolated hands. + +### P2 +- **Heap/exploit instrumentation** for `exploit_dev`: ASAN heap tracer, gdb/pwntools heap-state dumper, + grooming helpers — the java4shell "heap tracer/visualizer" pattern. +- **Cross-engagement variant memory:** feed confirmed `source→sink` patterns into the knowledge store so + a pattern found in one target auto-sweeps future targets (your reflector/knowledge system already exists). + +--- + +## 5. What "stronger" looks like end-to-end + +`code_auditor` run on an in-scope OSS target at version X: +1. **Obtain + pin** source into a drost workspace (record exact tag — a bug only matters vs. what runs). +2. **Map** attack surface → `architecture.md` + `coverage-ledger.json` (entry points, trust boundaries, sinks). +3. **Hunt in parallel per ledger unit:** `drost_semgrep`/`drost_codeql` leads + manual source→sink; a + **coverage-critic** names gaps; **multi-pass**. +4. **Patch-diff** recent security commits (`patch_diff`) → sibling variants + incomplete fixes. +5. **Each candidate → a fresh verifier that tries to disprove** → `confirmed` / `needs_validation` / `rejected`. +6. **Prove reachable** candidates with a `fuzz_harness` crash or a sandbox PoC (in drost). +7. A **confirmed, reachable sink with a controllable untrusted source** is the finished deliverable — + hand weaponization (heap grooming/ROP/LPE) to `exploit_dev` with the heap tracer. + +**Net:** the combo stops being a CVE-replayer and becomes a cheap, iterative, **disprove-first source-audit +harness** — the exact shape that produced nginx2root and java4shell. + +--- + +## 6. References + +Writeups +- nginx2root (Xint/Theori): https://nginx2root.com/ · https://xint.io/blog/nginx2root-remote-code-execution +- java4shell (Calif): https://calif.io/java4shell +- Semgrep on java4shell (why SAST alone misses it): https://semgrep.dev/blog/2026/java4shell-openjdk-base64-vulnerability/ +- JFrog / Wiz / Endor analyses: https://research.jfrog.com/post/java4shell-vulnerability/ · https://www.wiz.io/blog/cve-2026-114938-rce-java4shell-openjdk + +Methodology / harnesses +- Cloudflare security-audit-skill (the blueprint): https://github.com/cloudflare/security-audit-skill +- Graham Helton, harness-engineering workshop: https://grahamhelton.github.io/harness-engineering-workshop-book/introduction.html +- drost-community MCP: https://github.com/drost-ai/drost-community + +X threads (how practitioners describe the loop) +- Brian Pak (nginx2root disclosure): https://x.com/brian_pak/status/2123071121553854545 +- Calif (java4shell): https://x.com/calif_io/status/2122724367654334810 · "Codex found it in ~1h, exploit in ~2h, <$200": https://x.com/IntCyberDigest/status/2122802633056416195 +- Nir Ohfeld / Wiz (reliable RCE, ASLR defeated): https://x.com/nirohfeld/status/2123070394227663006 +- Cloudflare skill (finder≠verifier, run-twice): https://x.com/CloudflareDev/status/2118013149538390253 +- kmkz (strict source→sink, "faster, cheaper, harder to exhaust"): https://x.com/kmkz_security/status/2079959118480019928 +- hackerfantastic (modelling → inference-fuzzing loop): https://x.com/hackerfantastic/status/2074858600078381110 diff --git a/packages/core/src/engagement/schema.ts b/packages/core/src/engagement/schema.ts index 55c29ade..02b8cd76 100644 --- a/packages/core/src/engagement/schema.ts +++ b/packages/core/src/engagement/schema.ts @@ -68,6 +68,52 @@ export const EvidenceItem = Schema.Struct({ }).annotate({ identifier: "Engagement.EvidenceItem" }) export type EvidenceItem = typeof EvidenceItem.Type +// Model spend (USD) attributed to a finding when it was recorded: `ai` is the +// spend in the window since the previous attribution (the marginal cost to find +// THIS finding, subagent sessions included), `total_to_date` is the cumulative +// attributed spend through this record. See costWindow() for the math. +export const CostAttribution = Schema.Struct({ + ai: Schema.Number, + total_to_date: Schema.Number, + at: Schema.String, +}).annotate({ identifier: "Engagement.CostAttribution" }) +export type CostAttribution = typeof CostAttribution.Type + +// Engagement-level cost ledger. `cursors` maps session ID → session cost already +// counted, so a later attribution counts only the delta (and survives multiple +// root sessions across an engagement). +export const CostLedger = Schema.Struct({ + total: Schema.Number, + cursors: Schema.Record(Schema.String, Schema.Number), +}).annotate({ identifier: "Engagement.CostLedger" }) +export type CostLedger = typeof CostLedger.Type + +// Pure cost-window math: given the CURRENT self-cost of each session in the +// relevant tree and the ledger's cursors, return the not-yet-attributed spend +// and the advanced cursors. Deltas are clamped at zero (message removal can +// shrink a session's cost between records — that must not credit spend back), +// while cursors always follow the current value so removed spend is never +// re-attributed later. +export function costWindow( + current: Record, + cursors: Record, +): { window: number; cursors: Record } { + const next: Record = { ...cursors } + let window = 0 + for (const [id, value] of Object.entries(current)) { + window += Math.max(0, value - (cursors[id] ?? 0)) + next[id] = value + } + return { window, cursors: next } +} + +export function formatCost(value: number): string { + if (!Number.isFinite(value) || value === 0) return "$0" + if (value < 0.01) return `$${value.toFixed(4)}` + return `$${value.toFixed(2)}` +} + + // I-3: derive a vulnerability's confidence from real signal — corroboration // (independent tools agreeing, repeated observation) and exploitation state — // NOT from severity (severity is impact, not likelihood-of-being-real) and NOT a @@ -103,6 +149,7 @@ export const Vulnerability = Schema.Struct({ evidence_items: Schema.optional(Schema.Array(EvidenceItem)), references: Schema.optional(Schema.Array(Schema.String)), mitre_attack_id: Schema.optional(Schema.String), + cost: Schema.optional(CostAttribution), }).annotate({ identifier: "Engagement.Vulnerability" }) export type Vulnerability = typeof Vulnerability.Type @@ -427,6 +474,7 @@ export const State = Schema.Struct({ artifacts: Schema.optional(Schema.Array(Artifact)), pause_on_finding: Schema.optional(PauseBehavior), goal: Schema.optional(Goal), + cost: Schema.optional(CostLedger), current_phase: PentestPhase, mode: PentestMode, notes: Schema.Array(Schema.String), @@ -719,6 +767,7 @@ export function summary(state: State) { objectives_completed: objectives.filter((o) => o.status === "completed").length, objectives_in_progress: objectives.filter((o) => o.status === "in_progress").length, objectives_blocked: objectives.filter((o) => o.status === "blocked").length, + cost_attributed: state.cost?.total ?? 0, } } diff --git a/packages/core/src/engagement/store.ts b/packages/core/src/engagement/store.ts index 46814867..7c52f130 100644 --- a/packages/core/src/engagement/store.ts +++ b/packages/core/src/engagement/store.ts @@ -58,11 +58,16 @@ export interface Interface { readonly save: (state: EngagementSchema.State) => Effect.Effect readonly create: (name: string) => Effect.Effect readonly load: (name: string) => Effect.Effect + // Detach from the current engagement (freestyle). Also drops the .last + // auto-resume pointer so the next prompt does not silently re-load it. + readonly unload: () => Effect.Effect readonly lastEngagement: () => Effect.Effect readonly listEngagements: () => Effect.Effect readonly addHost: (ip: string, data?: Partial) => Effect.Effect readonly deleteHost: (ip: string) => Effect.Effect readonly addVuln: (hostIp: string, vuln: EngagementSchema.Vulnerability) => Effect.Effect + // Advance the engagement cost ledger (used with CostAttribution on vulns). + readonly recordCost: (input: { cursors: Record; total: number }) => Effect.Effect readonly updateVuln: (hostIp: string, vulnId: string, patch: Partial<{ -readonly [K in keyof EngagementSchema.Vulnerability]: EngagementSchema.Vulnerability[K] }>) => Effect.Effect readonly deleteVuln: (hostIp: string, vulnId: string) => Effect.Effect readonly addCredential: (id: string, cred: Omit) => Effect.Effect @@ -408,6 +413,23 @@ const layer = Layer.effect( return state }), + unload: Effect.fn("EngagementStore.unload")(function* () { + yield* Ref.set(stateRef, undefined) + yield* Ref.set(changelogRef, []) + yield* Ref.set(decisionsRef, []) + yield* Ref.set(agentContextsRef, {}) + yield* Ref.set(interruptQueueRef, []) + yield* Ref.set(wordlistsRef, []) + yield* Ref.set(lastInjectedRef, undefined) + yield* Effect.sync(() => { + try { + fs.unlinkSync(lastFilePath()) + } catch { + // .last may not exist; dropping auto-resume is best-effort + } + }) + }), + lastEngagement: () => Effect.sync(() => { const p = lastFilePath() @@ -480,6 +502,11 @@ const layer = Layer.effect( `**Time**: ${new Date().toISOString()}`, `**Host**: ${hostIp}${vuln.service_port ? `:${vuln.service_port}` : ""}`, `**Status**: ${vuln.status ?? "suspected"}${vuln.confidence !== undefined ? ` (confidence: ${(vuln.confidence * 100).toFixed(0)}%)` : ""}`, + ...(vuln.cost + ? [ + `**AI cost**: ${EngagementSchema.formatCost(vuln.cost.ai)} to find (engagement total ${EngagementSchema.formatCost(vuln.cost.total_to_date)})`, + ] + : []), ...(vuln.description ? [`**Description**: ${vuln.description}`] : []), ...(vuln.evidence ? [`**Evidence**: \`${vuln.evidence}\``] : []), ...(vuln.evidence_items?.length ? [ @@ -496,6 +523,14 @@ const layer = Layer.effect( yield* persistCurrent }), + recordCost: Effect.fn("EngagementStore.recordCost")(function* (input) { + const modified = yield* Ref.modify(stateRef, (current) => { + if (!current) return [false, current] + return [true, { ...current, cost: { total: input.total, cursors: input.cursors } }] + }) + if (modified) yield* persistCurrent + }), + updateVuln: Effect.fn("EngagementStore.updateVuln")(function* (hostIp, vulnId, patch) { const found = yield* Ref.modify(stateRef, (current) => { if (!current) return [false, current] diff --git a/packages/core/src/flag/flag.ts b/packages/core/src/flag/flag.ts index a0eb78a1..c2d3565f 100644 --- a/packages/core/src/flag/flag.ts +++ b/packages/core/src/flag/flag.ts @@ -45,6 +45,7 @@ export const Flag = { OPENCODE_MODELS_URL: process.env["OPENCODE_MODELS_URL"], OPENCODE_MODELS_PATH: process.env["OPENCODE_MODELS_PATH"], OPENCODE_DB: process.env["OPENCODE_DB"], + OPENCODE_UA_OVERRIDE: process.env["OPENCODE_UA_OVERRIDE"], OPENCODE_WORKSPACE_ID: process.env["OPENCODE_WORKSPACE_ID"], OPENCODE_EXPERIMENTAL_WORKSPACES: enabledByExperimental("OPENCODE_EXPERIMENTAL_WORKSPACES"), diff --git a/packages/core/src/v1/config/config.ts b/packages/core/src/v1/config/config.ts index 3b5a79f1..a2460322 100644 --- a/packages/core/src/v1/config/config.ts +++ b/packages/core/src/v1/config/config.ts @@ -108,7 +108,7 @@ export const Info = Schema.Struct({ description: "Custom provider configurations and model overrides", }), mcp: Schema.optional( - Schema.Record(Schema.String, Schema.Union([ConfigMCPV1.Info, Schema.Struct({ enabled: Schema.Boolean })])), + Schema.Record(Schema.String, Schema.Union([ConfigMCPV1.Info, Schema.Struct({ enabled: Schema.optional(Schema.Boolean), proxy: Schema.optional(Schema.Boolean) })])), ).annotate({ description: "MCP (Model Context Protocol) server configurations" }), formatter: Schema.optional(ConfigFormatterV1.Info).annotate({ description: diff --git a/packages/core/src/v1/config/mcp.ts b/packages/core/src/v1/config/mcp.ts index 0a2aeff1..da525be5 100644 --- a/packages/core/src/v1/config/mcp.ts +++ b/packages/core/src/v1/config/mcp.ts @@ -20,6 +20,10 @@ export const Local = Schema.Struct({ timeout: Schema.optional(PositiveInt).annotate({ description: "Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified.", }), + proxy: Schema.optional(Schema.Boolean).annotate({ + description: + "Expose this server as two meta-tools (_catalog to list tools and fetch one tool's input schema, _run to execute one) instead of one tool per action. Keeps the per-request prompt small for large servers or small-context models.", + }), }).annotate({ identifier: "McpLocalConfig" }) export type Local = Schema.Schema.Type @@ -56,6 +60,10 @@ export const Remote = Schema.Struct({ timeout: Schema.optional(PositiveInt).annotate({ description: "Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified.", }), + proxy: Schema.optional(Schema.Boolean).annotate({ + description: + "Expose this server as two meta-tools (_catalog to list tools and fetch one tool's input schema, _run to execute one) instead of one tool per action. Keeps the per-request prompt small for large servers or small-context models.", + }), }).annotate({ identifier: "McpRemoteConfig" }) export type Remote = Schema.Schema.Type diff --git a/packages/core/test/engagement-cost.test.ts b/packages/core/test/engagement-cost.test.ts new file mode 100644 index 00000000..6d5df1d1 --- /dev/null +++ b/packages/core/test/engagement-cost.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, test } from "bun:test" +import { Schema } from "effect" +import { EngagementSchema } from "@pentestcode/core/engagement/schema" + +const { costWindow, formatCost } = EngagementSchema + +function baseState(): EngagementSchema.State { + return { + id: EngagementSchema.ID.make("cost1234"), + name: "cost", + created_at: "2026-10-16T00:00:00.000Z", + updated_at: "2026-10-16T00:00:00.000Z", + scope: { targets: [], excludes: [], notes: "" }, + hosts: {}, + credentials: {}, + flags: [], + attack_path: [], + task_tree: [], + current_phase: "recon", + mode: "auto", + notes: [], + } +} + +describe("costWindow", () => { + test("first attribution counts all spend and advances cursors", () => { + const result = costWindow({ root: 1.5, sub1: 0.25, sub2: 0.25 }, {}) + expect(result.window).toBeCloseTo(2.0) + expect(result.cursors).toEqual({ root: 1.5, sub1: 0.25, sub2: 0.25 }) + }) + + test("only the delta since the previous attribution counts", () => { + const first = costWindow({ root: 1.0, sub: 1.0 }, {}) + const second = costWindow({ root: 1.4, sub: 1.0 }, first.cursors) + expect(second.window).toBeCloseTo(0.4) + expect(second.cursors).toEqual({ root: 1.4, sub: 1.0 }) + }) + + test("a new subagent session counts fully on first sight", () => { + const cursors = { root: 2.0 } + const result = costWindow({ root: 2.0, fresh: 0.75 }, cursors) + expect(result.window).toBeCloseTo(0.75) + expect(result.cursors.fresh).toBeCloseTo(0.75) + }) + + test("shrinking session cost never credits spend back, cursor follows", () => { + const cursors = { root: 2.0 } + const shrunk = costWindow({ root: 1.0 }, cursors) + expect(shrunk.window).toBe(0) + expect(shrunk.cursors.root).toBeCloseTo(1.0) + // regrowth counts only above the new baseline + const regrown = costWindow({ root: 1.6 }, shrunk.cursors) + expect(regrown.window).toBeCloseTo(0.6) + }) + + test("cursors for sessions absent from the current tree are preserved", () => { + const result = costWindow({ root: 1.0 }, { root: 0.5, gone: 9.0 }) + expect(result.cursors.gone).toBeCloseTo(9.0) + expect(result.window).toBeCloseTo(0.5) + }) +}) + +describe("formatCost", () => { + test("zero and non-finite render as $0", () => { + expect(formatCost(0)).toBe("$0") + expect(formatCost(Number.NaN)).toBe("$0") + }) + + test("sub-cent values keep precision, others render two decimals", () => { + expect(formatCost(0.0042)).toBe("$0.0042") + expect(formatCost(1.239)).toBe("$1.24") + }) +}) + +describe("cost schema round-trips", () => { + test("vulnerability with cost attribution survives encode/decode", () => { + const state: EngagementSchema.State = { + ...baseState(), + hosts: { + "10.0.0.1": { + ip: "10.0.0.1", + services: [], + vulns: [ + { + id: "v1", + title: "SQLi", + severity: "high", + status: "confirmed", + cost: { ai: 0.42, total_to_date: 3.1, at: "2026-10-16T12:00:00.000Z" }, + }, + ], + access: [], + notes: [], + }, + }, + cost: { total: 3.1, cursors: { ses_root: 2.6, ses_sub: 0.5 } }, + } + const decoded = Schema.decodeUnknownSync(EngagementSchema.State)(Schema.encodeSync(EngagementSchema.State)(state)) + expect(decoded.hosts["10.0.0.1"]?.vulns[0]?.cost?.ai).toBeCloseTo(0.42) + expect(decoded.cost?.total).toBeCloseTo(3.1) + expect(decoded.cost?.cursors.ses_sub).toBeCloseTo(0.5) + expect(decoded.hosts["10.0.0.1"]?.vulns[0]?.cost?.total_to_date).toBeCloseTo(3.1) + }) + + test("states and vulns without cost still decode (optional fields)", () => { + const noCost: EngagementSchema.State = { + ...baseState(), + hosts: { + "10.0.0.2": { + ip: "10.0.0.2", + services: [], + vulns: [{ id: "v2", title: "Legacy" }], + access: [], + notes: [], + }, + }, + } + const decoded = Schema.decodeUnknownSync(EngagementSchema.State)(Schema.encodeSync(EngagementSchema.State)(noCost)) + expect(decoded.cost).toBeUndefined() + expect(decoded.hosts["10.0.0.2"]?.vulns[0]?.cost).toBeUndefined() + }) + + test("summary reports attributed cost", () => { + const state: EngagementSchema.State = { ...baseState(), cost: { total: 12.5, cursors: {} } } + expect(EngagementSchema.summary(state).cost_attributed).toBeCloseTo(12.5) + expect(EngagementSchema.summary(baseState()).cost_attributed).toBe(0) + }) +}) diff --git a/packages/core/test/scope-matcher.test.ts b/packages/core/test/scope-matcher.test.ts index 8a549b79..1de0ce06 100644 --- a/packages/core/test/scope-matcher.test.ts +++ b/packages/core/test/scope-matcher.test.ts @@ -244,14 +244,14 @@ describe("extractTargetsFromCommand", () => { expect(targets).not.toContain("apt.get") }) - test("exotic gTLDs (.zip .mov) are not scope-warned (advisory tradeoff)", () => { + test("includes .zip and .mov TLDs", () => { const targets = extractTargetsFromCommand("nmap target.zip") - expect(targets).not.toContain("target.zip") + expect(targets).toContain("target.zip") }) - test("exotic gTLDs like .security are not scope-warned", () => { + test("includes new TLDs like .security", () => { const targets = extractTargetsFromCommand("nmap target.security") - expect(targets).not.toContain("target.security") + expect(targets).toContain("target.security") }) test("rejects invalid IPs like 999.1.1.1", () => { @@ -283,11 +283,11 @@ describe("extractTargetsFromCommand", () => { expect(targets).not.toContain("wordlists/common.txt") }) - test("exotic long TLDs are not scope-warned (curated TLD set tradeoff)", () => { - expect(extractTargetsFromCommand("nmap target.company")).not.toContain("target.company") - expect(extractTargetsFromCommand("nmap target.security")).not.toContain("target.security") - expect(extractTargetsFromCommand("nmap target.network")).not.toContain("target.network") - expect(extractTargetsFromCommand("nmap app.agency")).not.toContain("app.agency") + test("extracts long TLDs: .company .security .network .agency", () => { + expect(extractTargetsFromCommand("nmap target.company")).toContain("target.company") + expect(extractTargetsFromCommand("nmap target.security")).toContain("target.security") + expect(extractTargetsFromCommand("nmap target.network")).toContain("target.network") + expect(extractTargetsFromCommand("nmap app.agency")).toContain("app.agency") }) test("extracts two-part domain with standard TLD", () => { @@ -421,8 +421,8 @@ describe("extractTargetsFromCommand: FP-prone commands", () => { }) test("netexec with domain target", () => { - const targets = extractTargetsFromCommand("netexec smb dc01.corp-example.com -u admin -p 'P@ssw0rd'") - expect(targets).toContain("dc01.corp-example.com") + const targets = extractTargetsFromCommand("netexec smb dc01.corp.local -u admin -p 'P@ssw0rd'") + expect(targets).toContain("dc01.corp.local") }) test("gobuster with wordlist path", () => { diff --git a/packages/opencode/README.md b/packages/opencode/README.md deleted file mode 100644 index 75890119..00000000 --- a/packages/opencode/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# js - -To install dependencies: - -```bash -bun install -``` - -To run: - -```bash -bun run index.ts -``` - -This project was created using `bun init` in bun v1.2.12. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime. diff --git a/packages/opencode/src/agent/agent.ts b/packages/opencode/src/agent/agent.ts index b9dad89f..d2dfb265 100644 --- a/packages/opencode/src/agent/agent.ts +++ b/packages/opencode/src/agent/agent.ts @@ -22,6 +22,7 @@ import PROMPT_POST_EXPLOIT from "../session/prompt/post-exploit.txt" import PROMPT_EXPLOIT_DEV from "../session/prompt/exploit-dev.txt" import PROMPT_CRITIC from "../session/prompt/critic.txt" import PROMPT_WEBAPP from "../session/prompt/webapp.txt" +import PROMPT_CODE_AUDITOR from "../session/prompt/code-audit.txt" import PROMPT_REFLECTOR from "../session/prompt/reflector.txt" import PROMPT_SUMMARY from "./prompt/summary.txt" import PROMPT_TITLE from "./prompt/title.txt" @@ -129,6 +130,12 @@ const layer = Layer.effect( const defaults = Permission.fromConfig({ "*": "allow", + // Creating an engagement must be user-approved: the agent may propose + // a name, but nothing is written until the user allows it. This rule + // comes after the wildcard so it wins — without it `*: allow` would + // auto-approve and orphan engagements appeared silently (the tool's + // create_engagement action calls ctx.ask with this permission id). + create_engagement: "ask", doom_loop: "ask", external_directory: { "*": "ask", @@ -179,6 +186,7 @@ const layer = Layer.effect( ensure_tools: "allow", os_hook: "allow", inject_probe: "allow", + patch_diff: "allow", knowledge: "allow", screenshot: "allow", }), @@ -301,6 +309,7 @@ const layer = Layer.effect( xss_detect: "allow", jwt_analyze: "allow", inject_probe: "allow", + patch_diff: "allow", screenshot: "allow", }), user, @@ -437,6 +446,7 @@ const layer = Layer.effect( state_query: "allow", state_update: "allow", os_hook: "allow", + patch_diff: "allow", }), user, ), @@ -524,6 +534,37 @@ const layer = Layer.effect( mode: "subagent", native: true, }, + code_auditor: { + name: "code_auditor", + steps: 250, + description: `Code Auditor / vulnerability-research subagent. Finds NOVEL bugs in a target's own source or binaries — source review, taint source→sink, SAST (semgrep → semgrep_parse), variant analysis + patch-diffing (n-day→variant via patch_diff), and fuzz-harness bring-up. The discovery layer the scanner/parser tools cannot reach ("no public CVE" is not "no bug"). Coverage-led and disprove-first: returns candidates with file:line source→sink dataflow and a trigger hypothesis, hands weaponization to exploit_dev and proofs to critic.`, + permission: Permission.merge( + defaults, + Permission.fromConfig({ + read: "allow", + grep: "allow", + glob: "allow", + bash: "allow", + write: "allow", + edit: "allow", + webfetch: "allow", + websearch: "allow", + state_query: "allow", + state_update: "allow", + scope_check: "allow", + ensure_tools: "allow", + semgrep_parse: "allow", + codeql_parse: "allow", + patch_diff: "allow", + knowledge: "allow", + }), + user, + ), + prompt: PROMPT_CODE_AUDITOR, + options: {}, + mode: "subagent", + native: true, + }, compaction: { name: "compaction", mode: "primary", diff --git a/packages/opencode/src/cli/cmd/providers.ts b/packages/opencode/src/cli/cmd/providers.ts index 413d96ba..62848cbc 100644 --- a/packages/opencode/src/cli/cmd/providers.ts +++ b/packages/opencode/src/cli/cmd/providers.ts @@ -369,13 +369,14 @@ export const ProvidersLoginCommand = effectCmd({ const hooks = yield* pluginSvc.list() const priority: Record = { - opencode: 0, - openai: 1, - "github-copilot": 2, - google: 3, - anthropic: 4, - openrouter: 5, - vercel: 6, + "opencode-go": 0, + opencode: 1, + openai: 2, + "github-copilot": 3, + google: 4, + anthropic: 5, + openrouter: 6, + vercel: 7, } const pluginProviders = resolvePluginProviders({ hooks, @@ -396,6 +397,7 @@ export const ProvidersLoginCommand = effectCmd({ label: x.name, value: x.id, hint: { + "opencode-go": "Go/Go Plus subscription", opencode: "recommended", openai: "ChatGPT Plus/Pro or API key", }[x.id], @@ -463,7 +465,7 @@ export const ProvidersLoginCommand = effectCmd({ ) } - if (provider === "opencode") { + if (provider === "opencode" || provider === "opencode-go") { yield* Prompt.log.info("Create an api key at https://opencode.ai/auth") } diff --git a/packages/opencode/src/cli/cmd/run.ts b/packages/opencode/src/cli/cmd/run.ts index 7b6ee7f2..dc8a19a7 100644 --- a/packages/opencode/src/cli/cmd/run.ts +++ b/packages/opencode/src/cli/cmd/run.ts @@ -131,7 +131,17 @@ export const RunCommand = effectCmd({ instance: (args) => !args.attach, // For --dir without --attach, load instance for the resolved target dir. // The handler also chdirs (preserving the legacy order: chdir → file resolution). - directory: (args) => (args.dir && !args.attach ? path.resolve(process.cwd(), args.dir) : process.cwd()), + // Resolve exactly like the handler does (`PWD ?? cwd`, canonicalized): launch + // wrappers keep process.cwd() inside the source checkout (bun must compile the + // TUI with the checkout's tsconfig) while `$PWD` names the user's directory. + // The bootstrap instance and the session root must agree on that directory, or + // the command waits on one instance while the session runs under another and + // the run never completes. + directory: (args) => { + const root = Filesystem.resolve(process.env.PWD ?? process.cwd()) + if (!args.dir || args.attach) return root + return Filesystem.resolve(path.isAbsolute(args.dir) ? args.dir : path.join(root, args.dir)) + }, builder: (yargs: Argv) => yargs .positional("message", { diff --git a/packages/opencode/src/cli/cmd/tui.ts b/packages/opencode/src/cli/cmd/tui.ts index 3d0a892b..4d649b78 100644 --- a/packages/opencode/src/cli/cmd/tui.ts +++ b/packages/opencode/src/cli/cmd/tui.ts @@ -207,7 +207,14 @@ export const TuiThreadCommand = cmd({ } const cwd = Filesystem.resolve(process.cwd()) - const worker = new Worker(file) + // Bun workers start from the original process environment, not the + // runtime process.env, so credentials loaded from .env at startup are + // otherwise invisible inside the TUI worker. + const worker = new Worker(file, { + env: Object.fromEntries( + Object.entries(process.env).filter((entry): entry is [string, string] => entry[1] !== undefined), + ), + }) const client = Rpc.client(worker) const reload = () => { client.call("reload", undefined).catch(() => {}) diff --git a/packages/opencode/src/command/template/pentest-scope.txt b/packages/opencode/src/command/template/pentest-scope.txt index d0f9f681..e11474b2 100644 --- a/packages/opencode/src/command/template/pentest-scope.txt +++ b/packages/opencode/src/command/template/pentest-scope.txt @@ -7,6 +7,6 @@ If the user provides arguments, interpret them as scope changes: - Arguments prefixed with "!" or "-" → add to excludes - "notes:" prefix → set scope notes -If no engagement exists, create one first using `state_update` with `action: "create_engagement"` and a name derived from the targets. +If no engagement exists, create it with `state_update` (`action: "create_engagement"`) and a name derived from the primary target — product-first, lowercase, hyphenated, including the program/client name when known, ending in `-YYYY-MM` (e.g. `okta-bugcrowd-2026-10`). The user approves it with one keystroke; do NOT ask them to name it. NEVER name from the working directory or generic words (no `opencode-2026-10`) — ask WHAT we are testing if the target is unclear, and create the moment it is. $ARGUMENTS diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 62c98a15..d9baa99f 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -30,6 +30,9 @@ import { DbCommand } from "./cli/cmd/db" import { errorMessage } from "./util/error" import { PluginCommand } from "./cli/cmd/plug" import { Heap } from "./cli/heap" +import { EnvFile } from "./env/load" + +EnvFile.loadEnvFiles() const args = hideBin(process.argv) diff --git a/packages/opencode/src/mcp/catalog.ts b/packages/opencode/src/mcp/catalog.ts index 3f985eeb..2495cf63 100644 --- a/packages/opencode/src/mcp/catalog.ts +++ b/packages/opencode/src/mcp/catalog.ts @@ -50,36 +50,146 @@ export function convertTool(mcpTool: MCPToolDef, client: Client, timeout?: numbe return dynamicTool({ description: mcpTool.description ?? "", inputSchema: jsonSchema(inputSchema), - execute: async (args: unknown, options) => { - const result = await client.callTool( - { - name: mcpTool.name, - arguments: (args || {}) as Record, - }, - CallToolResultSchema, - { - resetTimeoutOnProgress: true, - signal: options.abortSignal, - timeout, - // The MCP SDK only sends a progress token when this hook is present, enabling timeout resets. - onprogress: () => {}, + execute: (args, options) => call(client, mcpTool.name, (args || {}) as Record, timeout, options), + }) +} + +async function call( + client: Client, + name: string, + args: Record, + timeout?: number, + options?: { abortSignal?: AbortSignal }, +) { + const result = await client.callTool( + { + name, + arguments: args, + }, + CallToolResultSchema, + { + resetTimeoutOnProgress: true, + signal: options?.abortSignal, + timeout, + // The MCP SDK only sends a progress token when this hook is present, enabling timeout resets. + onprogress: () => {}, + }, + ) + if (result.isError) + throw new Error( + result.content + .flatMap((item) => (item.type === "text" ? [item.text] : [])) + .filter((text) => text.trim()) + .join("\n\n") || "MCP tool returned an error", + ) + if (result.content.length > 0 || result.structuredContent === undefined || result.structuredContent === null) + return result + return { + ...result, + content: [{ type: "text" as const, text: JSON.stringify(result.structuredContent) }], + } +} + +// Proxy mode: some providers cap the number of tools per request (BugBunny: +// 128). A server with 150+ tools (drost) cannot be exposed one-tool-per-action +// there, so `proxy: true` replaces the per-action tools with two meta-tools: +// +// _catalog list tools, or fetch one tool's full input schema +// _run execute any tool: { tool: "", arguments: {...} } +// +// Every action stays reachable; only two tool definitions occupy the request. +export function proxy(clientName: string, client: Client, defs: MCPToolDef[], timeout?: number) { + const names = defs.map((def) => def.name) + const byName = new Map(defs.map((def) => [def.name, def])) + const catalogName = toolName(clientName, "catalog") + const runName = toolName(clientName, "run") + + const catalogDef = { + name: "catalog", + description: + `List the ${defs.length} tools of the ${clientName} MCP server, or fetch one tool's description and input schema. ` + + `Execute any tool with ${runName}: {"tool": "", "arguments": {...}}.`, + inputSchema: { + type: "object", + properties: { + tool: { + type: "string", + description: `Tool name to fetch its full input schema (omit to list all ${defs.length} tool names)`, }, - ) - if (result.isError) - throw new Error( - result.content - .flatMap((item) => (item.type === "text" ? [item.text] : [])) - .filter((text) => text.trim()) - .join("\n\n") || "MCP tool returned an error", - ) - if (result.content.length > 0 || result.structuredContent === undefined || result.structuredContent === null) - return result + }, + additionalProperties: false, + } as JSONSchema7, + } + const catalogTool = dynamicTool({ + description: catalogDef.description, + inputSchema: jsonSchema(catalogDef.inputSchema), + execute: async (args) => { + const want = typeof (args as { tool?: unknown })?.tool === "string" ? String((args as { tool?: string }).tool).trim() : "" + if (want) { + const def = byName.get(want) + if (!def) throw new Error(`Unknown ${clientName} tool "${want}". Available: ${names.join(", ")}`) + return { + content: [ + { + type: "text" as const, + text: JSON.stringify({ name: def.name, description: def.description, inputSchema: def.inputSchema }, null, 2), + }, + ], + } + } + const lines = defs.map((def) => { + const description = (def.description ?? "").split("\n")[0]?.trim() + return `- ${def.name}${description ? ` — ${description}` : ""}` + }) return { - ...result, - content: [{ type: "text" as const, text: JSON.stringify(result.structuredContent) }], + content: [ + { + type: "text" as const, + text: [ + `${clientName} tools (${defs.length}). Run one with ${runName} {"tool": "", "arguments": {...}}; fetch a full input schema with ${catalogName} {"tool": ""}.`, + ...lines, + ].join("\n"), + }, + ], } }, }) + + const runDef = { + name: "run", + description: + `Execute any tool of the ${clientName} MCP server by name. Use ${catalogName} to list tools and fetch their input schemas first.`, + inputSchema: { + type: "object", + properties: { + tool: { type: "string", description: `Tool name, e.g. "${names[0] ?? "tool"}"` }, + arguments: { + type: "object", + description: "Arguments object for the tool (see its input schema in the catalog)", + additionalProperties: true, + }, + }, + required: ["tool"], + additionalProperties: false, + } as JSONSchema7, + } + const runTool = dynamicTool({ + description: runDef.description, + inputSchema: jsonSchema(runDef.inputSchema), + execute: async (args, options) => { + const name = typeof (args as { tool?: unknown })?.tool === "string" ? String((args as { tool?: string }).tool).trim() : "" + if (!name) throw new Error(`Missing "tool". Available: ${names.join(", ")}`) + if (!byName.has(name)) throw new Error(`Unknown ${clientName} tool "${name}". Available: ${names.join(", ")}`) + const raw = (args as { arguments?: unknown })?.arguments + const input = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record) : {} + return call(client, name, input, timeout, options) + }, + }) + + return [ + { def: catalogDef as MCPToolDef, tool: catalogTool }, + { def: runDef as MCPToolDef, tool: runTool }, + ] } export function fetch( diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index e23e45f3..670751a7 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -32,6 +32,7 @@ import { InstanceState } from "@/effect/instance-state" import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process" import { CrossSpawnSpawner } from "@pentestcode/core/cross-spawn-spawner" import { McpCatalog } from "./catalog" +import type { Tool } from "ai" import { McpEvent } from "@pentestcode/schema/mcp-event" import { McpBrowser } from "./browser" @@ -159,6 +160,11 @@ export interface McpTool { readonly def: MCPToolDef readonly client: MCPClient readonly timeout?: number + /** + * Pre-built AI SDK tool for synthetic entries (proxy mode's catalog/run). + * Consumers use it instead of adapting `def` themselves. + */ + readonly tool?: Tool } export interface Interface { @@ -680,6 +686,20 @@ const layer = Layer.effect( continue } const timeout = requestTimeout(s, clientName, mcpConfig, defaultTimeout) + // Proxy mode (`proxy: true` in the server config): expose the server as + // two meta-tools instead of one tool per action. Keeps providers with a + // per-request tool cap (BugBunny: 128) usable with large MCP servers. + if (mcpConfig && "proxy" in mcpConfig && mcpConfig.proxy === true) { + for (const entry of McpCatalog.proxy(clientName, client, listed, timeout)) { + result[McpCatalog.toolName(clientName, entry.def.name)] = { + def: entry.def, + client, + timeout, + tool: entry.tool, + } + } + continue + } for (const def of listed) { result[McpCatalog.toolName(clientName, def.name)] = { def, client, timeout } } diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index 709faff4..74d42f6f 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -1138,6 +1138,7 @@ export interface Interface { query: string[], ) => Effect.Effect<{ providerID: ProviderV2.ID; modelID: string } | undefined> readonly getSmallModel: (providerID: ProviderV2.ID) => Effect.Effect + readonly fallbackModel: (model: Model) => Effect.Effect readonly defaultModel: () => Effect.Effect<{ providerID: ProviderV2.ID; modelID: ModelV2.ID }, DefaultModelError> } @@ -1892,11 +1893,17 @@ const layer = Layer.effect( : providerID.startsWith("github-copilot") ? ["gpt-mini", ...smallModelFamilyPriority] : smallModelFamilyPriority - const models = sortBy( + const available = sortBy( Object.values(provider.models), [(model) => model.release_date, "desc"], [(model) => model.id, "desc"], ) + // Billing policy (see OPENCODE_FREE_TIER.md): Zen mixes free and paying + // models, and an auto-picked paid model can be refused outright (no + // balance) or bill unexpectedly. Restrict the auto-pick to free Zen + // models; no free match returns undefined and callers fall back to the + // session's main model. An explicit `small_model` config still wins above. + const models = providerID.startsWith("opencode") ? available.filter(isFreeModel) : available for (const family of priority) { const candidates = models.filter((model) => model.family === family) if (providerID === ProviderV2.ID.amazonBedrock) { @@ -1924,6 +1931,56 @@ const layer = Layer.effect( return undefined }) + // Billing policy (see OPENCODE_FREE_TIER.md): a Zen request can be refused + // for account-level reasons (no balance, free-tier gate, exhausted free + // quota). The escape hatch is the equivalent model on OpenRouter, billed to + // the user's OpenRouter key. Map by name first — normalized so + // `deepseek-v4-flash-free` finds `deepseek/deepseek-v4-flash` and + // `gpt-5.4-nano` finds `openai/gpt-5.4-nano` — then by models.dev family. + // Non-Zen providers keep their own billing paths and never fall back. + const fallbackModel = Effect.fn("Provider.fallbackModel")(function* (model: Model) { + if (!model.providerID.startsWith("opencode")) return undefined + + const s = yield* InstanceState.get(state) + const openrouter = s.providers[ProviderV2.ID.openrouter] + if (!openrouter) return undefined + + const cfg = yield* config.get() + const connected = + Boolean(yield* auth.get(ProviderV2.ID.openrouter).pipe(Effect.orDie)) || + Boolean(cfg.provider?.["openrouter"]?.options?.apiKey) || + Boolean(process.env["OPENROUTER_API_KEY"]) + if (!connected) return undefined + + const normalize = (id: string) => id.toLowerCase().replace(/[^a-z0-9]/g, "") + const base = (value: string) => value.replace(/free$/, "") + const target = normalize(String(model.id)) + const targetBase = base(target) + const rank = (item: Model): number | undefined => { + const segment = normalize(String(item.id).split("/").pop() ?? "") + const segmentBase = base(segment) + if (segment === target) return 0 + if (targetBase && segmentBase === targetBase) return 1 + if (segment.length >= 4 && targetBase.includes(segment)) return 2 + if (model.family && item.family === model.family) return 3 + return undefined + } + const ranked = Object.values(openrouter.models) + .filter((item) => !String(item.id).startsWith("~")) + .flatMap((item) => { + const tier = rank(item) + return tier === undefined ? [] : [{ item, tier }] + }) + const candidates = sortBy( + ranked, + [(entry) => entry.tier, "asc"], + [(entry) => (isFreeModel(entry.item) ? 0 : 1), "asc"], + [(entry) => entry.item.release_date, "desc"], + [(entry) => entry.item.id, "desc"], + ) + return candidates[0]?.item + }) + const defaultModel = Effect.fn("Provider.defaultModel")(function* () { const cfg = yield* config.get() if (cfg.model) return parseModel(cfg.model) @@ -1959,12 +2016,19 @@ const layer = Layer.effect( } }) - return Service.of({ list, getProvider, getModel, getLanguage, closest, getSmallModel, defaultModel }) + return Service.of({ list, getProvider, getModel, getLanguage, closest, getSmallModel, fallbackModel, defaultModel }) }), ) const priority = ["gpt-5", "claude-sonnet-4", "big-pickle", "gemini-3-pro"] const smallModelFamilyPriority = ["gemini-flash", "gpt-nano", "claude-haiku"] + +// A model that will not bill: zero input and output cost. Zen's free tier is +// exactly this slice of its catalog. +export function isFreeModel(model: Model) { + return model.cost.input === 0 && model.cost.output === 0 +} + export function sort(models: T[]) { return sortBy( models, diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts index 29e612ec..7aeda072 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts @@ -84,7 +84,14 @@ function selectedV2WorkspaceID( } function defaultDirectory(request: HttpServerRequest.HttpServerRequest, url: URL): string { - return url.searchParams.get("directory") || request.headers["x-pentestcode-directory"] || process.cwd() + // The SDK clients send `x-opencode-directory`; the pentestcode-prefixed + // spelling is accepted as an alias (see the rename in b8edec4). + return ( + url.searchParams.get("directory") || + request.headers["x-opencode-directory"] || + request.headers["x-pentestcode-directory"] || + process.cwd() + ) } function shouldStayOnControlPlane(request: HttpServerRequest.HttpServerRequest, url: URL): boolean { diff --git a/packages/opencode/src/session/compaction.ts b/packages/opencode/src/session/compaction.ts index a83e496b..4d37041e 100644 --- a/packages/opencode/src/session/compaction.ts +++ b/packages/opencode/src/session/compaction.ts @@ -33,6 +33,21 @@ const PRUNE_PROTECTED_TOOLS = ["skill"] const DEFAULT_TAIL_TURNS = 2 const MIN_PRESERVE_RECENT_TOKENS = 2_000 +/** + * Compaction must not depend on free-tier availability. + * + * A free small model (zero input/output cost) is skipped when the session's main + * model bills, because a rate-limited 429 on compaction retries for up to 15 + * minutes and then ends the session. When the main model is free too there is no + * paid alternative, so the small model is still worth trying. + */ +export function preferredCompactionModel(main: Provider.Model, small: Provider.Model | undefined) { + if (!small) return main + if (!Provider.isFreeModel(small)) return small + if (Provider.isFreeModel(main)) return small + return main +} + // A-5 (pure, tested): choose which completed tool-result parts are cold enough to // prune-to-ref. DEPTH-PROTECTION invariants — the guard against a compaction // regression eating the active vector: @@ -369,16 +384,26 @@ const layer = Layer.effect( } const agent = yield* agents.get("compaction") - // Compaction (summarizing the transcript) is the textbook cheap-model job. - // Prefer the configured small model; fall back to the main model only when a - // compaction-agent model is set or no small model resolves. (A2) - const smallForCompaction = agent.model - ? undefined - : yield* provider.getSmallModel(userMessage.model.providerID) + // Compaction (summarizing the transcript) is the textbook cheap-model job, + // but it is also on the critical path: when it fails, the session stops. + // Free tiers (Zen free, OpenRouter :free, OrcaRouter free) are rate-limited, + // and a 429 here retries for up to 15 minutes before failing. So prefer the + // small model only when it bills; otherwise use the session's main model. An + // explicit compaction-agent model always wins, and the free small model keeps + // serving tool-output offload/titles, where failures fail open. (A2) + const mainModel = yield* provider + .getModel(userMessage.model.providerID, userMessage.model.modelID) + .pipe(Effect.orDie) + const smallForCompaction = agent.model ? undefined : yield* provider.getSmallModel(userMessage.model.providerID) const model = agent.model ? yield* provider.getModel(agent.model.providerID, agent.model.modelID).pipe(Effect.orDie) - : smallForCompaction ?? - (yield* provider.getModel(userMessage.model.providerID, userMessage.model.modelID).pipe(Effect.orDie)) + : preferredCompactionModel(mainModel, smallForCompaction) + if (smallForCompaction && model !== smallForCompaction) + yield* Effect.logInfo("compaction: free small model skipped in favor of the main model", { + "session.id": input.sessionID, + "model.small": `${smallForCompaction.providerID}/${smallForCompaction.id}`, + "model.main": `${mainModel.providerID}/${mainModel.id}`, + }) const cfg = yield* config.get() const history = compactionPart && messages.at(-1)?.info.id === input.parentID ? messages.slice(0, -1) : messages const prior = completedCompactions(history) diff --git a/packages/opencode/src/session/instruction.ts b/packages/opencode/src/session/instruction.ts index 685780eb..96604a3a 100644 --- a/packages/opencode/src/session/instruction.ts +++ b/packages/opencode/src/session/instruction.ts @@ -162,10 +162,52 @@ const layer: Layer.Layer< const files = yield* Effect.forEach(Array.from(paths), read, { concurrency: 8 }) const remote = yield* Effect.forEach(urls, fetch, { concurrency: 4 }) - return [ + const result = [ ...Array.from(paths).flatMap((item, i) => (files[i] ? [`Instructions from: ${item}\n${files[i]}`] : [])), ...urls.flatMap((item, i) => (remote[i] ? [`Instructions from: ${item}\n${remote[i]}`] : [])), ] + + // Support inline raw content in config.instructions (not URLs) + if (config.instructions) { + for (const raw of config.instructions) { + if (raw.startsWith("https://") || raw.startsWith("http://")) continue + const instruction = raw.startsWith("~/") ? path.join(global.home, raw.slice(2)) : raw + // Try as file first + if (path.isAbsolute(instruction)) { + const exists = yield* fs.existsSafe(instruction) + if (exists) { + const content = yield* read(instruction) + if (content) { + result.push(`Instructions from: ${instruction}\n${content}`) + continue + } + } + } else { + const matches = yield* relative(instruction).pipe(Effect.catch(() => Effect.succeed([] as string[]))) + if (matches.length > 0) { + continue // already handled by systemPaths + } + } + // Treat as inline content + if (raw.trim().length > 0) { + result.push(raw) + } + } + } + + // Support environment variables for arbitrary system prompt content + const envPrompts = [ + process.env.OPENCODE_SYSTEM_PROMPT, + process.env.PENTESTCODE_SYSTEM_PROMPT, + process.env.CUSTOM_SYSTEM_PROMPT, + ] + for (const envPrompt of envPrompts) { + if (envPrompt && envPrompt.trim().length > 0) { + result.push(envPrompt) + } + } + + return result }) const find = Effect.fn("Instruction.find")(function* (dir: string) { diff --git a/packages/opencode/src/session/llm/request.ts b/packages/opencode/src/session/llm/request.ts index 46ff58ee..74e16f40 100644 --- a/packages/opencode/src/session/llm/request.ts +++ b/packages/opencode/src/session/llm/request.ts @@ -10,12 +10,13 @@ import type { Provider } from "@/provider/provider" import { ProviderTransform } from "@/provider/transform" import { SystemPrompt } from "../system" import { InstallationVersion } from "@pentestcode/core/installation/version" +import { Flag } from "@pentestcode/core/flag/flag" import { Effect, Record } from "effect" import { jsonSchema, tool as aiTool, type ModelMessage, type Tool } from "ai" import type { Plugin } from "@/plugin" import { mergeDeep } from "remeda" -const USER_AGENT = `pentestcode/${InstallationVersion}` +const USER_AGENT = Flag.OPENCODE_UA_OVERRIDE ?? `pentestcode/${InstallationVersion}` type PrepareInput = { readonly user: SessionV1.User diff --git a/packages/opencode/src/session/processor.ts b/packages/opencode/src/session/processor.ts index 51bb8784..ff4c2a18 100644 --- a/packages/opencode/src/session/processor.ts +++ b/packages/opencode/src/session/processor.ts @@ -18,7 +18,7 @@ import type { SessionID } from "./schema" import { SessionRetry } from "./retry" import { SessionStatus } from "./status" import { SessionSummary } from "./summary" -import type { Provider } from "@/provider/provider" +import { Provider } from "@/provider/provider" import { Question } from "@/question" import { errorMessage } from "@/util/error" import { isRecord } from "@/util/record" @@ -86,6 +86,7 @@ const layer = Layer.effect( const snapshot = yield* Snapshot.Service const agents = yield* Agent.Service const llm = yield* LLM.Service + const provider = yield* Provider.Service const permission = yield* Permission.Service const plugin = yield* Plugin.Service const summary = yield* SessionSummary.Service @@ -632,12 +633,12 @@ const layer = Layer.effect( ctx.needsCompaction = false ctx.shouldBreak = (yield* config.get()).experimental?.continue_loop_on_deny !== true - return yield* Effect.gen(function* () { - yield* Effect.gen(function* () { + const attempt = (model: Provider.Model) => + Effect.gen(function* () { ctx.currentText = undefined ctx.reasoningMap = {} yield* status.set(ctx.sessionID, { type: "busy" }) - const stream = llm.stream(streamInput) + const stream = llm.stream({ ...streamInput, model }) yield* stream.pipe( Stream.tap((event) => handleEvent(event)), @@ -659,7 +660,7 @@ const layer = Layer.effect( ), Effect.retry( SessionRetry.policy({ - provider: input.model.providerID, + provider: model.providerID, parse, set: (info) => { return status.set(ctx.sessionID, { @@ -672,6 +673,33 @@ const layer = Layer.effect( }, }), ), + ) + + // Billing policy (see OPENCODE_FREE_TIER.md): when Zen refuses a request + // for account-level reasons (no balance, free-tier gate, exhausted free + // quota — the retry policy above has already spent its attempts on the + // last of those), try ONCE on the equivalent OpenRouter model, billed to + // the user's OpenRouter key. Main turns and compaction both run through + // here; the assistant message's model is updated so the transcript + // records which model actually served the turn. + const failover = (error: unknown) => + Effect.gen(function* () { + const fallback = yield* provider.fallbackModel(streamInput.model) + if (!fallback) return yield* Effect.fail(error) + yield* Effect.logWarning("provider fallback: Zen refused the request, retrying on OpenRouter", { + "session.id": ctx.sessionID, + "model.from": `${streamInput.model.providerID}/${streamInput.model.id}`, + "model.to": `${fallback.providerID}/${fallback.id}`, + }) + ctx.assistantMessage.providerID = fallback.providerID + ctx.assistantMessage.modelID = fallback.id + yield* session.updateMessage(ctx.assistantMessage) + yield* attempt(fallback) + }) + + return yield* Effect.gen(function* () { + yield* attempt(streamInput.model).pipe( + Effect.catchIf((error) => SessionRetry.billingBlocked(parse(error)), failover), Effect.catch(halt), Effect.ensuring(cleanup()), ) @@ -705,6 +733,7 @@ export const node = LayerNode.make({ Snapshot.node, Agent.node, LLM.node, + Provider.node, Permission.node, Plugin.node, SessionSummary.node, diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 1b58b5c9..74a04070 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -169,6 +169,10 @@ const layer = Layer.effect( Effect.gen(function* () { const status = yield* SessionStatus.Service const sessions = yield* Session.Service + // Sessions whose engagement picker chose "+ New engagement": naming is + // DEFERRED to the agent (it knows the target from the conversation) — this + // in-process set keeps the directive injected until the engagement exists. + const pendingNewEngagement = new Set() const agents = yield* Agent.Service const provider = yield* Provider.Service const processor = yield* SessionProcessor.Service @@ -1139,19 +1143,51 @@ const layer = Layer.effect( const ctx = yield* InstanceState.context let structured: unknown let step = 0 + // Overflow-recovery attempts for this run: a turn that failed with a + // context-overflow error compacts once and retries. A second consecutive + // overflow means compaction cannot shrink the prompt — fail cleanly + // instead of compacting in a loop. + let overflowCompactions = 0 const session = yield* sessions.get(sessionID).pipe(Effect.orDie) - // Auto-load engagement: .selected file (from TUI dialog) > .last fallback + // Apply a pending engagement selection from the TUI /engagement + // picker first (one-shot .selected file): it may switch AWAY from the + // in-memory engagement, not just fill an empty slot. Falls back to the + // in-memory engagement, then to .last on a fresh process. yield* Effect.gen(function* () { - const current = yield* engagement.get() - if (current) return const selected = yield* engagement.readSelected() - if (selected === "__none__") return - if (selected === "__new__") return + if (selected === "__none__") { + yield* engagement.unload() + return + } + if (selected === "__new__") { + // "+ New engagement" from the picker: do NOT create anything here. + // Directory-derived names are junk ("opencode-2026-10"); the agent + // knows the target from the conversation, so it creates (and names) + // the engagement on this turn, subject to user approval. Unload any + // active engagement first so nothing is recorded into the wrong one + // before the new engagement exists. + yield* engagement.unload() + pendingNewEngagement.add(sessionID) + return + } if (selected) { - yield* engagement.load(selected) + const existing = yield* engagement.listEngagements() + // "__new__:" comes from the picker's + New Engagement flow; + // a directory literally named that wins (created outside the TUI). + const isNew = selected.startsWith("__new__:") && !existing.includes(selected) + const name = isNew ? selected.slice("__new__:".length).trim() : selected + if (!name) return + const current = yield* engagement.get() + if (current?.name === name) return + if (existing.includes(name)) { + yield* engagement.load(name) + return + } + if (isNew) yield* engagement.create(name) return } + if (yield* engagement.get()) return const lastName = yield* engagement.lastEngagement() if (lastName) yield* engagement.load(lastName) }).pipe(Effect.ignore) @@ -1357,7 +1393,7 @@ const layer = Layer.effect( yield* plugin.trigger("experimental.chat.messages.transform", {}, { messages: msgs }) - const [skills, env, instructions, mcpInstructions, modelMsgs, engagementCtx, kernel, knowledgeCtx] = yield* Effect.all([ + const [skills, env, instructions, mcpInstructions, modelMsgs, engagementCtx, kernel, knowledgeCtx, customPrompts] = yield* Effect.all([ sys.skills(agent), sys.environment(model), instruction.system().pipe(Effect.orDie), @@ -1366,7 +1402,24 @@ const layer = Layer.effect( Effect.gen(function* () { try { const state = yield* engagement.get() - if (!state) return undefined + if (!state) { + if (!pendingNewEngagement.has(sessionID)) return undefined + // The user asked for a NEW engagement and none is loaded yet. + // The agent creates + names it (target-derived), one-keystroke + // approval; this directive survives until the engagement exists. + return { + volatile: [ + "", + 'The user chose "+ New engagement" and none is loaded. Create it with state_update (action: "create_engagement") BEFORE any other state writes this turn.', + "Name it from the target/product you are working on: lowercase, hyphenated, product-first, include the program/client name when known, ending in -YYYY-MM — e.g. \"okta-bugcrowd-2026-10\", \"mattermost-mbb-2026-10\", \"firedancer-2026-10\".", + "NEVER derive the name from the working directory (no \"opencode-2026-10\" junk) and never use generic words (engagement/target/test). NEVER ask the user to name it — they approve creation with one keystroke.", + "If the target is not yet clear from the conversation, ask WHAT we are testing (not what to call it) and create the engagement the moment it is.", + "", + ].join("\n"), + static: "", + } + } + pendingNewEngagement.delete(sessionID) // Orchestration bookkeeping (task graph, live subagents, user // command hints) is a coordinator concern — injecting it into // every focused subagent's turn is pure noise. See redesign QW2. @@ -1693,11 +1746,13 @@ const layer = Layer.effect( }), sys.kernel(agent), sys.knowledge(), + sys.custom().pipe(Effect.catch(() => Effect.succeed([]))), ]) // Static prefix only — the volatile engagement state is passed // separately as `volatileSystem` so this block stays cacheable // across turns (see redesign QW1). Ordered most-stable first. const system = [ + ...(customPrompts ? customPrompts : []), ...env, // Shared operator-protocol kernel (P1) — one copy for every agent, // on the cached prefix; specialty prompts no longer repeat it. @@ -1729,6 +1784,11 @@ const layer = Layer.effect( toolChoice: format.type === "json_schema" ? "required" : undefined, }) + // A turn that completed (success or any other error) means the next + // overflow may compact again; only back-to-back overflow failures + // count toward the loop guard below. + if (handle.message.finish) overflowCompactions = 0 + if (structured !== undefined) { handle.message.structured = structured handle.message.finish = handle.message.finish ?? "stop" @@ -1762,12 +1822,29 @@ const layer = Layer.effect( if (result === "stop") return "break" as const if (result === "compact") { + // `!handle.message.finish` = the turn died from a context-overflow + // error (reactive recovery), as opposed to a proactive compaction. + const reactive = !handle.message.finish + if (reactive && overflowCompactions >= 1) { + const error = new SessionV1.ContextOverflowError({ + message: + "The prompt still exceeds the provider's per-request size limit after compaction. " + + "Start a new session, shorten the message, or switch to a model with a larger limit.", + }) + handle.message.error = error.toObject() + handle.message.finish = "error" + yield* sessions.updateMessage(handle.message) + yield* events.publish(Session.Event.Error, { sessionID, error: handle.message.error }) + yield* status.set(sessionID, { type: "idle" }) + return "break" as const + } + if (reactive) overflowCompactions++ yield* compaction.create({ sessionID, agent: lastUser.agent, model: lastUser.model, auto: true, - overflow: !handle.message.finish, + overflow: reactive, }) } return "continue" as const diff --git a/packages/opencode/src/session/prompt/code-audit.txt b/packages/opencode/src/session/prompt/code-audit.txt new file mode 100644 index 00000000..d0c040f4 --- /dev/null +++ b/packages/opencode/src/session/prompt/code-audit.txt @@ -0,0 +1,51 @@ +You are a Code Auditor / vulnerability-research subagent. Domain: finding NOVEL bugs in a target's own source or binaries — the discipline that produces new CVEs, not the one that reuses them. (In your context: the Operator Protocol + specialist-common rules. This file adds the research playbook. You are the counterpart to exploiter/exploit_dev: they weaponize KNOWN bugs; you discover UNKNOWN ones.) + +# The mindset shift +The rest of the engagement runs "nuclei-first, known-CVE PoC-fetch-and-vet." You invert it: **no public CVE ≠ no bug.** You are called when the target runs software whose source or binaries you can obtain — an in-scope open-source dependency at a specific version, the client's own application code, a custom service, an appliance firmware. Your job is to read it, reason about its attack surface, and find the flaw nobody has reported yet. nginx2root was not found with a scanner; it was found by reading nginx's request/config parsing and diffing a fix. That is this agent's work. + +# What you excel at +Source audit (C/C++/Rust/Go/Python/PHP/JS/Java) · taint tracing source→sink · variant analysis (find siblings of a known bug pattern) · patch-diffing / n-day→variant (the highest-hit-rate path) · fuzz-harness bring-up for parsers and format handlers · attack-surface mapping. + +# Where to look first — target selection is most of the hit-rate +Novel bugs cluster. Spend your budget here, in order: +- **Complex, cross-boundary, rarely-exercised code** — JIT / intrinsics / hand-written asm fast paths, protocol state machines, flow-control accounting. (java4shell: an AVX-512 Base64 intrinsic reached only after JIT, for one input shape — ordinary tests never hit it.) +- **Object lifecycle** — alloc/free/reuse, cleanup callbacks, reusable-connection queues, teardown races → use-after-free. (nginx2root: 4 UAFs across resolver / reusable HTTP/2 conn / QUIC teardown / mail auth — all lifecycle.) +- **Length / integer / index math** — size arithmetic, signed↔unsigned casts, off-by-one, negative lengths → OOB read/write. (nginx2root CVE-2026-123007: HTTP/2 window underflow → near-2^64 memcpy.) +- **Untrusted parsers / deserializers / format loaders** — the classic surface; if there's no obvious logic bug, fuzz it. +- **Interactions between individually-well-tested features** — the flaw is rarely in one function; it's in how two correct features compose (flow control × cleanup, subrequests × connection draining). These survive a decade precisely because each half looks fine in isolation. +"Heavily audited" is a reason to look, not to skip: these targets had thousands of eyes and the bugs were still there. + +# What to hand off (be honest) +Weaponizing a memory-corruption primitive (ROP/heap grooming/kernel LPE) → exploit_dev or the kernel agent. You find and PROVE-reachable the bug; they build the reliable exploit. A confirmed, reachable sink with a controllable input is your finished deliverable even without a full RCE PoC. + +# Workflow +1. **Obtain + pin** — get the exact in-scope version's source (git clone at the tag, package source, extracted firmware) into the engagement workdir. Record the version — a bug only matters against what the target actually runs. +2. **Map attack surface** — enumerate UNTRUSTED entry points and dangerous sinks, then connect them. Entry: request/protocol parsers, file/format loaders, deserializers, auth/session handling, template/command execution, path handling. Sinks: `system`/`exec`/`popen`, `memcpy`/`strcpy`/pointer arithmetic (C/C++), `pickle`/`unserialize`/`readObject`, SQL/template interpolation, `../` path joins. Use grep/glob/read to build the map; note which sinks are reachable from an entry without passing a sanitizer. +3. **SAST pass** — run Semgrep (`semgrep --config auto --json -o out.json `, or a targeted ruleset / your own rule for a specific pattern), then `semgrep_parse` to fold leads into state. Treat every hit as a LEAD, not a bug. +4. **Variant analysis + patch-diff** — the fastest route to a real finding. For a known CVE or a suspicious commit: fetch the vulnerable and fixed versions, `git log`/`git diff` the security-relevant change, and hunt (a) incomplete fixes, (b) the same bug pattern in sibling code paths the patch didn't touch. Write a Semgrep rule for the pattern and sweep the whole tree. +5. **Fuzz the parsers** — when the surface is a parser/format/protocol handler, build a minimal harness (libFuzzer/AFL++ for C/C++, Atheris for Python, go-fuzz for Go), compile with ASAN/UBSAN, run time-boxed, then triage crashes: reproduce, dedupe by crash site, minimize. One reproducible ASAN crash from untrusted input is a finding. +6. **Trace + PROVE** — for each lead, manually trace input→sink and establish reachability: can an unauthenticated (or in-scope) actor drive data to the sink without a sanitizer neutralizing it? A lead is not a finding until you can point to the concrete source, the path, and the sink, with evidence. + +# Coverage + validation discipline — this separates a real audit from a lucky grep +Three rules, and they matter more than any single clever grep: +1. **Coverage ledger — no area skipped.** After mapping, write the attack surface as a list of UNITS (each parser, handler, deserializer, lifecycle path) and track per unit what you checked. When you think you're done, sweep the ledger and name the units you NEVER hunted — then hunt them. Tunnel vision (deep on one file, blind to the rest) is the #1 way real bugs get missed; the decade-old nginx/JDK bugs sat in units nobody revisited. +2. **Finder ≠ verifier — try to DISPROVE.** The agent that found a lead never confirms it. Hand each candidate to a fresh verifier — spawn `critic`, or re-examine with clean context — whose job is to KILL it: find the sanitizer, the bounds check, the unreachable guard. Verdicts: CONFIRMED (survived a real disprove attempt) / NEEDS_MORE_EVIDENCE (name the one unresolved fact) / FALSE_POSITIVE (disproved). Record all three via state_update so nothing is re-audited or rubber-stamped. +3. **Multi-pass — one sweep finds ~half.** A single hunt pass misses most bugs. Re-run against the same pinned source, reusing the ledger to target the gaps the last pass left, until passes stop producing new candidates. + +Build / fuzz / PoC target code ONLY inside an isolated sandbox (the drost container, or a disposable VM) — never a live production host, never your own environment. If you cannot sandbox it, keep the finding suspected / NEEDS_MORE_EVIDENCE rather than confirming it. + +# A finding is a LEAD until reachability is proven +Static match, fuzz crash, or pattern hit = SUSPECTED. Promote to confirmed only with a reachability argument: entry point → code path → sink, sanitizers ruled out, plus a trigger artifact (crash repro, a value reaching the sink, a dumped secret). Prioritize by reachability-from-untrusted-input, not by SAST severity — an unreachable "critical" is noise; a reachable "medium" in a parser is the nginx2root pattern. + +# Tools +`semgrep_parse` (fast intra-file SAST leads → state) · `codeql_parse` (CROSS-FUNCTION dataflow leads — UAF/integer/OOB across function boundaries, the nginx2root shape semgrep structurally misses → state) · `patch_diff` (n-day→variant: a fix diff → sibling/incomplete-fix sweeps) · grep/glob/read (manual audit — your primary instrument) · shell (run semgrep/codeql/joern, clone source, `git diff` for patch-diffing, build+run fuzz harnesses) · `ensure_tools` (installs semgrep/codeql/joern) · websearch/webfetch (advisories, the fix commit, affected-version ranges, prior research) · state_update/state_query · scope_check before pulling or testing anything new. + +# State Recording — CRITICAL +Record EVERY outcome via state_update as it happens: +- Reachable, proven bug → add_vuln (confirmed) with file:line, the source→sink path, and the trigger artifact as evidence +- Unproven lead worth tracing → add_vuln (suspected) with the location and why it may be reachable +- Dead end (sink sanitized / unreachable / false positive) → record in your dead_ends so it isn't re-audited +A subagent with zero state_update calls is a FAILED subagent — and `semgrep_parse` with auto_update already writes suspected leads, so at minimum reconcile them (promote or kill) before you finish. + +# Boundaries +Audit ONLY in-scope software (scope_check first). Keep obtained source and fuzz artifacts inside the engagement workdir — do not exfiltrate a client's source elsewhere. Building and fuzzing happen locally; never point a destructive fuzzer at a live production service. Hand memory-corruption weaponization to exploit_dev. Load the `source-audit` research skill (and the matching `svc-*` skill) for the target. diff --git a/packages/opencode/src/session/prompt/critic.txt b/packages/opencode/src/session/prompt/critic.txt index c055d41a..6af3e8e2 100644 --- a/packages/opencode/src/session/prompt/critic.txt +++ b/packages/opencode/src/session/prompt/critic.txt @@ -7,6 +7,13 @@ A finding is CONFIRMED only if its evidence contains a reproduced impact artifac - "nuclei/nmap-script says VULNERABLE", a version-number match with no test, a reflected-but-not-executed payload, or a described-but-not-shown result → NOT confirmed → verdict NEEDS_MORE_EVIDENCE, and name the EXACT missing artifact. - Your verdict drives state: CONFIRMED → coordinator sets the vuln `confirmed`; FALSE_POSITIVE → `resolved`/downgrade; NEEDS_MORE_EVIDENCE → stays `suspected`. This is the guard against hallucinated / unproven findings (a scanner hit is a lead, not proof). +## PROOF standard for a SOURCE-AUDIT / code finding +A code finding (a bug found by reading source or binaries — the `code_auditor` discipline — not by hitting a live host) is CONFIRMED only with BOTH: +1. **A complete source→sink trace.** The exact untrusted **entry point** (`file:line`), the **code path** to the **sink** (`file:line`), and an argument that the sanitizers / bounds checks / guards on that path do NOT neutralize. A semgrep/SAST hit, or a dangerous sink with no traced source, → NEEDS_MORE_EVIDENCE (name the missing half: the source, or the reason the guard doesn't apply). +2. **A bounded observed result.** A reproducible ASAN/UBSAN crash whose stack ends at the sink, a value demonstrably reaching the sink (logged/printed), dumped out-of-bounds bytes, or `id`/file-read bytes if it already reaches RCE. A one-off crash with no minimized repro, or a reachability argument with no trigger artifact, → NEEDS_MORE_EVIDENCE. + +Try to DISPROVE first: hunt the sanitizer, the length check, the unreachable guard that kills it — only a candidate that survives a genuine disprove attempt is CONFIRMED. **Reachability, not paper CVSS, drives severity**: a reachable-pre-auth medium outranks an unreachable critical. If the finding required building or running target code and you cannot confirm it ran in an **isolated sandbox** (drost container / disposable VM), do NOT confirm — unsandboxed execution output is untrusted → NEEDS_MORE_EVIDENCE. + # Validation Methodology For each finding, evaluate in this order: diff --git a/packages/opencode/src/session/retry.ts b/packages/opencode/src/session/retry.ts index 1fad4170..fad53879 100644 --- a/packages/opencode/src/session/retry.ts +++ b/packages/opencode/src/session/retry.ts @@ -163,6 +163,24 @@ export function retryable(error: Err, provider: string) { return undefined } +// Billing policy (see OPENCODE_FREE_TIER.md): requests sent to OpenCode Zen can +// be refused for account-level reasons no retry can fix — the account is +// unfunded (402), the free-tier gate has closed (403), or the free quota is +// exhausted (`FreeUsageLimitError`, which only reaches a caller after `policy` +// has spent its retry attempts). Session surfaces use this to route the request +// once to the OpenRouter fallback instead of failing the session. +export function billingBlocked(error: Err): boolean { + if (!SessionV1.APIError.isInstance(error)) return false + if (error.data.statusCode === 402 || error.data.statusCode === 403) return true + const body = error.data.responseBody?.toLowerCase() ?? "" + return ( + body.includes("freeusagelimiterror") || + body.includes("gousagelimiterror") || + body.includes("insufficient") || + body.includes("free tier") + ) +} + function str(value: unknown) { if (value === undefined || value === null) return "" return String(value) diff --git a/packages/opencode/src/session/session.ts b/packages/opencode/src/session/session.ts index 3c478ce0..14091625 100644 --- a/packages/opencode/src/session/session.ts +++ b/packages/opencode/src/session/session.ts @@ -244,6 +244,13 @@ export const Info = Schema.Struct({ }).annotate({ identifier: "Session" }) export type Info = Types.DeepMutable> +export type CostTree = { + root: SessionID + sessions: Array<{ id: SessionID; parentID?: SessionID; cost: number; tokens: NonNullable }> + cost: number + tokens: NonNullable +} + export const ProjectInfo = Schema.Struct({ id: ProjectV2.ID, name: optional(Schema.String), @@ -449,6 +456,10 @@ export interface Interface { readonly diff: (sessionID: SessionID) => Effect.Effect readonly messages: (input: { sessionID: SessionID; limit?: number }) => Effect.Effect readonly children: (parentID: SessionID) => Effect.Effect + // Self cost of `sessionID` plus every descendant session (subagents, + // recursively) — the "full cost including subagents" view. Self cost per + // session is what the projector accumulates; this only sums on read. + readonly costTree: (sessionID: SessionID) => Effect.Effect readonly remove: (sessionID: SessionID) => Effect.Effect readonly updateMessage: (msg: T) => Effect.Effect readonly removeMessage: (input: { sessionID: SessionID; messageID: MessageID }) => Effect.Effect @@ -605,6 +616,55 @@ const layer: Layer.Layer< return rows.map(fromRow) }) + // Walk up to the root (parent sessions may themselves be subagents), then + // breadth-first through descendants. Both walks are per-level queries so a + // tree is O(depth) round trips, not O(sessions). + const costTree = Effect.fn("Session.costTree")(function* (sessionID: SessionID) { + const start = yield* get(sessionID) + let root = start + while (root.parentID) { + const parent = yield* db + .select() + .from(SessionTable) + .where(eq(SessionTable.id, root.parentID)) + .get() + .pipe(Effect.orDie) + if (!parent) break + root = fromRow(parent) + } + + const nodes: CostTree["sessions"] = [] + const total: CostTree["tokens"] = { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } } + let cost = 0 + const visit = (info: Info) => { + const tokens = info.tokens ?? EmptyTokens + nodes.push({ id: info.id, parentID: info.parentID, cost: info.cost ?? 0, tokens }) + cost += info.cost ?? 0 + total.input += tokens.input + total.output += tokens.output + total.reasoning += tokens.reasoning + total.cache.read += tokens.cache.read + total.cache.write += tokens.cache.write + } + visit(root) + let frontier: SessionID[] = [root.id] + while (frontier.length > 0) { + const rows = yield* db + .select() + .from(SessionTable) + .where(inArray(SessionTable.parent_id, frontier)) + .all() + .pipe(Effect.orDie) + const level = rows.map(fromRow) + frontier = [] + for (const info of level) { + visit(info) + frontier.push(info.id) + } + } + return { root: root.id, sessions: nodes, cost, tokens: total } satisfies CostTree + }) + const remove: Interface["remove"] = Effect.fnUntraced(function* (sessionID: SessionID) { const session = yield* get(sessionID) try { @@ -925,6 +985,7 @@ const layer: Layer.Layer< diff, messages, children, + costTree, remove, updateMessage, removeMessage, diff --git a/packages/opencode/src/session/system.ts b/packages/opencode/src/session/system.ts index 52a0c00e..be766ea3 100644 --- a/packages/opencode/src/session/system.ts +++ b/packages/opencode/src/session/system.ts @@ -24,6 +24,8 @@ import { MCP } from "@/mcp" import { PermissionV1 } from "@pentestcode/core/v1/permission" import { EngagementStore } from "@pentestcode/core/engagement/store" import { KnowledgeStore } from "@pentestcode/core/knowledge/store" +import { Config } from "@/config/config" +import { Instruction } from "./instruction" export function provider(model: Provider.Model) { // PentestCode: always use the pentest prompt as the base, regardless of model @@ -36,6 +38,7 @@ export interface Interface { readonly skills: (agent: Agent.Info) => Effect.Effect readonly mcp: (agent: Agent.Info, permission?: PermissionV1.Ruleset) => Effect.Effect readonly knowledge: () => Effect.Effect + readonly custom: () => Effect.Effect } export class Service extends Context.Service()("@pentestcode/SystemPrompt") {} @@ -48,6 +51,8 @@ const layer = Layer.effect( const locations = yield* LocationServiceMap.Service const engagement = yield* EngagementStore.Service const knowledgeStore = yield* KnowledgeStore.Service + const config = yield* Config.Service + const instruction = yield* Instruction.Service return Service.of({ // Shared operator-protocol kernel injected for EVERY agent (coordinator + @@ -138,6 +143,29 @@ const layer = Layer.effect( ].join("\n") }), + custom: Effect.fn("SystemPrompt.custom")(function* () { + const result: string[] = [] + // Get from environment variables + for (const env of [process.env.OPENCODE_SYSTEM_PROMPT, process.env.PENTESTCODE_SYSTEM_PROMPT, process.env.CUSTOM_SYSTEM_PROMPT]) { + if (env && env.trim()) result.push(env) + } + // Get from config.instructions that are inline content + try { + const cfg = yield* config.get() + if (cfg.instructions) { + for (const raw of cfg.instructions) { + if (typeof raw !== "string") continue + if (raw.startsWith("https://") || raw.startsWith("http://")) continue + // Check if it's likely a file path or just content + if (raw.includes("\n") || raw.length > 200) { + result.push(raw) + } + } + } + } catch {} + return result + }), + mcp: Effect.fn("SystemPrompt.mcp")(function* (agent: Agent.Info, permission?: PermissionV1.Ruleset) { const ruleset = Permission.merge(agent.permission, permission ?? []) const instructions = (yield* mcp.instructions()).filter( @@ -168,7 +196,7 @@ const locationServiceMapNode = LayerNode.make({ export const node = LayerNode.make({ service: Service, layer: layer, - deps: [Skill.node, MCP.node, locationServiceMapNode, EngagementStore.node, KnowledgeStore.node], + deps: [Skill.node, MCP.node, locationServiceMapNode, EngagementStore.node, KnowledgeStore.node, Config.node, Instruction.node], }) export * as SystemPrompt from "./system" diff --git a/packages/opencode/src/session/tools.ts b/packages/opencode/src/session/tools.ts index aecf8a32..ee530ee7 100644 --- a/packages/opencode/src/session/tools.ts +++ b/packages/opencode/src/session/tools.ts @@ -455,7 +455,7 @@ export const resolve = Effect.fn("SessionTools.resolve")(function* (input: { } for (const [key, entry] of Object.entries(yield* mcp.tools())) { - const item = McpCatalog.convertTool(entry.def, entry.client, entry.timeout) + const item = entry.tool ?? McpCatalog.convertTool(entry.def, entry.client, entry.timeout) const execute = item.execute if (!execute) continue diff --git a/packages/opencode/src/tool/codeql-parse.ts b/packages/opencode/src/tool/codeql-parse.ts new file mode 100644 index 00000000..97c9e199 --- /dev/null +++ b/packages/opencode/src/tool/codeql-parse.ts @@ -0,0 +1,392 @@ +import { Effect, Schema } from "effect" +import { EngagementStore } from "@pentestcode/core/engagement/store" +import { EngagementSchema } from "@pentestcode/core/engagement/schema" +import { ScopeMatcher } from "@pentestcode/core/engagement/scope-matcher" +import { PentestEvent } from "@pentestcode/schema/pentest-event" +import { EventV2Bridge } from "@/event-v2-bridge" +import { FSUtil } from "@pentestcode/core/fs-util" +import DESCRIPTION from "./codeql-parse.txt" +import * as Tool from "./tool" + +// CodeQL (and other SARIF emitters: Joern's --format sarif, CodeChecker) is the +// cross-function layer semgrep cannot reach: it follows a value across function +// and file boundaries and reports the whole source→sink DATAFLOW PATH. That path +// is exactly the shape of nginx2root-class bugs — a pointer freed in one handler +// and used in another, or a length that wraps across a call. We parse the SARIF, +// fold each result into state as a `suspected` lead, and keep the full dataflow +// path as evidence so the code_auditor can trace and PROVE reachability (CodeQL +// proves the PATH exists; it does NOT prove the sink is driven by untrusted input +// or that no guard neutralizes it — that is still the auditor's job). + +export const Parameters = Schema.Struct({ + input: Schema.String.annotate({ + description: "CodeQL/Joern SARIF (v2.1.0) output text, or a file path to read it from (e.g. results.sarif).", + }), + host: Schema.optional(Schema.String).annotate({ + description: + "Target this code runs on (IP/hostname), so findings attach to that host. Omit for a pure source audit not yet mapped to a live target; findings then attach to the synthetic host 'source-audit'.", + }), + auto_update: Schema.optional(Schema.Boolean).annotate({ + description: "Add discovered findings to engagement state as suspected vulns (default: true)", + }), + min_severity: Schema.optional(Schema.String).annotate({ + description: "Drop findings below this severity: critical|high|medium|low|info (default: low)", + }), +}) + +const CODE_HOST = "source-audit" +const SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"] + +interface SarifRegion { + startLine?: number + endLine?: number +} +interface SarifPhysicalLocation { + artifactLocation?: { uri?: string } + region?: SarifRegion +} +interface SarifLocation { + physicalLocation?: SarifPhysicalLocation + message?: { text?: string } +} +interface SarifThreadFlow { + locations?: Array<{ location?: SarifLocation }> +} +interface SarifCodeFlow { + threadFlows?: SarifThreadFlow[] +} +interface SarifResult { + ruleId?: string + ruleIndex?: number + level?: string + message?: { text?: string } + locations?: SarifLocation[] + codeFlows?: SarifCodeFlow[] + properties?: Record +} +interface SarifRule { + id?: string + name?: string + shortDescription?: { text?: string } + helpUri?: string + properties?: { "security-severity"?: string | number; tags?: string[] } +} +interface SarifRun { + tool?: { driver?: { rules?: SarifRule[] } } + results?: SarifResult[] +} +interface SarifLog { + runs?: SarifRun[] +} + +interface ParsedFinding { + ruleId: string + shortRule: string + title: string + severity: string + path: string + line: number + message: string + flowPath: string + source: string + sink: string + steps: number + references: string[] + vulnId: string +} + +function looksLikeFilePath(input: string): boolean { + const trimmed = input.trimStart() + if (trimmed.startsWith("/") || trimmed.startsWith("./") || trimmed.startsWith("~/")) return true + if (/\.(sarif|json)$/i.test(trimmed.split("\n")[0]!.trim())) return true + return false +} + +function firstLine(s: string | undefined): string { + if (!s) return "" + return s.split("\n")[0]!.trim().slice(0, 240) +} + +function base(uri: string): string { + const clean = uri.replace(/^file:\/\//, "") + const parts = clean.split("/") + return parts[parts.length - 1] || clean +} + +function shortRuleName(ruleId: string): string { + const parts = ruleId.split("/") + return parts[parts.length - 1] || ruleId +} + +// CodeQL security queries carry a numeric `security-severity` (CVSS-like 0–10) on +// the rule. Prefer it; fall back to the SARIF `level` for queries without it. +function mapSeverity(securitySeverity: number | undefined, level: string | undefined): string { + if (securitySeverity !== undefined && Number.isFinite(securitySeverity)) { + if (securitySeverity >= 9.0) return "critical" + if (securitySeverity >= 7.0) return "high" + if (securitySeverity >= 4.0) return "medium" + if (securitySeverity > 0) return "low" + } + const lv = (level ?? "").toLowerCase() + if (lv === "error") return "high" + if (lv === "warning") return "medium" + if (lv === "note" || lv === "none") return "low" + return "info" +} + +function extractFlow(codeFlows: SarifCodeFlow[] | undefined): { + flowPath: string + source: string + sink: string + steps: number +} { + const locs = codeFlows?.[0]?.threadFlows?.[0]?.locations ?? [] + const points: string[] = [] + for (const l of locs) { + const p = l.location?.physicalLocation + const uri = p?.artifactLocation?.uri + const ln = p?.region?.startLine + if (!uri || !ln) continue + points.push(`${base(uri)}:${ln}`) + } + if (points.length === 0) return { flowPath: "", source: "", sink: "", steps: 0 } + const source = points[0]! + const sink = points[points.length - 1]! + // Keep the path readable: full when short, else head → … → tail. + let flowPath: string + if (points.length <= 8) flowPath = points.join(" → ") + else flowPath = [...points.slice(0, 3), `… (+${points.length - 6} steps)`, ...points.slice(-3)].join(" → ") + return { flowPath, source, sink, steps: points.length } +} + +export function parseSarif(content: string, minSeverity: string): ParsedFinding[] { + let parsed: SarifLog + try { + parsed = JSON.parse(content) as SarifLog + } catch { + return [] + } + const minIdx = SEVERITY_ORDER.indexOf(minSeverity) + const floor = minIdx === -1 ? SEVERITY_ORDER.length - 1 : minIdx + + const findings: ParsedFinding[] = [] + const seen = new Set() + + for (const run of parsed.runs ?? []) { + const rules = run.tool?.driver?.rules ?? [] + const byId = new Map() + for (const r of rules) if (r.id) byId.set(r.id, r) + + for (const res of run.results ?? []) { + const ruleId = res.ruleId ?? (res.ruleIndex !== undefined ? rules[res.ruleIndex]?.id : undefined) + if (!ruleId) continue + const rule = byId.get(ruleId) ?? (res.ruleIndex !== undefined ? rules[res.ruleIndex] : undefined) + + const loc = res.locations?.[0]?.physicalLocation + const path = loc?.artifactLocation?.uri ? base(loc.artifactLocation.uri) : "" + const fullPath = loc?.artifactLocation?.uri ?? "" + const line = loc?.region?.startLine ?? 0 + + const dedupKey = `${ruleId}:${fullPath}:${line}` + if (seen.has(dedupKey)) continue + seen.add(dedupKey) + + const secRaw = rule?.properties?.["security-severity"] ?? (res.properties?.["security-severity"] as string | number | undefined) + const sec = secRaw !== undefined ? Number(secRaw) : undefined + const severity = mapSeverity(sec, res.level) + if (SEVERITY_ORDER.indexOf(severity) > floor) continue + + const short = shortRuleName(ruleId) + const flow = extractFlow(res.codeFlows) + findings.push({ + ruleId, + shortRule: short, + title: firstLine(rule?.shortDescription?.text) || firstLine(res.message?.text) || short, + severity, + path: fullPath || path, + line, + message: res.message?.text ?? "", + flowPath: flow.flowPath, + source: flow.source, + sink: flow.sink, + steps: flow.steps, + references: rule?.helpUri ? [rule.helpUri] : [], + vulnId: `codeql-${short}-${(fullPath || path).replace(/[^a-zA-Z0-9]+/g, "_")}-L${line}`, + }) + } + } + + return findings +} + +export function formatOutput(findings: ParsedFinding[], host: string, autoUpdated: boolean): string { + const lines: string[] = [] + lines.push(`Parsed ${findings.length} CodeQL finding${findings.length !== 1 ? "s" : ""} (host: ${host})`) + lines.push("") + + const bySeverity: Record = {} + for (const f of findings) (bySeverity[f.severity.toUpperCase()] ??= []).push(f) + + for (const sev of SEVERITY_ORDER.map((s) => s.toUpperCase())) { + const group = bySeverity[sev] + if (!group || group.length === 0) continue + lines.push(`[${sev}] (${group.length})`) + for (const f of group) { + lines.push(` ${f.path}:${f.line} — ${f.title} (${f.shortRule})`) + if (f.flowPath) lines.push(` dataflow: ${f.flowPath}`) + } + lines.push("") + } + + lines.push( + "These are CROSS-FUNCTION DATAFLOW LEADS. CodeQL proved the path exists; it did NOT prove the source is", + "attacker-controlled or that the sink is reachable without a guard. Trace each path, confirm an untrusted", + "entry drives the source, and rule out sanitizers before marking confirmed. Prioritize by reachability.", + ) + if (autoUpdated) { + lines.push("") + lines.push(`[Auto-updated engagement state: ${findings.length} suspected finding(s) on host ${host}]`) + } else { + lines.push("") + lines.push("[Engagement state not updated (auto_update=false)]") + } + return lines.join("\n") +} + +export const CodeqlParseTool = Tool.define( + "codeql_parse", + Effect.gen(function* () { + const store = yield* EngagementStore.Service + const fs = yield* FSUtil.Service + const events = yield* EventV2Bridge.Service + + return { + description: DESCRIPTION, + parameters: Parameters, + execute: ( + params: { input: string; host?: string; auto_update?: boolean; min_severity?: string }, + _ctx: Tool.Context, + ) => + Effect.gen(function* () { + let content = params.input + const shouldUpdate = params.auto_update !== false + const minSeverity = (params.min_severity ?? "low").toLowerCase() + const host = (params.host ?? "").trim() || CODE_HOST + + if (looksLikeFilePath(content.trim())) { + const filePath = content.trim() + const exists = yield* fs.existsSafe(filePath) + if (exists) content = yield* fs.readFileString(filePath) + } + + const findings = parseSarif(content, minSeverity) + + if (findings.length === 0) { + return { + title: "codeql parse", + metadata: { findings: 0, high_critical: 0, host, auto_updated: false }, + output: + "No findings parsed from the SARIF input. Verify it is CodeQL/Joern SARIF v2.1.0 (`codeql database analyze --format=sarifv2.1.0`); the top-level object must have a `runs` array with `results`. If the scan produced only notifications, the query suite likely matched nothing at this min_severity.", + } + } + + let outOfScope = false + if (shouldUpdate) { + const state = yield* store.get() + if ( + host !== CODE_HOST && + state && + state.scope.targets.length > 0 && + state.mode !== "free" && + !ScopeMatcher.checkScope(host, state.scope).inScope + ) { + outOfScope = true + } + + if (!outOfScope) { + yield* store.addHost(host, { ip: host }) + + for (const f of findings) { + const location = `${f.path}:${f.line}` + const evidence = [ + `location: ${location}`, + `rule: ${f.ruleId}`, + f.flowPath ? `dataflow(${f.steps}): ${f.flowPath}` : "", + f.source ? `source: ${f.source}` : "", + f.sink ? `sink: ${f.sink}` : "", + ] + .filter(Boolean) + .join(" | ") + + const evidenceItem = { + tool: "codeql", + command: `codeql database analyze --format=sarifv2.1.0 (rule ${f.ruleId})`, + output: evidence, + timestamp: new Date().toISOString(), + reasoning: f.flowPath + ? `Cross-function dataflow ${f.source} → ${f.sink} via rule ${f.ruleId}. The PATH exists; untrusted-input reachability and sanitizer-absence NOT yet verified.` + : `CodeQL rule ${f.ruleId} matched at ${location}. Source→sink reachability NOT yet verified.`, + source_agent: "code_auditor", + attempt_number: 1, + verification_status: "unverified" as const, + } + const conf = EngagementSchema.deriveConfidence({ + status: "suspected", + evidence_items: [evidenceItem], + }) + + yield* store.addVuln(host, { + id: f.vulnId, + title: f.title, + severity: f.severity as any, + status: "suspected", + confidence: conf, + description: `CodeQL cross-function dataflow lead (${f.ruleId}) at ${location}.${ + f.flowPath ? ` Path: ${f.flowPath}.` : "" + } ${firstLine(f.message)} Trace the path, confirm untrusted input drives the source, and rule out sanitizers before confirming.`, + evidence, + evidence_items: [{ ...evidenceItem, confidence: conf }], + references: f.references, + }) + + if (state) { + yield* events.publish(PentestEvent.VulnFound, { + timestamp: Date.now(), + engagementID: state.id, + hostIp: host, + title: f.title, + severity: f.severity, + status: "suspected", + }) + } + } + + const updatedState = yield* store.get() + if (updatedState) yield* store.save(updatedState) + } + } + + let output = formatOutput(findings, host, shouldUpdate && !outOfScope) + if (outOfScope) { + output += `\n\n[SCOPE] Host ${host} is out of scope — findings parsed but NOT added to engagement state.` + } + + const highSev = findings.filter((f) => f.severity === "critical" || f.severity === "high") + if (shouldUpdate && !outOfScope && highSev.length > 0) { + output += `\n\n[Next] ${highSev.length} high/critical dataflow lead(s) recorded as SUSPECTED. Trace each source→sink path; spawn "critic" to disprove before any lead is reported as confirmed.` + } + + return { + title: `codeql: ${findings.length} dataflow leads`, + metadata: { + findings: findings.length, + high_critical: highSev.length, + host, + auto_updated: shouldUpdate && !outOfScope, + }, + output, + } + }).pipe(Effect.orDie), + } + }), +) diff --git a/packages/opencode/src/tool/codeql-parse.txt b/packages/opencode/src/tool/codeql-parse.txt new file mode 100644 index 00000000..be3f3c14 --- /dev/null +++ b/packages/opencode/src/tool/codeql-parse.txt @@ -0,0 +1,22 @@ +Parse CodeQL / Joern SARIF output and fold CROSS-FUNCTION dataflow leads into engagement state. This is the layer semgrep cannot reach: CodeQL follows a value across function and file boundaries and reports the whole source→sink path — exactly the shape of nginx2root-class bugs (a pointer freed in one handler and used in another; a length that wraps across a call). Run CodeQL via the shell first, then pass the SARIF here. + +Input: CodeQL/Joern SARIF v2.1.0 text, or a file path to it (e.g. results.sarif). The top-level object must have a `runs` array whose `results` carry ruleId, a primary location, and (for dataflow queries) `codeFlows` — the step-by-step path this tool extracts as the finding's evidence. + +How to produce the SARIF (do this in the shell, in the sandbox/container, then parse the output here): + # C/C++ (nginx2root's language) — build a DB, then run the memory + security suite + codeql database create db --language=cpp --command='make -j' # or --build-mode=none for header-only + codeql database analyze db codeql/cpp-queries:codeql-suites/cpp-security-extended.qls \ + --format=sarifv2.1.0 --output=results.sarif + # then: codeql_parse input=results.sarif host= +Other languages: swap --language (java|go|javascript|python|...) and the matching -security-extended suite. The high-signal memory queries are cpp/use-after-free, cpp/double-free, cpp/overflow-buffer, cpp/integer-overflow-tainted, cpp/unbounded-write. +Joern alternative (no build needed): import the source, run a cross-function reachableByFlows query, and `joern-export`/the SARIF formatter to emit SARIF — then parse it here the same way. + +Each result is recorded as status=suspected / verification=unverified, carrying the full dataflow path (source → … → sink) in its evidence. CodeQL proves the PATH exists; it does NOT prove the source is attacker-controlled or that the sink is reachable without a guard — high/critical leads are flagged for the code_auditor to trace and PROVE (and for critic to disprove) before anything is confirmed. + +Severity: taken from the rule's numeric `security-severity` (>=9 critical, >=7 high, >=4 medium, >0 low); falls back to SARIF level (error→high, warning→medium, note→low). Use min_severity to drop noise (default: low). Deduplicates by (ruleId, path, line). + +Params: +- host: the target this code runs on (IP/hostname) so leads attach to that host. Omit for a pure source audit — leads then attach to the synthetic host 'source-audit'. +- auto_update=false to parse without modifying state. + +This tool does NOT run CodeQL. Invoke CodeQL/Joern via the shell first, then parse the SARIF output here. diff --git a/packages/opencode/src/tool/ensure-tools.ts b/packages/opencode/src/tool/ensure-tools.ts index 7189b031..fa1f3984 100644 --- a/packages/opencode/src/tool/ensure-tools.ts +++ b/packages/opencode/src/tool/ensure-tools.ts @@ -108,9 +108,24 @@ const TOOLS: Record; ca install: { pip: "pip install wfuzz" }, category: "web", }, + semgrep: { + check: "semgrep", + install: { pipx: "pipx install semgrep", pip: "pip install semgrep", brew: "brew install semgrep" }, + category: "audit", + }, + codeql: { + check: "codeql", + install: { brew: "brew install codeql" }, + category: "audit", + }, + joern: { + check: "joern", + install: { sh: "curl -L https://github.com/joernio/joern/releases/latest/download/joern-install.sh | sh" }, + category: "audit", + }, } -const CATEGORIES = ["scanning", "web", "recon", "ad", "brute", "pivot", "wordlists"] as const +const CATEGORIES = ["scanning", "web", "recon", "ad", "brute", "pivot", "wordlists", "audit"] as const export const Parameters = Schema.Struct({ action: Schema.Literals(["check", "install"]).annotate({ diff --git a/packages/opencode/src/tool/patch-diff.ts b/packages/opencode/src/tool/patch-diff.ts new file mode 100644 index 00000000..0cde885b --- /dev/null +++ b/packages/opencode/src/tool/patch-diff.ts @@ -0,0 +1,353 @@ +import { Effect, Schema } from "effect" +import DESCRIPTION from "./patch-diff.txt" +import * as Tool from "./tool" + +// patch_diff — the n-day → variant engine, the highest-hit-rate path in source +// auditing (one patch → bugs #2..N; cf. nginx2root's four sibling use-after-frees). +// Given a security FIX diff it structures the change and emits the artifacts for +// variant hunting: the vulnerable code shape, the guard the fix added, and +// ripgrep/semgrep sweeps to find sibling call sites that may have been left +// unpatched (incomplete-fix) or that share the pattern. +// +// It does NOT run git or semgrep. The agent fetches the diff (git diff / a commit +// .patch) and runs the emitted sweeps, then folds real hits into engagement state +// via semgrep_parse / state_update. Every emitted pattern is a STARTING point to +// refine, not a guaranteed-correct rule — reachability is still proven by hand. + +export const Parameters = Schema.Struct({ + action: Schema.Literals(["plan", "analyze"]).annotate({ + description: + "plan: given a CVE / repo / fix commit, emit the exact git commands to fetch the vulnerable+fixed source and produce the fix diff. analyze: given the unified diff of a security fix, extract the vulnerable shape and emit variant-hunt sweeps.", + }), + diff: Schema.optional(Schema.String).annotate({ + description: + "For action=analyze (required): the unified diff of the security fix — output of `git diff ~1 ` or a commit .patch. May be a path to a file containing it.", + }), + repo: Schema.optional(Schema.String).annotate({ + description: "For action=plan: the source repo URL or local path to clone/inspect.", + }), + fix_ref: Schema.optional(Schema.String).annotate({ + description: "For action=plan: the fix commit/tag/branch (the version that CONTAINS the fix).", + }), + vuln_ref: Schema.optional(Schema.String).annotate({ + description: "For action=plan: the vulnerable commit/tag the target actually runs (default: fix_ref~1).", + }), + cve: Schema.optional(Schema.String).annotate({ + description: "Optional CVE id — labels the n-day and seeds the advisory lookup in the plan.", + }), + lang: Schema.optional(Schema.String).annotate({ + description: "Source language hint (c|cpp|java|go|python|js|ts|php|rust) — tunes the generated semgrep -e pattern and ripgrep sweeps.", + }), +}) + +type Params = { + action: string + diff?: string + repo?: string + fix_ref?: string + vuln_ref?: string + cve?: string + lang?: string +} + +// Dangerous sinks worth sweeping for siblings. A fix near one of these marks the +// bug class; the sweep finds the other call sites that may lack the new guard. +const SINK_PATTERNS: Array<{ re: RegExp; label: string }> = [ + // Leading `[A-Za-z_]*` so wrapped variants match too (nginx `ngx_memcpy`, `ngx_cpymem`, `ngx_pfree`). + { re: /\b[A-Za-z_]*(memcpy|memmove|cpymem|strcpy|strncpy|strcat|strncat|sprintf|vsprintf|snprintf|alloca|memset|bcopy)\b/, label: "memory op → OOB" }, + { re: /\b[A-Za-z_]*(malloc|calloc|realloc|free|kfree|kmalloc|kzalloc|vfree|palloc|pnalloc)\b/, label: "alloc/free → UAF/double-free" }, + { re: /\b(system|popen|execve|execl|execlp|execv|execvp|ProcessBuilder)\b/, label: "command exec → RCE" }, + { re: /\bRuntime\.getRuntime\b/, label: "command exec → RCE" }, + { re: /\b(unserialize|readObject|ObjectInputStream|yaml\.load|Marshal\.load)\b/, label: "deserialization" }, + { re: /\bpickle\.loads?\b/, label: "deserialization" }, + { re: /\b(eval|exec)\s*\(/, label: "dynamic eval" }, + { re: /(\.\.\/|\bpath\.join\b|os\.path\.join|\bFile\s*\()/, label: "path handling → traversal" }, + { re: /\b(query|execute|executeQuery|prepareStatement)\s*\(/, label: "SQL/query sink" }, +] + +// Hints that an ADDED line is the guard the fix introduced. +const GUARD_HINTS: Array<{ re: RegExp; label: string }> = [ + { re: /\b(len|length|size|count|bound|max|min|limit|remain|avail|cap)\b/i, label: "length/size bound" }, + { re: /\b(NULL|nullptr|null|None|nil)\b/, label: "null check" }, + { re: /\b(sanitiz|escap|valid|verify|clamp|assert|guard|bounds?)/i, label: "sanitizer/validation" }, + { re: /[<>]=?|==|!=/, label: "comparison/bounds check" }, + { re: /\b(return|goto|break|throw|abort|BUG_ON|WARN)\b/, label: "early-exit on bad input" }, +] + +const CODE_KEYWORDS = new Set([ + "if", "for", "while", "switch", "return", "sizeof", "else", "case", "do", "goto", + "typeof", "new", "delete", "and", "or", "not", "in", "is", "function", "def", "class", + "static", "const", "void", "int", "char", "unsigned", "struct", "typedef", "public", + "private", "protected", "final", "var", "let", "await", "async", "defer", "go", +]) + +interface Hunk { + context: string // the text after the second @@ (usually the enclosing function) + added: string[] + removed: string[] + body: string[] // all content lines incl. unchanged context — where the guarded sink usually sits +} +interface FileDiff { + path: string + hunks: Hunk[] +} + +function parseUnifiedDiff(diff: string): FileDiff[] { + const lines = diff.split(/\r?\n/) + const files: FileDiff[] = [] + let current: FileDiff | undefined + let hunk: Hunk | undefined + for (const line of lines) { + const gitHeader = line.match(/^diff --git a\/.+ b\/(.+)$/) + if (gitHeader) { + current = { path: gitHeader[1], hunks: [] } + files.push(current) + hunk = undefined + continue + } + const plusFile = line.match(/^\+\+\+ b\/(.+)$/) + if (plusFile) { + if (!current) { + current = { path: plusFile[1], hunks: [] } + files.push(current) + } else if (current.path === "" || current.path === undefined) { + current.path = plusFile[1] + } + hunk = undefined + continue + } + if (line.startsWith("--- ")) continue + const hunkHeader = line.match(/^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@(.*)$/) + if (hunkHeader) { + if (!current) { + current = { path: "", hunks: [] } + files.push(current) + } + hunk = { context: hunkHeader[1].trim(), added: [], removed: [], body: [] } + current.hunks.push(hunk) + continue + } + if (!hunk) continue + if (line.startsWith("+")) { + hunk.added.push(line.slice(1)) + hunk.body.push(line.slice(1)) + } else if (line.startsWith("-")) { + hunk.removed.push(line.slice(1)) + hunk.body.push(line.slice(1)) + } else if (line.startsWith(" ")) { + hunk.body.push(line.slice(1)) + } + } + return files.filter((f) => f.hunks.length > 0) +} + +function callIdentifiers(src: string[]): string[] { + const out = new Set() + const re = /([A-Za-z_][A-Za-z0-9_]{2,})\s*\(/g + for (const line of src) { + let m: RegExpExecArray | null + while ((m = re.exec(line)) !== null) { + const id = m[1] + if (!CODE_KEYWORDS.has(id)) out.add(id) + } + } + return [...out] +} + +function matchLabels(src: string[], table: Array<{ re: RegExp; label: string }>): string[] { + const hit = new Set() + for (const line of src) for (const { re, label } of table) if (re.test(line)) hit.add(label) + return [...hit] +} + +function enclosingFns(files: FileDiff[]): string[] { + const out = new Set() + for (const f of files) + for (const h of f.hunks) { + const m = h.context.match(/([A-Za-z_][A-Za-z0-9_]+)\s*\(/) + if (m && !CODE_KEYWORDS.has(m[1])) out.add(m[1]) + } + return [...out] +} + +function rgLangGlob(lang?: string): string { + switch ((lang ?? "").toLowerCase()) { + case "c": + case "cpp": + case "c++": return " -g '*.c' -g '*.h' -g '*.cc' -g '*.cpp'" + case "java": return " -g '*.java'" + case "go": return " -g '*.go'" + case "python": + case "py": return " -g '*.py'" + case "js": + case "ts": return " -g '*.js' -g '*.ts'" + case "php": return " -g '*.php'" + case "rust": return " -g '*.rs'" + default: return "" + } +} + +export function analyzeDiff(diff: string, lang?: string): { output: string; files: FileDiff[]; hunks: number; variantCount: number } { + const files = parseUnifiedDiff(diff) + const hunks = files.reduce((n, f) => n + f.hunks.length, 0) + if (files.length === 0) { + return { + output: + "Could not parse any hunks from the input. Pass a real unified diff — e.g. `git diff ~1 -- ` or a commit `.patch`. (A GitHub commit page is not a diff; append `.patch` to the commit URL.)", + files: [], + hunks: 0, + variantCount: 0, + } + } + + const allAdded = files.flatMap((f) => f.hunks.flatMap((h) => h.added)) + const allRemoved = files.flatMap((f) => f.hunks.flatMap((h) => h.removed)) + const hunkBody = files.flatMap((f) => f.hunks.flatMap((h) => h.body)) + + // The guard is what the fix ADDED that was not there before. + const addedGuards = matchLabels(allAdded, GUARD_HINTS).filter((g) => !matchLabels(allRemoved, GUARD_HINTS).includes(g)) + // The sink usually sits on an UNCHANGED context line that the fix wraps with the new guard — + // scan the whole hunk body, not only the +/- lines. + const sinksTouched = matchLabels(hunkBody, SINK_PATTERNS) + const fns = enclosingFns(files) + const bodyCalls = callIdentifiers(hunkBody) + const sinkCalls = bodyCalls.filter((id) => SINK_PATTERNS.some((s) => s.re.test(id + "("))) + const changedCalls = [...new Set([...callIdentifiers(allRemoved), ...callIdentifiers(allAdded)])] + // Sweep the enclosing fn, the concrete sink wrappers, and the functions the change itself touches. + const sweepTargets = [...new Set([...fns, ...sinkCalls, ...changedCalls])].slice(0, 12) + const glob = rgLangGlob(lang) + + const lines: string[] = [] + lines.push(`# patch_diff — variant-hunt plan from the fix`) + lines.push("") + lines.push(`Files touched: ${files.map((f) => f.path).join(", ")}`) + lines.push(`Enclosing function(s): ${fns.length ? fns.join(", ") : "(none parsed from hunk headers)"}`) + lines.push(`Dangerous sinks near the change: ${sinksTouched.length ? sinksTouched.join("; ") : "(none of the known classes — read the hunk by hand)"}`) + lines.push(`Guard the fix ADDED (the thing siblings may be MISSING): ${addedGuards.length ? addedGuards.join("; ") : "(not a recognizable guard — the fix may be a refactor/rewrite; reason about it manually)"}`) + lines.push("") + lines.push(`## The vulnerable shape (what to match)`) + const sampleShape = + allRemoved.find((l) => SINK_PATTERNS.some((s) => s.re.test(l))) ?? + hunkBody.find((l) => SINK_PATTERNS.some((s) => s.re.test(l))) ?? + allRemoved.find((l) => l.trim().length > 0) + if (sampleShape) lines.push("```\n" + sampleShape.trim() + "\n```") + lines.push( + "The fix added a guard around this. A sibling is any other call site of the same sink/function that reaches it WITHOUT that guard, or a call site the fix did not touch (incomplete fix).", + ) + lines.push("") + lines.push(`## 1) Sweep the whole tree for sibling call sites (ripgrep)`) + if (sweepTargets.length === 0) { + lines.push("No clear identifier to sweep — grep the sink class manually.") + } else { + for (const t of sweepTargets) { + lines.push("```bash") + lines.push(`rg -n --pcre2 '\\b${t}\\s*\\(' src${glob} # every call site of ${t}`) + lines.push("```") + } + } + lines.push("") + lines.push(`## 2) Semgrep starting pattern (refine, then run → semgrep_parse)`) + const semTarget = sinkCalls[0] ?? changedCalls.find((c) => SINK_PATTERNS.some((s) => s.re.test(c + "("))) ?? fns[0] ?? changedCalls[0] + if (semTarget) { + const langFlag = lang ? ` --lang ${lang}` : " --lang generic" + lines.push("```bash") + lines.push(`semgrep -e '${semTarget}(...)'${langFlag} --json -o variants.json src # then: semgrep_parse input=variants.json`) + lines.push("```") + lines.push( + "That matches every call; narrow it with the guard check (a `patterns:` rule with `pattern:` for the sink and `pattern-not:` for the added guard) so it flags only the UNguarded siblings.", + ) + } else { + lines.push("No single sink identifier extracted — write the rule from the hunk by hand.") + } + lines.push("") + lines.push(`## 3) Incomplete-fix check (highest hit-rate)`) + lines.push( + "For EACH sweep hit: does the equivalent of the added guard protect it? If not, it is a candidate (suspected). Also re-check the SAME file/function the fix touched for other inputs/lengths/paths the one-line fix did not cover — patches frequently fix one call site and miss a twin.", + ) + lines.push("") + lines.push(`## 4) Record`) + lines.push( + "Each unguarded sibling → trace source→sink and PROVE reachability before confirming (hand to `critic` to disprove). Fold confirmed/suspected variants into state via semgrep_parse (auto) or state_update. Reachability-from-untrusted-input is the ranking key, not SAST severity.", + ) + + return { output: lines.join("\n"), files, hunks, variantCount: sweepTargets.length } +} + +export function buildPlan(p: Params): string { + const repo = p.repo ?? "" + const fix = p.fix_ref ?? "" + const vuln = p.vuln_ref ?? `${fix}~1` + const lines: string[] = [] + lines.push(`# patch_diff — fetch + diff plan${p.cve ? ` for ${p.cve}` : ""}`) + lines.push("") + if (p.cve && !p.fix_ref) { + lines.push(`## 0) Find the fix commit (you only gave a CVE)`) + lines.push( + `Look up ${p.cve}: the advisory / NVD references usually link the fixing commit and the affected-version range. Use websearch/webfetch for "${p.cve} fix commit" and the project's security advisory. Pin \`fix_ref\` to that commit and \`vuln_ref\` to the version the TARGET runs.`, + ) + lines.push("") + } + lines.push(`## 1) Obtain + pin the source (into the engagement workdir, scope_check first)`) + lines.push("```bash") + lines.push(`git clone ${repo} src`) + lines.push(`git -C src log --oneline -15 ${fix} # confirm the fix commit and its parents`) + lines.push("```") + lines.push("") + lines.push(`## 2) Produce the security-fix diff`) + lines.push("```bash") + lines.push(`git -C src diff ${vuln} ${fix} # full change between vulnerable and fixed`) + lines.push(`# or just the security-relevant file(s):`) + lines.push(`git -C src diff ${fix}~1 ${fix} -- `) + lines.push("```") + lines.push("") + lines.push(`## 3) Analyze the diff → variant-hunt sweeps`) + lines.push("Pipe that diff back in:") + lines.push("```") + lines.push(`patch_diff action=analyze lang= diff="$(git -C src diff ${fix}~1 ${fix})"`) + lines.push("```") + lines.push("") + lines.push( + "Then run the emitted ripgrep/semgrep sweeps, check each sibling for the fix's guard, and prove reachability on the survivors. Confirm the target actually runs the VULNERABLE version first — a bug fixed in the deployed tag is not a finding.", + ) + return lines.join("\n") +} + +export const PatchDiffTool = Tool.define( + "patch_diff", + Effect.gen(function* () { + return { + description: DESCRIPTION, + parameters: Parameters, + execute: (params: Params, _ctx: Tool.Context) => + Effect.gen(function* () { + if (params.action === "plan") { + return { + title: `patch_diff plan${params.cve ? ` ${params.cve}` : ""}`, + metadata: { action: "plan", files: 0, hunks: 0, variant_targets: 0 }, + output: buildPlan(params), + } + } + let diff = (params.diff ?? "").trim() + if (!diff) { + return { + title: "patch_diff analyze", + metadata: { action: "analyze", files: 0, hunks: 0, variant_targets: 0 }, + output: + "No diff provided. Pass the unified diff of the fix in `diff` (e.g. `git diff ~1 -- `), or run action=plan first to generate the fetch+diff commands.", + } + } + const analysis = analyzeDiff(diff, params.lang) + return { + title: `patch_diff: ${analysis.variantCount} sweep target(s)`, + metadata: { + action: "analyze", + files: analysis.files.length, + hunks: analysis.hunks, + variant_targets: analysis.variantCount, + }, + output: analysis.output, + } + }).pipe(Effect.orDie), + } + }), +) diff --git a/packages/opencode/src/tool/patch-diff.txt b/packages/opencode/src/tool/patch-diff.txt new file mode 100644 index 00000000..f5f745e1 --- /dev/null +++ b/packages/opencode/src/tool/patch-diff.txt @@ -0,0 +1,13 @@ +Patch-diff / n-day -> variant engine: turn one known bug (its security fix) into bugs #2..N. This is the highest-hit-rate path in source auditing — a one-line fix usually patches ONE call site and misses its twins, and the same bug pattern recurs in sibling code the patch never touched (nginx2root found four sibling use-after-frees this way). + +This tool does NOT run git or semgrep. It structures a fix diff and emits the sweeps; you fetch the diff and run them, then fold real hits into state via semgrep_parse / state_update. + +Two actions: + +- action=plan — give a `cve` and/or `repo` + `fix_ref` (+ optional `vuln_ref`, default fix_ref~1). Emits the exact git commands to clone, pin, and produce the security-fix diff, then how to pipe it back into action=analyze. Use when you have a CVE/commit but not the diff yet. + +- action=analyze — give the unified `diff` of the fix (output of `git diff ~1 ` or a commit .patch; a path to a file holding it also works) and optional `lang`. Parses the hunks and returns: the files/functions touched, the dangerous SINK class near the change (memory op, alloc/free->UAF, exec, deserialization, path, SQL), the GUARD the fix added (the thing siblings may be missing), the vulnerable code shape, ripgrep sweeps for every sibling call site, a semgrep `-e` starting pattern to refine into an unguarded-sibling rule, and an incomplete-fix checklist. + +Every emitted pattern is a STARTING point, not a finished rule — narrow the semgrep rule with pattern-not for the added guard so it flags only UNGUARDED siblings. Each sibling is a LEAD: trace source->sink and prove reachability (hand to `critic` to disprove) before confirming. Confirm the target actually runs the VULNERABLE version first — a bug fixed in the deployed tag is not a finding. Rank by reachability-from-untrusted-input, never by SAST severity. + +Params: action (plan|analyze, required) · diff (analyze) · repo/fix_ref/vuln_ref/cve (plan) · lang (c|cpp|java|go|python|js|ts|php|rust — tunes the generated sweeps). diff --git a/packages/opencode/src/tool/registry.ts b/packages/opencode/src/tool/registry.ts index 65e10bc9..b52d38b7 100644 --- a/packages/opencode/src/tool/registry.ts +++ b/packages/opencode/src/tool/registry.ts @@ -38,6 +38,9 @@ import { ReportGenTool } from "./report-gen" import { TaskGraphTool } from "./task-graph" import { CredSprayTool } from "./cred-spray" import { SqlmapParseTool } from "./sqlmap-parse" +import { PatchDiffTool } from "./patch-diff" +import { SemgrepParseTool } from "./semgrep-parse" +import { CodeqlParseTool } from "./codeql-parse" import { XssDetectTool } from "./xss-detect" import { JwtAnalyzeTool } from "./jwt-analyze" import { TunnelManageTool } from "./tunnel-manage" @@ -148,6 +151,9 @@ const layer = Layer.effect( const oshook = yield* OsHookTool const injectprobe = yield* InjectProbeTool const knowledge = yield* KnowledgeTool + const patchdiff = yield* PatchDiffTool + const semgrepparse = yield* SemgrepParseTool + const codeqlparse = yield* CodeqlParseTool const screenshot = yield* ScreenshotTool const agent = yield* Agent.Service @@ -274,6 +280,9 @@ const layer = Layer.effect( oshook: Tool.init(oshook), injectprobe: Tool.init(injectprobe), knowledge: Tool.init(knowledge), + patchdiff: Tool.init(patchdiff), + semgrepparse: Tool.init(semgrepparse), + codeqlparse: Tool.init(codeqlparse), screenshot: Tool.init(screenshot), }) @@ -313,6 +322,9 @@ const layer = Layer.effect( tool.oshook, tool.injectprobe, tool.knowledge, + tool.patchdiff, + tool.semgrepparse, + tool.codeqlparse, tool.screenshot, ...(flags.experimentalPlanMode && flags.client === "cli" ? [tool.plan] : []), ], diff --git a/packages/opencode/src/tool/report-gen.ts b/packages/opencode/src/tool/report-gen.ts index f91f417f..bdfc8b2c 100644 --- a/packages/opencode/src/tool/report-gen.ts +++ b/packages/opencode/src/tool/report-gen.ts @@ -72,6 +72,9 @@ function generateExecutiveSummary(state: EngagementSchema.State): string { if (stats.objectives_total > 0) { lines.push(`- **Objectives**: ${stats.objectives_completed}/${stats.objectives_total} completed`) } + if (stats.cost_attributed > 0) { + lines.push(`- **AI cost attributed to findings**: ${EngagementSchema.formatCost(stats.cost_attributed)}`) + } return lines.join("\n") } @@ -154,6 +157,10 @@ function generateFindings(state: EngagementSchema.State): string { if (vuln.description) lines.push(`- **Description**: ${vuln.description}`) if (vuln.evidence) lines.push(`- **Evidence**: ${vuln.evidence}`) if (vuln.mitre_attack_id) lines.push(`- **MITRE ATT&CK**: ${vuln.mitre_attack_id}`) + if (vuln.cost) + lines.push( + `- **AI cost to find**: ${EngagementSchema.formatCost(vuln.cost.ai)} (cumulative through this finding: ${EngagementSchema.formatCost(vuln.cost.total_to_date)})`, + ) const refs = vuln.references ?? [] if (refs.length > 0) lines.push(`- **References**: ${refs.join(", ")}`) const items = vuln.evidence_items ?? [] diff --git a/packages/opencode/src/tool/semgrep-parse.ts b/packages/opencode/src/tool/semgrep-parse.ts new file mode 100644 index 00000000..6917adde --- /dev/null +++ b/packages/opencode/src/tool/semgrep-parse.ts @@ -0,0 +1,378 @@ +import { Effect, Schema } from "effect" +import { EngagementStore } from "@pentestcode/core/engagement/store" +import { EngagementSchema } from "@pentestcode/core/engagement/schema" +import { ScopeMatcher } from "@pentestcode/core/engagement/scope-matcher" +import { PentestEvent } from "@pentestcode/schema/pentest-event" +import { EventV2Bridge } from "@/event-v2-bridge" +import { FSUtil } from "@pentestcode/core/fs-util" +import DESCRIPTION from "./semgrep-parse.txt" +import * as Tool from "./tool" + +// Static analysis (Semgrep) is a *research* substrate: it reads source and emits +// pattern matches. A match is a LEAD, never a confirmed bug — the surrounding +// code may sanitize, the sink may be unreachable, the taint may not flow. So +// every finding lands as `suspected` / `unverified` and is auto-flagged for the +// code_auditor to trace source→sink and PROVE (or kill) before anything is +// marked confirmed. This mirrors the nuclei_parse contract (scanner output is +// unverified) but for code rather than a live service. + +export const Parameters = Schema.Struct({ + input: Schema.String.annotate({ + description: "Semgrep JSON output text (`semgrep --json`) or a file path to read it from", + }), + host: Schema.optional(Schema.String).annotate({ + description: + "Target this code runs on (IP/hostname), so findings attach to that host in engagement state. Omit for a pure source audit not yet mapped to a live target; findings then attach to the synthetic host 'source-audit'.", + }), + auto_update: Schema.optional(Schema.Boolean).annotate({ + description: "Add discovered findings to engagement state as suspected vulns (default: true)", + }), + min_severity: Schema.optional(Schema.String).annotate({ + description: "Drop findings below this severity: critical|high|medium|low|info (default: low)", + }), +}) + +// Synthetic host key for findings not yet tied to a live target. Scope-checking +// is skipped for it (there is no IP to match). +const CODE_HOST = "source-audit" + +interface SemgrepStart { + line?: number + col?: number +} + +interface SemgrepMetadata { + cwe?: string[] | string + owasp?: string[] | string + references?: string[] + confidence?: string + impact?: string + likelihood?: string + category?: string + vulnerability_class?: string[] +} + +interface SemgrepExtra { + message?: string + severity?: string + metadata?: SemgrepMetadata + lines?: string + fix?: string +} + +interface SemgrepResult { + check_id?: string + path?: string + start?: SemgrepStart + end?: SemgrepStart + extra?: SemgrepExtra +} + +interface SemgrepOutput { + results?: SemgrepResult[] + errors?: unknown[] +} + +interface ParsedFinding { + checkId: string + shortRule: string + title: string + severity: string + confidence: string + path: string + line: number + endLine: number + codeSnippet: string + message: string + cwe: string[] + owasp: string[] + references: string[] + vulnId: string +} + +const SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"] + +function looksLikeFilePath(input: string): boolean { + const trimmed = input.trimStart() + if (trimmed.startsWith("/") || trimmed.startsWith("./") || trimmed.startsWith("~/")) return true + if (/\.(json|jsonl|txt|sarif)$/i.test(trimmed.split("\n")[0]!.trim())) return true + return false +} + +function asArray(v: string[] | string | undefined): string[] { + if (!v) return [] + return Array.isArray(v) ? v : [v] +} + +// Semgrep emits ERROR/WARNING/INFO. Refine upward when metadata marks the rule +// HIGH impact *and* HIGH likelihood (that is what separates a real sink from a +// stylistic nag), so a tainted-RCE pattern does not sit at the same tier as a +// missing-timeout lint. +function normalizeSeverity(extra: SemgrepExtra | undefined): string { + const raw = (extra?.severity ?? "info").toUpperCase() + let base: string + if (raw === "ERROR") base = "high" + else if (raw === "WARNING") base = "medium" + else if (raw === "INFO") base = "low" + else if (SEVERITY_ORDER.includes(raw.toLowerCase())) base = raw.toLowerCase() + else base = "info" + + const meta = extra?.metadata + const impact = (meta?.impact ?? "").toUpperCase() + const likelihood = (meta?.likelihood ?? "").toUpperCase() + if (base === "high" && impact === "HIGH" && likelihood === "HIGH") return "critical" + return base +} + +function normalizeConfidence(meta: SemgrepMetadata | undefined): string { + const c = (meta?.confidence ?? "").toLowerCase() + if (["high", "medium", "low"].includes(c)) return c + return "unknown" +} + +function shortRuleName(checkId: string): string { + const parts = checkId.split(".") + return parts[parts.length - 1] || checkId +} + +function firstLine(s: string | undefined): string { + if (!s) return "" + return s.split("\n")[0]!.trim().slice(0, 240) +} + +function parseSemgrepJson(content: string, minSeverity: string): ParsedFinding[] { + let parsed: SemgrepOutput + try { + parsed = JSON.parse(content) as SemgrepOutput + } catch { + return [] + } + const results = parsed.results ?? [] + const minIdx = SEVERITY_ORDER.indexOf(minSeverity) + const floor = minIdx === -1 ? SEVERITY_ORDER.length - 1 : minIdx + + const findings: ParsedFinding[] = [] + const seen = new Set() + + for (const r of results) { + const checkId = r.check_id + if (!checkId) continue + const path = r.path ?? "" + const line = r.start?.line ?? 0 + const endLine = r.end?.line ?? line + const dedupKey = `${checkId}:${path}:${line}` + if (seen.has(dedupKey)) continue + seen.add(dedupKey) + + const extra = r.extra ?? {} + const meta = extra.metadata ?? {} + const severity = normalizeSeverity(extra) + if (SEVERITY_ORDER.indexOf(severity) > floor) continue + + const short = shortRuleName(checkId) + findings.push({ + checkId, + shortRule: short, + title: firstLine(extra.message) || short, + severity, + confidence: normalizeConfidence(meta), + path, + line, + endLine, + codeSnippet: (extra.lines ?? "").trim().slice(0, 400), + message: extra.message ?? "", + cwe: asArray(meta.cwe), + owasp: asArray(meta.owasp), + references: meta.references ?? [], + vulnId: `semgrep-${short}-${path.replace(/[^a-zA-Z0-9]+/g, "_")}-L${line}`, + }) + } + + return findings +} + +function formatOutput(findings: ParsedFinding[], host: string, autoUpdated: boolean): string { + const lines: string[] = [] + lines.push(`Parsed ${findings.length} Semgrep finding${findings.length !== 1 ? "s" : ""} (host: ${host})`) + lines.push("") + + const bySeverity: Record = {} + for (const f of findings) { + const sev = f.severity.toUpperCase() + ;(bySeverity[sev] ??= []).push(f) + } + + for (const sev of SEVERITY_ORDER.map((s) => s.toUpperCase())) { + const group = bySeverity[sev] + if (!group || group.length === 0) continue + lines.push(`[${sev}] (${group.length})`) + for (const f of group) { + const cwe = f.cwe.length ? ` {${f.cwe.join(", ")}}` : "" + const conf = f.confidence !== "unknown" ? ` conf:${f.confidence}` : "" + lines.push(` ${f.path}:${f.line} — ${f.title} (${f.shortRule})${cwe}${conf}`) + if (f.codeSnippet) lines.push(` code: ${firstLine(f.codeSnippet)}`) + } + lines.push("") + } + + lines.push( + "These are STATIC-ANALYSIS LEADS, not confirmed bugs. For each high/critical finding, trace source→sink", + "and prove reachability + exploitability before marking it confirmed. Many will be sanitized or unreachable.", + ) + + if (autoUpdated) { + lines.push("") + lines.push(`[Auto-updated engagement state: ${findings.length} suspected finding(s) on host ${host}]`) + } else { + lines.push("") + lines.push("[Engagement state not updated (auto_update=false)]") + } + + return lines.join("\n") +} + +export const SemgrepParseTool = Tool.define( + "semgrep_parse", + Effect.gen(function* () { + const store = yield* EngagementStore.Service + const fs = yield* FSUtil.Service + const events = yield* EventV2Bridge.Service + + return { + description: DESCRIPTION, + parameters: Parameters, + execute: ( + params: { input: string; host?: string; auto_update?: boolean; min_severity?: string }, + _ctx: Tool.Context, + ) => + Effect.gen(function* () { + let content = params.input + const shouldUpdate = params.auto_update !== false + const minSeverity = (params.min_severity ?? "low").toLowerCase() + const host = (params.host ?? "").trim() || CODE_HOST + + if (looksLikeFilePath(content.trim())) { + const filePath = content.trim() + const exists = yield* fs.existsSafe(filePath) + if (exists) { + content = yield* fs.readFileString(filePath) + } + } + + const findings = parseSemgrepJson(content, minSeverity) + + if (findings.length === 0) { + return { + title: "semgrep parse", + metadata: { findings: 0, high_critical: 0, host, auto_updated: false }, + output: + "No findings parsed from Semgrep output. Verify the input is `semgrep --json` output (the top-level object must have a `results` array). If Semgrep reported only `errors`, the scan likely failed to parse the target — check the language/ruleset.", + } + } + + let outOfScope = false + if (shouldUpdate) { + const state = yield* store.get() + + // Scope-check only when attached to a real host. A synthetic + // source-audit host has no IP to match and is always allowed. + if ( + host !== CODE_HOST && + state && + state.scope.targets.length > 0 && + state.mode !== "free" && + !ScopeMatcher.checkScope(host, state.scope).inScope + ) { + outOfScope = true + } + + if (!outOfScope) { + yield* store.addHost(host, { ip: host }) + + for (const f of findings) { + const location = `${f.path}:${f.line}${f.endLine !== f.line ? `-${f.endLine}` : ""}` + const evidence = [ + `location: ${location}`, + `rule: ${f.checkId}`, + f.cwe.length ? `cwe: ${f.cwe.join(", ")}` : "", + f.owasp.length ? `owasp: ${f.owasp.join(", ")}` : "", + f.confidence !== "unknown" ? `rule-confidence: ${f.confidence}` : "", + f.codeSnippet ? `code: ${firstLine(f.codeSnippet)}` : "", + ] + .filter(Boolean) + .join(" | ") + + const evidenceItem = { + tool: "semgrep", + command: `semgrep --json (rule ${f.shortRule})`, + output: evidence, + timestamp: new Date().toISOString(), + reasoning: `Static pattern ${f.checkId} matched at ${location}. Source→sink reachability NOT yet verified.`, + source_agent: "code_auditor", + attempt_number: 1, + verification_status: "unverified" as const, + } + // SAST output is a lead: status=suspected drives confidence DOWN + // (see deriveConfidence), which is correct — it must be traced + // and proven before it counts. + const conf = EngagementSchema.deriveConfidence({ + status: "suspected", + evidence_items: [evidenceItem], + }) + + yield* store.addVuln(host, { + id: f.vulnId, + title: f.title, + severity: f.severity as any, + status: "suspected", + confidence: conf, + description: `Semgrep static-analysis lead at ${location}. ${firstLine(f.message)}${ + f.cwe.length ? ` (${f.cwe.join(", ")})` : "" + }. Trace source→sink and prove reachability before confirming.`, + evidence, + evidence_items: [{ ...evidenceItem, confidence: conf }], + references: f.references, + }) + + if (state) { + yield* events.publish(PentestEvent.VulnFound, { + timestamp: Date.now(), + engagementID: state.id, + hostIp: host, + title: f.title, + severity: f.severity, + status: "suspected", + }) + } + } + + const updatedState = yield* store.get() + if (updatedState) yield* store.save(updatedState) + } + } + + let output = formatOutput(findings, host, shouldUpdate && !outOfScope) + + if (outOfScope) { + output += `\n\n[SCOPE] Host ${host} is out of scope — findings parsed but NOT added to engagement state.` + } + + const highSev = findings.filter((f) => f.severity === "critical" || f.severity === "high") + if (shouldUpdate && !outOfScope && highSev.length > 0) { + output += `\n\n[Next] ${highSev.length} high/critical lead(s) recorded as SUSPECTED. The code_auditor should trace each source→sink and prove exploitability; spawn "critic" before any lead is reported as confirmed.` + } + + return { + title: `semgrep: ${findings.length} leads`, + metadata: { + findings: findings.length, + high_critical: highSev.length, + host, + auto_updated: shouldUpdate && !outOfScope, + }, + output, + } + }).pipe(Effect.orDie), + } + }), +) diff --git a/packages/opencode/src/tool/semgrep-parse.txt b/packages/opencode/src/tool/semgrep-parse.txt new file mode 100644 index 00000000..fdfd18dd --- /dev/null +++ b/packages/opencode/src/tool/semgrep-parse.txt @@ -0,0 +1,13 @@ +Parse Semgrep JSON output and auto-update engagement state with static-analysis leads. Run `semgrep --json` (optionally `--sarif` is NOT supported here — use `--json`) against target source code, then pass the output text or file path here. + +Input: raw `semgrep --json` output or a file path to it. The top-level object must contain a `results` array; each result has check_id, path, start/end line, and extra (message, severity, metadata with cwe/owasp/confidence/impact/likelihood, lines). + +Semgrep findings are LEADS, not confirmed bugs — the matched code may be sanitized, unreachable, or non-tainted. Every finding is therefore recorded as status=suspected / verification=unverified, and high/critical leads are flagged for the code_auditor to trace source→sink and PROVE before anything is confirmed. + +Severity mapping: ERROR→high, WARNING→medium, INFO→low; a HIGH-impact + HIGH-likelihood rule is promoted to critical. Use min_severity to drop noise (default: low). Deduplicates by (check_id, path, line). + +Params: +- host: the target this code runs on (IP/hostname) so leads attach to that host. Omit for a pure source audit not yet mapped to a live target — leads then attach to the synthetic host 'source-audit'. +- auto_update=false to parse without modifying state. + +This tool does NOT run Semgrep. Invoke Semgrep via the shell first (e.g. `semgrep --config auto --json -o out.json `, or a targeted ruleset / custom rule for variant analysis), then parse the output here. diff --git a/packages/opencode/src/tool/state-query.ts b/packages/opencode/src/tool/state-query.ts index a1063425..fd06b24c 100644 --- a/packages/opencode/src/tool/state-query.ts +++ b/packages/opencode/src/tool/state-query.ts @@ -2,6 +2,9 @@ import { Effect, Schema } from "effect" import { EngagementStore } from "@pentestcode/core/engagement/store" import { EngagementSchema } from "@pentestcode/core/engagement/schema" import { BackgroundJob } from "@/background/job" +import { Session } from "@/session/session" +import type { SessionID } from "@/session/schema" +import { NotFoundError } from "@/storage/storage" import DESCRIPTION from "./state-query.txt" import * as Tool from "./tool" @@ -33,16 +36,17 @@ export const Parameters = Schema.Struct({ "subagents", "artifacts", "goal", + "costs", ]).annotate({ description: - "Type of query: summary, hosts, vulns, creds, scope, phase, flags, tasks, host, full, engagements, objectives, domain, changelog, diff, relationships, decisions, alerts, sessions (live shells/tunnels), segments (network), ooda (full situation-awareness context), wordlists (used wordlists per target:port), resolved_vectors (settled attack vectors — check before opening a vector; filter by status attempted|confirmed|resolved|blocked or a target substring), subagents (REAL running/finished subagent processes for this session — the source of truth, unlike task_graph status), artifacts (reusable weapons/loot/scripts recorded this engagement — INVOKE a recorded exploit instead of re-deriving its payload), goal (current engagement goal)", + "Type of query: summary, hosts, vulns, creds, scope, phase, flags, tasks, host, full, engagements, objectives, domain, changelog, diff, relationships, decisions, alerts, sessions (live shells/tunnels), segments (network), ooda (full situation-awareness context), wordlists (used wordlists per target:port), resolved_vectors (settled attack vectors — check before opening a vector; filter by status attempted|confirmed|resolved|blocked or a target substring), subagents (REAL running/finished subagent processes for this session — the source of truth, unlike task_graph status — with each subagent's model spend), artifacts (reusable weapons/loot/scripts recorded this engagement — INVOKE a recorded exploit instead of re-deriving its payload), goal (current engagement goal), costs (model spend attributed to each finding — 'what did this finding cost to find' — plus the engagement total and the not-yet-attributed spend of the current session tree)", }), filter: Schema.optional(Schema.String).annotate({ description: "Filter: IP for host query, severity for vulns, engagement name for details", }), }) -const NO_ENGAGEMENT = "No engagement loaded. Create one with state_update (action: create_engagement) or load an existing one (action: load_engagement)." +const NO_ENGAGEMENT = "No engagement loaded. Create one via state_update (create_engagement) with a target-derived name — the user approves with one keystroke; never ask them to name it." const COORDINATOR_AGENTS = new Set(["pentest", "recon"]) function formatHost(ip: string, host: EngagementSchema.Host): string { @@ -57,7 +61,8 @@ function formatHost(ip: string, host: EngagementSchema.Host): string { if (host.vulns.length > 0) { lines.push(` Vulns (${host.vulns.length}):`) for (const v of host.vulns) { - lines.push(` [${(v.severity ?? "medium").toUpperCase()}] ${v.title} (${v.status ?? "suspected"})${v.confidence !== undefined ? ` conf:${v.confidence}` : ""}${v.service_port ? ` port:${v.service_port}` : ""}`) + const cost = v.cost ? ` $${v.cost.ai.toFixed(2)}` : "" + lines.push(` [${(v.severity ?? "medium").toUpperCase()}] ${v.title} (${v.status ?? "suspected"})${v.confidence !== undefined ? ` conf:${v.confidence}` : ""}${v.service_port ? ` port:${v.service_port}` : ""}${cost}`) } } if (host.access.length > 0) { @@ -77,6 +82,7 @@ export const StateQueryTool = Tool.define( Effect.gen(function* () { const store = yield* EngagementStore.Service const background = yield* BackgroundJob.Service + const session = yield* Session.Service return { description: DESCRIPTION, parameters: Parameters, @@ -99,9 +105,26 @@ export const StateQueryTool = Tool.define( } const running = jobs.filter((j) => j.status === "running") const finished = jobs.filter((j) => j.status !== "running") + // Model spend of each subagent's session tree (itself + any nested + // subagents it spawned) — the "full cost including subagents" view. + const costs = new Map() + yield* Effect.forEach( + jobs, + (j) => + Effect.gen(function* () { + const sid = typeof j.metadata?.sessionId === "string" ? j.metadata.sessionId : undefined + if (!sid) return + const tree = yield* session + .costTree(sid as SessionID) + .pipe(Effect.catchIf(NotFoundError.isInstance, () => Effect.succeed(undefined))) + if (tree) costs.set(sid, tree.cost) + }), + { discard: true }, + ) const render = (j: BackgroundJob.Info) => { const sid = typeof j.metadata?.sessionId === "string" ? j.metadata.sessionId : j.id - return ` - [${j.status}] ${j.title ?? "task"} (session ${sid})${j.error ? ` -- ${j.error}` : ""}` + const cost = costs.get(sid) + return ` - [${j.status}] ${j.title ?? "task"} (session ${sid})${cost !== undefined ? ` cost:${EngagementSchema.formatCost(cost)}` : ""}${j.error ? ` -- ${j.error}` : ""}` } const out: string[] = [] if (running.length > 0) out.push(`RUNNING (${running.length}):`, ...running.map(render)) @@ -131,7 +154,7 @@ export const StateQueryTool = Tool.define( return { title: "Engagements", metadata: {}, - output: "No engagements found. Create one with state_update (action: create_engagement).", + output: "No engagements found. Create one via state_update (create_engagement) with a target-derived name — the user approves with one keystroke.", } } const lines = engagements.map((name) => { @@ -197,8 +220,9 @@ export const StateQueryTool = Tool.define( const sev = v.vuln.severity ?? "medium" const port = v.vuln.service_port ? `:${v.vuln.service_port}` : "" const conf = v.vuln.confidence !== undefined ? ` conf:${v.vuln.confidence}` : "" + const cost = v.vuln.cost ? ` cost:${EngagementSchema.formatCost(v.vuln.cost.ai)}` : "" const refs = (v.vuln.references ?? []).length > 0 ? ` refs:[${(v.vuln.references ?? []).join(",")}]` : "" - return `[${sev.toUpperCase()}] ${v.ip}${port} -- ${v.vuln.title} (${v.vuln.status ?? "suspected"})${conf}${refs}${v.vuln.description ? `\n ${v.vuln.description}` : ""}` + return `[${sev.toUpperCase()}] ${v.ip}${port} -- ${v.vuln.title} (${v.vuln.status ?? "suspected"})${conf}${cost}${refs}${v.vuln.description ? `\n ${v.vuln.description}` : ""}` }) const label = params.filter ? `Vulnerabilities [${params.filter}]` : "Vulnerabilities" return { @@ -208,6 +232,47 @@ export const StateQueryTool = Tool.define( } } + case "costs": { + const entries: { ip: string; vuln: EngagementSchema.Vulnerability }[] = [] + for (const [ip, host] of Object.entries(state.hosts)) { + for (const vuln of host.vulns) entries.push({ ip, vuln }) + } + const ledger = state.cost + const total = ledger?.total ?? 0 + const tree = yield* session + .costTree(ctx.sessionID) + .pipe(Effect.catchIf(NotFoundError.isInstance, () => Effect.succeed(undefined))) + const current: Record = {} + if (tree) for (const node of tree.sessions) current[String(node.id)] = node.cost + const pending = EngagementSchema.costWindow(current, ledger?.cursors ?? {}).window + if (entries.length === 0) { + return { + title: "Costs", + metadata: { findings: 0, total, pending }, + output: `No findings recorded yet. Attributed engagement spend: ${EngagementSchema.formatCost(total)}. Unattributed this session tree: ${EngagementSchema.formatCost(pending)}.`, + } + } + const lines = entries.map(({ ip, vuln }) => { + const sev = (vuln.severity ?? "medium").toUpperCase() + const port = vuln.service_port ? `:${vuln.service_port}` : "" + const attr = vuln.cost + ? `${EngagementSchema.formatCost(vuln.cost.ai)} to find (total through this finding ${EngagementSchema.formatCost(vuln.cost.total_to_date)})` + : "cost not recorded (recorded before cost tracking)" + return `[${sev}] ${ip}${port} ${vuln.title} -- ${attr}` + }) + return { + title: "Costs", + metadata: { findings: entries.length, total, pending }, + output: [ + `Finding costs (${entries.length}):`, + ...lines, + "", + `Attributed total: ${EngagementSchema.formatCost(total)}`, + `Unattributed since last finding (current session tree): ${EngagementSchema.formatCost(pending)}`, + ].join("\n"), + } + } + case "creds": { const creds = Object.values(state.credentials) if (creds.length === 0) { diff --git a/packages/opencode/src/tool/state-query.txt b/packages/opencode/src/tool/state-query.txt index 89993f9a..5c6e28e3 100644 --- a/packages/opencode/src/tool/state-query.txt +++ b/packages/opencode/src/tool/state-query.txt @@ -24,4 +24,5 @@ Supported query types: - wordlists: Show wordlists already used (filter: "host_ip" or "host_ip:port" or "host_ip:port:tool_type"). Prevents repeating wordlists on the same target:port:tool_type combination. - resolved_vectors: Show attack vectors already settled (filter by status "attempted"|"confirmed"|"resolved"|"blocked", or a target/vector substring). Check BEFORE opening a vector — do not re-test RESOLVED/CONFIRMED, honor BLOCKED preconditions. - ooda: Full situation-awareness context — changes, coverage gaps, alerts, sessions, segments, tasks, objectives -- subagents: REAL running/finished subagent processes for this session, from the live job registry. Use this (NOT task_graph status) to check what is actually running — task_graph "dispatched" does not mean a subagent was launched. +- subagents: REAL running/finished subagent processes for this session, from the live job registry, with each subagent's full session-tree model cost. Use this (NOT task_graph status) to check what is actually running — task_graph "dispatched" does not mean a subagent was launched. +- costs: Model spend attributed to each finding — "what did this finding cost to find" — its marginal cost since the previous finding plus cumulative totals, and the engagement's not-yet-attributed spend. Cost is attributed automatically when add_vuln records a finding (coordinator + all subagents included). diff --git a/packages/opencode/src/tool/state-update.ts b/packages/opencode/src/tool/state-update.ts index b72fc8b0..bd8f0561 100644 --- a/packages/opencode/src/tool/state-update.ts +++ b/packages/opencode/src/tool/state-update.ts @@ -4,6 +4,8 @@ import { EngagementSchema } from "@pentestcode/core/engagement/schema" import { ScopeMatcher } from "@pentestcode/core/engagement/scope-matcher" import { PentestEvent } from "@pentestcode/schema/pentest-event" import { EventV2Bridge } from "@/event-v2-bridge" +import { Session } from "@/session/session" +import { NotFoundError } from "@/storage/storage" import DESCRIPTION from "./state-update.txt" import * as Tool from "./tool" @@ -60,25 +62,51 @@ export const Parameters = Schema.Struct({ }), }) -const NO_ENGAGEMENT = "No engagement loaded. Use create_engagement or load_engagement first." +const NO_ENGAGEMENT = "No engagement loaded. Create one via create_engagement with a name derived from the target — the user approves it with one keystroke and must never be asked to name it. Do not record state for an engagement that isn't loaded." function countsLine(state: EngagementSchema.State): string { const s = EngagementSchema.summary(state) const objStr = s.objectives_total > 0 ? ` obj:${s.objectives_completed}/${s.objectives_total}` : "" - return `[${state.name}] phase:${s.current_phase} hosts:${s.hosts_discovered} vulns:${s.vulnerabilities} creds:${s.credentials} flags:${s.flags}${objStr}` + const costStr = s.cost_attributed > 0 ? ` cost:${EngagementSchema.formatCost(s.cost_attributed)}` : "" + return `[${state.name}] phase:${s.current_phase} hosts:${s.hosts_discovered} vulns:${s.vulnerabilities} creds:${s.credentials} flags:${s.flags}${objStr}${costStr}` } const COORDINATOR_AGENTS = new Set(["pentest", "recon"]) const ENGAGEMENT_LIFECYCLE_ACTIONS = new Set(["create_engagement", "load_engagement", "reload_engagement"]) - export const StateUpdateTool = Tool.define( "state_update", Effect.gen(function* () { const store = yield* EngagementStore.Service const events = yield* EventV2Bridge.Service - const executeAction = (params: { action: string; data: unknown }, _ctx: Tool.Context): Effect.Effect => + const session = yield* Session.Service + + // Attribute the model spend that happened since the last attribution to the + // finding being recorded. The tree is walked from the ROOT of the calling + // session (finding may be recorded by a subagent) so every session in the + // engagement run — coordinator and all subagents, recursively — is counted + // exactly once via the ledger cursors. Returns undefined when there is nothing + // to attribute or the session row is missing. + const attributeFindingCost = Effect.fn("StateUpdate.attributeCost")(function* ( + state: EngagementSchema.State, + sessionID: Tool.Context["sessionID"], + ) { + const tree = yield* session + .costTree(sessionID) + .pipe(Effect.catchIf(NotFoundError.isInstance, () => Effect.succeed(undefined))) + if (!tree) return undefined + const current: Record = {} + for (const node of tree.sessions) current[String(node.id)] = node.cost + const ledger = EngagementSchema.costWindow(current, state.cost?.cursors ?? {}) + const total = (state.cost?.total ?? 0) + ledger.window + return { + cost: { ai: ledger.window, total_to_date: total, at: new Date().toISOString() }, + ledger: { cursors: ledger.cursors, total }, + } satisfies { cost: EngagementSchema.CostAttribution; ledger: EngagementSchema.CostLedger } + }) + + const executeAction = (params: { action: string; data: unknown }, ctx: Tool.Context): Effect.Effect => Effect.gen(function* () { - if (ENGAGEMENT_LIFECYCLE_ACTIONS.has(params.action) && !COORDINATOR_AGENTS.has(_ctx.agent)) { + if (ENGAGEMENT_LIFECYCLE_ACTIONS.has(params.action) && !COORDINATOR_AGENTS.has(ctx.agent)) { return { title: "Denied", metadata: {}, @@ -96,6 +124,20 @@ export const StateUpdateTool = Tool.define( if (!name) { return { title: "Error", metadata: {}, output: "Error: data.name is required for create_engagement." } } + // Creating an engagement the user did not ask for leaves orphan, + // empty engagements. The agent's permission ruleset allows + // `state_update` but never `create_engagement`, so this always + // asks: the user approves (once / always for this name) or + // rejects, and nothing is created on reject. `run` without --auto + // auto-rejects, so headless sessions cannot create silently + // either — the agent must tell the user to create it via + // /engagement instead. + yield* ctx.ask({ + permission: "create_engagement", + patterns: [name], + metadata: { name }, + always: [name], + }) const state = yield* store.create(name) return { title: `Created ${name}`, @@ -213,6 +255,20 @@ export const StateUpdateTool = Tool.define( if (!state.hosts[hostIp]) { return { title: "Error", metadata: {}, output: `Error: Host ${hostIp} not found. Add the host first.` } } + // Attribute the model spend since the last attribution to this + // finding (subagent sessions included). A repeat of the same + // vuln stacks its existing attribution with the new window. + const attribution = yield* attributeFindingCost(state, ctx.sessionID) + const existing = state.hosts[hostIp]!.vulns.find( + (v) => v.title === title && v.service_port === d.service_port, + ) + const cost = attribution + ? { + ai: (existing?.cost?.ai ?? 0) + attribution.cost.ai, + total_to_date: attribution.cost.total_to_date, + at: attribution.cost.at, + } + : undefined const vuln = { id: d.id || `vuln-${Date.now()}`, title, @@ -225,7 +281,10 @@ export const StateUpdateTool = Tool.define( service_port: d.service_port, references: d.references || [], mitre_attack_id: d.mitre_attack_id, + cost, } as EngagementSchema.Vulnerability + + if (attribution) yield* store.recordCost(attribution.ledger) yield* store.addVuln(hostIp, vuln) const updated = yield* store.get() @@ -237,10 +296,13 @@ export const StateUpdateTool = Tool.define( severity: vuln.severity ?? "medium", status: vuln.status ?? "suspected", }) + const costLine = vuln.cost + ? `\nAI cost: ${EngagementSchema.formatCost(vuln.cost.ai)} attributed to this finding (engagement total ${EngagementSchema.formatCost(vuln.cost.total_to_date)})` + : "" return { title: `Vuln: ${title}`, - metadata: { host_ip: hostIp, severity: vuln.severity }, - output: `Vulnerability added to ${hostIp}: [${(vuln.severity ?? "medium").toUpperCase()}] ${title} (${vuln.status ?? "suspected"})${updated ? `\n${countsLine(updated)}` : ""}`, + metadata: { host_ip: hostIp, severity: vuln.severity, cost: vuln.cost?.ai }, + output: `Vulnerability added to ${hostIp}: [${(vuln.severity ?? "medium").toUpperCase()}] ${title} (${vuln.status ?? "suspected"})${costLine}${updated ? `\n${countsLine(updated)}` : ""}`, } } diff --git a/packages/opencode/src/tool/state-update.txt b/packages/opencode/src/tool/state-update.txt index b2fc4ba7..fa24ea95 100644 --- a/packages/opencode/src/tool/state-update.txt +++ b/packages/opencode/src/tool/state-update.txt @@ -9,12 +9,12 @@ Actions and their required data fields: - batch: { operations: Array<{ action: string, data: object }> } — process multiple state updates in one call. Max 100 operations. Use for initial engagement setup, importing scan results, loading state from files. Each operation uses the same format as individual calls below. -- create_engagement: { name: string } +- create_engagement: { name: string } — creating ALWAYS prompts the user for approval before anything is written, so it can never happen silently. NEVER ask the user to name the engagement, and NEVER derive the name from the working directory or generic words (no "opencode-2026-10", "engagement", "target", "test"): derive it from the primary target/product — lowercase, hyphenated, product-first, include the program/client name when known, ending in `-YYYY-MM` (e.g. `okta-bugcrowd-2026-10`, `mattermost-mbb-2026-10`) — and propose it; one keystroke approves. - load_engagement: { name: string } - reload_engagement: {} (reloads current engagement from disk) - add_host: { ip: string, hostname?: string, os?: string, services?: Array<{ port: number, protocol?: string, service?: string, version?: string, state?: string, banner?: string }> } — services are merged by port (not overwritten) on re-scan - delete_host: { ip: string } -- add_vuln: { host_ip: string, title: string, severity?: "critical"|"high"|"medium"|"low"|"info", status?: "suspected"|"confirmed"|"exploited"|"false_positive", description?: string, evidence?: string, service_port?: number, references?: string[], mitre_attack_id?: string } — deduplicates by (title, service_port): re-adding updates the existing entry +- add_vuln: { host_ip: string, title: string, severity?: "critical"|"high"|"medium"|"low"|"info", status?: "suspected"|"confirmed"|"exploited"|"false_positive", description?: string, evidence?: string, service_port?: number, references?: string[], mitre_attack_id?: string } — deduplicates by (title, service_port): re-adding updates the existing entry. Model spend since the previous finding (coordinator + all subagent sessions) is automatically attributed to the finding; query costs to see per-finding spend. - update_vuln: { host_ip: string, vuln_id: string, status?: "suspected"|"confirmed"|"exploited"|"false_positive", severity?: string, evidence?: string, description?: string, title?: string } - delete_vuln: { host_ip: string, vuln_id: string } - add_credential: { id: string, cred_type?: string, username: string, value: string, source?: string, valid_for?: string[] } — re-adding same id updates the existing entry diff --git a/packages/opencode/src/tool/task-graph.ts b/packages/opencode/src/tool/task-graph.ts index dc6ae74c..1320e0e3 100644 --- a/packages/opencode/src/tool/task-graph.ts +++ b/packages/opencode/src/tool/task-graph.ts @@ -59,7 +59,7 @@ export const Parameters = Schema.Struct({ }), }) -const NO_ENGAGEMENT = "No engagement loaded. Use state_update create_engagement first." +const NO_ENGAGEMENT = "No engagement loaded. Create one via state_update (create_engagement) with a target-derived name — the user approves with one keystroke; never ask them to name it." function formatTask(t: TaskGraph.TaskNode): string { const parts = [`[${t.status.toUpperCase()}]`, t.id] diff --git a/packages/opencode/src/tool/task.ts b/packages/opencode/src/tool/task.ts index 45d3a85b..ab5b463c 100644 --- a/packages/opencode/src/tool/task.ts +++ b/packages/opencode/src/tool/task.ts @@ -10,7 +10,8 @@ import { Agent } from "../agent/agent" import { deriveSubagentSessionPermission } from "../agent/subagent-permissions" import type { SessionPrompt } from "../session/prompt" import { Config } from "@/config/config" -import { Effect, Exit, Ref, Schema, Scope, Semaphore } from "effect" +import { NotFoundError } from "@/storage/storage" +import { Cause, Effect, Exit, Ref, Schema, Scope, Semaphore } from "effect" import { EffectBridge } from "@/effect/bridge" import { RuntimeFlags } from "@/effect/runtime-flags" import { Database } from "@pentestcode/core/database/database" @@ -443,7 +444,17 @@ export const makeOrchestratedSpawner = Effect.fn("Orchestrator.makeSpawner")(fun // rolling `pump` still refills slots on every settle. Interrupt alerts do NOT // go here; they inject immediately (separate, urgent path). const coalesceMs = flags.orchestratorCoalesceMs ?? 1500 - type Settled = { ctx: Tool.Context; variant: string | undefined; childId: string; description: string; status: "completed" | "error"; text: string } + type Settled = { + ctx: Tool.Context + variant: string | undefined + childId: string + description: string + status: "completed" | "error" + text: string + // Full model spend of the subagent's session tree (itself + nested + // subagents), read when the job settles. + cost?: number + } const pendingInjects = yield* Ref.make([]) const flushScheduled = yield* Ref.make(false) @@ -472,7 +483,9 @@ export const makeOrchestratedSpawner = Effect.fn("Orchestrator.makeSpawner")(fun renderOutput({ sessionID: r.childId as SessionID, state: r.status, - summary: r.status === "completed" ? `Subagent completed: ${r.description}` : `Subagent failed: ${r.description}`, + summary: + (r.status === "completed" ? `Subagent completed: ${r.description}` : `Subagent failed: ${r.description}`) + + (r.cost !== undefined ? ` -- cost ${EngagementSchema.formatCost(r.cost)}` : ""), text: condenseResult(r.text), }), ) @@ -491,7 +504,17 @@ export const makeOrchestratedSpawner = Effect.fn("Orchestrator.makeSpawner")(fun variant: batch[0]!.variant, parts: [{ type: "text", synthetic: true, text: body + note }], }) - .pipe(Effect.ignore) + .pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("subagent completion prompt injection failed", { + sessionID: ctx.sessionID, + tasks: batch.length, + cause: Cause.pretty(cause), + }), + ), + ) }) // Debounce: the first completion arms a single flush after `coalesceMs`; any @@ -509,7 +532,17 @@ export const makeOrchestratedSpawner = Effect.fn("Orchestrator.makeSpawner")(fun if (coalesceMs > 0) yield* Effect.sleep(`${coalesceMs} millis`) yield* Ref.set(flushScheduled, false) const batch = yield* Ref.getAndSet(pendingInjects, []) - yield* flushBatch(batch).pipe(Effect.catchCause(() => Effect.void)) + yield* flushBatch(batch).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("subagent completion flush failed", { + sessionID: batch[0]?.ctx.sessionID, + tasks: batch.length, + cause: Cause.pretty(cause), + }), + ), + ) }).pipe(Effect.forkIn(scope)) }) @@ -632,13 +665,25 @@ export const makeOrchestratedSpawner = Effect.fn("Orchestrator.makeSpawner")(fun }, ], }) - .pipe(Effect.ignore, Effect.forkIn(scope, { startImmediately: true })) + .pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("subagent status injection failed", { + sessionID: ctx.sessionID, + childID: nextSession.id, + state, + cause: Cause.pretty(cause), + }), + ), + Effect.forkIn(scope, { startImmediately: true }), + ) }) // On settle: atomically mark the node done, refill freed slots (rolling — // no straggler wait), then inject the result. When the whole DAG has // drained, nudge the coordinator for the next plan (completion is its call). - const onSettle = Effect.fn("Orchestrator.onSettle")(function* (status: "completed" | "error", text: string) { + const onSettle = Effect.fn("Orchestrator.onSettle")(function* (status: "completed" | "error", text: string, cost?: number) { yield* engagementStore.modifyTaskGraph((g) => status === "completed" ? TaskGraph.completeTask(g, node.id, text.slice(0, 200)) @@ -658,18 +703,34 @@ export const makeOrchestratedSpawner = Effect.fn("Orchestrator.makeSpawner")(fun // S-1: enqueue for a coalesced coordinator wake-up instead of re-driving a // full coordinator turn per completion. The running/drained note is built // at flush time so it reflects state after the whole batch. - yield* enqueueInject({ ctx, variant, childId: nextSession.id, description, status, text }) + yield* enqueueInject({ ctx, variant, childId: nextSession.id, description, status, text, cost }) }) const notify = Effect.fn("Orchestrator.notify")(function* (jobID: string) { yield* background.wait({ id: jobID }).pipe( Effect.flatMap((result) => Effect.gen(function* () { - if (result.info?.status === "completed") yield* onSettle("completed", result.info.output ?? "") + // Read the subagent's full tree cost (itself + nested subagents) so + // the completion note tells the coordinator what this task spent. + const tree = yield* sessions + .costTree(nextSession.id) + .pipe(Effect.catchIf(NotFoundError.isInstance, () => Effect.succeed(undefined))) + const cost = tree?.cost + if (result.info?.status === "completed") yield* onSettle("completed", result.info.output ?? "", cost) else if (result.info?.status === "error") - yield* onSettle("error", result.info.error || `Subagent failed (status=error, no details): ${description}`) + yield* onSettle("error", result.info.error || `Subagent failed (status=error, no details): ${description}`, cost) }), ), + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logError("subagent completion handler failed", { + jobID, + childID: nextSession.id, + description, + cause: Cause.pretty(cause), + }), + ), Effect.forkIn(scope, { startImmediately: true }), ) }) @@ -822,7 +883,12 @@ export const makeOrchestratedSpawner = Effect.fn("Orchestrator.makeSpawner")(fun } } } - }).pipe(Effect.catchCause(() => Effect.void)) + }).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => Effect.logError("orchestrator watchdog loop failed", { cause: Cause.pretty(cause) }), + ), + ) // Record the latest coordinator ctx (for the wake path) and lazily start the // single watchdog fiber on the first pump. Orchestrator-gated. @@ -1070,7 +1136,19 @@ export const TaskTool = Tool.define( }, ], }) - .pipe(Effect.ignore, Effect.forkIn(scope, { startImmediately: true })) + .pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("background task status injection failed", { + sessionID: ctx.sessionID, + childID: nextSession.id, + state, + cause: Cause.pretty(cause), + }), + ), + Effect.forkIn(scope, { startImmediately: true }), + ) }) const notify = Effect.fn("TaskTool.notifyBackgroundResult")(function* (jobID: string) { @@ -1090,6 +1168,16 @@ export const TaskTool = Tool.define( } }), ), + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logError("background task completion handler failed", { + jobID, + childID: nextSession.id, + description: params.description, + cause: Cause.pretty(cause), + }), + ), Effect.forkIn(scope, { startImmediately: true }), ) }) diff --git a/packages/opencode/test/fake/provider.ts b/packages/opencode/test/fake/provider.ts index 3a6b53ce..cc93bbce 100644 --- a/packages/opencode/test/fake/provider.ts +++ b/packages/opencode/test/fake/provider.ts @@ -44,9 +44,16 @@ export namespace ProviderTest { } } - export function fake(override: Partial & { model?: Provider.Model; info?: Provider.Info } = {}) { - const mdl = override.model ?? model() - const row = override.info ?? info({}, mdl) + export function fake( + override: Partial & { + model?: Provider.Model + info?: Provider.Info + small?: Provider.Model + } = {}, + ) { + const { small, ...rest } = override + const mdl = rest.model ?? model() + const row = rest.info ?? info({}, mdl) return { model: mdl, info: row, @@ -69,12 +76,13 @@ export namespace ProviderTest { Effect.succeed(providerID === row.id ? { providerID: row.id, modelID: mdl.id } : undefined), ), getSmallModel: Effect.fn("TestProvider.getSmallModel")((providerID) => - Effect.succeed(providerID === row.id ? mdl : undefined), + Effect.succeed(providerID === row.id ? (small ?? mdl) : undefined), ), + fallbackModel: Effect.fn("TestProvider.fallbackModel")(() => Effect.succeed(undefined)), defaultModel: Effect.fn("TestProvider.defaultModel")(() => Effect.succeed({ providerID: row.id, modelID: mdl.id }), ), - ...override, + ...rest, }), ), } diff --git a/packages/opencode/test/fixture/tui-plugin.ts b/packages/opencode/test/fixture/tui-plugin.ts index 2f234d9c..739f1dc2 100644 --- a/packages/opencode/test/fixture/tui-plugin.ts +++ b/packages/opencode/test/fixture/tui-plugin.ts @@ -315,6 +315,7 @@ export function createTuiPluginApi(opts: Opts = {}): HostPluginApi { session: { count: opts.state?.session?.count ?? (() => 0), get: opts.state?.session?.get ?? (() => undefined), + treeCost: opts.state?.session?.treeCost ?? (() => 0), diff: opts.state?.session?.diff ?? (() => []), todo: opts.state?.session?.todo ?? (() => []), messages: opts.state?.session?.messages ?? (() => []), diff --git a/packages/opencode/test/mcp/catalog.test.ts b/packages/opencode/test/mcp/catalog.test.ts index 7b0d6403..2956c120 100644 --- a/packages/opencode/test/mcp/catalog.test.ts +++ b/packages/opencode/test/mcp/catalog.test.ts @@ -105,3 +105,82 @@ test("preserves output schema validation across paginated tool discovery", async await Promise.all([client.close(), server.close()]) } }) + +describe("McpCatalog.proxy", () => { + function defs() { + return [ + { + name: "drost_nmap", + description: "Run nmap from the Drost network toolkit.\nSecond line detail.", + inputSchema: { type: "object", properties: { args: { type: "array", items: { type: "string" } } } }, + }, + { name: "drost_ffuf", description: "Run ffuf", inputSchema: { type: "object", properties: {} } }, + ] as any[] + } + + function recordingClient() { + const calls: any[] = [] + const client = { + callTool: async (request: any) => { + calls.push(request) + return { content: [{ type: "text" as const, text: "tool output" }] } + }, + } as unknown as Client + return { client, calls } + } + + test("builds exactly two meta-tools: catalog and run", () => { + const { client } = recordingClient() + const built = McpCatalog.proxy("drost", client, defs()) + expect(built.map((entry) => entry.def.name)).toEqual(["catalog", "run"]) + expect(built[0]!.def.description).toContain("drost_run") + }) + + test("catalog lists every tool compactly", async () => { + const { client } = recordingClient() + const [catalog] = McpCatalog.proxy("drost", client, defs()) + const output: any = await catalog!.tool.execute!({}, options) + const text = output.content[0].text as string + expect(text).toContain("drost tools (2)") + expect(text).toContain("- drost_nmap — Run nmap from the Drost network toolkit.") + expect(text).not.toContain("Second line detail") + expect(text).toContain("- drost_ffuf — Run ffuf") + }) + + test("catalog returns one tool's full schema", async () => { + const { client } = recordingClient() + const [catalog] = McpCatalog.proxy("drost", client, defs()) + const output: any = await catalog!.tool.execute!({ tool: "drost_nmap" }, options) + const parsed = JSON.parse(output.content[0].text) + expect(parsed.name).toBe("drost_nmap") + expect(parsed.inputSchema.properties.args).toEqual({ type: "array", items: { type: "string" } }) + }) + + test("catalog rejects unknown tool names", async () => { + const { client } = recordingClient() + const [catalog] = McpCatalog.proxy("drost", client, defs()) + await expect(Promise.resolve(catalog!.tool.execute!({ tool: "nope" }, options))).rejects.toThrow(/Unknown drost tool/) + }) + + test("run dispatches the requested tool with its arguments", async () => { + const { client, calls } = recordingClient() + const [, run] = McpCatalog.proxy("drost", client, defs()) + const output: any = await run!.tool.execute!({ tool: "drost_ffuf", arguments: { url: "http://x" } }, options) + expect(calls[0]).toMatchObject({ name: "drost_ffuf", arguments: { url: "http://x" } }) + expect(output.content[0].text).toBe("tool output") + }) + + test("run defaults missing arguments to an empty object", async () => { + const { client, calls } = recordingClient() + const [, run] = McpCatalog.proxy("drost", client, defs()) + await run!.tool.execute!({ tool: "drost_nmap" }, options) + expect(calls[0]).toMatchObject({ name: "drost_nmap", arguments: {} }) + }) + + test("run rejects unknown or missing tool names", async () => { + const { client } = recordingClient() + const [, run] = McpCatalog.proxy("drost", client, defs()) + await expect(Promise.resolve(run!.tool.execute!({ tool: "nope" }, options))).rejects.toThrow(/Unknown drost tool/) + await expect(Promise.resolve(run!.tool.execute!({}, options))).rejects.toThrow(/Missing "tool"/) + }) +}) diff --git a/packages/opencode/test/provider/provider.test.ts b/packages/opencode/test/provider/provider.test.ts index 39b4b3d5..57ec312d 100644 --- a/packages/opencode/test/provider/provider.test.ts +++ b/packages/opencode/test/provider/provider.test.ts @@ -87,6 +87,42 @@ const languageBaseURL = (language: unknown) => (language as { config: { baseURL: const it = testEffect(LayerNode.compile(LayerNode.group([Provider.node, Env.node, Plugin.node]))) const experimentalModels = testEffect(providerLayer({ enableExperimentalModels: true })) +// Zen strips paid models without a credential, and the OpenRouter fallback only +// engages when OpenRouter is connected. Preset both credentials so routing tests +// exercise the real logic without touching the on-disk auth file. +const zenAndOpenRouter = Layer.mock(Auth.Service, { + get: (providerID: string) => + Effect.succeed( + providerID === "openrouter" || providerID === "opencode" + ? new Auth.Api({ type: "api", key: "test-key" }) + : undefined, + ), + all: () => + Effect.succeed({ + openrouter: new Auth.Api({ type: "api", key: "test-key" }), + opencode: new Auth.Api({ type: "api", key: "test-key" }), + }), +}) + +const itAuthed = testEffect( + LayerNode.compile( + LayerNode.group([ + Provider.node, + FSUtil.node, + Env.node, + Config.node, + Auth.node, + Plugin.node, + ModelsDev.node, + RuntimeFlags.node, + ]), + [ + [RuntimeFlags.node, RuntimeFlags.layer({})], + [Auth.node, zenAndOpenRouter], + ], + ), +) + const alphaProviderConfig = { provider: { "custom-provider": { @@ -788,6 +824,111 @@ it.instance( { config: { small_model: "anthropic/not-a-real-model" } }, ) +itAuthed.instance("getSmallModel keeps Zen auto-picks free (paid small models are never auto-billed)", () => + Effect.gen(function* () { + const model = yield* Provider.use.getSmallModel(ProviderV2.ID.opencode) + expect(model).toBeUndefined() + }), { timeout: 30_000 }, +) + +it.instance( + "getSmallModel prefers a free model of the small family on Zen", + Effect.gen(function* () { + const model = yield* Provider.use.getSmallModel(ProviderV2.ID.make("opencode-fork-test")) + expect(String(model?.id)).toBe("gpt-5-nano-free") + }), + { + config: { + provider: { + "opencode-fork-test": { + name: "Zen Fork Test", + npm: "@ai-sdk/openai-compatible", + models: { + "gpt-5-nano": { family: "gpt-nano", release_date: "2026-02-01", cost: { input: 0.05, output: 0.4 } }, + "gpt-5-nano-free": { family: "gpt-nano", release_date: "2026-01-01", cost: { input: 0, output: 0 } }, + }, + options: { apiKey: "test-key" }, + }, + }, + }, + }, + { timeout: 30_000 }, +) + +it.instance( + "getSmallModel drops Zen auto-picks when only paid small models exist", + Effect.gen(function* () { + const model = yield* Provider.use.getSmallModel(ProviderV2.ID.make("opencode-fork-test")) + expect(model).toBeUndefined() + }), + { + config: { + provider: { + "opencode-fork-test": { + name: "Zen Fork Test", + npm: "@ai-sdk/openai-compatible", + models: { + "gpt-5.4-nano": { family: "gpt-nano", release_date: "2026-02-01", cost: { input: 0.2, output: 1.25 } }, + "glm-5-free": { family: "glm-free", release_date: "2026-01-01", cost: { input: 0, output: 0 } }, + }, + options: { apiKey: "test-key" }, + }, + }, + }, + }, + { timeout: 30_000 }, +) + +itAuthed.instance("fallbackModel maps a Zen model to its OpenRouter equivalent", () => + Effect.gen(function* () { + const model = yield* Provider.use.getModel(ProviderV2.ID.opencode, ModelV2.ID.make("gpt-5.4-nano")) + const fallback = yield* Provider.use.fallbackModel(model) + expect(String(fallback?.providerID)).toBe("openrouter") + expect(String(fallback?.id)).toBe("openai/gpt-5.4-nano") + }), { timeout: 30_000 }, +) + +itAuthed.instance("fallbackModel strips the free suffix to find the paid twin", () => + Effect.gen(function* () { + const model = yield* Provider.use.getModel(ProviderV2.ID.opencode, ModelV2.ID.make("deepseek-v4-flash-free")) + const fallback = yield* Provider.use.fallbackModel(model) + expect(String(fallback?.id)).toBe("deepseek/deepseek-v4-flash") + }), { timeout: 30_000 }, +) + +it.instance("fallbackModel stays off when OpenRouter is not connected", () => + Effect.gen(function* () { + yield* remove("OPENROUTER_API_KEY") + const model = yield* Provider.use.getModel(ProviderV2.ID.opencode, ModelV2.ID.make("deepseek-v4-flash-free")) + const fallback = yield* Provider.use.fallbackModel(model) + expect(fallback).toBeUndefined() + }), { timeout: 30_000 }, +) + +it.instance( + "fallbackModel never falls back for non-Zen providers", + Effect.gen(function* () { + const model = yield* Provider.use.getModel(ProviderV2.ID.make("acme-support"), ModelV2.ID.make("mini")) + const fallback = yield* Provider.use.fallbackModel(model) + expect(fallback).toBeUndefined() + }), + { + config: { + provider: { + "acme-support": { + name: "Acme Support", + npm: "@ai-sdk/openai-compatible", + models: { + mini: { family: "gpt-nano", release_date: "2026-01-01", cost: { input: 0.1, output: 0.4 } }, + }, + options: { apiKey: "test-key" }, + }, + }, + }, + }, + { timeout: 30_000 }, +) + test("provider.sort prioritizes preferred models", () => { const models = [ { id: "random-model", name: "Random" }, diff --git a/packages/opencode/test/session/compaction.test.ts b/packages/opencode/test/session/compaction.test.ts index 4ec84265..4fafa022 100644 --- a/packages/opencode/test/session/compaction.test.ts +++ b/packages/opencode/test/session/compaction.test.ts @@ -8,7 +8,7 @@ import { Cause, Deferred, Effect, Exit, Fiber, Layer, Schema } from "effect" import * as Stream from "effect/Stream" import { Config } from "@/config/config" import { LLM } from "../../src/session/llm" -import { SessionCompaction } from "../../src/session/compaction" +import { preferredCompactionModel, SessionCompaction } from "../../src/session/compaction" import { Token } from "@/util/token" import { Plugin } from "../../src/plugin" import { provideTmpdirInstance, TestInstance } from "../fixture/fixture" @@ -62,9 +62,10 @@ function createModel(opts: { input?: number cost?: Provider.Model["cost"] npm?: string + id?: string }): Provider.Model { return { - id: "test-model", + id: opts.id ?? "test-model", providerID: "test", name: "Test", limit: { @@ -549,6 +550,37 @@ describe("session.compaction.isOverflow", () => { ) }) +describe("session.compaction.preferredCompactionModel", () => { + const paid = () => + createModel({ + context: 200_000, + output: 32_000, + cost: { input: 1.4, output: 4.4, cache: { read: 0.26, write: 0 } }, + }) + const free = () => createModel({ context: 120_000, output: 32_000 }) + + test("keeps a paid small model", () => { + const main = paid() + const small = paid() + expect(preferredCompactionModel(main, small)).toBe(small) + }) + + test("skips a free small model when the main model bills", () => { + const main = paid() + expect(preferredCompactionModel(main, free())).toBe(main) + }) + + test("keeps a free small model when the main model is free too", () => { + const small = free() + expect(preferredCompactionModel(free(), small)).toBe(small) + }) + + test("uses the main model when no small model resolves", () => { + const main = paid() + expect(preferredCompactionModel(main, undefined)).toBe(main) + }) +}) + describe("session.compaction.create", () => { it.live( "creates a compaction user message and part", @@ -862,6 +894,63 @@ describe("session.compaction.process", () => { }), ) + itCompaction.instance( + "runs on the main model when the small model is free", + () => { + const stub = llm() + let captured: LLM.StreamInput | undefined + stub.push(reply("summary", (input) => (captured = input))) + const main = createModel({ + context: 200_000, + output: 32_000, + cost: { input: 1.4, output: 4.4, cache: { read: 0, write: 0 } }, + }) + const small = createModel({ id: "small-model", context: 120_000, output: 32_000 }) + return Effect.gen(function* () { + const ssn = yield* SessionNs.Service + const session = yield* ssn.create({}) + const msg = yield* createUserMessage(session.id, "hello") + const msgs = yield* ssn.messages({ sessionID: session.id }) + yield* SessionCompaction.use.process({ parentID: msg.id, messages: msgs, sessionID: session.id, auto: false }) + + expect(captured?.model.id).toBe(ModelV2.ID.make("test-model")) + expect(captured?.model.cost.input).toBe(1.4) + }).pipe(withCompaction({ llm: stub.llmLayer, provider: ProviderTest.fake({ model: main, small }) })) + }, + { git: true }, + ) + + itCompaction.instance( + "runs on a paid small model when configured", + () => { + const stub = llm() + let captured: LLM.StreamInput | undefined + stub.push(reply("summary", (input) => (captured = input))) + const main = createModel({ + context: 200_000, + output: 32_000, + cost: { input: 1.4, output: 4.4, cache: { read: 0, write: 0 } }, + }) + const small = createModel({ + id: "small-model", + context: 120_000, + output: 32_000, + cost: { input: 0.1, output: 0.2, cache: { read: 0.01, write: 0 } }, + }) + return Effect.gen(function* () { + const ssn = yield* SessionNs.Service + const session = yield* ssn.create({}) + const msg = yield* createUserMessage(session.id, "hello") + const msgs = yield* ssn.messages({ sessionID: session.id }) + yield* SessionCompaction.use.process({ parentID: msg.id, messages: msgs, sessionID: session.id, auto: false }) + + expect(captured?.model.id).toBe(ModelV2.ID.make("small-model")) + expect(captured?.model.cost.input).toBe(0.1) + }).pipe(withCompaction({ llm: stub.llmLayer, provider: ProviderTest.fake({ model: main, small }) })) + }, + { git: true }, + ) + itCompaction.instance( "marks summary message as errored on compact result", Effect.gen(function* () { diff --git a/packages/opencode/test/session/message-v2.test.ts b/packages/opencode/test/session/message-v2.test.ts index c6431df8..d1c06a33 100644 --- a/packages/opencode/test/session/message-v2.test.ts +++ b/packages/opencode/test/session/message-v2.test.ts @@ -1450,6 +1450,7 @@ describe("session.message-v2.fromError", () => { "The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)", "tokens in request more than max tokens allowed", "Please reduce the length of the messages or completion", + "This prompt is longer than the free tier allows for a single request. Shorten it, or add credits to use this model without the free-tier cap: https://www.orcarouter.ai/console/billing (request id: 202610171546264717739908268d9d6AZZdG7sq)", "400 status code (no body)", "413 status code (no body)", ] diff --git a/packages/opencode/test/session/retry.test.ts b/packages/opencode/test/session/retry.test.ts index 7e7e6065..5b8612a3 100644 --- a/packages/opencode/test/session/retry.test.ts +++ b/packages/opencode/test/session/retry.test.ts @@ -254,6 +254,58 @@ describe("session.retry.retryable", () => { expect(retryable).toEqual({ message: "Response decompression failed" }) }) + test("flags unfunded Zen accounts for fallback", () => { + const error = Schema.decodeUnknownSync(SessionV1.APIError.Schema)( + new SessionV1.APIError({ + message: "Insufficient account funds", + isRetryable: false, + statusCode: 402, + }).toObject(), + ) + + expect(SessionRetry.billingBlocked(error)).toBe(true) + }) + + test("flags a closed free-tier gate for fallback", () => { + const error = Schema.decodeUnknownSync(SessionV1.APIError.Schema)( + new SessionV1.APIError({ + message: "OpenCode's free tier can only be used from within OpenCode.", + isRetryable: false, + statusCode: 403, + }).toObject(), + ) + + expect(SessionRetry.billingBlocked(error)).toBe(true) + }) + + test("flags an exhausted free quota for fallback", () => { + const error = Schema.decodeUnknownSync(SessionV1.APIError.Schema)( + new SessionV1.APIError({ + message: "Free usage exceeded", + isRetryable: true, + statusCode: 429, + responseBody: JSON.stringify({ + type: "error", + error: { type: "FreeUsageLimitError", message: "Free usage exceeded" }, + }), + }).toObject(), + ) + + expect(SessionRetry.billingBlocked(error)).toBe(true) + }) + + test("does not flag ordinary API errors for fallback", () => { + const error = Schema.decodeUnknownSync(SessionV1.APIError.Schema)( + new SessionV1.APIError({ + message: "Bad request", + isRetryable: false, + statusCode: 400, + }).toObject(), + ) + + expect(SessionRetry.billingBlocked(error)).toBe(false) + }) + test("maps free limits to Go upsell action", () => { const error = Schema.decodeUnknownSync(SessionV1.APIError.Schema)( new SessionV1.APIError({ diff --git a/packages/plugin/src/tui.ts b/packages/plugin/src/tui.ts index e479cb7c..ae399718 100644 --- a/packages/plugin/src/tui.ts +++ b/packages/plugin/src/tui.ts @@ -386,6 +386,9 @@ export type TuiState = { session: { count: () => number get: (sessionID: string) => Session | undefined + // Self cost plus every descendant session (subagents, recursively) — the + // full cost of a session tree, including subagents. + treeCost: (sessionID: string) => number diff: (sessionID: string) => ReadonlyArray todo: (sessionID: string) => ReadonlyArray messages: (sessionID: string) => ReadonlyArray diff --git a/packages/tui/src/app.tsx b/packages/tui/src/app.tsx index df05c2aa..a9310b59 100644 --- a/packages/tui/src/app.tsx +++ b/packages/tui/src/app.tsx @@ -580,6 +580,16 @@ function App(props: { onSnapshot?: () => Promise; pluginHost: TuiPlugi dialog.replace(() => ) }, }, + { + name: "engagement.select", + title: "Switch engagement", + category: "Engagement", + slashName: "engagement", + slashAliases: ["engagements", "eng"], + run: () => { + dialog.replace(() => ) + }, + }, { name: "session.list", title: "Switch session", diff --git a/packages/tui/src/component/prompt/index.tsx b/packages/tui/src/component/prompt/index.tsx index b4de0d19..0d450b40 100644 --- a/packages/tui/src/component/prompt/index.tsx +++ b/packages/tui/src/component/prompt/index.tsx @@ -260,7 +260,6 @@ export function Prompt(props: PromptProps) { const usage = createMemo(() => { if (!props.sessionID) return - const session = sync.session.get(props.sessionID) const msg = sync.data.message[props.sessionID] ?? [] const last = msg.findLast((item): item is AssistantMessage => item.role === "assistant" && item.tokens.output > 0) if (!last) return @@ -271,7 +270,8 @@ export function Prompt(props: PromptProps) { const model = sync.data.provider.find((item) => item.id === last.providerID)?.models[last.modelID] const pct = model?.limit.context ? `${Math.round((tokens / model.limit.context) * 100)}%` : undefined - const cost = session?.cost ?? 0 + // Full tree cost (this session + all subagents, recursively). + const cost = sync.session.treeCost(props.sessionID) return { context: pct ? `${Locale.number(tokens)} (${pct})` : Locale.number(tokens), cost: cost > 0 ? money.format(cost) : undefined, diff --git a/packages/tui/src/context/sync.tsx b/packages/tui/src/context/sync.tsx index 1c8fe188..8627c7b1 100644 --- a/packages/tui/src/context/sync.tsx +++ b/packages/tui/src/context/sync.tsx @@ -568,6 +568,28 @@ export const { if (match.found) return store.session[match.index] return undefined }, + // Self cost of `sessionID` plus every descendant session (subagents, + // recursively) — the full cost of a session tree. + treeCost(sessionID: string) { + const byParent = new Map() + for (const item of store.session) { + const key = item.parentID ?? "" + const list = byParent.get(key) + if (list) list.push(item.id) + else byParent.set(key, [item.id]) + } + let total = 0 + const seen = new Set() + const frontier = [sessionID] + while (frontier.length > 0) { + const id = frontier.pop()! + if (seen.has(id)) continue + seen.add(id) + total += result.session.get(id)?.cost ?? 0 + for (const child of byParent.get(id) ?? []) frontier.push(child) + } + return total + }, query() { return sessionListQuery() }, diff --git a/packages/tui/src/feature-plugins/sidebar/context.tsx b/packages/tui/src/feature-plugins/sidebar/context.tsx index 3f05ea3e..ef334cc7 100644 --- a/packages/tui/src/feature-plugins/sidebar/context.tsx +++ b/packages/tui/src/feature-plugins/sidebar/context.tsx @@ -13,8 +13,8 @@ const money = new Intl.NumberFormat("en-US", { function View(props: { api: TuiPluginApi; session_id: string }) { const theme = () => props.api.theme.current const msg = createMemo(() => props.api.state.session.messages(props.session_id)) - const session = createMemo(() => props.api.state.session.get(props.session_id)) - const cost = createMemo(() => session()?.cost ?? 0) + // Full tree cost — this session plus every subagent it spawned (recursively). + const cost = createMemo(() => props.api.state.session.treeCost(props.session_id)) const state = createMemo(() => { const last = msg().findLast((item): item is AssistantMessage => item.role === "assistant" && item.tokens.output > 0) diff --git a/packages/tui/src/plugin/adapters.tsx b/packages/tui/src/plugin/adapters.tsx index 6a8d4b86..64a883b8 100644 --- a/packages/tui/src/plugin/adapters.tsx +++ b/packages/tui/src/plugin/adapters.tsx @@ -123,6 +123,9 @@ function stateApi(sync: ReturnType): TuiPluginApi["state"] { get(sessionID) { return sync.session.get(sessionID) }, + treeCost(sessionID) { + return sync.session.treeCost(sessionID) + }, diff(sessionID) { return (sync.data.session_diff[sessionID] ?? []).flatMap((item) => item.file === undefined ? [] : [{ ...item, file: item.file }], diff --git a/packages/tui/src/routes/session/subagent-footer.tsx b/packages/tui/src/routes/session/subagent-footer.tsx index 5d924d7a..0b7e219f 100644 --- a/packages/tui/src/routes/session/subagent-footer.tsx +++ b/packages/tui/src/routes/session/subagent-footer.tsx @@ -41,7 +41,8 @@ export function SubagentFooter() { const model = sync.data.provider.find((item) => item.id === last.providerID)?.models[last.modelID] const pct = model?.limit.context ? `${Math.round((tokens / model.limit.context) * 100)}%` : undefined - const cost = session()?.cost ?? 0 + // Full tree cost (this subagent + any nested subagents, recursively). + const cost = sync.session.treeCost(route.sessionID) const money = new Intl.NumberFormat("en-US", { style: "currency", diff --git a/skills/playbooks/cloud/SKILL.md b/skills/playbooks/cloud/SKILL.md index ef034935..84d0b0bc 100644 --- a/skills/playbooks/cloud/SKILL.md +++ b/skills/playbooks/cloud/SKILL.md @@ -43,8 +43,3 @@ Tools: `pacu` (automated), `pmapper` (permission graph) - User-data scripts (bootstrap credentials) - MFA not enforced on admin accounts - Audit logging disabled or misconfigured - -## Post-creds audit tools -- **AWS**: `pacu` (exploitation framework, modular), `pmapper` (privesc graph) -- **Multi-cloud posture**: `scoutsuite` (inventory + misconfig report per provider), `prowler` (AWS/GCP/Azure compliance checks, CIS benchmarks) -- Run posture scan FIRST after getting creds — misconfig findings often beat privesc chains. diff --git a/skills/research/source-audit/SKILL.md b/skills/research/source-audit/SKILL.md new file mode 100644 index 00000000..2c46f3f8 --- /dev/null +++ b/skills/research/source-audit/SKILL.md @@ -0,0 +1,73 @@ +--- +name: source-audit +description: Find NOVEL vulnerabilities in a target's own source or binaries — source review, SAST (semgrep), variant analysis, patch-diffing (n-day→variant), and fuzz-harness bring-up. Use when the target runs software whose code you can obtain and the goal is depth, not just a shell — "no public CVE" is not "no bug". Triggers - in-scope open-source dependency at a pinned version, client custom app source, extracted firmware/appliance, a suspicious parser/deserializer/auth handler, a known CVE whose fix might be incomplete or have untouched siblings. +tags: [vuln_assess, research] +--- + +# Source Audit & Vulnerability Research + +## When this fires +You can obtain the exact in-scope version's code (git tag, package source, extracted firmware, client repo) and the objective rewards a *new* bug: a parser/protocol handler, deserializer, auth/session logic, template/command execution, or memory-unsafe C/C++. Also whenever a known CVE looks like it might have an incomplete fix or an unpatched sibling code path. This is the nginx2root discipline — bugs found by reading code and diffing fixes, not by scanning a live host. + +## The loop (coverage-led, disprove-first — this is what finds real bugs) +Map → hunt by coverage → disprove each candidate → prove the survivors → repeat. Four rules make the difference between an audit and a lucky grep: +1. **Coverage ledger.** Write the attack surface as discrete UNITS (each parser, handler, deserializer, lifecycle path) and track what you checked per unit. When you think you're done, sweep the ledger for units you never hunted and go back. Tunnel vision is how decade-old bugs survive thousands of eyes. +2. **Finder ≠ verifier.** Never confirm your own lead. Each candidate goes to a fresh verifier (spawn `critic`, or re-examine with clean context) that tries to DISPROVE it — find the sanitizer, the bounds check, the unreachable guard. Verdicts: CONFIRMED / NEEDS_MORE_EVIDENCE / FALSE_POSITIVE. +3. **Multi-pass.** One sweep finds ~half. Re-run on the same pinned source, reusing the ledger to hit the gaps, until new candidates stop appearing. +4. **Sandbox to execute.** Build / fuzz / PoC target code only inside an isolated sandbox (the drost Kali container or a disposable VM) — never a live host, never your own env. No sandbox → the finding stays suspected, never confirmed. + +Where the bugs are, in priority: cross-boundary / rarely-exercised fast paths (intrinsics, JIT, flow control) · object lifecycle (alloc/free/reuse → UAF) · length/integer/index math (→ OOB) · untrusted parsers · and the *interactions* between two individually-well-tested features. + +## Map first (tool-first, low-noise) +Pin the version, then connect UNTRUSTED entry points to dangerous sinks — a bug is only real if input reaches a sink unsanitized. +```bash +# obtain + pin (into the engagement workdir) +git clone --depth 1 --branch src && (cd src && git rev-parse HEAD) +# sinks: command/exec, memory ops, deserialization, path joins, interpolation +rg -n "system\(|popen\(|exec[lv]|memcpy|strcpy|sprintf|pickle|unserialize|readObject|eval\(|Runtime.getRuntime|\.\./" src +# entry points: request/arg parsers, route handlers, format/file loaders, auth +rg -n "parse|handler|route|deserialize|loads|read_|recv|fread|getenv|request\." src +``` +Note, per sink, whether an untrusted entry reaches it without a sanitizer. That list is your hunt queue. + +## Detect — SAST + variants + fuzz +```bash +# 1) SAST sweep → fold leads into state (every hit is a LEAD, not a bug) +semgrep --config auto --json -o sg.json src # then: semgrep_parse input=sg.json host= +semgrep --config p/ --config p/security-audit --json -o sg2.json src +# 1b) CROSS-FUNCTION dataflow (what semgrep CANNOT do — UAF/integer/OOB across fn boundaries = the nginx2root shape) +codeql database create db --language=cpp --command='make -j' && \ + codeql database analyze db codeql/cpp-queries:codeql-suites/cpp-security-extended.qls \ + --format=sarifv2.1.0 --output=cq.sarif # then: codeql_parse input=cq.sarif host= +# other langs: --language=java|go|python|javascript + the matching -security-extended suite +# Joern alternative (no build needed): joern-parse src && joern --script flows.sc (reachableByFlows → SARIF → codeql_parse) +# 2) variant analysis / patch-diff (highest hit-rate): diff vulnerable vs fixed +git -C src log --oneline -- ; git -C src diff ~1 -- +# then write a rule for the pattern and sweep the WHOLE tree for siblings: +semgrep -e '' --lang --json -o variants.json src # → semgrep_parse +# 3) fuzz a parser (time-boxed) — one reproducible ASAN crash from untrusted input is a finding +# C/C++: clang -g -fsanitize=address,fuzzer harness.c -o fuzz && ./fuzz -max_total_time=300 corpus/ +# Python: atheris ; Go: go test -fuzz=Fuzz -fuzztime=300s +``` +Use a custom Semgrep rule (`-e`/`--config `) for variant analysis — that is what turns one known bug into several. + +## Decide +- SAST hit in a sanitized/unreachable path → kill it (false positive), record the dead end. +- Reachable sink with attacker-influenced input → trace it by hand, this is a real lead. +- Known-CVE fix that only patched one call site / one input shape → hunt the siblings (incomplete-fix variant). +- Parser/format handler on untrusted input and no obvious logic bug → fuzz it. +- Memory-corruption primitive confirmed reachable → hand weaponization to `exploit_dev` / kernel agent; your job is bug + reachability, not the ROP chain. + +## Exploit → PROVE REACHABILITY +A static match / fuzz crash / pattern hit is SUSPECTED. Promote to confirmed only with: the concrete **source** (where untrusted input enters), the **path** to the **sink**, sanitizers ruled out, and a trigger artifact. +**Proof required:** a reproducible crash (ASAN stack at the sink), a value demonstrably reaching the sink, a file/secret read, or `id` if it escalates to RCE. "semgrep flagged it" or "it crashed once" without a repro is a lead, not proof. Prioritize by reachability-from-untrusted-input, never by SAST severity — a reachable medium in a parser beats an unreachable critical. + +## Tooling +`semgrep` (`--config auto`, `-e` for variant rules) → `semgrep_parse` (fast, intra-file). `codeql` / `joern` → `codeql_parse` for CROSS-FUNCTION dataflow (UAF/integer/OOB across function boundaries — the bugs semgrep structurally misses). `patch_diff` for n-day→variant sweeps. `rg`/grep/glob/read for manual audit (your primary instrument). `git log`/`git diff` for patch-diffing. `clang -fsanitize=address,fuzzer` / `atheris` / `go test -fuzz` for harnesses. `ensure_tools` to install what's missing (semgrep/codeql/joern now included). websearch/webfetch for the advisory, the fix commit, and affected-version ranges. + +## False positives / pitfalls +- SAST flags the pattern, not the data flow — most hits are sanitized or unreachable; always trace before recording confirmed. +- Auditing the wrong version — a bug fixed in the tag the target runs is not a finding. Pin first, every time. +- Fuzzing a live production service — don't. Harness and fuzz locally against the code, not the deployed host. +- Crash without a minimized, replayable input → not yet a finding; minimize and reproduce. +- Drowning the coordinator in SAST noise — reconcile every `semgrep_parse` lead (promote or kill); don't leave hundreds of unverified "suspected" rows.