From 343f2a8a6148b8004d6f4d74fb779b4f30c9686a Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 03:11:22 +0100 Subject: M1-M5: sessions, six tools, approvals, prompt, Ctrl-C, target gate - append-only JSONL sessions with --continue/--session; reasoning stored, stripped on replay - read/write/edit/grep/glob + bash with timeout and capped output - diff-preview approval for the first edit of a session, per-call approval for bash - system prompt frozen per session with AGENTS.md snapshot and change warning - SIGINT aborts the turn, second Ctrl-C exits - glibc gate ignores weak symbols; verified in linux/386 debian:12 - acceptance test (calculator in C) passes on both x86-64 and i386 --- src/agent.rs | 218 +++++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 198 insertions(+), 20 deletions(-) (limited to 'src/agent.rs') diff --git a/src/agent.rs b/src/agent.rs index 2d84566..7e652ed 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -1,34 +1,211 @@ +use std::path::PathBuf; +use std::process::Command; use std::sync::atomic::AtomicBool; +use std::time::{Instant, SystemTime}; use serde_json::{json, Value}; use crate::config::Config; -use crate::provider::{self, Error, Outcome, Sink}; +use crate::provider::{self, Error, Outcome}; +use crate::session::Session; +use crate::tools::{self, Approval}; +use crate::ui::{self, Approver, Renderer}; -/// Frozen for the life of the process. Anything session-varying added here +/// Frozen for the life of the session. Anything session-varying added here /// invalidates the provider's prompt cache, so keep it boring. -pub fn system_message() -> Value { - json!({ - "role": "system", - "content": "You are agent686, a coding agent working in a Unix terminal. \ - You edit files and run commands. Be terse and do not explain \ - what you are about to do before doing it." - }) +pub fn system_prompt() -> Value { + let mut text = String::from( + "You are agent686, a coding agent in a Unix terminal.\n\n\ + Tools: read, write, edit, bash, grep, glob. Paths are relative to the working \ + directory.\n\ + - read before you edit; files are shown with line numbers.\n\ + - edit replaces one exact occurrence of the old text and fails if it is missing \ + or ambiguous, so include enough context.\n\ + - write replaces a whole file and does not create directories.\n\ + - bash starts a fresh shell in the working directory every call; cd does not \ + persist, pass cwd instead.\n\ + - Do not explain what you are about to do. Act, then report briefly.\n\n", + ); + + let cwd = std::env::current_dir() + .map(|p| p.display().to_string()) + .unwrap_or_default(); + text.push_str(&format!( + "Environment: cwd={cwd} · {} · {}", + std::env::consts::OS, + std::env::consts::ARCH + )); + if let Some(branch) = git_branch(&cwd) { + text.push_str(&format!(" · branch={branch}")); + } + text.push('\n'); + + if let Some((path, content)) = project_instructions() { + if !content.trim().is_empty() { + text.push_str(&format!( + "\n\n{}\n\n", + path.display(), + content.trim() + )); + } + } + + json!({ "role": "system", "content": text }) +} + +pub fn agents_md() -> Option<(PathBuf, SystemTime)> { + let path = project_instructions().map(|(path, _)| path)?; + let modified = std::fs::metadata(&path).ok()?.modified().ok()?; + Some((path, modified)) +} + +fn project_instructions() -> Option<(PathBuf, String)> { + let mut dir = std::env::current_dir().ok()?; + loop { + let candidate = dir.join("AGENTS.md"); + if candidate.is_file() { + let content = std::fs::read_to_string(&candidate).ok()?; + return Some((candidate, content)); + } + if !dir.pop() { + return None; + } + } } -/// Appends the user message, runs one provider round trip, and appends the -/// assistant message to the history whether or not it asked for tools. +fn git_branch(cwd: &str) -> Option { + let output = Command::new("git") + .arg("-C") + .arg(cwd) + .args(["rev-parse", "--abbrev-ref", "HEAD"]) + .output() + .ok()?; + if !output.status.success() { + return None; + } + let branch = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if branch.is_empty() { + None + } else { + Some(branch) + } +} + +pub fn new_history(system: Value) -> Vec { + vec![system] +} + +/// Runs one turn to completion: model, tools, model, ... until the model answers +/// without asking for a tool. Every message that is sent is also appended to the +/// session file, in order, before the next request. pub fn run_turn( cfg: &Config, + session: &mut Session, history: &mut Vec, prompt: &str, cancel: &AtomicBool, - sink: &mut dyn Sink, -) -> Result { - history.push(json!({ "role": "user", "content": prompt })); + approver: &mut Approver, +) -> Result<(), Error> { + let started = Instant::now(); + + let user = json!({ "role": "user", "content": prompt }); + push(session, history, user, None); - let outcome = provider::chat(cfg, history, cancel, sink)?; + let schemas = tools::schemas(); + let mut steps = 0usize; + let mut last: Option = None; + loop { + if cancel.load(std::sync::atomic::Ordering::Relaxed) { + crate::signal::reset(); + eprintln!("aborted"); + break; + } + + steps += 1; + let mut renderer = Renderer::new(); + let mut outcome = match provider::chat(cfg, history, &schemas, cancel, &mut renderer) { + Ok(outcome) => outcome, + Err(Error::Aborted) => { + crate::signal::reset(); + eprintln!("aborted"); + break; + } + Err(error) => return Err(error), + }; + + // A missing id would make the tool result unattachable. + for (index, call) in outcome.tool_calls.iter_mut().enumerate() { + if call.id.is_empty() { + call.id = format!("call_{steps}_{index}"); + } + } + + let assistant = assistant_message(&outcome); + push(session, history, assistant, Some(outcome.reasoning.as_str())); + + if outcome.tool_calls.is_empty() { + last = Some(outcome); + break; + } + let calls = outcome.tool_calls.clone(); + last = Some(outcome); + + for call in calls { + if cancel.load(std::sync::atomic::Ordering::Relaxed) { + crate::signal::reset(); + eprintln!("aborted"); + break; + } + let result = execute(&call, approver); + ui::tool_result(&result); + let content = match result { + Ok(output) => output, + Err(error) => format!("error: {error}"), + }; + let message = json!({ + "role": "tool", + "tool_call_id": call.id, + "content": content, + }); + push(session, history, message, None); + } + } + + if let Some(outcome) = last { + ui::status(steps, started.elapsed(), &outcome); + } + Ok(()) +} + +fn execute(call: &provider::ToolCall, approver: &mut Approver) -> Result { + let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); + ui::tool_line(&call.name, &args); + + match tools::approval(&call.name) { + Approval::Never => tools::run(&call.name, &args), + Approval::Once => match tools::plan(&call.name, &args) { + Ok(change) => { + if approver.allow_edit(change.path(), &change.preview()) { + change.apply() + } else { + Err("denied by the user".into()) + } + } + Err(error) => Err(error), + }, + Approval::EveryCall => { + let cmd = args.get("cmd").and_then(|v| v.as_str()).unwrap_or(""); + if approver.allow_bash(cmd) { + tools::run(&call.name, &args) + } else { + Err("denied by the user".into()) + } + } + } +} + +fn assistant_message(outcome: &Outcome) -> Value { let mut message = serde_json::Map::new(); message.insert("role".into(), json!("assistant")); message.insert( @@ -57,11 +234,12 @@ pub fn run_turn( .collect(); message.insert("tool_calls".into(), Value::Array(calls)); } - history.push(Value::Object(message)); - - Ok(outcome) + Value::Object(message) } -pub fn new_history() -> Vec { - vec![system_message()] +fn push(session: &mut Session, history: &mut Vec, message: Value, reasoning: Option<&str>) { + if let Err(error) = session.append(&message, reasoning) { + eprintln!("agent686: could not write session: {error}"); + } + history.push(message); } -- cgit v1.2.3