Skip to main content

pi_codes/
cli.rs

1//! Builder for `pi` invocations — assembles argv for `--mode json`
2//! one-shots and `--mode rpc` servers without hand-rolled string lists.
3
4use std::ffi::OsString;
5use std::path::PathBuf;
6
7/// Output mode (`--mode`).
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9pub enum Mode {
10    /// Interactive/plain text (the CLI default; rarely useful from an SDK).
11    Text,
12    /// One-shot JSONL event stream on stdout.
13    #[default]
14    Json,
15    /// Headless stdin/stdout command protocol ([`crate::rpc`]).
16    Rpc,
17}
18
19impl Mode {
20    fn as_str(self) -> &'static str {
21        match self {
22            Mode::Text => "text",
23            Mode::Json => "json",
24            Mode::Rpc => "rpc",
25        }
26    }
27}
28
29/// Typed argv builder for the `pi` CLI.
30///
31/// ```
32/// use pi_codes::cli::{Mode, PiCliBuilder};
33/// let args = PiCliBuilder::new()
34///     .mode(Mode::Rpc)
35///     .no_session(true)
36///     .assembled_args();
37/// assert_eq!(args[0], "--mode");
38/// ```
39#[derive(Debug, Clone, Default)]
40pub struct PiCliBuilder {
41    mode: Mode,
42    provider: Option<String>,
43    model: Option<String>,
44    api_key: Option<String>,
45    system_prompt: Option<String>,
46    session: Option<String>,
47    session_dir: Option<PathBuf>,
48    session_id: Option<String>,
49    fork: Option<String>,
50    continue_session: bool,
51    no_session: bool,
52    name: Option<String>,
53    no_tools: bool,
54    tools: Option<String>,
55    exclude_tools: Option<String>,
56    thinking: Option<String>,
57    print: bool,
58    approve: bool,
59    no_approve: bool,
60    offline: bool,
61    working_directory: Option<PathBuf>,
62    extra_args: Vec<OsString>,
63    prompt: Option<String>,
64}
65
66impl PiCliBuilder {
67    pub fn new() -> Self {
68        Self::default()
69    }
70
71    pub fn mode(mut self, mode: Mode) -> Self {
72        self.mode = mode;
73        self
74    }
75
76    /// Restrict `--model` lookup to one provider. pi 1.0.0+ rejects
77    /// `--provider` without `--model` (`Error: --provider requires --model`,
78    /// exit 1), so pair this with [`model`](Self::model).
79    pub fn provider(mut self, provider: impl Into<String>) -> Self {
80        self.provider = Some(provider.into());
81        self
82    }
83
84    pub fn model(mut self, model: impl Into<String>) -> Self {
85        self.model = Some(model.into());
86        self
87    }
88
89    /// API key for the provider. Prefer environment variables — argv is
90    /// visible to other processes; this exists for parity with the CLI.
91    pub fn api_key(mut self, key: impl Into<String>) -> Self {
92        self.api_key = Some(key.into());
93        self
94    }
95
96    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
97        self.system_prompt = Some(prompt.into());
98        self
99    }
100
101    /// `--session <path|id>` — use a specific session file or partial id.
102    pub fn session(mut self, session: impl Into<String>) -> Self {
103        self.session = Some(session.into());
104        self
105    }
106
107    pub fn session_dir(mut self, dir: impl Into<PathBuf>) -> Self {
108        self.session_dir = Some(dir.into());
109        self
110    }
111
112    /// `--session-id <id>` — exact project session id, created if missing.
113    pub fn session_id(mut self, id: impl Into<String>) -> Self {
114        self.session_id = Some(id.into());
115        self
116    }
117
118    /// `--fork <path|id>` — fork a session into a new one.
119    pub fn fork(mut self, source: impl Into<String>) -> Self {
120        self.fork = Some(source.into());
121        self
122    }
123
124    /// `--continue` — continue the previous session.
125    pub fn continue_session(mut self, enabled: bool) -> Self {
126        self.continue_session = enabled;
127        self
128    }
129
130    /// `--no-session` — ephemeral run, nothing persisted.
131    pub fn no_session(mut self, enabled: bool) -> Self {
132        self.no_session = enabled;
133        self
134    }
135
136    /// `--name` — session display name.
137    pub fn name(mut self, name: impl Into<String>) -> Self {
138        self.name = Some(name.into());
139        self
140    }
141
142    /// `--no-tools` — disable all tools.
143    pub fn no_tools(mut self, enabled: bool) -> Self {
144        self.no_tools = enabled;
145        self
146    }
147
148    /// `--tools` — comma-separated tool allowlist.
149    pub fn tools(mut self, tools: impl Into<String>) -> Self {
150        self.tools = Some(tools.into());
151        self
152    }
153
154    /// `--exclude-tools` — comma-separated tool denylist.
155    pub fn exclude_tools(mut self, tools: impl Into<String>) -> Self {
156        self.exclude_tools = Some(tools.into());
157        self
158    }
159
160    /// `--thinking` — off, minimal, low, medium, high, xhigh, max.
161    pub fn thinking(mut self, level: impl Into<String>) -> Self {
162        self.thinking = Some(level.into());
163        self
164    }
165
166    /// `--print` — non-interactive: process the prompt and exit.
167    pub fn print(mut self, enabled: bool) -> Self {
168        self.print = enabled;
169        self
170    }
171
172    /// `--approve` — trust project-local files (extensions, AGENTS.md)
173    /// for this run. Note pi has NO tool-approval gate: read/bash/edit/
174    /// write always run without prompting; this flag is only about
175    /// trusting local config.
176    pub fn approve(mut self, enabled: bool) -> Self {
177        self.approve = enabled;
178        self
179    }
180
181    /// `--no-approve` — ignore project-local files for this run.
182    pub fn no_approve(mut self, enabled: bool) -> Self {
183        self.no_approve = enabled;
184        self
185    }
186
187    /// `--offline` — disable startup network operations.
188    pub fn offline(mut self, enabled: bool) -> Self {
189        self.offline = enabled;
190        self
191    }
192
193    /// Working directory for the spawned process (not a pi flag — pi's
194    /// tools operate relative to its cwd). Used by
195    /// [`crate::client_async::PiRpcClient::spawn`].
196    pub fn working_directory(mut self, dir: impl Into<PathBuf>) -> Self {
197        self.working_directory = Some(dir.into());
198        self
199    }
200
201    /// The configured working directory, if any.
202    pub fn get_working_directory(&self) -> Option<&std::path::Path> {
203        self.working_directory.as_deref()
204    }
205
206    /// Escape hatch: raw args appended after every typed flag, before
207    /// the positional prompt.
208    pub fn extra_args<I, S>(mut self, args: I) -> Self
209    where
210        I: IntoIterator<Item = S>,
211        S: Into<OsString>,
212    {
213        self.extra_args.extend(args.into_iter().map(Into::into));
214        self
215    }
216
217    /// Positional prompt (used with `--mode json` one-shots).
218    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
219        self.prompt = Some(prompt.into());
220        self
221    }
222
223    /// The full argv (binary not included) — pure and testable.
224    pub fn assembled_args(&self) -> Vec<OsString> {
225        let mut a: Vec<OsString> = vec!["--mode".into(), self.mode.as_str().into()];
226        let mut flag = |name: &str, v: &Option<String>| {
227            if let Some(v) = v {
228                a.push(name.into());
229                a.push(v.into());
230            }
231        };
232        flag("--provider", &self.provider);
233        flag("--model", &self.model);
234        flag("--api-key", &self.api_key);
235        flag("--system-prompt", &self.system_prompt);
236        flag("--session", &self.session);
237        flag("--session-id", &self.session_id);
238        flag("--fork", &self.fork);
239        flag("--name", &self.name);
240        flag("--tools", &self.tools);
241        flag("--exclude-tools", &self.exclude_tools);
242        flag("--thinking", &self.thinking);
243        if let Some(dir) = &self.session_dir {
244            a.push("--session-dir".into());
245            a.push(dir.into());
246        }
247        if self.continue_session {
248            a.push("--continue".into());
249        }
250        if self.no_session {
251            a.push("--no-session".into());
252        }
253        if self.no_tools {
254            a.push("--no-tools".into());
255        }
256        if self.print {
257            a.push("--print".into());
258        }
259        if self.approve {
260            a.push("--approve".into());
261        }
262        if self.no_approve {
263            a.push("--no-approve".into());
264        }
265        if self.offline {
266            a.push("--offline".into());
267        }
268        a.extend(self.extra_args.iter().cloned());
269        if let Some(p) = &self.prompt {
270            a.push(p.into());
271        }
272        a
273    }
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    #[test]
281    fn assembled_args_order_flags_then_extras_then_prompt() {
282        let args = PiCliBuilder::new()
283            .mode(Mode::Json)
284            .provider("anthropic")
285            .no_session(true)
286            .extra_args(["--verbose"])
287            .prompt("hello")
288            .assembled_args();
289        let s: Vec<String> = args
290            .iter()
291            .map(|a| a.to_string_lossy().into_owned())
292            .collect();
293        assert_eq!(s[0..2], ["--mode", "json"]);
294        assert!(s.contains(&"--no-session".to_string()));
295        let vi = s.iter().position(|x| x == "--verbose").unwrap();
296        assert_eq!(s.last().unwrap(), "hello");
297        assert!(vi < s.len() - 1, "extras precede the positional prompt");
298    }
299
300    #[test]
301    fn rpc_mode_default_has_no_prompt() {
302        let args = PiCliBuilder::new().mode(Mode::Rpc).assembled_args();
303        assert_eq!(args.len(), 2);
304        assert_eq!(args[1], "rpc");
305    }
306}