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];
50
51/// Print a multi-line diagnostic and exit non-zero.
52///
53/// Returning `Box<dyn Error>` from `main` renders it with `Debug`, which turns every newline in a
54/// message into a literal `\n` — fine for a one-line error, unreadable for guidance that includes
55/// a command to run. These messages exist to be followed, so they are printed as written.
56fn fail(msg: &str) -> ! {
57    eprintln!("firstpass launch: {msg}");
58    std::process::exit(2)
59}
60
61/// Resolve the proxy's URL from the same variable the server binds on, so `launch` and `up` cannot
62/// disagree about where it is.
63#[must_use]
64pub fn base_url() -> String {
65    url_for_bind(&std::env::var("FIRSTPASS_BIND").unwrap_or_else(|_| "127.0.0.1:8080".to_owned()))
66}
67
68/// The client-reachable URL for a bind address. Pure, so the wildcard case is testable without
69/// touching process environment.
70fn url_for_bind(bind: &str) -> String {
71    // A wildcard bind is not an address a client can connect to.
72    let host = bind
73        .strip_prefix("0.0.0.0")
74        .map_or_else(|| bind.to_owned(), |port| format!("127.0.0.1{port}"));
75    format!("http://{host}")
76}
77
78/// Split `args` (everything after `launch`) into the agent name and the argv to hand the agent.
79/// A bare `--` separates our arguments from the agent's, so `firstpass launch claude -- -p 'hi'`
80/// passes `-p hi` through untouched.
81fn split(args: &[String]) -> (Option<&str>, Vec<String>) {
82    let mut rest = args.iter();
83    let name = rest.next().map(String::as_str);
84    let passthrough: Vec<String> = rest
85        .skip_while(|a| a.as_str() == "--")
86        .map(Clone::clone)
87        .collect();
88    (name, passthrough)
89}
90
91/// The env the agent should run with: every base-url var this agent needs, pointed at `url`.
92fn env_for(agent: &Agent, url: &str) -> HashMap<String, String> {
93    agent
94        .vars
95        .iter()
96        .map(|v| ((*v).to_owned(), url.to_owned()))
97        .collect()
98}
99
100/// What is listening at `url`.
101#[derive(Debug, PartialEq, Eq)]
102enum Listener {
103    /// Firstpass answered.
104    Firstpass,
105    /// Something answered, but it is not Firstpass. Routing an agent into it would send real
106    /// traffic to a stranger — a worse outcome than nothing listening, because it can look like it
107    /// is working.
108    Foreign,
109    /// Nothing reachable.
110    None,
111}
112
113/// Decide from a `/healthz` body whether we are talking to Firstpass. Split out so the
114/// discrimination is testable without a live port.
115fn classify(status_ok: bool, body: Option<&serde_json::Value>) -> Listener {
116    if !status_ok {
117        return Listener::None;
118    }
119    match body.and_then(|b| b.get("service")).and_then(|s| s.as_str()) {
120        Some("firstpass") => Listener::Firstpass,
121        _ => Listener::Foreign,
122    }
123}
124
125/// Probe `url` and say what is there.
126async fn probe(url: &str) -> Listener {
127    let Ok(client) = reqwest::Client::builder()
128        .timeout(std::time::Duration::from_secs(2))
129        .build()
130    else {
131        return Listener::None;
132    };
133    let Ok(resp) = client.get(format!("{url}/healthz")).send().await else {
134        return Listener::None;
135    };
136    let ok = resp.status().is_success();
137    let body = resp.json::<serde_json::Value>().await.ok();
138    classify(ok, body.as_ref())
139}
140
141/// Run `firstpass launch …`.
142///
143/// # Errors
144/// When no agent is named, the agent is unknown, the proxy is not listening, or the agent binary
145/// cannot be executed.
146pub async fn run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
147    let (name, passthrough) = split(args);
148    let Some(name) = name else {
149        let names: Vec<&str> = AGENTS.iter().map(|a| a.name).collect();
150        fail(&format!(
151            "firstpass launch <agent> [-- args…]\n  agents: {}\n\n\
152             `openai` needs an explicit command: firstpass launch openai -- <cmd> [args…]",
153            names.join(", ")
154        ));
155    };
156    let Some(agent) = AGENTS.iter().find(|a| a.name == name) else {
157        let names: Vec<&str> = AGENTS.iter().map(|a| a.name).collect();
158        fail(&format!(
159            "unknown agent {name:?} (known: {})",
160            names.join(", ")
161        ));
162    };
163
164    // The binary is the agent's own, unless this is the generic form, where the caller supplies it
165    // after `--`.
166    let (bin, argv) = if agent.bin.is_empty() {
167        let Some((first, rest)) = passthrough.split_first() else {
168            fail(&format!(
169                "`firstpass launch {name}` needs a command:\n\n    firstpass launch {name} -- <cmd> [args…]"
170            ));
171        };
172        (first.clone(), rest.to_vec())
173    } else {
174        (agent.bin.to_owned(), passthrough)
175    };
176
177    let url = base_url();
178    match probe(&url).await {
179        Listener::Firstpass => {}
180        Listener::None => {
181            fail(&format!(
182                "no proxy is listening at {url} — start one first:\n\n    firstpass up\n\n\
183                 (or `firstpass kiosk` to configure and start it in one press).\n\n\
184                 Launching into a proxy that is not up produces a connection error from inside \
185                 {bin}, which reads like {bin} is broken."
186            ));
187        }
188        Listener::Foreign => {
189            fail(&format!(
190                "something is listening at {url}, but it is not firstpass.\n\n\
191                 Refusing to launch {bin} against it: every request would go to that service \
192                 instead of through the gate, and it may well answer, so nothing would look \
193                 wrong.\n\n\
194                 Free the port, or point firstpass elsewhere and use the same address here:\n\n    \
195                 FIRSTPASS_BIND=127.0.0.1:8099 firstpass up\n    \
196                 FIRSTPASS_BIND=127.0.0.1:8099 firstpass launch {name}"
197            ));
198        }
199    }
200
201    let env = env_for(agent, &url);
202    for (k, v) in &env {
203        eprintln!("firstpass: {k}={v}");
204    }
205    eprintln!("firstpass: exec {bin}");
206
207    let mut cmd = Command::new(&bin);
208    cmd.args(&argv).envs(&env);
209
210    #[cfg(unix)]
211    {
212        // Replaces this process: the agent gets the terminal and PID directly, so Ctrl-C and TUI
213        // raw mode behave as if it had been run by hand. Only returns on failure.
214        use std::os::unix::process::CommandExt;
215        let err = cmd.exec();
216        Err(format!("could not exec {bin}: {err}. Is it installed and on PATH?").into())
217    }
218    #[cfg(not(unix))]
219    {
220        let status = cmd
221            .status()
222            .map_err(|e| format!("could not run {bin}: {e}. Is it installed and on PATH?"))?;
223        std::process::exit(status.code().unwrap_or(1));
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    #[test]
232    fn a_wildcard_bind_becomes_a_connectable_loopback_address() {
233        // 0.0.0.0 is a bind address, not somewhere a client can connect to. Handing it to an agent
234        // verbatim fails on some stacks and is never what was meant.
235        assert_eq!(url_for_bind("0.0.0.0:9090"), "http://127.0.0.1:9090");
236        assert_eq!(url_for_bind("127.0.0.1:7777"), "http://127.0.0.1:7777");
237    }
238
239    #[test]
240    fn a_foreign_service_holding_the_port_is_not_mistaken_for_firstpass() {
241        // Found by running this for real: an unrelated dev server was on :8080, answered /healthz
242        // 200, and the first version of this check launched an agent straight into it. Every
243        // request would have bypassed the gate while appearing to work.
244        let foreign = serde_json::json!({ "status": "ok", "llmMode": "api" });
245        assert_eq!(classify(true, Some(&foreign)), Listener::Foreign);
246
247        let ours =
248            serde_json::json!({ "status": "ok", "service": "firstpass", "version": "0.3.0" });
249        assert_eq!(classify(true, Some(&ours)), Listener::Firstpass);
250
251        // A body-less or unhealthy answer is not proof of anything.
252        assert_eq!(classify(false, Some(&ours)), Listener::None);
253        assert_eq!(classify(true, None), Listener::Foreign);
254    }
255
256    #[test]
257    fn a_bare_double_dash_separates_our_args_from_the_agents() {
258        let args: Vec<String> = ["claude", "--", "-p", "hi"]
259            .iter()
260            .map(|s| (*s).to_owned())
261            .collect();
262        let (name, rest) = split(&args);
263        assert_eq!(name, Some("claude"));
264        assert_eq!(rest, vec!["-p".to_owned(), "hi".to_owned()]);
265    }
266
267    #[test]
268    fn agent_args_survive_without_a_separator_too() {
269        let args: Vec<String> = ["claude", "-p", "hi"]
270            .iter()
271            .map(|s| (*s).to_owned())
272            .collect();
273        let (_, rest) = split(&args);
274        assert_eq!(rest, vec!["-p".to_owned(), "hi".to_owned()]);
275    }
276
277    #[test]
278    fn each_agent_routes_the_vendor_it_actually_speaks() {
279        // A wrong variable here is the worst failure mode this module has: the agent starts fine,
280        // talks straight to the vendor, and every call silently bypasses the gate.
281        let claude = AGENTS.iter().find(|a| a.name == "claude").expect("claude");
282        assert_eq!(
283            env_for(claude, "http://127.0.0.1:8080").get("ANTHROPIC_BASE_URL"),
284            Some(&"http://127.0.0.1:8080".to_owned())
285        );
286        let codex = AGENTS.iter().find(|a| a.name == "codex").expect("codex");
287        assert_eq!(
288            env_for(codex, "http://127.0.0.1:8080").get("OPENAI_BASE_URL"),
289            Some(&"http://127.0.0.1:8080".to_owned())
290        );
291    }
292}