axiopera 0.3.2

Orchestrate coding agents (Claude Code, Codex, Grok Build) as sub-agents of each other
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Agent adapters: one native process per running turn, driven over its stdio protocol.

mod claude;
mod codex;
pub mod codex_remote;
mod grok;
pub mod models;
mod rpc;

use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::{Arc, Mutex, OnceLock, Weak};

use anyhow::{Context, Result, bail};
use serde_json::Value;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWriteExt, BufReader, Lines};
use tokio::process::{Child, ChildStdin, ChildStdout};
use tokio::sync::{mpsc, oneshot};

use crate::ipc::{Agent, Tier};
use crate::platform;

/// What adapters report to the task actor.
#[derive(Debug)]
pub enum AgentEvent {
    Session {
        id: String,
        file: Option<PathBuf>,
    },
    Tool {
        id: Option<String>,
        name: String,
        detail: String,
    },
    ToolUpdated {
        id: String,
        name: String,
        detail: String,
    },
    FileChanged(String),
    /// A message the agent wrote, once it is complete. The last one of a turn is also its
    /// result.
    Said(String),
    /// A request we answered with a refusal without asking anyone.
    Blocked(String),
    /// A request that needs someone's decision.
    Approval(Approval),
    /// The backend put this input into the turn's conversation.
    InputRead(u64),
    /// The agent started a turn by itself, e.g. when background work ended.
    TurnStarted,
    /// A problem in the agent's own setup that its parent should hear of.
    Notice(String),
    TurnEnded {
        ok: bool,
        result: String,
        error: Option<String>,
        usage: Option<Value>,
    },
    Exited(String),
}

pub type Events = mpsc::UnboundedSender<AgentEvent>;

#[derive(Debug)]
pub struct Approval {
    /// One line on what the agent wants to do.
    pub summary: String,
    /// Everything the request says, for whoever decides: a summary can hide what matters.
    pub detail: String,
    pub reply: oneshot::Sender<Decision>,
}

#[derive(Debug)]
pub enum Decision {
    Approve,
    /// With the reason the agent is told.
    Deny(String),
}

/// Hand a request to the daemon and wait for its decision; a dropped request is a refusal.
/// Adapters await this off their message loop, which must keep running meanwhile.
fn ask_approval(
    events: &Events,
    summary: String,
    detail: String,
) -> impl Future<Output = Decision> + use<> {
    let (reply, rx) = oneshot::channel();
    let _ = events.send(AgentEvent::Approval(Approval {
        summary,
        detail,
        reply,
    }));
    async move {
        rx.await.unwrap_or_else(|_| {
            Decision::Deny("Refused by axiopera: the approval channel closed.".into())
        })
    }
}

/// Environment an agent needs on top of its caller's.
pub fn extra_env(agent: Agent) -> &'static [(&'static str, &'static str)] {
    match agent {
        Agent::Grok => &grok::ENV,
        _ => &[],
    }
}

pub enum Steer {
    Accepted,
    NoActiveTurn,
}

pub struct StartSpec {
    pub task_id: String,
    pub agent: Agent,
    pub tier: Tier,
    pub cwd: PathBuf,
    pub model: Option<String>,
    pub effort: Option<String>,
    /// Final environment for the agent process.
    pub env: Vec<(String, String)>,
    /// Native session to resume.
    pub resume: Option<String>,
    pub trace: Option<PathBuf>,
}

#[derive(Default)]
struct Inputs(VecDeque<(Option<u64>, String)>);

impl Inputs {
    fn push(&mut self, id: Option<u64>, text: &str) {
        self.0.push_back((id, text.to_string()));
    }

    fn read(&mut self, text: &str, events: &Events) {
        if let Some(i) = self
            .0
            .iter()
            .position(|(_, sent)| sent.trim_end() == text.trim_end())
            && let Some((Some(id), _)) = self.0.remove(i)
        {
            let _ = events.send(AgentEvent::InputRead(id));
        }
    }
}

fn content_text(content: &Value) -> String {
    content.as_str().map(str::to_string).unwrap_or_else(|| {
        content
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|b| b["text"].as_str())
            .collect::<Vec<_>>()
            .join("\n")
    })
}

/// Instructions every sub-agent gets on top of its own system prompt.
fn protocol_text(spec: &StartSpec) -> String {
    let ask = if spec.agent == Agent::Codex {
        "call the `ask` tool of the axiopera MCP server"
    } else {
        "run `axiopera ask \"<question>\"`"
    };
    format!(
        "You are an axiopera sub-agent working for a parent. The parent receives your final \
         message from each turn. Include the outcome and the context it needs to act. Long \
         results may first arrive as a tail excerpt with a path to the full text.\n\
         If you need a decision or information that only your parent has, {ask} and keep \
         working on what does not depend on the answer; do not wait or poll for it. Answers \
         arrive in this task's main session, during its current turn or in a new one. If \
         blocked on the answer, end your turn and state the dependency."
    )
}

/// A plain `axiopera ...` invocation with nothing else for a shell to run. Sub-agents may always
/// talk to axiopera; anything chained to it goes through normal approval. Quote-aware for bash
/// and PowerShell, the shells the agents run, and conservative where they disagree: the scan
/// must never think it is inside quotes when the shell is not.
pub fn is_axiopera_command(command: &str) -> bool {
    let Some(rest) = command.trim().strip_prefix("axiopera") else {
        return false;
    };
    if !(rest.is_empty() || rest.starts_with(' ')) {
        return false;
    }
    // PowerShell also takes typographic quotes as string delimiters.
    if rest.contains(['‘', '’', '‚', '‛', '“', '”', '„', '‟']) {
        return false;
    }
    // PowerShell's stop-parsing token, recognised after quote removal (`--'%'`) and with any
    // dash character, turns the quotes after it into plain characters.
    let unquoted = rest
        .replace(['\'', '"'], "")
        .replace(['\u{2013}', '\u{2014}', '\u{2015}'], "-");
    if unquoted.contains("--%") {
        return false;
    }
    let mut quote = None;
    for c in rest.chars() {
        match (quote, c) {
            (Some(q), c) if c == q => quote = None,
            (Some('\''), _) => {}
            // Expansion inside double quotes, and bash's `\"`, which does not end the string.
            (Some(_), '$' | '`' | '\\') => return false,
            (Some(_), _) => {}
            (None, '\'' | '"') => quote = Some(c),
            // Separators, redirection, substitution, grouping, and the escapes that could hide a
            // quote from this scan (bash `\`, cmd `^`, PowerShell backtick).
            (
                None,
                ';' | '&' | '|' | '<' | '>' | '(' | ')' | '{' | '}' | '$' | '`' | '\\' | '^' | '%'
                | '\n' | '\r',
            ) => return false,
            (None, _) => {}
        }
    }
    quote.is_none() && !rest.contains(['\n', '\r'])
}

pub const REFUSED: &str = "Refused by axiopera: read tier does not allow this action.";

pub enum Backend {
    Claude(claude::Claude),
    Codex(codex::Codex),
    Grok(grok::Grok),
}

impl Backend {
    /// Start the native process and open (or resume) its session. Turns start with `turn`.
    pub async fn start(spec: &StartSpec, exe: &Path, events: Events) -> Result<Backend> {
        Ok(match spec.agent {
            Agent::Claude => Backend::Claude(claude::Claude::start(spec, exe, events).await?),
            Agent::Codex => Backend::Codex(codex::Codex::start(spec, exe, events).await?),
            Agent::Grok => Backend::Grok(grok::Grok::start(spec, exe, events).await?),
        })
    }

    pub async fn turn(&mut self, text: &str) -> Result<()> {
        match self {
            Backend::Claude(a) => a.turn(text).await,
            Backend::Codex(a) => a.turn(text).await,
            Backend::Grok(a) => a.turn(text).await,
        }
    }

    pub async fn steer(&mut self, text: &str, id: Option<u64>) -> Result<Steer> {
        match self {
            Backend::Claude(a) => a.steer(text, id).await,
            Backend::Codex(a) => a.steer(text, id).await,
            Backend::Grok(a) => a.steer(text).await,
        }
    }

    pub async fn interrupt(&mut self) -> Result<()> {
        match self {
            Backend::Claude(a) => a.interrupt().await,
            Backend::Codex(a) => a.interrupt().await,
            Backend::Grok(a) => a.interrupt().await,
        }
    }

    /// Whether a turn is still running from the agent's point of view.
    pub fn busy(&self) -> bool {
        match self {
            Backend::Claude(a) => a.busy(),
            Backend::Codex(a) => a.busy(),
            Backend::Grok(a) => a.busy(),
        }
    }

    /// Whether a turn is running right now; `busy` also counts the agent's background work.
    pub fn in_turn(&self) -> bool {
        match self {
            Backend::Claude(a) => a.in_turn(),
            Backend::Codex(a) => a.busy(),
            Backend::Grok(a) => a.in_turn(),
        }
    }

    fn proc(&mut self) -> &mut Proc {
        match self {
            Backend::Claude(a) => &mut a.proc,
            Backend::Codex(a) => &mut a.proc,
            Backend::Grok(a) => &mut a.proc,
        }
    }

    pub fn kill(&mut self) {
        self.proc().job.kill();
    }

    /// Let the agent exit on its own so its session file is complete, then clear the job.
    pub async fn shutdown(&mut self) {
        let p = self.proc();
        p.stdin.close().await;
        let _ = tokio::time::timeout(std::time::Duration::from_secs(5), p.child.wait()).await;
        p.job.kill();
        let _ = p.child.wait().await;
    }

    pub fn stderr_tail(&mut self) -> String {
        self.proc()
            .stderr
            .lock()
            .unwrap()
            .iter()
            .cloned()
            .collect::<Vec<_>>()
            .join("\n")
    }
}

// ---- process plumbing ----

#[derive(Clone, Default)]
pub struct Trace(Option<Arc<Mutex<TraceFile>>>);

struct TraceFile {
    file: std::fs::File,
    path: PathBuf,
}

impl Trace {
    fn open(path: Option<&Path>) -> std::io::Result<Self> {
        let Some(path) = path else {
            return Ok(Self::default());
        };
        // A previous process may still be draining stdout when its successor starts.
        static OPEN: OnceLock<Mutex<HashMap<PathBuf, Weak<Mutex<TraceFile>>>>> = OnceLock::new();
        let mut open = OPEN.get_or_init(Mutex::default).lock().unwrap();
        open.retain(|_, file| file.strong_count() > 0);
        if let Some(file) = open.get(path).and_then(Weak::upgrade) {
            return Ok(Self(Some(file)));
        }
        let file = Arc::new(Mutex::new(TraceFile {
            file: std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)?,
            path: path.to_owned(),
        }));
        open.insert(path.to_owned(), Arc::downgrade(&file));
        Ok(Self(Some(file)))
    }

    pub fn line(&self, direction: &str, line: &str) {
        if let Some(file) = &self.0 {
            let mut guard = file.lock().unwrap();
            let TraceFile { file, path } = &mut *guard;
            let _ = crate::diagnostics::append(
                file,
                path,
                &format!("{direction} {line}\n"),
                crate::diagnostics::PROTOCOL_BYTES,
            );
        }
    }
}

#[derive(Clone)]
pub struct Writer {
    stdin: Arc<tokio::sync::Mutex<Option<ChildStdin>>>,
    pub trace: Trace,
}

impl Writer {
    pub async fn send(&self, v: &Value) -> std::io::Result<()> {
        let mut line = serde_json::to_vec(v)?;
        line.push(b'\n');
        let mut guard = self.stdin.lock().await;
        let w = guard
            .as_mut()
            .ok_or_else(|| std::io::Error::other("stdin closed"))?;
        w.write_all(&line).await?;
        self.trace.line("send", &v.to_string());
        w.flush().await
    }

    /// EOF on stdin asks every supported agent to finish up and exit.
    pub async fn close(&self) {
        self.stdin.lock().await.take();
    }
}

pub fn lines<R: AsyncRead>(r: R) -> Lines<BufReader<R>> {
    BufReader::with_capacity(1 << 16, r).lines()
}

pub struct Proc {
    pub job: platform::Job,
    pub child: Child,
    pub stdin: Writer,
    /// Last lines of stderr, each cut to a few hundred characters, for error reports. Never
    /// logged.
    pub stderr: Arc<Mutex<VecDeque<String>>>,
}

impl Proc {
    pub fn spawn(exe: &Path, args: &[String], spec: &StartSpec) -> Result<(Proc, ChildStdout)> {
        Self::spawn_with(exe, args, &spec.cwd, &spec.env, spec.trace.as_deref())
    }

    pub fn spawn_with(
        exe: &Path,
        args: &[String],
        cwd: &Path,
        env: &[(String, String)],
        trace: Option<&Path>,
    ) -> Result<(Proc, ChildStdout)> {
        let mut cmd = tokio::process::Command::new(exe);
        cmd.args(args)
            .current_dir(cwd)
            .env_clear()
            .envs(env.iter().map(|(k, v)| (k, v)))
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true);
        let job = platform::Job::new()?;
        let mut child = job
            .spawn(&mut cmd)
            .with_context(|| format!("starting {}", exe.display()))?;
        let stdin = Writer {
            stdin: Arc::new(tokio::sync::Mutex::new(child.stdin.take())),
            trace: Trace::open(trace)?,
        };
        let stdout = child.stdout.take().unwrap();
        let stderr: Arc<Mutex<VecDeque<String>>> = Arc::default();
        let tail = stderr.clone();
        let err = child.stderr.take().unwrap();
        tokio::spawn(async move {
            let mut lines = lines(err);
            while let Ok(Some(l)) = lines.next_line().await {
                let mut t = tail.lock().unwrap();
                if t.len() == 20 {
                    t.pop_front();
                }
                // Node prints the source line of an uncaught error, a whole bundle when minified.
                t.push_back(clip(&l, 300));
            }
        });
        Ok((
            Proc {
                job,
                child,
                stdin,
                stderr,
            },
            stdout,
        ))
    }
}

// ---- finding the real executables ----

/// The native executable for an agent. npm installs put a script shim on PATH; on Windows we
/// need the real `.exe` behind it so the job owns the actual agent process.
pub fn resolve_exe(
    agent: Agent,
    configured: Option<&Path>,
    env: &[(String, String)],
) -> Result<PathBuf> {
    if let Some(exe) = configured {
        if exe.is_file() {
            return Ok(exe.to_path_buf());
        }
        bail!("{} (set in config.toml) is not a file", exe.display());
    }
    let var = |name: &str| {
        env.iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.clone())
    };
    let name = match agent {
        Agent::Claude => "claude",
        Agent::Codex => "codex",
        Agent::Grok => "grok",
    };
    if agent == Agent::Grok {
        let home = var("GROK_HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|| home_dir().join(".grok"));
        let exe = home
            .join("bin")
            .join(if cfg!(windows) { "grok.exe" } else { "grok" });
        if exe.is_file() {
            return Ok(exe);
        }
    }
    let path = var("PATH").unwrap_or_default();
    for dir in std::env::split_paths(&path) {
        if cfg!(windows) {
            let exe = dir.join(format!("{name}.exe"));
            if exe.is_file() {
                return Ok(exe);
            }
            if dir.join(format!("{name}.cmd")).is_file()
                && let Some(exe) = npm_native(&dir, agent)
            {
                return Ok(exe);
            }
        } else if dir.join(name).is_file() {
            return Ok(dir.join(name));
        }
    }
    bail!("cannot find the {name} executable on the caller's PATH")
}

fn npm_native(dir: &Path, agent: Agent) -> Option<PathBuf> {
    let modules = dir.join("node_modules");
    let (arch, triple) = if cfg!(target_arch = "aarch64") {
        ("arm64", "aarch64-pc-windows-msvc")
    } else {
        ("x64", "x86_64-pc-windows-msvc")
    };
    let exe = match agent {
        Agent::Claude => modules.join("@anthropic-ai/claude-code/bin/claude.exe"),
        Agent::Codex => modules.join(format!(
            "@openai/codex/node_modules/@openai/codex-win32-{arch}/vendor/{triple}/bin/codex.exe"
        )),
        Agent::Grok => return None,
    };
    exe.is_file().then_some(exe)
}

pub fn home_dir() -> PathBuf {
    PathBuf::from(
        std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).unwrap_or_default(),
    )
}

/// Every argument of a tool call in full, one per line; multi-line and long values start on a
/// line of their own.
pub fn arguments(input: &Value) -> String {
    let Some(fields) = input.as_object() else {
        return serde_json::to_string_pretty(input).unwrap_or_default();
    };
    fields
        .iter()
        .map(|(k, v)| match v {
            Value::String(s) if s.contains('\n') || s.chars().count() > 200 => {
                format!("{k}:\n{s}")
            }
            Value::String(s) => format!("{k}: {s}"),
            other => format!("{k}: {other}"),
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// One line for summaries: line breaks shown as ↵, cut to `max` characters with a count of
/// what was left out.
pub fn clip(s: &str, max: usize) -> String {
    let mut kept = String::new();
    let mut total = 0;
    for (i, line) in s.trim().lines().enumerate() {
        let separator = if i == 0 { "" } else { " ↵ " };
        for c in separator.chars().chain(line.chars()) {
            if total < max {
                kept.push(c);
            }
            total += 1;
        }
    }
    if total > max {
        kept.push_str(&format!("…(+{} chars)", total - max));
    }
    kept
}

#[cfg(test)]
mod tests {
    use super::clip;
    use super::is_axiopera_command as ok;

    #[test]
    fn overlapping_protocol_readers_share_the_rotation_lock() {
        let dir = std::env::temp_dir().join(format!("axiopera-trace-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("protocol.log");
        let old = super::Trace::open(Some(&path)).unwrap();
        let new = super::Trace::open(Some(&path)).unwrap();
        assert!(std::sync::Arc::ptr_eq(
            old.0.as_ref().unwrap(),
            new.0.as_ref().unwrap()
        ));
        old.line("out", "last old record");
        new.line("in", "first new record");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "out last old record\nin first new record\n"
        );
        drop(old);
        drop(new);
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn clipped_lines_keep_every_line_and_count_the_rest() {
        assert_eq!(clip("cargo test", 200), "cargo test");
        assert_eq!(
            clip("cd crates\r\ncargo test\n", 200),
            "cd crates ↵ cargo test"
        );
        assert_eq!(clip("审查意见很长", 2), "审查…(+4 chars)");
        assert_eq!(clip(" \r\n  ", 0), "");
        assert_eq!(clip("a\r\nb", 3), "a ↵…(+2 chars)");
        assert_eq!(clip(&"中\n".repeat(100_000), 1), "中…(+399996 chars)");
    }

    #[test]
    fn plain_axiopera_commands() {
        assert!(ok("axiopera answers"));
        assert!(ok(r#"axiopera ask "Which port (8080 or 3000)?""#));
        assert!(ok("axiopera ask 'it''s fine; really'"));
        assert!(ok(r#"  axiopera reply q7k2m "use 8080 & restart""#));
        assert!(ok(r#"axiopera ask "Is 30% faster enough?""#));
    }

    #[test]
    fn anything_else_needs_approval() {
        assert!(!ok("axiopera-evil ask x"));
        assert!(!ok("rm -rf / ; axiopera answers"));
        assert!(!ok(r#"axiopera ask "x"; rm -rf /"#));
        assert!(!ok("axiopera ask x && calc"));
        assert!(!ok("axiopera ask x | calc"));
        assert!(!ok(r#"axiopera ask "$(whoami)""#));
        assert!(!ok(r#"axiopera ask "`whoami`""#));
        assert!(!ok(r#"axiopera ask \"; calc \""#));
        assert!(!ok(r#"axiopera ask ^"& calc ^""#));
        assert!(!ok(r#"axiopera ask "unterminated"#));
        assert!(!ok("axiopera ask x\ncalc"));
        assert!(!ok("axiopera ask x > out.txt"));
        assert!(!ok(r#"axiopera ask "a\"b"; echo bypass #""#));
        assert!(!ok("axiopera ask \"a“; calc; echo “b\""));
        assert!(!ok("axiopera ask 'a‘; calc; echo ‘b'"));
        assert!(!ok("axiopera --'%' ask x' | calc #'"));
        assert!(!ok(r#"axiopera ask "--%" x"#));
        assert!(!ok("axiopera –-'%' ask x' | calc #'"));
    }
}