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
|
use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpListener;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::thread;
use serde_json::json;
use agent686::agent;
use agent686::config::Config;
use agent686::session::Session;
use agent686::ui::Approver;
fn sse(body: &str) -> String {
format!(
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n{body}"
)
}
/// Serves one canned SSE response per connection, in order.
fn serve_sequence(responses: Vec<String>) -> String {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
thread::spawn(move || {
for response in responses {
let (mut stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut length = 0usize;
loop {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
break;
}
if line == "\r\n" || line == "\n" {
break;
}
if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") {
length = value.trim().parse().unwrap_or(0);
}
}
let mut body = vec![0u8; length];
let _ = reader.read_exact(&mut body);
let _ = stream.write_all(response.as_bytes());
let _ = stream.flush();
}
});
format!("http://{addr}")
}
fn temp_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("agent686-loop-{tag}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn runs_a_tool_call_then_finishes_and_records_every_message() {
let dir = temp_dir("write");
let target = dir.join("hello.txt");
let arguments = json!({
"path": target.display().to_string(),
"content": "hello from the mock\n"
})
.to_string();
let tool_round = sse(&format!(
"data: {}\n\ndata: [DONE]\n\n",
json!({
"choices": [{
"delta": { "tool_calls": [{
"index": 0,
"id": "call_1",
"function": { "name": "write", "arguments": arguments }
}]},
"finish_reason": "tool_calls"
}]
})
));
let final_round = sse(
"data: {\"choices\":[{\"delta\":{\"content\":\"done\"},\"finish_reason\":\"stop\"}]}\n\n\
data: [DONE]\n\n",
);
let base = serve_sequence(vec![tool_round, final_round]);
std::env::set_var("AGENT686_DATA", dir.join("data"));
let system = agent::system_prompt();
let mut session = Session::create("test-model", &system).unwrap();
let cfg = Config {
base_url: base,
api_key: "test-key".into(),
model: "test-model".into(),
session: session.id.clone(),
yolo: true,
};
let mut history = agent::new_history(system);
let mut approver = Approver::new(true);
agent::run_turn(
&cfg,
&mut session,
&mut history,
"write a file",
&AtomicBool::new(false),
&mut approver,
)
.expect("turn should complete");
assert_eq!(
fs::read_to_string(&target).unwrap(),
"hello from the mock\n"
);
// system, user, assistant(tool_calls), tool result, assistant(final)
assert_eq!(history.len(), 5);
assert_eq!(history[3]["role"], "tool");
assert_eq!(history[3]["tool_call_id"], "call_1");
let log = fs::read_to_string(session.path()).unwrap();
let lines: Vec<&str> = log.lines().collect();
assert_eq!(lines.len(), 5, "header plus four messages: {log}");
assert!(lines[0].contains("\"t\":\"header\""));
assert_eq!(lines[3].contains("\"role\":\"tool\""), true);
}
#[test]
fn a_denied_tool_call_is_returned_as_data() {
let dir = temp_dir("denied");
let target = dir.join("never.txt");
let arguments = json!({
"path": target.display().to_string(),
"content": "should not exist"
})
.to_string();
let tool_round = sse(&format!(
"data: {}\n\ndata: [DONE]\n\n",
json!({
"choices": [{
"delta": { "tool_calls": [{
"index": 0,
"id": "call_1",
"function": { "name": "write", "arguments": arguments }
}]},
"finish_reason": "tool_calls"
}]
})
));
let final_round = sse(
"data: {\"choices\":[{\"delta\":{\"content\":\"understood\"},\"finish_reason\":\"stop\"}]}\n\n\
data: [DONE]\n\n",
);
let base = serve_sequence(vec![tool_round, final_round]);
std::env::set_var("AGENT686_DATA", dir.join("data"));
let system = agent::system_prompt();
let mut session = Session::create("test-model", &system).unwrap();
let cfg = Config {
base_url: base,
api_key: "test-key".into(),
model: "test-model".into(),
session: session.id.clone(),
yolo: false,
};
let mut history = agent::new_history(system);
// Not a terminal, so the approver must deny rather than block.
let mut approver = Approver::new(false);
agent::run_turn(
&cfg,
&mut session,
&mut history,
"write a file",
&AtomicBool::new(false),
&mut approver,
)
.expect("a denial is not a failed turn");
assert!(!target.exists());
assert_eq!(history[3]["role"], "tool");
assert!(
history[3]["content"]
.as_str()
.unwrap()
.contains("denied by the user")
);
assert_eq!(history[4]["content"], "understood");
}
|