axiopera 0.1.0

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
//! One actor per task with a live agent process: drives turns, steers, and lets go of the
//! process as soon as a turn ends with nothing else to do.

use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;

use anyhow::{Result, anyhow};
use serde_json::json;
use tokio::sync::{mpsc, oneshot};
use tokio::time::Instant;

use super::{Daemon, agent_env};
use crate::agent::{self, AgentEvent, Backend, StartSpec, Steer};
use crate::ipc::Agent;
use crate::store::{Fingerprint, Status};

#[derive(Debug)]
pub enum Cmd {
    /// A message from the parent: steer the running turn, or start the next one.
    Input(Input),
    /// A note from a sibling: steer the running turn, or keep it for the next one.
    Mail(String),
    Cancel(Cancellation),
    /// The daemon is going away; the task can be resumed later.
    Abort,
}

#[derive(Debug, serde::Serialize)]
pub struct Cancellation {
    pub reason: String,
    pub by: String,
}

#[derive(Debug)]
pub struct Input {
    pub text: String,
    pub reply: oneshot::Sender<&'static str>,
}

impl Input {
    fn queued(self) -> String {
        let _ = self.reply.send("queued for a new turn");
        self.text
    }
}

#[derive(Default)]
struct InputTracking {
    pending: BTreeMap<u64, String>,
    serial: u64,
    grok_unconfirmed: usize,
}

impl InputTracking {
    async fn steer(
        &mut self,
        d: &Daemon,
        id: &str,
        agent: Agent,
        backend: &mut Backend,
        input: &str,
    ) -> Result<Option<&'static str>> {
        let queued = !backend.in_turn();
        self.serial += 1;
        if matches!(
            backend.steer(input, Some(self.serial)).await?,
            Steer::NoActiveTurn
        ) {
            return Ok(None);
        }
        if agent == Agent::Grok {
            self.grok_unconfirmed += 1;
        } else {
            self.pending.insert(self.serial, input.to_string());
        }
        d.emit(id, "steered", json!({"queued": queued}));
        Ok(Some(if queued {
            "queued for a following turn"
        } else {
            "sent to its running turn"
        }))
    }
}

// Grok broadcasts interjections on admission, before the model consumes them. Its final
// drain and background wake can race turn_completed, with no consumed notification.
const GROK_GRACE: Duration = Duration::from_secs(1);

enum Exit {
    Released,
    Failed(String),
    Cancelled(Cancellation),
    Aborted,
    Detached,
}

pub async fn run(d: Arc<Daemon>, id: String, mut rx: mpsc::UnboundedReceiver<Cmd>) {
    let exit = match drive(&d, &id, &mut rx).await {
        Ok(exit) => exit,
        Err(e) => Exit::Failed(format!("{e:#}")),
    };
    match exit {
        Exit::Released => {}
        Exit::Failed(error) => {
            d.set_status(&id, Status::Failed);
            d.emit(&id, "failed", json!({"error": error}));
        }
        Exit::Cancelled(cause) => {
            d.set_status(&id, Status::Cancelled);
            d.emit(&id, "cancelled", json!(cause));
        }
        Exit::Aborted => {
            d.set_status(&id, Status::Interrupted);
            d.emit(&id, "interrupted", json!({"reason": "the daemon stopped"}));
        }
        Exit::Detached => {
            d.update(&id, |t| t.detached = true);
            d.emit(
                &id,
                "detached",
                json!({"reason": "the native session was continued outside axiopera"}),
            );
        }
    }
    d.actor_done(&id);
}

async fn drive(d: &Arc<Daemon>, id: &str, rx: &mut mpsc::UnboundedReceiver<Cmd>) -> Result<Exit> {
    let (task, env, mut inputs) = {
        let mut st = d.lock();
        let e = st
            .tasks
            .get_mut(id)
            .ok_or_else(|| anyhow!("task vanished"))?;
        let inputs = e.pending.drain(..).collect::<Vec<_>>();
        (e.task.clone(), e.env.clone(), inputs)
    };
    let Some(env) = env else {
        return Ok(Exit::Failed(
            "caller environment lost after daemon restart; re-send from outside the agent sandbox"
                .into(),
        ));
    };
    if let Some(fp) = &task.session_file
        && Fingerprint::of(&fp.path).as_ref() != Some(fp)
    {
        return Ok(Exit::Detached);
    }
    let exe = agent::resolve_exe(
        task.agent,
        d.opts.agents.get(task.agent).path.as_deref(),
        &env,
    )?;
    let spec = StartSpec {
        task_id: id.to_string(),
        agent: task.agent,
        tier: task.tier,
        cwd: task.cwd.clone(),
        model: task.model.clone(),
        effort: task.effort.clone(),
        env: agent_env(&env, id, task.agent, &d.opts.home),
        resume: task.session.clone(),
        trace: std::env::var_os("AXIOPERA_TRACE_PROTOCOL")
            .filter(|v| v == "1")
            .map(|_| d.opts.home.join("tasks").join(id).join("protocol.log")),
    };
    let deadline = task.timeout_secs.map(|s| {
        let elapsed = Duration::from_millis(crate::store::now_ms().saturating_sub(task.created_ms));
        Instant::now() + Duration::from_secs(s).saturating_sub(elapsed)
    });
    let timed_out = || {
        d.cancel_children(id, "timeout");
        Cancellation {
            reason: format!("timed out after {}s", task.timeout_secs.unwrap_or(0)),
            by: "timeout".into(),
        }
    };
    d.update(id, |t| {
        t.status = Status::Running;
        t.stalled = false;
    });
    let (etx, mut erx) = mpsc::unbounded_channel();
    // Starting can hang (an MCP server, a slow handshake): keep honouring cancel and the
    // deadline. Dropping the half-started backend kills its process.
    let start = Backend::start(&spec, &exe, etx);
    tokio::pin!(start);
    let mut backend = loop {
        tokio::select! {
            b = &mut start => break b?,
            cmd = rx.recv() => match cmd {
                Some(Cmd::Input(m)) => inputs.push(m.queued()),
                Some(Cmd::Mail(m)) => keep_mail(d, id, m),
                Some(Cmd::Cancel(cause)) => return Ok(Exit::Cancelled(cause)),
                Some(Cmd::Abort) | None => return Ok(Exit::Aborted),
            },
            _ = sleep_until(deadline) => return Ok(Exit::Cancelled(timed_out())),
        }
    };
    let mut session_file = task.session_file.as_ref().map(|f| f.path.clone());
    start_turn(d, id, &mut backend, &inputs.join("\n\n")).await?;
    let mut last_activity = Instant::now();
    let mut stalled = false;
    let mut tick = tokio::time::interval(Duration::from_secs(30));
    let mut last_ok = true;
    let mut tracking = InputTracking::default();
    let mut deferred = Vec::new();
    let mut turn_open = true;

    let exit = loop {
        if !turn_open && erx.is_empty() {
            if !deferred.is_empty() {
                let input = deferred.join("\n\n");
                deferred.clear();
                if backend.busy()
                    && tracking
                        .steer(d, id, task.agent, &mut backend, &input)
                        .await?
                        .is_some()
                {
                    continue;
                }
                start_turn(d, id, &mut backend, &input).await?;
                turn_open = true;
                continue;
            }
            if !backend.busy() {
                match release_or_continue(d, id, rx) {
                    Next::Turn(input) => {
                        start_turn(d, id, &mut backend, &input.join("\n\n")).await?;
                        turn_open = true;
                    }
                    Next::Stop(exit) => break exit,
                }
            }
        }
        tokio::select! {
            biased;
            ev = erx.recv() => {
                let Some(ev) = ev else {
                    break Exit::Failed("agent event stream closed".into());
                };
                last_activity = Instant::now();
                if stalled {
                    stalled = false;
                    d.update(id, |t| t.stalled = false);
                }
                match ev {
                    AgentEvent::Session { id: sid, file } => {
                        d.update(id, |t| t.session = Some(sid));
                        if file.is_some() {
                            session_file = file;
                        }
                    }
                    AgentEvent::Tool { name, detail } => d.emit(id, "tool", json!({"name": name, "detail": detail})),
                    AgentEvent::FileChanged(path) => {
                        d.update(id, |t| {
                            if !t.changed_files.contains(&path) {
                                t.changed_files.push(path.clone());
                            }
                        });
                        d.emit(id, "file_changed", json!({"path": path}));
                    }
                    AgentEvent::InputRead(message) => {
                        if tracking.pending.remove(&message).is_some() {
                            d.emit(id, "input_read", json!({}));
                        }
                    }
                    AgentEvent::Blocked(detail) => d.emit(id, "blocked", json!({"detail": detail})),
                    AgentEvent::Approval(a) => d.request_approval(id, a),
                    AgentEvent::TurnEnded { ok, result, error, usage } => {
                        last_ok = ok;
                        turn_open = false;
                        let next = next_input(d, id, rx, &mut backend).await;
                        let mut stop = None;
                        match next {
                            Some(Next::Turn(input)) => deferred.extend(input),
                            Some(Next::Stop(exit)) => stop = Some(exit),
                            None => {}
                        }
                        let unread = tracking.pending.len() + deferred.len();
                        end_turn(d, id, ok, &result, error, usage, (unread, tracking.grok_unconfirmed))?;
                        tracking.grok_unconfirmed = 0;
                        if let Some(exit) = stop {
                            break exit;
                        }
                        // Codex may persist late inputs during turn cleanup without sampling
                        // again. Explicitly start a follow-up for inputs with no model response.
                        if task.agent == Agent::Codex {
                            deferred.splice(0..0, std::mem::take(&mut tracking.pending).into_values());
                        }
                        if task.agent == Agent::Grok {
                            tokio::time::sleep(GROK_GRACE).await;
                        }
                    }
                    AgentEvent::Exited(msg) => {
                        let tail = backend.stderr_tail();
                        break Exit::Failed(if tail.is_empty() {
                            msg
                        } else {
                            format!("{msg}: {tail}")
                        });
                    }
                }
            }
            cmd = rx.recv() => match cmd {
                Some(Cmd::Input(input)) => {
                    if backend.busy() {
                        match tracking.steer(d, id, task.agent, &mut backend, &input.text).await? {
                            Some(how) => {
                                let _ = input.reply.send(how);
                            }
                            None => deferred.push(input.queued()),
                        }
                    } else if turn_open {
                        // The adapter has ended the turn, but its queued TurnEnded must be
                        // handled before any new turn can consume this input.
                        deferred.push(input.queued());
                    } else {
                        let text = input.queued();
                        start_turn(d, id, &mut backend, &text).await?;
                        turn_open = true;
                    }
                }
                Some(Cmd::Mail(msg)) => {
                    if backend.in_turn() && matches!(backend.steer(&msg, None).await?, Steer::Accepted) {
                        d.emit(id, "steered", json!({"chars": msg.len()}));
                    } else {
                        keep_mail(d, id, msg);
                    }
                }
                Some(Cmd::Cancel(cause)) => break cancel(&mut backend, cause).await,
                Some(Cmd::Abort) | None => {
                    backend.kill();
                    break Exit::Aborted;
                }
            },
            _ = tick.tick() => {
                if backend.busy() && !stalled && last_activity.elapsed() >= d.stall_after() {
                    stalled = true;
                    d.update(id, |t| t.stalled = true);
                    d.emit(id, "stalled", json!({"quiet_secs": last_activity.elapsed().as_secs()}));
                }
            }
            _ = sleep_until(deadline) => break cancel(&mut backend, timed_out()).await,
        }
    };

    backend.shutdown().await;
    if let Exit::Released = exit {
        let fp = session_file.as_deref().and_then(Fingerprint::of);
        d.update(id, |t| {
            t.session_file = fp;
            // A cancel that arrived while letting go has already settled the status.
            if !t.status.is_final() {
                t.status = if !last_ok {
                    Status::Failed
                } else if t.open_questions().next().is_some() {
                    Status::Waiting
                } else {
                    Status::Idle
                };
            }
        });
    }
    Ok(exit)
}

async fn sleep_until(deadline: Option<Instant>) {
    match deadline {
        Some(t) => tokio::time::sleep_until(t).await,
        None => std::future::pending().await,
    }
}

/// Sibling notes kept for this turn go first.
async fn start_turn(d: &Daemon, id: &str, backend: &mut Backend, input: &str) -> Result<()> {
    let mut parts: Vec<String> = d
        .lock()
        .tasks
        .get_mut(id)
        .map(|e| e.mail.drain(..).collect())
        .unwrap_or_default();
    parts.push(input.to_string());
    let input = parts.join(
        "

",
    );
    backend.turn(&input).await?;
    let turn = d.lock().tasks.get(id).map_or(0, |e| e.task.turns) + 1;
    d.emit(
        id,
        "turn_started",
        json!({"turn": turn, "chars": input.len()}),
    );
    Ok(())
}

fn end_turn(
    d: &Daemon,
    id: &str,
    ok: bool,
    result: &str,
    error: Option<String>,
    usage: Option<serde_json::Value>,
    messages: (usize, usize),
) -> Result<()> {
    let (unread, unconfirmed) = messages;
    let mut turn = 0;
    d.update(id, |t| {
        t.turns += 1;
        turn = t.turns;
    });
    d.store().save_turn(id, turn, result)?;
    let (files, open) = d.lock().tasks.get(id).map_or((0, Vec::new()), |e| {
        let open: Vec<String> = e.task.open_questions().map(|q| q.id.clone()).collect();
        (e.task.changed_files.len(), open)
    });
    let blocked = {
        let mut st = d.lock();
        st.tasks
            .get_mut(id)
            .map_or(0, |e| std::mem::take(&mut e.blocked))
    };
    d.emit(id, "turn_ended", json!({"unread": unread, "unconfirmed": unconfirmed, "blocked": blocked, "turn": turn, "ok": ok, "error": error, "usage": usage, "chars": result.len(), "files": files, "open_questions": open}));
    Ok(())
}

enum Next {
    Turn(Vec<String>),
    Stop(Exit),
}

fn keep_mail(d: &Daemon, id: &str, message: String) {
    if let Some(e) = d.lock().tasks.get_mut(id) {
        e.mail.push(message);
    }
}

/// Commands that arrived while the turn was ending.
async fn next_input(
    d: &Daemon,
    id: &str,
    rx: &mut mpsc::UnboundedReceiver<Cmd>,
    backend: &mut Backend,
) -> Option<Next> {
    let mut inputs = Vec::new();
    while let Ok(cmd) = rx.try_recv() {
        match cmd {
            Cmd::Input(m) => inputs.push(m.queued()),
            Cmd::Mail(m) => keep_mail(d, id, m),
            Cmd::Cancel(cause) => return Some(Next::Stop(cancel(backend, cause).await)),
            Cmd::Abort => {
                backend.kill();
                return Some(Next::Stop(Exit::Aborted));
            }
        }
    }
    (!inputs.is_empty()).then_some(Next::Turn(inputs))
}

/// Under the daemon lock, either pick up input that slipped in, or mark the task as releasing so
/// that later input waits for a fresh process.
fn release_or_continue(d: &Daemon, id: &str, rx: &mut mpsc::UnboundedReceiver<Cmd>) -> Next {
    let mut st = d.lock();
    let mut inputs = Vec::new();
    while let Ok(cmd) = rx.try_recv() {
        match cmd {
            Cmd::Input(m) => inputs.push(m.queued()),
            Cmd::Mail(m) => {
                if let Some(e) = st.tasks.get_mut(id) {
                    e.mail.push(m);
                }
            }
            // Cancellation of an idle task needs no process; the daemon handles it after release.
            Cmd::Cancel(cause) => return Next::Stop(Exit::Cancelled(cause)),
            Cmd::Abort => return Next::Stop(Exit::Aborted),
        }
    }
    if !inputs.is_empty() {
        return Next::Turn(inputs);
    }
    if let Some(e) = st.tasks.get_mut(id) {
        e.releasing = true;
    }
    Next::Stop(Exit::Released)
}

async fn cancel(backend: &mut Backend, cause: Cancellation) -> Exit {
    let _ = tokio::time::timeout(Duration::from_secs(2), backend.interrupt()).await;
    tokio::time::sleep(Duration::from_secs(2)).await;
    backend.kill();
    Exit::Cancelled(cause)
}

#[cfg(test)]
mod tests {
    use super::super::tests::fixture;
    use super::*;

    #[test]
    fn cancellation_keeps_its_author_while_running_or_releasing() {
        for releasing in [false, true] {
            let f = fixture();
            let (tx, mut rx) = mpsc::unbounded_channel();
            {
                let mut st = f.d.lock();
                let entry = st.tasks.get_mut("test").unwrap();
                entry.actor = Some(tx);
                entry.releasing = releasing;
            }
            f.d.cancel_tree("test", "cancelled by request", "codex:host");
            if releasing {
                assert_eq!(f.d.lock().tasks["test"].wake[0].data["by"], "codex:host");
                assert!(rx.try_recv().is_err());
            } else {
                let Next::Stop(Exit::Cancelled(cause)) = release_or_continue(&f.d, "test", &mut rx)
                else {
                    panic!("lost cancellation");
                };
                assert_eq!(cause.by, "codex:host");
                assert_eq!(cause.reason, "cancelled by request");
            }
        }
    }

    #[tokio::test]
    async fn two_inputs_at_release_stay_ordered_and_new_input_survives_shutdown() {
        let f = fixture();
        let (tx, mut rx) = mpsc::unbounded_channel();
        f.d.lock().tasks.get_mut("test").unwrap().actor = Some(tx.clone());
        let mut replies = Vec::new();
        for text in ["first", "second"] {
            let (reply, receive) = oneshot::channel();
            tx.send(Cmd::Input(Input {
                text: text.into(),
                reply,
            }))
            .unwrap();
            replies.push(receive);
        }
        let Next::Turn(inputs) = release_or_continue(&f.d, "test", &mut rx) else {
            panic!("lost inputs")
        };
        assert_eq!(inputs, ["first", "second"]);
        for reply in replies {
            assert_eq!(reply.await.unwrap(), "queued for a new turn");
        }
        assert!(!f.d.lock().tasks["test"].releasing);
        assert!(matches!(
            release_or_continue(&f.d, "test", &mut rx),
            Next::Stop(Exit::Released)
        ));
        assert_eq!(
            f.d.input("test", "during shutdown".into(), None)
                .await
                .unwrap(),
            "queued for a new turn"
        );
        {
            let mut st = f.d.lock();
            st.running = 1;
            st.top_running = 1;
        }
        f.d.actor_done("test");
        let st = f.d.lock();
        assert_eq!(st.tasks["test"].pending, ["during shutdown"]);
        assert_eq!(st.tasks["test"].task.status, Status::Queued);
        assert_eq!(st.queue.front().map(String::as_str), Some("test"));
    }

    #[test]
    fn turn_end_reports_late_input_and_resets_refusals() {
        let f = fixture();
        f.d.emit("test", "blocked", json!({"detail": "denied"}));
        end_turn(
            &f.d,
            "test",
            true,
            "answer before input",
            None,
            None,
            (2, 0),
        )
        .unwrap();
        end_turn(&f.d, "test", true, "answer after input", None, None, (0, 0)).unwrap();
        let st = f.d.lock();
        let events = &st.tasks["test"].wake;
        assert_eq!(events[0].data["unread"], 2);
        assert_eq!(events[0].data["blocked"], 1);
        assert_eq!(events[1].data["blocked"], 0);
        let line = super::super::render::event_line(&events[0], Agent::Codex);
        assert!(line.contains("this result predates 2 parent message(s)"));
        assert!(line.contains("axiopera log test"));
    }
}