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
|
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};
use crate::session::Session;
use crate::tools::{self, Approval};
use crate::ui::{self, Approver, Renderer};
/// 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_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<project-instructions source=\"{}\">\n{}\n</project-instructions>\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;
}
}
}
fn git_branch(cwd: &str) -> Option<String> {
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<Value> {
vec![system]
}
#[derive(Debug, Default, Clone, Copy)]
pub struct TurnReport {
pub steps: usize,
pub aborted: bool,
pub denied: usize,
}
pub enum ToolOutcome {
Ok(String),
Denied,
Failed(String),
}
impl ToolOutcome {
fn content(&self) -> String {
match self {
ToolOutcome::Ok(output) => output.clone(),
ToolOutcome::Denied => "error: denied by the user".to_string(),
ToolOutcome::Failed(error) => format!("error: {error}"),
}
}
fn summary(&self) -> String {
match self {
ToolOutcome::Ok(output) => output
.lines()
.find(|line| !line.trim().is_empty())
.unwrap_or("")
.trim()
.to_string(),
ToolOutcome::Denied => "denied".to_string(),
ToolOutcome::Failed(error) => format!("error: {error}"),
}
}
fn denied(&self) -> bool {
matches!(self, ToolOutcome::Denied)
}
}
/// 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<Value>,
prompt: &str,
cancel: &AtomicBool,
approver: &mut Approver,
) -> Result<TurnReport, Error> {
// A Ctrl-C pressed after the previous turn finished must not abort this one.
cancel.store(false, std::sync::atomic::Ordering::SeqCst);
let started = Instant::now();
repair_tool_results(session, history);
let user = json!({ "role": "user", "content": prompt });
push(session, history, user, None);
let schemas = tools::schemas();
let mut steps = 0usize;
let mut last: Option<Outcome> = None;
let mut aborted = false;
let mut denied = 0usize;
let mut truncated: Option<String> = None;
loop {
if cancel.load(std::sync::atomic::Ordering::Relaxed) {
aborted = true;
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) => {
aborted = true;
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}");
}
}
if outcome.finish.as_deref() == Some("length") {
truncated = Some("the model hit its output limit; the answer is cut off".into());
}
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 {
// Cancelling between calls still has to answer every tool call the
// assistant message announced: an unanswered id makes the session
// permanently unusable, because history is never rewritten.
if cancel.load(std::sync::atomic::Ordering::Relaxed) {
aborted = true;
}
let result = if aborted {
ToolOutcome::Failed("aborted by the user before this call ran".into())
} else {
execute(&call, approver, cancel)
};
if result.denied() {
denied += 1;
}
ui::tool_result(&result.summary(), aborted);
let message = json!({
"role": "tool",
"tool_call_id": call.id,
"content": result.content(),
});
push(session, history, message, None);
}
if aborted {
break;
}
}
if aborted {
eprintln!("aborted");
}
if let Some(note) = truncated {
eprintln!("agent686: {note}");
}
if let Some(outcome) = last {
ui::status(steps, started.elapsed(), &outcome);
}
Ok(TurnReport {
steps,
aborted,
denied,
})
}
/// Any assistant message whose tool calls never got results would be rejected by
/// the provider, and the transcript is append-only. Repair by appending the
/// missing results, which is legal: only rewriting is forbidden.
fn repair_tool_results(session: &mut Session, history: &mut Vec<Value>) {
let index = match history.iter().rposition(|message| {
message.get("role").and_then(|role| role.as_str()) == Some("assistant")
&& message
.get("tool_calls")
.and_then(|calls| calls.as_array())
.is_some_and(|calls| !calls.is_empty())
}) {
Some(index) => index,
None => return,
};
let ids: Vec<String> = history[index]["tool_calls"]
.as_array()
.map(|calls| {
calls
.iter()
.filter_map(|call| call.get("id").and_then(|id| id.as_str()))
.map(|id| id.to_string())
.collect()
})
.unwrap_or_default();
let answered: std::collections::HashSet<String> = history[index + 1..]
.iter()
.filter_map(|message| message.get("tool_call_id").and_then(|id| id.as_str()))
.map(|id| id.to_string())
.collect();
for id in ids {
if answered.contains(&id) {
continue;
}
let message = json!({
"role": "tool",
"tool_call_id": id,
"content": "error: this call was interrupted before it ran",
});
push(session, history, message, None);
}
}
fn execute(
call: &provider::ToolCall,
approver: &mut Approver,
cancel: &AtomicBool,
) -> ToolOutcome {
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 => match tools::run(&call.name, &args, cancel) {
Ok(output) => ToolOutcome::Ok(output),
Err(error) => ToolOutcome::Failed(error),
},
Approval::Once => match tools::plan(&call.name, &args) {
Ok(change) => {
if approver.allow_edit(change.path(), &change.preview()) {
match change.apply() {
Ok(output) => ToolOutcome::Ok(output),
Err(error) => ToolOutcome::Failed(error),
}
} else {
ToolOutcome::Denied
}
}
Err(error) => ToolOutcome::Failed(error),
},
Approval::EveryCall => {
let cmd = args.get("cmd").and_then(|v| v.as_str()).unwrap_or("");
if approver.allow_bash(cmd) {
match tools::run(&call.name, &args, cancel) {
Ok(output) => ToolOutcome::Ok(output),
Err(error) => ToolOutcome::Failed(error),
}
} else {
ToolOutcome::Denied
}
}
}
}
fn assistant_message(outcome: &Outcome) -> Value {
let mut message = serde_json::Map::new();
message.insert("role".into(), json!("assistant"));
message.insert(
"content".into(),
if outcome.content.is_empty() {
Value::Null
} else {
json!(outcome.content)
},
);
if !outcome.tool_calls.is_empty() {
let calls: Vec<Value> = outcome
.tool_calls
.iter()
.map(|call| {
json!({
"id": call.id,
"type": "function",
"function": {
"name": call.name,
// Byte-for-byte what the model sent.
"arguments": call.arguments,
}
})
})
.collect();
message.insert("tool_calls".into(), Value::Array(calls));
}
Value::Object(message)
}
fn push(session: &mut Session, history: &mut Vec<Value>, message: Value, reasoning: Option<&str>) {
if let Err(error) = session.append(&message, reasoning) {
eprintln!("agent686: could not write session: {error}");
}
history.push(message);
}
|