stubb 0.1.0

A Rust library for embedding coding agents (Codex, Claude Code, Pi, and ACP agents) in your application
Documentation
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
//! A supervised child process speaking newline-delimited JSON-RPC (without
//! the `jsonrpc` field) over stdio, as `codex app-server` does. It is
//! used by Codex, whose [`Handler`] interprets the app-server's messages.
//!
//! A reader task owns stdout and routes each line: responses complete the
//! matching pending request; notifications and requests from the child are
//! handed to the provider's [`Handler`], and resulting events go to the
//! session they name.

use std::collections::HashMap;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, ChildStdout, Command};
use tokio::sync::oneshot;
use tokio::task::JoinHandle;

use crate::session;
use crate::{Error, Result};

const STDERR_TAIL_BYTES: usize = 8 * 1024;
const SHUTDOWN_GRACE: Duration = Duration::from_secs(2);

/// Synchronous delivery from the reader into the provider's state reducer.
/// Implementations serialize state updates and publication at this boundary.
pub(in crate::providers::codex) trait EventSink: Send + Sync {
    fn emit(&self, event: session::Event);
}

/// Provider-specific interpretation of messages from the child.
pub(in crate::providers::codex) trait Handler:
    Send + Sync + 'static
{
    /// Provider routing/discovery before exact-session filtering. Returning true
    /// means the provider consumed or buffered this notification itself.
    fn route_notification(&self, _method: &str, _params: &Value) -> bool {
        false
    }

    fn route_event(&self, _params: &Value, _event: &session::Event) -> bool {
        false
    }
    /// The session a notification or request belongs to.
    fn session_id<'a>(&self, params: &'a Value) -> Option<&'a str>;

    /// Events for one notification about a registered session; may be none or several.
    fn notification(&self, method: &str, params: Value) -> Vec<session::Event>;

    /// Reply to a request from the child, and an optional event for its session.
    fn request(&self, id: &Value, method: &str, params: &Value) -> (Value, Option<session::Event>);

    /// Called when a session stops being routed, to drop per-session state.
    fn session_closed(&self, _session_id: &str) {}
}

pub(in crate::providers::codex) struct Connection {
    shared: Arc<Shared>,
    child: tokio::sync::Mutex<Child>,
    tasks: Vec<JoinHandle<()>>,
}

struct Shared {
    label: &'static str,
    handler: Arc<dyn Handler>,
    stdin: tokio::sync::Mutex<Option<ChildStdin>>,
    pending: Mutex<HashMap<i64, oneshot::Sender<Reply>>>,
    sessions: Mutex<HashMap<String, Arc<dyn EventSink>>>,
    next_id: AtomicI64,
    /// Set once the process is gone; holds the reason reported to callers.
    closed: Mutex<Option<String>>,
    stderr_tail: Mutex<String>,
}

type Reply = std::result::Result<Value, RpcFailure>;

struct RpcFailure {
    code: i64,
    message: String,
}

impl Connection {
    /// Spawns `command` with piped stdio. `label` names the process in errors.
    pub(in crate::providers::codex) fn spawn(
        mut command: Command,
        label: &'static str,
        handler: Arc<dyn Handler>,
    ) -> Result<Self> {
        let executable = PathBuf::from(command.as_std().get_program());
        crate::process::die_with_parent(&mut command);
        let mut child = command
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .map_err(|source| {
                if source.kind() == std::io::ErrorKind::NotFound {
                    Error::ExecutableNotFound {
                        executable: executable.clone(),
                    }
                } else {
                    Error::SpawnFailed {
                        executable: executable.clone(),
                        source,
                    }
                }
            })?;

        let stdin = child.stdin.take().expect("stdin is piped");
        let stdout = child.stdout.take().expect("stdout is piped");
        let stderr = child.stderr.take().expect("stderr is piped");

        let shared = Arc::new(Shared {
            label,
            handler,
            stdin: tokio::sync::Mutex::new(Some(stdin)),
            pending: Mutex::new(HashMap::new()),
            sessions: Mutex::new(HashMap::new()),
            next_id: AtomicI64::new(0),
            closed: Mutex::new(None),
            stderr_tail: Mutex::new(String::new()),
        });

        let stderr_task = tokio::spawn({
            let shared = Arc::clone(&shared);
            async move {
                let mut lines = BufReader::new(stderr).lines();
                while let Ok(Some(line)) = lines.next_line().await {
                    shared.append_stderr(&line);
                }
            }
        });
        let reader_task = tokio::spawn(read_loop(Arc::clone(&shared), stdout));

        Ok(Self {
            shared,
            child: tokio::sync::Mutex::new(child),
            tasks: vec![reader_task, stderr_task],
        })
    }

    pub(in crate::providers::codex) fn is_alive(&self) -> bool {
        self.shared.closed.lock().expect("closed lock").is_none()
    }

    /// Requests sent and not answered yet.
    pub(in crate::providers::codex) fn pending_requests(&self) -> usize {
        self.shared.pending.lock().expect("pending lock").len()
    }

    pub(in crate::providers::codex) async fn request<P, R>(
        &self,
        method: &str,
        params: &P,
        timeout: Duration,
    ) -> Result<R>
    where
        P: Serialize,
        R: DeserializeOwned,
    {
        if let Some(reason) = self.shared.closed_reason() {
            return Err(Error::ProcessExited { stderr: reason });
        }
        let params = serde_json::to_value(params).map_err(|source| Error::Decode {
            method: method.to_owned(),
            source,
        })?;
        let id = self.shared.next_id.fetch_add(1, Ordering::Relaxed);
        let (reply_tx, reply_rx) = oneshot::channel();
        self.shared
            .pending
            .lock()
            .expect("pending lock")
            .insert(id, reply_tx);

        let sent = self
            .shared
            .write(&json!({ "id": id, "method": method, "params": params }))
            .await;
        if let Err(error) = sent {
            self.shared
                .pending
                .lock()
                .expect("pending lock")
                .remove(&id);
            return Err(error);
        }

        let reply = match tokio::time::timeout(timeout, reply_rx).await {
            Ok(Ok(reply)) => reply,
            // The reader dropped the sender because the process exited.
            Ok(Err(_)) => {
                return Err(Error::ProcessExited {
                    stderr: self.shared.closed_reason().unwrap_or_default(),
                });
            }
            Err(_) => {
                self.shared
                    .pending
                    .lock()
                    .expect("pending lock")
                    .remove(&id);
                return Err(Error::Timeout(timeout));
            }
        };
        let value = reply.map_err(|failure| Error::Rpc {
            method: method.to_owned(),
            code: failure.code,
            message: failure.message,
        })?;
        serde_json::from_value(value).map_err(|source| Error::Decode {
            method: method.to_owned(),
            source,
        })
    }

    pub(in crate::providers::codex) async fn notify(&self, method: &str) -> Result<()> {
        self.shared.write(&json!({ "method": method })).await
    }

    /// Routes events for `session_id` directly into its provider reducer.
    pub(in crate::providers::codex) fn register_session(
        &self,
        session_id: &str,
        sink: Arc<dyn EventSink>,
    ) {
        self.shared
            .sessions
            .lock()
            .expect("sessions lock")
            .insert(session_id.to_owned(), sink);
    }

    pub(in crate::providers::codex) fn unregister_session(&self, session_id: &str) {
        self.shared
            .sessions
            .lock()
            .expect("sessions lock")
            .remove(session_id);
        self.shared.handler.session_closed(session_id);
    }

    /// Closes stdin and waits briefly for a clean exit before killing.
    pub(in crate::providers::codex) async fn shutdown(&self) {
        self.shared.stdin.lock().await.take();
        let mut child = self.child.lock().await;
        if tokio::time::timeout(SHUTDOWN_GRACE, child.wait())
            .await
            .is_err()
        {
            let _ = child.kill().await;
        }
    }
}

impl Drop for Connection {
    fn drop(&mut self) {
        for task in &self.tasks {
            task.abort();
        }
    }
}

impl Shared {
    async fn write(&self, message: &Value) -> Result<()> {
        let mut stdin = self.stdin.lock().await;
        let Some(stdin) = stdin.as_mut() else {
            return Err(Error::ProcessExited {
                stderr: self.closed_reason().unwrap_or_default(),
            });
        };
        let mut line = message.to_string().into_bytes();
        line.push(b'\n');
        stdin.write_all(&line).await?;
        stdin.flush().await?;
        Ok(())
    }

    fn closed_reason(&self) -> Option<String> {
        self.closed.lock().expect("closed lock").clone()
    }

    fn append_stderr(&self, line: &str) {
        let mut tail = self.stderr_tail.lock().expect("stderr lock");
        tail.push_str(line);
        tail.push('\n');
        if tail.len() > STDERR_TAIL_BYTES {
            let mut cut = tail.len() - STDERR_TAIL_BYTES;
            while !tail.is_char_boundary(cut) {
                cut += 1;
            }
            tail.drain(..cut);
        }
    }

    async fn dispatch(&self, line: &str) {
        let Ok(message) = serde_json::from_str::<Value>(line) else {
            return;
        };
        let method = message.get("method").and_then(Value::as_str);
        let params = || message.get("params").cloned().unwrap_or(Value::Null);
        match (message.get("id"), method) {
            (Some(id), None) => self.complete(id, &message),
            (Some(id), Some(method)) => {
                let params = params();
                let (reply, event) = self.handler.request(id, method, &params);
                let _ = self.write(&reply).await;
                if let Some(event) = event
                    && !self.handler.route_event(&params, &event)
                {
                    self.emit(&params, vec![event]);
                }
            }
            (None, Some(method)) => {
                let params = params();
                // Skip the mapping work for sessions nobody routes.
                if !self.handler.route_notification(method, &params)
                    && self.sender(&params).is_some()
                {
                    let events = self.handler.notification(method, params.clone());
                    self.emit(&params, events);
                }
            }
            (None, None) => {}
        }
    }

    fn complete(&self, id: &Value, message: &Value) {
        let Some(id) = id.as_i64() else { return };
        let Some(reply_tx) = self.pending.lock().expect("pending lock").remove(&id) else {
            return;
        };
        let reply = match message.get("error") {
            Some(error) => Err(RpcFailure {
                code: error.get("code").and_then(Value::as_i64).unwrap_or(0),
                message: error
                    .get("message")
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .to_owned(),
            }),
            None => Ok(message.get("result").cloned().unwrap_or(Value::Null)),
        };
        let _ = reply_tx.send(reply);
    }

    fn sender(&self, params: &Value) -> Option<Arc<dyn EventSink>> {
        let session_id = self.handler.session_id(params)?;
        self.sessions
            .lock()
            .expect("sessions lock")
            .get(session_id)
            .cloned()
    }

    /// Sends `events` to the session named in `params`, if one is registered.
    fn emit(&self, params: &Value, events: Vec<session::Event>) {
        if let Some(sender) = self.sender(params) {
            for event in events {
                sender.emit(event);
            }
        }
    }

    /// Marks the connection dead, fails pending requests, and tells every
    /// registered session it must be resumed elsewhere.
    fn close(&self) {
        let stderr = self
            .stderr_tail
            .lock()
            .expect("stderr lock")
            .trim()
            .to_owned();
        let reason = if stderr.is_empty() {
            format!("{} exited", self.label)
        } else {
            format!("{} exited: {stderr}", self.label)
        };
        *self.closed.lock().expect("closed lock") = Some(reason.clone());
        self.pending.lock().expect("pending lock").clear();
        for (_, events) in self.sessions.lock().expect("sessions lock").drain() {
            events.emit(session::Event::Closed {
                reason: session::CloseReason::Exited {
                    message: reason.clone(),
                },
            });
        }
    }
}

async fn read_loop(shared: Arc<Shared>, stdout: ChildStdout) {
    let mut lines = BufReader::new(stdout).lines();
    while let Ok(Some(line)) = lines.next_line().await {
        shared.dispatch(&line).await;
    }
    // Give the stderr reader a moment to capture the exit message.
    tokio::time::sleep(Duration::from_millis(100)).await;
    shared.close();
}

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

    struct Passthrough;
    impl Handler for Passthrough {
        fn session_id<'a>(&self, params: &'a Value) -> Option<&'a str> {
            params["threadId"].as_str()
        }
        fn notification(&self, method: &str, params: Value) -> Vec<session::Event> {
            vec![session::Event::Raw {
                name: method.into(),
                payload: params,
            }]
        }
        fn request(&self, id: &Value, method: &str, _: &Value) -> (Value, Option<session::Event>) {
            (
                json!({"id": id, "result": {}}),
                Some(session::Event::RequestDeclined {
                    method: method.into(),
                    turn_id: None,
                    summary: None,
                }),
            )
        }
    }

    #[derive(Default)]
    struct Captured(Mutex<Vec<session::Event>>);
    impl EventSink for Captured {
        fn emit(&self, event: session::Event) {
            self.0.lock().unwrap().push(event);
        }
    }

    #[tokio::test]
    async fn reader_dispatch_and_process_exit_reach_the_registered_sink_directly() {
        let sink = Arc::new(Captured::default());
        let shared = Shared {
            label: "fixture",
            handler: Arc::new(Passthrough),
            stdin: tokio::sync::Mutex::new(None),
            pending: Mutex::new(HashMap::new()),
            sessions: Mutex::new(HashMap::from([(
                "root".into(),
                sink.clone() as Arc<dyn EventSink>,
            )])),
            next_id: AtomicI64::new(0),
            closed: Mutex::new(None),
            stderr_tail: Mutex::new(String::new()),
        };
        shared
            .dispatch(r#"{"method":"known","params":{"threadId":"root"}}"#)
            .await;
        shared
            .dispatch(r#"{"method":"unrouted","params":{"threadId":"child"}}"#)
            .await;
        shared
            .dispatch(r#"{"id":7,"method":"approval","params":{"threadId":"root"}}"#)
            .await;
        shared.close();
        let events = sink.0.lock().unwrap();
        assert_eq!(events.len(), 3);
        assert!(matches!(&events[0], session::Event::Raw { name, .. } if name == "known"));
        assert!(
            matches!(&events[1], session::Event::RequestDeclined { method, .. } if method == "approval")
        );
        assert!(matches!(
            &events[2],
            session::Event::Closed {
                reason: session::CloseReason::Exited { .. }
            }
        ));
        assert!(shared.sessions.lock().unwrap().is_empty());
    }
}