summaryrefslogtreecommitdiffstats
path: root/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/main.rs')
-rw-r--r--src/main.rs217
1 files changed, 162 insertions, 55 deletions
diff --git a/src/main.rs b/src/main.rs
index 8c9a58c..c53ebb6 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,7 +1,13 @@
1use std::io::{BufRead, IsTerminal, Write}; 1use std::io::{BufRead, IsTerminal, Write};
2use std::sync::atomic::AtomicBool; 2use std::path::PathBuf;
3use std::time::SystemTime;
3 4
4use agent686::{agent, config::Config, ui}; 5use serde_json::Value;
6
7use agent686::config::Config;
8use agent686::session::{self, Session};
9use agent686::ui::Approver;
10use agent686::{agent, signal};
5 11
6const HELP: &str = "\ 12const HELP: &str = "\
7agent686 — a small coding agent 13agent686 — a small coding agent
@@ -9,33 +15,40 @@ agent686 — a small coding agent
9USAGE: 15USAGE:
10 agent686 [OPTIONS] [PROMPT...] 16 agent686 [OPTIONS] [PROMPT...]
11 17
12With a prompt it runs one turn and exits; without one it reads prompts from 18With a prompt it runs one turn and exits. Without one it reads prompts from
13stdin, one per line. /exit quits. 19stdin, one per line. Commands: /paste, /exit, /help.
14 20
15OPTIONS: 21OPTIONS:
16 -m, --model <ID> model id (default: deepseek-v4.1-flash) 22 -m, --model <ID> model id (default: deepseek-v4.1-flash)
17 --base-url <URL> provider base URL, e.g. http://127.0.0.1:8080/v1 23 --base-url <URL> provider base URL
18 --session <ID> reuse a session id, including for the provider header 24 --session <ID> resume a specific session
25 -c, --continue resume the most recent session
26 --yolo approve every tool call without asking
19 -h, --help this text 27 -h, --help this text
20 28
21ENVIRONMENT: 29ENVIRONMENT:
22 OPENCODE_API_KEY credential (falls back to ~/.config/agent686/key) 30 OPENCODE_API_KEY credential (falls back to ~/.config/agent686/key)
23 AGENT686_MODEL default model id 31 AGENT686_MODEL default model id
24 AGENT686_BASE_URL default provider base URL 32 AGENT686_BASE_URL default provider base URL
33 AGENT686_DATA where sessions live (default ~/.local/share/agent686)
25"; 34";
26 35
27fn main() { 36fn main() {
28 let mut prompt: Option<String> = None; 37 let mut prompt_words: Vec<String> = Vec::new();
29 let mut model = None; 38 let mut model = None;
30 let mut base_url = None; 39 let mut base_url = None;
31 let mut session = None; 40 let mut resume = None;
41 let mut continue_last = false;
42 let mut yolo = false;
32 43
33 let mut args = std::env::args().skip(1); 44 let mut args = std::env::args().skip(1);
34 while let Some(arg) = args.next() { 45 while let Some(arg) = args.next() {
35 match arg.as_str() { 46 match arg.as_str() {
36 "-m" | "--model" => model = args.next(), 47 "-m" | "--model" => model = args.next(),
37 "--base-url" => base_url = args.next(), 48 "--base-url" => base_url = args.next(),
38 "--session" => session = args.next(), 49 "--session" | "--resume" => resume = args.next(),
50 "-c" | "--continue" => continue_last = true,
51 "--yolo" => yolo = true,
39 "-h" | "--help" => { 52 "-h" | "--help" => {
40 print!("{HELP}"); 53 print!("{HELP}");
41 return; 54 return;
@@ -45,16 +58,13 @@ fn main() {
45 print!("{HELP}"); 58 print!("{HELP}");
46 std::process::exit(2); 59 std::process::exit(2);
47 } 60 }
48 word => { 61 word => prompt_words.push(word.to_string()),
49 prompt = Some(match prompt.take() {
50 Some(existing) => format!("{existing} {word}"),
51 None => word.to_string(),
52 })
53 }
54 } 62 }
55 } 63 }
56 64
57 let cfg = match Config::resolve(model, base_url, session) { 65 signal::install();
66
67 let mut cfg = match Config::resolve(model, base_url, yolo) {
58 Ok(cfg) => cfg, 68 Ok(cfg) => cfg,
59 Err(message) => { 69 Err(message) => {
60 eprintln!("agent686: {message}"); 70 eprintln!("agent686: {message}");
@@ -62,18 +72,31 @@ fn main() {
62 } 72 }
63 }; 73 };
64 74
65 let cancel = AtomicBool::new(false); 75 let (mut session, mut history) = match open_session(&cfg, resume, continue_last) {
66 let mut history = agent::new_history(); 76 Ok(pair) => pair,
67 77 Err(message) => {
68 // One-shot mode: a prompt on the command line means one turn, then exit. 78 eprintln!("agent686: {message}");
69 if let Some(prompt) = prompt { 79 std::process::exit(1);
70 let mut sink = ui::Renderer::new(ui::stdout_is_tty()); 80 }
71 match agent::run_turn(&cfg, &mut history, &prompt, &cancel, &mut sink) { 81 };
72 Ok(outcome) => note_tool_calls(&outcome), 82 cfg.session = session.id.clone();
73 Err(error) => { 83
74 eprintln!("agent686: {error}"); 84 let mut approver = Approver::new(cfg.yolo);
75 std::process::exit(1); 85 let watched = agent::agents_md();
76 } 86 let mut warned = false;
87
88 if !prompt_words.is_empty() {
89 let prompt = prompt_words.join(" ");
90 if let Err(error) = agent::run_turn(
91 &cfg,
92 &mut session,
93 &mut history,
94 &prompt,
95 &signal::CANCEL,
96 &mut approver,
97 ) {
98 eprintln!("agent686: {error}");
99 std::process::exit(1);
77 } 100 }
78 return; 101 return;
79 } 102 }
@@ -84,9 +107,9 @@ fn main() {
84 "agent686 · {} · session {}{}", 107 "agent686 · {} · session {}{}",
85 cfg.model, 108 cfg.model,
86 cfg.session, 109 cfg.session,
87 if is_local(&cfg.base_url) { " · local" } else { "" } 110 if cfg.yolo { " · yolo" } else { "" }
88 ); 111 );
89 eprintln!("one prompt per line · /exit to quit"); 112 eprintln!("one prompt per line · /paste · /exit");
90 } 113 }
91 114
92 let stdin = std::io::stdin(); 115 let stdin = std::io::stdin();
@@ -100,37 +123,121 @@ fn main() {
100 if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 { 123 if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 {
101 break; 124 break;
102 } 125 }
103 let text = line.trim_end(); 126 let mut text = line.trim_end().to_string();
104 if text.is_empty() { 127 if text.is_empty() {
105 continue; 128 continue;
106 } 129 }
107 if text == "/exit" || text == "/quit" { 130
108 break; 131 match text.as_str() {
132 "/exit" | "/quit" => break,
133 "/help" => {
134 print!("{HELP}");
135 continue;
136 }
137 "/paste" => {
138 let mut buffer = String::new();
139 loop {
140 if interactive {
141 print!("… ");
142 let _ = std::io::stdout().flush();
143 }
144 line.clear();
145 if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 {
146 break;
147 }
148 let piece = line.trim_end_matches(['\n', '\r']);
149 if piece == "." {
150 break;
151 }
152 buffer.push_str(piece);
153 buffer.push('\n');
154 }
155 text = buffer.trim_end().to_string();
156 if text.is_empty() {
157 continue;
158 }
159 }
160 _ => {}
109 } 161 }
110 let mut sink = ui::Renderer::new(ui::stdout_is_tty()); 162
111 match agent::run_turn(&cfg, &mut history, text, &cancel, &mut sink) { 163 warn_if_changed(&watched, &mut warned);
112 Ok(outcome) => note_tool_calls(&outcome), 164 if let Err(error) = agent::run_turn(
113 Err(error) => eprintln!("agent686: {error}"), 165 &cfg,
166 &mut session,
167 &mut history,
168 &text,
169 &signal::CANCEL,
170 &mut approver,
171 ) {
172 eprintln!("agent686: {error}");
114 } 173 }
115 } 174 }
116} 175}
117 176
118fn note_tool_calls(outcome: &agent686::provider::Outcome) { 177fn open_session(
119 if outcome.tool_calls.is_empty() { 178 cfg: &Config,
120 return; 179 resume: Option<String>,
180 continue_last: bool,
181) -> Result<(Session, Vec<Value>), String> {
182 let id = match resume {
183 Some(id) => Some(id),
184 None if continue_last => Some(
185 session::latest()?
186 .ok_or_else(|| "no sessions to continue; run without --continue".to_string())?,
187 ),
188 None => None,
189 };
190
191 match id {
192 Some(id) => {
193 let (session, system, messages) = Session::open(&id)?;
194 if !session.model.is_empty() && session.model != cfg.model {
195 eprintln!(
196 "agent686: session used {}; continuing with {}",
197 session.model, cfg.model
198 );
199 }
200 // The system message frozen at session start is reused verbatim, so
201 // the request prefix stays byte-identical across restarts.
202 let system = if system.is_null() {
203 agent::system_prompt()
204 } else {
205 system
206 };
207 let mut history = agent::new_history(system);
208 let count = messages.len();
209 history.extend(messages);
210 eprintln!("agent686: resumed {} ({count} messages)", session.id);
211 Ok((session, history))
212 }
213 None => {
214 let system = agent::system_prompt();
215 let session = Session::create(&cfg.model, &system)?;
216 eprintln!(
217 "agent686: new session {} ({})",
218 session.id,
219 session.path().display()
220 );
221 Ok((session, agent::new_history(system)))
222 }
121 } 223 }
122 let names: Vec<&str> = outcome
123 .tool_calls
124 .iter()
125 .map(|call| call.name.as_str())
126 .collect();
127 eprintln!(
128 "agent686: model asked for {} tool call(s) [{}]; tools arrive in milestone 2",
129 names.len(),
130 names.join(", ")
131 );
132} 224}
133 225
134fn is_local(base_url: &str) -> bool { 226fn warn_if_changed(watched: &Option<(PathBuf, SystemTime)>, warned: &mut bool) {
135 base_url.contains("127.0.0.1") || base_url.contains("localhost") 227 let (path, seen) = match watched {
228 Some(watched) => watched,
229 None => return,
230 };
231 if *warned {
232 return;
233 }
234 if let Ok(modified) = std::fs::metadata(path).and_then(|m| m.modified()) {
235 if modified != *seen {
236 eprintln!(
237 "agent686: {} changed; start a new session to pick it up",
238 path.display()
239 );
240 *warned = true;
241 }
242 }
136} 243}