From c41691c33d7103f35d87242e9d8fd31b6c6034cd Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 15:20:14 -0600 Subject: [PATCH] fleet: codify the laptop route forms T0-T7 (#13717) New domains: laptop (T0, the generic tiered command walking T1->T2->T3 and reporting the serving tier), commander (T1, Desktop Commander MCP client; #13654), http (T2, the daemon HTTP API over an HTTP-only ladder), ssh (T3, binary-owned ssh client contract). Timeouts required by construction on every form; every result names the form that served it. Raw forms T4-T6 and the laptop-ssh wrapper (T7) are codified in the design record (doc/2026-11-23T21-18-54Z_design_laptop_route_forms) and the mechanics doc; laptop-ssh is demoted by documentation-and-defaults, not removed. DOC-01: registry, README inventory, docs/verbs.md and the book chapter updated in the same change. --- ...-23T21-18-54Z_design_laptop_route_forms.md | 129 +++++ pkgs/fleet/README.md | 5 +- pkgs/fleet/book/SUMMARY.md | 1 + .../book/reference/laptop-route-forms.md | 79 +++ .../crates/fleet-laptop-agent/src/legs.rs | 22 + pkgs/fleet/crates/fleet-registry/src/lib.rs | 53 ++ pkgs/fleet/crates/fleet/Cargo.toml | 12 + pkgs/fleet/crates/fleet/src/commander.rs | 520 ++++++++++++++++++ pkgs/fleet/crates/fleet/src/forms.rs | 148 +++++ pkgs/fleet/crates/fleet/src/http.rs | 309 +++++++++++ pkgs/fleet/crates/fleet/src/laptop.rs | 203 +++++++ pkgs/fleet/crates/fleet/src/main.rs | 46 ++ pkgs/fleet/crates/fleet/src/ssh.rs | 231 ++++++++ pkgs/fleet/docs/verbs.md | 51 ++ 14 files changed, 1808 insertions(+), 1 deletion(-) create mode 100644 doc/2026-11-23T21-18-54Z_design_laptop_route_forms/2026-11-23T21-18-54Z_design_laptop_route_forms.md create mode 100644 pkgs/fleet/book/reference/laptop-route-forms.md create mode 100644 pkgs/fleet/crates/fleet/src/commander.rs create mode 100644 pkgs/fleet/crates/fleet/src/forms.rs create mode 100644 pkgs/fleet/crates/fleet/src/http.rs create mode 100644 pkgs/fleet/crates/fleet/src/laptop.rs create mode 100644 pkgs/fleet/crates/fleet/src/ssh.rs diff --git a/doc/2026-11-23T21-18-54Z_design_laptop_route_forms/2026-11-23T21-18-54Z_design_laptop_route_forms.md b/doc/2026-11-23T21-18-54Z_design_laptop_route_forms/2026-11-23T21-18-54Z_design_laptop_route_forms.md new file mode 100644 index 0000000000..8ea9de4107 --- /dev/null +++ b/doc/2026-11-23T21-18-54Z_design_laptop_route_forms/2026-11-23T21-18-54Z_design_laptop_route_forms.md @@ -0,0 +1,129 @@ +# Laptop route forms — the codified matrix (T0–T7) + +Design record for developing-today/code#13717 (companion: #13654). +Direction: Drew, 2026-11-23 14:56 + 14:59 + 15:07 CST. + +## Why a matrix, not a ladder + +The platform execution-risk behaviour observed on 2026-11-23 keys on +the **literal command shape** an agent runs: the same laptop +operation returned via one route comes back clean, via another +trips the check. A single opaque command that papers over every +route would hide which form actually works for a given operation, +and would remove the raw forms an agent sometimes needs when the +wrapper itself is the obstacle. So the raw commands are first-class +tiers, not implementation details — and tier 0, the one generic +command, still reports exactly which tier served the call. + +## The codified matrix + +| Tier | Method | Shape | Literal command | +|---|---|---|---| +| T0 | tiered | fleet subcommand | `fleet laptop exec [--timeout S] -- cmd...` — walks T1 → T2 → T3 internally, reports the serving tier | +| T1 | commander | fleet subcommand | `fleet commander exec [--cwd D] --timeout S -- cmd...` | +| T2 | http-direct | fleet subcommand | `fleet http exec [--cwd D] --timeout S -- cmd...` | +| T3 | ssh | fleet subcommand | `fleet ssh exec [--cwd D] --timeout S -- cmd...` | +| T4 | commander | raw command | the documented curl recipe against `https://commander.security.cab/mcp` | +| T5 | http-direct | raw command | literal curl to the daemon API through the session proxy | +| T6 | ssh | raw command | the literal `ssh` invocation written out in `TOOLS.d/laptop.md` | +| T7 | wrapper | simplified tier | `laptop-ssh 'cmd...'` — final fallback, and the one-command form for an agent without the full matrix | + +**Composition.** Tier 0 is the first option. It attempts T1 → T2 → +T3 in order, each attempt a literal invocation of that tier's own +implementation, advancing only when a tier fails to *serve* +(transport / auth / connect failure or a tier-level timeout) — +never on a served result, whatever its exit code — and it names +the serving tier. Tier 0 does **not** fall through to the wrapper: +when tier 0 fails, the individual forms come into play as their +own literal commands — the fleet subcommands (T1–T3) again, +because an attempt under tier 0's process shape is a different +literal invocation than the standalone subcommand — then the raw +commands (T4–T6), then the wrapper (T7). + +One recorded casualty of the walk rule: ssh's own failure exit is +255, so tier 0 reads a remote command that itself exits 255 over +ssh as a tier failure. Standalone `fleet ssh` propagates 255 +untouched; only the walker applies the convention. + +## Endpoint-grade contracts (the commander pattern, all three methods) + +- **Commander (T1)** — `crates/fleet/src/commander.rs`. Bearer + resolved in-process from the secrets broker by name + (`desktop-commander.machine-bearer`), never stored; browser UA + (the edge 1010-blocks non-browser agents, #13404); one MCP + session per invocation; `timeout_ms` always sent; spawned + processes polled to completion or force-terminated on the + deadline — no orphaned processes on the laptop; the remote exit + code is read from the endpoint's own completion line. +- **HTTP (T2)** — `crates/fleet/src/http.rs` over the + fleet-laptop-agent client. The daemon is the endpoint; this is + its contract surface: token auth from the token file, the + primary-checkout guard applied before anything is sent (a guard + refusal is a *served* result — tier 0 must not route around it), + daemon `timeout_s` plus the transport grace as the local + deadline, exit codes from the daemon reply. The ladder is built + HTTP-only (`legs::http_ladder`: broker socket → Cloudflare + tunnel → Tailscale CONNECT) — the SSH leg is excluded by + construction, so T2 can never silently become T3. +- **SSH (T3)** — `crates/fleet/src/ssh.rs`. The endpoint-grade + shape for SSH is a **binary-owned client contract**: the binary + constructs the ssh invocation itself (pinned host key in + `~/.ssh/known_hosts_laptop`, `StrictHostKeyChecking=yes`, proxy + CONNECT helper, `IdentitiesOnly`, `ConnectTimeout`) instead of + delegating to a shell script; a mandatory overall deadline + enforced by the binary (child kill → exit 124). Honest limit: + sshd owns the remote process, so a client-side kill ends the + session but cannot cancel the remote command protocol-side. + Session hygiene: a fleet-owned ControlMaster path + (`~/.ssh/cm-fleet-…`, persist 600 s — separate from laptop-ssh's + master) and `fleet ssh close` to tear it down. A native + in-process SSH protocol implementation is the recorded horizon, + not this build. + +Timeouts are required by construction on every fleet-shape form: +there is no invocation path without one (T0 sets a per-attempt +timeout, default 120 s; T1 default 120 s; T2 and T3 default 300 s). + +## Selection doctrine + +- Circumstance decides which form is the right way through. There + is no single blessed invocation. +- An agent tries each form as **its own literal command** — never + a blended invocation. +- **Form visibility**: every result and log line names the exact + form used, as method × shape (`form T2 http/fleet`, + `form T4 commander/raw`). The fleet forms announce themselves on + stderr; tier 0 narrates each attempt and the serving tier. +- Raw forms must exist, stay documented, and stay exercised — + they are the route around a wrapper that has itself become the + obstacle. Their literal recipes live in `TOOLS.d/laptop.md`. + +## The demotion of `laptop-ssh` (T7) + +Documentation-and-defaults, not removal. `laptop-ssh` keeps working +for every existing caller — it is load-bearing in the heal/init +stack (the channel-heal and init-ensure scripts delegate through +it), in crons, and in lane habits. What changes: the mechanics doc +and the shim's own header teach the matrix and the tier-0-first +order, and name `laptop-ssh` as tier T7 — the fallback when the +fleet tiers fail, and the simplified tier for an agent that +doesn't carry the full list: one command that does something sane. + +## Recorded horizon (Drew, 2026-11-23) + +Longer-term design threads named alongside this codification, not +part of this build: host selection and access without Tailscale; a +direct iroh transport for non-Muse agents; a generic pooling +system. + +## Verification (2026-11-23) + +Built in the `pkgs/fleet` workspace (features `commander`, `http`, +`ssh`, `laptop`, all in `full`); `cargo test` green across +fleet-registry, fleet-laptop-agent and the fleet binary (including +the DOC-01 inventory test, which now lists the four new domains). +Smoke from the sandbox with the built binary: every fleet form ran +`hostname` → `amd`, read `/etc/hostname`, and propagated a remote +`exit 3` as exit 3, naming its form; the raw forms ran as written +in `TOOLS.d/laptop.md`. The seat-wide install rides the next +fleet-static publish; nothing was installed over the seat binary. diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md index 9b0f8ec110..24658d0e2d 100644 --- a/pkgs/fleet/README.md +++ b/pkgs/fleet/README.md @@ -304,7 +304,10 @@ and every build compiles it, so no build can know a domain another build forgot. The registered domains are `fleet queue`, `fleet serve`, `fleet proxy`, `fleet dispatch`, `fleet dispatch-test`, `fleet secrets`, `fleet gh`, `fleet bridge`, `fleet agent`, -`fleet shell`, `fleet search` and `fleet laptop-agent`, plus the +`fleet shell`, `fleet search` and `fleet laptop-agent`, and the +laptop route forms (#13717): `fleet laptop` (tier T0, the generic +tiered command), `fleet commander` (T1), `fleet http` (T2) and +`fleet ssh` (T3), plus the built-ins `fleet init`, `fleet session`, `fleet version`, `fleet capabilities` and `fleet help`. diff --git a/pkgs/fleet/book/SUMMARY.md b/pkgs/fleet/book/SUMMARY.md index a7fa19a99d..5b61eb9298 100644 --- a/pkgs/fleet/book/SUMMARY.md +++ b/pkgs/fleet/book/SUMMARY.md @@ -36,6 +36,7 @@ - [fleet shell](reference/shell.md) - [fleet search](reference/search.md) - [fleet laptop-agent](reference/laptop-agent.md) +- [fleet laptop route forms](reference/laptop-route-forms.md) - [Tutorial: enrol a new seat](tutorials/enrol-a-seat.md) - [Tutorial: claim and complete a queue task](tutorials/claim-and-complete.md) diff --git a/pkgs/fleet/book/reference/laptop-route-forms.md b/pkgs/fleet/book/reference/laptop-route-forms.md new file mode 100644 index 0000000000..001b80ba11 --- /dev/null +++ b/pkgs/fleet/book/reference/laptop-route-forms.md @@ -0,0 +1,79 @@ +# fleet laptop route forms + +The four Fleet domains that reach the laptop, codified as one +matrix by #13717: **tier 0** (`fleet laptop`), the generic tiered +command; **T1** (`fleet commander`), the Desktop Commander MCP +endpoint; **T2** (`fleet http`), the laptop-agent daemon's HTTP +API; **T3** (`fleet ssh`), real SSH. Outside the binary, the same +methods exist as raw commands (T4–T6, literal recipes in the +laptop mechanics doc) and the `laptop-ssh` script is T7 — the +fallback / simplified tier. + +Why forms at all: the platform's execution-risk behaviour keys on +the literal command shape an agent runs, so each form stays a +first-class, separately invocable command, and every result names +the form that served it. Circumstance decides the form; there is +no single blessed invocation. + +## fleet laptop — tier T0 + +`fleet laptop tiers` prints the matrix. `fleet laptop exec +[--form T1|T2|T3] [--timeout SECS] [--cwd DIR] -- CMD...` walks +T1 → T2 → T3 in order (or attempts one pinned tier), each attempt +a literal invocation of that tier's own implementation. It +advances only when a tier fails to *serve* — transport, auth or +connect failure, or a tier-level timeout — never on a served +result, whatever its exit code, and it reports the serving tier +on stderr (`fleet: served by form T1 commander/fleet`). The +per-attempt `--timeout` always applies (default 120 s). Tier 0 +deliberately does not fall through to the `laptop-ssh` wrapper: +reaching T7 is the caller's own final step. + +One recorded casualty of the walk rule: ssh's own failure exit is +255, so the walker reads a remote command that itself exits 255 +over ssh as a tier failure. Standalone `fleet ssh` propagates 255 +untouched. + +## fleet commander — tier T1 + +A client for the self-hosted Desktop Commander MCP endpoint +(#13404, #13654). The bearer is resolved from the secrets broker +by name (`desktop-commander.machine-bearer`) at call time and +never stored; requests carry a browser user agent (the edge +1010-blocks non-browser agents). One MCP session per invocation. +`exec` starts the command via `start_process` (the schema's +`timeout_ms` is always sent), polls `read_process_output` to +completion, and propagates the remote exit code from the +endpoint's own completion line; on the deadline (default 120 s) +it force-terminates the process and exits 124 — an exec never +leaves a running process behind on the laptop. `health` +initializes a session, runs `hostname`, and reports +`{"ok":true,"form":"T1 commander/fleet",...}`. + +## fleet http — tier T2 + +The laptop-agent daemon's HTTP API as a route-form surface: the +same verbs as [fleet laptop-agent](laptop-agent.md), over a +ladder built from the client's HTTP legs only (`http_ladder`: +broker socket → Cloudflare tunnel → Tailscale CONNECT). The SSH +leg is excluded by construction, so this tier can never silently +become the ssh tier. The primary-checkout guard is applied before +anything is sent; a guard refusal is a served result (exit 1), +never something tier 0 may route around. Timeouts always apply: +the daemon's `timeout_s` (default 300) plus the transport grace +as the local deadline; a daemon-side timeout exits 124. + +## fleet ssh — tier T3 + +SSH's endpoint-grade shape is a binary-owned client contract: the +binary constructs the ssh invocation itself — pinned host key +(`~/.ssh/known_hosts_laptop`, `StrictHostKeyChecking=yes`), +proxy CONNECT helper, `IdentitiesOnly`, `ConnectTimeout` — +instead of delegating to a shell script, and enforces a mandatory +overall deadline (default 300 s; the ssh child is killed on +expiry, exit 124). Connections multiplex over a fleet-owned +ControlMaster socket (`~/.ssh/cm-fleet-…`, persist 600 s, +separate from laptop-ssh's master); `fleet ssh close` tears it +down. The honest limit: sshd owns the remote process, so a +client-side kill ends the session but cannot cancel the remote +command protocol-side. diff --git a/pkgs/fleet/crates/fleet-laptop-agent/src/legs.rs b/pkgs/fleet/crates/fleet-laptop-agent/src/legs.rs index 7a598700bb..168903f6da 100644 --- a/pkgs/fleet/crates/fleet-laptop-agent/src/legs.rs +++ b/pkgs/fleet/crates/fleet-laptop-agent/src/legs.rs @@ -256,6 +256,28 @@ pub fn ladder(config: &fleet_config::Config) -> Result { Ok(Ladder::new(legs)) } +/// The HTTP-only ladder for tier T2 (`fleet http`, #13717): the same +/// legs as [`ladder`] minus the SSH leg, by construction — the http +/// form can never silently become the ssh form. +pub fn http_ladder(config: &fleet_config::Config) -> Result { + let token = read_token(&token_file())?; + let legs: Vec> = vec![ + Box::new(BrokerLeg { + socket: broker_socket(), + }), + Box::new(CfLeg { + token: token.clone(), + config: config.clone(), + cf_host: config.cf_host().to_string(), + cache: Mutex::new(CfCache::default()), + }), + Box::new(TailscaleLeg { + token: token.clone(), + }), + ]; + Ok(Ladder::new(legs)) +} + #[cfg(test)] mod tests { use super::*; diff --git a/pkgs/fleet/crates/fleet-registry/src/lib.rs b/pkgs/fleet/crates/fleet-registry/src/lib.rs index 775cbd3288..2064d7f5d9 100644 --- a/pkgs/fleet/crates/fleet-registry/src/lib.rs +++ b/pkgs/fleet/crates/fleet-registry/src/lib.rs @@ -65,6 +65,19 @@ pub enum Capability { /// the next piece of work down the intake ladder, and run a command /// where builds belong. Composes the other domains' verbs. Agent, + /// `fleet commander …` — tier T1 (commander/fleet) of the laptop + /// route forms (#13717): the Desktop Commander MCP endpoint. + Commander, + /// `fleet http …` — tier T2 (http/fleet) of the laptop route + /// forms (#13717): the laptop-agent daemon HTTP API, HTTP legs + /// only. + LaptopHttp, + /// `fleet ssh …` — tier T3 (ssh/fleet) of the laptop route forms + /// (#13717): real SSH under a binary-owned client contract. + LaptopSsh, + /// `fleet laptop …` — tier T0 (tiered/fleet) of the laptop route + /// forms (#13717): the generic tiered command and the form index. + Laptop, } impl Capability { @@ -87,6 +100,10 @@ impl Capability { Capability::Gh => "gh", Capability::Bridge => "bridge", Capability::Agent => "agent", + Capability::Commander => "commander", + Capability::LaptopHttp => "laptop-http", + Capability::LaptopSsh => "laptop-ssh", + Capability::Laptop => "laptop", } } @@ -108,6 +125,10 @@ impl Capability { Capability::Gh, Capability::Bridge, Capability::Agent, + Capability::Commander, + Capability::LaptopHttp, + Capability::LaptopSsh, + Capability::Laptop, ]; } @@ -366,6 +387,38 @@ pub const DOMAINS: &[Domain] = &[ aliases: &["laptop-agent"], subcommands: &["health", "jobs", "kill", "exec", "run", "poll", "fetch"], }, + Domain { + name: "commander", + summary: "Tier T1 (commander/fleet) of the laptop route forms (#13717): run commands on the laptop through the Desktop Commander MCP endpoint.", + capabilities: &[Capability::Commander], + primary: Capability::Commander, + aliases: &[], + subcommands: &["health", "exec"], + }, + Domain { + name: "http", + summary: "Tier T2 (http/fleet) of the laptop route forms (#13717): the laptop-agent daemon HTTP API as a fleet subcommand (HTTP legs only; never ssh).", + capabilities: &[Capability::LaptopHttp], + primary: Capability::LaptopHttp, + aliases: &[], + subcommands: &["health", "jobs", "kill", "exec", "run", "poll", "fetch"], + }, + Domain { + name: "ssh", + summary: "Tier T3 (ssh/fleet) of the laptop route forms (#13717): real SSH to the laptop under a binary-owned client contract (pinned host key, proxy CONNECT, fleet-owned multiplexing).", + capabilities: &[Capability::LaptopSsh], + primary: Capability::LaptopSsh, + aliases: &[], + subcommands: &["health", "exec", "close"], + }, + Domain { + name: "laptop", + summary: "Tier T0 (tiered/fleet) of the laptop route forms (#13717): the generic tiered command - walks T1 -> T2 -> T3 and reports the serving tier; `fleet laptop tiers` prints the matrix.", + capabilities: &[Capability::Laptop], + primary: Capability::Laptop, + aliases: &[], + subcommands: &["tiers", "exec"], + }, ]; /// Look a domain up by canonical name. diff --git a/pkgs/fleet/crates/fleet/Cargo.toml b/pkgs/fleet/crates/fleet/Cargo.toml index 21d30b6972..623bcd53af 100644 --- a/pkgs/fleet/crates/fleet/Cargo.toml +++ b/pkgs/fleet/crates/fleet/Cargo.toml @@ -80,6 +80,10 @@ full = [ "dispatch", "dispatch-test", "laptop-agent", + "commander", + "http", + "ssh", + "laptop", "secrets", "gh", "bridge", @@ -130,6 +134,14 @@ gh = [ "dep:rusqlite", ] laptop-agent = ["dep:fleet-secrets", "dep:fleet-laptop-agent"] +# The laptop route forms (developing-today/code#13717): T1 commander +# (an MCP client over ureq; the bearer comes from fleet-secrets), T2 +# http (the daemon client, HTTP legs only), T3 ssh (no deps: the +# binary owns the ssh argv), T0 the tiered walker composing T1-T3. +commander = ["dep:fleet-secrets", "dep:ureq"] +http = ["dep:fleet-laptop-agent"] +ssh = [] +laptop = ["commander", "http", "ssh"] # Ask the local OpenCode server whether a worktree's recorded session # is live before reusing it (session_state.rs). In full and serve; # never in connect, where ureq+rustls would break the D7 2 MiB gate diff --git a/pkgs/fleet/crates/fleet/src/commander.rs b/pkgs/fleet/crates/fleet/src/commander.rs new file mode 100644 index 0000000000..cbb09ed336 --- /dev/null +++ b/pkgs/fleet/crates/fleet/src/commander.rs @@ -0,0 +1,520 @@ +//! Tier T1 (commander/fleet) — developing-today/code#13654, #13717. +//! +//! A client for the self-hosted Desktop Commander MCP endpoint +//! (#13404), built in the endpoint's own pattern: the bearer is +//! resolved by name from the secrets broker at call time, one MCP +//! session per invocation, `timeout_ms` is always sent (the tool +//! schema requires it), and every spawned process is polled to +//! completion or force-terminated — an exec never leaves a running +//! process behind on the laptop (the pile-up failure mode of +//! 2026-11-23). The remote exit code is read from the endpoint's own +//! completion line ("Process completed with exit code N"). + +use std::time::{Duration, Instant}; + +use fleet_config::Config; +use fleet_secrets::Resolver; +use serde_json::{Value, json}; + +use crate::forms::{ServeOutcome, T1, announce, shell_quote}; + +const ENDPOINT: &str = "https://commander.security.cab/mcp"; +const BEARER_SECRET: &str = "desktop-commander.machine-bearer"; +/// The edge 1010-blocks non-browser user agents (#13404). +const BROWSER_UA: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \ + (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"; +const EXIT_TIMEOUT: i32 = 124; +const EXIT_USAGE: i32 = 2; +const DEFAULT_TIMEOUT_S: u64 = 120; +/// How long one read_process_output poll may wait server-side. +const POLL_WAIT_MS: u64 = 5_000; + +const USAGE: &str = "\ +Usage: fleet commander [args...] + +Tier T1 (commander/fleet) of the laptop route forms (#13717): run +commands on the laptop through the Desktop Commander MCP endpoint. + +Commands: + health Initialize a session, run `hostname`, report latency + exec [--cwd D] [--timeout S] -- cmd... + Run a command line on the laptop (through its shell); + the remote exit code propagates. --timeout is in seconds + and always applies (default 120): on expiry the remote + process is force-terminated and the exit code is 124."; + +struct Client { + agent: ureq::Agent, + bearer: String, + session: String, + next_id: u64, +} + +impl Client { + fn connect(config: &Config) -> Result { + let bearer = Resolver::default_chain(config) + .resolve(BEARER_SECRET) + .map_err(|e| format!("secret {BEARER_SECRET} unavailable: {e}"))? + .expose() + .to_string(); + let agent: ureq::Agent = ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(30))) + .timeout_connect(Some(Duration::from_secs(15))) + .http_status_as_error(false) + .tls_config( + ureq::tls::TlsConfig::builder() + .root_certs(ureq::tls::RootCerts::PlatformVerifier) + .build(), + ) + .build() + .into(); + let mut client = Client { + agent, + bearer, + session: String::new(), + next_id: 1, + }; + client.rpc( + "initialize", + Some(json!({ + "protocolVersion": "2025-03-26", + "capabilities": {}, + "clientInfo": { "name": "fleet", "version": env!("CARGO_PKG_VERSION") }, + })), + )?; + if client.session.is_empty() { + return Err("commander endpoint sent no Mcp-Session-Id".into()); + } + client.notify("notifications/initialized")?; + Ok(client) + } + + /// One JSON-RPC round trip. The response may be SSE (`data:` + /// lines) or a bare JSON body; the message matching our request + /// id wins. An `initialize` response's session id is captured. + fn rpc(&mut self, method: &str, params: Option) -> Result { + let id = self.next_id; + self.next_id += 1; + let mut body = json!({ "jsonrpc": "2.0", "id": id, "method": method }); + if let Some(p) = params { + body["params"] = p; + } + let (status, session, text) = self.post(&body.to_string())?; + if method == "initialize" { + if let Some(s) = session { + self.session = s; + } + } + if !(200..300).contains(&status) { + return Err(format!("commander HTTP {status}")); + } + let msg = pick_message(&text, id) + .ok_or_else(|| format!("commander reply to {method} carried no result"))?; + if let Some(err) = msg.get("error") { + let m = err + .get("message") + .and_then(Value::as_str) + .unwrap_or("rpc error"); + return Err(format!("commander {method}: {m}")); + } + Ok(msg.get("result").cloned().unwrap_or(Value::Null)) + } + + fn notify(&mut self, method: &str) -> Result<(), String> { + let body = json!({ "jsonrpc": "2.0", "method": method }); + let (status, _, _) = self.post(&body.to_string())?; + if !(200..300).contains(&status) { + return Err(format!("commander HTTP {status} on {method}")); + } + Ok(()) + } + + fn post(&mut self, body: &str) -> Result<(u16, Option, String), String> { + let mut req = self + .agent + .post(ENDPOINT) + .header("Authorization", &format!("Bearer {}", self.bearer)) + .header("User-Agent", BROWSER_UA) + .header("Accept", "application/json, text/event-stream") + .content_type("application/json"); + if !self.session.is_empty() { + req = req.header("Mcp-Session-Id", &self.session); + } + let mut resp = req + .send(body) + .map_err(|e| format!("commander transport: {e}"))?; + let status = resp.status().as_u16(); + let session = resp + .headers() + .get("mcp-session-id") + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + let text = resp + .body_mut() + .read_to_string() + .map_err(|e| format!("commander reply unreadable: {e}"))?; + Ok((status, session, text)) + } + + fn tools_call(&mut self, name: &str, arguments: Value) -> Result { + let result = self.rpc( + "tools/call", + Some(json!({ "name": name, "arguments": arguments })), + )?; + let text = content_text(&result); + if result + .get("isError") + .and_then(Value::as_bool) + .unwrap_or(false) + { + return Err(format!("commander tool {name} failed: {text}")); + } + Ok(text) + } +} + +fn pick_message(text: &str, want_id: u64) -> Option { + let mut candidates: Vec = Vec::new(); + for line in text.lines() { + if let Some(data) = line.trim().strip_prefix("data:") { + if let Ok(v) = serde_json::from_str::(data.trim()) { + candidates.push(v); + } + } + } + if candidates.is_empty() { + if let Ok(v) = serde_json::from_str::(text.trim()) { + candidates.push(v); + } + } + candidates + .iter() + .find(|v| v.get("id").and_then(Value::as_u64) == Some(want_id)) + .cloned() + .or_else(|| candidates.last().cloned()) +} + +fn content_text(result: &Value) -> String { + result + .get("content") + .and_then(Value::as_array) + .map(|items| { + items + .iter() + .filter_map(|c| c.get("text").and_then(Value::as_str)) + .collect::>() + .join("\n") + }) + .unwrap_or_default() +} + +fn parse_pid(text: &str) -> Option { + let idx = text.find("PID ")? + 4; + let num: String = text[idx..] + .chars() + .take_while(|c| c.is_ascii_digit()) + .collect(); + num.parse().ok() +} + +struct ReadChunk { + output: String, + total_lines: u64, + exit_code: Option, + completed: bool, +} + +/// Parse one read_process_output reply: a leading `[...]` status +/// line (whose `(total: N lines)` is the authoritative output-line +/// count), a blank separator, the new output lines, and — once the +/// process ends — the endpoint's completion line. +fn parse_read_chunk(text: &str, prev_total: u64) -> ReadChunk { + let mut lines: Vec<&str> = text.lines().collect(); + let mut total: Option = None; + if let Some(first) = lines.first() { + let first = *first; + if first.starts_with('[') && first.ends_with(']') { + if let Some(t) = first + .split("(total: ") + .nth(1) + .and_then(|s| s.split_whitespace().next()) + .and_then(|n| n.parse::().ok()) + { + total = Some(t); + } + lines.remove(0); + if lines.first().map(|l| l.is_empty()).unwrap_or(false) { + lines.remove(0); + } + } + } + let mut exit_code = None; + let mut completed = false; + let mut out_lines: Vec<&str> = Vec::new(); + for l in lines { + if let Some(idx) = l.find("Process completed with exit code ") { + completed = true; + let rest = &l[idx + "Process completed with exit code ".len()..]; + let num: String = rest + .chars() + .take_while(|c| c.is_ascii_digit() || *c == '-') + .collect(); + exit_code = num.parse::().ok(); + continue; + } + if l.contains("Process completed") || l.contains("Process terminated") { + completed = true; + continue; + } + out_lines.push(l); + } + let total_lines = total.unwrap_or(prev_total + out_lines.len() as u64); + let mut output = out_lines.join("\n"); + if !output.is_empty() { + output.push('\n'); + } + ReadChunk { + output, + total_lines, + exit_code, + completed, + } +} + +struct Capture { + outcome: ServeOutcome, + output: String, +} + +fn exec_capture(config: &Config, cwd: Option<&str>, timeout_s: u64, cmd: &[String]) -> Capture { + let fail = |m: String| Capture { + outcome: ServeOutcome::Failed(m), + output: String::new(), + }; + let mut client = match Client::connect(config) { + Ok(c) => c, + Err(m) => return fail(m), + }; + let mut line = cmd.join(" "); + if let Some(d) = cwd { + line = format!("cd {} && {}", shell_quote(d), line); + } + let start = match client.tools_call( + "start_process", + json!({ "command": line, "timeout_ms": 3000 }), + ) { + Ok(t) => t, + Err(m) => return fail(m), + }; + let pid = match parse_pid(&start) { + Some(p) => p, + None => { + return fail(format!( + "commander start_process named no PID: {}", + start.lines().next().unwrap_or("") + )); + } + }; + let deadline = Instant::now() + Duration::from_secs(timeout_s.max(1)); + let mut offset: u64 = 0; + let mut output = String::new(); + loop { + match client.tools_call( + "read_process_output", + json!({ "pid": pid, "offset": offset, "timeout_ms": POLL_WAIT_MS }), + ) { + Ok(text) => { + let chunk = parse_read_chunk(&text, offset); + offset = chunk.total_lines; + output.push_str(&chunk.output); + if let Some(code) = chunk.exit_code { + return Capture { + outcome: ServeOutcome::Served(code), + output, + }; + } + if chunk.completed { + return Capture { + outcome: ServeOutcome::Served(1), + output, + }; + } + } + Err(m) => { + let _ = client.tools_call("force_terminate", json!({ "pid": pid })); + return Capture { + outcome: ServeOutcome::Failed(m), + output, + }; + } + } + if Instant::now() >= deadline { + let _ = client.tools_call("force_terminate", json!({ "pid": pid })); + return Capture { + outcome: ServeOutcome::TimedOut, + output, + }; + } + std::thread::sleep(Duration::from_millis(200)); + } +} + +/// Serve one exec through this tier, printing the remote output. +/// Used by the standalone verb and by tier 0. +pub fn serve(config: &Config, cwd: Option<&str>, timeout_s: u64, cmd: &[String]) -> ServeOutcome { + use std::io::Write; + let capture = exec_capture(config, cwd, timeout_s, cmd); + print!("{}", capture.output); + let _ = std::io::stdout().flush(); + capture.outcome +} + +fn health(config: &Config) -> i32 { + let started = Instant::now(); + let capture = exec_capture(config, None, 20, &["hostname".to_string()]); + let ms = started.elapsed().as_millis(); + match capture.outcome { + ServeOutcome::Served(0) if capture.output.trim() == "amd" => { + println!( + "{}", + json!({ "ok": true, "form": "T1 commander/fleet", "host": "amd", "latency_ms": ms }) + ); + 0 + } + ServeOutcome::Served(code) => { + eprintln!( + "commander: health: unexpected result (exit {code}, output {:?})", + capture.output.trim() + ); + 1 + } + ServeOutcome::TimedOut => { + eprintln!("commander: health: timed out"); + EXIT_TIMEOUT + } + ServeOutcome::Failed(m) => { + eprintln!("commander: health: {m}"); + 1 + } + } +} + +struct ExecArgs { + cwd: Option, + timeout_s: u64, + cmd: Vec, +} + +fn parse_exec_args(args: &[String]) -> Result { + let mut cwd = None; + let mut timeout_s = DEFAULT_TIMEOUT_S; + let mut i = 0; + while i < args.len() { + let a = &args[i]; + if a == "--" { + let cmd: Vec = args[i + 1..].to_vec(); + if cmd.is_empty() { + return Err("exec: no command after --".into()); + } + return Ok(ExecArgs { + cwd, + timeout_s, + cmd, + }); + } else if a == "--cwd" { + i += 1; + cwd = Some( + args.get(i) + .ok_or("exec: --cwd needs a value")? + .to_string(), + ); + } else if let Some(v) = a.strip_prefix("--cwd=") { + cwd = Some(v.to_string()); + } else if a == "--timeout" { + i += 1; + timeout_s = args + .get(i) + .ok_or("exec: --timeout needs a value")? + .parse() + .map_err(|_| "exec: --timeout must be seconds".to_string())?; + } else if let Some(v) = a.strip_prefix("--timeout=") { + timeout_s = v + .parse() + .map_err(|_| "exec: --timeout must be seconds".to_string())?; + } else { + return Err(format!("exec: unexpected argument {a} (command goes after --)")); + } + i += 1; + } + Err("exec: missing -- before the command".into()) +} + +pub fn run(config: &Config, args: &[String]) -> i32 { + match args.first().map(|s| s.as_str()) { + Some("--help") | Some("-h") => { + println!("{USAGE}"); + 0 + } + Some("health") => health(config), + Some("exec") => { + let parsed = match parse_exec_args(&args[1..]) { + Ok(p) => p, + Err(m) => { + eprintln!("commander: {m}\n{USAGE}"); + return EXIT_USAGE; + } + }; + announce(T1); + match serve(config, parsed.cwd.as_deref(), parsed.timeout_s, &parsed.cmd) { + ServeOutcome::Served(code) => code, + ServeOutcome::TimedOut => { + eprintln!( + "commander: timed out after {}s (remote process terminated)", + parsed.timeout_s + ); + EXIT_TIMEOUT + } + ServeOutcome::Failed(m) => { + eprintln!("commander: {m}"); + 1 + } + } + } + _ => { + eprintln!("{USAGE}"); + EXIT_USAGE + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pid_parses_from_start_reply() { + assert_eq!( + parse_pid("Process started with PID 352522 (shell: /bin/bash)\nInitial output:\n"), + Some(352522) + ); + assert_eq!(parse_pid("no pid here"), None); + } + + #[test] + fn chunk_parses_header_output_and_exit() { + let text = "[Reading 3 new lines (total: 3 lines)]\n\nprobe-out\nprobe-err\n\ + \u{2705} Process completed with exit code 3 (runtime: 1.01s)"; + let chunk = parse_read_chunk(text, 0); + assert_eq!(chunk.total_lines, 3); + assert_eq!(chunk.exit_code, Some(3)); + assert!(chunk.output.contains("probe-out")); + assert!(!chunk.output.contains("Process completed")); + } + + #[test] + fn chunk_without_header_counts_lines() { + let chunk = parse_read_chunk("one\ntwo", 5); + assert_eq!(chunk.total_lines, 7); + assert_eq!(chunk.exit_code, None); + } +} diff --git a/pkgs/fleet/crates/fleet/src/forms.rs b/pkgs/fleet/crates/fleet/src/forms.rs new file mode 100644 index 0000000000..76b7b7af69 --- /dev/null +++ b/pkgs/fleet/crates/fleet/src/forms.rs @@ -0,0 +1,148 @@ +//! The laptop route forms (developing-today/code#13717): the shared +//! vocabulary of the codified matrix — tier 0 (the generic tiered +//! command), 3 methods × 2 shapes (T1–T6), and the `laptop-ssh` +//! wrapper (T7) — and the outcome type every fleet-shape form's exec +//! returns, so tier 0 can compose the subcommand tiers without any +//! of them knowing about the others. +//! +//! Why forms, not a ladder: the platform's execution-risk behaviour +//! keys on the literal command shape an agent runs, so each form is +//! a first-class, separately invocable command, and every result +//! names the exact form that served it (method × shape). Tier 0's +//! internal attempts run under tier 0's own process shape, which is +//! itself a different literal invocation than the standalone +//! subcommands — after tier 0 fails, the individual forms are tried +//! as their own commands, then the raw forms, then the wrapper. + +use std::process::Command; +use std::time::{Duration, Instant}; + +/// How one form's exec attempt ended. +pub enum ServeOutcome { + /// The form served the call; the value is the remote command's + /// exit code (its output has already been printed). + Served(i32), + /// The form's own deadline expired before the command completed + /// (the form cleaned up after itself: the commander form + /// force-terminates, the http form cancels through the daemon). + /// Tier 0 treats this as "this form did not serve" and moves to + /// the next form; the standalone form maps it to exit 124. + TimedOut, + /// The form could not serve at all (transport, auth, connect, + /// missing local piece). The string says why; it never carries a + /// secret value. + Failed(String), +} + +/// One codified form of reaching the laptop. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Form { + pub id: &'static str, + pub method: &'static str, + pub shape: &'static str, + /// The literal command, as documented for agents to run as-is. + pub command: &'static str, +} + +pub const T0: Form = Form { + id: "T0", + method: "tiered", + shape: "fleet", + command: "fleet laptop exec [--timeout S] -- cmd...", +}; +pub const T1: Form = Form { + id: "T1", + method: "commander", + shape: "fleet", + command: "fleet commander exec [--cwd D] --timeout S -- cmd...", +}; +pub const T2: Form = Form { + id: "T2", + method: "http", + shape: "fleet", + command: "fleet http exec [--cwd D] --timeout S -- cmd...", +}; +pub const T3: Form = Form { + id: "T3", + method: "ssh", + shape: "fleet", + command: "fleet ssh exec --timeout S -- cmd...", +}; +pub const T4: Form = Form { + id: "T4", + method: "commander", + shape: "raw", + command: "curl to https://commander.security.cab/mcp (recipe in TOOLS.d/laptop.md)", +}; +pub const T5: Form = Form { + id: "T5", + method: "http", + shape: "raw", + command: "curl to the daemon API via the session proxy (recipe in TOOLS.d/laptop.md)", +}; +pub const T6: Form = Form { + id: "T6", + method: "ssh", + shape: "raw", + command: "ssh (literal invocation in TOOLS.d/laptop.md) user@100.99.113.103 'cmd...'", +}; +pub const T7: Form = Form { + id: "T7", + method: "wrapper", + shape: "laptop-ssh", + command: "laptop-ssh 'cmd...'", +}; + +/// All eight codified forms, tier 0 first. +pub const FORMS: [Form; 8] = [T0, T1, T2, T3, T4, T5, T6, T7]; + +/// The fleet subcommand tiers tier 0 walks, in order. The wrapper +/// (T7) is deliberately NOT in this list: it is the agent's own +/// final step after tier 0 and the individual forms, never +/// something tier 0 papers over. +pub const WALK_ORDER: [Form; 3] = [T1, T2, T3]; + +impl Form { + /// The label every result and log line names: `T2 http/fleet`. + pub fn label(self) -> String { + format!("{} {}/{}", self.id, self.method, self.shape) + } +} + +/// Announce the form about to serve an exec (stderr only: stdout +/// stays the remote command's own). +pub fn announce(form: Form) { + eprintln!("fleet: form {}", form.label()); +} + +/// Single-quote a string for a POSIX shell command line. +pub fn shell_quote(s: &str) -> String { + format!("'{}'", s.replace('\'', "'\\''")) +} + +/// Spawn a child (stdio inherited) and bound the wait by a deadline: +/// on expiry the child is killed and the outcome is `TimedOut` +/// (callers map it to exit 124). Used by the ssh form, whose child +/// is a local process; the commander and http forms manage their +/// remote processes through their own protocols instead. +pub fn spawn_with_deadline(cmd: &mut Command, timeout_s: u64) -> ServeOutcome { + let mut child = match cmd.spawn() { + Ok(c) => c, + Err(e) => return ServeOutcome::Failed(format!("spawn: {e}")), + }; + let deadline = Instant::now() + Duration::from_secs(timeout_s.max(1)); + loop { + match child.try_wait() { + Ok(Some(status)) => return ServeOutcome::Served(status.code().unwrap_or(1)), + Ok(None) => { + if Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + return ServeOutcome::TimedOut; + } + std::thread::sleep(Duration::from_millis(100)); + } + Err(e) => return ServeOutcome::Failed(format!("wait: {e}")), + } + } +} diff --git a/pkgs/fleet/crates/fleet/src/http.rs b/pkgs/fleet/crates/fleet/src/http.rs new file mode 100644 index 0000000000..e175109155 --- /dev/null +++ b/pkgs/fleet/crates/fleet/src/http.rs @@ -0,0 +1,309 @@ +//! Tier T2 (http/fleet) — developing-today/code#13717. +//! +//! The fleet-shape client for the laptop-agent daemon's HTTP API. +//! The daemon is the endpoint; this module is its contract surface +//! in the fleet binary: token auth (read from the token file at call +//! time, never in argv), the primary-checkout guard applied before +//! anything is sent, a timeout on every call (the daemon's own +//! `timeout_s` plus the transport grace as the local deadline), and +//! exit codes propagated from the daemon's reply. +//! +//! The ladder is built from the daemon client's HTTP legs only +//! (broker socket → Cloudflare tunnel → Tailscale CONNECT) via +//! `legs::http_ladder`: the SSH leg is excluded by construction, so +//! this tier can never silently become the ssh tier. + +use std::io::Write; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use fleet_config::Config; +use fleet_laptop_agent::ladder::Ladder; +use fleet_laptop_agent::{client, guard, legs, new_trip}; +use serde_json::{Value, json}; + +use crate::forms::{ServeOutcome, T2, announce}; + +const EXIT_TIMEOUT: i32 = 124; +const EXIT_USAGE: i32 = 2; +const DEFAULT_TIMEOUT_S: u64 = 300; + +const USAGE: &str = "\ +Usage: fleet http [args...] + +Tier T2 (http/fleet) of the laptop route forms (#13717): the +laptop-agent daemon's HTTP API as a fleet subcommand. The ladder is +HTTP legs only — this tier never falls through to ssh. + +Commands: + health Daemon reachability (GET /health through the ladder) + jobs List daemon jobs + kill JOB Terminate a daemon job + exec [--cwd D] [--timeout S] [--shell] -- cmd... + Run synchronously; the daemon's exit code propagates. + --timeout is in seconds and always applies (default + 300); a daemon-side timeout exits 124. + run [--cwd D] [--shell] -- cmd... + Submit as a background job; prints the job id + poll JOB [--wait S] Poll a job, optionally waiting + fetch REMOTE LOCAL Fetch a file written by a job"; + +fn build_ladder(config: &Config) -> Result, String> { + legs::http_ladder(config).map(Arc::new) +} + +/// Mirror of the laptop-agent domain's external-deadline clamp: a +/// harness-imposed `LAPTOP_AGENT_DEADLINE_S` bounds every call. +fn clamp_external(timeout_s: u64) -> u64 { + if let Ok(raw) = std::env::var(fleet_laptop_agent::EXTERNAL_DEADLINE_ENV) { + if let Ok(cap) = raw.trim().parse::() { + let cap = cap.max(1.0) as u64; + return timeout_s.min(cap).max(1); + } + } + timeout_s.max(1) +} + +/// Render a daemon /exec reply the way the laptop-agent domain does +/// (stdout/stderr through, timeout → 124), with this tier's prefix +/// on the side lines. +fn render_exec_reply(body: &Value) -> i32 { + let Some(result) = body + .get("results") + .and_then(Value::as_array) + .and_then(|a| a.first()) + else { + eprintln!("http: daemon reply carried no result: {body}"); + return 1; + }; + if let Some(s) = result.get("stdout").and_then(Value::as_str) { + print!("{s}"); + } + if let Some(s) = result.get("stderr").and_then(Value::as_str) { + eprint!("{s}"); + } + let _ = std::io::stdout().flush(); + let _ = std::io::stderr().flush(); + if result + .get("truncated") + .and_then(Value::as_bool) + .unwrap_or(false) + { + eprintln!("http: warning: command output was truncated by the daemon"); + } + if let Some(err) = result.get("error").and_then(Value::as_str) { + if !err.is_empty() { + eprintln!("http: daemon error: {err}"); + return 1; + } + } + if result + .get("timeout") + .and_then(Value::as_bool) + .unwrap_or(false) + { + return EXIT_TIMEOUT; + } + result + .get("exit") + .and_then(Value::as_i64) + .map(|c| c as i32) + .unwrap_or(1) +} + +fn serve_with_ladder( + ladder: &Arc, + cwd: Option<&str>, + shell: bool, + timeout_s: u64, + cmd: &[String], +) -> ServeOutcome { + if let Err(m) = guard::check_job(cwd, cmd) { + // A policy refusal is the tier answering, not failing: the + // guard exists so no route drives the primary checkout, and + // tier 0 must not route around it. + eprintln!("http: {m}"); + return ServeOutcome::Served(1); + } + let timeout_s = clamp_external(timeout_s); + let spec = client::command_spec(cwd, shell, cmd); + let trip = new_trip(); + let deadline = Duration::from_secs(timeout_s + fleet_laptop_agent::TRANSPORT_GRACE_S); + let body = json!({ "cmds": [spec], "timeout_s": timeout_s }); + match client::call(ladder, &trip, "POST", "/exec", Some(body), false, deadline) { + Ok(reply) => ServeOutcome::Served(render_exec_reply(&reply.body)), + Err(client::CallFailure::Deadline) => { + client::cancel(ladder, &trip); + ServeOutcome::TimedOut + } + Err(e) => ServeOutcome::Failed(e.to_string()), + } +} + +/// Serve one exec through this tier. Used by the standalone verb +/// and by tier 0. +pub fn serve(config: &Config, cwd: Option<&str>, timeout_s: u64, cmd: &[String]) -> ServeOutcome { + match build_ladder(config) { + Ok(ladder) => serve_with_ladder(&ladder, cwd, false, timeout_s, cmd), + Err(m) => ServeOutcome::Failed(m), + } +} + +struct ExecArgs { + cwd: Option, + timeout_s: u64, + shell: bool, + cmd: Vec, +} + +fn parse_exec_args(args: &[String], with_timeout: bool) -> Result { + let mut cwd = None; + let mut timeout_s = DEFAULT_TIMEOUT_S; + let mut shell = false; + let mut i = 0; + while i < args.len() { + let a = &args[i]; + if a == "--" { + let cmd: Vec = args[i + 1..].to_vec(); + if cmd.is_empty() { + return Err("no command after --".into()); + } + return Ok(ExecArgs { + cwd, + timeout_s, + shell, + cmd, + }); + } else if a == "--cwd" { + i += 1; + cwd = Some(args.get(i).ok_or("--cwd needs a value")?.to_string()); + } else if let Some(v) = a.strip_prefix("--cwd=") { + cwd = Some(v.to_string()); + } else if a == "--timeout" && with_timeout { + i += 1; + timeout_s = args + .get(i) + .ok_or("--timeout needs a value")? + .parse() + .map_err(|_| "--timeout must be seconds".to_string())?; + } else if let Some(v) = a.strip_prefix("--timeout=") { + if !with_timeout { + return Err("--timeout is not taken here".into()); + } + timeout_s = v.parse().map_err(|_| "--timeout must be seconds".to_string())?; + } else if a == "--shell" { + shell = true; + } else { + return Err(format!("unexpected argument {a} (command goes after --)")); + } + i += 1; + } + Err("missing -- before the command".into()) +} + +pub fn run(config: &Config, args: &[String]) -> i32 { + let verb = args.first().map(|s| s.as_str()); + if verb.is_none() || matches!(verb, Some("--help") | Some("-h")) { + println!("{USAGE}"); + return if verb.is_none() { EXIT_USAGE } else { 0 }; + } + let ladder = match build_ladder(config) { + Ok(l) => l, + Err(m) => { + eprintln!("http: {m}"); + return 1; + } + }; + match verb.unwrap() { + "health" => client::health(&ladder), + "jobs" => client::jobs(&ladder), + "kill" => match args.get(1) { + Some(job) => client::kill(&ladder, job), + None => { + eprintln!("http: kill needs a job id\n{USAGE}"); + EXIT_USAGE + } + }, + "exec" => { + let parsed = match parse_exec_args(&args[1..], true) { + Ok(p) => p, + Err(m) => { + eprintln!("http: exec: {m}\n{USAGE}"); + return EXIT_USAGE; + } + }; + announce(T2); + match serve_with_ladder( + &ladder, + parsed.cwd.as_deref(), + parsed.shell, + parsed.timeout_s, + &parsed.cmd, + ) { + ServeOutcome::Served(code) => code, + ServeOutcome::TimedOut => { + eprintln!( + "http: timed out after {}s (daemon job cancelled)", + parsed.timeout_s + ); + EXIT_TIMEOUT + } + ServeOutcome::Failed(m) => { + eprintln!("http: {m}"); + 1 + } + } + } + "run" => { + let parsed = match parse_exec_args(&args[1..], false) { + Ok(p) => p, + Err(m) => { + eprintln!("http: run: {m}\n{USAGE}"); + return EXIT_USAGE; + } + }; + if let Err(m) = guard::check_job(parsed.cwd.as_deref(), &parsed.cmd) { + eprintln!("http: {m}"); + return 1; + } + announce(T2); + client::run( + &ladder, + client::command_spec(parsed.cwd.as_deref(), parsed.shell, &parsed.cmd), + ) + } + "poll" => { + let Some(job) = args.get(1) else { + eprintln!("http: poll needs a job id\n{USAGE}"); + return EXIT_USAGE; + }; + let mut wait: u64 = 30; + let mut i = 2; + while i < args.len() { + if args[i] == "--wait" { + i += 1; + wait = args + .get(i) + .and_then(|v| v.parse().ok()) + .unwrap_or(wait); + } else if let Some(v) = args[i].strip_prefix("--wait=") { + wait = v.parse().unwrap_or(wait); + } + i += 1; + } + client::poll(&ladder, job, wait) + } + "fetch" => match (args.get(1), args.get(2)) { + (Some(remote), Some(local)) => client::fetch(&ladder, remote, &PathBuf::from(local)), + _ => { + eprintln!("http: fetch needs REMOTE and LOCAL paths\n{USAGE}"); + EXIT_USAGE + } + }, + other => { + eprintln!("http: unknown command {other}\n{USAGE}"); + EXIT_USAGE + } + } +} diff --git a/pkgs/fleet/crates/fleet/src/laptop.rs b/pkgs/fleet/crates/fleet/src/laptop.rs new file mode 100644 index 0000000000..21c2bc17fe --- /dev/null +++ b/pkgs/fleet/crates/fleet/src/laptop.rs @@ -0,0 +1,203 @@ +//! Tier T0 (tiered/fleet) — developing-today/code#13717. +//! +//! The generic tiered command: the first option before any +//! fallback. It walks the fleet subcommand tiers T1 → T2 → T3 in +//! order, each attempt a literal invocation of that tier's own +//! implementation, advancing only when a tier fails to *serve* +//! (transport / auth / connect failure, or a tier-level timeout) — +//! never on a served result, whatever its exit code — and it +//! reports the tier that served. +//! +//! Tier 0 deliberately does not fall through to the wrapper (T7): +//! when tier 0 fails, the individual forms come into play as their +//! own literal commands — the subcommands again, then the raw +//! commands (T4–T6), then `laptop-ssh` — because an attempt under +//! tier 0's process shape is a different literal invocation than +//! the standalone command, and gate behaviour keys on the literal +//! shape. + +use fleet_config::Config; + +use crate::forms::{FORMS, Form, ServeOutcome, WALK_ORDER}; + +const EXIT_USAGE: i32 = 2; +const DEFAULT_TIMEOUT_S: u64 = 120; + +const USAGE: &str = "\ +Usage: fleet laptop [args...] + +Tier T0 (tiered/fleet) of the laptop route forms (#13717), and the +index of the whole matrix. + +Commands: + tiers Print the codified form table (T0–T7) and the doctrine + exec [--form T1|T2|T3] [--timeout S] [--cwd D] -- cmd... + Run a command on the laptop. Without --form, walks + T1 -> T2 -> T3 in order and reports the tier that + served. --timeout is per attempt, in seconds, and + always applies (default 120)."; + +fn tiers_text() -> String { + let mut s = String::from( + "The laptop route forms (#13717): tier 0, 3 methods x 2 shapes, the wrapper.\n\ + Circumstance decides the form; every form is tried as its own literal\n\ + command; every result names the form that served it.\n\n", + ); + for f in FORMS { + s.push_str(&format!( + "{} {:<10} {:<11} {}\n", + f.id, f.method, f.shape, f.command + )); + } + s.push_str( + "\nComposition: tier 0 first. When it fails, the individual fleet\n\ + subcommands as their own commands, then the raw commands, then\n\ + the wrapper (T7, the fallback / simplified tier).\n", + ); + s +} + +fn form_by_id(id: &str) -> Option
{ + FORMS.iter().find(|f| f.id == id).copied() +} + +struct WalkArgs { + form: Option, + timeout_s: u64, + cwd: Option, + cmd: Vec, +} + +fn parse_walk_args(args: &[String]) -> Result { + let mut form = None; + let mut timeout_s = DEFAULT_TIMEOUT_S; + let mut cwd = None; + let mut i = 0; + while i < args.len() { + let a = &args[i]; + if a == "--" { + let cmd: Vec = args[i + 1..].to_vec(); + if cmd.is_empty() { + return Err("exec: no command after --".into()); + } + return Ok(WalkArgs { + form, + timeout_s, + cwd, + cmd, + }); + } else if a == "--form" { + i += 1; + let v = args.get(i).ok_or("exec: --form needs a value")?; + form = Some(form_by_id(v).ok_or_else(|| format!("exec: unknown form {v}"))?); + } else if let Some(v) = a.strip_prefix("--form=") { + form = Some(form_by_id(v).ok_or_else(|| format!("exec: unknown form {v}"))?); + } else if a == "--timeout" { + i += 1; + timeout_s = args + .get(i) + .ok_or("exec: --timeout needs a value")? + .parse() + .map_err(|_| "exec: --timeout must be seconds".to_string())?; + } else if let Some(v) = a.strip_prefix("--timeout=") { + timeout_s = v + .parse() + .map_err(|_| "exec: --timeout must be seconds".to_string())?; + } else if a == "--cwd" { + i += 1; + cwd = Some( + args.get(i) + .ok_or("exec: --cwd needs a value")? + .to_string(), + ); + } else if let Some(v) = a.strip_prefix("--cwd=") { + cwd = Some(v.to_string()); + } else { + return Err(format!("exec: unexpected argument {a} (command goes after --)")); + } + i += 1; + } + Err("exec: missing -- before the command".into()) +} + +fn attempt(config: &Config, form: Form, cwd: Option<&str>, timeout_s: u64, cmd: &[String]) -> ServeOutcome { + match form.id { + "T1" => crate::commander::serve(config, cwd, timeout_s, cmd), + "T2" => crate::http::serve(config, cwd, timeout_s, cmd), + "T3" => match crate::ssh::serve(config, cwd, timeout_s, cmd) { + // ssh's own failure exit is 255 (connect/auth/protocol): + // by ssh convention that is the tier failing to serve, + // not the command's result. Recorded casualty: a remote + // command that itself exits 255 over ssh reads as a + // tier failure here. + ServeOutcome::Served(255) => { + ServeOutcome::Failed("ssh exited 255 (connect/auth failure)".into()) + } + other => other, + }, + _ => ServeOutcome::Failed(format!("form {} is not a fleet subcommand tier", form.id)), + } +} + +fn walk(config: &Config, args: &[String]) -> i32 { + let parsed = match parse_walk_args(args) { + Ok(p) => p, + Err(m) => { + eprintln!("laptop: {m}\n{USAGE}"); + return EXIT_USAGE; + } + }; + let order: Vec = match parsed.form { + Some(f) => { + if !WALK_ORDER.contains(&f) { + eprintln!( + "laptop: --form {} cannot be attempted by tier 0 (raw forms and the \ + wrapper are run as their own literal commands)", + f.id + ); + return EXIT_USAGE; + } + vec![f] + } + None => WALK_ORDER.to_vec(), + }; + for form in order { + eprintln!("fleet: trying form {}", form.label()); + match attempt(config, form, parsed.cwd.as_deref(), parsed.timeout_s, &parsed.cmd) { + ServeOutcome::Served(code) => { + eprintln!("fleet: served by form {}", form.label()); + return code; + } + ServeOutcome::TimedOut => { + eprintln!( + "fleet: form {} timed out after {}s; trying next", + form.label(), + parsed.timeout_s + ); + } + ServeOutcome::Failed(m) => { + eprintln!("fleet: form {} failed: {m}; trying next", form.label()); + } + } + } + eprintln!("fleet: no tier served the call (the individual forms, then the raw forms, then laptop-ssh remain)"); + 1 +} + +pub fn run(config: &Config, args: &[String]) -> i32 { + match args.first().map(|s| s.as_str()) { + Some("--help") | Some("-h") => { + println!("{USAGE}"); + 0 + } + Some("tiers") | Some("forms") => { + print!("{}", tiers_text()); + 0 + } + Some("exec") => walk(config, &args[1..]), + _ => { + eprintln!("{USAGE}"); + EXIT_USAGE + } + } +} diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index 870dc0897c..f3deb0fcb7 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -56,6 +56,21 @@ mod gh_closure; mod gh_guard; #[cfg(feature = "gh")] mod gh_metadata; +#[cfg(feature = "commander")] +mod commander; +#[cfg(feature = "http")] +mod http; +#[cfg(feature = "ssh")] +mod ssh; +#[cfg(feature = "laptop")] +mod laptop; +#[cfg(any( + feature = "commander", + feature = "http", + feature = "ssh", + feature = "laptop" +))] +mod forms; mod invocation_ledger; mod session_state; @@ -108,6 +123,18 @@ fn compiled_capabilities() -> CapabilitySet { if cfg!(feature = "laptop-agent") { caps.insert(Capability::LaptopAgent); } + if cfg!(feature = "commander") { + caps.insert(Capability::Commander); + } + if cfg!(feature = "http") { + caps.insert(Capability::LaptopHttp); + } + if cfg!(feature = "ssh") { + caps.insert(Capability::LaptopSsh); + } + if cfg!(feature = "laptop") { + caps.insert(Capability::Laptop); + } if cfg!(feature = "secrets") { caps.insert(Capability::Secrets); } @@ -958,6 +985,25 @@ fn run_domain_with_initializer( if d.name == "laptop-agent" { return fleet_laptop_agent::cli::run(&surface.config, args); } + // developing-today/code#13717: the laptop route forms - + // T1 commander, T2 http, T3 ssh, and T0, the tiered + // walker (`fleet laptop`). + #[cfg(feature = "commander")] + if d.name == "commander" { + return commander::run(&surface.config, args); + } + #[cfg(feature = "http")] + if d.name == "http" { + return http::run(&surface.config, args); + } + #[cfg(feature = "ssh")] + if d.name == "ssh" { + return ssh::run(&surface.config, args); + } + #[cfg(feature = "laptop")] + if d.name == "laptop" { + return laptop::run(&surface.config, args); + } // code#8887: the gh domain runs for real — the real // `gh` binary as a passthrough under the token // rotation (App installations, then personal last). diff --git a/pkgs/fleet/crates/fleet/src/ssh.rs b/pkgs/fleet/crates/fleet/src/ssh.rs new file mode 100644 index 0000000000..b8cb4ba8f9 --- /dev/null +++ b/pkgs/fleet/crates/fleet/src/ssh.rs @@ -0,0 +1,231 @@ +//! Tier T3 (ssh/fleet) — developing-today/code#13717. +//! +//! SSH's endpoint-grade shape is a **binary-owned client contract**: +//! the binary constructs the ssh invocation itself — pinned host +//! key, proxy CONNECT helper, identities-only key, connect timeout +//! — instead of delegating to a shell script, and enforces a +//! mandatory overall deadline (child kill → exit 124). The record +//! stays honest about the one thing SSH cannot do: sshd owns the +//! remote process, so a client-side kill ends the session but +//! cannot cancel the remote command protocol-side. +//! +//! Session hygiene: connections multiplex over a fleet-owned +//! ControlMaster socket (`~/.ssh/cm-fleet-…`, persist 600 s — the +//! fleet path is separate from laptop-ssh's, so the two surfaces +//! never share a master), and `fleet ssh close` tears the master +//! down. + +use std::path::PathBuf; +use std::process::Command; + +use fleet_config::Config; + +use crate::forms::{ServeOutcome, T3, announce, shell_quote, spawn_with_deadline}; + +const TARGET: &str = "user@100.99.113.103"; +const EXIT_TIMEOUT: i32 = 124; +const EXIT_USAGE: i32 = 2; +const DEFAULT_TIMEOUT_S: u64 = 300; + +const USAGE: &str = "\ +Usage: fleet ssh [args...] + +Tier T3 (ssh/fleet) of the laptop route forms (#13717): real SSH to +the laptop under a binary-owned client contract (pinned host key, +proxy CONNECT, multiplexing on a fleet-owned socket). + +Commands: + health Run `hostname` over ssh; exit 0 iff the host answers amd + exec [--cwd D] [--timeout S] -- cmd... + Run a command line over ssh (the remote shell parses + it); the remote exit code propagates. --timeout is in + seconds and always applies (default 300): on expiry + the ssh client is killed and the exit code is 124. + Note: ssh's own failure exit is 255. + close Tear down the fleet-owned multiplex master, if any"; + +fn ssh_base(home: &PathBuf, connect_timeout_s: u64) -> Command { + let mut cmd = Command::new("ssh"); + cmd.arg("-o") + .arg(format!( + "ProxyCommand=python3 {}", + home.join("tools/laptop-proxy-connect.py").display() + )) + .arg("-o") + .arg("StrictHostKeyChecking=yes") + .arg("-o") + .arg(format!( + "UserKnownHostsFile={}", + home.join(".ssh/known_hosts_laptop").display() + )) + .arg("-o") + .arg("IdentitiesOnly=yes") + .arg("-i") + .arg(home.join(".ssh/id_ed25519")) + .arg("-o") + .arg(format!( + "ConnectTimeout={}", + connect_timeout_s.clamp(1, 60) + )) + .arg("-o") + .arg("ServerAliveInterval=15") + .arg("-o") + .arg("ServerAliveCountMax=8") + .arg("-o") + .arg("ControlMaster=auto") + .arg("-o") + .arg(format!( + "ControlPath={}", + home.join(".ssh/cm-fleet-%r@%h:%p").display() + )) + .arg("-o") + .arg("ControlPersist=600") + .arg(TARGET); + cmd +} + +/// Serve one exec through this tier (stdio inherited: ssh output is +/// the command's output). Used by the standalone verb and tier 0. +pub fn serve(_config: &Config, cwd: Option<&str>, timeout_s: u64, cmd: &[String]) -> ServeOutcome { + if std::env::var_os("HTTPS_PROXY").is_none() { + return ServeOutcome::Failed( + "HTTPS_PROXY is not set (the proxy CONNECT helper reads it)".into(), + ); + } + let home = fleet_config::Config::home_dir(); + let mut line = cmd.join(" "); + if let Some(d) = cwd { + line = format!("cd {} && {}", shell_quote(d), line); + } + let mut ssh = ssh_base(&home, timeout_s); + ssh.arg(line); + spawn_with_deadline(&mut ssh, timeout_s) +} + +fn health(config: &Config) -> i32 { + match serve(config, None, 20, &["hostname".to_string()]) { + ServeOutcome::Served(0) => { + println!("ssh: ok (form {})", T3.label()); + 0 + } + ServeOutcome::Served(code) => { + eprintln!("ssh: health: ssh exited {code}"); + code + } + ServeOutcome::TimedOut => { + eprintln!("ssh: health: timed out"); + EXIT_TIMEOUT + } + ServeOutcome::Failed(m) => { + eprintln!("ssh: health: {m}"); + 1 + } + } +} + +fn close() -> i32 { + let home = fleet_config::Config::home_dir(); + let mut cmd = Command::new("ssh"); + cmd.arg("-O") + .arg("exit") + .arg("-o") + .arg(format!( + "ControlPath={}", + home.join(".ssh/cm-fleet-%r@%h:%p").display() + )) + .arg(TARGET); + match spawn_with_deadline(&mut cmd, 15) { + ServeOutcome::Served(code) => code, + ServeOutcome::TimedOut => EXIT_TIMEOUT, + ServeOutcome::Failed(m) => { + eprintln!("ssh: close: {m}"); + 1 + } + } +} + +struct ExecArgs { + cwd: Option, + timeout_s: u64, + cmd: Vec, +} + +fn parse_exec_args(args: &[String]) -> Result { + let mut cwd = None; + let mut timeout_s = DEFAULT_TIMEOUT_S; + let mut i = 0; + while i < args.len() { + let a = &args[i]; + if a == "--" { + let cmd: Vec = args[i + 1..].to_vec(); + if cmd.is_empty() { + return Err("exec: no command after --".into()); + } + return Ok(ExecArgs { + cwd, + timeout_s, + cmd, + }); + } else if a == "--cwd" { + i += 1; + cwd = Some( + args.get(i) + .ok_or("exec: --cwd needs a value")? + .to_string(), + ); + } else if let Some(v) = a.strip_prefix("--cwd=") { + cwd = Some(v.to_string()); + } else if a == "--timeout" { + i += 1; + timeout_s = args + .get(i) + .ok_or("exec: --timeout needs a value")? + .parse() + .map_err(|_| "exec: --timeout must be seconds".to_string())?; + } else if let Some(v) = a.strip_prefix("--timeout=") { + timeout_s = v + .parse() + .map_err(|_| "exec: --timeout must be seconds".to_string())?; + } else { + return Err(format!("exec: unexpected argument {a} (command goes after --)")); + } + i += 1; + } + Err("exec: missing -- before the command".into()) +} + +pub fn run(config: &Config, args: &[String]) -> i32 { + match args.first().map(|s| s.as_str()) { + Some("--help") | Some("-h") => { + println!("{USAGE}"); + 0 + } + Some("health") => health(config), + Some("close") => close(), + Some("exec") => { + let parsed = match parse_exec_args(&args[1..]) { + Ok(p) => p, + Err(m) => { + eprintln!("ssh: {m}\n{USAGE}"); + return EXIT_USAGE; + } + }; + announce(T3); + match serve(config, parsed.cwd.as_deref(), parsed.timeout_s, &parsed.cmd) { + ServeOutcome::Served(code) => code, + ServeOutcome::TimedOut => { + eprintln!("ssh: timed out after {}s", parsed.timeout_s); + EXIT_TIMEOUT + } + ServeOutcome::Failed(m) => { + eprintln!("ssh: {m}"); + 1 + } + } + } + _ => { + eprintln!("{USAGE}"); + EXIT_USAGE + } + } +} diff --git a/pkgs/fleet/docs/verbs.md b/pkgs/fleet/docs/verbs.md index 9710de595a..1296452435 100644 --- a/pkgs/fleet/docs/verbs.md +++ b/pkgs/fleet/docs/verbs.md @@ -311,6 +311,57 @@ standalone artifact). Use `fleet laptop-agent --help` for exact forms. This daemon interface is distinct from `fleet queue dispatch --surface laptop`, which currently records a handoff and does not execute arbitrary laptop commands. + +## The laptop route forms — `laptop`, `commander`, `http`, `ssh` (#13717) + +The codified matrix for reaching the laptop: tier 0, 3 methods × 2 +shapes, and the `laptop-ssh` wrapper (T7, a shell script, not a +Fleet domain). Circumstance decides the form; every form is tried +as its own literal command; every result names the form that +served it. The raw shapes (T4 raw curl to the commander endpoint, +T5 raw curl to the daemon API, T6 raw `ssh`) are documented as +literal recipes in the laptop mechanics doc, not here. + +## `laptop` — tier T0, the generic tiered command + +| Verb | Purpose | +| ---------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `tiers` | Print the codified form table (T0–T7) and the composition doctrine. | +| `exec [--form T1\|T2\|T3] [--timeout SECS] [--cwd DIR] -- CMD...` | Walk T1 → T2 → T3 (or one pinned tier), advancing only when a tier fails to serve; reports the serving tier. `--timeout` is per attempt and always applies (default 120). | + +## `commander` — tier T1 (commander/fleet) + +| Verb | Purpose | +| --------------------------------------------- | ----------------------------------------------------------------------- | +| `health` | Initialize an MCP session, run `hostname`, report latency as JSON. | +| `exec [--cwd DIR] [--timeout SECS] -- CMD...` | Run a command line on the laptop through the Desktop Commander MCP endpoint; the remote exit code propagates. The bearer is resolved from the secrets broker by name at call time; spawned processes are polled to completion or force-terminated (timeout exits 124). | + +## `http` — tier T2 (http/fleet) + +The laptop-agent daemon's HTTP API as its own subcommand. The +ladder is HTTP legs only (broker socket → Cloudflare tunnel → +Tailscale CONNECT): this tier never falls through to ssh. The verb +set mirrors `laptop-agent`'s; the difference is the contract — +this domain is the route-form surface, `laptop-agent` is the +daemon's general client. + +| Verb | Purpose | +| ------------------------------------------------------- | -------------------------------------------------- | +| `health` | Check daemon reachability through the HTTP ladder. | +| `jobs` | List daemon jobs. | +| `kill JOB` | Stop a daemon job. | +| `exec [--cwd DIR] [--timeout SECS] [--shell] -- CMD...` | Execute a guarded command and wait; exit codes propagate (daemon timeout exits 124). | +| `run [--cwd DIR] [--shell] -- CMD...` | Submit a guarded command as a job. | +| `poll JOB [--wait SECS]` | Read a job result or wait for it to finish. | +| `fetch REMOTE_PATH LOCAL_PATH` | Fetch a file from the laptop. | + +## `ssh` — tier T3 (ssh/fleet) + +| Verb | Purpose | +| --------------------------------------------- | ----------------------------------------------------------------------- | +| `health` | Run `hostname` over ssh; exit 0 iff the host answers. | +| `exec [--cwd DIR] [--timeout SECS] -- CMD...` | Run a command line over ssh under the binary-owned client contract (pinned host key, proxy CONNECT, fleet-owned multiplex master); the remote exit code propagates; the binary deadline exits 124. ssh's own failure exit is 255. | +| `close` | Tear down the fleet-owned multiplex master, if any. | ## Exit and availability Usage errors generally exit 2. Capability stubs exit 69. Some domains define additional statuses, such as queue transport unavailable or `agent next` having no work. A successful command's exit code and output belong to its handler; preserve both when wrapping Fleet in scripts.