argonauts-app 0.1.0

Argonauts Code's app controller and run host: the conversation, routing, choosing Captain or crew, and the run host each run has.
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! `!` commands. Each runs as you where the conversation works, with your shell and outside the
//! sandbox, since you typed it: the repo folder, or the run's worktree of an agent's session the
//! conversation carries on. Its output shows as it prints, and the command and its output wait
//! for the main agent's next turn; running one never starts a turn by itself. One runs at a time.

use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;

use argonauts_core::NoteLevel;
use argonauts_core::app::{AppEvent, ShellEvent};
use argonauts_core::events::session::{InputPart, InputPartKind};
use argonauts_core::sanitize::sanitize_for_terminal;
use nix::sys::signal::{Signal, killpg};
use nix::unistd::Pid;
use tokio::io::{AsyncRead, AsyncReadExt};
use tokio::process::{Child, Command};
use tokio::sync::mpsc::UnboundedSender;

use super::{Ctx, Internal};

/// How much of one command's output the main agent gets, as Claude Code caps its own: the start and
/// the end, with the middle cut.
const KEPT_BYTES: usize = 30_000;

/// What the commands waiting for your next message hold together, a few commands' worth, so
/// a long session of them can't swamp the prompt. The oldest go first.
const HELD_BYTES: usize = 3 * KEPT_BYTES;

/// A job the command left in the background can hold its pipes open after it ends. Output
/// still on the way gets this long.
const DRAIN: Duration = Duration::from_millis(300);

pub(crate) const STILL_RUNNING: &str = "A command is still running. Ctrl+C stops it.";

#[derive(Default)]
pub(crate) struct ShellState {
    last_id: u32,
    running: Option<Running>,
}

struct Running {
    id: u32,
    command: String,
    /// Where it runs, when that isn't the repo folder.
    folder: Option<PathBuf>,
    output: Kept,
    /// The shell is first in a session and process group of its own, so a stop reaches
    /// everything it started.
    group: Option<Pid>,
    stopped: bool,
}

/// From a command's task to the loop.
#[derive(Debug)]
pub(crate) enum ShellUpdate {
    Output { id: u32, text: String },
    Done { id: u32, exit_code: Option<i32> },
}

/// A finished command, kept for the main agent's next turn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ShellRan {
    /// Commands run one at a time and are numbered as they start, so a higher id ended later.
    pub id: u32,
    pub command: String,
    /// Where it ran, when that wasn't the repo folder.
    pub folder: Option<PathBuf>,
    pub output: String,
    pub exit_code: Option<i32>,
    pub stopped: bool,
}

/// Runs `command` in `folder`, where the conversation works.
pub(crate) fn run(ctx: &mut Ctx, shell: &mut ShellState, command: String, folder: &Path) {
    let command = command.trim_end().to_owned();
    if command.trim().is_empty() {
        return;
    }
    if shell.running.is_some() {
        ctx.notice(NoteLevel::Info, STILL_RUNNING);
        return;
    }
    shell.last_id += 1;
    let id = shell.last_id;
    ctx.send(AppEvent::Shell {
        event: ShellEvent::Started {
            id,
            command: command.clone(),
        },
    });
    let program = user_shell();
    let mut child = match spawn(&program, &command, folder) {
        Ok(child) => child,
        Err(err) => {
            let text = format!("Couldn't start {}: {err}\n", program.display());
            ctx.send(AppEvent::Shell {
                event: ShellEvent::Output { id, text },
            });
            ctx.send(AppEvent::Shell {
                event: ShellEvent::Finished {
                    id,
                    exit_code: None,
                    stopped: false,
                },
            });
            return;
        }
    };
    let group = child
        .id()
        .and_then(|pid| i32::try_from(pid).ok())
        .map(Pid::from_raw);
    let readers = [
        child
            .stdout
            .take()
            .map(|pipe| forward(pipe, id, &ctx.internal)),
        child
            .stderr
            .take()
            .map(|pipe| forward(pipe, id, &ctx.internal)),
    ];
    tokio::spawn(watch(child, readers, id, ctx.internal.clone()));
    shell.running = Some(Running {
        id,
        command,
        folder: (folder != ctx.env.repo_root).then(|| folder.to_owned()),
        output: Kept::default(),
        group,
        stopped: false,
    });
}

/// Ctrl+C: an interrupt, as a terminal sends one. A command that ignores it gets killed by the
/// next Ctrl+C.
pub(crate) fn stop(shell: &mut ShellState) {
    let Some(running) = shell.running.as_mut() else {
        return;
    };
    let signal = if running.stopped {
        Signal::SIGKILL
    } else {
        Signal::SIGINT
    };
    running.stopped = true;
    if let Some(group) = running.group {
        let _ = killpg(group, signal);
    }
}

/// The app is closing, so nothing it started outlives it.
pub(crate) fn close(shell: &mut ShellState) {
    if let Some(group) = shell.running.take().and_then(|running| running.group) {
        let _ = killpg(group, Signal::SIGKILL);
    }
}

/// Shows the output, and hands back the command once it ends.
pub(crate) fn on_update(
    ctx: &mut Ctx,
    shell: &mut ShellState,
    update: ShellUpdate,
) -> Option<ShellRan> {
    match update {
        ShellUpdate::Output { id, text } => {
            let running = shell.running.as_mut().filter(|running| running.id == id)?;
            running.output.push(&text);
            ctx.send(AppEvent::Shell {
                event: ShellEvent::Output { id, text },
            });
            None
        }
        ShellUpdate::Done { id, exit_code } => {
            let running = shell.running.take_if(|running| running.id == id)?;
            ctx.send(AppEvent::Shell {
                event: ShellEvent::Finished {
                    id,
                    exit_code,
                    stopped: running.stopped,
                },
            });
            Some(ShellRan {
                id,
                command: running.command,
                folder: running.folder,
                output: running.output.text(),
                exit_code,
                stopped: running.stopped,
            })
        }
    }
}

/// Keeps `ran` for your next message, past [`HELD_BYTES`] without the oldest commands.
pub(crate) fn hold(held: &mut Vec<ShellRan>, ran: ShellRan) {
    held.push(ran);
    let size = |ran: &ShellRan| ran.command.len() + ran.output.len();
    let mut total: usize = held.iter().map(size).sum();
    while held.len() > 1 && total > HELD_BYTES {
        total -= size(&held.remove(0));
    }
}

/// The commands you ran since the main agent's last turn, oldest first, as one part of its prompt.
pub(crate) fn context_part(ran: &[ShellRan]) -> Option<InputPart> {
    let text = context_text(ran)?;
    Some(super::turn::part(
        InputPartKind::Message,
        "shell commands",
        text,
    ))
}

/// The commands and their output in words, for a message to the main agent or to a run, saying
/// where they ran. Output is cleaned of terminal escapes, which mean nothing to a model and
/// could reach a terminal that shows the prompt.
pub(crate) fn context_text(ran: &[ShellRan]) -> Option<String> {
    let first = ran.first()?;
    let one_folder = ran.iter().all(|command| command.folder == first.folder);
    let place = match (&first.folder, one_folder) {
        (_, false) => "each in the folder named after it".to_owned(),
        (None, true) => "in the repo folder".to_owned(),
        (Some(folder), true) => format!("in {}", sanitize_for_terminal(&folder.to_string_lossy())),
    };
    let mut text = format!(
        "Before this message I ran these commands myself, {place}. Their output is here as \
         context.\n"
    );
    for command in ran {
        text.push_str(&format!(
            "\n$ {}\n",
            sanitize_for_terminal(&command.command)
        ));
        if !one_folder {
            let folder = command.folder.as_ref().map_or_else(
                || "the repo folder".to_owned(),
                |folder| sanitize_for_terminal(&folder.to_string_lossy()),
            );
            text.push_str(&format!("(in {folder})\n"));
        }
        let output = sanitize_for_terminal(&settled(&command.output));
        if !output.is_empty() {
            text.push_str(&output);
            text.push('\n');
        }
        let end = match (command.stopped, command.exit_code) {
            (true, _) => "(stopped with Ctrl+C)".to_owned(),
            (false, Some(0)) => String::new(),
            (false, Some(code)) => format!("(exit code {code})"),
            (false, None) => "(ended by a signal)".to_owned(),
        };
        if !end.is_empty() {
            text.push_str(&end);
            text.push('\n');
        }
    }
    Some(text)
}

/// Your shell, as your terminal would start it, or `sh` without one.
fn user_shell() -> PathBuf {
    std::env::var_os("SHELL")
        .filter(|shell| !shell.is_empty())
        .map_or_else(|| PathBuf::from("/bin/sh"), PathBuf::from)
}

fn spawn(program: &Path, command: &str, folder: &Path) -> std::io::Result<Child> {
    let mut shell = Command::new(program);
    shell
        .arg("-c")
        .arg(command)
        .current_dir(folder)
        // Nothing can type into it, so a command that waits for input ends instead of hanging.
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);
    // SAFETY: setsid is async-signal-safe and touches no memory the parent shares. A session
    // of its own leaves the command no terminal, so one that asks there, such as sudo for a
    // password, fails at once rather than stopping in the background for good. Its process
    // group is the shell's pid, which a stop signals.
    unsafe {
        shell.pre_exec(|| {
            nix::unistd::setsid()
                .map(drop)
                .map_err(std::io::Error::from)
        });
    }
    shell.spawn()
}

async fn watch(
    mut child: Child,
    readers: [Option<tokio::task::JoinHandle<()>>; 2],
    id: u32,
    internal: UnboundedSender<Internal>,
) {
    let exit_code = child.wait().await.ok().and_then(|status| status.code());
    for reader in readers.into_iter().flatten() {
        let abort = reader.abort_handle();
        if tokio::time::timeout(DRAIN, reader).await.is_err() {
            abort.abort();
        }
    }
    let _ = internal.send(Internal::Shell(ShellUpdate::Done { id, exit_code }));
}

/// Standard output and error go out as one stream, in the order they arrive, as a terminal
/// shows them.
fn forward<R>(
    mut pipe: R,
    id: u32,
    internal: &UnboundedSender<Internal>,
) -> tokio::task::JoinHandle<()>
where
    R: AsyncRead + Unpin + Send + 'static,
{
    let internal = internal.clone();
    tokio::spawn(async move {
        let mut buffer = vec![0; 8192];
        let mut pending = Vec::new();
        loop {
            let read = match pipe.read(&mut buffer).await {
                Ok(0) | Err(_) => break,
                Ok(read) => read,
            };
            pending.extend_from_slice(&buffer[..read]);
            let text = whole_chars(&mut pending);
            if text.is_empty() {
                continue;
            }
            if internal
                .send(Internal::Shell(ShellUpdate::Output { id, text }))
                .is_err()
            {
                return;
            }
        }
        if !pending.is_empty() {
            let text = String::from_utf8_lossy(&pending).into_owned();
            let _ = internal.send(Internal::Shell(ShellUpdate::Output { id, text }));
        }
    })
}

/// The text at the front of `bytes`, leaving a character a read cut in two for the next read.
fn whole_chars(bytes: &mut Vec<u8>) -> String {
    let end = match std::str::from_utf8(bytes) {
        Err(err) if err.error_len().is_none() => err.valid_up_to(),
        _ => bytes.len(),
    };
    let text = String::from_utf8_lossy(&bytes[..end]).into_owned();
    bytes.drain(..end);
    text
}

/// Each line as a terminal leaves it: a carriage return starts the line over, as a progress
/// bar does.
fn settled(output: &str) -> String {
    output
        .replace("\r\n", "\n")
        .trim_end_matches('\n')
        .split('\n')
        .map(|line| {
            line.trim_end_matches('\r')
                .rsplit('\r')
                .next()
                .unwrap_or("")
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// The start and the end of a command's output, with the middle cut once it passes
/// [`KEPT_BYTES`].
#[derive(Debug, Default)]
struct Kept {
    head: String,
    tail: String,
    cut_lines: usize,
    cut: bool,
}

impl Kept {
    fn push(&mut self, text: &str) {
        let half = KEPT_BYTES / 2;
        let room = floor_boundary(text, half.saturating_sub(self.head.len()));
        self.head.push_str(&text[..room]);
        self.tail.push_str(&text[room..]);
        // Trimmed in batches, so a chatty command isn't copied once per read.
        if self.tail.len() > 2 * half {
            self.trim_tail(half);
        }
    }

    fn trim_tail(&mut self, keep: usize) {
        if self.tail.len() <= keep {
            return;
        }
        let from = ceil_boundary(&self.tail, self.tail.len() - keep);
        self.cut_lines += self.tail[..from].matches('\n').count();
        self.cut = true;
        self.tail.drain(..from);
    }

    fn text(mut self) -> String {
        self.trim_tail(KEPT_BYTES / 2);
        if !self.cut {
            return self.head + &self.tail;
        }
        let lines = if self.cut_lines == 1 { "line" } else { "lines" };
        format!(
            "{}\n[… {} {lines} cut …]\n{}",
            self.head.trim_end_matches('\n'),
            self.cut_lines,
            self.tail
        )
    }
}

fn floor_boundary(text: &str, at: usize) -> usize {
    let mut at = at.min(text.len());
    while !text.is_char_boundary(at) {
        at -= 1;
    }
    at
}

fn ceil_boundary(text: &str, at: usize) -> usize {
    let mut at = at.min(text.len());
    while !text.is_char_boundary(at) {
        at += 1;
    }
    at
}

#[cfg(test)]
mod tests;