-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreact_loop.rs
More file actions
808 lines (779 loc) · 36.6 KB
/
react_loop.rs
File metadata and controls
808 lines (779 loc) · 36.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
// The ReAct loop: observe → think → act → repeat.
//
// Drives the LLM through tool chain subfinder → httpx → nuclei with
// intelligent skipping, scope guards, and a per-iteration rate limit.
// Produces a RunRecord which is then written to JSON + markdown by `report`.
use crate::config::{Cli, Config};
use crate::findings::{
dedup_findings, extract_hosts_from_subfinder, parse_httpx_output, parse_nuclei_output,
DedupedFinding, Finding, Severity,
};
use crate::llm::{parse_action, strip_think, system_prompt, AgentAction, ChatMessage, LlmClient};
use crate::preflight::run_pius;
use crate::report::render_report;
use super::state::PreflightReport;
use crate::scope::{host_in_scope, normalize_host};
use crate::tools::{
exec_dnsx, exec_ffuf, exec_httpx, exec_nuclei, exec_subfinder, nuclei_templates_root,
parse_dnsx_output, parse_ffuf_output, resolve_wordlist, select_interesting_urls, ToolExecution,
ToolKind,
};
use super::state::{preview, RunRecord, StepRecord};
use anyhow::{bail, Context, Result};
use chrono::Utc;
use std::time::Duration;
pub async fn run_recon(cli: &Cli, domain: &str) -> Result<()> {
let cfg = Config::resolve(cli, domain);
let scope_display = cfg.scope_patterns.join(", ");
println!("[*] AgentSpyBoo Phase 3 (CPU-track + Pius preflight)");
println!("[*] Target : {domain}");
if let Some(ref org) = cfg.org {
println!("[*] Org : {org}");
}
if let Some(ref asn) = cfg.asn {
println!("[*] ASN : {asn}");
}
println!("[*] Scope : {scope_display}");
println!("[*] LLM : {} ({})", cfg.model, cfg.base_url);
println!("[*] Max iterations: {}", cfg.max_iterations);
println!("[*] Rate limit : {}ms", cfg.rate_limit_ms);
println!("[*] httpx cap : {}", cfg.httpx_cap);
println!("[*] nuclei cap : {}", cfg.nuclei_cap);
println!(
"[*] dedup : {}",
if cfg.no_dedup {
"off (--no-dedup)"
} else {
"on"
}
);
println!();
// Preflight: refuse if target itself is out of scope.
if !host_in_scope(domain, &cfg.scope_patterns) {
bail!("target '{domain}' does not match scope patterns {scope_display:?}");
}
// Preflight: warn if nuclei templates are missing — don't fail, the LLM may skip.
if nuclei_templates_root().is_none() {
eprintln!("[!] nuclei-templates not found — run `nuclei -update-templates` once. Nuclei tool calls will error.");
}
let llm = LlmClient::new(&cfg.base_url, &cfg.model, &cfg.api_key);
let started_at = Utc::now();
let sys = system_prompt(domain, &scope_display, cfg.active);
let mut messages: Vec<ChatMessage> = vec![
ChatMessage {
role: "system".into(),
content: sys,
},
ChatMessage {
role: "user".into(),
content: format!(
"Perform a vuln assessment on {domain}. Chain subfinder -> httpx -> nuclei, and skip steps when prior output is empty."
),
},
];
let mut steps: Vec<StepRecord> = Vec::new();
let mut all_findings: Vec<Finding> = Vec::new();
let mut tools_fired: Vec<String> = Vec::new();
let mut last_subfinder_hosts: Vec<String> = Vec::new();
let mut preflight_report: Option<PreflightReport> = None;
// --- Pius preflight (runs before the agent loop if --org is set) ---
if let Some(ref org) = cfg.org {
println!("[*] Running Pius org-level preflight for {org:?}...");
match run_pius(
org,
Some(domain),
cfg.asn.as_deref(),
&cfg.scope_patterns,
cfg.verbose,
)
.await
{
Ok(result) => {
println!(
"[+] Pius: {} domains, {} CIDRs, {} github orgs ({:.1}s)",
result.domains.len(),
result.cidrs.len(),
result.github_orgs.len(),
result.runtime_secs,
);
// Pre-seed subfinder host list with Pius-discovered domains
for d in &result.domains {
if !last_subfinder_hosts.contains(&d.host) {
last_subfinder_hosts.push(d.host.clone());
}
}
// CIDRs go directly to findings as severity::Low
for cidr in &result.cidrs {
let asn_suffix = cidr
.asn
.as_deref()
.map(|a| format!(", asn: {a}"))
.unwrap_or_default();
all_findings.push(Finding::new(
Severity::Low,
"cidr-discovered",
&cidr.cidr,
format!(
"CIDR block discovered via Pius (source: {}{asn_suffix})",
cidr.source
),
));
}
preflight_report = Some(PreflightReport {
org: org.clone(),
asn: cfg.asn.clone(),
mode: "passive".into(),
runtime_secs: result.runtime_secs,
total_raw: result.total_raw,
filtered_out: result.filtered_out,
plugins_fired: result.plugins_fired,
key_status: result.key_status,
domains: result.domains,
cidrs: result.cidrs,
github_orgs: result.github_orgs,
});
println!();
}
Err(e) => {
eprintln!("[!] Pius preflight failed: {e}");
eprintln!("[!] Continuing without org-level recon.");
println!();
}
}
}
let mut last_httpx_urls: Vec<String> = Vec::new();
let mut last_httpx_stdout: String = String::new();
// Records whether nuclei was narrowed from a larger httpx pool (for report methodology note).
let mut nuclei_narrow_note: Option<(usize, usize)> = None;
let mut final_summary = String::new();
let mut next_steps_llm: Vec<String> = Vec::new();
let mut retry_used = false;
for iter in 1..=cfg.max_iterations {
if iter > 1 && cfg.rate_limit_ms > 0 {
tokio::time::sleep(Duration::from_millis(cfg.rate_limit_ms)).await;
}
println!(
"[>] Iteration {iter}/{} — asking LLM for next action...",
cfg.max_iterations
);
let raw = match llm.chat(&messages).await {
Ok(r) => r,
Err(e) => {
eprintln!("[!] LLM call failed: {e:#}");
bail!("LLM error on iteration {iter}: {e}");
}
};
if cfg.verbose {
println!("[<] LLM raw:\n{}\n", raw.trim());
} else {
let short = raw
.trim()
.lines()
.next()
.unwrap_or("")
.chars()
.take(120)
.collect::<String>();
println!("[<] LLM: {short}...");
}
let action = parse_action(&raw);
let action = match action {
Some(a) => a,
None => {
eprintln!("[!] Could not parse JSON action from LLM output");
if !retry_used {
retry_used = true;
println!("[>] Retrying with clarifying system message...");
messages.push(ChatMessage {
role: "assistant".into(),
content: raw.clone(),
});
messages.push(ChatMessage {
role: "system".into(),
content: "Your previous response was not valid JSON. Respond ONLY with a single JSON object like {\"tool\": \"...\", \"arguments\": {...}} or {\"action\": \"done\", \"summary\": \"...\", \"next_steps\": [...]}. No prose.".into(),
});
steps.push(StepRecord {
iteration: iter,
llm_raw: raw,
tool: None,
args: None,
stdout_lines: 0,
stdout_preview: String::new(),
stderr_preview: String::new(),
error: Some("unparseable; retry requested".into()),
duration_ms: 0,
});
continue;
} else {
println!("[!] Retry also failed — treating raw text as final summary");
final_summary = strip_think(&raw).trim().to_string();
steps.push(StepRecord {
iteration: iter,
llm_raw: raw,
tool: None,
args: None,
stdout_lines: 0,
stdout_preview: String::new(),
stderr_preview: String::new(),
error: Some("unparseable after retry".into()),
duration_ms: 0,
});
break;
}
}
};
match action {
AgentAction::Done {
summary,
next_steps,
} => {
println!("[+] LLM signaled done.");
final_summary = summary;
next_steps_llm = next_steps;
steps.push(StepRecord {
iteration: iter,
llm_raw: raw,
tool: Some("done".into()),
args: None,
stdout_lines: 0,
stdout_preview: String::new(),
stderr_preview: String::new(),
error: None,
duration_ms: 0,
});
break;
}
AgentAction::Tool { name, args } => {
let kind = match ToolKind::from_name(&name) {
Some(k) => k,
None => {
let err = format!("unknown tool '{name}'");
println!("[!] {err}");
messages.push(ChatMessage {
role: "assistant".into(),
content: raw.clone(),
});
messages.push(ChatMessage {
role: "user".into(),
content: format!(
"Observation: {err}. Available tools are subfinder, httpx, nuclei. Try again or emit done."
),
});
steps.push(StepRecord {
iteration: iter,
llm_raw: raw,
tool: Some(name),
args: Some(args),
stdout_lines: 0,
stdout_preview: String::new(),
stderr_preview: String::new(),
error: Some(err),
duration_ms: 0,
});
continue;
}
};
println!("[>] Executing {} with args {}", kind.name(), args);
let t0 = std::time::Instant::now();
let exec = match kind {
ToolKind::Subfinder => {
let d = args
.get("domain")
.and_then(|x| x.as_str())
.unwrap_or(domain)
.to_string();
if !host_in_scope(&d, &cfg.scope_patterns) {
println!("[!] scope guard: '{d}' not in scope, skipping subfinder");
ToolExecution {
tool: kind,
args: args.clone(),
stdout: String::new(),
stderr: String::new(),
error: Some(format!("out-of-scope target '{d}'")),
duration_ms: 0,
}
} else {
match exec_subfinder(&d).await {
Ok((so, se)) => ToolExecution {
tool: kind,
args: args.clone(),
stdout: so,
stderr: se,
error: None,
duration_ms: t0.elapsed().as_millis(),
},
Err(e) => ToolExecution {
tool: kind,
args: args.clone(),
stdout: String::new(),
stderr: String::new(),
error: Some(format!("{e:#}")),
duration_ms: t0.elapsed().as_millis(),
},
}
}
}
ToolKind::Httpx => {
let raw_hosts: Vec<String> = if args
.get("hosts_from")
.and_then(|s| s.as_str())
.map(|s| s.eq_ignore_ascii_case("subfinder"))
.unwrap_or(false)
{
last_subfinder_hosts.clone()
} else if let Some(arr) = args.get("hosts").and_then(|h| h.as_array()) {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
} else {
last_subfinder_hosts.clone()
};
// Apply scope guard.
let before = raw_hosts.len();
let scoped: Vec<String> = raw_hosts
.into_iter()
.filter(|h| host_in_scope(h, &cfg.scope_patterns))
.collect();
let dropped = before - scoped.len();
if dropped > 0 {
println!("[!] scope guard: dropped {dropped} out-of-scope hosts before httpx");
}
// dnsx filter: drop NXDOMAIN/SERVFAIL before httpx
// probes them. Preserves CNAME-only hosts via `-cname`.
// Fall back to the raw scoped list when dnsx errors, is
// missing, or returns suspiciously few hits (likely a
// local DNS-resolver hiccup rather than a real filter).
let hosts: Vec<String> = if scoped.is_empty() {
scoped
} else {
match exec_dnsx(&scoped).await {
Ok((so, _se)) => {
let mut resolved = parse_dnsx_output(&so);
resolved.sort();
resolved.dedup();
let kept = resolved.len();
let dropped_dns = scoped.len().saturating_sub(kept);
// Suspicious-low threshold: if scoped had >50
// hosts and dnsx resolved <2%, treat as DNS
// failure rather than a valid filter.
let suspicious_low =
scoped.len() > 50 && kept * 50 < scoped.len();
if kept == 0 || suspicious_low {
println!(
"[!] dnsx resolved {}/{} — suspiciously low, falling back to unfiltered list",
kept, scoped.len()
);
scoped
} else {
println!(
"[*] dnsx: {}/{} hosts resolved ({} dead-DNS dropped)",
kept,
scoped.len(),
dropped_dns
);
resolved
}
}
Err(e) => {
println!("[!] dnsx error ({e:#}); passing raw list to httpx");
scoped
}
}
};
match exec_httpx(&hosts, cfg.httpx_cap).await {
Ok((so, se)) => ToolExecution {
tool: kind,
args: args.clone(),
stdout: so,
stderr: se,
error: None,
duration_ms: t0.elapsed().as_millis(),
},
Err(e) => ToolExecution {
tool: kind,
args: args.clone(),
stdout: String::new(),
stderr: String::new(),
error: Some(format!("{e:#}")),
duration_ms: t0.elapsed().as_millis(),
},
}
}
ToolKind::Nuclei => {
// Prefer explicit URLs from the LLM; otherwise pull from httpx.
// When falling back to httpx, run the interesting-host
// heuristic so nuclei only scans the top N URLs.
let explicit_urls: Option<Vec<String>> =
args.get("urls").and_then(|h| h.as_array()).map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
});
// urls_from is accepted for LLM compatibility but we
// always fall back to httpx when no explicit URLs are
// given — no other source exists in-pipeline.
let _ = args.get("urls_from");
let raw_urls: Vec<String> = if let Some(u) = explicit_urls {
u
} else {
last_httpx_urls.clone()
};
let live_count = last_httpx_urls.len();
let before = raw_urls.len();
let scoped: Vec<String> = raw_urls
.into_iter()
.filter(|u| host_in_scope(u, &cfg.scope_patterns))
.collect();
let dropped = before - scoped.len();
if dropped > 0 {
println!("[!] scope guard: dropped {dropped} out-of-scope urls before nuclei");
}
// Select the most-interesting URLs from the raw httpx
// stdout, then intersect with scoped set. If we don't
// have httpx JSON (e.g. LLM gave explicit URLs), just
// take the first `nuclei_cap` in order.
let urls: Vec<String> = if !last_httpx_stdout.is_empty() {
let ranked = select_interesting_urls(
&last_httpx_stdout,
cfg.nuclei_cap.saturating_mul(4),
);
let scoped_set: std::collections::HashSet<String> =
scoped.iter().cloned().collect();
let mut out: Vec<String> = ranked
.into_iter()
.filter(|u| scoped_set.contains(u))
.take(cfg.nuclei_cap)
.collect();
// If heuristic produced fewer than cap (e.g. LLM
// supplied its own URL list not in stdout), fill
// from the scoped list in order.
if out.len() < cfg.nuclei_cap {
for u in &scoped {
if out.len() >= cfg.nuclei_cap {
break;
}
if !out.contains(u) {
out.push(u.clone());
}
}
}
out
} else {
scoped.iter().take(cfg.nuclei_cap).cloned().collect()
};
if live_count > urls.len() {
nuclei_narrow_note = Some((urls.len(), live_count));
}
println!(
"[>] Executing nuclei against {} of {} live hosts (cap via --nuclei-cap, heuristic: status/tech/non-cdn)",
urls.len(),
live_count
);
match exec_nuclei(&urls).await {
Ok((so, se)) => ToolExecution {
tool: kind,
args: args.clone(),
stdout: so,
stderr: se,
error: None,
duration_ms: t0.elapsed().as_millis(),
},
Err(e) => ToolExecution {
tool: kind,
args: args.clone(),
stdout: String::new(),
stderr: String::new(),
error: Some(format!("{e:#}")),
duration_ms: t0.elapsed().as_millis(),
},
}
}
ToolKind::Ffuf => {
// Active mode: ffuf must pick one live URL at a time.
// Prefer the LLM's explicit "url" arg; otherwise fall
// back to the first scoped URL from last httpx run.
let llm_url = args.get("url").and_then(|u| u.as_str()).map(String::from);
let target_url = llm_url.unwrap_or_else(|| {
last_httpx_urls
.iter()
.find(|u| host_in_scope(u, &cfg.scope_patterns))
.cloned()
.unwrap_or_default()
});
if target_url.is_empty() {
ToolExecution {
tool: kind,
args: args.clone(),
stdout: String::new(),
stderr: String::new(),
error: Some(
"no URL supplied and no live httpx URL available".into(),
),
duration_ms: t0.elapsed().as_millis(),
}
} else if !host_in_scope(&target_url, &cfg.scope_patterns) {
println!(
"[!] scope guard: ffuf URL '{target_url}' not in scope, skipping"
);
ToolExecution {
tool: kind,
args: args.clone(),
stdout: String::new(),
stderr: String::new(),
error: Some(format!("out-of-scope ffuf URL '{target_url}'")),
duration_ms: t0.elapsed().as_millis(),
}
} else {
match resolve_wordlist(cfg.ffuf_wordlist.as_deref()) {
Ok((wl, _is_tmp)) => {
println!(
"[>] ffuf path-fuzzing {} (wordlist: {})",
target_url,
wl.display()
);
match exec_ffuf(&target_url, &wl).await {
Ok((so, se)) => ToolExecution {
tool: kind,
args: args.clone(),
stdout: so,
stderr: se,
error: None,
duration_ms: t0.elapsed().as_millis(),
},
Err(e) => ToolExecution {
tool: kind,
args: args.clone(),
stdout: String::new(),
stderr: String::new(),
error: Some(format!("{e:#}")),
duration_ms: t0.elapsed().as_millis(),
},
}
}
Err(e) => ToolExecution {
tool: kind,
args: args.clone(),
stdout: String::new(),
stderr: String::new(),
error: Some(format!("wordlist resolve failed: {e:#}")),
duration_ms: t0.elapsed().as_millis(),
},
}
}
}
};
let line_count = exec.stdout.lines().filter(|l| !l.trim().is_empty()).count();
if let Some(err) = &exec.error {
println!("[!] {} error: {}", kind.name(), err);
} else {
println!(
"[+] {} returned {} lines in {} ms",
kind.name(),
line_count,
exec.duration_ms
);
if cfg.verbose {
for l in exec.stdout.lines().take(8) {
println!(" {l}");
}
}
if !tools_fired.contains(&kind.name().to_string()) {
tools_fired.push(kind.name().to_string());
}
}
// Post-processing per tool: collect findings + cache outputs.
match kind {
ToolKind::Subfinder => {
if exec.error.is_none() {
last_subfinder_hosts = extract_hosts_from_subfinder(&exec.stdout);
for h in &last_subfinder_hosts {
all_findings.push(Finding::new(
Severity::Info,
"subdomain",
h.clone(),
"discovered via subfinder",
));
}
}
}
ToolKind::Httpx => {
if exec.error.is_none() {
let (urls, httpx_findings) = parse_httpx_output(&exec.stdout);
last_httpx_urls = urls;
last_httpx_stdout = exec.stdout.clone();
all_findings.extend(httpx_findings);
}
}
ToolKind::Nuclei => {
if exec.error.is_none() {
let n = parse_nuclei_output(&exec.stdout);
all_findings.extend(n);
}
}
ToolKind::Ffuf => {
if exec.error.is_none() {
// Pull the host out of the URL string the LLM
// passed (or fall back to the target). Cheap
// string parse — avoids pulling in the url crate.
let host = args
.get("url")
.and_then(|u| u.as_str())
.map(normalize_host)
.unwrap_or_else(|| domain.to_string());
let f = parse_ffuf_output(&exec.stdout, &host);
all_findings.extend(f);
}
}
}
// Feed a SLIM observation back to the LLM. Full httpx/nuclei JSON
// blows Lemonade's context window on Qwen3-1.7B. Summarize instead.
let observation = if let Some(err) = &exec.error {
format!("Observation: {} FAILED: {}", kind.name(), err)
} else if line_count == 0 {
format!(
"Observation: {} returned 0 lines (empty). Per rules, emit done now.",
kind.name()
)
} else {
let slim = match kind {
ToolKind::Subfinder => {
let hosts: Vec<&str> = exec
.stdout
.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty())
.take(10)
.collect();
format!(
"{} subdomains found. First {}: {}",
line_count,
hosts.len(),
hosts.join(", ")
)
}
ToolKind::Httpx => {
let urls: Vec<String> =
last_httpx_urls.iter().take(10).cloned().collect();
format!(
"{} live hosts responded. First {}: {}",
line_count,
urls.len(),
urls.join(", ")
)
}
ToolKind::Nuclei => {
let n = all_findings.iter().filter(|f| f.kind == "nuclei").count();
format!(
"nuclei scan complete: {} JSONL lines, {} parsed findings. Next step should be done.",
line_count, n
)
}
ToolKind::Ffuf => {
let n = all_findings.iter().filter(|f| f.kind == "ffuf").count();
format!(
"ffuf path-fuzz complete: {} parsed findings. Next step should be done unless you want to fuzz another live host.",
n
)
}
};
format!("Observation: {}. {}", kind.name(), slim)
};
messages.push(ChatMessage {
role: "assistant".into(),
content: raw.clone(),
});
messages.push(ChatMessage {
role: "user".into(),
content: format!(
"{observation}\n\nWhat next? Respond with a single JSON action."
),
});
steps.push(StepRecord {
iteration: iter,
llm_raw: raw,
tool: Some(kind.name().into()),
args: Some(exec.args.clone()),
stdout_lines: line_count,
stdout_preview: preview(&exec.stdout, 25),
stderr_preview: preview(&exec.stderr, 8),
error: exec.error.clone(),
duration_ms: exec.duration_ms,
});
}
}
}
// If we ran out of iterations with no done, force a summary.
if final_summary.is_empty() {
println!("[>] Loop hit max iterations — requesting final summary...");
messages.push(ChatMessage {
role: "user".into(),
content: "You've hit the iteration cap. Reply ONLY with {\"action\": \"done\", \"summary\": \"...\", \"next_steps\": [\"...\"]} summarizing what you found in 3-5 sentences.".into(),
});
if let Ok(raw) = llm.chat(&messages).await {
match parse_action(&raw) {
Some(AgentAction::Done {
summary,
next_steps,
}) => {
final_summary = summary;
next_steps_llm = next_steps;
}
_ => final_summary = strip_think(&raw).trim().to_string(),
}
}
}
// Sort raw findings by severity desc for report rendering.
all_findings.sort_by_key(|f| std::cmp::Reverse(f.severity));
let raw_findings_view = all_findings.clone();
// Dedup (default) or passthrough.
let findings_view: Vec<DedupedFinding> = if cfg.no_dedup {
all_findings
.iter()
.map(|f| DedupedFinding {
severity: f.severity,
kind: f.kind.clone(),
targets: vec![f.target.clone()],
details: f.details.clone(),
count: 1,
first_seen: f.first_seen,
})
.collect()
} else {
dedup_findings(&all_findings)
};
let finished_at = Utc::now();
let record = RunRecord {
target: domain.to_string(),
started_at,
finished_at,
iterations: steps.len(),
model: cfg.model.clone(),
scope: cfg.scope_patterns.clone(),
tools_fired: tools_fired.clone(),
steps,
findings: findings_view,
raw_findings: raw_findings_view,
dedup_enabled: !cfg.no_dedup,
final_summary: final_summary.clone(),
next_steps: next_steps_llm,
nuclei_narrow: nuclei_narrow_note,
preflight: preflight_report,
};
let ts = started_at.format("%Y%m%dT%H%M%SZ").to_string();
let findings_dir = std::path::Path::new("findings");
let reports_dir = std::path::Path::new("reports");
std::fs::create_dir_all(findings_dir).context("create findings/")?;
std::fs::create_dir_all(reports_dir).context("create reports/")?;
let findings_path = findings_dir.join(format!("{}-{}.json", domain, ts));
let report_path = reports_dir.join(format!("{}-{}.md", domain, ts));
std::fs::write(&findings_path, serde_json::to_string_pretty(&record)?)
.context("write findings json")?;
std::fs::write(&report_path, render_report(&record)).context("write markdown report")?;
println!();
println!("========== AGENT SUMMARY ==========");
println!("{}", final_summary.trim());
println!("===================================");
println!("[+] Findings : {}", findings_path.display());
println!("[+] Report : {}", report_path.display());
Ok(())
}