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
//! One `pi --mode rpc` process.
//!
//! Pi's RPC protocol is newline-delimited JSON on stdin/stdout. Stubb writes
//! commands with an `id`; Pi answers each with a `response` record carrying
//! the same id, and streams session events without one. Extensions can ask
//! for user input through `extension_ui_request` dialogs, which Stubb
//! declines.

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

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

use super::events::SessionState;
use crate::process::Environment;
use crate::{Error, Result, session};

const STDERR_TAIL_BYTES: usize = 8 * 1024;
const SHUTDOWN_GRACE: Duration = Duration::from_secs(2);
const EVENT_BUFFER: usize = 1024;
/// Extension UI methods that wait for an answer.
const DIALOGS: [&str; 4] = ["select", "confirm", "input", "editor"];

/// Which session the process works on.
pub(super) enum Conversation<'a> {
    /// No session (used to read the model catalog).
    None,
    New {
        id: &'a str,
    },
    Resume {
        path: &'a Path,
    },
}

pub(super) struct Launch<'a> {
    pub executable: &'a Path,
    pub agent_dir: Option<&'a Path>,
    pub environment: &'a Environment,
    pub cwd: &'a Path,
    pub conversation: Conversation<'a>,
}

pub(super) struct PiProcess {
    shared: Arc<Shared>,
    child: tokio::sync::Mutex<Child>,
    tasks: Vec<JoinHandle<()>>,
}

struct Shared {
    stdin: tokio::sync::Mutex<Option<ChildStdin>>,
    pending: Mutex<HashMap<String, oneshot::Sender<std::result::Result<Value, String>>>>,
    next_id: AtomicU64,
    state: Mutex<SessionState>,
    /// Told the turn id once Pi echoes the user message of a sent prompt.
    prompted: Mutex<Option<oneshot::Sender<String>>>,
    events: broadcast::Sender<session::Event>,
    /// Set once the process is gone; holds the reason reported to callers.
    closed: Mutex<Option<String>>,
    /// Stubb asked the process to stop, so its exit is not a disconnect.
    closing: AtomicBool,
    stderr_tail: Mutex<String>,
}

impl PiProcess {
    pub(super) fn spawn(launch: &Launch<'_>) -> Result<Self> {
        let mut command = Command::new(launch.executable);
        command
            .args(["--mode", "rpc"])
            .current_dir(launch.cwd)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true);
        crate::process::die_with_parent(&mut command);
        launch.environment.apply(&mut command);
        if let Some(agent_dir) = launch.agent_dir {
            command.env("PI_CODING_AGENT_DIR", agent_dir);
        }
        match launch.conversation {
            Conversation::None => {
                command.arg("--no-session");
            }
            Conversation::New { id } => {
                command.args(["--session-id", id]);
            }
            Conversation::Resume { path } => {
                command.arg("--session").arg(path);
            }
        }

        let mut child = command.spawn().map_err(|source| {
            let executable = PathBuf::from(launch.executable);
            if source.kind() == std::io::ErrorKind::NotFound {
                Error::ExecutableNotFound { executable }
            } else {
                Error::SpawnFailed { executable, 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 {
            stdin: tokio::sync::Mutex::new(Some(stdin)),
            pending: Mutex::new(HashMap::new()),
            next_id: AtomicU64::new(0),
            state: Mutex::new(SessionState::default()),
            prompted: Mutex::new(None),
            events: broadcast::channel(EVENT_BUFFER).0,
            closed: Mutex::new(None),
            closing: AtomicBool::new(false),
            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(super) fn is_alive(&self) -> bool {
        self.shared.closed.lock().expect("closed lock").is_none()
    }

    pub(super) fn subscribe(&self) -> broadcast::Receiver<session::Event> {
        self.shared.events.subscribe()
    }

    pub(super) fn set_context_window(&self, context_window: Option<i64>) {
        self.shared
            .state
            .lock()
            .expect("state lock")
            .set_context_window(context_window);
    }

    /// Sends a command, such as `{"type": "get_state"}`, and waits for the
    /// `data` of its response.
    pub(super) async fn command(&self, mut command: Value, timeout: Duration) -> Result<Value> {
        let method = command
            .get("type")
            .and_then(Value::as_str)
            .unwrap_or("command")
            .to_owned();
        if let Some(reason) = self.shared.closed_reason() {
            return Err(Error::ProcessExited { stderr: reason });
        }
        let id = format!(
            "stubb_{}",
            self.shared.next_id.fetch_add(1, Ordering::Relaxed)
        );
        command["id"] = Value::String(id.clone());
        let (reply_tx, reply_rx) = oneshot::channel();
        self.shared
            .pending
            .lock()
            .expect("pending lock")
            .insert(id.clone(), reply_tx);
        if let Err(error) = self.shared.write(&command).await {
            self.shared
                .pending
                .lock()
                .expect("pending lock")
                .remove(&id);
            return Err(error);
        }
        match tokio::time::timeout(timeout, reply_rx).await {
            Ok(Ok(Ok(data))) => Ok(data),
            Ok(Ok(Err(message))) => Err(Error::Rpc {
                method,
                code: 0,
                message,
            }),
            Ok(Err(_)) => Err(Error::ProcessExited {
                stderr: self.shared.closed_reason().unwrap_or_default(),
            }),
            Err(_) => {
                self.shared
                    .pending
                    .lock()
                    .expect("pending lock")
                    .remove(&id);
                Err(Error::Timeout(timeout))
            }
        }
    }

    /// Starts a turn by sending a prompt, and returns the turn id once Pi
    /// has echoed the prompt's user message, before any reply.
    pub(super) async fn send_user(
        &self,
        text: &str,
        images: Vec<Value>,
        timeout: Duration,
    ) -> Result<String> {
        if !self.shared.state.lock().expect("state lock").prompt_sent() {
            return Err(Error::Rpc {
                method: "prompt".to_owned(),
                code: 0,
                message: "a turn is already running".to_owned(),
            });
        }
        let (started_tx, started_rx) = oneshot::channel();
        *self.shared.prompted.lock().expect("prompted lock") = Some(started_tx);
        let sent = self
            .command(
                if images.is_empty() {
                    json!({ "type": "prompt", "message": text })
                } else {
                    json!({ "type": "prompt", "message": text, "images": images })
                },
                timeout,
            )
            .await;
        let handled = match &sent {
            Ok(data) => data.get("disposition").and_then(Value::as_str) == Some("handled"),
            Err(_) => false,
        };
        if sent.is_err() || handled {
            self.shared.prompted.lock().expect("prompted lock").take();
            let mut state = self.shared.state.lock().expect("state lock");
            let Err(error) = sent else {
                let turn_id = uuid::Uuid::new_v4().to_string();
                let events = state.prompt_handled(&turn_id, text);
                drop(state);
                self.shared.emit(events);
                return Ok(turn_id);
            };
            state.prompt_failed();
            return Err(error);
        }
        match tokio::time::timeout(timeout, started_rx).await {
            Ok(Ok(turn_id)) => Ok(turn_id),
            Ok(Err(_)) => Err(Error::ProcessExited {
                stderr: self.shared.closed_reason().unwrap_or_default(),
            }),
            Err(_) => Err(Error::Timeout(timeout)),
        }
    }

    /// Closes stdin and waits briefly for a clean exit before killing.
    /// Subscribers learn that the client closed the session.
    pub(super) async fn close(&self) {
        // An exited process already announced `Closed { Exited }`.
        if !self.shared.closing.swap(true, Ordering::Relaxed) && self.is_alive() {
            self.shared.emit(vec![session::Event::Closed {
                reason: session::CloseReason::Client,
            }]);
        }
        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 PiProcess {
    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 emit(&self, events: Vec<session::Event>) {
        for event in events {
            // No subscribers is fine; the event is simply dropped.
            let _ = self.events.send(event);
        }
    }

    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(record) = serde_json::from_str::<Value>(line) else {
            return;
        };
        match record.get("type").and_then(Value::as_str) {
            Some("response") => self.complete(&record),
            Some("extension_ui_request") => self.extension_ui(&record).await,
            _ => {
                let (events, prompted) = {
                    let mut state = self.state.lock().expect("state lock");
                    (state.event(&record), state.take_prompted())
                };
                self.emit(events);
                if let Some(turn_id) = prompted
                    && let Some(started_tx) = self.prompted.lock().expect("prompted lock").take()
                {
                    let _ = started_tx.send(turn_id);
                }
            }
        }
    }

    fn complete(&self, response: &Value) {
        let Some(id) = response.get("id").and_then(Value::as_str) else {
            return;
        };
        let Some(reply_tx) = self.pending.lock().expect("pending lock").remove(id) else {
            return;
        };
        let reply = if response.get("success").and_then(Value::as_bool) == Some(true) {
            Ok(response.get("data").cloned().unwrap_or(Value::Null))
        } else {
            Err(response
                .get("error")
                .and_then(Value::as_str)
                .unwrap_or("command failed")
                .to_owned())
        };
        let _ = reply_tx.send(reply);
    }

    /// Dialogs are cancelled, since Stubb cannot ask the user yet;
    /// notifications and status updates pass through as raw events.
    async fn extension_ui(&self, request: &Value) {
        let method = request.get("method").and_then(Value::as_str).unwrap_or("");
        if !DIALOGS.contains(&method) {
            self.emit(vec![session::Event::Raw {
                name: format!("pi/extension_ui/{method}"),
                payload: request.clone(),
            }]);
            return;
        }
        let events = self
            .state
            .lock()
            .expect("state lock")
            .dialog_declined(method, request.get("title").and_then(Value::as_str));
        self.emit(events);
        let id = request.get("id").cloned().unwrap_or(Value::Null);
        let _ = self
            .write(&json!({ "type": "extension_ui_response", "id": id, "cancelled": true }))
            .await;
    }

    /// Marks the process gone and fails pending commands. An exit Stubb did
    /// not ask for is reported to subscribers as a disconnect.
    fn close(&self) {
        let stderr = self
            .stderr_tail
            .lock()
            .expect("stderr lock")
            .trim()
            .to_owned();
        let reason = if stderr.is_empty() {
            "pi exited".to_owned()
        } else {
            format!("pi exited: {stderr}")
        };
        *self.closed.lock().expect("closed lock") = Some(reason.clone());
        self.pending.lock().expect("pending lock").clear();
        if !self.closing.load(Ordering::Relaxed) {
            self.emit(vec![session::Event::Closed {
                reason: session::CloseReason::Exited { message: reason },
            }]);
        }
    }
}

async fn read_loop(shared: Arc<Shared>, stdout: ChildStdout) {
    // Records are split on LF only: Unicode line separators are valid inside
    // Pi's JSON strings.
    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();
}