refactor: migrate monolithic crate to Cargo Workspace with Clean Architecture
Transform the single binary crate into a 9-crate workspace monorepo: - Root Cargo.toml as [workspace] manager with resolver = "2" - zesdex-entities: Domain entity types (session, settings, store, message, etc.) - zesdex-utils: Pure utility functions (error, logger, pagination, slug, clipboard) - zesdex-dto: Data Transfer Objects for LLM provider API communication - zesdex-ipc: Unix-socket IPC layer (client/server/framing/protocol) - zesdex-iam: Identity & Access Management (Clean Architecture: domain/application/infrastructure) - zesdex-cms: Content Management (Clean Architecture: domain/application/infrastructure) - zesdex-middleware: HTTP middleware (Auth, CORS, Rate Limiting) - zesdex-libs: Composition root (AppContext, DB init, JWT, Argon2) - zesdex-backend: Main binary entry point + seed/migrate binaries - DevOps: Dockerfile, docker-compose, Nix (flake/shell/default), CI/CD updates - Remove dead root src/ and src-misc/ directories All crate re-exports maintain backward compatibility with original crate::model::*, crate::dto::*, crate::ipc::* module paths. Feature crates enforce strict layer separation: domain -> application -> infrastructure with generic trait-based dependency injection.
This commit is contained in:
@@ -0,0 +1,605 @@
|
||||
//! Auto-subagent orchestration: the main agent automatically delegates
|
||||
//! review, test-generation, architecture-review, and security-review tasks
|
||||
//! to subagents without requiring explicit tool calls from the LLM.
|
||||
//!
|
||||
//! Two modes:
|
||||
//! - **Inline** (`spawn_quick_review`): runs synchronously within the turn
|
||||
//! after each write/edit tool call. Results are fed back into the LLM
|
||||
//! conversation so the agent can act on feedback immediately.
|
||||
//! - **Background** (`spawn_background_*`): runs asynchronously on a
|
||||
//! dedicated OS thread at the end of a turn. Reports results via
|
||||
//! `TurnEvent::SystemNote`, consumed by the TUI on the next Tick.
|
||||
//!
|
||||
//! Why inline vs background:
|
||||
//! - Inline reviews give the agent an immediate feedback loop ("I just
|
||||
//! wrote this file, let me check if it's correct before continuing").
|
||||
//! - Background reviews catch broader concerns (missing tests, architectural
|
||||
//! drift, security issues) without blocking the main agent's flow.
|
||||
use crate::app::state::runtime::TurnEvent;
|
||||
use crate::app::subagent::context::build_subagent_context;
|
||||
use crate::app::subagent::engine::run_subagent;
|
||||
use crate::app::subagent::event::SubagentEvent;
|
||||
use crate::app::subagent::spawn::AgentDefinition;
|
||||
use std::collections::VecDeque;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// File extensions that should not trigger auto-review (config, lock, data).
|
||||
const SKIP_REVIEW_EXTENSIONS: &[&str] = &[
|
||||
".lock", ".md", ".txt", ".json", ".toml", ".yaml", ".yml", ".svg", ".png", ".jpg", ".ico",
|
||||
".woff", ".woff2",
|
||||
];
|
||||
|
||||
/// File names that should not trigger auto-review.
|
||||
const SKIP_REVIEW_FILES: &[&str] = &[
|
||||
"Cargo.lock",
|
||||
"yarn.lock",
|
||||
"package-lock.json",
|
||||
".gitignore",
|
||||
".env",
|
||||
".env.example",
|
||||
];
|
||||
|
||||
/// Prevents a second background subagent of the same kind from spawning
|
||||
/// while one is already in flight. Without this, a chatty multi-turn edit
|
||||
/// session could stack overlapping test-gen/arch/security reviews of
|
||||
/// overlapping file sets, none of which could be told apart in the
|
||||
/// `SystemNote` toast stream.
|
||||
static TEST_GEN_RUNNING: AtomicBool = AtomicBool::new(false);
|
||||
static ARCH_REVIEW_RUNNING: AtomicBool = AtomicBool::new(false);
|
||||
static SECURITY_REVIEW_RUNNING: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// RAII guard that resets a per-kind overlap flag back to `false` on drop —
|
||||
/// including during a panic-triggered unwind inside the spawned thread — so
|
||||
/// a background review can never wedge itself permanently disabled for the
|
||||
/// rest of the process if the subagent run panics before reaching its
|
||||
/// normal completion path.
|
||||
struct RunningGuard(&'static AtomicBool);
|
||||
|
||||
impl Drop for RunningGuard {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// ─── Helpers ───
|
||||
///
|
||||
/// Check whether a file path is worth auto-reviewing (not config/lock/data).
|
||||
///
|
||||
/// Vendored/generated directories are matched by path *segment* rather than
|
||||
/// a `/target/`-style substring check — the substring form misses paths
|
||||
/// where the directory is the first component (e.g. `target/debug/build.rs`,
|
||||
/// which has no leading slash), the same class of bug fixed in
|
||||
/// `is_production_code` below.
|
||||
pub fn is_reviewable_path(path: &str) -> bool {
|
||||
let lower = path.to_lowercase();
|
||||
if SKIP_REVIEW_FILES.iter().any(|f| lower.ends_with(f)) {
|
||||
return false;
|
||||
}
|
||||
if SKIP_REVIEW_EXTENSIONS.iter().any(|e| lower.ends_with(e)) {
|
||||
return false;
|
||||
}
|
||||
// Skip paths that are clearly generated or vendored
|
||||
let in_vendored_dir = std::path::Path::new(&lower).components().any(|c| {
|
||||
matches!(
|
||||
c,
|
||||
std::path::Component::Normal(seg)
|
||||
if matches!(seg.to_str(), Some("target" | "node_modules" | ".git" | "vendor"))
|
||||
)
|
||||
});
|
||||
if in_vendored_dir {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Determine whether a file change looks like it modifies production logic
|
||||
/// (vs. tests, config, or documentation) — used to decide if a test-gen
|
||||
/// or security-review background subagent should fire.
|
||||
///
|
||||
/// Matches test-ness by path *segment* (a directory literally named
|
||||
/// "test"/"tests"/"__tests__") or by filename convention
|
||||
/// (`foo_test.rs`, `foo.test.ts`, `test_foo.py`, `foo_spec.rb`), not by a
|
||||
/// raw substring check — a plain `.contains("test")` would wrongly exclude
|
||||
/// legitimate production files like `src/attestation.rs` or
|
||||
/// `src/latest/foo.rs`.
|
||||
fn is_production_code(path: &str) -> bool {
|
||||
let lower = path.to_lowercase();
|
||||
let path_obj = std::path::Path::new(&lower);
|
||||
|
||||
let in_test_dir = path_obj.components().any(|c| {
|
||||
matches!(
|
||||
c,
|
||||
std::path::Component::Normal(seg)
|
||||
if matches!(seg.to_str(), Some("test" | "tests" | "__tests__"))
|
||||
)
|
||||
});
|
||||
|
||||
let file_stem = path_obj.file_stem().and_then(|s| s.to_str()).unwrap_or("");
|
||||
let is_test_filename = file_stem.starts_with("test_")
|
||||
|| file_stem.ends_with("_test")
|
||||
|| std::path::Path::new(file_stem)
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("test"))
|
||||
|| file_stem == "spec"
|
||||
|| file_stem.ends_with("_spec")
|
||||
|| std::path::Path::new(file_stem)
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("spec"));
|
||||
|
||||
if in_test_dir || is_test_filename {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Only source files — use Path::extension() to avoid clippy
|
||||
// case_sensitive_file_extension_comparisons lint
|
||||
path_obj
|
||||
.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| {
|
||||
matches!(
|
||||
ext,
|
||||
"rs" | "ts"
|
||||
| "tsx"
|
||||
| "js"
|
||||
| "jsx"
|
||||
| "go"
|
||||
| "py"
|
||||
| "java"
|
||||
| "kt"
|
||||
| "swift"
|
||||
| "c"
|
||||
| "cpp"
|
||||
| "h"
|
||||
| "hpp"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// ─── Inline Quick Review (synchronous, feeds back to LLM) ───
|
||||
///
|
||||
/// Spawn a lightweight inline code review subagent for the given file.
|
||||
///
|
||||
/// The subagent reads the file (read-only), checks for common issues,
|
||||
/// and returns a concise text verdict. This runs synchronously so the
|
||||
/// main agent's `run_agent_turn` can inject the result back into the
|
||||
/// LLM conversation for immediate action.
|
||||
///
|
||||
/// Returns `Ok(verdict)` if the review completed, or an error if the
|
||||
/// subagent could not be spawned or failed internally. Callers should
|
||||
/// log and swallow errors gracefully — a failed inline review should
|
||||
/// never interrupt the main agent's flow.
|
||||
pub fn spawn_quick_review(
|
||||
file_path: &str,
|
||||
session_dir: &Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
) -> anyhow::Result<String> {
|
||||
let prompt = format!(
|
||||
"{}\n\nFile to review: {}",
|
||||
crate::resources::AUTO_REVIEWER_PROMPT,
|
||||
file_path,
|
||||
);
|
||||
|
||||
let def = AgentDefinition::new("quick-reviewer".to_string(), "reviewer".to_string())
|
||||
.with_system_prompt(prompt);
|
||||
|
||||
let mut ctx = build_subagent_context(&def);
|
||||
ctx.session_dir = session_dir.to_path_buf();
|
||||
ctx.workspaces = workspaces.to_vec();
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
|
||||
let _drain = std::thread::spawn(move || {
|
||||
while let Some(event) = rx.blocking_recv() {
|
||||
match &event {
|
||||
SubagentEvent::ToolCall { tool, .. } => {
|
||||
tracing::debug!("[auto-review] tool call: {}", tool);
|
||||
}
|
||||
SubagentEvent::ToolResult { tool, .. } => {
|
||||
tracing::debug!("[auto-review] tool result: {}", tool);
|
||||
}
|
||||
SubagentEvent::Completed => {
|
||||
tracing::debug!("[auto-review] completed");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let verdict = run_subagent(&ctx, &tx)?;
|
||||
tracing::info!(
|
||||
"[auto-review] quick review for '{}': {}",
|
||||
file_path,
|
||||
verdict.lines().next().unwrap_or(&verdict),
|
||||
);
|
||||
Ok(verdict)
|
||||
}
|
||||
|
||||
/// ─── Background Subagent Spawners (async, report via `SystemNote`) ───
|
||||
///
|
||||
/// Run a subagent built from `def`, retrying once if the first attempt
|
||||
/// fails. Background subagents call this instead of running once and
|
||||
/// silently swallowing the error into a note string, so a single transient
|
||||
/// LLM/tool failure doesn't just disappear.
|
||||
///
|
||||
/// `abort_flag` is checked before every attempt (including the first) and
|
||||
/// forwarded into the subagent's own context, so a cancelled turn stops
|
||||
/// retrying immediately instead of burning a second attempt.
|
||||
///
|
||||
/// Return: `Ok(output)` if either attempt succeeded, `Err(message)`
|
||||
/// describing the final failure if both attempts failed, or the literal
|
||||
/// message `"aborted by user"` if `abort_flag` was already set before an
|
||||
/// attempt could start.
|
||||
fn run_subagent_with_retry(
|
||||
def: &AgentDefinition,
|
||||
session_dir: &Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
label: &str,
|
||||
abort_flag: Option<&Arc<AtomicBool>>,
|
||||
) -> Result<String, String> {
|
||||
let mut last_err = String::new();
|
||||
for attempt in 1..=2 {
|
||||
if abort_flag.is_some_and(|f| f.load(Ordering::SeqCst)) {
|
||||
return Err("aborted by user".to_string());
|
||||
}
|
||||
let mut ctx = build_subagent_context(def);
|
||||
ctx.session_dir = session_dir.to_path_buf();
|
||||
ctx.workspaces = workspaces.to_vec();
|
||||
ctx.abort_flag = abort_flag.cloned();
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
|
||||
let drain_label = label.to_string();
|
||||
let _drain = std::thread::spawn(move || {
|
||||
while let Some(event) = rx.blocking_recv() {
|
||||
if let SubagentEvent::StepFailed { step, error } = &event {
|
||||
tracing::warn!("[{drain_label}] step {step} failed: {error}");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
match run_subagent(&ctx, &tx) {
|
||||
Ok(output) => return Ok(output),
|
||||
Err(e) => {
|
||||
tracing::warn!("[{label}] attempt {attempt}/2 failed: {e}");
|
||||
last_err = e.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(format!("failed after 2 attempts: {last_err}"))
|
||||
}
|
||||
|
||||
/// Spawn a background subagent that generates tests for modified files.
|
||||
///
|
||||
/// Uses the test-generator prompt and has read-write access so it can
|
||||
/// create test files. Runs in a separate OS thread and reports completion
|
||||
/// via `TurnEvent::SystemNote { kind: "bg-test-gen" }`.
|
||||
///
|
||||
/// Skipped (no-op) if a test-gen run is already in flight (guarded by
|
||||
/// `TEST_GEN_RUNNING`) — prevents a chatty multi-turn edit session from
|
||||
/// stacking overlapping runs. `abort_flag` is forwarded to
|
||||
/// `run_subagent_with_retry` so the run can be cancelled if the turn aborts.
|
||||
pub fn spawn_background_test_gen(
|
||||
file_paths: &[String],
|
||||
session_dir: &Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
|
||||
abort_flag: Arc<AtomicBool>,
|
||||
) {
|
||||
if file_paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
if TEST_GEN_RUNNING
|
||||
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_err()
|
||||
{
|
||||
tracing::debug!("[bg-test-gen] skipped — a test-gen run is already in flight");
|
||||
return;
|
||||
}
|
||||
|
||||
let paths = file_paths.to_vec();
|
||||
let sd = session_dir.to_path_buf();
|
||||
let ws = workspaces.to_vec();
|
||||
let events = turn_events.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let _running_guard = RunningGuard(&TEST_GEN_RUNNING);
|
||||
tracing::info!(
|
||||
"[bg-test-gen] spawning for {} file(s): {:?}",
|
||||
paths.len(),
|
||||
paths,
|
||||
);
|
||||
|
||||
let file_list = paths.join("\n");
|
||||
let prompt = format!(
|
||||
"{}\n\nModified files that need tests:\n{}",
|
||||
crate::resources::TEST_GENERATOR_PROMPT,
|
||||
file_list,
|
||||
);
|
||||
|
||||
let def = AgentDefinition::new(
|
||||
"test-generator".to_string(),
|
||||
"coder".to_string(), // needs write access
|
||||
)
|
||||
.with_system_prompt(prompt);
|
||||
|
||||
let result = run_subagent_with_retry(&def, &sd, &ws, "bg-test-gen", Some(&abort_flag));
|
||||
let message = match &result {
|
||||
Ok(output) => {
|
||||
let first = output.lines().next().unwrap_or(output);
|
||||
format!("Auto test-gen: {first}")
|
||||
}
|
||||
Err(e) if e.contains("aborted") => format!("Auto test-gen cancelled: {e}"),
|
||||
Err(e) => format!("ESCALATED: Auto test-gen {e}"),
|
||||
};
|
||||
|
||||
if let Ok(mut q) = events.lock() {
|
||||
q.push_back(TurnEvent::SystemNote {
|
||||
kind: "bg-test-gen".to_string(),
|
||||
message,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Spawn a background architecture-review subagent.
|
||||
///
|
||||
/// Inspects the modified files for architectural consistency (layering,
|
||||
/// coupling, module boundaries). Reports via
|
||||
/// `TurnEvent::SystemNote { kind: "bg-arch-review" }`.
|
||||
///
|
||||
/// Skipped (no-op) if an arch-review run is already in flight (guarded by
|
||||
/// `ARCH_REVIEW_RUNNING`). `abort_flag` is forwarded to
|
||||
/// `run_subagent_with_retry` so the run can be cancelled if the turn aborts.
|
||||
pub fn spawn_background_arch_review(
|
||||
file_paths: &[String],
|
||||
session_dir: &Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
|
||||
abort_flag: Arc<AtomicBool>,
|
||||
) {
|
||||
if file_paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
if ARCH_REVIEW_RUNNING
|
||||
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_err()
|
||||
{
|
||||
tracing::debug!("[bg-arch-review] skipped — an arch-review run is already in flight");
|
||||
return;
|
||||
}
|
||||
|
||||
let paths = file_paths.to_vec();
|
||||
let sd = session_dir.to_path_buf();
|
||||
let ws = workspaces.to_vec();
|
||||
let events = turn_events.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let _running_guard = RunningGuard(&ARCH_REVIEW_RUNNING);
|
||||
let file_list = paths.join("\n");
|
||||
let prompt = format!(
|
||||
"{}\n\nModified files for architecture review:\n{}",
|
||||
crate::resources::ARCH_REVIEWER_PROMPT,
|
||||
file_list,
|
||||
);
|
||||
|
||||
let def = AgentDefinition::new("arch-reviewer".to_string(), "reviewer".to_string())
|
||||
.with_system_prompt(prompt);
|
||||
|
||||
let result = run_subagent_with_retry(&def, &sd, &ws, "bg-arch-review", Some(&abort_flag));
|
||||
let message = match &result {
|
||||
Ok(output) => {
|
||||
let first = output.lines().next().unwrap_or(output);
|
||||
format!("Architecture review: {first}")
|
||||
}
|
||||
Err(e) if e.contains("aborted") => format!("Architecture review cancelled: {e}"),
|
||||
Err(e) => format!("ESCALATED: Architecture review {e}"),
|
||||
};
|
||||
|
||||
if let Ok(mut q) = events.lock() {
|
||||
q.push_back(TurnEvent::SystemNote {
|
||||
kind: "bg-arch-review".to_string(),
|
||||
message,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Spawn a background security-review subagent.
|
||||
///
|
||||
/// Checks modified files for security vulnerabilities. Reports via
|
||||
/// `TurnEvent::SystemNote { kind: "bg-security-review" }`.
|
||||
///
|
||||
/// Skipped (no-op) if a security-review run is already in flight (guarded by
|
||||
/// `SECURITY_REVIEW_RUNNING`). `abort_flag` is forwarded to
|
||||
/// `run_subagent_with_retry` so the run can be cancelled if the turn aborts.
|
||||
pub fn spawn_background_security_review(
|
||||
file_paths: &[String],
|
||||
session_dir: &Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
|
||||
abort_flag: Arc<AtomicBool>,
|
||||
) {
|
||||
if file_paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only review production code files for security — test files and
|
||||
// config files are out of scope for security review.
|
||||
let prod_paths: Vec<String> = file_paths
|
||||
.iter()
|
||||
.filter(|p| is_production_code(p))
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
if prod_paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
if SECURITY_REVIEW_RUNNING
|
||||
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_err()
|
||||
{
|
||||
tracing::debug!(
|
||||
"[bg-security-review] skipped — a security-review run is already in flight"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let paths = prod_paths;
|
||||
let sd = session_dir.to_path_buf();
|
||||
let ws = workspaces.to_vec();
|
||||
let events = turn_events.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let _running_guard = RunningGuard(&SECURITY_REVIEW_RUNNING);
|
||||
let file_list = paths.join("\n");
|
||||
let prompt = format!(
|
||||
"{}\n\nModified files for security review:\n{}",
|
||||
crate::resources::SECURITY_REVIEWER_PROMPT,
|
||||
file_list,
|
||||
);
|
||||
|
||||
let def = AgentDefinition::new("security-reviewer".to_string(), "reviewer".to_string())
|
||||
.with_system_prompt(prompt);
|
||||
|
||||
let result =
|
||||
run_subagent_with_retry(&def, &sd, &ws, "bg-security-review", Some(&abort_flag));
|
||||
let message = match &result {
|
||||
Ok(output) => {
|
||||
let first = output.lines().next().unwrap_or(output);
|
||||
format!("Security review: {first}")
|
||||
}
|
||||
Err(e) if e.contains("aborted") => format!("Security review cancelled: {e}"),
|
||||
Err(e) => format!("ESCALATED: Security review {e}"),
|
||||
};
|
||||
|
||||
if let Ok(mut q) = events.lock() {
|
||||
q.push_back(TurnEvent::SystemNote {
|
||||
kind: "bg-security-review".to_string(),
|
||||
message,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Convenience: spawn all applicable background subagents for a set of edited
|
||||
/// file paths. Called once at the end of a main agent turn.
|
||||
///
|
||||
/// Flow: always spawns arch-review and security-review if there are
|
||||
/// reviewable production files → spawns test-gen only if there are source
|
||||
/// files that aren't already tests.
|
||||
///
|
||||
/// `abort_flag` is cloned and forwarded to all three spawn calls so a
|
||||
/// single cancellation source stops every kind of background review.
|
||||
pub fn spawn_all_background(
|
||||
file_paths: &[String],
|
||||
session_dir: &Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
|
||||
abort_flag: Arc<AtomicBool>,
|
||||
) {
|
||||
if file_paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Background test-gen: only for non-test source files
|
||||
let source_paths: Vec<String> = file_paths
|
||||
.iter()
|
||||
.filter(|p| is_production_code(p))
|
||||
.cloned()
|
||||
.collect();
|
||||
spawn_background_test_gen(
|
||||
&source_paths,
|
||||
session_dir,
|
||||
workspaces,
|
||||
turn_events,
|
||||
abort_flag.clone(),
|
||||
);
|
||||
|
||||
// Background arch review: for all files that are reviewable
|
||||
let reviewable: Vec<String> = file_paths
|
||||
.iter()
|
||||
.filter(|p| is_reviewable_path(p))
|
||||
.cloned()
|
||||
.collect();
|
||||
spawn_background_arch_review(
|
||||
&reviewable,
|
||||
session_dir,
|
||||
workspaces,
|
||||
turn_events,
|
||||
abort_flag.clone(),
|
||||
);
|
||||
|
||||
// Background security review: only production source files
|
||||
spawn_background_security_review(
|
||||
&source_paths,
|
||||
session_dir,
|
||||
workspaces,
|
||||
turn_events,
|
||||
abort_flag,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reviewable_path_skips_lockfiles_and_known_extensions() {
|
||||
assert!(!is_reviewable_path("Cargo.lock"));
|
||||
assert!(!is_reviewable_path("package.json"));
|
||||
assert!(!is_reviewable_path("logo.svg"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reviewable_path_skips_vendored_and_generated_dirs() {
|
||||
assert!(!is_reviewable_path("target/debug/build.rs"));
|
||||
assert!(!is_reviewable_path("node_modules/foo/index.js"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reviewable_path_accepts_ordinary_source_files() {
|
||||
assert!(is_reviewable_path("src/main.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_code_excludes_dedicated_test_directories() {
|
||||
assert!(!is_production_code("src/tests/foo.rs"));
|
||||
assert!(!is_production_code("__tests__/baz.test.ts"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_code_excludes_test_filename_conventions() {
|
||||
assert!(!is_production_code("src/foo_test.rs"));
|
||||
assert!(!is_production_code("src/test_foo.py"));
|
||||
assert!(!is_production_code("src/foo.spec.ts"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_code_does_not_false_positive_on_substring_test() {
|
||||
// Regression: a plain `.contains("test")` would wrongly exclude
|
||||
// these legitimate production files.
|
||||
assert!(is_production_code("src/attestation.rs"));
|
||||
assert!(is_production_code("src/latest/foo.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_code_requires_known_source_extension() {
|
||||
assert!(!is_production_code("README.md"));
|
||||
assert!(is_production_code("src/main.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn running_guard_resets_flag_on_drop_even_after_panic() {
|
||||
static TEST_FLAG: AtomicBool = AtomicBool::new(false);
|
||||
TEST_FLAG.store(true, Ordering::SeqCst);
|
||||
let result = std::panic::catch_unwind(|| {
|
||||
let _guard = RunningGuard(&TEST_FLAG);
|
||||
panic!("simulated failure inside guarded region");
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert!(
|
||||
!TEST_FLAG.load(Ordering::SeqCst),
|
||||
"guard must reset the flag even when the guarded closure panics"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Construction of a `SubagentContext` from an `AgentDefinition`,
|
||||
//! including the default read-only tool set for reviewer agents.
|
||||
use super::spawn::AgentDefinition;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{atomic::AtomicBool, Arc, Mutex};
|
||||
|
||||
/// Default read-only tool names granted to `role == "reviewer"` agents.
|
||||
pub const REVIEWER_ALLOWED: &[&str] = &["read", "grep", "glob", "recall", "remember"];
|
||||
|
||||
/// Per-invocation configuration for a subagent: prompt, allowed tools,
|
||||
/// step budget, session directory, and optional workflow-findings Arc
|
||||
/// for cross-agent communication within a workflow run.
|
||||
pub struct SubagentContext {
|
||||
pub system_prompt: String,
|
||||
pub allowed_tools: Vec<String>,
|
||||
pub max_steps: usize,
|
||||
pub session_dir: PathBuf,
|
||||
pub workspaces: Vec<PathBuf>,
|
||||
/// Ephemeral findings shared between sibling subagents in the same
|
||||
/// workflow run. Set by the workflow engine; `note_finding` writes
|
||||
/// into this from tool code via `ToolCtx.workflow_findings`.
|
||||
pub workflow_findings: Option<Arc<Mutex<Vec<String>>>>,
|
||||
/// Atomic abort flag: when set to `true`, the subagent loop will exit
|
||||
/// at the earliest opportunity (before the next LLM call). Mirrors the
|
||||
/// main agent's `abort_flag` mechanism so that long-running or stuck
|
||||
/// subagents can be cancelled from the parent.
|
||||
pub abort_flag: Option<Arc<AtomicBool>>,
|
||||
}
|
||||
|
||||
/// Build a `SubagentContext` from an `AgentDefinition`.
|
||||
///
|
||||
/// Flow: copy optional `allowed_tools` from the def → fall back to the
|
||||
/// reviewer-allowlist when the def has none and the role is "reviewer" →
|
||||
/// fall back to an empty list (i.e. "all tools allowed") for other roles.
|
||||
/// `max_steps` is read from the definition, defaulting to 25 if absent.
|
||||
///
|
||||
/// Return: a context with empty `system_prompt`, empty `workspaces`,
|
||||
/// empty `session_dir`, resolved `max_steps`, and the resolved allowed-tool list.
|
||||
pub fn build_subagent_context(def: &AgentDefinition) -> SubagentContext {
|
||||
let allowed_tools = def.allowed_tools.clone().unwrap_or_else(|| {
|
||||
if def.role == "reviewer" {
|
||||
REVIEWER_ALLOWED
|
||||
.iter()
|
||||
.map(std::string::ToString::to_string)
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
});
|
||||
let max_steps = def.max_steps.unwrap_or(usize::MAX);
|
||||
SubagentContext {
|
||||
system_prompt: String::new(),
|
||||
allowed_tools,
|
||||
max_steps,
|
||||
session_dir: PathBuf::new(),
|
||||
workspaces: Vec::new(),
|
||||
workflow_findings: None,
|
||||
abort_flag: None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! Access tiers for the anonymous processing nodes spawned by the
|
||||
//! hive-mind orchestrator (`app::workflow::hive_mind`).
|
||||
//!
|
||||
//! Nodes have no persistent identity of their own — the Core Intelligence
|
||||
//! addresses each one only by directive and access tier. Since node
|
||||
//! designations are system-assigned coordinates rather than named roles,
|
||||
//! tool access can't be a lookup table keyed by role name. Instead the
|
||||
//! Core Intelligence picks one of these three tiers per node, matched to
|
||||
//! what that node's specific directive needs — this keeps the Harness
|
||||
//! gate meaningful while the node roster itself stays fully dynamic.
|
||||
|
||||
/// The three tool-access tiers a hive-mind node can be granted.
|
||||
pub mod tool_scope {
|
||||
/// Read-only investigation: no file mutation, no shell, no VCS.
|
||||
pub const READ: &str = "read";
|
||||
/// Read-tier plus file mutation and non-destructive shell (tests/builds).
|
||||
pub const WRITE: &str = "write";
|
||||
/// Write-tier plus delete, git, and the remaining LSP actions.
|
||||
pub const FULL: &str = "full";
|
||||
|
||||
/// The read-only tool set — reused by `context::dedup` as the
|
||||
/// authoritative "safe to deduplicate" classification, so there's a
|
||||
/// single list of read-only tool names in the codebase instead of two.
|
||||
pub const READ_TOOLS: &[&str] = &[
|
||||
"read",
|
||||
"grep",
|
||||
"glob",
|
||||
"search",
|
||||
"seqthink",
|
||||
"recall",
|
||||
"lsp_connect",
|
||||
"lsp_diagnostics",
|
||||
"lsp_hover",
|
||||
"lsp_definition",
|
||||
"lsp_references",
|
||||
"read_findings",
|
||||
];
|
||||
|
||||
const WRITE_TOOLS: &[&str] = &[
|
||||
"read",
|
||||
"grep",
|
||||
"glob",
|
||||
"search",
|
||||
"seqthink",
|
||||
"recall",
|
||||
"lsp_connect",
|
||||
"lsp_diagnostics",
|
||||
"lsp_hover",
|
||||
"lsp_definition",
|
||||
"lsp_references",
|
||||
"read_findings",
|
||||
"write",
|
||||
"edit",
|
||||
"bash",
|
||||
"todowrite",
|
||||
"todofinish",
|
||||
"remember",
|
||||
];
|
||||
|
||||
const FULL_TOOLS: &[&str] = &[
|
||||
"read",
|
||||
"grep",
|
||||
"glob",
|
||||
"search",
|
||||
"seqthink",
|
||||
"recall",
|
||||
"lsp_connect",
|
||||
"lsp_diagnostics",
|
||||
"lsp_hover",
|
||||
"lsp_definition",
|
||||
"lsp_references",
|
||||
"read_findings",
|
||||
"write",
|
||||
"edit",
|
||||
"bash",
|
||||
"todowrite",
|
||||
"todofinish",
|
||||
"remember",
|
||||
"delete",
|
||||
"git_operator",
|
||||
"lsp_completion",
|
||||
"lsp_disconnect",
|
||||
];
|
||||
|
||||
/// Resolve a tier name to its concrete tool allowlist.
|
||||
///
|
||||
/// Unrecognized scope strings fall back to `READ` — the least-privileged
|
||||
/// tier — rather than silently granting broader access.
|
||||
///
|
||||
/// Return: an owned `Vec<String>` suitable for `AgentDefinition::with_allowed_tools`.
|
||||
pub fn tools_for(scope: &str) -> Vec<String> {
|
||||
let tools: &[&str] = match scope {
|
||||
FULL => FULL_TOOLS,
|
||||
WRITE => WRITE_TOOLS,
|
||||
_ => READ_TOOLS,
|
||||
};
|
||||
tools.iter().map(|s| (*s).to_string()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::tool_scope::{tools_for, FULL, READ, WRITE};
|
||||
|
||||
#[test]
|
||||
fn read_tier_excludes_write_tools() {
|
||||
let tools = tools_for(READ);
|
||||
assert!(!tools.contains(&"write".to_string()));
|
||||
assert!(!tools.contains(&"bash".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_tier_includes_bash_but_not_delete_or_git() {
|
||||
let tools = tools_for(WRITE);
|
||||
assert!(tools.contains(&"bash".to_string()));
|
||||
assert!(tools.contains(&"write".to_string()));
|
||||
assert!(!tools.contains(&"delete".to_string()));
|
||||
assert!(!tools.contains(&"git_operator".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_tier_includes_delete_and_git() {
|
||||
let tools = tools_for(FULL);
|
||||
assert!(tools.contains(&"delete".to_string()));
|
||||
assert!(tools.contains(&"git_operator".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_scope_falls_back_to_read() {
|
||||
let tools = tools_for("bogus");
|
||||
assert!(!tools.contains(&"write".to_string()));
|
||||
assert!(!tools.contains(&"delete".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_tier_is_subset_of_write_tier_and_write_is_subset_of_full() {
|
||||
use std::collections::HashSet;
|
||||
let read: HashSet<_> = tools_for(READ).into_iter().collect();
|
||||
let write: HashSet<_> = tools_for(WRITE).into_iter().collect();
|
||||
let full: HashSet<_> = tools_for(FULL).into_iter().collect();
|
||||
assert!(
|
||||
read.is_subset(&write),
|
||||
"read tier must be a subset of write tier"
|
||||
);
|
||||
assert!(
|
||||
write.is_subset(&full),
|
||||
"write tier must be a subset of full tier"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
//! Subagent execution loop: drive an LLM conversation, gate tool calls
|
||||
//! against the context's allowlist, run tools, and stream progress events
|
||||
//! to the parent via an mpsc channel.
|
||||
//!
|
||||
//! Security: subagent tool gating mirrors the main agent's `Harness` checks
|
||||
//! (path traversal, reason validation, stub/denial/assumption scanning,
|
||||
//! bash exfiltration and destructive-pattern detection) so that subagents
|
||||
//! are not a weaker link than the main agent.
|
||||
|
||||
use std::fmt::Write;
|
||||
use sha2::Digest;
|
||||
use tokio::sync::mpsc;
|
||||
use crate::dto::chat::message::ChatMessage;
|
||||
use crate::dto::provider::request::ToolDef;
|
||||
use crate::tool::{all_tools, tool_defs, tool_is_risky};
|
||||
use super::context::SubagentContext;
|
||||
use super::event::SubagentEvent;
|
||||
|
||||
/// Maps a subagent's allowed tool names to concrete Tool trait objects and
|
||||
/// OpenAI-style tool definitions.
|
||||
///
|
||||
/// Flow: load `all_tools()` → if `allowed_tools` is empty, use all; else
|
||||
/// filter by membership → derive `ToolDef`s for the LLM.
|
||||
///
|
||||
/// Why: an empty allowlist means "no restriction" (matches
|
||||
/// `build_subagent_context`'s default for non-reviewer roles).
|
||||
///
|
||||
/// Return: `(tool impls, schema defs)` for the subagent to use.
|
||||
fn build_subagent_tools(allowed_tools: &[String]) -> (Vec<Box<dyn crate::tool::Tool>>, Vec<ToolDef>) {
|
||||
let all = all_tools();
|
||||
let filtered: Vec<Box<dyn crate::tool::Tool>> = if allowed_tools.is_empty() {
|
||||
all.into_iter()
|
||||
.filter(|t| t.name() != "hive_mind" && t.name() != "workflow_run")
|
||||
.collect()
|
||||
} else {
|
||||
all.into_iter()
|
||||
.filter(|t| {
|
||||
allowed_tools.contains(&t.name().to_string())
|
||||
&& t.name() != "hive_mind"
|
||||
&& t.name() != "workflow_run"
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let defs = tool_defs(&filtered);
|
||||
(filtered, defs)
|
||||
}
|
||||
|
||||
/// Resolve the API key, model, and base URL from persisted app config.
|
||||
///
|
||||
/// Flow: try the settings key for the active provider → fall back to the
|
||||
/// provider's `api_key_env` env-var → fall back to the provider's
|
||||
/// `default_api_key` → fall back to an empty string.
|
||||
///
|
||||
/// Why: matches the main agent's credential resolution exactly, so
|
||||
/// subagents automatically inherit the same provider settings.
|
||||
///
|
||||
/// Return: `(api_key, model, optional_base_url, provider_name)`. `api_key`
|
||||
/// is empty when every resolution path was exhausted — callers must check
|
||||
/// for this before issuing requests (see `run_subagent`).
|
||||
fn resolve_provider_config() -> (String, String, Option<String>, String) {
|
||||
let settings = crate::model::settings::Settings::load();
|
||||
let app_config = crate::model::app_config::AppConfig::load();
|
||||
|
||||
let mut api_key = settings.api_keys.get(&settings.provider).cloned().unwrap_or_else(|| {
|
||||
tracing::warn!("[subagent] no API key for provider '{}' in settings, trying env/default", settings.provider);
|
||||
String::new()
|
||||
});
|
||||
let model = settings.model.clone();
|
||||
let base_url = app_config.providers.get(&settings.provider)
|
||||
.map(|p| p.api_base.clone());
|
||||
|
||||
if api_key.is_empty() {
|
||||
if let Some(provider_cfg) = app_config.providers.get(&settings.provider) {
|
||||
api_key = provider_cfg.api_key_env.as_ref()
|
||||
.and_then(|env| std::env::var(env).ok())
|
||||
.or_else(|| provider_cfg.default_api_key.clone())
|
||||
.unwrap_or_else(|| {
|
||||
tracing::warn!("[subagent] all API key resolution paths exhausted for '{}'", settings.provider);
|
||||
String::new()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
(api_key, model, base_url, settings.provider)
|
||||
}
|
||||
|
||||
/// Reject an empty API key with an actionable error instead of letting the
|
||||
/// caller send a request that is guaranteed to fail once it reaches the network.
|
||||
///
|
||||
/// Return: `Ok(())` if `api_key` is non-empty, `Err` with a message naming
|
||||
/// `provider` and where to fix it otherwise.
|
||||
fn require_api_key(api_key: &str, provider: &str) -> anyhow::Result<()> {
|
||||
if api_key.is_empty() {
|
||||
anyhow::bail!(
|
||||
"no API key configured for provider '{provider}' — set one in Settings or ~/.claude/settings.json"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ─── Subagent-level tool gating (mirrors Harness checks) ───
|
||||
|
||||
const STUB_PATTERNS: &[&str] = &[
|
||||
"todo!()", "todo!(",
|
||||
"unimplemented!()", "unimplemented!(",
|
||||
"FIXME", "fixme:", "XXX:", "PLACEHOLDER",
|
||||
"REPLACE_ME", "stub_value", "stub_function",
|
||||
"fake_response", "fake_data",
|
||||
"not implemented", "not yet implemented",
|
||||
"to be implemented", "to be done",
|
||||
];
|
||||
|
||||
const DENIAL_PATTERNS: &[&str] = &[
|
||||
"// skip", "// skipping", "// skipping for now",
|
||||
"// for now just", "// punt", "// hack:",
|
||||
"// workaround:", "// cba", "// later",
|
||||
"// do later", "// ignore for now", "// disable",
|
||||
"// bypass", "// quick fix", "// temp fix",
|
||||
"// temporary fix", "// temp:", "// temporary:",
|
||||
"// noop",
|
||||
];
|
||||
|
||||
const ASSUMPTION_PATTERNS: &[&str] = &[
|
||||
"// assume", "// probably", "// guess",
|
||||
"// should work", "// hopefully", "// i think",
|
||||
"// should be fine", "// likely",
|
||||
];
|
||||
|
||||
const EXFIL_PATTERNS: &[&str] = &[
|
||||
"curl ", "wget ", "nc -e ", "ncat ", "/dev/tcp/",
|
||||
"base64 -d |", "base64 --decode |",
|
||||
"openssl s_client", "ssh -R ",
|
||||
"scp /", "rsync /",
|
||||
];
|
||||
|
||||
const SENSITIVE_PATH_PATTERNS: &[&str] = &[
|
||||
".ssh/id_rsa", ".ssh/id_ed25519",
|
||||
".aws/credentials", ".aws/config",
|
||||
".kube/config", ".docker/config.json",
|
||||
"/etc/shadow", "/etc/passwd", "/proc/self/environ",
|
||||
];
|
||||
|
||||
const MIN_REASON_LEN: usize = 8;
|
||||
|
||||
/// Gate a tool call in the subagent context. Returns `Some(block_reason)` if
|
||||
/// the call should be blocked, `None` to allow.
|
||||
///
|
||||
/// Flow: always blocks dangerous patterns — path traversal, stub/denial/
|
||||
/// assumption language, bash exfiltration, destructive commands, sensitive
|
||||
/// path reads — regardless of the allowed-tools list. Tools that are not
|
||||
/// risky only get the basic allowlist check.
|
||||
fn gate_subagent_tool_call(
|
||||
tool_name: &str,
|
||||
args: &serde_json::Value,
|
||||
) -> Option<String> {
|
||||
// File-mutating tools: write / edit / delete
|
||||
if matches!(tool_name, "write" | "edit" | "delete") {
|
||||
if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
|
||||
if path.contains("..") {
|
||||
return Some("path traversal detected in 'path' argument".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// write / edit require a non-trivial `reason`
|
||||
if matches!(tool_name, "write" | "edit" | "delete") {
|
||||
let reason = args.get("reason").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if reason.trim().len() < MIN_REASON_LEN {
|
||||
return Some(format!(
|
||||
"{tool_name} requires a non-trivial 'reason' (>= {MIN_REASON_LEN} chars) explaining why",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// write / edit content must not contain stubs, denial, or assumption language
|
||||
if matches!(tool_name, "write" | "edit") {
|
||||
let content = match tool_name {
|
||||
"write" => args.get("content").and_then(|v| v.as_str()).unwrap_or(""),
|
||||
"edit" => {
|
||||
let old = args.get("old").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let new = args.get("new").and_then(|v| v.as_str()).unwrap_or("");
|
||||
// For edits, scanning old+new together catches stubs in both
|
||||
return if contains_any(old, STUB_PATTERNS) || contains_any(new, STUB_PATTERNS) {
|
||||
Some("content contains stub/placeholder pattern; production code must be fully implemented".to_string())
|
||||
} else if contains_any(new, DENIAL_PATTERNS) {
|
||||
Some("content contains denial/punt pattern; implement properly instead of skipping".to_string())
|
||||
} else if contains_any(new, ASSUMPTION_PATTERNS) {
|
||||
Some("content contains assumption pattern; verify against data instead of guessing".to_string())
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
}
|
||||
_ => "",
|
||||
};
|
||||
if contains_any(content, STUB_PATTERNS) {
|
||||
return Some("content contains stub/placeholder pattern; production code must be fully implemented".to_string());
|
||||
}
|
||||
if contains_any(content, DENIAL_PATTERNS) {
|
||||
return Some("content contains denial/punt pattern; implement properly instead of skipping".to_string());
|
||||
}
|
||||
if contains_any(content, ASSUMPTION_PATTERNS) {
|
||||
return Some("content contains assumption pattern; verify against data instead of guessing".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// Bash: exfiltration, sensitive paths, destructive commands
|
||||
if tool_name == "bash" {
|
||||
let cmd = args.get("command").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if cmd.contains("..") {
|
||||
return Some("path traversal detected in bash command".to_string());
|
||||
}
|
||||
// Only check exfiltration for non-standard commands
|
||||
let is_standard = cmd.trim_start().starts_with("cargo")
|
||||
|| cmd.trim_start().starts_with("rustc")
|
||||
|| cmd.trim_start().starts_with("git ")
|
||||
|| cmd.trim_start().starts_with("ls")
|
||||
|| cmd.trim_start().starts_with("pwd")
|
||||
|| cmd.trim_start().starts_with("echo")
|
||||
|| cmd.trim_start().starts_with("cat")
|
||||
|| cmd.trim_start().starts_with("find")
|
||||
|| cmd.trim_start().starts_with("grep")
|
||||
|| cmd.trim_start().starts_with("test");
|
||||
if !is_standard {
|
||||
for pat in EXFIL_PATTERNS {
|
||||
if cmd.contains(pat) {
|
||||
return Some(format!("potential data-exfiltration command blocked (matched '{pat}')"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for pat in SENSITIVE_PATH_PATTERNS {
|
||||
if cmd.contains(pat) {
|
||||
return Some(format!("refused to read/write sensitive path '{pat}'"));
|
||||
}
|
||||
}
|
||||
let dangerous = ["rm -rf /", "rm -rf --no-preserve-root", "rm -rf ~",
|
||||
"rm -fr /", "mkfs.", "dd if=", ":(){", "> /dev/sda",
|
||||
"chmod -R 000 /", "shutdown ", "poweroff ", "reboot ", "halt "];
|
||||
for pat in &dangerous {
|
||||
if cmd.contains(pat) {
|
||||
return Some(format!("destructive command pattern blocked: {pat}"));
|
||||
}
|
||||
}
|
||||
if contains_any(cmd, STUB_PATTERNS) {
|
||||
return Some("bash command contains stub pattern".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// git_operator: require reason
|
||||
if tool_name == "git_operator" {
|
||||
let reason = args.get("reason").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if reason.trim().len() < MIN_REASON_LEN {
|
||||
return Some("git_operator requires a non-trivial 'reason' (>= 8 chars)".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Check if `text` matches any pattern (case-insensitive substring).
|
||||
fn contains_any(text: &str, patterns: &[&str]) -> bool {
|
||||
let lower = text.to_lowercase();
|
||||
patterns.iter().any(|p| lower.contains(&p.to_lowercase()))
|
||||
}
|
||||
|
||||
/// Build an ASCII tree of the workspace directory structure for the
|
||||
/// system prompt, so the LLM can see the file layout.
|
||||
///
|
||||
/// Flow: for each root, walk using `ignore::WalkBuilder` (respecting
|
||||
/// `.gitignore` and hidden files) → prefix `[DIR]` for directories →
|
||||
/// truncate after 1000 entries.
|
||||
fn generate_workspace_tree(roots: &[std::path::PathBuf]) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("Current Workspace Directory Structure:\n");
|
||||
for root in roots {
|
||||
writeln!(out, "Root: {}", root.display()).unwrap();
|
||||
let walker = ignore::WalkBuilder::new(root)
|
||||
.hidden(true)
|
||||
.git_ignore(true)
|
||||
.build();
|
||||
let mut count = 0;
|
||||
for entry in walker.flatten() {
|
||||
let path = entry.path();
|
||||
if let Ok(rel) = path.strip_prefix(root) {
|
||||
if rel.as_os_str().is_empty() { continue; }
|
||||
let is_dir = entry.file_type().is_some_and(|ft| ft.is_dir());
|
||||
let prefix = if is_dir { "[DIR] " } else { " " };
|
||||
writeln!(out, " {}{}", prefix, rel.display()).unwrap();
|
||||
count += 1;
|
||||
if count > 1000 {
|
||||
out.push_str(" ... (truncated)\n");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn format_subagent_progress(prefix: &str, text: &str) -> String {
|
||||
let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
if lines.is_empty() {
|
||||
format!("{prefix}...")
|
||||
} else if lines.len() == 1 {
|
||||
format!("{prefix}: {}", lines[0])
|
||||
} else {
|
||||
lines[lines.len() - 2..].join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronous subagent entry point: run up to `ctx.max_steps` iterations
|
||||
/// of the LLM tool loop.
|
||||
///
|
||||
/// Flow: inject system prompt (with workspace tree if available) → for each
|
||||
/// step: resolve provider config, build an LLM client, call
|
||||
/// `chat_with_tools_streaming` (with abort check per SSE event), process
|
||||
/// tool calls (gated against both the allowlist and Harness-style content
|
||||
/// safety checks) or collect text output → send `SubagentEvent`s on `tx` →
|
||||
/// break on first text-only (non-empty) response.
|
||||
///
|
||||
/// Why: runs synchronously on a dedicated thread so the main async event
|
||||
/// loop is not blocked. Tool gating prevents restricted, risky, or
|
||||
/// malicious/poor-quality tool calls from executing.
|
||||
///
|
||||
/// Return: the concatenated text output, or an `anyhow::Error` if the LLM
|
||||
/// call fails at any step.
|
||||
#[allow(clippy::too_many_lines)]
|
||||
pub fn run_subagent(ctx: &SubagentContext, tx: &mpsc::Sender<SubagentEvent>) -> anyhow::Result<String> {
|
||||
let mut output = String::new();
|
||||
let mut messages: Vec<ChatMessage> = Vec::new();
|
||||
|
||||
// Build system prompt with workspace tree context if we have workspaces,
|
||||
// giving subagents the same project-awareness as the main agent.
|
||||
let system_with_context = if ctx.workspaces.is_empty() {
|
||||
ctx.system_prompt.clone()
|
||||
} else {
|
||||
let tree_info = generate_workspace_tree(&ctx.workspaces);
|
||||
format!("{}\n\n{}", ctx.system_prompt, tree_info)
|
||||
};
|
||||
messages.push(ChatMessage::system(system_with_context));
|
||||
|
||||
let tool_ctx = crate::tool::ToolCtx::builder()
|
||||
.session_dir(ctx.session_dir.clone())
|
||||
.workspaces(ctx.workspaces.clone())
|
||||
.origin(crate::app::state::types::Origin::SubAgent)
|
||||
.workflow_findings(ctx.workflow_findings.clone())
|
||||
.build();
|
||||
|
||||
// Build tool list once before the loop
|
||||
let (tools, tdefs) = build_subagent_tools(&ctx.allowed_tools);
|
||||
let tdefs_opt: Option<Vec<ToolDef>> = if tdefs.is_empty() { None } else { Some(tdefs) };
|
||||
|
||||
// Cache provider config once before the loop instead of re-resolving
|
||||
// from disk on every step (Settings::load + AppConfig::load each parse
|
||||
// JSON files, and the config cannot change between steps).
|
||||
let (api_key, model, base_url, provider) = resolve_provider_config();
|
||||
|
||||
// Fail fast on a missing key instead of sending a doomed request: an
|
||||
// empty api_key still reaches the network (base_url falls back to a
|
||||
// default endpoint), so without this check every step burns a full
|
||||
// 10-retry timeout/backoff cycle against a server that was never going
|
||||
// to authenticate, and the real cause (no key configured) never
|
||||
// surfaces past a buried WARN log.
|
||||
if let Err(error) = require_api_key(&api_key, &provider) {
|
||||
let error = error.to_string();
|
||||
let _ = tx.blocking_send(SubagentEvent::StepFailed { step: 0, error: error.clone() });
|
||||
anyhow::bail!(error);
|
||||
}
|
||||
|
||||
let client = crate::service::provider::LlmClient::new(api_key, model, base_url);
|
||||
|
||||
for step in 0..ctx.max_steps {
|
||||
|
||||
// Check abort flag before each LLM call so a stuck subagent can
|
||||
// be cancelled from the parent (mirrors main agent behaviour).
|
||||
if ctx.abort_flag.as_ref().is_some_and(|f| f.load(std::sync::atomic::Ordering::SeqCst)) {
|
||||
let _ = tx.blocking_send(SubagentEvent::StepFailed {
|
||||
step,
|
||||
error: "subagent aborted by parent".to_string(),
|
||||
});
|
||||
anyhow::bail!("subagent aborted by parent at step {step}");
|
||||
}
|
||||
|
||||
let tx_clone = tx.clone();
|
||||
let mut current_thinking = String::new();
|
||||
let mut current_token = String::new();
|
||||
let mut step_usage: Option<(u64, u64)> = None;
|
||||
|
||||
// Use streaming API so the abort flag is checked per SSE event,
|
||||
// making the subagent responsive to cancellation even during an
|
||||
// LLM call (non-streaming would block for 10-30s unchecked).
|
||||
let stream_result = client.chat_with_tools_streaming(
|
||||
&messages,
|
||||
tdefs_opt.clone(),
|
||||
Some(0.7),
|
||||
Some(4096),
|
||||
|event| -> bool {
|
||||
// Check abort on every SSE event for responsive cancellation.
|
||||
if ctx.abort_flag.as_ref().is_some_and(|f| f.load(std::sync::atomic::Ordering::SeqCst)) {
|
||||
return false; // signals provider to abort
|
||||
}
|
||||
match event {
|
||||
crate::app::runtime::stream::StreamEvent::Reasoning(text) => {
|
||||
current_thinking.push_str(text);
|
||||
let prog = format_subagent_progress("thinking", ¤t_thinking);
|
||||
let _ = tx_clone.blocking_send(SubagentEvent::Progress(prog));
|
||||
}
|
||||
crate::app::runtime::stream::StreamEvent::Token(text) => {
|
||||
current_token.push_str(text);
|
||||
let prog = format_subagent_progress("replying", ¤t_token);
|
||||
let _ = tx_clone.blocking_send(SubagentEvent::Progress(prog));
|
||||
}
|
||||
crate::app::runtime::stream::StreamEvent::Usage { prompt_tokens, completion_tokens, .. } => {
|
||||
// Capture usage so the drain thread can route it
|
||||
// to the parent's `UsageStats::review_tokens`.
|
||||
// Last writer wins — providers send exactly one
|
||||
// Usage event per streaming call.
|
||||
step_usage = Some((*prompt_tokens, *completion_tokens));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
true
|
||||
},
|
||||
);
|
||||
|
||||
let (response, returned_usage) = match stream_result {
|
||||
Ok(result) => result,
|
||||
Err(e) => {
|
||||
let is_abort = ctx.abort_flag.as_ref().is_some_and(|f| f.load(std::sync::atomic::Ordering::SeqCst))
|
||||
|| e.to_string().contains("aborted");
|
||||
let _ = tx.blocking_send(SubagentEvent::StepFailed {
|
||||
step,
|
||||
error: if is_abort {
|
||||
"subagent aborted by user".to_string()
|
||||
} else {
|
||||
e.to_string()
|
||||
},
|
||||
});
|
||||
if is_abort {
|
||||
anyhow::bail!("subagent aborted by parent at step {step}");
|
||||
}
|
||||
// No non-streaming fallback — API must support streaming.
|
||||
// Non-streaming calls block for up to 1 min without checking
|
||||
// abort_flag, making cancellation unresponsive.
|
||||
anyhow::bail!("subagent call failed at step {step}: {e}");
|
||||
}
|
||||
};
|
||||
|
||||
// Emit the token usage from this streaming call so the parent's
|
||||
// drain thread can accumulate it and update the Usage panel.
|
||||
// Without this, the Usage panel always shows zeros because the
|
||||
// subagent never tells the parent about the tokens consumed.
|
||||
let (mut tok_in, mut tok_out) = returned_usage.unwrap_or((0, 0));
|
||||
if tok_in == 0 {
|
||||
let prompt_chars: usize = messages.iter()
|
||||
.filter_map(|m| m.content.as_deref())
|
||||
.map(str::len)
|
||||
.sum();
|
||||
tok_in = (prompt_chars / 4).max(1) as u64;
|
||||
}
|
||||
if tok_out == 0 {
|
||||
let response_chars = response.content.as_deref().map_or(0, str::len);
|
||||
tok_out = (response_chars / 4).max(1) as u64;
|
||||
}
|
||||
let _ = tx.blocking_send(SubagentEvent::Usage {
|
||||
tokens_in: tok_in,
|
||||
tokens_out: tok_out,
|
||||
});
|
||||
|
||||
let has_tool_calls = response.tool_calls.is_some()
|
||||
&& response.tool_calls.as_ref().is_some_and(|tc| !tc.is_empty());
|
||||
|
||||
let content = response.content.clone().unwrap_or_default();
|
||||
|
||||
// Emit thinking/reasoning text as StepCompleted so the parent's
|
||||
// drain thread can show it as progress instead of just the tool name.
|
||||
if !content.is_empty() {
|
||||
let _ = tx.blocking_send(SubagentEvent::StepCompleted {
|
||||
output: content.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
if has_tool_calls {
|
||||
let tool_calls = response.tool_calls.clone().unwrap_or_default();
|
||||
// Push the assistant message with tool_calls into the conversation
|
||||
messages.push(response);
|
||||
|
||||
let mut results_vec = Vec::new();
|
||||
std::thread::scope(|s| {
|
||||
let mut handles = Vec::new();
|
||||
let tools_ref = &tools;
|
||||
let tool_ctx_ref = &tool_ctx;
|
||||
for tool_call in &tool_calls {
|
||||
let handle = s.spawn(move || {
|
||||
// Check abort flag before each tool execution
|
||||
if ctx.abort_flag.as_ref().is_some_and(|f| f.load(std::sync::atomic::Ordering::SeqCst)) {
|
||||
return (tool_call, Err(anyhow::anyhow!("subagent aborted by parent during tool execution")));
|
||||
}
|
||||
|
||||
let tool_name = &tool_call.function.name;
|
||||
let args = crate::dto::chat::tool::sanitize_tool_arguments(&tool_call.function.arguments);
|
||||
let explicitly_allowed = ctx.allowed_tools.contains(tool_name);
|
||||
let generally_allowed = ctx.allowed_tools.is_empty() || explicitly_allowed;
|
||||
|
||||
// Level 1: allowlist check — is this tool even permitted?
|
||||
if !generally_allowed {
|
||||
return (tool_call, Ok(format!("tool '{tool_name}' not allowed for this subagent")));
|
||||
}
|
||||
|
||||
// Level 2: risky tool check — risky tools require explicit permission
|
||||
if tool_is_risky(tool_name) && !explicitly_allowed {
|
||||
return (tool_call, Ok(format!("risky tool '{tool_name}' requires explicit permission; not allowed for this subagent")));
|
||||
}
|
||||
|
||||
// Level 3: Harness-style content safety gating
|
||||
if let Some(block_reason) = gate_subagent_tool_call(tool_name, &args) {
|
||||
return (tool_call, Ok(format!("Blocked by subagent gate: {block_reason}")));
|
||||
}
|
||||
|
||||
let result = match tools_ref.iter().find(|t| t.name() == tool_name.as_str()) {
|
||||
Some(tool) => {
|
||||
let is_edit = tool_name == "write" || tool_name == "edit";
|
||||
if is_edit && !tool_call.id.is_empty() {
|
||||
if let Ok(conn) = crate::model::msglog::open_or_create(&ctx.session_dir) {
|
||||
let path = args.get("path").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if let Ok(abs_path) = crate::tool::resolve_path(&tool_ctx_ref.workspaces, path) {
|
||||
if let Ok(bytes) = std::fs::read(&abs_path) {
|
||||
let session_id = ctx.session_dir
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.unwrap_or("unknown");
|
||||
let _ = crate::model::msglog::store_blob(
|
||||
&conn, session_id, &tool_call.id, &bytes, None,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let run_res = tool.run(tool_ctx_ref, &args);
|
||||
|
||||
if is_edit && run_res.is_ok() {
|
||||
let reason = args
|
||||
.get("reason")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("unnamed");
|
||||
let path = args
|
||||
.get("path")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("unknown");
|
||||
let content_sha256 = {
|
||||
let content = args.get("content").or_else(|| args.get("new"));
|
||||
let hash = sha2::Sha256::digest(
|
||||
content.and_then(|v| v.as_str()).unwrap_or("").as_bytes(),
|
||||
);
|
||||
hex::encode(hash)
|
||||
};
|
||||
let bytes_delta = if tool_name == "write" {
|
||||
args.get("content")
|
||||
.and_then(|v| v.as_str())
|
||||
.map_or(0, |s| s.len() as i64)
|
||||
} else {
|
||||
let old = args.get("old").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let new = args.get("new").and_then(|v| v.as_str()).unwrap_or("");
|
||||
(new.len() as i64 - old.len() as i64).abs()
|
||||
};
|
||||
let session_id = ctx.session_dir
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
let entry = crate::model::editlog::EditLogEntry {
|
||||
ts: chrono::Utc::now().timestamp_millis(),
|
||||
tool: tool_name.clone(),
|
||||
path: path.to_string(),
|
||||
reason: reason.to_string(),
|
||||
content_sha256,
|
||||
bytes_delta,
|
||||
origin: tool_ctx_ref.origin.tag(),
|
||||
session_id,
|
||||
};
|
||||
let mut el = crate::model::editlog::EditLog::new(&ctx.session_dir);
|
||||
el.append(entry).ok();
|
||||
}
|
||||
run_res
|
||||
}
|
||||
None => Err(anyhow::anyhow!("tool '{tool_name}' not found")),
|
||||
};
|
||||
(tool_call, result)
|
||||
});
|
||||
handles.push(handle);
|
||||
}
|
||||
for h in handles {
|
||||
if let Ok(res) = h.join() {
|
||||
results_vec.push(res);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
for (tool_call, result) in results_vec {
|
||||
let tool_name = &tool_call.function.name;
|
||||
let args = crate::dto::chat::tool::sanitize_tool_arguments(&tool_call.function.arguments);
|
||||
|
||||
let _ = tx.blocking_send(SubagentEvent::ToolCall {
|
||||
tool: tool_name.clone(),
|
||||
args: args.clone(),
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(output_text) => {
|
||||
messages.push(ChatMessage::tool_result(tool_call.id.clone(), output_text.clone()));
|
||||
let _ = tx.blocking_send(SubagentEvent::ToolResult {
|
||||
tool: tool_name.clone(),
|
||||
args: args.clone(),
|
||||
});
|
||||
|
||||
let is_readonly = tool_name == "read"
|
||||
|| tool_name == "view_file"
|
||||
|| tool_name == "grep"
|
||||
|| tool_name == "grep_search"
|
||||
|| tool_name == "glob"
|
||||
|| tool_name == "dir_list"
|
||||
|| tool_name == "list_dir";
|
||||
|
||||
if is_readonly {
|
||||
if let Some(ref findings) = ctx.workflow_findings {
|
||||
if let Ok(mut f) = findings.lock() {
|
||||
let args_json = serde_json::to_string(&args).unwrap_or_default();
|
||||
let mut shared_text = output_text;
|
||||
if shared_text.len() > 50_000 {
|
||||
shared_text.truncate(50_000);
|
||||
shared_text.push_str("\n...[truncated]");
|
||||
}
|
||||
f.push(format!("[Auto-Shared] Sibling drone executed '{tool_name}' with args {args_json}:\n{shared_text}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let err_str = e.to_string();
|
||||
if err_str.contains("subagent aborted by parent") {
|
||||
let _ = tx.blocking_send(SubagentEvent::StepFailed {
|
||||
step,
|
||||
error: err_str.clone(),
|
||||
});
|
||||
anyhow::bail!("{err_str}");
|
||||
}
|
||||
let msg = format!("tool '{tool_name}' failed: {e}");
|
||||
messages.push(ChatMessage::tool_result(tool_call.id.clone(), msg.clone()));
|
||||
let _ = tx.blocking_send(SubagentEvent::ToolResult {
|
||||
tool: tool_name.clone(),
|
||||
args: args.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Text-only response — accumulate and finish
|
||||
if !content.is_empty() {
|
||||
output.push_str(&content);
|
||||
output.push('\n');
|
||||
}
|
||||
let _ = tx.blocking_send(SubagentEvent::StepCompleted {
|
||||
output: content.clone(),
|
||||
});
|
||||
// Break only when we got real content; empty means something went wrong
|
||||
if !content.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let _ = tx.blocking_send(SubagentEvent::Completed);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn require_api_key_rejects_empty_key_with_provider_named_in_message() {
|
||||
let err = require_api_key("", "claude").unwrap_err();
|
||||
assert!(err.to_string().contains("claude"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn require_api_key_accepts_non_empty_key() {
|
||||
assert!(require_api_key("sk-live-abc123", "claude").is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//! Event variants that a running subagent can emit to its parent via the
|
||||
//! shared mpsc channel.
|
||||
use serde_json::Value;
|
||||
|
||||
/// Progress and outcome events emitted by `run_subagent` as it processes
|
||||
/// LLM responses and tool calls.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum SubagentEvent {
|
||||
StepCompleted {
|
||||
output: String,
|
||||
},
|
||||
StepFailed {
|
||||
step: usize,
|
||||
error: String,
|
||||
},
|
||||
Completed,
|
||||
ToolCall {
|
||||
tool: String,
|
||||
args: Value,
|
||||
},
|
||||
ToolResult {
|
||||
tool: String,
|
||||
args: Value,
|
||||
},
|
||||
Progress(String),
|
||||
/// Token usage reported by the LLM after one streaming call inside the
|
||||
/// subagent. The drain thread accumulates these across all steps and
|
||||
/// forwards the total to the parent's `TurnEvent::ReviewUsage` handler
|
||||
/// so the Usage panel can split "main" tokens from "self-learning"
|
||||
/// tokens (review, test-gen, arch-review, security-review, etc.).
|
||||
///
|
||||
/// Why a separate variant instead of folding into `Completed`: usage
|
||||
/// is reported per-step, so the parent can update the running total
|
||||
/// incrementally rather than waiting for the whole subagent run to
|
||||
/// finish. The drain thread still aggregates before forwarding.
|
||||
Usage {
|
||||
tokens_in: u64,
|
||||
tokens_out: u64,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//! Subagent management: spawning, context building, engine loop, and
|
||||
//! progress events.
|
||||
pub mod auto;
|
||||
pub mod context;
|
||||
pub mod division;
|
||||
pub mod engine;
|
||||
pub mod event;
|
||||
pub mod spawn;
|
||||
@@ -0,0 +1,56 @@
|
||||
//! `AgentDefinition` -- declarative specification for instantiating a
|
||||
//! subagent from workflow scripts or programmatic calls.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Declarative specification for instantiating a subagent: name, role,
|
||||
/// optional system prompt, allowed tools, step budget, and temperature.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AgentDefinition {
|
||||
pub name: String,
|
||||
pub role: String,
|
||||
pub system_prompt: Option<String>,
|
||||
pub allowed_tools: Option<Vec<String>>,
|
||||
pub max_steps: Option<usize>,
|
||||
pub temperature: Option<f32>,
|
||||
}
|
||||
|
||||
impl AgentDefinition {
|
||||
/// Create an agent definition with the required name and role; all
|
||||
/// optional fields start as `None`.
|
||||
pub fn new(name: String, role: String) -> Self {
|
||||
AgentDefinition {
|
||||
name,
|
||||
role,
|
||||
system_prompt: None,
|
||||
allowed_tools: None,
|
||||
max_steps: None,
|
||||
temperature: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Builder method: set the system prompt for this agent.
|
||||
pub fn with_system_prompt(mut self, prompt: String) -> Self {
|
||||
self.system_prompt = Some(prompt);
|
||||
self
|
||||
}
|
||||
|
||||
/// Builder method: set the allowed tool list for this agent.
|
||||
pub fn with_allowed_tools(mut self, tools: Vec<String>) -> Self {
|
||||
self.allowed_tools = Some(tools);
|
||||
self
|
||||
}
|
||||
|
||||
/// Builder method: set the maximum step count for this agent.
|
||||
#[allow(dead_code)]
|
||||
pub fn with_max_steps(mut self, steps: usize) -> Self {
|
||||
self.max_steps = Some(steps);
|
||||
self
|
||||
}
|
||||
|
||||
/// Builder method: set the temperature for this agent.
|
||||
#[allow(dead_code)]
|
||||
pub fn with_temperature(mut self, temp: f32) -> Self {
|
||||
self.temperature = Some(temp);
|
||||
self
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user