Skip to main content

firstpass_proxy/
launch.rs

1//! `firstpass launch <agent> [args…]` — start a coding agent already pointed at this proxy.
2//!
3//! The env-var swap is one line, so a subcommand that only exported it would be a convenience and
4//! nothing more. What it actually buys is the **precondition**: pointing an agent at a proxy that
5//! is not listening produces a connection error from inside the agent's own error surface, which
6//! reads like the agent is broken rather than like the proxy is down. So this refuses to launch
7//! until `/healthz` answers, and says which of the two is wrong.
8//!
9//! It also refuses when something answers that is **not** Firstpass. A 200 on `/healthz` only
10//! proves the port is held; whatever else is listening on 8080 during development will happily
11//! answer it. Handing an agent that address would route every request past the gate to a stranger
12//! that may well reply — a failure that looks like success, which is the worse one.
13//!
14//! Uses `exec` on unix rather than spawning a child: the agent inherits this process's PID and
15//! terminal directly, so job control, `Ctrl-C`, and raw-mode TUIs behave exactly as they do when
16//! the agent is run by hand. A wrapper process in between breaks all three.
17
18use std::collections::HashMap;
19use std::process::Command;
20
21/// A launchable agent: which binary to run, and which base-url variable points it at a proxy.
22struct Agent {
23    /// The `firstpass launch <name>` name.
24    name: &'static str,
25    /// The executable to run, if it is not the same as `name`.
26    bin: &'static str,
27    /// Base-url env vars to set. More than one when the agent can talk to several vendors and we
28    /// want every one of them routed — a half-routed agent silently bypasses the gate.
29    vars: &'static [&'static str],
30}
31
32const AGENTS: &[Agent] = &[
33    Agent {
34        name: "claude",
35        bin: "claude",
36        vars: &["ANTHROPIC_BASE_URL"],
37    },
38    Agent {
39        name: "codex",
40        bin: "codex",
41        vars: &["OPENAI_BASE_URL"],
42    },
43    // Anything OpenAI-compatible: `firstpass launch openai -- <cmd> [args…]`.
44    Agent {
45        name: "openai",
46        bin: "",
47        vars: &["OPENAI_BASE_URL"],
48    },
49    // Gemini CLI (`gemini` binary from `google-gemini/gemini-cli`).
50    // Uses `GOOGLE_GEMINI_BASE_URL` with no path suffix — the SDK appends
51    // `/v1beta/models/{model}:generateContent` directly.
52    Agent {
53        name: "gemini",
54        bin: "gemini",
55        vars: &["GOOGLE_GEMINI_BASE_URL"],
56    },
57];
58
59/// Print a multi-line diagnostic and exit non-zero.
60///
61/// Returning `Box<dyn Error>` from `main` renders it with `Debug`, which turns every newline in a
62/// message into a literal `\n` — fine for a one-line error, unreadable for guidance that includes
63/// a command to run. These messages exist to be followed, so they are printed as written.
64fn fail(msg: &str) -> ! {
65    eprintln!("firstpass launch: {msg}");
66    std::process::exit(2)
67}
68
69/// Resolve the proxy's URL from the same variable the server binds on, so `launch` and `up` cannot
70/// disagree about where it is.
71#[must_use]
72pub fn base_url() -> String {
73    url_for_bind(&std::env::var("FIRSTPASS_BIND").unwrap_or_else(|_| "127.0.0.1:8080".to_owned()))
74}
75
76/// The client-reachable URL for a bind address. Pure, so the wildcard case is testable without
77/// touching process environment.
78fn url_for_bind(bind: &str) -> String {
79    // A wildcard bind is not an address a client can connect to.
80    let host = bind
81        .strip_prefix("0.0.0.0")
82        .map_or_else(|| bind.to_owned(), |port| format!("127.0.0.1{port}"));
83    format!("http://{host}")
84}
85
86/// Split `args` (everything after `launch`) into the agent name and the argv to hand the agent.
87/// A bare `--` separates our arguments from the agent's, so `firstpass launch claude -- -p 'hi'`
88/// passes `-p hi` through untouched.
89fn split(args: &[String]) -> (Option<&str>, Vec<String>) {
90    let mut rest = args.iter();
91    let name = rest.next().map(String::as_str);
92    let passthrough: Vec<String> = rest
93        .skip_while(|a| a.as_str() == "--")
94        .map(Clone::clone)
95        .collect();
96    (name, passthrough)
97}
98
99/// The env the agent should run with: every base-url var this agent needs, pointed at `url`.
100fn env_for(agent: &Agent, url: &str) -> HashMap<String, String> {
101    agent
102        .vars
103        .iter()
104        .map(|v| {
105            // OpenAI SDKs (and Codex) treat the base URL as already ending in `/v1` and append
106            // `/responses` or `/chat/completions`; Anthropic SDKs append `/v1/messages` themselves.
107            let base = if v.starts_with("OPENAI") {
108                format!("{url}/v1")
109            } else {
110                url.to_owned()
111            };
112            ((*v).to_owned(), base)
113        })
114        .collect()
115}
116
117/// What is listening at `url`.
118#[derive(Debug, PartialEq, Eq)]
119enum Listener {
120    /// Firstpass answered.
121    Firstpass,
122    /// Something answered, but it is not Firstpass. Routing an agent into it would send real
123    /// traffic to a stranger — a worse outcome than nothing listening, because it can look like it
124    /// is working.
125    Foreign,
126    /// Nothing reachable.
127    None,
128}
129
130/// Decide from a `/healthz` body whether we are talking to Firstpass. Split out so the
131/// discrimination is testable without a live port.
132fn classify(status_ok: bool, body: Option<&serde_json::Value>) -> Listener {
133    if !status_ok {
134        return Listener::None;
135    }
136    match body.and_then(|b| b.get("service")).and_then(|s| s.as_str()) {
137        Some("firstpass") => Listener::Firstpass,
138        _ => Listener::Foreign,
139    }
140}
141
142/// Probe `url` and say what is there.
143async fn probe(url: &str) -> Listener {
144    let Ok(client) = reqwest::Client::builder()
145        .timeout(std::time::Duration::from_secs(2))
146        .build()
147    else {
148        return Listener::None;
149    };
150    let Ok(resp) = client.get(format!("{url}/healthz")).send().await else {
151        return Listener::None;
152    };
153    let ok = resp.status().is_success();
154    let body = resp.json::<serde_json::Value>().await.ok();
155    classify(ok, body.as_ref())
156}
157
158/// Run `firstpass launch …`.
159///
160/// # Errors
161/// When no agent is named, the agent is unknown, the proxy is not listening, or the agent binary
162/// cannot be executed.
163pub async fn run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
164    let (name, passthrough) = split(args);
165    let Some(name) = name else {
166        let names: Vec<&str> = AGENTS.iter().map(|a| a.name).collect();
167        fail(&format!(
168            "firstpass launch <agent> [-- args…]\n  agents: {}\n\n\
169             `openai` needs an explicit command: firstpass launch openai -- <cmd> [args…]",
170            names.join(", ")
171        ));
172    };
173    let Some(agent) = AGENTS.iter().find(|a| a.name == name) else {
174        let names: Vec<&str> = AGENTS.iter().map(|a| a.name).collect();
175        fail(&format!(
176            "unknown agent {name:?} (known: {})",
177            names.join(", ")
178        ));
179    };
180
181    // The binary is the agent's own, unless this is the generic form, where the caller supplies it
182    // after `--`.
183    let (bin, argv) = if agent.bin.is_empty() {
184        let Some((first, rest)) = passthrough.split_first() else {
185            fail(&format!(
186                "`firstpass launch {name}` needs a command:\n\n    firstpass launch {name} -- <cmd> [args…]"
187            ));
188        };
189        (first.clone(), rest.to_vec())
190    } else {
191        (agent.bin.to_owned(), passthrough)
192    };
193
194    let url = base_url();
195    match probe(&url).await {
196        Listener::Firstpass => {}
197        Listener::None => {
198            fail(&format!(
199                "no proxy is listening at {url} — start one first:\n\n    firstpass up\n\n\
200                 (or `firstpass kiosk` to configure and start it in one press).\n\n\
201                 Launching into a proxy that is not up produces a connection error from inside \
202                 {bin}, which reads like {bin} is broken."
203            ));
204        }
205        Listener::Foreign => {
206            fail(&format!(
207                "something is listening at {url}, but it is not firstpass.\n\n\
208                 Refusing to launch {bin} against it: every request would go to that service \
209                 instead of through the gate, and it may well answer, so nothing would look \
210                 wrong.\n\n\
211                 Free the port, or point firstpass elsewhere and use the same address here:\n\n    \
212                 FIRSTPASS_BIND=127.0.0.1:8099 firstpass up\n    \
213                 FIRSTPASS_BIND=127.0.0.1:8099 firstpass launch {name}"
214            ));
215        }
216    }
217
218    let env = env_for(agent, &url);
219    for (k, v) in &env {
220        eprintln!("firstpass: {k}={v}");
221    }
222    eprintln!("firstpass: exec {bin}");
223
224    let mut cmd = Command::new(&bin);
225    cmd.args(&argv).envs(&env);
226
227    #[cfg(unix)]
228    {
229        // Replaces this process: the agent gets the terminal and PID directly, so Ctrl-C and TUI
230        // raw mode behave as if it had been run by hand. Only returns on failure.
231        use std::os::unix::process::CommandExt;
232        let err = cmd.exec();
233        Err(format!("could not exec {bin}: {err}. Is it installed and on PATH?").into())
234    }
235    #[cfg(not(unix))]
236    {
237        let status = cmd
238            .status()
239            .map_err(|e| format!("could not run {bin}: {e}. Is it installed and on PATH?"))?;
240        std::process::exit(status.code().unwrap_or(1));
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    #[test]
249    fn a_wildcard_bind_becomes_a_connectable_loopback_address() {
250        // 0.0.0.0 is a bind address, not somewhere a client can connect to. Handing it to an agent
251        // verbatim fails on some stacks and is never what was meant.
252        assert_eq!(url_for_bind("0.0.0.0:9090"), "http://127.0.0.1:9090");
253        assert_eq!(url_for_bind("127.0.0.1:7777"), "http://127.0.0.1:7777");
254    }
255
256    #[test]
257    fn a_foreign_service_holding_the_port_is_not_mistaken_for_firstpass() {
258        // Found by running this for real: an unrelated dev server was on :8080, answered /healthz
259        // 200, and the first version of this check launched an agent straight into it. Every
260        // request would have bypassed the gate while appearing to work.
261        let foreign = serde_json::json!({ "status": "ok", "llmMode": "api" });
262        assert_eq!(classify(true, Some(&foreign)), Listener::Foreign);
263
264        let ours =
265            serde_json::json!({ "status": "ok", "service": "firstpass", "version": "0.3.0" });
266        assert_eq!(classify(true, Some(&ours)), Listener::Firstpass);
267
268        // A body-less or unhealthy answer is not proof of anything.
269        assert_eq!(classify(false, Some(&ours)), Listener::None);
270        assert_eq!(classify(true, None), Listener::Foreign);
271    }
272
273    #[test]
274    fn a_bare_double_dash_separates_our_args_from_the_agents() {
275        let args: Vec<String> = ["claude", "--", "-p", "hi"]
276            .iter()
277            .map(|s| (*s).to_owned())
278            .collect();
279        let (name, rest) = split(&args);
280        assert_eq!(name, Some("claude"));
281        assert_eq!(rest, vec!["-p".to_owned(), "hi".to_owned()]);
282    }
283
284    #[test]
285    fn agent_args_survive_without_a_separator_too() {
286        let args: Vec<String> = ["claude", "-p", "hi"]
287            .iter()
288            .map(|s| (*s).to_owned())
289            .collect();
290        let (_, rest) = split(&args);
291        assert_eq!(rest, vec!["-p".to_owned(), "hi".to_owned()]);
292    }
293
294    #[test]
295    fn each_agent_routes_the_vendor_it_actually_speaks() {
296        // A wrong variable here is the worst failure mode this module has: the agent starts fine,
297        // talks straight to the vendor, and every call silently bypasses the gate.
298        let claude = AGENTS.iter().find(|a| a.name == "claude").expect("claude");
299        assert_eq!(
300            env_for(claude, "http://127.0.0.1:8080").get("ANTHROPIC_BASE_URL"),
301            Some(&"http://127.0.0.1:8080".to_owned())
302        );
303        let codex = AGENTS.iter().find(|a| a.name == "codex").expect("codex");
304        assert_eq!(
305            env_for(codex, "http://127.0.0.1:8080").get("OPENAI_BASE_URL"),
306            Some(&"http://127.0.0.1:8080/v1".to_owned())
307        );
308        // Gemini CLI: GOOGLE_GEMINI_BASE_URL must NOT have /v1 appended — the SDK constructs
309        // `/v1beta/models/{model}:generateContent` from the base itself.
310        let gemini = AGENTS.iter().find(|a| a.name == "gemini").expect("gemini");
311        assert_eq!(
312            env_for(gemini, "http://127.0.0.1:8080").get("GOOGLE_GEMINI_BASE_URL"),
313            Some(&"http://127.0.0.1:8080".to_owned()),
314            "GOOGLE_GEMINI_BASE_URL must point at the proxy root, not /v1"
315        );
316        // mutant: if we add /v1 to GOOGLE vars, this assertion fails
317    }
318}