diff options
Diffstat (limited to 'src/agent.rs')
| -rw-r--r-- | src/agent.rs | 218 |
1 files changed, 198 insertions, 20 deletions
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 @@ | |||
| 1 | use std::path::PathBuf; | ||
| 2 | use std::process::Command; | ||
| 1 | use std::sync::atomic::AtomicBool; | 3 | use std::sync::atomic::AtomicBool; |
| 4 | use std::time::{Instant, SystemTime}; | ||
| 2 | 5 | ||
| 3 | use serde_json::{json, Value}; | 6 | use serde_json::{json, Value}; |
| 4 | 7 | ||
| 5 | use crate::config::Config; | 8 | use crate::config::Config; |
| 6 | use crate::provider::{self, Error, Outcome, Sink}; | 9 | use crate::provider::{self, Error, Outcome}; |
| 10 | use crate::session::Session; | ||
| 11 | use crate::tools::{self, Approval}; | ||
| 12 | use crate::ui::{self, Approver, Renderer}; | ||
| 7 | 13 | ||
| 8 | /// Frozen for the life of the process. Anything session-varying added here | 14 | /// Frozen for the life of the session. Anything session-varying added here |
| 9 | /// invalidates the provider's prompt cache, so keep it boring. | 15 | /// invalidates the provider's prompt cache, so keep it boring. |
| 10 | pub fn system_message() -> Value { | 16 | pub fn system_prompt() -> Value { |
| 11 | json!({ | 17 | let mut text = String::from( |
| 12 | "role": "system", | 18 | "You are agent686, a coding agent in a Unix terminal.\n\n\ |
| 13 | "content": "You are agent686, a coding agent working in a Unix terminal. \ | 19 | Tools: read, write, edit, bash, grep, glob. Paths are relative to the working \ |
| 14 | You edit files and run commands. Be terse and do not explain \ | 20 | directory.\n\ |
| 15 | what you are about to do before doing it." | 21 | - read before you edit; files are shown with line numbers.\n\ |
| 16 | }) | 22 | - edit replaces one exact occurrence of the old text and fails if it is missing \ |
| 23 | or ambiguous, so include enough context.\n\ | ||
| 24 | - write replaces a whole file and does not create directories.\n\ | ||
| 25 | - bash starts a fresh shell in the working directory every call; cd does not \ | ||
| 26 | persist, pass cwd instead.\n\ | ||
| 27 | - Do not explain what you are about to do. Act, then report briefly.\n\n", | ||
| 28 | ); | ||
| 29 | |||
| 30 | let cwd = std::env::current_dir() | ||
| 31 | .map(|p| p.display().to_string()) | ||
| 32 | .unwrap_or_default(); | ||
| 33 | text.push_str(&format!( | ||
| 34 | "Environment: cwd={cwd} · {} · {}", | ||
| 35 | std::env::consts::OS, | ||
| 36 | std::env::consts::ARCH | ||
| 37 | )); | ||
| 38 | if let Some(branch) = git_branch(&cwd) { | ||
| 39 | text.push_str(&format!(" · branch={branch}")); | ||
| 40 | } | ||
| 41 | text.push('\n'); | ||
| 42 | |||
| 43 | if let Some((path, content)) = project_instructions() { | ||
| 44 | if !content.trim().is_empty() { | ||
| 45 | text.push_str(&format!( | ||
| 46 | "\n<project-instructions source=\"{}\">\n{}\n</project-instructions>\n", | ||
| 47 | path.display(), | ||
| 48 | content.trim() | ||
| 49 | )); | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | json!({ "role": "system", "content": text }) | ||
| 54 | } | ||
| 55 | |||
| 56 | pub fn agents_md() -> Option<(PathBuf, SystemTime)> { | ||
| 57 | let path = project_instructions().map(|(path, _)| path)?; | ||
| 58 | let modified = std::fs::metadata(&path).ok()?.modified().ok()?; | ||
| 59 | Some((path, modified)) | ||
| 60 | } | ||
| 61 | |||
| 62 | fn project_instructions() -> Option<(PathBuf, String)> { | ||
| 63 | let mut dir = std::env::current_dir().ok()?; | ||
| 64 | loop { | ||
| 65 | let candidate = dir.join("AGENTS.md"); | ||
| 66 | if candidate.is_file() { | ||
| 67 | let content = std::fs::read_to_string(&candidate).ok()?; | ||
| 68 | return Some((candidate, content)); | ||
| 69 | } | ||
| 70 | if !dir.pop() { | ||
| 71 | return None; | ||
| 72 | } | ||
| 73 | } | ||
| 17 | } | 74 | } |
| 18 | 75 | ||
| 19 | /// Appends the user message, runs one provider round trip, and appends the | 76 | fn git_branch(cwd: &str) -> Option<String> { |
| 20 | /// assistant message to the history whether or not it asked for tools. | 77 | let output = Command::new("git") |
| 78 | .arg("-C") | ||
| 79 | .arg(cwd) | ||
| 80 | .args(["rev-parse", "--abbrev-ref", "HEAD"]) | ||
| 81 | .output() | ||
| 82 | .ok()?; | ||
| 83 | if !output.status.success() { | ||
| 84 | return None; | ||
| 85 | } | ||
| 86 | let branch = String::from_utf8_lossy(&output.stdout).trim().to_string(); | ||
| 87 | if branch.is_empty() { | ||
| 88 | None | ||
| 89 | } else { | ||
| 90 | Some(branch) | ||
| 91 | } | ||
| 92 | } | ||
| 93 | |||
| 94 | pub fn new_history(system: Value) -> Vec<Value> { | ||
| 95 | vec![system] | ||
| 96 | } | ||
| 97 | |||
| 98 | /// Runs one turn to completion: model, tools, model, ... until the model answers | ||
| 99 | /// without asking for a tool. Every message that is sent is also appended to the | ||
| 100 | /// session file, in order, before the next request. | ||
| 21 | pub fn run_turn( | 101 | pub fn run_turn( |
| 22 | cfg: &Config, | 102 | cfg: &Config, |
| 103 | session: &mut Session, | ||
| 23 | history: &mut Vec<Value>, | 104 | history: &mut Vec<Value>, |
| 24 | prompt: &str, | 105 | prompt: &str, |
| 25 | cancel: &AtomicBool, | 106 | cancel: &AtomicBool, |
| 26 | sink: &mut dyn Sink, | 107 | approver: &mut Approver, |
| 27 | ) -> Result<Outcome, Error> { | 108 | ) -> Result<(), Error> { |
| 28 | history.push(json!({ "role": "user", "content": prompt })); | 109 | let started = Instant::now(); |
| 110 | |||
| 111 | let user = json!({ "role": "user", "content": prompt }); | ||
| 112 | push(session, history, user, None); | ||
| 29 | 113 | ||
| 30 | let outcome = provider::chat(cfg, history, cancel, sink)?; | 114 | let schemas = tools::schemas(); |
| 115 | let mut steps = 0usize; | ||
| 116 | let mut last: Option<Outcome> = None; | ||
| 31 | 117 | ||
| 118 | loop { | ||
| 119 | if cancel.load(std::sync::atomic::Ordering::Relaxed) { | ||
| 120 | crate::signal::reset(); | ||
| 121 | eprintln!("aborted"); | ||
| 122 | break; | ||
| 123 | } | ||
| 124 | |||
| 125 | steps += 1; | ||
| 126 | let mut renderer = Renderer::new(); | ||
| 127 | let mut outcome = match provider::chat(cfg, history, &schemas, cancel, &mut renderer) { | ||
| 128 | Ok(outcome) => outcome, | ||
| 129 | Err(Error::Aborted) => { | ||
| 130 | crate::signal::reset(); | ||
| 131 | eprintln!("aborted"); | ||
| 132 | break; | ||
| 133 | } | ||
| 134 | Err(error) => return Err(error), | ||
| 135 | }; | ||
| 136 | |||
| 137 | // A missing id would make the tool result unattachable. | ||
| 138 | for (index, call) in outcome.tool_calls.iter_mut().enumerate() { | ||
| 139 | if call.id.is_empty() { | ||
| 140 | call.id = format!("call_{steps}_{index}"); | ||
| 141 | } | ||
| 142 | } | ||
| 143 | |||
| 144 | let assistant = assistant_message(&outcome); | ||
| 145 | push(session, history, assistant, Some(outcome.reasoning.as_str())); | ||
| 146 | |||
| 147 | if outcome.tool_calls.is_empty() { | ||
| 148 | last = Some(outcome); | ||
| 149 | break; | ||
| 150 | } | ||
| 151 | let calls = outcome.tool_calls.clone(); | ||
| 152 | last = Some(outcome); | ||
| 153 | |||
| 154 | for call in calls { | ||
| 155 | if cancel.load(std::sync::atomic::Ordering::Relaxed) { | ||
| 156 | crate::signal::reset(); | ||
| 157 | eprintln!("aborted"); | ||
| 158 | break; | ||
| 159 | } | ||
| 160 | let result = execute(&call, approver); | ||
| 161 | ui::tool_result(&result); | ||
| 162 | let content = match result { | ||
| 163 | Ok(output) => output, | ||
| 164 | Err(error) => format!("error: {error}"), | ||
| 165 | }; | ||
| 166 | let message = json!({ | ||
| 167 | "role": "tool", | ||
| 168 | "tool_call_id": call.id, | ||
| 169 | "content": content, | ||
| 170 | }); | ||
| 171 | push(session, history, message, None); | ||
| 172 | } | ||
| 173 | } | ||
| 174 | |||
| 175 | if let Some(outcome) = last { | ||
| 176 | ui::status(steps, started.elapsed(), &outcome); | ||
| 177 | } | ||
| 178 | Ok(()) | ||
| 179 | } | ||
| 180 | |||
| 181 | fn execute(call: &provider::ToolCall, approver: &mut Approver) -> Result<String, String> { | ||
| 182 | let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); | ||
| 183 | ui::tool_line(&call.name, &args); | ||
| 184 | |||
| 185 | match tools::approval(&call.name) { | ||
| 186 | Approval::Never => tools::run(&call.name, &args), | ||
| 187 | Approval::Once => match tools::plan(&call.name, &args) { | ||
| 188 | Ok(change) => { | ||
| 189 | if approver.allow_edit(change.path(), &change.preview()) { | ||
| 190 | change.apply() | ||
| 191 | } else { | ||
| 192 | Err("denied by the user".into()) | ||
| 193 | } | ||
| 194 | } | ||
| 195 | Err(error) => Err(error), | ||
| 196 | }, | ||
| 197 | Approval::EveryCall => { | ||
| 198 | let cmd = args.get("cmd").and_then(|v| v.as_str()).unwrap_or(""); | ||
| 199 | if approver.allow_bash(cmd) { | ||
| 200 | tools::run(&call.name, &args) | ||
| 201 | } else { | ||
| 202 | Err("denied by the user".into()) | ||
| 203 | } | ||
| 204 | } | ||
| 205 | } | ||
| 206 | } | ||
| 207 | |||
| 208 | fn assistant_message(outcome: &Outcome) -> Value { | ||
| 32 | let mut message = serde_json::Map::new(); | 209 | let mut message = serde_json::Map::new(); |
| 33 | message.insert("role".into(), json!("assistant")); | 210 | message.insert("role".into(), json!("assistant")); |
| 34 | message.insert( | 211 | message.insert( |
| @@ -57,11 +234,12 @@ pub fn run_turn( | |||
| 57 | .collect(); | 234 | .collect(); |
| 58 | message.insert("tool_calls".into(), Value::Array(calls)); | 235 | message.insert("tool_calls".into(), Value::Array(calls)); |
| 59 | } | 236 | } |
| 60 | history.push(Value::Object(message)); | 237 | Value::Object(message) |
| 61 | |||
| 62 | Ok(outcome) | ||
| 63 | } | 238 | } |
| 64 | 239 | ||
| 65 | pub fn new_history() -> Vec<Value> { | 240 | fn push(session: &mut Session, history: &mut Vec<Value>, message: Value, reasoning: Option<&str>) { |
| 66 | vec![system_message()] | 241 | if let Err(error) = session.append(&message, reasoning) { |
| 242 | eprintln!("agent686: could not write session: {error}"); | ||
| 243 | } | ||
| 244 | history.push(message); | ||
| 67 | } | 245 | } |
