summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: ccd4e37ffc207f24b1794a063bd959b6d710d076 (plain) (blame)
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
use std::io::{BufRead, Write};
use std::path::PathBuf;
use std::time::SystemTime;

use serde_json::Value;

use agent686::config::Config;
use agent686::line::Editor;
use agent686::session::{self, Session};
use agent686::ui::Approver;
use agent686::{agent, signal};

const HELP: &str = "\
agent686 — a small coding agent

USAGE:
  agent686 [OPTIONS] [PROMPT...]

With a prompt it runs one turn and exits. Without one it reads prompts from
stdin. In a terminal: up/down for history, ctrl-a/e/u/w/k to edit, ctrl-d to
exit, ctrl-c to abandon the line. Commands: /paste, /exit, /help.

/cmd
  /paste   read a block of lines until a lone `.`
  /exit    quit

OPTIONS:
  -m, --model <ID>      model id (default: deepseek-v4.1-flash)
      --base-url <URL>  provider base URL
      --session <ID>    resume a session, creating it if the id is new
  -c, --continue        resume the most recent session
      --list            list sessions and exit
      --doctor          check key, directories, provider and model, then exit
  -V, --version         print the version and exit
      --yolo            approve every tool call without asking
  -h, --help            this text

ENVIRONMENT:
  OPENCODE_API_KEY     credential (falls back to ~/.config/agent686/key)
  AGENT686_MODEL       default model id
  AGENT686_BASE_URL    default provider base URL
  AGENT686_DATA        where sessions live (default ~/.local/share/agent686)
";

fn main() {
    let mut prompt_words: Vec<String> = Vec::new();
    let mut model = None;
    let mut base_url = None;
    let mut resume = None;
    let mut continue_last = false;
    let mut list = false;
    let mut doctor = false;
    let mut yolo = false;

    let mut args = std::env::args().skip(1);
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "-m" | "--model" => model = args.next(),
            "--base-url" => base_url = args.next(),
            "--session" | "--resume" => resume = args.next(),
            "-c" | "--continue" => continue_last = true,
            "--list" => list = true,
            "--doctor" => doctor = true,
            "-V" | "--version" => {
                println!("agent686 {}", env!("CARGO_PKG_VERSION"));
                return;
            }
            "--yolo" => yolo = true,
            "-h" | "--help" => {
                print!("{HELP}");
                return;
            }
            flag if flag.starts_with('-') && flag.len() > 1 => {
                eprintln!("agent686: unknown flag {flag}\n");
                print!("{HELP}");
                std::process::exit(2);
            }
            word => prompt_words.push(word.to_string()),
        }
    }

    signal::install();

    if list {
        print_sessions();
        return;
    }

    if doctor {
        let config = Config::resolve_lenient(model, base_url, yolo);
        std::process::exit(agent686::doctor::run(&config));
    }

    let mut cfg = match Config::resolve(model, base_url, yolo) {
        Ok(cfg) => cfg,
        Err(message) => {
            eprintln!("agent686: {message}");
            std::process::exit(2);
        }
    };

    let (mut session, mut history) = match open_session(&cfg, resume, continue_last) {
        Ok(pair) => pair,
        Err(message) => {
            eprintln!("agent686: {message}");
            std::process::exit(1);
        }
    };
    cfg.session = session.id.clone();

    let mut approver = Approver::new(cfg.yolo);
    let watched = agent::agents_md();
    let mut warned = false;

    if !prompt_words.is_empty() {
        let prompt = prompt_words.join(" ");
        if let Err(error) = agent::run_turn(
            &cfg,
            &mut session,
            &mut history,
            &prompt,
            &signal::CANCEL,
            &mut approver,
        ) {
            eprintln!("agent686: {error}");
            std::process::exit(1);
        }
        return;
    }

    let mut editor = Editor::new();
    let interactive = editor.is_interactive();
    if interactive {
        eprintln!(
            "agent686 · {} · session {}{}",
            cfg.model,
            cfg.session,
            if cfg.yolo { " · yolo" } else { "" }
        );
        eprintln!("type a prompt · up/down history · ctrl-d exit · /help");
    }

    let stdin = std::io::stdin();
    let mut line = String::new();
    loop {
        let mut text = match editor.read("> ") {
            Ok(Some(text)) => text,
            Ok(None) => break,
            Err(error) => {
                eprintln!("agent686: input: {error}");
                break;
            }
        };
        if text.trim().is_empty() {
            continue;
        }

        match text.as_str() {
            "/exit" | "/quit" => break,
            "/help" => {
                print!("{HELP}");
                continue;
            }
            "/paste" => {
                let mut buffer = String::new();
                loop {
                    if interactive {
                        print!("… ");
                        let _ = std::io::stdout().flush();
                    }
                    line.clear();
                    if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 {
                        break;
                    }
                    let piece = line.trim_end_matches(['\n', '\r']);
                    if piece == "." {
                        break;
                    }
                    buffer.push_str(piece);
                    buffer.push('\n');
                }
                text = buffer.trim_end().to_string();
                if text.is_empty() {
                    continue;
                }
            }
            _ => {}
        }

        warn_if_changed(&watched, &mut warned);
        if let Err(error) = agent::run_turn(
            &cfg,
            &mut session,
            &mut history,
            &text,
            &signal::CANCEL,
            &mut approver,
        ) {
            eprintln!("agent686: {error}");
        }
    }
}

fn open_session(
    cfg: &Config,
    resume: Option<String>,
    continue_last: bool,
) -> Result<(Session, Vec<Value>), String> {
    let id = match resume {
        Some(id) => Some(id),
        None if continue_last => Some(
            session::latest()?
                .ok_or_else(|| "no sessions to continue; run without --continue".to_string())?,
        ),
        None => None,
    };

    match id {
        Some(id) if !session::exists(&id) => {
            let system = agent::system_prompt();
            let session = Session::create_as(id, &cfg.model, &system)?;
            eprintln!(
                "agent686: new session {} ({})",
                session.id,
                session.path().display()
            );
            Ok((session, agent::new_history(system)))
        }
        Some(id) => {
            let (session, system, messages) = Session::open(&id)?;
            if !session.model.is_empty() && session.model != cfg.model {
                eprintln!(
                    "agent686: session used {}; continuing with {}",
                    session.model, cfg.model
                );
            }
            // The system message frozen at session start is reused verbatim, so
            // the request prefix stays byte-identical across restarts.
            let system = if system.is_null() {
                agent::system_prompt()
            } else {
                system
            };
            let mut history = agent::new_history(system);
            let count = messages.len();
            history.extend(messages);
            eprintln!("agent686: resumed {} ({count} messages)", session.id);
            Ok((session, history))
        }
        None => {
            let system = agent::system_prompt();
            let session = Session::create(&cfg.model, &system)?;
            eprintln!(
                "agent686: new session {} ({})",
                session.id,
                session.path().display()
            );
            Ok((session, agent::new_history(system)))
        }
    }
}

fn warn_if_changed(watched: &Option<(PathBuf, SystemTime)>, warned: &mut bool) {
    let (path, seen) = match watched {
        Some(watched) => watched,
        None => return,
    };
    if *warned {
        return;
    }
    if let Ok(modified) = std::fs::metadata(path).and_then(|m| m.modified()) {
        if modified != *seen {
            eprintln!(
                "agent686: {} changed; start a new session to pick it up",
                path.display()
            );
            *warned = true;
        }
    }
}

fn print_sessions() {
    let sessions = match session::list() {
        Ok(sessions) => sessions,
        Err(error) => {
            eprintln!("agent686: {error}");
            return;
        }
    };
    if sessions.is_empty() {
        println!("no sessions");
        return;
    }
    println!("{:<34} {:<22} {:>5}  {:>4}", "SESSION", "MODEL", "MSGS", "AGE");
    for info in sessions {
        println!(
            "{:<34} {:<22} {:>5}  {:>4}",
            info.id,
            info.model,
            info.messages,
            ago(info.modified)
        );
    }
}

fn ago(modified: SystemTime) -> String {
    let seconds = SystemTime::now()
        .duration_since(modified)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    match seconds {
        0..=59 => format!("{seconds}s"),
        60..=3599 => format!("{}m", seconds / 60),
        3600..=86_399 => format!("{}h", seconds / 3600),
        _ => format!("{}d", seconds / 86_400),
    }
}