mirror of
https://github.com/CyberSecurityUP/NeuroSploit.git
synced 2026-11-25 21:54:26 +01:00
feat(harness): per-agent token ledger and opt-in shared prompt prefix
- usage.rs records provider-reported input/output/cached tokens per agent (HTTP API, claude CLI, codex) and writes usage.json plus a run summary. Observational only; budget gates are unchanged. - NEUROSPLOIT_PROMPT_PREFIX=1 moves the block shared by all exploit agents to the front of the system message so provider prompt caches can hit. Off by default; the prompt is unchanged when unset.
This commit is contained in:
1 parent
14afa7e8ca
commit
23c2fc684f
5 files changed
+196
-10
No files matched your search
@@ -57,6 +57,7 @@ pub mod taint;
|
||||
pub mod traces;
|
||||
pub mod transport;
|
||||
pub mod types;
|
||||
pub mod usage;
|
||||
pub mod typesafe;
|
||||
pub mod typesafe_agent;
|
||||
pub mod uncertainty;
|
||||
|
||||
@@ -158,6 +158,12 @@ impl ChatClient {
|
||||
/// One chat completion. Errors (missing key, network, non-2xx) propagate so
|
||||
/// the pool can fail over to the next candidate model.
|
||||
pub async fn chat(&self, m: &ModelRef, system: &str, user: &str) -> Result<String> {
|
||||
self.chat_labeled("", m, system, user).await
|
||||
}
|
||||
|
||||
/// Same as [`chat`], attributing the provider-reported usage to `label` in
|
||||
/// the [`crate::usage`] ledger.
|
||||
pub async fn chat_labeled(&self, label: &str, m: &ModelRef, system: &str, user: &str) -> Result<String> {
|
||||
let p = provider_for(&m.provider)
|
||||
.ok_or_else(|| anyhow!("unknown provider '{}'", m.provider))?;
|
||||
let key = resolve_key(&p);
|
||||
@@ -250,6 +256,9 @@ impl ChatClient {
|
||||
));
|
||||
}
|
||||
};
|
||||
if let Some((i, o, c)) = v.get("usage").and_then(crate::usage::parse) {
|
||||
crate::usage::record(label, i, o, c);
|
||||
}
|
||||
let choice = &v["choices"][0];
|
||||
if choice.is_null() {
|
||||
// Some providers signal a soft failure with an empty `choices` and an
|
||||
@@ -532,6 +541,11 @@ impl ChatClient {
|
||||
let ti = v.pointer("/usage/input_tokens").and_then(|x| x.as_u64());
|
||||
let to = v.pointer("/usage/output_tokens").and_then(|x| x.as_u64());
|
||||
let cost = v.get("total_cost_usd").and_then(|x| x.as_f64());
|
||||
if let Some(u) = v.get("usage") {
|
||||
if let Some((i, o, c)) = crate::usage::parse(u) {
|
||||
crate::usage::record(label, i, o, c);
|
||||
}
|
||||
}
|
||||
if ti.is_some() || to.is_some() || cost.is_some() {
|
||||
emit(format!("tokens: in={} out={} cost=${:.4}",
|
||||
ti.unwrap_or(0), to.unwrap_or(0), cost.unwrap_or(0.0)));
|
||||
@@ -656,6 +670,11 @@ impl ChatClient {
|
||||
"turn.completed" => {
|
||||
let ti = v.pointer("/usage/input_tokens").and_then(|x| x.as_u64());
|
||||
let to = v.pointer("/usage/output_tokens").and_then(|x| x.as_u64());
|
||||
if let Some(u) = v.get("usage") {
|
||||
if let Some((i, o, c)) = crate::usage::parse(u) {
|
||||
crate::usage::record(label, i, o, c);
|
||||
}
|
||||
}
|
||||
if ti.is_some() || to.is_some() {
|
||||
emit(format!("tokens: in={} out={}", ti.unwrap_or(0), to.unwrap_or(0)));
|
||||
}
|
||||
|
||||
@@ -142,6 +142,12 @@ const RECON_SYS: &str = "You are an elite web recon specialist on an AUTHORIZED
|
||||
Prioritise auth/reset/payment/upload/admin/export flows and the less-hardened subdomains.\n\
|
||||
Base everything on real observed responses — never assume. Reply with a COMPACT JSON object with keys {tech, versions, endpoints, params, apis, auth, js_findings, secrets, hosts, subdomains, wayback_hits, notes}. No prose.";
|
||||
|
||||
/// `NEUROSPLOIT_PROMPT_PREFIX=1` moves the block shared by every exploit agent
|
||||
/// to the front of the system message so provider prompt caches can hit on it.
|
||||
fn prompt_prefix_enabled() -> bool {
|
||||
std::env::var("NEUROSPLOIT_PROMPT_PREFIX").map(|v| v == "1" || v.eq_ignore_ascii_case("true")).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Operator directives (focus instructions + auth material) prepended to
|
||||
/// recon/exploit prompts so the engagement is steered as the user asked.
|
||||
fn operator_directives(cfg: &RunConfig) -> String {
|
||||
@@ -1448,8 +1454,21 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender
|
||||
let budget_warner = std::sync::Arc::new(crate::resilience::BudgetWarner::new());
|
||||
|
||||
let snap_ref = snapshot.as_ref();
|
||||
// Everything every exploit agent receives identically (directives, doctrines,
|
||||
// evidence contract). Providers cache by identical prefix from the first
|
||||
// token, so with NEUROSPLOIT_PROMPT_PREFIX=1 this block leads the system
|
||||
// message instead of sitting behind each agent's own system prompt. Off by
|
||||
// default: the prompt is then byte-for-byte what it was.
|
||||
let shared_block = format!(
|
||||
"{directives}{react}{depth}{decision}{explore}{spa}{safety}{ops}{doctrine}{shots}",
|
||||
directives = directives, react = REACT_DOCTRINE, depth = DEPTH_DOCTRINE, decision = DECISION_DOCTRINE,
|
||||
explore = EXPLORE_DOCTRINE, spa = spa, safety = SAFETY_DOCTRINE, ops = ops,
|
||||
doctrine = tool_doctrine(mcp_on), shots = shots,
|
||||
);
|
||||
let prefix_on = prompt_prefix_enabled();
|
||||
let raw: Vec<(String, String, Vec<Finding>)> = stream::iter(selected.iter().cloned())
|
||||
.map(|ag| {
|
||||
let shared_block = shared_block.clone();
|
||||
let target = target.clone();
|
||||
let recon = recon_ctx.clone();
|
||||
let directives = directives.clone();
|
||||
@@ -1482,10 +1501,15 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender
|
||||
if verbose {
|
||||
let _ = txc.send(format!(" ▶ launching agent: {} ({})", ag.name, ag.title.replace(" Agent", ""))).await;
|
||||
}
|
||||
let (system_eff, shared_in_user) = if prefix_on {
|
||||
(format!("{shared_block}\n\n{}", ag.system), String::new())
|
||||
} else {
|
||||
(ag.system.clone(), shared_block.clone())
|
||||
};
|
||||
let user = format!(
|
||||
"AUTHORIZED engagement — you have explicit permission to test {target}. \
|
||||
Do not ask for confirmation — proceed and PROVE each issue.\n\n\
|
||||
{directives}{react}{depth}{decision}{explore}{spa}{safety}{ops}{doctrine}{shots}{body}\n\nWhen done, reply with ONLY a JSON array of confirmed findings (may be empty []). \
|
||||
{shared_in_user}{body}\n\nWhen done, reply with ONLY a JSON array of confirmed findings (may be empty []). \
|
||||
Each item: {{id,title,severity,cwe,endpoint,location,payload,evidence,repro_steps,impact,remediation,confidence,auth_context,account,secret,screenshots}}. \
|
||||
Write for a developer who has never seen this app and has to fix it today:\n\
|
||||
- `location`: EXACTLY where it is — the parameter, form field, header, JSON key, or flow step (e.g. \"POST /api/orders, JSON field `role`\"). An endpoint alone sends them hunting.\n\
|
||||
@@ -1505,15 +1529,10 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender
|
||||
Set `auth_context` to \"authenticated\" or \"unauthenticated\"; set `account` to the test user/role you used (if any); \
|
||||
for a created test account set `secret` to its generated password (it is stored in the run vault and masked in the report).",
|
||||
target = target,
|
||||
directives = directives,
|
||||
react = REACT_DOCTRINE,
|
||||
depth = DEPTH_DOCTRINE, decision = DECISION_DOCTRINE, spa = spa, safety = SAFETY_DOCTRINE, explore = EXPLORE_DOCTRINE,
|
||||
ops = ops,
|
||||
doctrine = tool_doctrine(mcp_on),
|
||||
shots = shots,
|
||||
shared_in_user = shared_in_user,
|
||||
body = ag.user.replace("{target}", &target).replace("{recon_json}", &recon),
|
||||
);
|
||||
match pool.complete_routed(Task::Exploit, &ag.name, &ag.system, &user).await {
|
||||
match pool.complete_routed(Task::Exploit, &ag.name, &system_eff, &user).await {
|
||||
Ok((m, text)) => {
|
||||
let f = extract_findings(&text, &ag.name);
|
||||
let _ = txc.send(format!("exploit {} via {} → {} candidate(s)", ag.name, m.label(), f.len())).await;
|
||||
@@ -1554,7 +1573,7 @@ pub async fn run(mut cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sender
|
||||
// Nudge: retry with simplified prompt (skip for auth failures).
|
||||
if !is_auth && !pool.stop_exploiting() {
|
||||
let _ = txc.send(format!("🔄 nudging {} with simplified prompt...", ag.name)).await;
|
||||
let nudged = crate::resilience::nudge_agent(pool, &ag.name, &ag.system, &user, Task::Exploit).await;
|
||||
let nudged = crate::resilience::nudge_agent(pool, &ag.name, &system_eff, &user, Task::Exploit).await;
|
||||
if !nudged.is_empty() {
|
||||
let _ = txc.send(format!("✓ nudge recovered {} finding(s) from {}", nudged.len(), ag.name)).await;
|
||||
return (ag.name.clone(), String::new(), nudged);
|
||||
@@ -3597,6 +3616,16 @@ async fn finish(cfg: RunConfig, _lib: &Library, pool: &ModelPool, recon: String,
|
||||
let _ = tx.send(format!("notify: evidence saved → {}", cfg.workdir.clone().unwrap_or_default())).await;
|
||||
let _ = tx.send(format!("artifacts saved: {}", artifacts.join(", "))).await;
|
||||
}
|
||||
// Provider-reported token usage per agent (observational; see `usage`).
|
||||
{
|
||||
let rep = crate::usage::report();
|
||||
if !rep.is_empty() {
|
||||
let _ = tx.send(rep).await;
|
||||
}
|
||||
if let Some(d) = cfg.workdir.as_deref() {
|
||||
crate::usage::write_json(Path::new(d));
|
||||
}
|
||||
}
|
||||
// Automatic partial summary (phase complete).
|
||||
{
|
||||
let mut by: std::collections::BTreeMap<&str, usize> = Default::default();
|
||||
|
||||
@@ -324,7 +324,7 @@ impl ModelPool {
|
||||
.chat_cli(label, &m.provider, &m.model, system, user, self.mcp_config.as_deref(), progress.clone())
|
||||
.await
|
||||
} else {
|
||||
self.client.chat(m, system, user).await
|
||||
self.client.chat_labeled(label, m, system, user).await
|
||||
}
|
||||
};
|
||||
let r = tokio::select! {
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Per-agent token ledger.
|
||||
//!
|
||||
//! `ModelPool::tokens_used` approximates spend as `response_chars / 4`, which
|
||||
//! counts output only and cannot say whether a prompt change saved anything.
|
||||
//! This ledger records what the provider actually reported — input, output and
|
||||
//! cache-hit tokens — keyed by agent label, so a run can show where its tokens
|
||||
//! went and a prompt-layout change can be measured instead of assumed.
|
||||
//!
|
||||
//! It is observational only: nothing here feeds the budget gates, so enabling
|
||||
//! or ignoring it cannot change which agents run.
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
|
||||
pub struct Usage {
|
||||
pub calls: u64,
|
||||
pub input: u64,
|
||||
pub output: u64,
|
||||
/// Input tokens served from the provider's prompt cache.
|
||||
pub cached: u64,
|
||||
}
|
||||
|
||||
fn ledger() -> &'static Mutex<BTreeMap<String, Usage>> {
|
||||
static L: OnceLock<Mutex<BTreeMap<String, Usage>>> = OnceLock::new();
|
||||
L.get_or_init(|| Mutex::new(BTreeMap::new()))
|
||||
}
|
||||
|
||||
/// Add one call's usage under `label` (empty label → `"(unlabelled)"`).
|
||||
pub fn record(label: &str, input: u64, output: u64, cached: u64) {
|
||||
let key = if label.is_empty() { "(unlabelled)" } else { label };
|
||||
if let Ok(mut l) = ledger().lock() {
|
||||
let e = l.entry(key.to_string()).or_default();
|
||||
e.calls += 1;
|
||||
e.input += input;
|
||||
e.output += output;
|
||||
e.cached += cached;
|
||||
}
|
||||
}
|
||||
|
||||
/// Pull `(input, output, cached)` out of an OpenAI-compatible `usage` object.
|
||||
/// Handles the field spellings seen across providers: `prompt_tokens` /
|
||||
/// `input_tokens`, `completion_tokens` / `output_tokens`, and the cache-hit
|
||||
/// counters (`prompt_tokens_details.cached_tokens`, `prompt_cache_hit_tokens`,
|
||||
/// `cache_read_input_tokens`).
|
||||
pub fn parse(usage: &Value) -> Option<(u64, u64, u64)> {
|
||||
let num = |p: &str| usage.pointer(p).and_then(|x| x.as_u64());
|
||||
let input = num("/prompt_tokens").or_else(|| num("/input_tokens"));
|
||||
let output = num("/completion_tokens").or_else(|| num("/output_tokens"));
|
||||
if input.is_none() && output.is_none() {
|
||||
return None;
|
||||
}
|
||||
let cached = num("/prompt_tokens_details/cached_tokens")
|
||||
.or_else(|| num("/prompt_cache_hit_tokens"))
|
||||
.or_else(|| num("/cache_read_input_tokens"))
|
||||
.unwrap_or(0);
|
||||
Some((input.unwrap_or(0), output.unwrap_or(0), cached))
|
||||
}
|
||||
|
||||
pub fn snapshot() -> Vec<(String, Usage)> {
|
||||
ledger().lock().map(|l| l.iter().map(|(k, v)| (k.clone(), v.clone())).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn total() -> Usage {
|
||||
snapshot().into_iter().fold(Usage::default(), |mut a, (_, u)| {
|
||||
a.calls += u.calls;
|
||||
a.input += u.input;
|
||||
a.output += u.output;
|
||||
a.cached += u.cached;
|
||||
a
|
||||
})
|
||||
}
|
||||
|
||||
/// Human summary: totals, cache-hit share, and the five heaviest agents.
|
||||
/// Empty when nothing was recorded (e.g. a provider that reports no usage).
|
||||
pub fn report() -> String {
|
||||
let t = total();
|
||||
if t.calls == 0 {
|
||||
return String::new();
|
||||
}
|
||||
let hit = if t.input > 0 { t.cached as f64 * 100.0 / t.input as f64 } else { 0.0 };
|
||||
let mut rows = snapshot();
|
||||
rows.sort_by(|a, b| (b.1.input + b.1.output).cmp(&(a.1.input + a.1.output)));
|
||||
let mut s = format!(
|
||||
"token usage: {} call(s) · in {} · out {} · cached {} ({:.0}% of input)",
|
||||
t.calls, t.input, t.output, t.cached, hit
|
||||
);
|
||||
for (k, u) in rows.iter().take(5) {
|
||||
s.push_str(&format!("\n {k}: in {} out {} cached {} ({} call(s))", u.input, u.output, u.cached, u.calls));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Write `usage.json` into `dir`. Best effort — never fails the run.
|
||||
pub fn write_json(dir: &Path) {
|
||||
let rows = snapshot();
|
||||
if rows.is_empty() {
|
||||
return;
|
||||
}
|
||||
let doc = serde_json::json!({ "total": total(), "agents": rows.into_iter().collect::<BTreeMap<_, _>>() });
|
||||
if let Ok(s) = serde_json::to_string_pretty(&doc) {
|
||||
let _ = std::fs::write(dir.join("usage.json"), s);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_openai_and_deepseek_and_anthropic_spellings() {
|
||||
let oa = serde_json::json!({"prompt_tokens": 1200, "completion_tokens": 80,
|
||||
"prompt_tokens_details": {"cached_tokens": 1024}});
|
||||
assert_eq!(parse(&oa), Some((1200, 80, 1024)));
|
||||
let ds = serde_json::json!({"prompt_tokens": 900, "completion_tokens": 10, "prompt_cache_hit_tokens": 512});
|
||||
assert_eq!(parse(&ds), Some((900, 10, 512)));
|
||||
let an = serde_json::json!({"input_tokens": 50, "output_tokens": 7, "cache_read_input_tokens": 30});
|
||||
assert_eq!(parse(&an), Some((50, 7, 30)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_usage_is_none_not_zero() {
|
||||
assert_eq!(parse(&serde_json::json!({})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ledger_accumulates_per_label() {
|
||||
record("usage_test_agent", 100, 10, 40);
|
||||
record("usage_test_agent", 50, 5, 0);
|
||||
let u = snapshot().into_iter().find(|(k, _)| k == "usage_test_agent").unwrap().1;
|
||||
assert_eq!(u, Usage { calls: 2, input: 150, output: 15, cached: 40 });
|
||||
assert!(report().contains("usage_test_agent"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user