use std::path::PathBuf;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct ReplConfig {
pub repo_root: PathBuf,
pub model: Option<String>,
pub gate: Option<String>,
pub context_strategy: String,
pub container: Option<String>,
pub max_turns: usize,
pub max_gates: usize,
pub rollback: bool,
pub converse: bool,
pub dispatch_cmd: Option<String>,
pub fold_budget: Option<usize>,
pub sandbox: String,
pub network: Option<String>,
pub allow_read: Vec<PathBuf>,
pub pass_env: Vec<String>,
}
impl Default for ReplConfig {
fn default() -> Self {
Self {
repo_root: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
model: None,
gate: None,
context_strategy: "folded".to_string(),
container: None,
max_turns: 60,
max_gates: 5,
rollback: true,
converse: false,
dispatch_cmd: None,
fold_budget: None,
sandbox: "on".to_string(),
network: None,
allow_read: Vec::new(),
pass_env: Vec::new(),
}
}
}
pub struct ReplSession {
pub repo_root: PathBuf,
pub gate: Option<String>,
pub model: String,
pub context_strategy: String,
pub container: Option<String>,
pub max_turns: usize,
pub max_gates: usize,
pub rollback: bool,
pub converse: bool,
pub dispatch_cmd: Option<String>,
pub fold_budget: Option<usize>,
pub sandbox: String,
pub network: String,
pub allow_read: Vec<PathBuf>,
pub pass_env: Vec<String>,
pub state: blyte_agent::state::State,
pub session_id: String,
private_tmpdir: Option<PathBuf>,
}
impl Drop for ReplSession {
fn drop(&mut self) {
if let Some(ref dir) = self.private_tmpdir {
let _ = std::fs::remove_dir_all(dir);
}
}
}
pub fn new_session_id(now_secs: u64, pid: u32) -> String {
format!("{now_secs}-{pid}")
}
impl ReplSession {
pub fn try_new(config: &ReplConfig) -> Result<Self, String> {
Self::try_new_with_approver(config, None)
}
pub fn try_new_with_approver(
config: &ReplConfig,
approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
) -> Result<Self, String> {
let session_id = match std::env::var("BLYTE_SESSION") {
Ok(v) if !v.is_empty() => v,
_ => {
let now_secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let id = new_session_id(now_secs, std::process::id());
std::env::set_var("BLYTE_SESSION", &id);
id
}
};
let gate = config.gate.clone();
let verification_cmd = gate.clone().unwrap_or_default();
let goal = "Interactive REPL session".to_string();
let mut state = blyte_agent::state::State::new(goal, verification_cmd);
state.runtime.conversation = Some(Vec::new());
let network = match &config.network {
Some(v) => v.clone(),
None if config.converse && config.sandbox == "on" && config.container.is_none() => {
"off".to_string()
}
None => "on".to_string(),
};
let sandbox_on = config.sandbox == "on";
let policy = crate::task_runner::configure_converse_policy_with_paths(
config.converse,
sandbox_on,
&config.repo_root,
approver,
)?;
if config.converse {
if let Err(e) = crate::conversation_text::set_state_instructions(
&mut state,
config.dispatch_cmd.is_some(),
&config.repo_root,
sandbox_on,
policy.allowed_count,
) {
if let Some(ref dir) = policy.private_tmpdir {
let _ = std::fs::remove_dir_all(dir);
}
return Err(e);
}
}
Ok(Self {
repo_root: config.repo_root.clone(),
gate,
model: config
.model
.clone()
.unwrap_or_else(|| "gemini-3.8-flash".to_string()),
context_strategy: config.context_strategy.clone(),
container: config.container.clone(),
max_turns: config.max_turns,
max_gates: config.max_gates,
rollback: config.rollback,
converse: config.converse,
dispatch_cmd: config.dispatch_cmd.clone(),
fold_budget: config.fold_budget,
sandbox: config.sandbox.clone(),
network,
allow_read: config.allow_read.clone(),
pass_env: config.pass_env.clone(),
state,
session_id,
private_tmpdir: policy.private_tmpdir,
})
}
pub fn private_tmpdir(&self) -> Option<&std::path::Path> {
self.private_tmpdir.as_deref()
}
pub fn new(config: &ReplConfig) -> Self {
Self::try_new(config).expect("failed to initialize REPL session")
}
pub fn task_config_for_prompt(&self, prompt: &str) -> crate::task_runner::TaskConfig {
crate::task_runner::TaskConfig {
prompt: prompt.to_string(),
gate: self.gate.clone(),
context_strategy: self.context_strategy.clone(),
model: Some(self.model.clone()),
container: self.container.clone(),
max_turns: self.max_turns,
max_gates: self.max_gates,
rollback: self.rollback,
root: self.repo_root.clone(),
container_workdir: "/workspace".into(),
max_seconds: None,
max_cost_usd: None,
report: None,
fold_budget: self.fold_budget,
sandbox: self.sandbox.clone(),
network: self.network.clone(),
allow_read: self.allow_read.clone(),
pass_env: self.pass_env.clone(),
research: false,
claim_check: false,
base_check: false,
base_check_dir: None,
converse: self.converse,
dispatch_cmd: self.dispatch_cmd.clone(),
in_place: None,
}
}
}
pub fn format_event(event: &blyte_agent::run::Event<'_>) -> String {
match event {
blyte_agent::run::Event::Turn { n, text, .. } => {
format!("[Turn {}] {}", n, text)
}
blyte_agent::run::Event::Tool {
name,
input,
summary,
is_error,
} => {
if *is_error {
format!("\x1b[31m● {} {} -> {}\x1b[0m", name, input, summary)
} else {
format!("● {} {} -> {}", name, input, summary)
}
}
blyte_agent::run::Event::GateStart { attempt } => {
format!("⏳ Gate running (attempt {})", attempt)
}
blyte_agent::run::Event::GateSlotWait { ms } => {
format!("⏳ Gate waited {}ms for slot", ms)
}
blyte_agent::run::Event::Gate {
attempt,
passed,
output,
} => {
if *passed {
format!("✓ Gate passed (attempt {})", attempt)
} else {
format!("✗ Gate failed (attempt {}): {}", attempt, output.trim())
}
}
blyte_agent::run::Event::RolledBack { to } => {
format!("↺ Rolled back working tree to {}", to)
}
blyte_agent::run::Event::FirstOutput { .. }
| blyte_agent::run::Event::ToolStart { .. }
| blyte_agent::run::Event::Retry { .. } => String::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use blyte_agent::run::Event;
#[test]
fn test_new_session_id_format() {
assert_eq!(new_session_id(1700000000, 42), "1700000000-42");
}
#[test]
fn test_repl_session_default_model_is_gemini_3_8_flash() {
let session = ReplSession::new(&ReplConfig::default());
assert_eq!(session.model, "gemini-3.8-flash");
}
#[test]
fn test_format_event() {
let e1 = Event::Turn {
n: 1,
text: "Thinking about plan",
usage: Default::default(),
};
let s1 = format_event(&e1);
assert!(s1.contains('1') && s1.contains("Thinking about plan"));
let e2 = Event::Tool {
name: "bash",
input: "git status".to_string(),
summary: "clean working tree".to_string(),
is_error: false,
};
let s2 = format_event(&e2);
assert!(s2.contains('●') && s2.contains("bash") && s2.contains("git status"));
let e3 = Event::Tool {
name: "bash",
input: "cargo test".to_string(),
summary: "exit 101".to_string(),
is_error: true,
};
let s3 = format_event(&e3);
assert!(s3.contains('●') && s3.contains("cargo test"));
let e4 = Event::Gate {
attempt: 1,
passed: true,
output: "ok",
};
let s4 = format_event(&e4);
assert!(s4.contains("✓ Gate passed"));
let e5 = Event::Gate {
attempt: 2,
passed: false,
output: "failed",
};
let s5 = format_event(&e5);
assert!(s5.contains("✗ Gate failed"));
let e6 = Event::RolledBack { to: "abc1234" };
let s6 = format_event(&e6);
assert!(s6.contains("↺ Rolled back working tree to abc1234"));
}
#[test]
fn test_format_event_turn_full_text() {
let text = "x".repeat(299) + "Z";
let event = Event::Turn {
n: 3,
text: &text,
usage: Default::default(),
};
let formatted = format_event(&event);
assert_eq!(formatted, format!("[Turn 3] {text}"));
assert!(formatted.contains('Z'));
assert!(!formatted.ends_with("..."));
}
#[test]
fn test_format_event_turn_multiline() {
let text = "Plan:\n1. a\n2. b\nShall I go ahead?";
let event = Event::Turn {
n: 1,
text,
usage: Default::default(),
};
assert_eq!(
format_event(&event),
"[Turn 1] Plan:\n1. a\n2. b\nShall I go ahead?"
);
}
#[test]
fn test_format_event_turn_multibyte() {
let text = "é".repeat(100);
let event = Event::Turn {
n: 1,
text: &text,
usage: Default::default(),
};
let formatted = format_event(&event);
assert_eq!(formatted.chars().count(), "[Turn 1] ".len() + 100);
}
#[test]
fn a_gate_start_renders_as_gate_running() {
let e = Event::GateStart { attempt: 2 };
assert_eq!(format_event(&e), "⏳ Gate running (attempt 2)");
}
}