From 3a21e13f08605c6c507d524ca17bb92c8a576a67 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:20:59 -0600 Subject: [PATCH] =?UTF-8?q?fleet=20step=204=20(#5432):=20the=20dispatch=20?= =?UTF-8?q?thin=20client=20=E2=80=94=20status,=20launch,=20enqueue=20over?= =?UTF-8?q?=20pm-stack?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New crates/fleet-dispatch: verbs over pm-dispatch's live HTTP API only (D6 — pm-stack untouched): status = GET /health, launch = POST /v1/sessions, enqueue = POST /v1/tasks. The bearer token resolves BY NAME through fleet-secrets (pm-dispatch.api-token, filed in the vault by this step — the token previously had no by-name home); it enters one Authorization header per request and is never printed or stored. Transports follow fleet-queue's two-shape pattern: direct http:// (FLEET_DISPATCH_URL / [dispatch] url, or the laptop seat's loopback probe) and, for the sandbox, a CONNECT tunnel on the proxy egress via fleet-proxy's tunnel module — the framed session-broker request shape forwards only X-Agent-Token, which pm-dispatch does not accept, so the client opens its own tunnel on the same egress. Exit codes: 0 ok, 2 usage, 3 transport/credentials, 4 service HTTP error, 69 capability stub (unchanged machinery). fleet-config gains the [dispatch] table (url/token_name/port); the registry names the enqueue verb the live API carries. Smoke gains a hermetic dispatch section (stub pm-dispatch + stub bws): 62 passed, 0 failed; workspace tests 51/51. --- pkgs/fleet/Cargo.lock | 12 + pkgs/fleet/Cargo.toml | 5 +- pkgs/fleet/README.md | 32 +- pkgs/fleet/crates/fleet-config/src/lib.rs | 79 ++ pkgs/fleet/crates/fleet-dispatch/Cargo.toml | 20 + pkgs/fleet/crates/fleet-dispatch/src/lib.rs | 852 ++++++++++++++++++++ pkgs/fleet/crates/fleet-registry/src/lib.rs | 4 +- pkgs/fleet/crates/fleet/Cargo.toml | 3 +- pkgs/fleet/crates/fleet/src/main.rs | 18 +- pkgs/fleet/smoke.sh | 104 ++- 10 files changed, 1114 insertions(+), 15 deletions(-) create mode 100644 pkgs/fleet/crates/fleet-dispatch/Cargo.toml create mode 100644 pkgs/fleet/crates/fleet-dispatch/src/lib.rs diff --git a/pkgs/fleet/Cargo.lock b/pkgs/fleet/Cargo.lock index 2feb70a8ea..f1fef3656f 100644 --- a/pkgs/fleet/Cargo.lock +++ b/pkgs/fleet/Cargo.lock @@ -140,6 +140,7 @@ name = "fleet" version = "0.1.0" dependencies = [ "fleet-config", + "fleet-dispatch", "fleet-proxy", "fleet-proxy-proto", "fleet-queue", @@ -156,6 +157,17 @@ dependencies = [ "toml", ] +[[package]] +name = "fleet-dispatch" +version = "0.1.0" +dependencies = [ + "fleet-config", + "fleet-proxy", + "fleet-secrets", + "serde", + "serde_json", +] + [[package]] name = "fleet-proxy" version = "0.1.0" diff --git a/pkgs/fleet/Cargo.toml b/pkgs/fleet/Cargo.toml index 3be1063a37..952ef82a57 100644 --- a/pkgs/fleet/Cargo.toml +++ b/pkgs/fleet/Cargo.toml @@ -6,7 +6,8 @@ # root. Crates land one step at a time: step 1 (#5429) the skeleton # (platform crates + the bin's dispatch/stub machinery + variant # builds); step 2 (#5430) the queue domain (crates/fleet-queue); -# step 3 (#5431) the proxy domain (crates/fleet-proxy). +# step 3 (#5431) the proxy domain (crates/fleet-proxy); step 4 +# (#5432) the dispatch thin client (crates/fleet-dispatch). [workspace] members = [ "crates/fleet-registry", @@ -14,6 +15,7 @@ members = [ "crates/fleet-secrets", "crates/fleet-proxy-proto", "crates/fleet-queue", + "crates/fleet-dispatch", "crates/fleet-proxy", "crates/fleet", ] @@ -31,6 +33,7 @@ fleet-config = { path = "crates/fleet-config" } fleet-secrets = { path = "crates/fleet-secrets" } fleet-proxy-proto = { path = "crates/fleet-proxy-proto" } fleet-queue = { path = "crates/fleet-queue" } +fleet-dispatch = { path = "crates/fleet-dispatch" } fleet-proxy = { path = "crates/fleet-proxy" } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md index 4fcf90d7ec..ac874246ec 100644 --- a/pkgs/fleet/README.md +++ b/pkgs/fleet/README.md @@ -8,9 +8,10 @@ config, secrets-by-name and proxy-protocol platform crates. Step 2 (#5430) landed the queue domain — the repo-queue client and the queue-broker / secrets-broker serve roles are real below. Step 3 (#5431) landed the proxy domain — the session broker, its client, -the hello negotiation and the PATH shims. The remaining domains -are capability stubs until their own steps land (dispatch #5432, -search #5433). +the hello negotiation and the PATH shims. Step 4 (#5432) landed +the dispatch domain — a thin client over pm-stack dispatch. The +remaining domain is a capability stub until its own step lands +(search #5433). ## Layout @@ -23,7 +24,8 @@ crates/fleet-registry/ the FULL domain registry — every domain's capability ids behind them. Compiled into every variant, so --help is always complete. crates/fleet-config/ fleet.toml: [domains] switches, [proxy], - [secrets]; path/ports/socket constants. + [secrets], [dispatch]; path/ports/socket + constants. crates/fleet-secrets/ secrets by NAME only (broker first, then `bws` fallback). Values never appear in code, tests, errors or logs. @@ -51,6 +53,17 @@ crates/fleet-queue/ the queue domain (step 2): the repo-queue repo-queue / queue-broker / secrets-broker artifacts (the `fleet-brokers` package): the migration's rollback inventory. +crates/fleet-dispatch/ the dispatch domain (step 4): a THIN + client over pm-stack's pm-dispatch — + `dispatch status` (GET /health), + `dispatch launch` (POST /v1/sessions), + `dispatch enqueue` (POST /v1/tasks). + pm-stack is not rewritten (D6); the + bearer token resolves by name through + fleet-secrets, and the client reaches + the service directly (laptop seat) or + through its own CONNECT on the proxy + egress (sandbox seat). crates/fleet/ the binary: multicall dispatch, capability stubs, `version`, `capabilities`, help. default.nix the four variant packages (see below) @@ -126,3 +139,14 @@ fleet artifact — each verified by health plus a real enqueue→claim→complete round-trip before the next begins (the evidence lives on #5430). The standalone artifacts above are the rollback for every flip. + +Step 4 flips nothing live: the dispatch domain is a client, and +pm-stack keeps running exactly as it did (the step's gate is a +zero pm-stack diff). What changes is the caller's side — agents +hold `fleet dispatch status|launch|enqueue` instead of +hand-rolled curl against pm-dispatch, with the bearer token +resolved by name (`pm-dispatch.api-token`) through fleet-secrets +and the transport chosen by seat: direct on the laptop, a CONNECT +tunnel on the proxy egress from the sandbox. The steward cron's +call sites move to these verbs only if they want them; no cron +is rewritten by this epic (the evidence lives on #5432). diff --git a/pkgs/fleet/crates/fleet-config/src/lib.rs b/pkgs/fleet/crates/fleet-config/src/lib.rs index 363db8b4f0..69285f0f6c 100644 --- a/pkgs/fleet/crates/fleet-config/src/lib.rs +++ b/pkgs/fleet/crates/fleet-config/src/lib.rs @@ -49,6 +49,17 @@ pub const DEFAULT_BROKER_TOKEN_FILE: &str = "tools/laptop-agent-token"; /// files, read per request, never stored, never logged). pub const DEFAULT_SECRETS_TOKEN_FILE: &str = "tools/secrets-broker-token"; +/// pm-dispatch's port on the laptop (pm-stack/dispatch: the intake +/// service binds loopback + the tailnet address there). +pub const PORT_DISPATCH: u16 = 4879; + +/// The fleet-secrets name the dispatch domain resolves its bearer +/// token by (step 4, #5432). The value is pm-dispatch's +/// `DISPATCH_API_TOKEN`; its by-name home is the vault, per the +/// platform rule that secrets resolve by name through fleet-secrets +/// only. +pub const DEFAULT_DISPATCH_TOKEN_NAME: &str = "pm-dispatch.api-token"; + #[derive(Debug, Clone, Default, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct Config { @@ -56,6 +67,7 @@ pub struct Config { pub domains: BTreeMap, pub proxy: ProxyConfig, pub secrets: SecretsConfig, + pub dispatch: DispatchConfig, } #[derive(Debug, Clone, Default, Deserialize)] @@ -102,6 +114,25 @@ pub struct SecretsConfig { pub token_file: Option, } +/// `[dispatch]` — the dispatch thin client's view of pm-dispatch +/// (step 4, #5432). All optional: the laptop seat needs no config +/// at all (the client probes the loopback bind), and the sandbox +/// seat rides the proxy egress to the target host's dispatch port. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct DispatchConfig { + /// Direct base URL (`http://host[:port]`) for pm-dispatch, + /// bypassing transport selection. `FLEET_DISPATCH_URL` beats + /// the file (the fleet-queue client's env-first pattern). + pub url: Option, + /// The fleet-secrets name the bearer token resolves by + /// (default [`DEFAULT_DISPATCH_TOKEN_NAME`]). + pub token_name: Option, + /// pm-dispatch's port on the target host (default + /// [`PORT_DISPATCH`]). + pub port: Option, +} + #[derive(Debug)] pub enum ConfigError { /// The config file exists but does not parse. Carries the path and @@ -293,6 +324,29 @@ impl Config { resolve_under_home(DEFAULT_BROKER_TOKEN_FILE) } + /// The dispatch base URL when one is configured: + /// `FLEET_DISPATCH_URL` (empty counts as unset, as with every + /// env path here) beats `[dispatch] url`. + pub fn dispatch_url(&self) -> Option { + match std::env::var("FLEET_DISPATCH_URL") { + Ok(v) if !v.trim().is_empty() => Some(v.trim().to_string()), + _ => self.dispatch.url.clone(), + } + } + + /// The fleet-secrets name the dispatch bearer token resolves by. + pub fn dispatch_token_name(&self) -> &str { + self.dispatch + .token_name + .as_deref() + .unwrap_or(DEFAULT_DISPATCH_TOKEN_NAME) + } + + /// pm-dispatch's port on the target host. + pub fn dispatch_port(&self) -> u16 { + self.dispatch.port.unwrap_or(PORT_DISPATCH) + } + /// The secrets-broker token *file path* (never its contents). pub fn secrets_token_file(&self) -> PathBuf { match &self.secrets.token_file { @@ -453,6 +507,31 @@ mod tests { ); } + #[test] + fn dispatch_settings_default_to_the_live_service() { + let cfg = Config::default(); + assert_eq!(cfg.dispatch_port(), PORT_DISPATCH); + assert_eq!(cfg.dispatch_token_name(), DEFAULT_DISPATCH_TOKEN_NAME); + assert_eq!(cfg.dispatch_url(), None); + } + + #[test] + fn dispatch_settings_resolve() { + let (_dir, path) = write_temp( + "[dispatch]\nport = 14879\ntoken_name = \"other.token\"\nurl = \"http://127.0.0.1:9\"\n", + ); + let cfg = Config::load_from(&path).unwrap(); + assert_eq!(cfg.dispatch_port(), 14879); + assert_eq!(cfg.dispatch_token_name(), "other.token"); + assert_eq!(cfg.dispatch_url().as_deref(), Some("http://127.0.0.1:9")); + // A misspelled dispatch key is a loud error like any other. + let (_dir2, path2) = write_temp("[dispatch]\nprt = 1\n"); + match Config::load_from(&path2) { + Err(ConfigError::Parse { .. }) => {} + other => panic!("expected Parse error, got {other:?}"), + } + } + #[test] fn proxy_settings_resolve() { let (_dir, path) = diff --git a/pkgs/fleet/crates/fleet-dispatch/Cargo.toml b/pkgs/fleet/crates/fleet-dispatch/Cargo.toml new file mode 100644 index 0000000000..161485e7b2 --- /dev/null +++ b/pkgs/fleet/crates/fleet-dispatch/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "fleet-dispatch" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The fleet dispatch domain: a thin client over pm-stack's pm-dispatch service — status, launch, and enqueue verbs (epic developing-today/code#5412, step 4 #5432)." + +[dependencies] +fleet-config = { workspace = true } +fleet-secrets = { workspace = true } +# The tunnel half only: the dispatch client opens its own CONNECT +# through the proxy egress (see lib.rs docs for why the framed +# session-broker path cannot carry its Authorization header). The +# broker half (`serve` feature) is not part of this domain. +fleet-proxy = { workspace = true, default-features = false } +serde = { workspace = true } +# preserve_order, as in fleet-queue: the service's JSON key order is +# part of the output shape agents consume. +serde_json = { version = "1", features = ["preserve_order"] } diff --git a/pkgs/fleet/crates/fleet-dispatch/src/lib.rs b/pkgs/fleet/crates/fleet-dispatch/src/lib.rs new file mode 100644 index 0000000000..0ef8b4be7b --- /dev/null +++ b/pkgs/fleet/crates/fleet-dispatch/src/lib.rs @@ -0,0 +1,852 @@ +//! fleet-dispatch — the dispatch domain of the fleet multicall +//! binary (design note §6, epic developing-today/code#5412; +//! step 4, #5432: the thin client). +//! +//! D6: pm-stack is a working TypeScript/Bun service suite and is +//! **not** rewritten, rehomed, or re-platformed by this epic. This +//! crate is verbs over pm-dispatch's existing HTTP interfaces — +//! and nothing else. The live API (pm-stack/dispatch/src/server.ts, +//! read directly for this step) has exactly three routes: +//! +//! fleet dispatch status GET /health (unauthenticated) +//! fleet dispatch launch POST /v1/sessions (launch now) +//! fleet dispatch enqueue POST /v1/tasks (enqueue only) +//! +//! Deltas against the design note, recorded on #5432: the note's +//! rendered state dir (`~/.local/state/pm-dispatch/`) does not +//! exist — pm-dispatch keeps no client-readable state files; its +//! state is the repo queue itself, so per-task status reads ride +//! the queue domain (`fleet queue list`), not this one. And of the +//! service's two auth forms, GitHub Actions OIDC is a CI shape a +//! local client cannot mint; the static bearer is the client form. +//! +//! Auth: `Authorization: Bearer `, the token resolved **by +//! name** through fleet-secrets (default name +//! `pm-dispatch.api-token`; `[dispatch] token_name` overrides) — +//! the platform rule: no domain reads a token file or shells out +//! to a vault on its own. The value enters exactly one HTTP header +//! per request and is never printed, logged, or stored here. +//! +//! Transports, fleet-queue's two-shape pattern over dispatch's +//! routes: +//! 1. **direct** — an `http://` base URL from `FLEET_DISPATCH_URL` +//! or `[dispatch] url`; also the laptop seat's zero-config +//! path (dispatch binds loopback there; a refused loopback +//! probe falls through to the tunnel); +//! 2. **tunnel** — a CONNECT through the fleet proxy egress to +//! the target host's dispatch port (`[dispatch] port`, +//! default 4879): the sandbox's route. The framed +//! session-broker request shape forwards only an +//! `X-Agent-Token` header, which pm-dispatch does not accept, +//! so the client opens its own tunnel on the same egress — +//! the construction fleet-proxy already maintains — and +//! speaks HTTP over it. +//! +//! Exit codes follow the workspace conventions (§3's collision +//! table): 0 ok · 2 usage · 3 transport down / credentials +//! unresolved or rejected · 4 the service answered with an HTTP +//! error status. Success bodies print to stdout as the service +//! sent them (pretty JSON); errors go to stderr. + +use std::io::Read; +use std::net::{TcpStream, ToSocketAddrs}; +use std::time::Duration; + +use fleet_config::Config; +use fleet_secrets::{Resolver, SecretValue}; +use serde_json::{Map, Value, json}; + +const EXIT_OK: i32 = 0; +const EXIT_USAGE: i32 = 2; +const EXIT_TRANSPORT: i32 = 3; +const EXIT_HTTP: i32 = 4; + +/// The task kinds pm-dispatch accepts for `POST /v1/tasks` +/// (pm-stack/dispatch/src/validate.ts `TASK_KINDS`, read live). +const TASK_KINDS: [&str; 4] = ["triage", "small_fix", "pr_shepherd", "ci_investigation"]; + +#[derive(Debug)] +enum DispatchError { + Usage(String), + Transport(String), + Http { status: u16, message: String }, +} + +impl DispatchError { + fn exit_code(&self) -> i32 { + match self { + DispatchError::Usage(_) => EXIT_USAGE, + DispatchError::Transport(_) => EXIT_TRANSPORT, + DispatchError::Http { .. } => EXIT_HTTP, + } + } + fn message(&self) -> String { + match self { + DispatchError::Usage(m) | DispatchError::Transport(m) => m.clone(), + DispatchError::Http { status, message } => { + format!("pm-dispatch answered HTTP {status}: {message}") + } + } + } +} + +type Result = std::result::Result; + +fn usage(msg: impl Into) -> DispatchError { + DispatchError::Usage(msg.into()) +} + +fn transport_err(msg: impl Into) -> DispatchError { + DispatchError::Transport(msg.into()) +} + +// --------------------------------------------------------------------------- +// Transport selection + HTTP exchange +// --------------------------------------------------------------------------- + +enum Transport { + /// Plain HTTP to `host:port` (the authority is also the Host + /// header). + Direct { authority: String }, + /// CONNECT through the proxy egress to the target host. + Tunnel { target_host: String, port: u16 }, +} + +impl Transport { + fn describe(&self) -> String { + match self { + Transport::Direct { authority } => format!("direct http://{authority}"), + Transport::Tunnel { target_host, port } => { + format!("tunnel via proxy egress to {target_host}:{port}") + } + } + } + fn host_header(&self) -> String { + match self { + Transport::Direct { authority } => authority.clone(), + Transport::Tunnel { target_host, port } => format!("{target_host}:{port}"), + } + } +} + +/// Parse an `http://host[:port]` base URL into its authority. No +/// path prefix: pm-dispatch's routes are rooted, and a smuggled +/// path would silently re-root every request. +fn parse_direct_url(url: &str, default_port: u16) -> Result { + let rest = url + .strip_prefix("http://") + .ok_or_else(|| usage(format!("dispatch URL {url:?} must be http://host[:port]")))?; + let authority = rest.trim_end_matches('/'); + if authority.is_empty() || authority.contains('/') || authority.contains(char::is_whitespace) { + return Err(usage(format!( + "dispatch URL {url:?} must be http://host[:port] with no path" + ))); + } + if authority.contains(':') { + Ok(authority.to_string()) + } else { + Ok(format!("{authority}:{default_port}")) + } +} + +fn pick_transport(config: &Config) -> Result { + let port = config.dispatch_port(); + if let Some(url) = config.dispatch_url() { + return Ok(Transport::Direct { + authority: parse_direct_url(&url, port)?, + }); + } + // The laptop seat needs no configuration: pm-dispatch binds + // loopback there. Probe it (briefly) before paying for a + // tunnel — on the sandbox nothing answers and the probe is a + // fast refusal. + let loopback = ("127.0.0.1", port) + .to_socket_addrs() + .ok() + .and_then(|mut a| a.next()); + if let Some(addr) = loopback { + if TcpStream::connect_timeout(&addr, Duration::from_millis(750)).is_ok() { + return Ok(Transport::Direct { + authority: format!("127.0.0.1:{port}"), + }); + } + } + if config.proxy_direct() { + return Ok(Transport::Direct { + authority: format!("{}:{port}", config.target_host()), + }); + } + Ok(Transport::Tunnel { + target_host: config.target_host().to_string(), + port, + }) +} + +fn open_stream(config: &Config, transport: &Transport) -> Result { + match transport { + Transport::Direct { authority } => { + let addr = authority + .to_socket_addrs() + .map_err(|e| { + transport_err(format!("cannot resolve dispatch address {authority}: {e}")) + })? + .next() + .ok_or_else(|| { + transport_err(format!("cannot resolve dispatch address {authority}")) + })?; + let stream = + TcpStream::connect_timeout(&addr, Duration::from_secs(10)).map_err(|e| { + transport_err(format!("cannot connect to pm-dispatch at {authority}: {e}")) + })?; + stream.set_read_timeout(Some(Duration::from_secs(300))).ok(); + stream.set_write_timeout(Some(Duration::from_secs(60))).ok(); + Ok(stream) + } + Transport::Tunnel { target_host, port } => { + let egress = fleet_proxy::tunnel::egress_from_env(config.egress_proxy_port()) + .map_err(transport_err)?; + fleet_proxy::tunnel::connect_tunnel(Some(&egress), target_host, *port).map_err(|e| { + transport_err(format!( + "cannot open tunnel to pm-dispatch at {target_host}:{port}: {e}" + )) + }) + } + } +} + +/// Read one HTTP/1.1 response: status line, headers, and a body +/// framed by chunked encoding, Content-Length, or connection +/// close — the three shapes a Bun.serve JSON reply can take. +fn read_response(stream: &mut TcpStream) -> Result<(u16, Vec)> { + let mut raw: Vec = Vec::with_capacity(8192); + let mut chunk = [0u8; 16384]; + let header_end = loop { + if let Some(pos) = find_subslice(&raw, b"\r\n\r\n") { + break pos + 4; + } + let n = stream + .read(&mut chunk) + .map_err(|e| transport_err(format!("pm-dispatch read failed: {e}")))?; + if n == 0 { + return Err(transport_err( + "pm-dispatch closed the connection without a response", + )); + } + raw.extend_from_slice(&chunk[..n]); + if raw.len() > 1024 * 1024 { + return Err(transport_err("pm-dispatch response headers exceed 1 MiB")); + } + }; + let head = String::from_utf8_lossy(&raw[..header_end]).into_owned(); + let status: u16 = head + .split_whitespace() + .nth(1) + .and_then(|c| c.parse().ok()) + .ok_or_else(|| transport_err("pm-dispatch answered with a malformed status line"))?; + let mut content_length: Option = None; + let mut chunked = false; + for line in head.lines().skip(1) { + let Some((name, value)) = line.split_once(':') else { + continue; + }; + let value = value.trim(); + if name.eq_ignore_ascii_case("content-length") { + content_length = value.parse().ok(); + } else if name.eq_ignore_ascii_case("transfer-encoding") + && value.to_ascii_lowercase().contains("chunked") + { + chunked = true; + } + } + let mut body: Vec = raw[header_end..].to_vec(); + // Fill the body per its framing. `Connection: close` was sent, + // so EOF is a valid terminator for every shape. + let complete = |body: &[u8]| -> bool { + if chunked { + dechunked_len(body).is_some() + } else if let Some(n) = content_length { + body.len() >= n + } else { + false + } + }; + while !complete(&body) { + let n = stream + .read(&mut chunk) + .map_err(|e| transport_err(format!("pm-dispatch read failed: {e}")))?; + if n == 0 { + break; + } + body.extend_from_slice(&chunk[..n]); + if body.len() > 64 * 1024 * 1024 { + return Err(transport_err("pm-dispatch response body exceeds 64 MiB")); + } + } + let body = if chunked { + dechunk(&body) + } else if let Some(n) = content_length { + body[..n.min(body.len())].to_vec() + } else { + body + }; + Ok((status, body)) +} + +/// Length of the decoded body if `body` holds at least one full +/// chunked stream, else None (more bytes needed). +fn dechunked_len(body: &[u8]) -> Option { + let mut total = 0usize; + let mut rest = body; + loop { + let line_end = find_subslice(rest, b"\r\n")?; + let size_str = String::from_utf8_lossy(&rest[..line_end]).into_owned(); + let size = usize::from_str_radix(size_str.trim().split(';').next()?.trim(), 16).ok()?; + rest = &rest[line_end + 2..]; + if size == 0 { + return Some(total); + } + if rest.len() < size + 2 { + return None; + } + total += size; + rest = &rest[size + 2..]; + } +} + +fn dechunk(body: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut rest = body; + while let Some(line_end) = find_subslice(rest, b"\r\n") { + let size_str = String::from_utf8_lossy(&rest[..line_end]).into_owned(); + let Ok(size) = usize::from_str_radix(size_str.trim().split(';').next().unwrap_or(""), 16) + else { + break; + }; + rest = &rest[line_end + 2..]; + if size == 0 || rest.len() < size { + break; + } + out.extend_from_slice(&rest[..size]); + rest = &rest[size..]; + if rest.starts_with(b"\r\n") { + rest = &rest[2..]; + } + } + out +} + +fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option { + haystack.windows(needle.len()).position(|w| w == needle) +} + +/// One request/response exchange. The bearer token, when given, +/// enters exactly this one header — its only appearance anywhere. +fn exchange( + config: &Config, + transport: &Transport, + method: &str, + path: &str, + token: Option<&SecretValue>, + body: Option<&Value>, +) -> Result<(u16, Value)> { + let mut stream = open_stream(config, transport)?; + let payload = body + .map(serde_json::to_vec) + .transpose() + .map_err(|e| transport_err(format!("cannot encode request body: {e}")))?; + let mut head = format!( + "{method} {path} HTTP/1.1\r\nHost: {}\r\n", + transport.host_header() + ); + if let Some(token) = token { + head.push_str(&format!("Authorization: Bearer {}\r\n", token.expose())); + } + head.push_str("Content-Type: application/json\r\n"); + if let Some(payload) = &payload { + head.push_str(&format!("Content-Length: {}\r\n", payload.len())); + } + head.push_str("Connection: close\r\n\r\n"); + use std::io::Write; + stream + .write_all(head.as_bytes()) + .and_then(|_| match &payload { + Some(p) => stream.write_all(p), + None => Ok(()), + }) + .map_err(|e| transport_err(format!("pm-dispatch write failed: {e}")))?; + let (status, raw) = read_response(&mut stream)?; + let parsed: Value = if raw.is_empty() { + Value::Null + } else { + serde_json::from_slice(&raw).map_err(|_| { + transport_err(format!( + "pm-dispatch answered HTTP {status} with a non-JSON body" + )) + })? + }; + Ok((status, parsed)) +} + +/// The shared response tail: 2xx prints the service's JSON; 401 is +/// a credentials failure (exit 3, the repair-the-transport branch); +/// any other error status is exit 4 with the service's own message. +fn finish(verb: &str, result: Result<(u16, Value)>) -> Result { + let (status, body) = result?; + match status { + 200..=299 => Ok(body), + 401 => Err(transport_err( + "pm-dispatch rejected the bearer token (HTTP 401): the resolved secret \ + does not match the service's DISPATCH_API_TOKEN", + )), + _ => { + let error_text = body.get("error").and_then(|e| e.as_str()); + let mut message = match error_text { + Some(e) => e.to_string(), + None => serde_json::to_string(&body).unwrap_or_default(), + }; + // Error bodies can carry ids the caller needs (a failed + // launch's 502 names its cancelled task_id) — keep the + // whole body when it says more than the error string. + if error_text.is_some() && body.as_object().is_some_and(|m| m.len() > 1) { + message.push_str(&format!( + " [{}]", + serde_json::to_string(&body).unwrap_or_default() + )); + } + if message.chars().count() > 600 { + message = format!("{}…", message.chars().take(600).collect::()); + } + Err(DispatchError::Http { + status, + message: format!("{verb}: {message}"), + }) + } + } +} + +fn print_json(v: &Value) { + println!( + "{}", + serde_json::to_string_pretty(v).unwrap_or_else(|_| "null".to_string()) + ); +} + +/// Resolve the bearer token by name through fleet-secrets — the +/// one secrets path (§1). Failure is a transport-class error: the +/// client cannot even present credentials. +fn bearer_token(config: &Config) -> Result { + let name = config.dispatch_token_name(); + Resolver::default_chain(config) + .resolve(name) + .map_err(|e| transport_err(e.to_string())) +} + +// --------------------------------------------------------------------------- +// Verbs +// --------------------------------------------------------------------------- + +fn verb_status(config: &Config) -> Result { + let transport_sel = pick_transport(config)?; + let described = transport_sel.describe(); + let body = finish( + "status", + exchange(config, &transport_sel, "GET", "/health", None, None), + )?; + // The service's health body, plus the route it arrived by — the + // two facts a status verb exists to report. + let mut out: Map = match body { + Value::Object(m) => m, + other => { + let mut m = Map::new(); + m.insert("health".to_string(), other); + m + } + }; + out.insert("transport".to_string(), Value::String(described)); + Ok(Value::Object(out)) +} + +const LAUNCH_USAGE: &str = "\ +Usage: fleet dispatch launch --repo --prompt [options] + +Launch an OpenCode session on the laptop NOW via pm-dispatch +(POST /v1/sessions): creates the tracking issue and queue task, +starts the session, and assigns the task to it. + + --repo required; an allowlisted fleet repo + --prompt required (or --prompt-file) + --prompt-file read the prompt from a file + --title default: the prompt's first line + --model model hint for the session + --directory must be the repo's laptop primary or inside it + --priority

integer 10-90, or critical|high|normal|low + --issue / --no-issue create the tracking issue (default: issue) + --wait / --no-wait wait for the launch to complete (default: wait)"; + +const ENQUEUE_USAGE: &str = "\ +Usage: fleet dispatch enqueue --repo --title --prompt [options] + +Enqueue work into the repo queue via pm-dispatch (POST /v1/tasks) +without launching a session. + + --repo required; an allowlisted fleet repo + --title required + --prompt required (or --prompt-file) + --prompt-file read the prompt from a file + --kind triage|small_fix|pr_shepherd|ci_investigation (default: triage) + --priority

integer 10-90, or critical|high|normal|low + --model stored as the payload's model hint only + --issue create a tracking issue first (default: no issue) + --issue-number attach to this existing issue instead + --dedupe-key default: canonical key from the issue, else unique"; + +/// A minimal `--flag value` / `--flag=value` parser, workspace +/// style (the queue client parses the same way). +struct Args { + values: Map, + flags: Map, +} + +fn parse_args(args: &[String], value_flags: &[&str], bool_flags: &[&str]) -> Result { + let mut values = Map::new(); + let mut flags = Map::new(); + let mut i = 0; + while i < args.len() { + let arg = &args[i]; + let Some(long) = arg.strip_prefix("--") else { + return Err(usage(format!("unexpected argument {arg:?}"))); + }; + let (name, inline) = match long.split_once('=') { + Some((n, v)) => (n, Some(v.to_string())), + None => (long, None), + }; + if bool_flags.contains(&name) { + if inline.is_some() { + return Err(usage(format!("--{name} takes no value"))); + } + flags.insert(name.to_string(), Value::Bool(true)); + } else if value_flags.contains(&name) { + let value = match inline { + Some(v) => v, + None => { + i += 1; + args.get(i) + .cloned() + .ok_or_else(|| usage(format!("--{name} needs a value")))? + } + }; + values.insert(name.to_string(), Value::String(value)); + } else { + return Err(usage(format!("unknown option --{name}"))); + } + i += 1; + } + Ok(Args { values, flags }) +} + +impl Args { + fn get(&self, name: &str) -> Option<&str> { + self.values.get(name).and_then(|v| v.as_str()) + } + fn require(&self, name: &str) -> Result<&str> { + self.get(name) + .ok_or_else(|| usage(format!("--{name} is required"))) + } + fn flag(&self, name: &str) -> bool { + self.flags + .get(name) + .and_then(|v| v.as_bool()) + .unwrap_or(false) + } +} + +fn prompt_of(args: &Args) -> Result { + if let Some(path) = args.get("prompt-file") { + return std::fs::read_to_string(path) + .map_err(|e| usage(format!("cannot read prompt file {path}: {e}"))); + } + args.require("prompt").map(str::to_string) +} + +/// Priority crosses the wire as a number when it parses as one — +/// the service also accepts decimal strings and the named scale, +/// and validating the scale is its job (validate.ts), not a thin +/// client's. +fn priority_value(raw: &str) -> Value { + match raw.parse::() { + Ok(n) => json!(n), + Err(_) => Value::String(raw.to_string()), + } +} + +fn verb_launch(config: &Config, args: &[String]) -> Result { + if args.iter().any(|a| a == "--help" || a == "-h") { + println!("{LAUNCH_USAGE}"); + return Ok(Value::Null); + } + let parsed = parse_args( + args, + &[ + "repo", + "prompt", + "prompt-file", + "title", + "model", + "directory", + "priority", + ], + &["issue", "no-issue", "wait", "no-wait"], + )?; + let mut body = Map::new(); + body.insert( + "repo".into(), + Value::String(parsed.require("repo")?.to_string()), + ); + body.insert("prompt".into(), Value::String(prompt_of(&parsed)?)); + if let Some(v) = parsed.get("title") { + body.insert("title".into(), Value::String(v.to_string())); + } + if let Some(v) = parsed.get("model") { + body.insert("model".into(), Value::String(v.to_string())); + } + if let Some(v) = parsed.get("directory") { + body.insert("directory".into(), Value::String(v.to_string())); + } + if let Some(v) = parsed.get("priority") { + body.insert("priority".into(), priority_value(v)); + } + if parsed.flag("no-issue") { + body.insert("issue".into(), Value::Bool(false)); + } else if parsed.flag("issue") { + body.insert("issue".into(), Value::Bool(true)); + } + if parsed.flag("no-wait") { + body.insert("wait".into(), Value::Bool(false)); + } else if parsed.flag("wait") { + body.insert("wait".into(), Value::Bool(true)); + } + let token = bearer_token(config)?; + let transport_sel = pick_transport(config)?; + finish( + "launch", + exchange( + config, + &transport_sel, + "POST", + "/v1/sessions", + Some(&token), + Some(&Value::Object(body)), + ), + ) +} + +fn verb_enqueue(config: &Config, args: &[String]) -> Result { + if args.iter().any(|a| a == "--help" || a == "-h") { + println!("{ENQUEUE_USAGE}"); + return Ok(Value::Null); + } + let parsed = parse_args( + args, + &[ + "repo", + "title", + "prompt", + "prompt-file", + "kind", + "priority", + "model", + "issue-number", + "dedupe-key", + ], + &["issue"], + )?; + let mut body = Map::new(); + body.insert( + "repo".into(), + Value::String(parsed.require("repo")?.to_string()), + ); + body.insert( + "title".into(), + Value::String(parsed.require("title")?.to_string()), + ); + body.insert("prompt".into(), Value::String(prompt_of(&parsed)?)); + if let Some(kind) = parsed.get("kind") { + if !TASK_KINDS.contains(&kind) { + return Err(usage(format!( + "unknown task kind {kind:?}: expected one of {}", + TASK_KINDS.join(", ") + ))); + } + body.insert("kind".into(), Value::String(kind.to_string())); + } + if let Some(v) = parsed.get("priority") { + body.insert("priority".into(), priority_value(v)); + } + if let Some(v) = parsed.get("model") { + body.insert("model".into(), Value::String(v.to_string())); + } + if parsed.flag("issue") { + body.insert("issue".into(), Value::Bool(true)); + } + if let Some(v) = parsed.get("issue-number") { + let n: i64 = v + .parse() + .map_err(|_| usage(format!("--issue-number must be an integer, got {v:?}")))?; + body.insert("issue_number".into(), json!(n)); + } + if let Some(v) = parsed.get("dedupe-key") { + body.insert("dedupe_key".into(), Value::String(v.to_string())); + } + let token = bearer_token(config)?; + let transport_sel = pick_transport(config)?; + finish( + "enqueue", + exchange( + config, + &transport_sel, + "POST", + "/v1/tasks", + Some(&token), + Some(&Value::Object(body)), + ), + ) +} + +// --------------------------------------------------------------------------- +// Entry point +// --------------------------------------------------------------------------- + +const USAGE: &str = "\ +Usage: fleet dispatch [args...] + +Thin client over pm-stack dispatch (D6 — the service is not +rewritten; these are verbs over its existing HTTP interfaces): + + status GET /health — is pm-dispatch up, which build + launch [options] POST /v1/sessions — launch a session now + enqueue [options] POST /v1/tasks — enqueue work, no session + +Per-task status lives in the queue: fleet queue list. +Run 'fleet dispatch launch --help' or 'fleet dispatch enqueue +--help' for a verb's options."; + +/// The dispatch domain's entry point (the bin crate routes here +/// once the capability checks have passed). +pub fn run(config: &Config, args: &[String]) -> i32 { + let verb = args.first().map(|s| s.as_str()); + let rest = if args.is_empty() { &[][..] } else { &args[1..] }; + let result = match verb { + Some("status") => verb_status(config), + Some("launch") => verb_launch(config, rest), + Some("enqueue") => verb_enqueue(config, rest), + Some(other) => Err(usage(format!( + "unknown dispatch command {other:?}\n\n{USAGE}" + ))), + None => Err(usage(USAGE.to_string())), + }; + match result { + Ok(Value::Null) => EXIT_OK, + Ok(body) => { + print_json(&body); + EXIT_OK + } + Err(e) => { + eprintln!("fleet dispatch: {}", e.message()); + e.exit_code() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn strings(list: &[&str]) -> Vec { + list.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn direct_url_parsing() { + assert_eq!( + parse_direct_url("http://127.0.0.1:4879", 4879).unwrap(), + "127.0.0.1:4879" + ); + assert_eq!( + parse_direct_url("http://localhost", 4879).unwrap(), + "localhost:4879" + ); + assert_eq!( + parse_direct_url("http://127.0.0.1:4879/", 4879).unwrap(), + "127.0.0.1:4879" + ); + assert!(parse_direct_url("https://dispatch.example", 4879).is_err()); + assert!(parse_direct_url("http://127.0.0.1:4879/v1", 4879).is_err()); + assert!(parse_direct_url("http://", 4879).is_err()); + } + + #[test] + fn priority_crosses_as_number_or_string() { + assert_eq!(priority_value("20"), json!(20)); + assert_eq!(priority_value("high"), json!("high")); + assert_eq!(priority_value("40.5"), json!("40.5")); + } + + #[test] + fn launch_body_carries_only_set_fields() { + let parsed = parse_args( + &strings(&[ + "--repo", + "developing-today/code", + "--prompt", + "fix it", + "--no-wait", + ]), + &[ + "repo", + "prompt", + "prompt-file", + "title", + "model", + "directory", + "priority", + ], + &["issue", "no-issue", "wait", "no-wait"], + ) + .unwrap(); + assert_eq!(parsed.require("repo").unwrap(), "developing-today/code"); + assert!(parsed.flag("no-wait")); + assert!(!parsed.flag("issue")); + assert!(parse_args(&strings(&["--repo"]), &["repo"], &[]).is_err()); + assert!(parse_args(&strings(&["--bogus", "x"]), &["repo"], &[]).is_err()); + } + + #[test] + fn enqueue_rejects_unknown_kinds() { + let parsed = parse_args(&strings(&["--kind", "bogus"]), &["kind"], &[]).unwrap(); + let kind = parsed.get("kind").unwrap(); + assert!(!TASK_KINDS.contains(&kind)); + assert!(TASK_KINDS.contains(&"triage")); + } + + #[test] + fn chunked_bodies_dechunk() { + let wire = b"4\r\nWiki\r\n5\r\npedia\r\n0\r\n\r\n"; + assert_eq!(dechunk(wire), b"Wikipedia"); + assert_eq!(dechunked_len(wire), Some(9)); + assert_eq!(dechunked_len(b"4\r\nWi"), None); + } + + #[test] + fn usage_errors_exit_2_and_transport_3() { + assert_eq!(usage("x").exit_code(), 2); + assert_eq!(transport_err("x").exit_code(), 3); + assert_eq!( + DispatchError::Http { + status: 409, + message: "m".into() + } + .exit_code(), + 4 + ); + } +} diff --git a/pkgs/fleet/crates/fleet-registry/src/lib.rs b/pkgs/fleet/crates/fleet-registry/src/lib.rs index 59ef9b9e1c..21b76b8d7b 100644 --- a/pkgs/fleet/crates/fleet-registry/src/lib.rs +++ b/pkgs/fleet/crates/fleet-registry/src/lib.rs @@ -237,11 +237,11 @@ pub const DOMAINS: &[Domain] = &[ }, Domain { name: "dispatch", - summary: "Thin client over the pm-stack dispatch services (status and launch verbs).", + summary: "Thin client over pm-stack dispatch: status, launch, and enqueue verbs.", capabilities: &[Capability::Dispatch], primary: Capability::Dispatch, aliases: &[], - subcommands: &["status", "launch"], + subcommands: &["status", "launch", "enqueue"], }, Domain { name: "search", diff --git a/pkgs/fleet/crates/fleet/Cargo.toml b/pkgs/fleet/crates/fleet/Cargo.toml index 16bc3a9a65..a8fce7521d 100644 --- a/pkgs/fleet/crates/fleet/Cargo.toml +++ b/pkgs/fleet/crates/fleet/Cargo.toml @@ -15,6 +15,7 @@ fleet-registry = { workspace = true } fleet-config = { workspace = true } fleet-proxy-proto = { workspace = true } fleet-queue = { workspace = true, optional = true } +fleet-dispatch = { workspace = true, optional = true } # The proxy CLIENT is part of every variant's registry (the # connect capability ships in all three builds); only the broker # half (fleet-proxy's `serve` feature) is variant-gated, through @@ -50,5 +51,5 @@ queue-broker = ["dep:fleet-secrets", "dep:fleet-queue", "fleet-queue/queue-broke secrets-broker = ["dep:fleet-secrets", "dep:fleet-queue", "fleet-queue/secrets-broker"] search = ["dep:fleet-secrets"] search-serve = ["dep:fleet-secrets"] -dispatch = ["dep:fleet-secrets"] +dispatch = ["dep:fleet-dispatch"] laptop-agent = ["dep:fleet-secrets"] diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index 7f72e64200..613b54d98b 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -6,11 +6,12 @@ //! dispatch layer, the capability-stub machinery, and the variant //! builds. Step 2 (#5430) landed the first real domain — queue: the //! repo-queue client and the queue-broker / secrets-broker serve -//! roles run for real below. A compiled-in domain that has not -//! landed yet answers with the "not implemented yet" form of the -//! stub — but the *surface* is complete and honest: every variant -//! renders the full registry, and every missing capability answers -//! with a branchable stub, never a parser error. +//! roles run for real below; step 3 (#5431) the proxy domain; step 4 +//! (#5432) the dispatch thin client. A compiled-in domain that has +//! not landed yet answers with the "not implemented yet" form of +//! the stub — but the *surface* is complete and honest: every +//! variant renders the full registry, and every missing capability +//! answers with a branchable stub, never a parser error. //! //! Dispatch order (§3), extended by Refinement A (name-scoping): //! @@ -352,6 +353,7 @@ fn print_domain_help(surface: &Surface, d: &Domain) { let status = match surface.domain_state(d) { CapState::Available => match d.name { "queue" => "included in this build", + "dispatch" => "included in this build", "proxy" => "included in this build", "serve" => { "included in this build (queue-broker and secrets-broker roles; \ @@ -469,6 +471,12 @@ fn run_domain(surface: &Surface, d: &Domain, args: &[String], invoked_as: &str) if d.name == "serve" && args.first().map(|s| s.as_str()) == Some("secrets-broker") { return fleet_queue::secrets_broker::run(); } + // Step 4 (#5432): the dispatch domain runs for real — a + // thin client over pm-stack's pm-dispatch service. + #[cfg(feature = "dispatch")] + if d.name == "dispatch" { + return fleet_dispatch::run(&surface.config, args); + } if d.name == "proxy" { return run_proxy(surface, args); } diff --git a/pkgs/fleet/smoke.sh b/pkgs/fleet/smoke.sh index 27fda786bb..9a7ef7b329 100755 --- a/pkgs/fleet/smoke.sh +++ b/pkgs/fleet/smoke.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash # Per-variant smoke suite for the fleet workspace # (step 1, developing-today/code#5429; queue-domain sections added -# by step 2, #5430; proxy-domain sections by step 3, #5431). +# by step 2, #5430; proxy-domain sections by step 3, #5431; +# dispatch-domain sections by step 4, #5432). # # Usage: # smoke.sh @@ -38,7 +39,8 @@ QB_PID="" PB_PID="" UP_PID="" IDLE_PID="" -trap 'kill $SB_PID $QB_PID $PB_PID $UP_PID $IDLE_PID 2>/dev/null; rm -rf "$TMP"' EXIT +DS_PID="" +trap 'kill $SB_PID $QB_PID $PB_PID $UP_PID $IDLE_PID $DS_PID 2>/dev/null; rm -rf "$TMP"' EXIT ok() { PASS=$((PASS + 1)); echo "ok - $1"; } bad() { FAIL=$((FAIL + 1)); echo "FAIL - $1"; } @@ -333,6 +335,104 @@ kill "$SB_PID" "$QB_PID" 2>/dev/null SB_PID="" QB_PID="" +echo "== dispatch domain: thin client over a stub pm-dispatch (step 4, #5432) ==" +# Hermetic dispatch world: a stub pm-dispatch on a scratch loopback +# port (health unauthenticated; POSTs bearer-checked, with canned +# answers and one deliberate 409) and a stub `bws` on PATH, so the +# client's by-name token resolution through fleet-secrets succeeds +# with no vault and no session broker (the scratch HOME has no +# broker socket, so the chain falls through to the bws source). +# The client must resolve the token by name, present it as +# Authorization: Bearer, and print the service's JSON verbatim. +DS="$TMP/dispatch" +mkdir -p "$DS/bin" "$DS/home" +cat > "$DS/stub.py" <<'PYEOF' +import json +from http.server import BaseHTTPRequestHandler, HTTPServer +TOKEN = "smoke-dispatch-token" +class H(BaseHTTPRequestHandler): + def log_message(self, *a): pass + def _send(self, code, obj): + body = json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + def do_GET(self): + if self.path == "/health": + self._send(200, {"ok": True, "status": "ok", "version": "smoke"}) + else: + self._send(404, {"error": "not found"}) + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length) if length else b"{}" + if self.headers.get("Authorization") != "Bearer " + TOKEN: + self._send(401, {"error": "unauthorized"}) + return + try: + req = json.loads(raw) + except Exception: + req = {} + if self.path == "/v1/sessions": + self._send(201, {"task_id": 4242, "session_id": "ses_smoke", + "issue_number": None, + "queue": "repo-health-code-pilot", + "status": "claimed"}) + elif self.path == "/v1/tasks": + if req.get("dedupe_key") == "smoke-dupe": + self._send(409, {"error": "dedupe_key already has an open task"}) + return + self._send(201, {"task_id": 4243, "issue_number": None, + "queue": "repo-health-code-pilot"}) + else: + self._send(404, {"error": "not found"}) +HTTPServer(("127.0.0.1", 14879), H).serve_forever() +PYEOF +python3 "$DS/stub.py" >"$DS/stub.log" 2>&1 & +DS_PID=$! +cat > "$DS/bin/bws" <<'EOF' +#!/usr/bin/env bash +# fleet-secrets' bws fallback, stubbed: one secret under a fixed id. +if [ "$1 $2" = "secret list" ]; then + echo '[{"id":"smoke-id","key":"pm-dispatch.api-token"}]' +elif [ "$1 $2" = "secret get" ]; then + echo '{"id":"smoke-id","key":"pm-dispatch.api-token","value":"smoke-dispatch-token"}' +else + exit 1 +fi +EOF +chmod +x "$DS/bin/bws" +printf '[dispatch]\nport = 14879\n' > "$DS/fleet.toml" +sleep 1 +run "dispatch: status round-trips the stub /health" 0 '"version": "smoke"' \ + env HOME="$DS/home" PATH="$DS/bin:$PATH" FLEET_CONFIG="$DS/fleet.toml" \ + "$FULL_OUT/bin/fleet" dispatch status +run "dispatch: status names its transport" 0 '"transport": "direct http://127.0.0.1:14879"' \ + env HOME="$DS/home" PATH="$DS/bin:$PATH" FLEET_CONFIG="$DS/fleet.toml" \ + "$FULL_OUT/bin/fleet" dispatch status +run "dispatch: launch round-trips with the by-name bearer token" 0 '"task_id": 4242' \ + env HOME="$DS/home" PATH="$DS/bin:$PATH" FLEET_CONFIG="$DS/fleet.toml" \ + "$FULL_OUT/bin/fleet" dispatch launch --repo developing-today/code \ + --prompt "smoke launch" --no-wait +run "dispatch: enqueue round-trips" 0 '"task_id": 4243' \ + env HOME="$DS/home" PATH="$DS/bin:$PATH" FLEET_CONFIG="$DS/fleet.toml" \ + "$FULL_OUT/bin/fleet" dispatch enqueue --repo developing-today/code \ + --title "smoke" --prompt "smoke enqueue" +run "dispatch: a service HTTP error exits 4 with its message" 4 "dedupe_key already has an open task" \ + env HOME="$DS/home" PATH="$DS/bin:$PATH" FLEET_CONFIG="$DS/fleet.toml" \ + "$FULL_OUT/bin/fleet" dispatch enqueue --repo developing-today/code \ + --title "smoke" --prompt "x" --dedupe-key smoke-dupe +run "dispatch: an unknown task kind is a usage error" 2 "unknown task kind" \ + env HOME="$DS/home" PATH="$DS/bin:$PATH" FLEET_CONFIG="$DS/fleet.toml" \ + "$FULL_OUT/bin/fleet" dispatch enqueue --repo developing-today/code \ + --title "t" --prompt "p" --kind bogus +run "dispatch: an unresolved token name exits 3 before any request" 3 "unresolved" \ + env HOME="$DS/home" PATH="/nonexistent" FLEET_CONFIG="$DS/fleet.toml" \ + "$FULL_OUT/bin/fleet" dispatch launch --repo developing-today/code --prompt "x" +kill "$DS_PID" 2>/dev/null +DS_PID="" + echo "== name narrowing: full build invoked as fleet-connect ==" ln -s "$FULL_OUT/bin/fleet" "$TMP/fleet-connect" run "narrowed: version lists only the connect set" 0 "$CONNECT_CAPS" "$TMP/fleet-connect" version