axiopera 0.3.3

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
//! A host Codex session, reached through the user's shared Codex app-server daemon, which the
//! interactive Codex uses by default, or through a private app-server for sessions the daemon
//! does not have. `codex app-server proxy` relays bytes to the daemon's control socket, which
//! speaks JSON-RPC over WebSocket; a private `codex app-server` speaks it in lines on stdio.

use std::path::Path;
use std::process::Stdio;

use anyhow::{Context, Result, anyhow, bail};
use serde_json::{Value, json};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::process::{Child, ChildStdin, ChildStdout, Command};

pub struct Remote {
    _child: Child,
    stdin: ChildStdin,
    stdout: ChildStdout,
    buf: Vec<u8>,
    /// Through the shared daemon rather than a private app-server.
    shared: bool,
    next: u64,
    /// A message went out and was not refused.
    sent: bool,
}

impl Remote {
    /// `codex_home` locates the daemon; `None` means Codex's default.
    pub async fn connect(exe: &Path, codex_home: Option<&Path>) -> Result<Remote> {
        let mut r = Remote::spawn(exe, codex_home, &["app-server", "proxy"], true)?;
        let key = base64(&uuid::Uuid::new_v4().into_bytes());
        r.stdin
            .write_all(
                format!(
                    "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\
                     Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n"
                )
                .as_bytes(),
            )
            .await?;
        let end = loop {
            if let Some(i) = r.buf.windows(4).position(|w| w == b"\r\n\r\n") {
                break i + 4;
            }
            r.read_more().await?;
        };
        let head: Vec<u8> = r.buf.drain(..end).collect();
        if !head.starts_with(b"HTTP/1.1 101") {
            bail!("the Codex daemon refused the connection");
        }
        r.initialize(None).await?;
        Ok(r)
    }

    /// An app-server of its own on the Codex home's data, which reads any stored session and
    /// writes its queue, but runs none.
    pub async fn private(exe: &Path, codex_home: Option<&Path>) -> Result<Remote> {
        let mut r = Remote::spawn(exe, codex_home, &["app-server"], false)?;
        // The queue is an experimental API.
        r.initialize(Some(json!({"experimentalApi": true}))).await?;
        Ok(r)
    }

    fn spawn(exe: &Path, codex_home: Option<&Path>, args: &[&str], shared: bool) -> Result<Remote> {
        let mut cmd = Command::new(exe);
        cmd.args(args);
        match codex_home {
            Some(home) => cmd.env("CODEX_HOME", home),
            None => cmd.env_remove("CODEX_HOME"),
        };
        cmd.stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .kill_on_drop(true);
        // The daemon has no console; without this Windows opens a window for the child.
        #[cfg(windows)]
        cmd.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
        let mut child = cmd
            .spawn()
            .with_context(|| format!("starting `codex {}`", args.join(" ")))?;
        Ok(Remote {
            stdin: child.stdin.take().unwrap(),
            stdout: child.stdout.take().unwrap(),
            _child: child,
            buf: Vec::new(),
            shared,
            next: 0,
            sent: false,
        })
    }

    async fn initialize(&mut self, capabilities: Option<Value>) -> Result<()> {
        let mut params =
            json!({"clientInfo": {"name": "axiopera", "version": env!("CARGO_PKG_VERSION")}});
        if let Some(c) = capabilities {
            params["capabilities"] = c;
        }
        self.call("initialize", params).await?;
        self.send(json!({"method": "initialized", "params": {}}))
            .await
    }

    /// Whether the session is open in the daemon. A closed one must not be messaged: that
    /// would run a turn nobody watches.
    pub async fn is_open(&mut self, thread: &str) -> Result<bool> {
        let mut cursor = Value::Null;
        loop {
            let page = self
                .call("thread/loaded/list", json!({"cursor": cursor}))
                .await?;
            let ids = page["data"].as_array().into_iter().flatten();
            if ids.filter_map(Value::as_str).any(|id| id == thread) {
                return Ok(true);
            }
            cursor = page["nextCursor"].clone();
            if cursor.is_null() {
                return Ok(false);
            }
        }
    }

    /// Into the running turn, or as a new turn if the session is idle. Returns which. `id` goes
    /// with the message as its `clientUserMessageId`, outside the text the agent reads.
    pub async fn message(&mut self, thread: &str, text: &str, id: &str) -> Result<&'static str> {
        let input = json!([{"type": "text", "text": text}]);
        let mut last_err = None;
        // The session may start or end a turn between our look and our message.
        for _ in 0..3 {
            let turns = self
                .call(
                    "thread/turns/list",
                    json!({"threadId": thread, "limit": 1, "sortDirection": "desc", "itemsView": "notLoaded"}),
                )
                .await?;
            let last = &turns["data"][0];
            // Cleared again by a refusal.
            self.sent = true;
            let sent = if last["status"] == "inProgress" {
                self.call(
                    "turn/steer",
                    json!({
                        "threadId": thread, "expectedTurnId": last["id"], "input": input,
                        "clientUserMessageId": id,
                    }),
                )
                .await
                .map(|_| "steered into its running turn")
            } else {
                self.call(
                    "turn/start",
                    json!({"threadId": thread, "input": input, "clientUserMessageId": id}),
                )
                .await
                .map(|_| "started a turn")
            };
            match sent {
                Ok(how) => return Ok(how),
                Err(e) if self.sent => return Err(e),
                Err(e) => last_err = Some(e),
            }
        }
        Err(last_err.unwrap())
    }

    /// Whether `message` got its message out, even if it then failed waiting for the answer.
    pub fn sent(&self) -> bool {
        self.sent
    }

    /// Whether the session has the user message sent with `id`. Codex keeps the ID with the
    /// message, also in a session loaded again from disk. A message steered into a running turn
    /// is not listed yet when the steer is accepted.
    pub async fn contains_message(&mut self, thread: &str, id: &str) -> Result<bool> {
        let mut cursor = Value::Null;
        loop {
            let page = self
                .call(
                    "thread/turns/list",
                    json!({
                        "threadId": thread, "limit": 20, "sortDirection": "desc",
                        "itemsView": "full", "cursor": cursor,
                    }),
                )
                .await?;
            let turns = page["data"]
                .as_array()
                .context("thread/turns/list omitted data")?;
            if turns.iter().any(|t| !t["items"].is_array()) {
                bail!("thread/turns/list omitted full items");
            }
            if turns.iter().any(|t| has_message(t, id)) {
                return Ok(true);
            }
            cursor = page["nextCursor"].clone();
            if cursor.is_null() {
                return Ok(false);
            }
        }
    }

    /// Whether a long-lived client serves the session's queue. Sessions of app-server clients,
    /// such as the Codex app and the IDE extension, report `vscode`. `codex exec` quits after
    /// its turn, so a message queued for it would fire whenever the session is next opened. The
    /// terminal Codex normally runs on the shared daemon and is not tried outside it.
    pub async fn serves_queue(&mut self, thread: &str) -> Result<bool> {
        let t = self
            .call("thread/read", json!({"threadId": thread}))
            .await?;
        let t = &t["thread"];
        if t["source"] != "vscode" || t["ephemeral"] == true {
            return Ok(false);
        }
        // Fails where this Codex has no queue.
        self.call("thread/queue/list", json!({"threadId": thread, "limit": 1}))
            .await?;
        Ok(true)
    }

    /// Queue a message for the session's next turn; returns the ID it has in the queue. `id` goes
    /// with it as its `clientUserMessageId`, as with `message`.
    pub async fn enqueue(&mut self, thread: &str, text: &str, id: &str) -> Result<String> {
        let added = self
            .call(
                "thread/queue/add",
                json!({
                    "threadId": thread,
                    "input": [{"type": "text", "text": text}],
                    "clientUserMessageId": id,
                }),
            )
            .await?;
        added["queuedSubmission"]["id"]
            .as_str()
            .map(str::to_string)
            .context("thread/queue/add omitted the ID")
    }

    /// Whether a queued message still waits to start a turn.
    pub async fn queued(&mut self, thread: &str, id: &str) -> Result<bool> {
        let mut cursor = Value::Null;
        loop {
            let page = self
                .call(
                    "thread/queue/list",
                    json!({"threadId": thread, "cursor": cursor}),
                )
                .await?;
            let items = page["data"].as_array().into_iter().flatten();
            if items.filter_map(|s| s["id"].as_str()).any(|s| s == id) {
                return Ok(true);
            }
            cursor = page["nextCursor"].clone();
            if cursor.is_null() {
                return Ok(false);
            }
        }
    }

    /// Returns whether it was still queued.
    pub async fn dequeue(&mut self, thread: &str, id: &str) -> Result<bool> {
        let r = self
            .call(
                "thread/queue/delete",
                json!({"threadId": thread, "queuedSubmissionId": id}),
            )
            .await?;
        Ok(r["deleted"] == true)
    }

    /// Delete keys from the user's `config.toml`, editing it the way Codex itself does.
    pub async fn clear_config(&mut self, key_paths: &[String]) -> Result<()> {
        let edits: Vec<Value> = key_paths
            .iter()
            .map(|k| json!({"keyPath": k, "value": null, "mergeStrategy": "replace"}))
            .collect();
        self.call("config/batchWrite", json!({"edits": edits}))
            .await?;
        Ok(())
    }

    async fn call(&mut self, method: &str, params: Value) -> Result<Value> {
        self.next += 1;
        let id = self.next;
        self.send(json!({"id": id, "method": method, "params": params}))
            .await?;
        loop {
            let m = self.recv().await?;
            // Notifications and the daemon's own requests carry a method; replies do not.
            if m["id"] != json!(id) || m.get("method").is_some() {
                continue;
            }
            if let Some(e) = m.get("error") {
                if matches!(method, "turn/steer" | "turn/start") {
                    self.sent = false;
                }
                bail!("{method}: {}", e["message"].as_str().unwrap_or("failed"));
            }
            return Ok(m["result"].clone());
        }
    }

    async fn send(&mut self, message: Value) -> Result<()> {
        let text = message.to_string();
        if self.shared {
            return self.send_frame(0x1, text.as_bytes()).await;
        }
        self.stdin.write_all(format!("{text}\n").as_bytes()).await?;
        self.stdin.flush().await?;
        Ok(())
    }

    async fn send_frame(&mut self, opcode: u8, data: &[u8]) -> Result<()> {
        let mut frame = vec![0x80 | opcode];
        match data.len() {
            n if n < 126 => frame.push(0x80 | n as u8),
            n if n <= u16::MAX as usize => {
                frame.push(0x80 | 126);
                frame.extend((n as u16).to_be_bytes());
            }
            n => {
                frame.push(0x80 | 127);
                frame.extend((n as u64).to_be_bytes());
            }
        }
        // Client frames must be masked.
        let mask = uuid::Uuid::new_v4().into_bytes();
        frame.extend(&mask[..4]);
        frame.extend(data.iter().enumerate().map(|(i, b)| b ^ mask[i % 4]));
        self.stdin.write_all(&frame).await?;
        self.stdin.flush().await?;
        Ok(())
    }

    async fn recv(&mut self) -> Result<Value> {
        if !self.shared {
            loop {
                if let Some(i) = self.buf.iter().position(|b| *b == b'\n') {
                    let line: Vec<u8> = self.buf.drain(..=i).collect();
                    return serde_json::from_slice(&line).map_err(|e| anyhow!(e));
                }
                self.read_more().await?;
            }
        }
        let mut message = Vec::new();
        loop {
            self.fill(2).await?;
            let fin = self.buf[0] & 0x80 != 0;
            let opcode = self.buf[0] & 0x0F;
            let (start, len) = match self.buf[1] & 0x7F {
                126 => {
                    self.fill(4).await?;
                    (4, u16::from_be_bytes([self.buf[2], self.buf[3]]) as usize)
                }
                127 => {
                    self.fill(10).await?;
                    (10, u64::from_be_bytes(self.buf[2..10].try_into()?) as usize)
                }
                n => (2, n as usize),
            };
            self.fill(start + len).await?;
            let payload: Vec<u8> = self.buf.drain(..start + len).skip(start).collect();
            match opcode {
                0x8 => bail!("the Codex daemon closed the connection"),
                0x9 => self.send_frame(0xA, &payload).await?,
                0xA => {}
                _ => {
                    message.extend(payload);
                    if fin {
                        return serde_json::from_slice(&message).map_err(|e| anyhow!(e));
                    }
                }
            }
        }
    }

    async fn fill(&mut self, n: usize) -> Result<()> {
        while self.buf.len() < n {
            self.read_more().await?;
        }
        Ok(())
    }

    async fn read_more(&mut self) -> Result<()> {
        let mut chunk = [0u8; 8192];
        let n = self.stdout.read(&mut chunk).await?;
        if n == 0 {
            if self.shared {
                bail!("the Codex daemon is not running");
            }
            bail!("the Codex app-server exited");
        }
        self.buf.extend_from_slice(&chunk[..n]);
        Ok(())
    }
}

fn has_message(turn: &Value, id: &str) -> bool {
    turn["items"]
        .as_array()
        .into_iter()
        .flatten()
        .any(|item| item["type"] == "userMessage" && item["clientId"] == id)
}

fn base64(bytes: &[u8]) -> String {
    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::new();
    for chunk in bytes.chunks(3) {
        let b = [
            chunk[0],
            *chunk.get(1).unwrap_or(&0),
            *chunk.get(2).unwrap_or(&0),
        ];
        let n = (b[0] as u32) << 16 | (b[1] as u32) << 8 | b[2] as u32;
        for i in 0..4 {
            if i <= chunk.len() {
                out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char);
            } else {
                out.push('=');
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    #[test]
    fn receipt_matches_only_the_user_message_sent_with_the_id() {
        use serde_json::json;
        let id = "axiopera:batch";
        let turn = json!({"items": [
            {"type": "agentMessage", "id": id, "text": id},
            {"type": "userMessage", "clientId": null, "content": [{"text": id}]},
            {"type": "userMessage", "clientId": "axiopera:other", "content": [{"text": "result"}]}
        ]});
        assert!(!super::has_message(&turn, id));
        let turn = json!({"items": [
            {"type": "userMessage", "clientId": id, "content": [{"text": "result"}]}
        ]});
        assert!(super::has_message(&turn, id));
    }

    #[test]
    fn base64_matches_rfc4648() {
        assert_eq!(super::base64(b"f"), "Zg==");
        assert_eq!(super::base64(b"fo"), "Zm8=");
        assert_eq!(super::base64(b"foo"), "Zm9v");
        assert_eq!(super::base64(b"foobar"), "Zm9vYmFy");
    }
}