Skip to main content

objectiveai_sdk/cli/command/command_executor/
binary.rs

1use std::path::PathBuf;
2use std::pin::Pin;
3
4use futures::{Stream, StreamExt};
5use tokio::io::{AsyncBufReadExt, BufReader};
6use tokio::process::Command;
7
8use crate::identity::Identity;
9use crate::cli::command::{CommandExecutor, CommandRequest, CommandResponse};
10
11/// Spawn the `objectiveai` cli binary on disk, feed it the argv from
12/// `request.into_command()`, and stream each stdout JSONL line back as
13/// either a typed `T` or a structured [`crate::cli::Error`].
14///
15/// The binary is resolved at `execute` time (not at construction).
16/// Resolution order:
17///
18/// - [`BinaryExecutor::from_path`] — returns the explicit path verbatim
19///   (used by tests pointing at an out-of-tree build).
20/// - [`BinaryExecutor::new`] with `Some(objectiveai_dir)` —
21///   `<objectiveai_dir>/bin/objectiveai{.exe}`.
22/// - [`BinaryExecutor::new`] with `None` —
23///   `<home>/.objectiveai/bin/objectiveai{.exe}`.
24pub struct BinaryExecutor {
25    /// The layout root (`OBJECTIVEAI_DIR`); the binary inside is
26    /// always `bin/objectiveai{.exe}`. `None` falls back to the
27    /// home-dir default (`~/.objectiveai`).
28    objectiveai_dir: Option<PathBuf>,
29    /// When set, used verbatim and the `objectiveai_dir` lookup is
30    /// skipped entirely. Lets callers (notably tests) point the
31    /// executor at any binary by absolute path without enforcing the
32    /// `<dir>/objectiveai` naming convention.
33    explicit_path: Option<PathBuf>,
34    /// Extra environment variables to set on the spawned child. Stacks
35    /// on top of the parent's environment (the child inherits the rest
36    /// — this map only overrides). Set via [`Self::env`].
37    extra_env: Vec<(String, String)>,
38    /// When `true`, the spawned child is sent a kill signal whenever
39    /// the [`tokio::process::Child`] held in the stream state is
40    /// dropped. Defaults to `false` (the SDK's long-standing
41    /// behaviour: drop-without-kill lets the child finish its work
42    /// orphaned). Set via [`Self::kill_on_drop`]. Test wrappers that
43    /// want to abort hung children (e.g. cli-test
44    /// `HangPreventingBinaryCommandExecutor`) flip this on.
45    kill_on_drop: bool,
46    /// When `true`, spawn the child detached from the parent's console
47    /// / process group so it survives the parent process exiting.
48    /// Unix already does this automatically when the parent dies
49    /// (kernel re-parents to init). Windows needs explicit
50    /// `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP` creation flags;
51    /// otherwise the child's inherited console closes with the parent
52    /// and the child gets a `CTRL_CLOSE_EVENT`. Defaults to `false`.
53    detach: bool,
54}
55
56impl BinaryExecutor {
57    pub fn new(objectiveai_dir: Option<impl Into<PathBuf>>) -> Self {
58        Self {
59            objectiveai_dir: objectiveai_dir.map(Into::into),
60            explicit_path: None,
61            extra_env: Vec::new(),
62            kill_on_drop: false,
63            detach: false,
64        }
65    }
66
67    /// Construct an executor that spawns the binary at `binary`
68    /// directly, regardless of file name. Skips the `objectiveai`
69    /// name lookup so tests can target a `target/debug/objectiveai-cli`
70    /// build without renaming or symlinking.
71    pub fn from_path(binary: impl Into<PathBuf>) -> Self {
72        Self {
73            objectiveai_dir: None,
74            explicit_path: Some(binary.into()),
75            extra_env: Vec::new(),
76            kill_on_drop: false,
77            detach: false,
78        }
79    }
80
81
82    /// Set an environment variable on every child the executor spawns.
83    /// Stacks on top of the parent's env; intended for tests that need
84    /// to pin a per-instance `OBJECTIVEAI_DIR`/`OBJECTIVEAI_STATE` or `OBJECTIVEAI_ADDRESS`
85    /// without racing other parallel tests via `std::env::set_var`.
86    pub fn env(
87        mut self,
88        key: impl Into<String>,
89        value: impl Into<String>,
90    ) -> Self {
91        self.extra_env.push((key.into(), value.into()));
92        self
93    }
94
95    /// When `true`, the spawned [`tokio::process::Child`] held in the
96    /// stream state is sent a kill signal when the stream is dropped.
97    /// Defaults to `false`. Wrappers that detect hangs (e.g. the
98    /// cli-test `HangPreventingBinaryCommandExecutor`) toggle this on
99    /// so dropping the inner stream tears the cli child down.
100    pub fn kill_on_drop(mut self, on: bool) -> Self {
101        self.kill_on_drop = on;
102        self
103    }
104
105    /// When `true`, the child is spawned detached from the parent's
106    /// console / process group so it survives parent exit. Pairs
107    /// naturally with `kill_on_drop = false` (the default): drop the
108    /// stream + exit the parent, the child keeps running orphaned.
109    ///
110    /// - **Windows**: sets `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP`
111    ///   on the `CreateProcessW` call. `DETACHED_PROCESS` is what
112    ///   actually makes orphan survival work — without it the child
113    ///   inherits the parent's console and receives `CTRL_CLOSE_EVENT`
114    ///   when the parent's console window closes. The process-group
115    ///   flag is belt-and-suspenders signal isolation.
116    /// - **Unix**: no-op. The kernel automatically re-parents the
117    ///   child to init when the parent exits.
118    ///
119    /// Defaults to `false`.
120    pub fn detach(mut self, on: bool) -> Self {
121        self.detach = on;
122        self
123    }
124
125    fn binary_path(&self) -> Result<PathBuf, Error> {
126        if let Some(p) = &self.explicit_path {
127            return Ok(p.clone());
128        }
129        let dir = match &self.objectiveai_dir {
130            Some(d) => d.clone(),
131            None => dirs::home_dir()
132                .ok_or(Error::NoHomeDir)?
133                .join(".objectiveai"),
134        };
135        let name = if cfg!(windows) { "objectiveai.exe" } else { "objectiveai" };
136        Ok(dir.join("bin").join(name))
137    }
138}
139
140#[derive(Debug, thiserror::Error)]
141pub enum Error {
142    /// `dirs::home_dir()` returned `None` and no `objectiveai_dir` was set.
143    #[error("no home directory and no objectiveai_dir set")]
144    NoHomeDir,
145    /// Failed to spawn the binary at the resolved path.
146    #[error("failed to spawn cli binary: {0}")]
147    Spawn(std::io::Error),
148    /// Child stdout was unexpectedly absent after spawn.
149    #[error("cli binary child has no stdout handle")]
150    NoStdout,
151    /// Reading stdout line failed.
152    #[error("read cli binary stdout: {0}")]
153    Io(std::io::Error),
154    /// Stdout produced a line that didn't deserialize as either the
155    /// structured `cli::Error` or `T`.
156    #[error("decode cli binary stdout line: {0}")]
157    Json(serde_json::Error),
158    /// Structured error emitted by the cli binary on stdout.
159    #[error("{0}")]
160    Cli(crate::cli::Error),
161    /// `execute_one` was called but the stream produced no items.
162    #[error("cli binary stream produced no items")]
163    Empty,
164}
165
166/// Per-line untagged decode. `Err` is listed first so serde tries it
167/// before `Ok` — `cli::Error`'s `type:"error"` constant short-circuits
168/// every non-error wire shape, then `Ok(T)` is the fallthrough.
169#[derive(serde::Deserialize)]
170#[serde(untagged)]
171enum Line<T> {
172    Err(crate::cli::Error),
173    Ok(T),
174}
175
176impl<T> From<Line<T>> for Result<T, Error> {
177    fn from(line: Line<T>) -> Self {
178        match line {
179            Line::Err(e) => Err(Error::Cli(e)),
180            Line::Ok(t) => Ok(t),
181        }
182    }
183}
184
185impl CommandExecutor for BinaryExecutor {
186    type Error = Error;
187    type Stream<T>
188        = Pin<Box<dyn Stream<Item = Result<T, Error>> + Send>>
189    where
190        T: Send + 'static;
191
192    async fn execute<R, T>(
193        &self,
194        request: R,
195        identity: Option<&Identity>,
196    ) -> Result<Self::Stream<T>, Error>
197    where
198        R: CommandRequest + Send + serde::Serialize,
199        T: CommandResponse + serde::Serialize + serde::de::DeserializeOwned + Send + 'static,
200    {
201        // Dispatch the typed request as JSON via the cli's top-level
202        // `--request` flag — request -> argv lowering no longer exists.
203        let argv = vec![
204            "--request".to_string(),
205            serde_json::to_string(&request).map_err(Error::Json)?,
206        ];
207        let binary = self.binary_path()?;
208
209        let mut command = Command::new(&binary);
210        crate::process::no_window(&mut command);
211        command
212            .args(&argv)
213            .stdin(std::process::Stdio::null())
214            .stdout(std::process::Stdio::piped())
215            .stderr(std::process::Stdio::inherit())
216            .kill_on_drop(self.kill_on_drop);
217        for (k, v) in &self.extra_env {
218            command.env(k, v);
219        }
220        // Windows detach. Required for orphan-survival when the
221        // parent will exit before the child finishes — without
222        // `DETACHED_PROCESS` the child inherits the parent's
223        // console and dies on `CTRL_CLOSE_EVENT` when the
224        // parent's console closes. We've hit this bug twice in
225        // the past; preserve the flag. Unix gets re-parent-to-init
226        // for free.
227        #[cfg(windows)]
228        if self.detach {
229            const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
230            const DETACHED_PROCESS: u32 = 0x0000_0008;
231            command.creation_flags(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS);
232        }
233        // Per-call agent identity override. When `Some`, every field
234        // gets applied atomically: `Some(v)` → set, `None` →
235        // env_remove so the parent's value can't leak through. When
236        // the bag itself is `None`, parent env is inherited
237        // untouched.
238        if let Some(args) = identity {
239            args.apply_to_command(&mut command);
240        }
241        // Keep OUR OWN std handles out of the child (and thus out of
242        // any resident server the child goes on to spawn): a leaked
243        // copy of our stdout's write end in a long-lived grandchild
244        // means whoever pipes us never sees EOF after we exit. See
245        // `win_handles::disinherit_std_handles`. Our explicit pipes to
246        // this child and its inherited stderr are unaffected.
247        #[cfg(windows)]
248        crate::win_handles::disinherit_std_handles();
249        let mut child = command.spawn().map_err(Error::Spawn)?;
250
251        let stdout = child.stdout.take().ok_or(Error::NoStdout)?;
252        let lines = BufReader::new(stdout).lines();
253
254        // Carry `child` in the unfold state so its handle isn't dropped
255        // mid-stream. tokio's Child defaults to kill_on_drop = false,
256        // so on stream drop the child remains running until it finishes.
257        let stream = futures::stream::unfold(
258            (child, lines),
259            |(child, mut lines)| async move {
260                match lines.next_line().await {
261                    Ok(Some(line)) => {
262                        let item = match serde_json::from_str::<Line<T>>(&line) {
263                            Ok(line) => line.into(),
264                            Err(e) => Err(Error::Json(e)),
265                        };
266                        Some((item, (child, lines)))
267                    }
268                    Ok(None) => None,
269                    Err(e) => Some((Err(Error::Io(e)), (child, lines))),
270                }
271            },
272        );
273
274        Ok(Box::pin(stream))
275    }
276
277    async fn execute_one<R, T>(
278        &self,
279        request: R,
280        identity: Option<&Identity>,
281    ) -> Result<T, Error>
282    where
283        R: CommandRequest + Send + serde::Serialize,
284        T: CommandResponse + serde::Serialize + serde::de::DeserializeOwned + Send + 'static,
285    {
286        let mut stream = self.execute::<R, T>(request, identity).await?;
287        stream.next().await.ok_or(Error::Empty)?
288    }
289}