From ff7fa63d0dce96410132f28fcbcfcfb05dfd0b73 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Wed, 4 Nov 2026 23:40:53 +0100 Subject: [PATCH] feat(cli-rs): add the run command Port of handlers/run.ts, run/run.ts and run/noninteractive.ts: text and --format json output, permissions and forms auto-rejected (or approved with --auto), -f attachments typed by the mime-types table, stdin and words after --, -w worktrees, titles and archived sessions. Events and messages stay JSON so JSON lines pass server fields through unchanged. P-CLI scenarios in parity/scenarios/C.10 compare it with the TS run. --- packages/cli-rs/Cargo.lock | 2 + packages/cli-rs/crates/api/src/client.rs | 3 +- packages/cli-rs/crates/cli/Cargo.toml | 2 + .../cli-rs/crates/cli/src/commands/client.rs | 28 +- .../cli-rs/crates/cli/src/commands/run.rs | 289 +++- packages/cli-rs/crates/cli/src/run/files.rs | 188 +++ packages/cli-rs/crates/cli/src/run/mime.rs | 1244 ++++++++++++++++ packages/cli-rs/crates/cli/src/run/prompt.rs | 1308 +++++++++++++++++ packages/cli-rs/crates/cli/src/run/ui.rs | 29 + .../parity/scenarios/C.10/bad-model.cli.ts | 5 + .../parity/scenarios/C.10/continue.cli.ts | 20 + .../parity/scenarios/C.10/dashdash.cli.ts | 8 + .../scenarios/C.10/file-directory.cli.ts | 9 + .../parity/scenarios/C.10/file-large.cli.ts | 9 + .../parity/scenarios/C.10/file-missing.cli.ts | 9 + .../cli-rs/parity/scenarios/C.10/files.cli.ts | 16 + .../cli-rs/parity/scenarios/C.10/fixture.ts | 168 +++ .../parity/scenarios/C.10/fork-alone.cli.ts | 5 + .../cli-rs/parity/scenarios/C.10/fork.cli.ts | 18 + .../cli-rs/parity/scenarios/C.10/form.cli.ts | 21 + .../parity/scenarios/C.10/interrupted.cli.ts | 8 + .../cli-rs/parity/scenarios/C.10/json.cli.ts | 14 + .../parity/scenarios/C.10/no-message.cli.ts | 5 + .../parity/scenarios/C.10/not-promoted.cli.ts | 9 + .../scenarios/C.10/permission-auto.cli.ts | 12 + .../scenarios/C.10/permission-pending.cli.ts | 15 + .../parity/scenarios/C.10/permission.cli.ts | 13 + .../scenarios/C.10/pre-promotion-error.cli.ts | 13 + .../parity/scenarios/C.10/question.cli.ts | 14 + .../scenarios/C.10/reconcile-json.cli.ts | 9 + .../parity/scenarios/C.10/reconcile.cli.ts | 21 + .../parity/scenarios/C.10/server-down.cli.ts | 10 + .../parity/scenarios/C.10/session-new.cli.ts | 12 + .../parity/scenarios/C.10/stdin-only.cli.ts | 9 + .../cli-rs/parity/scenarios/C.10/stdin.cli.ts | 9 + .../scenarios/C.10/step-failed-json.cli.ts | 9 + .../parity/scenarios/C.10/step-failed.cli.ts | 13 + .../cli-rs/parity/scenarios/C.10/text.cli.ts | 26 + .../scenarios/C.10/thinking-text.cli.ts | 13 + .../parity/scenarios/C.10/tool-failed.cli.ts | 22 + .../scenarios/C.10/worktree-continue.cli.ts | 5 + .../parity/scenarios/C.10/worktree.cli.ts | 15 + packages/cli-rs/script/gen/mime.ts | 20 + 43 files changed, 3666 insertions(+), 11 deletions(-) create mode 100644 packages/cli-rs/crates/cli/src/run/files.rs create mode 100644 packages/cli-rs/crates/cli/src/run/mime.rs create mode 100644 packages/cli-rs/crates/cli/src/run/prompt.rs create mode 100644 packages/cli-rs/crates/cli/src/run/ui.rs create mode 100644 packages/cli-rs/parity/scenarios/C.10/bad-model.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/continue.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/dashdash.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/file-directory.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/file-large.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/file-missing.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/files.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/fixture.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/fork-alone.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/fork.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/form.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/interrupted.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/json.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/no-message.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/not-promoted.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/permission-auto.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/permission-pending.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/permission.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/pre-promotion-error.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/question.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/reconcile-json.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/reconcile.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/server-down.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/session-new.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/stdin-only.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/stdin.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/step-failed-json.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/step-failed.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/text.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/thinking-text.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/tool-failed.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/worktree-continue.cli.ts create mode 100644 packages/cli-rs/parity/scenarios/C.10/worktree.cli.ts create mode 100644 packages/cli-rs/script/gen/mime.ts diff --git a/packages/cli-rs/Cargo.lock b/packages/cli-rs/Cargo.lock index d69e1035e8c..08e231f2e92 100644 --- a/packages/cli-rs/Cargo.lock +++ b/packages/cli-rs/Cargo.lock @@ -1084,9 +1084,11 @@ name = "opencode-cli" version = "0.1.0" dependencies = [ "anyhow", + "base64", "chrono", "clap", "clap_complete", + "futures-util", "log", "opencode-acp", "opencode-api", diff --git a/packages/cli-rs/crates/api/src/client.rs b/packages/cli-rs/crates/api/src/client.rs index 241e7787b52..6c8bfbbe80c 100644 --- a/packages/cli-rs/crates/api/src/client.rs +++ b/packages/cli-rs/crates/api/src/client.rs @@ -232,7 +232,8 @@ impl Client { .map(|value| value.data) } - pub(crate) async fn empty(&self, call: Call, options: &RequestOptions) -> Result<(), Error> { + /// Sends `call` and expects no body. Public so a caller can send a body with its own key order. + pub async fn empty(&self, call: Call, options: &RequestOptions) -> Result<(), Error> { self.execute(call, options).await.map(|_| ()) } diff --git a/packages/cli-rs/crates/cli/Cargo.toml b/packages/cli-rs/crates/cli/Cargo.toml index 6cfa30bd6af..b12c806a9c2 100644 --- a/packages/cli-rs/crates/cli/Cargo.toml +++ b/packages/cli-rs/crates/cli/Cargo.toml @@ -21,7 +21,9 @@ workspace = true [dependencies] anyhow.workspace = true +base64.workspace = true chrono.workspace = true +futures-util.workspace = true clap = { workspace = true, features = ["string"] } clap_complete.workspace = true log = { workspace = true, features = ["kv"] } diff --git a/packages/cli-rs/crates/cli/src/commands/client.rs b/packages/cli-rs/crates/cli/src/commands/client.rs index ded1e004818..3e0f017f696 100644 --- a/packages/cli-rs/crates/cli/src/commands/client.rs +++ b/packages/cli-rs/crates/cli/src/commands/client.rs @@ -32,10 +32,28 @@ pub struct Connected { /// `ServerConnection.resolve()` with the command's `--server` and `--standalone`, and a client for it. /// Keep the result for as long as the command talks to the server. pub async fn connect(context: &Context) -> anyhow::Result { - connect_in(context, &Paths::from_env()?, &Env::from_env()).await + connect_in(context, &Paths::from_env()?, &Env::from_env(), false).await } -async fn connect_in(context: &Context, paths: &Paths, env: &Env) -> anyhow::Result { +/// `ServerConnection.resolve({ autostart: false })` (`run`): a running service, else a standalone server, so a +/// one-off command never leaves a new service running. +pub async fn connect_without_autostart(context: &Context) -> anyhow::Result { + connect_in(context, &Paths::from_env()?, &Env::from_env(), true).await +} + +impl Connected { + /// True for a registered background service (`Resolved.service` in TS). + pub fn is_service(&self) -> bool { + matches!(self._connection.source, connect::Source::Service { .. }) + } +} + +async fn connect_in( + context: &Context, + paths: &Paths, + env: &Env, + standalone_fallback: bool, +) -> anyhow::Result { let transport: Arc = Arc::new(Reqwest::default()); let connection = connect::resolve( transport.clone(), @@ -45,8 +63,8 @@ async fn connect_in(context: &Context, paths: &Paths, env: &Env) -> anyhow::Resu server: context.server.server.clone(), standalone: context.server.standalone, client_version: crate::help::VERSION.to_owned(), - // `ServerConnection.resolve()` with no arguments: start the service quietly when none runs. - standalone_fallback: false, + // Without it, `ServerConnection.resolve()` with no arguments: start the service quietly when none runs. + standalone_fallback, on_start: None, }, ) @@ -170,7 +188,7 @@ process.exit(0) }, }; // The commands bind the result as these lines do; `let (_, client)` stopped the server here. - let server = connect_in(&context, &paths, &env).await.unwrap(); + let server = connect_in(&context, &paths, &env, false).await.unwrap(); let info = server.client.server_info(&RequestOptions::default()).await; assert_eq!(info.unwrap().version, "test"); } diff --git a/packages/cli-rs/crates/cli/src/commands/run.rs b/packages/cli-rs/crates/cli/src/commands/run.rs index 9e20903ff34..75f94e05ab9 100644 --- a/packages/cli-rs/crates/cli/src/commands/run.rs +++ b/packages/cli-rs/crates/cli/src/commands/run.rs @@ -1,8 +1,287 @@ -//! `run`: send a message and print the reply. +//! `run`: send a message and print the reply (`packages/cli/src/commands/handlers/run.ts`, +//! `packages/cli/src/run/run.ts`). The prompt itself and its output are in `run/prompt.rs`. -use super::{Context, not_built}; -use crate::args::RunArgs; +use std::cell::Cell; +use std::io::{IsTerminal, Read}; +use std::rc::Rc; -pub fn run(_context: &Context, _args: &RunArgs) -> anyhow::Result<()> { - not_built("run", "C.10") +use opencode_api::client::RequestOptions; +use opencode_api::generated::{SessionID, SessionUpdateInput}; +use opencode_store::target::{self, Prepared, TargetInput}; +use serde_json::json; + +use super::Context; +use super::client::{Connected, connect_without_autostart}; +use crate::args::{OutputFormat, RunArgs}; + +#[path = "../run/files.rs"] +mod files; +#[path = "../run/mime.rs"] +mod mime; +#[path = "../run/prompt.rs"] +mod prompt; +#[path = "../run/ui.rs"] +mod ui; + +pub fn run(context: &Context, args: &RunArgs) -> anyhow::Result<()> { + let json = args.format == OutputFormat::Json; + let exit = Rc::new(Cell::new(0u8)); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + tokio::task::LocalSet::new().block_on(&runtime, async { + // A one-off run uses the background service when it is already up, but never leaves a new one running. + let server = match connect_without_autostart(context).await { + Ok(server) => server, + Err(error) => { + log::error!("run could not resolve its server: {error:#}"); + return report(json, &exit, &error.to_string(), None); + } + }; + if let Err(failure) = execute(args, &server, json, &exit).await { + report(json, &exit, &failure.message, failure.session.as_deref()); + } + }); + match exit.get() { + 0 => Ok(()), + code => Err(crate::output::Exit(code).into()), + } +} + +struct Failure { + message: String, + session: Option, +} + +impl From for Failure { + fn from(error: T) -> Self { + Self { + message: error.to_string(), + session: None, + } + } +} + +async fn execute( + args: &RunArgs, + server: &Connected, + json: bool, + exit: &Rc>, +) -> Result<(), Failure> { + if args.fork && !args.continue_ && args.session.is_none() { + return Err("--fork requires --continue or --session".into()); + } + if args.worktree.is_some() && (args.continue_ || args.session.is_some()) { + return Err( + "--worktree starts a new session and cannot be combined with --continue or --session" + .into(), + ); + } + let root = opencode_local::paths::start_directory()?; + let directory = root.to_string_lossy().into_owned(); + let piped = if std::io::stdin().is_terminal() { + None + } else { + let mut bytes = Vec::new(); + std::io::stdin().read_to_end(&mut bytes)?; + Some(String::from_utf8_lossy(&bytes).into_owned()) + }; + let message = merge_input(format_message(&words(args)), piped).unwrap_or_default(); + if message.trim().is_empty() { + return Err("You must provide a message".into()); + } + let files = args + .file + .iter() + .map(|file| files::prepare(file, &root)) + .collect::, _>>()?; + + let client = &server.client; + let explicit = target::parse_model(args.model.as_deref())?; + let worktree = match args.worktree() { + None => None, + Some(name) => Some( + target::create_worktree_location( + client, + Some(directory.clone()), + name.map(str::to_owned), + ) + .await?, + ), + }; + if let Some(worktree) = &worktree { + ui::println(&[&format!( + "{}worktree {}{}", + ui::TEXT_DIM, + worktree.root, + ui::TEXT_NORMAL + )]); + } + let target = target::resolve_session_target( + client, + TargetInput { + directory: Some( + worktree + .map(|worktree| worktree.directory) + .unwrap_or(directory), + ), + continue_latest: args.continue_, + session: args.session.clone().map(SessionID), + fork: args.fork, + model: explicit, + agent: args.agent.clone(), + environment: server + .is_service() + .then(opencode_store::environment::session_environment), + }, + |next| async move { + Ok(Prepared { + model: next.model, + agent: next.agent, + }) + }, + ) + .await?; + let session = target.session.id.0.clone(); + let failed = |error: String| Failure { + message: error, + session: Some(session.clone()), + }; + let title = match &args.title { + Some(title) if !target.resume => Some(if title.is_empty() { + default_title(&message) + } else { + title.clone() + }), + _ => None, + }; + // Archive before the first prompt is admitted, so the run never reaches an inbox as working or finished. + let archived = args.archived && (!target.resume || args.fork); + if title.is_some() || archived { + client + .session_update( + &SessionUpdateInput { + session_id: target.session.id.clone(), + title, + archived: archived.then_some(true), + ..Default::default() + }, + &RequestOptions::default(), + ) + .await?; + } + prompt::run(prompt::Input { + client: client.clone(), + session_id: session.clone(), + directory: target.location.directory.0.clone(), + message, + files, + agent: target.agent, + model: target.model, + thinking: args.thinking, + json, + auto: args.permissions.auto(), + exit: exit.clone(), + }) + .await + .map_err(failed) +} + +/// The message words, then the words after `--` again, as the TS handler appends `process.argv` after the +/// separator to the parsed message. +fn words(args: &RunArgs) -> Vec { + let argv: Vec = std::env::args().skip(1).collect(); + let after = argv + .iter() + .position(|arg| arg == "--") + .map_or(&[][..], |at| &argv[at + 1..]); + args.message.iter().chain(after).cloned().collect() +} + +/// Words with spaces are quoted, with their quotes escaped. +fn format_message(words: &[String]) -> Option { + let value = words + .iter() + .map(|word| { + if word.contains(' ') { + format!("\"{}\"", word.replace('"', "\\\"")) + } else { + word.clone() + } + }) + .collect::>() + .join(" "); + (!value.is_empty()).then_some(value) +} + +fn merge_input(message: Option, piped: Option) -> Option { + let piped = piped.filter(|piped| !piped.is_empty()); + match (message, piped) { + (None, piped) => piped, + (Some(message), None) => Some(message), + (Some(message), Some(piped)) => Some(format!("{message}\n{piped}")), + } +} + +/// `--title ""`: the first 50 UTF-16 units of the message, and `...` when it is longer. +fn default_title(message: &str) -> String { + let units: Vec = message.encode_utf16().collect(); + let head = String::from_utf16_lossy(&units[..units.len().min(50)]); + if units.len() > 50 { + return head + "..."; + } + head +} + +/// `reportRunError`: exit code 1, and the error as a line on stderr or a JSON event on stdout. +fn report(json: bool, exit: &Cell, message: &str, session: Option<&str>) { + exit.set(1); + if json { + let line = json!({ + "type": "error", + "timestamp": std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_millis() as u64), + "sessionID": session.unwrap_or_default(), + "error": { "type": "unknown", "message": message }, + }); + let _ = crate::output::print(&(line.to_string() + "\n")); + return; + } + ui::error(message); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn messages_quote_words_with_spaces() { + let words = ["fix".to_owned(), "the \"bug\" now".to_owned()]; + assert_eq!( + format_message(&words).as_deref(), + Some("fix \"the \\\"bug\\\" now\"") + ); + assert_eq!(format_message(&[]), None); + } + + #[test] + fn stdin_follows_the_message() { + assert_eq!( + merge_input(Some("a".into()), Some("b\n".into())).as_deref(), + Some("a\nb\n") + ); + assert_eq!(merge_input(None, Some("".into())), None); + assert_eq!( + merge_input(Some("a".into()), Some("".into())).as_deref(), + Some("a") + ); + } + + #[test] + fn default_titles_cut_at_fifty_units() { + assert_eq!(default_title("short"), "short"); + let long = "x".repeat(51); + assert_eq!(default_title(&long), "x".repeat(50) + "..."); + } } diff --git a/packages/cli-rs/crates/cli/src/run/files.rs b/packages/cli-rs/crates/cli/src/run/files.rs new file mode 100644 index 00000000000..f45d4c05043 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/run/files.rs @@ -0,0 +1,188 @@ +//! `run -f` attachments (`prepareFile` in `packages/cli/src/run/run.ts` and `noninteractive.ts`): read the +//! file, type it, and send text inline in the prompt and anything else as a data URL. + +use std::io::Read; +use std::path::Path; + +use base64::Engine; +use base64::engine::general_purpose::STANDARD; + +const ATTACH_FILE_MAX_BYTES: u64 = 10 * 1024 * 1024; + +/// What the prompt gets for one file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Prepared { + /// `` and the content, appended to the prompt text. + Text(String), + /// A `files` attachment: the data URL and the file name. + Attachment { uri: String, name: String }, +} + +/// Reads `input`, relative to `root`. The errors are the TS messages. +pub fn prepare(input: &str, root: &Path) -> Result { + let file = resolve(root, input); + let mut handle = + std::fs::File::open(&file).map_err(|_| format!("File not found: {input}"))?; + let metadata = handle + .metadata() + .map_err(|_| format!("File not found: {input}"))?; + if !metadata.is_file() || metadata.len() > ATTACH_FILE_MAX_BYTES { + return Err(format!( + "Cannot attach a directory, special file, or file larger than 10 MiB: {input}" + )); + } + let mut bytes = Vec::with_capacity(metadata.len() as usize); + // At most the size `stat` reported, as the TS read loop does. + (&mut handle) + .take(metadata.len()) + .read_to_end(&mut bytes) + .map_err(|error| error.to_string())?; + let name = file + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + Ok(classify(&file.to_string_lossy(), name, bytes)) +} + +fn classify(path: &str, name: String, bytes: Vec) -> Prepared { + let detected = mime_type(path); + // Valid UTF-8 is exactly what survives `Buffer.toString` and back unchanged. + let mime = if detected.starts_with("image/") || detected == "application/pdf" { + detected + } else if !is_binary(&bytes) && std::str::from_utf8(&bytes).is_ok() { + "text/plain" + } else { + detected + }; + // Any `text/plain` file goes inline, decoded with replacement characters when it is not UTF-8. + if mime == "text/plain" { + let text = String::from_utf8_lossy(&bytes); + return Prepared::Text(format!("\n{text}\n")); + } + Prepared::Attachment { + uri: format!("data:{mime};base64,{}", STANDARD.encode(&bytes)), + name, + } +} + +/// `path.resolve(root, input)`: absolute, with `.` and `..` resolved lexically. +fn resolve(root: &Path, input: &str) -> std::path::PathBuf { + let joined = root.join(input); + let mut out = std::path::PathBuf::from("/"); + for part in joined.components() { + match part { + std::path::Component::ParentDir => { + out.pop(); + } + std::path::Component::Normal(part) => out.push(part), + _ => {} + } + } + out +} + +/// `FSUtil.mimeType`: `mime-types`' `lookup`, else `application/octet-stream`. +pub fn mime_type(path: &str) -> &'static str { + lookup(path).unwrap_or("application/octet-stream") +} + +// `extname("x." + path)`: the extension of the last segment, unless its only dot leads. +fn lookup(path: &str) -> Option<&'static str> { + let base = format!("x.{path}"); + let base = base.rsplit('/').next().unwrap_or_default(); + let dot = base.rfind('.').filter(|at| *at > 0)?; + let extension = base[dot + 1..].to_lowercase(); + super::mime::TYPES + .binary_search_by(|(key, _)| (*key).cmp(extension.as_str())) + .ok() + .map(|index| super::mime::TYPES[index].1) +} + +fn is_binary(bytes: &[u8]) -> bool { + if bytes.is_empty() { + return false; + } + if bytes.contains(&0) { + return true; + } + let control = bytes + .iter() + .filter(|byte| **byte < 9 || (**byte > 13 && **byte < 32)) + .count(); + control as f64 / bytes.len() as f64 > 0.3 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn types_follow_mime_types() { + // From `bun -e 'console.log(require("mime-types").lookup(p))'`. + for (path, expected) in [ + ("/a/b.png", "image/png"), + ("/a/B.PDF", "application/pdf"), + ("/a/notes.md", "text/markdown"), + ("/a/data.json", "application/json"), + ("/a/x.tar.gz", "application/gzip"), + ("/a/Makefile", "application/octet-stream"), + ("/a/.bashrc", "application/octet-stream"), + ("/a/trailing.", "application/octet-stream"), + ("png", "image/png"), + ] { + assert_eq!(mime_type(path), expected, "{path}"); + } + } + + #[test] + fn text_goes_inline_and_the_rest_as_data_urls() { + let text = classify("/w/a.md", "a.md".into(), b"# hi\n".to_vec()); + assert_eq!( + text, + Prepared::Text("\n# hi\n\n".into()) + ); + // An image stays an image even when its bytes are text. + let image = classify("/w/a.png", "a.png".into(), b"abc".to_vec()); + assert_eq!( + image, + Prepared::Attachment { + uri: "data:image/png;base64,YWJj".into(), + name: "a.png".into() + } + ); + let binary = classify("/w/a.bin", "a.bin".into(), vec![0, 1, 2]); + assert_eq!( + binary, + Prepared::Attachment { + uri: "data:application/octet-stream;base64,AAEC".into(), + name: "a.bin".into() + } + ); + // Invalid UTF-8 keeps the detected type: a `.txt` file goes inline with a replacement character, + // anything else as a data URL. + let latin1 = classify("/w/a.txt", "a.txt".into(), vec![b'h', 0xe9]); + assert_eq!( + latin1, + Prepared::Text("\nh\u{fffd}\n".into()) + ); + let csv = classify("/w/a.csv", "a.csv".into(), vec![b'h', 0xe9]); + assert_eq!( + csv, + Prepared::Attachment { + uri: "data:text/csv;base64,aOk=".into(), + name: "a.csv".into() + } + ); + assert!(is_binary(&[1, 2, 3, b'a'])); + assert!(!is_binary(b"\t\r\n")); + } + + #[test] + fn paths_resolve_like_node() { + assert_eq!( + resolve(Path::new("/w/x"), "../a/./b.txt"), + Path::new("/w/a/b.txt") + ); + assert_eq!(resolve(Path::new("/w"), "/abs/c"), Path::new("/abs/c")); + } +} diff --git a/packages/cli-rs/crates/cli/src/run/mime.rs b/packages/cli-rs/crates/cli/src/run/mime.rs new file mode 100644 index 00000000000..6c40ebb21e4 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/run/mime.rs @@ -0,0 +1,1244 @@ +// Generated by script/gen/mime.ts from the `mime-types` package. Do not edit. + +/// `(extension, type)`, sorted by extension. +pub const TYPES: &[(&str, &str)] = &[ + ("123", "application/vnd.lotus-1-2-3"), + ("1km", "application/vnd.1000minds.decision-model+xml"), + ("210", "model/step"), + ("3dml", "text/vnd.in3d.3dml"), + ("3ds", "image/x-3ds"), + ("3g2", "video/3gpp2"), + ("3gp", "video/3gpp"), + ("3gpp", "video/3gpp"), + ("3mf", "model/3mf"), + ("7z", "application/x-7z-compressed"), + ("aab", "application/x-authorware-bin"), + ("aac", "audio/aac"), + ("aam", "application/x-authorware-map"), + ("aas", "application/x-authorware-seg"), + ("abw", "application/x-abiword"), + ("ac", "application/pkix-attr-cert"), + ("acc", "application/vnd.americandynamics.acc"), + ("ace", "application/x-ace-compressed"), + ("acu", "application/vnd.acucobol"), + ("acutc", "application/vnd.acucorp"), + ("adp", "audio/adpcm"), + ("adts", "audio/aac"), + ("aep", "application/vnd.audiograph"), + ("afm", "application/x-font-type1"), + ("afp", "application/vnd.ibm.modcap"), + ("age", "application/vnd.age"), + ("ahead", "application/vnd.ahead.space"), + ("ai", "application/postscript"), + ("aif", "audio/x-aiff"), + ("aifc", "audio/x-aiff"), + ("aiff", "audio/x-aiff"), + ("air", "application/vnd.adobe.air-application-installer-package+zip"), + ("ait", "application/vnd.dvb.ait"), + ("ami", "application/vnd.amiga.ami"), + ("aml", "application/automationml-aml+xml"), + ("amlx", "application/automationml-amlx+zip"), + ("amr", "audio/amr"), + ("apk", "application/vnd.android.package-archive"), + ("apng", "image/apng"), + ("appcache", "text/cache-manifest"), + ("appinstaller", "application/appinstaller"), + ("application", "application/x-ms-application"), + ("appx", "application/appx"), + ("appxbundle", "application/appxbundle"), + ("apr", "application/vnd.lotus-approach"), + ("arc", "application/x-freearc"), + ("arj", "application/x-arj"), + ("asc", "application/pgp-keys"), + ("asf", "video/x-ms-asf"), + ("asm", "text/x-asm"), + ("aso", "application/vnd.accpac.simply.aso"), + ("asx", "video/x-ms-asf"), + ("atc", "application/vnd.acucorp"), + ("atom", "application/atom+xml"), + ("atomcat", "application/atomcat+xml"), + ("atomdeleted", "application/atomdeleted+xml"), + ("atomsvc", "application/atomsvc+xml"), + ("atx", "application/vnd.antix.game-component"), + ("au", "audio/basic"), + ("avci", "image/avci"), + ("avcs", "image/avcs"), + ("avi", "video/x-msvideo"), + ("avif", "image/avif"), + ("aw", "application/applixware"), + ("azf", "application/vnd.airzip.filesecure.azf"), + ("azs", "application/vnd.airzip.filesecure.azs"), + ("azv", "image/vnd.airzip.accelerator.azv"), + ("azw", "application/vnd.amazon.ebook"), + ("b16", "image/vnd.pco.b16"), + ("bary", "model/vnd.bary"), + ("bat", "application/x-msdownload"), + ("bcpio", "application/x-bcpio"), + ("bdf", "application/x-font-bdf"), + ("bdm", "application/vnd.syncml.dm+wbxml"), + ("bdo", "application/vnd.nato.bindingdataobject+xml"), + ("bdoc", "application/bdoc"), + ("bed", "application/vnd.realvnc.bed"), + ("bh2", "application/vnd.fujitsu.oasysprs"), + ("bin", "application/octet-stream"), + ("blb", "application/x-blorb"), + ("blend", "application/x-blender"), + ("blorb", "application/x-blorb"), + ("bmi", "application/vnd.bmi"), + ("bmml", "application/vnd.balsamiq.bmml+xml"), + ("bmp", "image/bmp"), + ("book", "application/vnd.framemaker"), + ("box", "application/vnd.previewsystems.box"), + ("boz", "application/x-bzip2"), + ("bpk", "application/octet-stream"), + ("brush", "application/vnd.procreate.brush"), + ("brushset", "application/vnd.procrate.brushset"), + ("bsp", "model/vnd.valve.source.compiled-map"), + ("btf", "image/prs.btif"), + ("btif", "image/prs.btif"), + ("buffer", "application/octet-stream"), + ("bz", "application/x-bzip"), + ("bz2", "application/x-bzip2"), + ("c", "text/x-c"), + ("c11amc", "application/vnd.cluetrust.cartomobile-config"), + ("c11amz", "application/vnd.cluetrust.cartomobile-config-pkg"), + ("c4d", "application/vnd.clonk.c4group"), + ("c4f", "application/vnd.clonk.c4group"), + ("c4g", "application/vnd.clonk.c4group"), + ("c4p", "application/vnd.clonk.c4group"), + ("c4u", "application/vnd.clonk.c4group"), + ("cab", "application/vnd.ms-cab-compressed"), + ("caf", "audio/x-caf"), + ("cap", "application/vnd.tcpdump.pcap"), + ("car", "application/vnd.curl.car"), + ("cat", "application/vnd.ms-pki.seccat"), + ("cb7", "application/x-cbr"), + ("cba", "application/x-cbr"), + ("cbr", "application/x-cbr"), + ("cbt", "application/x-cbr"), + ("cbz", "application/x-cbr"), + ("cc", "text/x-c"), + ("cco", "application/x-cocoa"), + ("cct", "application/x-director"), + ("ccxml", "application/ccxml+xml"), + ("cdbcmsg", "application/vnd.contact.cmsg"), + ("cdf", "application/x-netcdf"), + ("cdfx", "application/cdfx+xml"), + ("cdkey", "application/vnd.mediastation.cdkey"), + ("cdmia", "application/cdmi-capability"), + ("cdmic", "application/cdmi-container"), + ("cdmid", "application/cdmi-domain"), + ("cdmio", "application/cdmi-object"), + ("cdmiq", "application/cdmi-queue"), + ("cdx", "chemical/x-cdx"), + ("cdxml", "application/vnd.chemdraw+xml"), + ("cdy", "application/vnd.cinderella"), + ("cer", "application/pkix-cert"), + ("cfs", "application/x-cfs-compressed"), + ("cgm", "image/cgm"), + ("chat", "application/x-chat"), + ("chm", "application/vnd.ms-htmlhelp"), + ("chrt", "application/vnd.kde.kchart"), + ("cif", "chemical/x-cif"), + ("cii", "application/vnd.anser-web-certificate-issue-initiation"), + ("cil", "application/vnd.ms-artgalry"), + ("cjs", "application/node"), + ("cla", "application/vnd.claymore"), + ("class", "application/java-vm"), + ("cld", "model/vnd.cld"), + ("clkk", "application/vnd.crick.clicker.keyboard"), + ("clkp", "application/vnd.crick.clicker.palette"), + ("clkt", "application/vnd.crick.clicker.template"), + ("clkw", "application/vnd.crick.clicker.wordbank"), + ("clkx", "application/vnd.crick.clicker"), + ("clp", "application/x-msclip"), + ("cmc", "application/vnd.cosmocaller"), + ("cmdf", "chemical/x-cmdf"), + ("cml", "chemical/x-cml"), + ("cmp", "application/vnd.yellowriver-custom-menu"), + ("cmx", "image/x-cmx"), + ("cod", "application/vnd.rim.cod"), + ("coffee", "text/coffeescript"), + ("com", "application/x-msdownload"), + ("conf", "text/plain"), + ("cpio", "application/x-cpio"), + ("cpl", "application/cpl+xml"), + ("cpp", "text/x-c"), + ("cpt", "application/mac-compactpro"), + ("crd", "application/x-mscardfile"), + ("crl", "application/pkix-crl"), + ("crt", "application/x-x509-ca-cert"), + ("crx", "application/x-chrome-extension"), + ("cryptonote", "application/vnd.rig.cryptonote"), + ("csh", "application/x-csh"), + ("csl", "application/vnd.citationstyles.style+xml"), + ("csml", "chemical/x-csml"), + ("csp", "application/vnd.commonspace"), + ("css", "text/css"), + ("cst", "application/x-director"), + ("csv", "text/csv"), + ("cu", "application/cu-seeme"), + ("curl", "text/vnd.curl"), + ("cwl", "application/cwl"), + ("cww", "application/prs.cww"), + ("cxt", "application/x-director"), + ("cxx", "text/x-c"), + ("dae", "model/vnd.collada+xml"), + ("daf", "application/vnd.mobius.daf"), + ("dart", "application/vnd.dart"), + ("dataless", "application/vnd.fdsn.seed"), + ("davmount", "application/davmount+xml"), + ("dbf", "application/vnd.dbf"), + ("dbk", "application/docbook+xml"), + ("dcm", "application/dicom"), + ("dcmp", "application/vnd.dcmp+xml"), + ("dcr", "application/x-director"), + ("dcurl", "text/vnd.curl.dcurl"), + ("dd2", "application/vnd.oma.dd2+xml"), + ("ddd", "application/vnd.fujixerox.ddd"), + ("ddf", "application/vnd.syncml.dmddf+xml"), + ("dds", "image/vnd.ms-dds"), + ("deb", "application/x-debian-package"), + ("def", "text/plain"), + ("deploy", "application/octet-stream"), + ("der", "application/x-x509-ca-cert"), + ("dfac", "application/vnd.dreamfactory"), + ("dgc", "application/x-dgc-compressed"), + ("dib", "image/bmp"), + ("dic", "text/x-c"), + ("dir", "application/x-director"), + ("dis", "application/vnd.mobius.dis"), + ("disposition-notification", "message/disposition-notification"), + ("dist", "application/octet-stream"), + ("distz", "application/octet-stream"), + ("djv", "image/vnd.djvu"), + ("djvu", "image/vnd.djvu"), + ("dll", "application/x-msdownload"), + ("dmg", "application/x-apple-diskimage"), + ("dmp", "application/vnd.tcpdump.pcap"), + ("dms", "application/octet-stream"), + ("dna", "application/vnd.dna"), + ("dng", "image/x-adobe-dng"), + ("doc", "application/msword"), + ("docm", "application/vnd.ms-word.document.macroenabled.12"), + ("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"), + ("dot", "application/msword"), + ("dotm", "application/vnd.ms-word.template.macroenabled.12"), + ("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"), + ("dp", "application/vnd.osgi.dp"), + ("dpg", "application/vnd.dpgraph"), + ("dpx", "image/dpx"), + ("dra", "audio/vnd.dra"), + ("drle", "image/dicom-rle"), + ("drm", "application/vnd.procreate.dream"), + ("dsc", "text/prs.lines.tag"), + ("dssc", "application/dssc+der"), + ("dtb", "application/x-dtbook+xml"), + ("dtd", "application/xml-dtd"), + ("dts", "audio/vnd.dts"), + ("dtshd", "audio/vnd.dts.hd"), + ("dump", "application/octet-stream"), + ("dvb", "video/vnd.dvb.file"), + ("dvi", "application/x-dvi"), + ("dwd", "application/atsc-dwd+xml"), + ("dwf", "model/vnd.dwf"), + ("dwg", "image/vnd.dwg"), + ("dxf", "image/vnd.dxf"), + ("dxp", "application/vnd.spotfire.dxp"), + ("dxr", "application/x-director"), + ("ear", "application/java-archive"), + ("ecelp4800", "audio/vnd.nuera.ecelp4800"), + ("ecelp7470", "audio/vnd.nuera.ecelp7470"), + ("ecelp9600", "audio/vnd.nuera.ecelp9600"), + ("ecma", "application/ecmascript"), + ("edm", "application/vnd.novadigm.edm"), + ("edx", "application/vnd.novadigm.edx"), + ("efif", "application/vnd.picsel"), + ("ei6", "application/vnd.pg.osasli"), + ("elc", "application/octet-stream"), + ("emf", "image/emf"), + ("eml", "message/rfc822"), + ("emma", "application/emma+xml"), + ("emotionml", "application/emotionml+xml"), + ("emz", "application/x-msmetafile"), + ("eol", "audio/vnd.digital-winds"), + ("eot", "application/vnd.ms-fontobject"), + ("eps", "application/postscript"), + ("epub", "application/epub+zip"), + ("es3", "application/vnd.eszigno3+xml"), + ("esa", "application/vnd.osgi.subsystem"), + ("esf", "application/vnd.epson.esf"), + ("et3", "application/vnd.eszigno3+xml"), + ("etx", "text/x-setext"), + ("eva", "application/x-eva"), + ("evy", "application/x-envoy"), + ("exe", "application/x-msdos-program"), + ("exi", "application/exi"), + ("exp", "application/express"), + ("exr", "image/aces"), + ("ext", "application/vnd.novadigm.ext"), + ("ez", "application/andrew-inset"), + ("ez2", "application/vnd.ezpix-album"), + ("ez3", "application/vnd.ezpix-package"), + ("f", "text/x-fortran"), + ("f4v", "video/x-f4v"), + ("f77", "text/x-fortran"), + ("f90", "text/x-fortran"), + ("fbs", "image/vnd.fastbidsheet"), + ("fbx", "application/vnd.autodesk.fbx"), + ("fcdt", "application/vnd.adobe.formscentral.fcdt"), + ("fcs", "application/vnd.isac.fcs"), + ("fdf", "application/fdf"), + ("fdt", "application/fdt+xml"), + ("fe_launch", "application/vnd.denovo.fcselayout-link"), + ("fg5", "application/vnd.fujitsu.oasysgp"), + ("fgd", "application/x-director"), + ("fh", "image/x-freehand"), + ("fh4", "image/x-freehand"), + ("fh5", "image/x-freehand"), + ("fh7", "image/x-freehand"), + ("fhc", "image/x-freehand"), + ("fig", "application/x-xfig"), + ("fits", "image/fits"), + ("flac", "audio/x-flac"), + ("fli", "video/x-fli"), + ("flo", "application/vnd.micrografx.flo"), + ("flv", "video/x-flv"), + ("flw", "application/vnd.kde.kivio"), + ("flx", "text/vnd.fmi.flexstor"), + ("fly", "text/vnd.fly"), + ("fm", "application/vnd.framemaker"), + ("fnc", "application/vnd.frogans.fnc"), + ("fo", "application/vnd.software602.filler.form+xml"), + ("for", "text/x-fortran"), + ("fpx", "image/vnd.fpx"), + ("frame", "application/vnd.framemaker"), + ("fsc", "application/vnd.fsc.weblaunch"), + ("fst", "image/vnd.fst"), + ("ftc", "application/vnd.fluxtime.clip"), + ("fti", "application/vnd.anser-web-funds-transfer-initiation"), + ("fvt", "video/vnd.fvt"), + ("fxp", "application/vnd.adobe.fxp"), + ("fxpl", "application/vnd.adobe.fxp"), + ("fzs", "application/vnd.fuzzysheet"), + ("g2w", "application/vnd.geoplan"), + ("g3", "image/g3fax"), + ("g3w", "application/vnd.geospace"), + ("gac", "application/vnd.groove-account"), + ("gam", "application/x-tads"), + ("gbr", "application/rpki-ghostbusters"), + ("gca", "application/x-gca-compressed"), + ("gdl", "model/vnd.gdl"), + ("gdoc", "application/vnd.google-apps.document"), + ("gdraw", "application/vnd.google-apps.drawing"), + ("ged", "text/vnd.familysearch.gedcom"), + ("geo", "application/vnd.dynageo"), + ("geojson", "application/geo+json"), + ("gex", "application/vnd.geometry-explorer"), + ("gform", "application/vnd.google-apps.form"), + ("ggb", "application/vnd.geogebra.file"), + ("ggs", "application/vnd.geogebra.slides"), + ("ggt", "application/vnd.geogebra.tool"), + ("ghf", "application/vnd.groove-help"), + ("gif", "image/gif"), + ("gim", "application/vnd.groove-identity-message"), + ("gjam", "application/vnd.google-apps.jam"), + ("glb", "model/gltf-binary"), + ("gltf", "model/gltf+json"), + ("gmap", "application/vnd.google-apps.map"), + ("gml", "application/gml+xml"), + ("gmx", "application/vnd.gmx"), + ("gnumeric", "application/x-gnumeric"), + ("gph", "application/vnd.flographit"), + ("gpx", "application/gpx+xml"), + ("gqf", "application/vnd.grafeq"), + ("gqs", "application/vnd.grafeq"), + ("gram", "application/srgs"), + ("gramps", "application/x-gramps-xml"), + ("gre", "application/vnd.geometry-explorer"), + ("grv", "application/vnd.groove-injector"), + ("grxml", "application/srgs+xml"), + ("gscript", "application/vnd.google-apps.script"), + ("gsf", "application/x-font-ghostscript"), + ("gsheet", "application/vnd.google-apps.spreadsheet"), + ("gsite", "application/vnd.google-apps.site"), + ("gslides", "application/vnd.google-apps.presentation"), + ("gtar", "application/x-gtar"), + ("gtm", "application/vnd.groove-tool-message"), + ("gtw", "model/vnd.gtw"), + ("gv", "text/vnd.graphviz"), + ("gxf", "application/gxf"), + ("gxt", "application/vnd.geonext"), + ("gz", "application/gzip"), + ("h", "text/x-c"), + ("h261", "video/h261"), + ("h263", "video/h263"), + ("h264", "video/h264"), + ("hal", "application/vnd.hal+xml"), + ("hbci", "application/vnd.hbci"), + ("hbs", "text/x-handlebars-template"), + ("hdd", "application/x-virtualbox-hdd"), + ("hdf", "application/x-hdf"), + ("heic", "image/heic"), + ("heics", "image/heic-sequence"), + ("heif", "image/heif"), + ("heifs", "image/heif-sequence"), + ("hej2", "image/hej2k"), + ("held", "application/atsc-held+xml"), + ("hh", "text/x-c"), + ("hjson", "application/hjson"), + ("hlp", "application/winhlp"), + ("hpgl", "application/vnd.hp-hpgl"), + ("hpid", "application/vnd.hp-hpid"), + ("hps", "application/vnd.hp-hps"), + ("hqx", "application/mac-binhex40"), + ("htc", "text/x-component"), + ("htke", "application/vnd.kenameaapp"), + ("htm", "text/html"), + ("html", "text/html"), + ("hvd", "application/vnd.yamaha.hv-dic"), + ("hvp", "application/vnd.yamaha.hv-voice"), + ("hvs", "application/vnd.yamaha.hv-script"), + ("i2g", "application/vnd.intergeo"), + ("icc", "application/vnd.iccprofile"), + ("ice", "x-conference/x-cooltalk"), + ("icm", "application/vnd.iccprofile"), + ("ico", "image/vnd.microsoft.icon"), + ("ics", "text/calendar"), + ("ief", "image/ief"), + ("ifb", "text/calendar"), + ("ifm", "application/vnd.shana.informed.formdata"), + ("iges", "model/iges"), + ("igl", "application/vnd.igloader"), + ("igm", "application/vnd.insors.igm"), + ("igs", "model/iges"), + ("igx", "application/vnd.micrografx.igx"), + ("iif", "application/vnd.shana.informed.interchange"), + ("img", "application/octet-stream"), + ("imp", "application/vnd.accpac.simply.imp"), + ("ims", "application/vnd.ms-ims"), + ("in", "text/plain"), + ("ini", "text/plain"), + ("ink", "application/inkml+xml"), + ("inkml", "application/inkml+xml"), + ("install", "application/x-install-instructions"), + ("iota", "application/vnd.astraea-software.iota"), + ("ipfix", "application/ipfix"), + ("ipk", "application/vnd.shana.informed.package"), + ("ipynb", "application/x-ipynb+json"), + ("irm", "application/vnd.ibm.rights-management"), + ("irp", "application/vnd.irepository.package+xml"), + ("iso", "application/x-iso9660-image"), + ("itp", "application/vnd.shana.informed.formtemplate"), + ("its", "application/its+xml"), + ("ivp", "application/vnd.immervision-ivp"), + ("ivu", "application/vnd.immervision-ivu"), + ("jad", "text/vnd.sun.j2me.app-descriptor"), + ("jade", "text/jade"), + ("jaii", "image/jaii"), + ("jais", "image/jais"), + ("jam", "application/vnd.jam"), + ("jar", "application/java-archive"), + ("jardiff", "application/x-java-archive-diff"), + ("java", "text/x-java-source"), + ("jfif", "image/pjpeg"), + ("jhc", "image/jphc"), + ("jisp", "application/vnd.jisp"), + ("jls", "image/jls"), + ("jlt", "application/vnd.hp-jlyt"), + ("jng", "image/x-jng"), + ("jnlp", "application/x-java-jnlp-file"), + ("joda", "application/vnd.joost.joda-archive"), + ("jp2", "image/jp2"), + ("jpe", "image/jpeg"), + ("jpeg", "image/jpeg"), + ("jpf", "image/jpx"), + ("jpg", "image/jpeg"), + ("jpg2", "image/jp2"), + ("jpgm", "image/jpm"), + ("jpgv", "video/jpeg"), + ("jph", "image/jph"), + ("jpm", "image/jpm"), + ("jpx", "image/jpx"), + ("js", "text/javascript"), + ("json", "application/json"), + ("json5", "application/json5"), + ("jsonld", "application/ld+json"), + ("jsonml", "application/jsonml+json"), + ("jsx", "text/jsx"), + ("jt", "model/jt"), + ("jxl", "image/jxl"), + ("jxr", "image/jxr"), + ("jxra", "image/jxra"), + ("jxrs", "image/jxrs"), + ("jxs", "image/jxs"), + ("jxsc", "image/jxsc"), + ("jxsi", "image/jxsi"), + ("jxss", "image/jxss"), + ("kar", "audio/midi"), + ("karbon", "application/vnd.kde.karbon"), + ("kdbx", "application/x-keepass2"), + ("key", "application/vnd.apple.keynote"), + ("kfo", "application/vnd.kde.kformula"), + ("kia", "application/vnd.kidspiration"), + ("kml", "application/vnd.google-earth.kml+xml"), + ("kmz", "application/vnd.google-earth.kmz"), + ("kne", "application/vnd.kinar"), + ("knp", "application/vnd.kinar"), + ("kon", "application/vnd.kde.kontour"), + ("kpr", "application/vnd.kde.kpresenter"), + ("kpt", "application/vnd.kde.kpresenter"), + ("kpxx", "application/vnd.ds-keypoint"), + ("ksp", "application/vnd.kde.kspread"), + ("ktr", "application/vnd.kahootz"), + ("ktx", "image/ktx"), + ("ktx2", "image/ktx2"), + ("ktz", "application/vnd.kahootz"), + ("kwd", "application/vnd.kde.kword"), + ("kwt", "application/vnd.kde.kword"), + ("lasxml", "application/vnd.las.las+xml"), + ("latex", "application/x-latex"), + ("lbd", "application/vnd.llamagraphics.life-balance.desktop"), + ("lbe", "application/vnd.llamagraphics.life-balance.exchange+xml"), + ("les", "application/vnd.hhe.lesson-player"), + ("less", "text/less"), + ("lgr", "application/lgr+xml"), + ("lha", "application/x-lzh-compressed"), + ("link66", "application/vnd.route66.link66+xml"), + ("list", "text/plain"), + ("list3820", "application/vnd.ibm.modcap"), + ("listafp", "application/vnd.ibm.modcap"), + ("litcoffee", "text/coffeescript"), + ("lnk", "application/x-ms-shortcut"), + ("log", "text/plain"), + ("lostxml", "application/lost+xml"), + ("lottie", "application/zip+dotlottie"), + ("lrf", "application/octet-stream"), + ("lrm", "application/vnd.ms-lrm"), + ("ltf", "application/vnd.frogans.ltf"), + ("lua", "text/x-lua"), + ("luac", "application/x-lua-bytecode"), + ("lvp", "audio/vnd.lucent.voice"), + ("lwp", "application/vnd.lotus-wordpro"), + ("lzh", "application/x-lzh-compressed"), + ("m13", "application/x-msmediaview"), + ("m14", "application/x-msmediaview"), + ("m1v", "video/mpeg"), + ("m21", "application/mp21"), + ("m2a", "audio/mpeg"), + ("m2t", "video/mp2t"), + ("m2ts", "video/mp2t"), + ("m2v", "video/mpeg"), + ("m3a", "audio/mpeg"), + ("m3u", "audio/x-mpegurl"), + ("m3u8", "application/vnd.apple.mpegurl"), + ("m4a", "audio/mp4"), + ("m4b", "audio/mp4"), + ("m4p", "application/mp4"), + ("m4s", "video/iso.segment"), + ("m4u", "video/vnd.mpegurl"), + ("m4v", "video/x-m4v"), + ("ma", "application/mathematica"), + ("mads", "application/mads+xml"), + ("maei", "application/mmt-aei+xml"), + ("mag", "application/vnd.ecowin.chart"), + ("maker", "application/vnd.framemaker"), + ("man", "text/troff"), + ("manifest", "text/cache-manifest"), + ("map", "application/json"), + ("mar", "application/octet-stream"), + ("markdown", "text/markdown"), + ("mathml", "application/mathml+xml"), + ("mb", "application/mathematica"), + ("mbk", "application/vnd.mobius.mbk"), + ("mbox", "application/mbox"), + ("mc1", "application/vnd.medcalcdata"), + ("mcd", "application/vnd.mcd"), + ("mcurl", "text/vnd.curl.mcurl"), + ("md", "text/markdown"), + ("mdb", "application/x-msaccess"), + ("mdi", "image/vnd.ms-modi"), + ("mdx", "text/mdx"), + ("me", "text/troff"), + ("mesh", "model/mesh"), + ("meta4", "application/metalink4+xml"), + ("metalink", "application/metalink+xml"), + ("mets", "application/mets+xml"), + ("mfm", "application/vnd.mfmp"), + ("mft", "application/rpki-manifest"), + ("mgp", "application/vnd.osgeo.mapguide.package"), + ("mgz", "application/vnd.proteus.magazine"), + ("mht", "message/rfc822"), + ("mhtml", "message/rfc822"), + ("mid", "audio/midi"), + ("midi", "audio/midi"), + ("mie", "application/x-mie"), + ("mif", "application/vnd.mif"), + ("mime", "message/rfc822"), + ("mj2", "video/mj2"), + ("mjp2", "video/mj2"), + ("mjs", "text/javascript"), + ("mk3d", "video/x-matroska"), + ("mka", "audio/x-matroska"), + ("mkd", "text/x-markdown"), + ("mks", "video/x-matroska"), + ("mkv", "video/x-matroska"), + ("mlp", "application/vnd.dolby.mlp"), + ("mmd", "application/vnd.chipnuts.karaoke-mmd"), + ("mmf", "application/vnd.smaf"), + ("mml", "text/mathml"), + ("mmr", "image/vnd.fujixerox.edmics-mmr"), + ("mng", "video/x-mng"), + ("mny", "application/x-msmoney"), + ("mobi", "application/x-mobipocket-ebook"), + ("mods", "application/mods+xml"), + ("mov", "video/quicktime"), + ("movie", "video/x-sgi-movie"), + ("mp2", "audio/mpeg"), + ("mp21", "application/mp21"), + ("mp2a", "audio/mpeg"), + ("mp3", "audio/mpeg"), + ("mp4", "video/mp4"), + ("mp4a", "audio/mp4"), + ("mp4s", "application/mp4"), + ("mp4v", "video/mp4"), + ("mpc", "application/vnd.mophun.certificate"), + ("mpd", "application/dash+xml"), + ("mpe", "video/mpeg"), + ("mpeg", "video/mpeg"), + ("mpf", "application/media-policy-dataset+xml"), + ("mpg", "video/mpeg"), + ("mpg4", "video/mp4"), + ("mpga", "audio/mpeg"), + ("mpkg", "application/vnd.apple.installer+xml"), + ("mpm", "application/vnd.blueice.multipass"), + ("mpn", "application/vnd.mophun.application"), + ("mpp", "application/dash-patch+xml"), + ("mpt", "application/vnd.ms-project"), + ("mpy", "application/vnd.ibm.minipay"), + ("mqy", "application/vnd.mobius.mqy"), + ("mrc", "application/marc"), + ("mrcx", "application/marcxml+xml"), + ("ms", "text/troff"), + ("mscml", "application/mediaservercontrol+xml"), + ("mseed", "application/vnd.fdsn.mseed"), + ("mseq", "application/vnd.mseq"), + ("msf", "application/vnd.epson.msf"), + ("msg", "application/vnd.ms-outlook"), + ("msh", "model/mesh"), + ("msi", "application/x-msdownload"), + ("msix", "application/msix"), + ("msixbundle", "application/msixbundle"), + ("msl", "application/vnd.mobius.msl"), + ("msm", "application/octet-stream"), + ("msp", "application/octet-stream"), + ("msty", "application/vnd.muvee.style"), + ("mtl", "model/mtl"), + ("mts", "video/mp2t"), + ("mus", "application/vnd.musician"), + ("musd", "application/mmt-usd+xml"), + ("musicxml", "application/vnd.recordare.musicxml+xml"), + ("mvb", "application/x-msmediaview"), + ("mvt", "application/vnd.mapbox-vector-tile"), + ("mwf", "application/vnd.mfer"), + ("mxf", "application/mxf"), + ("mxl", "application/vnd.recordare.musicxml"), + ("mxmf", "audio/mobile-xmf"), + ("mxml", "application/xv+xml"), + ("mxs", "application/vnd.triscape.mxs"), + ("mxu", "video/vnd.mpegurl"), + ("n-gage", "application/vnd.nokia.n-gage.symbian.install"), + ("n3", "text/n3"), + ("nb", "application/mathematica"), + ("nbp", "application/vnd.wolfram.player"), + ("nc", "application/x-netcdf"), + ("ncx", "application/x-dtbncx+xml"), + ("nfo", "text/x-nfo"), + ("ngdat", "application/vnd.nokia.n-gage.data"), + ("nitf", "application/vnd.nitf"), + ("nlu", "application/vnd.neurolanguage.nlu"), + ("nml", "application/vnd.enliven"), + ("nnd", "application/vnd.noblenet-directory"), + ("nns", "application/vnd.noblenet-sealer"), + ("nnw", "application/vnd.noblenet-web"), + ("npx", "image/vnd.net-fpx"), + ("nq", "application/n-quads"), + ("nsc", "application/x-conference"), + ("nsf", "application/vnd.lotus-notes"), + ("nt", "application/n-triples"), + ("ntf", "application/vnd.nitf"), + ("numbers", "application/vnd.apple.numbers"), + ("nzb", "application/x-nzb"), + ("oa2", "application/vnd.fujitsu.oasys2"), + ("oa3", "application/vnd.fujitsu.oasys3"), + ("oas", "application/vnd.fujitsu.oasys"), + ("obd", "application/x-msbinder"), + ("obgx", "application/vnd.openblox.game+xml"), + ("obj", "model/obj"), + ("oda", "application/oda"), + ("odb", "application/vnd.oasis.opendocument.database"), + ("odc", "application/vnd.oasis.opendocument.chart"), + ("odf", "application/vnd.oasis.opendocument.formula"), + ("odft", "application/vnd.oasis.opendocument.formula-template"), + ("odg", "application/vnd.oasis.opendocument.graphics"), + ("odi", "application/vnd.oasis.opendocument.image"), + ("odm", "application/vnd.oasis.opendocument.text-master"), + ("odp", "application/vnd.oasis.opendocument.presentation"), + ("ods", "application/vnd.oasis.opendocument.spreadsheet"), + ("odt", "application/vnd.oasis.opendocument.text"), + ("oga", "audio/ogg"), + ("ogex", "model/vnd.opengex"), + ("ogg", "audio/ogg"), + ("ogv", "video/ogg"), + ("ogx", "application/ogg"), + ("omdoc", "application/omdoc+xml"), + ("one", "application/onenote"), + ("onea", "application/onenote"), + ("onepkg", "application/onenote"), + ("onetmp", "application/onenote"), + ("onetoc", "application/onenote"), + ("onetoc2", "application/onenote"), + ("opf", "application/oebps-package+xml"), + ("opml", "text/x-opml"), + ("oprc", "application/vnd.palm"), + ("opus", "audio/ogg"), + ("org", "application/vnd.lotus-organizer"), + ("osf", "application/vnd.yamaha.openscoreformat"), + ("osfpvg", "application/vnd.yamaha.openscoreformat.osfpvg+xml"), + ("osm", "application/vnd.openstreetmap.data+xml"), + ("otc", "application/vnd.oasis.opendocument.chart-template"), + ("otf", "font/otf"), + ("otg", "application/vnd.oasis.opendocument.graphics-template"), + ("oth", "application/vnd.oasis.opendocument.text-web"), + ("oti", "application/vnd.oasis.opendocument.image-template"), + ("otp", "application/vnd.oasis.opendocument.presentation-template"), + ("ots", "application/vnd.oasis.opendocument.spreadsheet-template"), + ("ott", "application/vnd.oasis.opendocument.text-template"), + ("ova", "application/x-virtualbox-ova"), + ("ovf", "application/x-virtualbox-ovf"), + ("owl", "application/rdf+xml"), + ("oxps", "application/oxps"), + ("oxt", "application/vnd.openofficeorg.extension"), + ("p", "text/x-pascal"), + ("p10", "application/pkcs10"), + ("p12", "application/x-pkcs12"), + ("p21", "model/step"), + ("p7b", "application/x-pkcs7-certificates"), + ("p7c", "application/pkcs7-mime"), + ("p7m", "application/pkcs7-mime"), + ("p7r", "application/x-pkcs7-certreqresp"), + ("p7s", "application/pkcs7-signature"), + ("p8", "application/pkcs8"), + ("pac", "application/x-ns-proxy-autoconfig"), + ("pages", "application/vnd.apple.pages"), + ("pas", "text/x-pascal"), + ("paw", "application/vnd.pawaafile"), + ("pbd", "application/vnd.powerbuilder6"), + ("pbm", "image/x-portable-bitmap"), + ("pcap", "application/vnd.tcpdump.pcap"), + ("pcf", "application/x-font-pcf"), + ("pcl", "application/vnd.hp-pcl"), + ("pclxl", "application/vnd.hp-pclxl"), + ("pct", "image/x-pict"), + ("pcurl", "application/vnd.curl.pcurl"), + ("pcx", "image/vnd.zbrush.pcx"), + ("pdb", "application/vnd.palm"), + ("pde", "text/x-processing"), + ("pdf", "application/pdf"), + ("pem", "application/x-x509-ca-cert"), + ("pfa", "application/x-font-type1"), + ("pfb", "application/x-font-type1"), + ("pfm", "application/x-font-type1"), + ("pfr", "application/font-tdpfr"), + ("pfx", "application/x-pkcs12"), + ("pgm", "image/x-portable-graymap"), + ("pgn", "application/x-chess-pgn"), + ("pgp", "application/pgp-encrypted"), + ("php", "application/x-httpd-php"), + ("pic", "image/x-pict"), + ("pkg", "application/octet-stream"), + ("pki", "application/pkixcmp"), + ("pkipath", "application/pkix-pkipath"), + ("pkpass", "application/vnd.apple.pkpass"), + ("pl", "application/x-perl"), + ("plb", "application/vnd.3gpp.pic-bw-large"), + ("plc", "application/vnd.mobius.plc"), + ("plf", "application/vnd.pocketlearn"), + ("pls", "application/pls+xml"), + ("pm", "application/x-perl"), + ("pml", "application/vnd.ctc-posml"), + ("png", "image/png"), + ("pnm", "image/x-portable-anymap"), + ("portpkg", "application/vnd.macports.portpkg"), + ("pot", "application/vnd.ms-powerpoint"), + ("potm", "application/vnd.ms-powerpoint.template.macroenabled.12"), + ("potx", "application/vnd.openxmlformats-officedocument.presentationml.template"), + ("ppam", "application/vnd.ms-powerpoint.addin.macroenabled.12"), + ("ppd", "application/vnd.cups-ppd"), + ("ppm", "image/x-portable-pixmap"), + ("pps", "application/vnd.ms-powerpoint"), + ("ppsm", "application/vnd.ms-powerpoint.slideshow.macroenabled.12"), + ("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"), + ("ppt", "application/vnd.ms-powerpoint"), + ("pptm", "application/vnd.ms-powerpoint.presentation.macroenabled.12"), + ("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"), + ("pqa", "application/vnd.palm"), + ("prc", "model/prc"), + ("pre", "application/vnd.lotus-freelance"), + ("prf", "application/pics-rules"), + ("provx", "application/provenance+xml"), + ("ps", "application/postscript"), + ("psb", "application/vnd.3gpp.pic-bw-small"), + ("psd", "image/vnd.adobe.photoshop"), + ("psf", "application/x-font-linux-psf"), + ("pskcxml", "application/pskc+xml"), + ("pti", "image/prs.pti"), + ("ptid", "application/vnd.pvi.ptid1"), + ("pub", "application/x-mspublisher"), + ("pvb", "application/vnd.3gpp.pic-bw-var"), + ("pwn", "application/vnd.3m.post-it-notes"), + ("pya", "audio/vnd.ms-playready.media.pya"), + ("pyo", "model/vnd.pytha.pyox"), + ("pyox", "model/vnd.pytha.pyox"), + ("pyv", "video/vnd.ms-playready.media.pyv"), + ("qam", "application/vnd.epson.quickanime"), + ("qbo", "application/vnd.intu.qbo"), + ("qfx", "application/vnd.intu.qfx"), + ("qps", "application/vnd.publishare-delta-tree"), + ("qt", "video/quicktime"), + ("qwd", "application/vnd.quark.quarkxpress"), + ("qwt", "application/vnd.quark.quarkxpress"), + ("qxb", "application/vnd.quark.quarkxpress"), + ("qxd", "application/vnd.quark.quarkxpress"), + ("qxl", "application/vnd.quark.quarkxpress"), + ("qxt", "application/vnd.quark.quarkxpress"), + ("ra", "audio/x-pn-realaudio"), + ("ram", "audio/x-pn-realaudio"), + ("raml", "application/raml+yaml"), + ("rapd", "application/route-apd+xml"), + ("rar", "application/vnd.rar"), + ("ras", "image/x-cmu-raster"), + ("rcprofile", "application/vnd.ipunplugged.rcprofile"), + ("rdf", "application/rdf+xml"), + ("rdz", "application/vnd.data-vision.rdz"), + ("relo", "application/p2p-overlay+xml"), + ("rep", "application/vnd.businessobjects"), + ("res", "application/x-dtbresource+xml"), + ("rgb", "image/x-rgb"), + ("rif", "application/reginfo+xml"), + ("rip", "audio/vnd.rip"), + ("ris", "application/x-research-info-systems"), + ("rl", "application/resource-lists+xml"), + ("rlc", "image/vnd.fujixerox.edmics-rlc"), + ("rld", "application/resource-lists-diff+xml"), + ("rm", "application/vnd.rn-realmedia"), + ("rmi", "audio/midi"), + ("rmp", "audio/x-pn-realaudio-plugin"), + ("rms", "application/vnd.jcp.javame.midlet-rms"), + ("rmvb", "application/vnd.rn-realmedia-vbr"), + ("rnc", "application/relax-ng-compact-syntax"), + ("rng", "application/xml"), + ("roa", "application/rpki-roa"), + ("roff", "text/troff"), + ("rp9", "application/vnd.cloanto.rp9"), + ("rpm", "application/x-redhat-package-manager"), + ("rpss", "application/vnd.nokia.radio-presets"), + ("rpst", "application/vnd.nokia.radio-preset"), + ("rq", "application/sparql-query"), + ("rs", "application/rls-services+xml"), + ("rsat", "application/atsc-rsat+xml"), + ("rsd", "application/rsd+xml"), + ("rsheet", "application/urc-ressheet+xml"), + ("rss", "application/rss+xml"), + ("rtf", "application/rtf"), + ("rtx", "text/richtext"), + ("run", "application/x-makeself"), + ("rusd", "application/route-usd+xml"), + ("s", "text/x-asm"), + ("s3m", "audio/s3m"), + ("saf", "application/vnd.yamaha.smaf-audio"), + ("sass", "text/x-sass"), + ("sbml", "application/sbml+xml"), + ("sc", "application/vnd.ibm.secure-container"), + ("scd", "application/x-msschedule"), + ("scm", "application/vnd.lotus-screencam"), + ("scq", "application/scvp-cv-request"), + ("scs", "application/scvp-cv-response"), + ("scss", "text/x-scss"), + ("scurl", "text/vnd.curl.scurl"), + ("sda", "application/vnd.stardivision.draw"), + ("sdc", "application/vnd.stardivision.calc"), + ("sdd", "application/vnd.stardivision.impress"), + ("sdkd", "application/vnd.solent.sdkm+xml"), + ("sdkm", "application/vnd.solent.sdkm+xml"), + ("sdp", "application/sdp"), + ("sdw", "application/vnd.stardivision.writer"), + ("sea", "application/x-sea"), + ("see", "application/vnd.seemail"), + ("seed", "application/vnd.fdsn.seed"), + ("sema", "application/vnd.sema"), + ("semd", "application/vnd.semd"), + ("semf", "application/vnd.semf"), + ("senmlx", "application/senml+xml"), + ("sensmlx", "application/sensml+xml"), + ("ser", "application/java-serialized-object"), + ("setpay", "application/set-payment-initiation"), + ("setreg", "application/set-registration-initiation"), + ("sfd-hdstx", "application/vnd.hydrostatix.sof-data"), + ("sfs", "application/vnd.spotfire.sfs"), + ("sfv", "text/x-sfv"), + ("sgi", "image/sgi"), + ("sgl", "application/vnd.stardivision.writer-global"), + ("sgm", "text/sgml"), + ("sgml", "text/sgml"), + ("sh", "application/x-sh"), + ("shar", "application/x-shar"), + ("shex", "text/shex"), + ("shf", "application/shf+xml"), + ("shtml", "text/html"), + ("sid", "image/x-mrsid-image"), + ("sieve", "application/sieve"), + ("sig", "application/pgp-signature"), + ("sil", "audio/silk"), + ("silo", "model/mesh"), + ("sis", "application/vnd.symbian.install"), + ("sisx", "application/vnd.symbian.install"), + ("sit", "application/x-stuffit"), + ("sitx", "application/x-stuffitx"), + ("siv", "application/sieve"), + ("skd", "application/vnd.koan"), + ("skm", "application/vnd.koan"), + ("skp", "application/vnd.koan"), + ("skt", "application/vnd.koan"), + ("sldm", "application/vnd.ms-powerpoint.slide.macroenabled.12"), + ("sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"), + ("slim", "text/slim"), + ("slm", "text/slim"), + ("sls", "application/route-s-tsid+xml"), + ("slt", "application/vnd.epson.salt"), + ("sm", "application/vnd.stepmania.stepchart"), + ("smf", "application/vnd.stardivision.math"), + ("smi", "application/smil+xml"), + ("smil", "application/smil+xml"), + ("smv", "video/x-smv"), + ("smzip", "application/vnd.stepmania.package"), + ("snd", "audio/basic"), + ("snf", "application/x-font-snf"), + ("so", "application/octet-stream"), + ("spc", "application/x-pkcs7-certificates"), + ("spdx", "text/spdx"), + ("spf", "application/vnd.yamaha.smaf-phrase"), + ("spl", "application/x-futuresplash"), + ("spot", "text/vnd.in3d.spot"), + ("spp", "application/scvp-vp-response"), + ("spq", "application/scvp-vp-request"), + ("spx", "audio/ogg"), + ("sql", "application/sql"), + ("src", "application/x-wais-source"), + ("srt", "application/x-subrip"), + ("sru", "application/sru+xml"), + ("srx", "application/sparql-results+xml"), + ("ssdl", "application/ssdl+xml"), + ("sse", "application/vnd.kodak-descriptor"), + ("ssf", "application/vnd.epson.ssf"), + ("ssml", "application/ssml+xml"), + ("st", "application/vnd.sailingtracker.track"), + ("stc", "application/vnd.sun.xml.calc.template"), + ("std", "application/vnd.sun.xml.draw.template"), + ("step", "model/step"), + ("stf", "application/vnd.wt.stf"), + ("sti", "application/vnd.sun.xml.impress.template"), + ("stk", "application/hyperstudio"), + ("stl", "model/stl"), + ("stp", "model/step"), + ("stpnc", "model/step"), + ("stpx", "model/step+xml"), + ("stpxz", "model/step-xml+zip"), + ("stpz", "model/step+zip"), + ("str", "application/vnd.pg.format"), + ("stw", "application/vnd.sun.xml.writer.template"), + ("styl", "text/stylus"), + ("stylus", "text/stylus"), + ("sub", "text/vnd.dvb.subtitle"), + ("sus", "application/vnd.sus-calendar"), + ("susp", "application/vnd.sus-calendar"), + ("sv4cpio", "application/x-sv4cpio"), + ("sv4crc", "application/x-sv4crc"), + ("svc", "application/vnd.dvb.service"), + ("svd", "application/vnd.svd"), + ("svg", "image/svg+xml"), + ("svgz", "image/svg+xml"), + ("swa", "application/x-director"), + ("swf", "application/x-shockwave-flash"), + ("swi", "application/vnd.aristanetworks.swi"), + ("swidtag", "application/swid+xml"), + ("sxc", "application/vnd.sun.xml.calc"), + ("sxd", "application/vnd.sun.xml.draw"), + ("sxg", "application/vnd.sun.xml.writer.global"), + ("sxi", "application/vnd.sun.xml.impress"), + ("sxm", "application/vnd.sun.xml.math"), + ("sxw", "application/vnd.sun.xml.writer"), + ("t", "text/troff"), + ("t3", "application/x-t3vm-image"), + ("t38", "image/t38"), + ("taglet", "application/vnd.mynfc"), + ("tao", "application/vnd.tao.intent-module-archive"), + ("tap", "image/vnd.tencent.tap"), + ("tar", "application/x-tar"), + ("tcap", "application/vnd.3gpp2.tcap"), + ("tcl", "application/x-tcl"), + ("td", "application/urc-targetdesc+xml"), + ("teacher", "application/vnd.smart.teacher"), + ("tei", "application/tei+xml"), + ("teicorpus", "application/tei+xml"), + ("tex", "application/x-tex"), + ("texi", "application/x-texinfo"), + ("texinfo", "application/x-texinfo"), + ("text", "text/plain"), + ("tfi", "application/thraud+xml"), + ("tfm", "application/x-tex-tfm"), + ("tfx", "image/tiff-fx"), + ("tga", "image/x-tga"), + ("thmx", "application/vnd.ms-officetheme"), + ("tif", "image/tiff"), + ("tiff", "image/tiff"), + ("tk", "application/x-tcl"), + ("tmo", "application/vnd.tmobile-livetv"), + ("toml", "application/toml"), + ("torrent", "application/x-bittorrent"), + ("tpl", "application/vnd.groove-tool-template"), + ("tpt", "application/vnd.trid.tpt"), + ("tr", "text/troff"), + ("tra", "application/vnd.trueapp"), + ("trig", "application/trig"), + ("trm", "application/x-msterminal"), + ("ts", "video/mp2t"), + ("tsd", "application/timestamped-data"), + ("tsv", "text/tab-separated-values"), + ("ttc", "font/collection"), + ("ttf", "font/ttf"), + ("ttl", "text/turtle"), + ("ttml", "application/ttml+xml"), + ("twd", "application/vnd.simtech-mindmapper"), + ("twds", "application/vnd.simtech-mindmapper"), + ("txd", "application/vnd.genomatix.tuxedo"), + ("txf", "application/vnd.mobius.txf"), + ("txt", "text/plain"), + ("u32", "application/x-authorware-bin"), + ("u3d", "model/u3d"), + ("u8dsn", "message/global-delivery-status"), + ("u8hdr", "message/global-headers"), + ("u8mdn", "message/global-disposition-notification"), + ("u8msg", "message/global"), + ("ubj", "application/ubjson"), + ("udeb", "application/x-debian-package"), + ("ufd", "application/vnd.ufdl"), + ("ufdl", "application/vnd.ufdl"), + ("ulx", "application/x-glulx"), + ("umj", "application/vnd.umajin"), + ("unityweb", "application/vnd.unity"), + ("uo", "application/vnd.uoml+xml"), + ("uoml", "application/vnd.uoml+xml"), + ("uri", "text/uri-list"), + ("uris", "text/uri-list"), + ("urls", "text/uri-list"), + ("usda", "model/vnd.usda"), + ("usdz", "model/vnd.usdz+zip"), + ("ustar", "application/x-ustar"), + ("utz", "application/vnd.uiq.theme"), + ("uu", "text/x-uuencode"), + ("uva", "audio/vnd.dece.audio"), + ("uvd", "application/vnd.dece.data"), + ("uvf", "application/vnd.dece.data"), + ("uvg", "image/vnd.dece.graphic"), + ("uvh", "video/vnd.dece.hd"), + ("uvi", "image/vnd.dece.graphic"), + ("uvm", "video/vnd.dece.mobile"), + ("uvp", "video/vnd.dece.pd"), + ("uvs", "video/vnd.dece.sd"), + ("uvt", "application/vnd.dece.ttml+xml"), + ("uvu", "video/vnd.uvvu.mp4"), + ("uvv", "video/vnd.dece.video"), + ("uvva", "audio/vnd.dece.audio"), + ("uvvd", "application/vnd.dece.data"), + ("uvvf", "application/vnd.dece.data"), + ("uvvg", "image/vnd.dece.graphic"), + ("uvvh", "video/vnd.dece.hd"), + ("uvvi", "image/vnd.dece.graphic"), + ("uvvm", "video/vnd.dece.mobile"), + ("uvvp", "video/vnd.dece.pd"), + ("uvvs", "video/vnd.dece.sd"), + ("uvvt", "application/vnd.dece.ttml+xml"), + ("uvvu", "video/vnd.uvvu.mp4"), + ("uvvv", "video/vnd.dece.video"), + ("uvvx", "application/vnd.dece.unspecified"), + ("uvvz", "application/vnd.dece.zip"), + ("uvx", "application/vnd.dece.unspecified"), + ("uvz", "application/vnd.dece.zip"), + ("vbox", "application/x-virtualbox-vbox"), + ("vbox-extpack", "application/x-virtualbox-vbox-extpack"), + ("vcard", "text/vcard"), + ("vcd", "application/x-cdlink"), + ("vcf", "text/x-vcard"), + ("vcg", "application/vnd.groove-vcard"), + ("vcs", "text/x-vcalendar"), + ("vcx", "application/vnd.vcx"), + ("vdi", "application/x-virtualbox-vdi"), + ("vds", "model/vnd.sap.vds"), + ("vdx", "application/vnd.ms-visio.viewer"), + ("vhd", "application/x-virtualbox-vhd"), + ("vis", "application/vnd.visionary"), + ("viv", "video/vnd.vivo"), + ("vmdk", "application/x-virtualbox-vmdk"), + ("vob", "video/x-ms-vob"), + ("vor", "application/vnd.stardivision.writer"), + ("vox", "application/x-authorware-bin"), + ("vrml", "model/vrml"), + ("vsd", "application/vnd.visio"), + ("vsdx", "application/vnd.visio"), + ("vsf", "application/vnd.vsf"), + ("vss", "application/vnd.visio"), + ("vst", "application/vnd.visio"), + ("vsw", "application/vnd.visio"), + ("vtf", "image/vnd.valve.source.texture"), + ("vtt", "text/vtt"), + ("vtu", "model/vnd.vtu"), + ("vtx", "application/vnd.visio"), + ("vxml", "application/voicexml+xml"), + ("w3d", "application/x-director"), + ("wad", "application/x-doom"), + ("wadl", "application/vnd.sun.wadl+xml"), + ("war", "application/java-archive"), + ("wasm", "application/wasm"), + ("wav", "audio/wav"), + ("wax", "audio/x-ms-wax"), + ("wbmp", "image/vnd.wap.wbmp"), + ("wbs", "application/vnd.criticaltools.wbs+xml"), + ("wbxml", "application/vnd.wap.wbxml"), + ("wcm", "application/vnd.ms-works"), + ("wdb", "application/vnd.ms-works"), + ("wdp", "image/vnd.ms-photo"), + ("weba", "audio/webm"), + ("webapp", "application/x-web-app-manifest+json"), + ("webm", "video/webm"), + ("webmanifest", "application/manifest+json"), + ("webp", "image/webp"), + ("wg", "application/vnd.pmi.widget"), + ("wgsl", "text/wgsl"), + ("wgt", "application/widget"), + ("wif", "application/watcherinfo+xml"), + ("wks", "application/vnd.ms-works"), + ("wm", "video/x-ms-wm"), + ("wma", "audio/x-ms-wma"), + ("wmd", "application/x-ms-wmd"), + ("wmf", "image/wmf"), + ("wml", "text/vnd.wap.wml"), + ("wmlc", "application/vnd.wap.wmlc"), + ("wmls", "text/vnd.wap.wmlscript"), + ("wmlsc", "application/vnd.wap.wmlscriptc"), + ("wmv", "video/x-ms-wmv"), + ("wmx", "video/x-ms-wmx"), + ("wmz", "application/x-ms-wmz"), + ("woff", "font/woff"), + ("woff2", "font/woff2"), + ("wpd", "application/vnd.wordperfect"), + ("wpl", "application/vnd.ms-wpl"), + ("wps", "application/vnd.ms-works"), + ("wqd", "application/vnd.wqd"), + ("wri", "application/x-mswrite"), + ("wrl", "model/vrml"), + ("wsc", "message/vnd.wfa.wsc"), + ("wsdl", "application/wsdl+xml"), + ("wspolicy", "application/wspolicy+xml"), + ("wtb", "application/vnd.webturbo"), + ("wvx", "video/x-ms-wvx"), + ("x32", "application/x-authorware-bin"), + ("x3d", "model/x3d+xml"), + ("x3db", "model/x3d+fastinfoset"), + ("x3dbz", "model/x3d+binary"), + ("x3dv", "model/x3d-vrml"), + ("x3dvz", "model/x3d+vrml"), + ("x3dz", "model/x3d+xml"), + ("x_b", "model/vnd.parasolid.transmit.binary"), + ("x_t", "model/vnd.parasolid.transmit.text"), + ("xaml", "application/xaml+xml"), + ("xap", "application/x-silverlight-app"), + ("xar", "application/vnd.xara"), + ("xav", "application/xcap-att+xml"), + ("xbap", "application/x-ms-xbap"), + ("xbd", "application/vnd.fujixerox.docuworks.binder"), + ("xbm", "image/x-xbitmap"), + ("xca", "application/xcap-caps+xml"), + ("xcs", "application/calendar+xml"), + ("xdcf", "application/vnd.gov.sk.xmldatacontainer+xml"), + ("xdf", "application/xcap-diff+xml"), + ("xdm", "application/vnd.syncml.dm+xml"), + ("xdp", "application/vnd.adobe.xdp+xml"), + ("xdssc", "application/dssc+xml"), + ("xdw", "application/vnd.fujixerox.docuworks"), + ("xel", "application/xcap-el+xml"), + ("xenc", "application/xenc+xml"), + ("xer", "application/patch-ops-error+xml"), + ("xfdf", "application/xfdf"), + ("xfdl", "application/vnd.xfdl"), + ("xht", "application/xhtml+xml"), + ("xhtm", "application/vnd.pwg-xhtml-print+xml"), + ("xhtml", "application/xhtml+xml"), + ("xhvml", "application/xv+xml"), + ("xif", "image/vnd.xiff"), + ("xla", "application/vnd.ms-excel"), + ("xlam", "application/vnd.ms-excel.addin.macroenabled.12"), + ("xlc", "application/vnd.ms-excel"), + ("xlf", "application/xliff+xml"), + ("xlm", "application/vnd.ms-excel"), + ("xls", "application/vnd.ms-excel"), + ("xlsb", "application/vnd.ms-excel.sheet.binary.macroenabled.12"), + ("xlsm", "application/vnd.ms-excel.sheet.macroenabled.12"), + ("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"), + ("xlt", "application/vnd.ms-excel"), + ("xltm", "application/vnd.ms-excel.template.macroenabled.12"), + ("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"), + ("xlw", "application/vnd.ms-excel"), + ("xm", "audio/xm"), + ("xml", "application/xml"), + ("xns", "application/xcap-ns+xml"), + ("xo", "application/vnd.olpc-sugar"), + ("xop", "application/xop+xml"), + ("xpi", "application/x-xpinstall"), + ("xpl", "application/xproc+xml"), + ("xpm", "image/x-xpixmap"), + ("xpr", "application/vnd.is-xpr"), + ("xps", "application/vnd.ms-xpsdocument"), + ("xpw", "application/vnd.intercon.formnet"), + ("xpx", "application/vnd.intercon.formnet"), + ("xsd", "application/xml"), + ("xsf", "application/prs.xsf+xml"), + ("xsl", "application/xml"), + ("xslt", "application/xslt+xml"), + ("xsm", "application/vnd.syncml+xml"), + ("xspf", "application/xspf+xml"), + ("xul", "application/vnd.mozilla.xul+xml"), + ("xvm", "application/xv+xml"), + ("xvml", "application/xv+xml"), + ("xwd", "image/x-xwindowdump"), + ("xyz", "chemical/x-xyz"), + ("xz", "application/x-xz"), + ("yaml", "text/yaml"), + ("yang", "application/yang"), + ("yin", "application/yin+xml"), + ("yml", "text/yaml"), + ("ymp", "text/x-suse-ymp"), + ("z1", "application/x-zmachine"), + ("z2", "application/x-zmachine"), + ("z3", "application/x-zmachine"), + ("z4", "application/x-zmachine"), + ("z5", "application/x-zmachine"), + ("z6", "application/x-zmachine"), + ("z7", "application/x-zmachine"), + ("z8", "application/x-zmachine"), + ("zaz", "application/vnd.zzazz.deck+xml"), + ("zip", "application/zip"), + ("zir", "application/vnd.zul"), + ("zirz", "application/vnd.zul"), + ("zmm", "application/vnd.handheld-entertainment+xml"), +]; diff --git a/packages/cli-rs/crates/cli/src/run/prompt.rs b/packages/cli-rs/crates/cli/src/run/prompt.rs new file mode 100644 index 00000000000..fa824e7a8a4 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/run/prompt.rs @@ -0,0 +1,1308 @@ +//! The prompt of a non-interactive run (`runNonInteractivePrompt`, `packages/cli/src/run/noninteractive.ts`): +//! subscribe to events, send the prompt, print what the session does, answer permissions and forms nobody +//! can answer, wait until the session and its background work are idle, then print what the event stream +//! missed from the projected messages. +//! +//! Events and messages stay JSON, as the TS client reads them: `--format json` passes their fields through +//! unchanged, unknown ones included. + +use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, HashSet}; +use std::io::IsTerminal; +use std::rc::Rc; + +use futures_util::StreamExt; +use opencode_api::client::{Call, Client, RequestOptions}; +use opencode_api::error::Error as ApiError; +use opencode_api::generated::*; +use opencode_api::transport::SseResponse; +use opencode_ui::tool_info::{tool_inline_info, tool_output_text}; +use serde_json::{Map, Value, json}; +use tokio::sync::{Notify, watch}; + +use super::files::Prepared; +use super::ui; + +// MCP elicitations belong to this sentinel instead of a session. `run` is always attached to a shared +// server, so it never answers them. +const GLOBAL_FORM_SESSION_ID: &str = "global"; + +const QUESTION_CANCELLED_FEEDBACK: &str = "This non-interactive run cannot ask the user questions, so the question was cancelled. Continue without an answer; make reasonable assumptions and state them."; + +const PERMISSION_REJECTED_FEEDBACK: &str = "This non-interactive run cannot ask the user for permission, so the request was rejected. Continue without this action."; + +pub struct Input { + pub client: Client, + pub session_id: String, + /// The target location's directory. + pub directory: String, + pub message: String, + pub files: Vec, + pub agent: Option, + /// The model, with the variant. + pub model: Option, + pub thinking: bool, + pub json: bool, + pub auto: bool, + /// `process.exitCode`. + pub exit: Rc>, +} + +#[derive(Default)] +struct Flags { + submitted: bool, + promoted: bool, + emitted_error: bool, + form_cancelled: bool, + interrupted: bool, + finalizing: bool, + waiting_for_background: bool, + pre_promotion_error: Option, +} + +struct ToolState { + id: String, + timestamp: Value, + tool: String, + input: Value, + raw: Option, + provider: Option, + native: Option, + metadata: Value, +} + +struct Run { + input: Input, + message_id: String, + flags: RefCell, + starts: RefCell>, + tools: RefCell>, + rendered_text: RefCell>, + rendered_reasoning: RefCell>, + rendered_tools: RefCell>, + // Steps the live stream saw: false when started, true when ended. + steps: RefCell>, + owned: RefCell>, + job_sessions: RefCell>, + abort: watch::Sender, + admission: Notify, + completed: watch::Sender>>, +} + +enum Flow { + Next, + Done, +} + +pub async fn run(input: Input) -> Result<(), String> { + let response = input + .client + .event_subscribe(&EventSubscribeInput::default(), &RequestOptions::default()) + .await + .map_err(|error| error.to_string())?; + let mut stream = Box::pin(SseResponse::::new(response.response).events(|| {})); + if !matches!(stream.next().await, Some(Ok(_))) { + return Err("Event stream disconnected before prompt admission".into()); + } + let session_id = input.session_id.clone(); + let run = Rc::new(Run { + input, + message_id: opencode_api::id::message(), + flags: RefCell::default(), + starts: RefCell::default(), + tools: RefCell::default(), + rendered_text: RefCell::default(), + rendered_reasoning: RefCell::default(), + rendered_tools: RefCell::default(), + steps: RefCell::default(), + owned: RefCell::new(HashMap::from([(session_id.clone(), true)])), + job_sessions: RefCell::new(vec![session_id]), + abort: watch::channel(false).0, + admission: Notify::new(), + completed: watch::channel(None).0, + }); + let signals = tokio::task::spawn_local(interrupt_on_signal(run.clone())); + let result = run.clone().execute(stream).await; + signals.abort(); + run.abort.send_replace(true); + result +} + +impl Run { + async fn execute( + self: Rc, + stream: std::pin::Pin> + 'static>>, + ) -> Result<(), String> { + let client = &self.input.client; + let session = SessionID(self.input.session_id.clone()); + if let Some(agent) = &self.input.agent { + client + .session_switch_agent( + &SessionSwitchAgentInput { + session_id: session.clone(), + agent: AgentID(agent.clone()), + }, + &RequestOptions::default(), + ) + .await + .map_err(|error| error.to_string())?; + } + if let Some(model) = &self.input.model { + // The TS key order, `{ providerID, id, variant }`; the generated `ModelRef` puts `id` first. + let mut call = Call::new( + "POST", + format!("/api/session/{}/model", path(&self.input.session_id)), + 204, + &[400, 401, 404], + ); + call.json(&json!({ "model": object([ + ("providerID", Some(model.provider_id.0.clone().into())), + ("id", Some(model.id.clone().into())), + ("variant", model.variant.clone().map(Value::from)), + ]) })) + .map_err(|error| error.to_string())?; + client + .empty(call, &RequestOptions::default()) + .await + .map_err(|error| error.to_string())?; + } + if self.flags.borrow().interrupted { + return Ok(()); + } + self.flags.borrow_mut().submitted = true; + tokio::task::spawn_local({ + let run = self.clone(); + async move { + let result = run.clone().consume(stream).await; + run.completed.send_replace(Some(result)); + } + }); + let text = std::iter::once(self.input.message.as_str()) + .chain(self.input.files.iter().filter_map(|file| match file { + Prepared::Text(text) => Some(text.as_str()), + Prepared::Attachment { .. } => None, + })) + .collect::>() + .join("\n\n"); + let files: Vec = self + .input + .files + .iter() + .filter_map(|file| match file { + Prepared::Attachment { uri, name } => Some(json!({ "uri": uri, "name": name })), + Prepared::Text(_) => None, + }) + .collect(); + let mut call = Call::new( + "POST", + format!("/api/session/{}/prompt", path(&self.input.session_id)), + 200, + &[400, 401, 404, 409], + ); + call.json(&json!({ + "id": self.message_id, + "text": text, + "files": files, + "delivery": "steer", + })) + .map_err(|error| error.to_string())?; + let options = RequestOptions::default(); + let admitted = tokio::select! { + result = client.json::(call, &options) => result.map_err(|error| error.to_string()), + () = self.admission.notified() => Err("The operation was aborted.".to_owned()), + }; + if let Err(error) = admitted { + if self.flags.borrow().interrupted { + self.interrupt_session().await; + } + self.abort.send_replace(true); + let _ = self.wait_completed().await; + let flags = self.flags.borrow(); + if flags.interrupted || flags.emitted_error { + return Ok(()); + } + return Err(error); + } + if self.flags.borrow().interrupted { + self.interrupt_session().await; + } + + let permissions = self + .data(&format!("/api/session/{}/permission", path(&self.input.session_id)), &[]) + .await + .ok(); + let forms = self + .data(&format!("/api/session/{}/form", path(&self.input.session_id)), &[]) + .await + .ok(); + for permission in array(permissions.as_ref()) { + self.reply_permission(permission).await; + } + for form in array(forms.as_ref()) { + self.cancel_form(form).await?; + } + + // `Promise.race([waiting, completed.then(() => waiting)])`: the wait, unless the event loop fails first. + let waiting = self.wait_until_idle(); + tokio::pin!(waiting); + tokio::select! { + result = &mut waiting => result?, + Err(error) = self.wait_completed() => return Err(error), + } + self.flags.borrow_mut().finalizing = true; + let (found, responded) = self.reconcile().await?; + let settled = |flags: &Flags| { + !flags.interrupted && !flags.form_cancelled && !flags.emitted_error + }; + let wait_for_stream = { + let flags = self.flags.borrow(); + !responded && settled(&flags) && flags.pre_promotion_error.is_none() + }; + if wait_for_stream { + self.wait_completed().await?; + } + if !found && settled(&self.flags.borrow()) { + let error = self + .flags + .borrow() + .pre_promotion_error + .clone() + .unwrap_or_else(|| json!({ "type": "unknown", "message": "Prompt was not promoted" })); + self.fail(&error, &now()); + } + Ok(()) + } + + async fn wait_until_idle(&self) -> Result<(), String> { + self.session_wait().await?; + if !self.pending_background().await { + return Ok(()); + } + self.wait_completed().await?; + let more = settled_flags(&self.flags.borrow()); + if more { + self.session_wait().await?; + } + Ok(()) + } + + async fn session_wait(&self) -> Result<(), String> { + self.input + .client + .experimental_session_wait( + &ExperimentalSessionWaitInput { + session_id: SessionID(self.input.session_id.clone()), + }, + &RequestOptions::default(), + ) + .await + .map_err(|error| error.to_string()) + } + + async fn wait_completed(&self) -> Result<(), String> { + let mut receiver = self.completed.subscribe(); + let done = receiver.wait_for(Option::is_some).await; + match done { + Ok(value) => value.clone().unwrap_or(Ok(())), + Err(_) => Ok(()), + } + } + + async fn consume( + self: Rc, + mut stream: std::pin::Pin>>>, + ) -> Result<(), String> { + let mut abort = self.abort.subscribe(); + loop { + let next = tokio::select! { + next = stream.next() => next, + _ = abort.wait_for(|aborted| *aborted) => None, + }; + let event = match next { + Some(Ok(event)) => event, + Some(Err(error)) => { + let flags = self.flags.borrow(); + if !flags.emitted_error && !flags.interrupted { + return Err(error.to_string()); + } + return Ok(()); + } + None => { + let flags = self.flags.borrow(); + if flags.emitted_error || flags.interrupted { + return Ok(()); + } + return Err("Event stream disconnected during prompt execution".into()); + } + }; + if let Flow::Done = self.handle(&event).await? { + return Ok(()); + } + } + } + + async fn handle(&self, event: &Value) -> Result { + let kind = event["type"].as_str().unwrap_or_default(); + let data = &event["data"]; + let submitted = self.flags.borrow().submitted; + if kind == "permission.asked" && submitted && self.owns(text(&data["sessionID"])).await { + self.reply_permission(data).await; + return Ok(Flow::Next); + } + if kind == "form.created" && submitted && self.owns(text(&data["form"]["sessionID"])).await { + self.cancel_form(&data["form"]).await?; + return Ok(Flow::Next); + } + let Some(session) = data.get("sessionID") else { + return Ok(Flow::Next); + }; + if text(session) != self.input.session_id { + // While waiting, a reply ending anywhere in the tree may have finished the last of the work. + if self.flags.borrow().waiting_for_background + && matches!( + kind, + "session.execution.succeeded" | "session.execution.failed" | "session.execution.interrupted" + ) + && self.owns(text(session)).await + && !self.pending_background().await + { + return Ok(Flow::Done); + } + return Ok(Flow::Next); + } + let time = event_time(event); + + if kind == "session.inbox.delivered" && text(&data["inboxID"]) == self.message_id { + let mut flags = self.flags.borrow_mut(); + flags.promoted = true; + flags.pre_promotion_error = None; + return Ok(Flow::Next); + } + { + let mut flags = self.flags.borrow_mut(); + if kind == "session.execution.interrupted" + && data["reason"] == "user" + && (flags.interrupted || flags.form_cancelled) + { + return Ok(Flow::Done); + } + if !flags.promoted && kind == "session.execution.failed" { + flags.pre_promotion_error = Some(data["error"].clone()); + return Ok(if flags.finalizing { Flow::Done } else { Flow::Next }); + } + if !flags.promoted + && flags.finalizing + && matches!(kind, "session.execution.succeeded" | "session.execution.interrupted") + { + return Ok(Flow::Done); + } + if !flags.promoted { + return Ok(Flow::Next); + } + if flags.finalizing && !kind.starts_with("session.execution.") { + return Ok(Flow::Next); + } + } + let message = text(&data["assistantMessageID"]).to_owned(); + let part_id = part_id(text(&event["id"])); + + match kind { + "session.step.started" => { + let part = object([ + ("id", Some(Value::from(part_id))), + ("sessionID", Some(self.input.session_id.clone().into())), + ("messageID", Some(message.clone().into())), + ("type", Some("step-start".into())), + ("snapshot", data.get("snapshot").cloned()), + ]); + self.steps.borrow_mut().insert(message, false); + if !self.emit("step_start", &time, [("part", part)]) { + ui::empty(); + ui::println(&[&format!( + "> {} · {}", + text(&data["agent"]), + text(&data["model"]["id"]) + )]); + ui::empty(); + } + } + "session.text.started" | "session.reasoning.started" => { + let prefix = kind.split('.').nth(1).unwrap_or_default(); + self.starts.borrow_mut().insert( + format!("{prefix}\0{}", content_key(&message, &data["ordinal"])), + (part_id, time), + ); + } + "session.text.ended" => { + let key = content_key(&message, &data["ordinal"]); + let started = self.starts.borrow_mut().remove(&format!("text\0{key}")); + let (id, start) = started.unwrap_or((part_id, time.clone())); + let part = object([ + ("id", Some(id.into())), + ("sessionID", Some(self.input.session_id.clone().into())), + ("messageID", Some(message.into())), + ("type", Some("text".into())), + ("text", Some(data["text"].clone())), + ("time", Some(json!({ "start": start, "end": time }))), + ]); + self.rendered_text + .borrow_mut() + .insert(key, text(&data["text"]).to_owned()); + self.write_text(part, &time); + } + "session.reasoning.ended" if self.input.thinking => { + let key = content_key(&message, &data["ordinal"]); + let started = self.starts.borrow_mut().remove(&format!("reasoning\0{key}")); + let (id, start) = started.unwrap_or((part_id, time.clone())); + let part = object([ + ("id", Some(id.into())), + ("sessionID", Some(self.input.session_id.clone().into())), + ("messageID", Some(message.into())), + ("type", Some("reasoning".into())), + ("text", Some(data["text"].clone())), + ("metadata", data.get("native").cloned()), + ("time", Some(json!({ "start": start, "end": time }))), + ]); + self.rendered_reasoning + .borrow_mut() + .insert(key, text(&data["text"]).to_owned()); + self.write_reasoning(part, &time); + } + "session.tool.input.started" => { + self.tools.borrow_mut().insert( + tool_key(&message, text(&data["id"])), + ToolState { + id: part_id, + timestamp: time, + tool: text(&data["name"]).to_owned(), + input: json!({}), + raw: None, + provider: None, + native: None, + metadata: json!({}), + }, + ); + } + "session.tool.input.ended" | "session.tool.input.delta" => { + if let Some(current) = self + .tools + .borrow_mut() + .get_mut(&tool_key(&message, text(&data["id"]))) + { + current.raw = Some(if kind.ends_with("ended") { + text(&data["text"]).to_owned() + } else { + current.raw.take().unwrap_or_default() + text(&data["delta"]) + }); + } + } + "session.tool.called" => { + let key = tool_key(&message, text(&data["id"])); + let mut tools = self.tools.borrow_mut(); + let current = tools.remove(&key); + let provider = object([ + ("executed", data.get("executed").cloned()), + ("state", data.get("native").cloned()), + ]); + tools.insert( + key, + ToolState { + id: current.as_ref().map_or(part_id, |current| current.id.clone()), + timestamp: current + .as_ref() + .map_or(time, |current| current.timestamp.clone()), + tool: current + .as_ref() + .map_or("tool".to_owned(), |current| current.tool.clone()), + input: data["input"].clone(), + raw: current.and_then(|current| current.raw), + provider: Some(provider), + native: data.get("native").cloned(), + metadata: json!({}), + }, + ); + } + "session.tool.progress" => { + if let Some(current) = self + .tools + .borrow_mut() + .get_mut(&tool_key(&message, text(&data["id"]))) + { + current.metadata = data["metadata"].clone(); + } + } + "session.tool.success" | "session.tool.failed" => { + self.tool_ended(kind == "session.tool.success", event, &message, part_id, &time) + .await; + } + "session.step.ended" => { + self.steps.borrow_mut().insert(message.clone(), true); + let part = object([ + ("id", Some(part_id.into())), + ("sessionID", Some(self.input.session_id.clone().into())), + ("messageID", Some(message.into())), + ("type", Some("step-finish".into())), + ("reason", data.get("finish").cloned()), + ("snapshot", data.get("snapshot").cloned()), + ("cost", data.get("cost").cloned()), + ("tokens", data.get("tokens").cloned()), + ]); + self.emit("step_finish", &time, [("part", part)]); + } + "session.step.failed" => { + let quiet = { + let flags = self.flags.borrow(); + flags.interrupted || flags.form_cancelled + }; + if !quiet { + self.fail(&data["error"], &time); + } + } + "session.execution.failed" => { + let report = { + let flags = self.flags.borrow(); + !flags.emitted_error && !flags.form_cancelled + }; + if report { + self.fail(&data["error"], &time); + } + return Ok(Flow::Done); + } + "session.execution.interrupted" => { + let (interrupted, report) = { + let flags = self.flags.borrow(); + (flags.interrupted, !flags.emitted_error && !flags.form_cancelled) + }; + let reason = text(&data["reason"]); + if reason == "user" && interrupted { + self.input.exit.set(130); + } + // A declined tool call ends the step with an interruption; it was already reported above. + if reason != "user" && report { + self.fail( + &json!({ "type": "aborted", "message": format!("Session interrupted: {reason}") }), + &time, + ); + } + return Ok(Flow::Done); + } + "session.execution.succeeded" => { + let waiting = self.pending_background().await; + self.flags.borrow_mut().waiting_for_background = waiting; + if !waiting { + return Ok(Flow::Done); + } + } + _ => {} + } + Ok(Flow::Next) + } + + async fn tool_ended(&self, success: bool, event: &Value, message: &str, part_id: String, time: &Value) { + let data = &event["data"]; + let id = text(&data["id"]); + let key = tool_key(message, id); + let current = self.tools.borrow_mut().remove(&key).unwrap_or(ToolState { + id: part_id, + timestamp: time.clone(), + tool: "tool".to_owned(), + input: json!({}), + raw: None, + provider: None, + native: None, + metadata: json!({}), + }); + self.rendered_tools.borrow_mut().insert(key); + let native = match (data.get("native"), ¤t.native) { + (Some(Value::Object(next)), Some(Value::Object(previous))) => { + let mut merged = previous.clone(); + merged.extend(next.clone()); + Some(Value::Object(merged)) + } + (Some(next), _) if !next.is_null() => Some(next.clone()), + (_, previous) => previous.clone(), + }; + let provider_result = object([ + ("executed", data.get("executed").cloned()), + ("state", data.get("native").cloned()), + ]); + let tool_time = json!({ "created": current.timestamp, "ran": current.timestamp, "completed": time }); + let part_time = json!({ "start": current.timestamp, "end": time }); + let tool = |state: Value| { + object([ + ("type", Some("tool".into())), + ("id", Some(id.into())), + ("name", Some(current.tool.clone().into())), + ("executed", data.get("executed").cloned()), + ("native", native.clone()), + ("state", Some(state)), + ("time", Some(tool_time.clone())), + ]) + }; + if success { + let state = object([ + ("status", Some("completed".into())), + ("input", Some(current.input.clone())), + ("metadata", data.get("metadata").cloned()), + ("content", data.get("content").cloned()), + ]); + let part = object([ + ("partID", Some(current.id.clone().into())), + ("sessionID", Some(self.input.session_id.clone().into())), + ("messageID", Some(message.into())), + ("type", Some("tool".into())), + ("id", Some(id.into())), + ("tool", Some(current.tool.clone().into())), + ( + "state", + Some(object([ + ("status", Some("completed".into())), + ("input", Some(current.input.clone())), + ("output", Some(output_text(¤t.tool, data.get("content")).into())), + ("title", Some(current.tool.clone().into())), + ( + "metadata", + Some(object([ + ("metadata", data.get("metadata").cloned()), + ("content", data.get("content").cloned()), + ("providerCall", current.provider.clone()), + ("providerResult", Some(provider_result)), + ("rawInput", current.raw.clone().map(Value::from)), + ])), + ), + ("time", Some(part_time)), + ])), + ), + ]); + if !self.emit("tool_use", time, [("part", part)]) { + self.render_tool(&tool(state)); + } + return; + } + let error = &data["error"]; + let metadata = data.get("metadata").cloned().unwrap_or(current.metadata.clone()); + // `nonEmptyToolContent(current.content)`: the live state never holds content. + let content = data.get("content").cloned(); + let part = object([ + ("partID", Some(current.id.clone().into())), + ("sessionID", Some(self.input.session_id.clone().into())), + ("messageID", Some(message.into())), + ("type", Some("tool".into())), + ("id", Some(id.into())), + ("tool", Some(current.tool.clone().into())), + ( + "state", + Some(object([ + ("status", Some("error".into())), + ("input", Some(current.input.clone())), + ("error", error.get("message").cloned()), + ( + "metadata", + Some(object([ + ("providerCall", current.provider.clone()), + ("providerResult", Some(provider_result)), + ("rawInput", current.raw.clone().map(Value::from)), + ])), + ), + ("time", Some(part_time)), + ])), + ), + ]); + if self.emit("tool_use", time, [("part", part)]) { + return; + } + if content.is_some() && !output_text(¤t.tool, content.as_ref()).trim().is_empty() { + self.render_tool(&tool(object([ + ("status", Some("completed".into())), + ("input", Some(current.input.clone())), + ("metadata", Some(metadata.clone())), + ("content", content.clone()), + ]))); + } + let failed = tool(object([ + ("status", Some("error".into())), + ("input", Some(current.input.clone())), + ("metadata", Some(metadata)), + ("content", content), + ("error", Some(error.clone())), + ])); + self.render_tool_error(&failed); + ui::error(text(&error["message"])); + } + + /// Emits only the step lines, text, reasoning, tools and errors the live stream missed. + async fn reconcile(&self) -> Result<(bool, bool), String> { + let (found, messages) = self.projected_messages().await?; + for message in &messages { + if message["type"] != "assistant" { + continue; + } + let id = text(&message["id"]); + let created = message["time"]["created"].clone(); + let timestamp = match &message["time"]["completed"] { + Value::Null => created.clone(), + completed => completed.clone(), + }; + let step = self.steps.borrow().get(id).copied(); + if step.is_none() { + let part = object([ + ("id", Some(projected_part_id(id, "step-start").into())), + ("sessionID", Some(self.input.session_id.clone().into())), + ("messageID", Some(id.into())), + ("type", Some("step-start".into())), + ("snapshot", message.get("snapshot").and_then(|s| s.get("start")).cloned()), + ]); + self.emit("step_start", &created, [("part", part)]); + } + let mut text_ordinal = 0; + let mut reasoning_ordinal = 0; + for item in message["content"].as_array().into_iter().flatten() { + let item_type = text(&item["type"]); + if item_type == "text" || item_type == "reasoning" { + let reasoning = item_type == "reasoning"; + let ordinal = if reasoning { &mut reasoning_ordinal } else { &mut text_ordinal }; + let current = *ordinal; + *ordinal += 1; + if reasoning && !self.input.thinking { + continue; + } + let key = content_key(id, &Value::from(current)); + let rendered_map = if reasoning { &self.rendered_reasoning } else { &self.rendered_text }; + let rendered = rendered_map.borrow().get(&key).cloned().unwrap_or_default(); + let full = text(&item["text"]); + if rendered == full || !full.starts_with(&rendered) { + continue; + } + let rest = &full[rendered.len()..]; + let part = object([ + ("id", Some(projected_part_id(id, &format!("{item_type}-{current}")).into())), + ("sessionID", Some(self.input.session_id.clone().into())), + ("messageID", Some(id.into())), + ("type", Some(item_type.into())), + ("text", Some(rest.into())), + ("metadata", if reasoning { item.get("native").cloned() } else { None }), + ("time", Some(json!({ "start": created, "end": timestamp }))), + ]); + rendered_map.borrow_mut().insert(key, full.to_owned()); + if reasoning { + self.write_reasoning(part, ×tamp); + } else { + self.write_text(part, ×tamp); + } + continue; + } + + let item_id = text(&item["id"]); + let key = tool_key(id, item_id); + let status = text(&item["state"]["status"]); + if self.rendered_tools.borrow().contains(&key) || status == "streaming" || status == "running" { + continue; + } + let name = text(&item["name"]); + let state = &item["state"]; + let start = match &item["time"]["ran"] { + Value::Null => item["time"]["created"].clone(), + ran => ran.clone(), + }; + let end = match &item["time"]["completed"] { + Value::Null => timestamp.clone(), + completed => completed.clone(), + }; + let metadata = object([ + ("metadata", state.get("metadata").cloned()), + ("content", state.get("content").cloned()), + ]); + let projected = if status == "completed" { + object([ + ("status", Some("completed".into())), + ("input", state.get("input").cloned()), + ("output", Some(output_text(name, state.get("content")).into())), + ("title", Some(name.into())), + ("metadata", Some(metadata)), + ("time", Some(json!({ "start": start, "end": end }))), + ]) + } else { + object([ + ("status", Some("error".into())), + ("input", state.get("input").cloned()), + ("error", state["error"].get("message").cloned()), + ("metadata", Some(metadata)), + ("time", Some(json!({ "start": start, "end": end }))), + ]) + }; + let part = object([ + ("partID", Some(projected_part_id(id, &format!("tool-{item_id}")).into())), + ("sessionID", Some(self.input.session_id.clone().into())), + ("messageID", Some(id.into())), + ("type", Some("tool".into())), + ("id", Some(item_id.into())), + ("tool", Some(name.into())), + ("state", Some(projected)), + ]); + self.rendered_tools.borrow_mut().insert(key); + if self.emit("tool_use", ×tamp, [("part", part)]) { + continue; + } + if status == "completed" { + self.render_tool(item); + continue; + } + if state.get("content").is_some_and(|content| !content.is_null()) + && !output_text(name, state.get("content")).trim().is_empty() + { + let mut completed = item.clone(); + completed["state"] = object([ + ("status", Some("completed".into())), + ("input", state.get("input").cloned()), + ("metadata", state.get("metadata").cloned()), + ("content", state.get("content").cloned()), + ]); + self.render_tool(&completed); + } + self.render_tool_error(item); + ui::error(text(&state["error"]["message"])); + } + + if step != Some(true) && !message["finish"].is_null() && !message["tokens"].is_null() { + let part = object([ + ("id", Some(projected_part_id(id, "step-finish").into())), + ("sessionID", Some(self.input.session_id.clone().into())), + ("messageID", Some(id.into())), + ("type", Some("step-finish".into())), + ("reason", message.get("finish").cloned()), + ("snapshot", message.get("snapshot").and_then(|s| s.get("end")).cloned()), + ("cost", Some(match &message["cost"] { + Value::Null => 0.into(), + cost => cost.clone(), + })), + ("tokens", message.get("tokens").cloned()), + ]); + self.emit("step_finish", ×tamp, [("part", part)]); + } + + // A declined tool call ends its step with an interrupted-step error that is only a consequence + // of our own rejection; it was already reported above. + let report = { + let flags = self.flags.borrow(); + !flags.emitted_error && !flags.form_cancelled + }; + if truthy(&message["error"]) && report { + self.fail(&message["error"], ×tamp); + } + } + let responded = messages.iter().any(|message| message["type"] == "assistant"); + Ok((found, responded)) + } + + /// The messages after this run's prompt, oldest first, and whether the prompt was found. + async fn projected_messages(&self) -> Result<(bool, Vec), String> { + let mut messages = Vec::new(); + let mut cursor: Option = None; + loop { + let mut call = Call::new( + "GET", + format!("/api/session/{}/message", path(&self.input.session_id)), + 200, + &[400, 401, 404, 500], + ); + call.query("limit", &200).map_err(|error| error.to_string())?; + match &cursor { + Some(cursor) => call.query("cursor", cursor), + None => call.query("order", "desc"), + } + .map_err(|error| error.to_string())?; + let page: Value = self + .input + .client + .json(call, &RequestOptions::default()) + .await + .map_err(|error| error.to_string())?; + for message in page["data"].as_array().into_iter().flatten() { + if text(&message["id"]) == self.message_id { + messages.reverse(); + return Ok((true, messages)); + } + messages.push(message.clone()); + } + match page["cursor"]["next"].as_str().filter(|next| !next.is_empty()) { + Some(next) => cursor = Some(next.to_owned()), + None => return Ok((false, Vec::new())), + } + } + } + + /// Any job in the tree holds the run open: this session's, its subagents', and theirs. + async fn pending_background(&self) -> bool { + if !settled_flags(&self.flags.borrow()) { + return false; + } + let jobs = self + .data( + "/api/experimental/job", + &[ + ("sessionID", Value::from(self.input.session_id.clone())), + ("descendants", Value::from(true)), + ], + ) + .await + .unwrap_or_else(|_| json!([])); + for job in array(Some(&jobs)) { + self.add_job_session(text(&job["sessionID"])); + if job["kind"] == "subagent" { + self.add_job_session(text(&job["childSessionID"])); + } + } + if !array(Some(&jobs)).is_empty() { + return true; + } + // A finished job wakes its session before its row is removed, so a wake that raced the list above + // shows up as a queued inbox item or an active session in the tree. + let active = self.data("/api/session/active", &[]).await.unwrap_or_else(|_| json!({})); + let sessions = self.job_sessions.borrow().clone(); + for session in sessions { + let inbox = self + .data(&format!("/api/session/{}/inbox", path(&session)), &[]) + .await + .unwrap_or_else(|_| json!([])); + if !array(Some(&inbox)).is_empty() { + return true; + } + } + for session in active.as_object().into_iter().flat_map(|active| active.keys()) { + if self.owns(session).await { + return true; + } + } + false + } + + fn add_job_session(&self, session: &str) { + let mut sessions = self.job_sessions.borrow_mut(); + if !sessions.iter().any(|known| known == session) { + sessions.push(session.to_owned()); + } + } + + /// Subagents run in child sessions; their asks and questions belong to this run too. Other sessions on + /// a shared server (the TUI's, for example) are left alone. + fn owns<'a>(&'a self, session: &'a str) -> std::pin::Pin + 'a>> { + Box::pin(async move { + if let Some(known) = self.owned.borrow().get(session) { + return *known; + } + let result = if session == GLOBAL_FORM_SESSION_ID { + false + } else { + match self.data(&format!("/api/session/{}", path(session)), &[]).await { + Ok(info) => match info["parentID"].as_str() { + Some(parent) if !parent.is_empty() => self.owns(parent).await, + _ => false, + }, + Err(_) => false, + } + }; + self.owned.borrow_mut().insert(session.to_owned(), result); + result + }) + } + + /// Nobody can approve here: reject with feedback so the tool fails as ordinary model-visible output, or + /// approve once with `--auto`. + async fn reply_permission(&self, request: &Value) { + let auto = self.input.auto; + if !auto { + let resources = request["resources"] + .as_array() + .into_iter() + .flatten() + .map(text) + .collect::>() + .join(", "); + ui::println(&[ + &format!("{}!", ui::TEXT_WARNING_BOLD), + &format!( + "{}permission requested: {} ({resources}); auto-rejecting", + ui::TEXT_NORMAL, + text(&request["action"]) + ), + ]); + } + let _ = self + .input + .client + .permission_reply( + &PermissionReplyInput { + session_id: SessionID(text(&request["sessionID"]).to_owned()), + request_id: PermissionID(text(&request["id"]).to_owned()), + decision: if auto { PermissionReply::Once } else { PermissionReply::Reject }, + message: (!auto).then(|| PERMISSION_REJECTED_FEEDBACK.to_owned()), + }, + &RequestOptions::default(), + ) + .await; + } + + /// Nobody can answer a form here. A question is cancelled with a message so the model continues + /// without an answer; any other form ends the run with exit code 1. + async fn cancel_form(&self, form: &Value) -> Result<(), String> { + let continuing = form["metadata"]["kind"] == "question"; + let result = self + .input + .client + .session_form_cancel( + &SessionFormCancelInput { + session_id: text(&form["sessionID"]).to_owned(), + form_id: FormID(text(&form["id"]).to_owned()), + message: continuing.then(|| QUESTION_CANCELLED_FEEDBACK.to_owned()), + }, + &RequestOptions::default(), + ) + .await; + if let Err(error) = result { + let settled = error + .declared() + .is_some_and(|declared| declared.tag.as_deref() == Some("FormAlreadySettledError")); + if !settled { + return Err(error.to_string()); + } + } + if continuing { + return Ok(()); + } + self.flags.borrow_mut().form_cancelled = true; + self.input.exit.set(1); + Ok(()) + } + + async fn interrupt_session(&self) { + let _ = self.interrupt_request().await; + } + + async fn interrupt_request(&self) -> Result { + let call = Call::new( + "POST", + format!("/api/session/{}/interrupt", path(&self.input.session_id)), + 200, + &[400, 401, 404], + ); + self.input.client.json(call, &RequestOptions::default()).await + } + + /// `GET path` and its `data`, as the TS Promise client unwraps it. + async fn data(&self, path: &str, query: &[(&str, Value)]) -> Result { + let mut call = Call::new("GET", path.to_owned(), 200, &[400, 401, 404]); + for (key, value) in query { + call.query(key, value)?; + } + let mut value: Value = self.input.client.json(call, &RequestOptions::default()).await?; + Ok(value.get_mut("data").map(Value::take).unwrap_or(Value::Null)) + } + + /// A step or execution error: exit code 1, then the error line or JSON event. + fn fail(&self, error: &Value, time: &Value) { + self.flags.borrow_mut().emitted_error = true; + self.input.exit.set(1); + if !self.emit("error", time, [("error", error.clone())]) { + ui::error(text(&error["message"])); + } + } + + fn emit(&self, kind: &str, timestamp: &Value, data: [(&str, Value); N]) -> bool { + if !self.input.json { + return false; + } + let mut line = Map::new(); + line.insert("type".into(), kind.into()); + line.insert("timestamp".into(), timestamp.clone()); + line.insert("sessionID".into(), self.input.session_id.clone().into()); + for (key, value) in data { + line.insert(key.into(), value); + } + let _ = crate::output::print(&(Value::Object(line).to_string() + "\n")); + true + } + + fn write_text(&self, part: Value, time: &Value) { + if self.emit("text", time, [("part", part.clone())]) { + return; + } + let body = text(&part["text"]).trim(); + if body.is_empty() { + return; + } + if !std::io::stdout().is_terminal() { + let _ = crate::output::print(&format!("{body}\n")); + return; + } + ui::empty(); + ui::println(&[body]); + ui::empty(); + } + + fn write_reasoning(&self, part: Value, time: &Value) { + if self.emit("reasoning", time, [("part", part.clone())]) { + return; + } + let body = text(&part["text"]).trim(); + if body.is_empty() { + return; + } + let line = format!("Thinking: {body}"); + if !std::io::stdout().is_terminal() { + let _ = crate::output::print(&format!("{line}\n")); + return; + } + ui::empty(); + ui::println(&[&format!("{}\x1b[3m{line}\x1b[0m{}", ui::TEXT_DIM, ui::TEXT_NORMAL)]); + ui::empty(); + } + + fn render_tool(&self, part: &Value) { + let Some(info) = inline(part, &self.input.directory) else { + return; + }; + if info.block { + ui::empty(); + ui::println(&[ + &format!("{}{}", ui::TEXT_NORMAL, info.icon), + &format!("{}{}", ui::TEXT_NORMAL, info.title), + ]); + if let Some(body) = info.body.filter(|body| !body.trim().is_empty()) { + ui::println(&[&body]); + } + ui::empty(); + return; + } + let description = info + .description + .filter(|description| !description.is_empty()) + .map(|description| format!("{}{description}{}", ui::TEXT_DIM, ui::TEXT_NORMAL)) + .unwrap_or_default(); + ui::println(&[ + &format!("{}{}", ui::TEXT_NORMAL, info.icon), + &format!("{}{}", ui::TEXT_NORMAL, info.title), + &description, + ]); + } + + fn render_tool_error(&self, part: &Value) { + let Some(info) = inline(part, &self.input.directory) else { + return; + }; + ui::println(&[ + &format!("{}✗", ui::TEXT_NORMAL), + &format!("{}{} failed", ui::TEXT_NORMAL, info.title), + ]); + } +} + +/// The first Ctrl+C interrupts the session; a second one exits at once with 130. +async fn interrupt_on_signal(run: Rc) { + loop { + if tokio::signal::ctrl_c().await.is_err() { + return; + } + if run.flags.borrow().interrupted { + std::process::exit(130); + } + run.flags.borrow_mut().interrupted = true; + run.input.exit.set(130); + run.admission.notify_one(); + let target = run.clone(); + tokio::task::spawn_local(async move { + let stopped = target + .interrupt_request() + .await + .is_ok_and(|result| result["interrupted"] == true); + if !stopped { + target.abort.send_replace(true); + } + }); + } +} + +fn settled_flags(flags: &Flags) -> bool { + !flags.interrupted && !flags.form_cancelled && !flags.emitted_error +} + +/// `toolInlineInfo` over the JSON part. The generated type needs `metadata` and `content`, which the TS +/// summary reads as optional. +fn inline(part: &Value, directory: &str) -> Option { + let mut part = part.clone(); + if let Some(state) = part["state"].as_object_mut() { + state.entry("metadata").or_insert_with(|| json!({})); + if state.get("content").is_none_or(Value::is_null) { + state.insert("content".into(), json!([])); + } + } + match serde_json::from_value::(part) { + Ok(tool) => Some(tool_inline_info(&tool, Some(directory))), + Err(error) => { + log::warn!("run: cannot summarize a tool part: {error}"); + None + } + } +} + +fn output_text(name: &str, content: Option<&Value>) -> String { + let content: Vec = content + .and_then(|content| serde_json::from_value(content.clone()).ok()) + .unwrap_or_default(); + tool_output_text(name, &content) +} + +/// An object of the fields that are present: `undefined` fields vanish from `JSON.stringify`. +fn object(fields: [(&str, Option); N]) -> Value { + Value::Object( + fields + .into_iter() + .filter_map(|(key, value)| value.map(|value| (key.to_owned(), value))) + .collect(), + ) +} + +fn array(value: Option<&Value>) -> &[Value] { + value.and_then(Value::as_array).map_or(&[], Vec::as_slice) +} + +fn text(value: &Value) -> &str { + value.as_str().unwrap_or_default() +} + +fn truthy(value: &Value) -> bool { + !matches!(value, Value::Null | Value::Bool(false)) +} + +fn path(segment: &str) -> String { + opencode_api::client::path_param(segment).unwrap_or_else(|_| segment.to_owned()) +} + +fn event_time(event: &Value) -> Value { + match &event["created"] { + Value::Number(number) => Value::Number(number.clone()), + _ => now(), + } +} + +fn now() -> Value { + let millis = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_millis() as u64); + Value::from(millis) +} + +fn part_id(event_id: &str) -> String { + format!("prt_{}", event_id.strip_prefix("evt_").unwrap_or(event_id)) +} + +fn projected_part_id(message_id: &str, part: &str) -> String { + format!("prt_{}_{part}", message_id.strip_prefix("msg_").unwrap_or(message_id)) +} + +fn tool_key(message_id: &str, id: &str) -> String { + format!("{message_id}\0{id}") +} + +fn content_key(message_id: &str, ordinal: &Value) -> String { + format!("{message_id}\0{ordinal}") +} diff --git a/packages/cli-rs/crates/cli/src/run/ui.rs b/packages/cli-rs/crates/cli/src/run/ui.rs new file mode 100644 index 00000000000..c340d3517a8 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/run/ui.rs @@ -0,0 +1,29 @@ +//! `run`'s text output on stderr (`packages/cli/src/run/ui.ts`). + +use std::io::Write; +use std::sync::atomic::{AtomicBool, Ordering}; + +pub const TEXT_DIM: &str = "\x1b[90m"; +pub const TEXT_NORMAL: &str = "\x1b[0m"; +pub const TEXT_WARNING_BOLD: &str = "\x1b[93m\x1b[1m"; +pub const TEXT_DANGER_BOLD: &str = "\x1b[91m\x1b[1m"; + +/// The parts joined by spaces, then a newline, on stderr. +pub fn println(parts: &[&str]) { + let _ = writeln!(std::io::stderr().lock(), "{}", parts.join(" ")); +} + +// TS never resets its flag, so only the first blank line of a run is printed. +static BLANK: AtomicBool = AtomicBool::new(false); + +pub fn empty() { + if BLANK.swap(true, Ordering::Relaxed) { + return; + } + println(&[TEXT_NORMAL]); +} + +pub fn error(message: &str) { + let message = message.strip_prefix("Error: ").unwrap_or(message); + println(&[&format!("{TEXT_DANGER_BOLD}Error: {TEXT_NORMAL}{message}")]); +} diff --git a/packages/cli-rs/parity/scenarios/C.10/bad-model.cli.ts b/packages/cli-rs/parity/scenarios/C.10/bad-model.cli.ts new file mode 100644 index 00000000000..01e990fded9 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/bad-model.cli.ts @@ -0,0 +1,5 @@ +// An invalid `-m` fails before anything is created. +import { defineCli } from "../../cli/run" +import { server } from "./fixture" + +export default defineCli({ args: ["run", "-m", "nomodel", "hi"], server: server() }) diff --git a/packages/cli-rs/parity/scenarios/C.10/continue.cli.ts b/packages/cli-rs/parity/scenarios/C.10/continue.cli.ts new file mode 100644 index 00000000000..98a3acd9c81 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/continue.cli.ts @@ -0,0 +1,20 @@ +// `-c -m demo/other#high --agent plan --title kept --archived`: the latest session of the directory is +// resumed, so neither the title nor the archive flag is applied; the agent and model are switched. +import { defineCli } from "../../cli/run" +import { location, server, session, textStep } from "./fixture" + +export default defineCli({ + args: ["run", "-c", "-m", "demo/other#high", "--agent", "plan", "--title", "kept", "--archived", "again"], + server: server({ + sessionID: "ses_old", + events: () => textStep("ok"), + routes: [ + { + path: "/api/session", + json: { data: [session("ses_child", { location: { directory: "/tmp/run/sub" } }), session("ses_old", { agent: "build" })], cursor: {} }, + }, + { method: "POST", path: "/api/session/ses_old/agent", status: 204 }, + { method: "POST", path: "/api/session/ses_old/model", status: 204 }, + ], + }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/dashdash.cli.ts b/packages/cli-rs/parity/scenarios/C.10/dashdash.cli.ts new file mode 100644 index 00000000000..1cf71e1ce12 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/dashdash.cli.ts @@ -0,0 +1,8 @@ +// Words after `--` are message words, not flags. +import { defineCli } from "../../cli/run" +import { server, textStep } from "./fixture" + +export default defineCli({ + args: ["run", "a", "--server", "$SERVER", "--", "--model", "x", "-c"], + server: server({ events: () => textStep("ok") }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/file-directory.cli.ts b/packages/cli-rs/parity/scenarios/C.10/file-directory.cli.ts new file mode 100644 index 00000000000..e47524e59a3 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/file-directory.cli.ts @@ -0,0 +1,9 @@ +// A directory cannot be attached. +import { defineCli } from "../../cli/run" +import { server } from "./fixture" + +export default defineCli({ + args: ["run", "hi", "-f", "sub"], + files: { "sub/x": "x" }, + server: server(), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/file-large.cli.ts b/packages/cli-rs/parity/scenarios/C.10/file-large.cli.ts new file mode 100644 index 00000000000..569b5c69b2b --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/file-large.cli.ts @@ -0,0 +1,9 @@ +// A file over 10 MiB cannot be attached. +import { defineCli } from "../../cli/run" +import { server } from "./fixture" + +export default defineCli({ + args: ["run", "hi", "-f", "big.txt"], + files: { "big.txt": "x".repeat(10 * 1024 * 1024 + 1) }, + server: server(), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/file-missing.cli.ts b/packages/cli-rs/parity/scenarios/C.10/file-missing.cli.ts new file mode 100644 index 00000000000..4db417aa7e1 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/file-missing.cli.ts @@ -0,0 +1,9 @@ +// A missing file fails before anything is created, as a JSON error envelope with no session. +import { defineCli } from "../../cli/run" +import { nowMask, server } from "./fixture" + +export default defineCli({ + args: ["run", "--format", "json", "hi", "-f", "nope.txt"], + server: server(), + masks: [nowMask], +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/files.cli.ts b/packages/cli-rs/parity/scenarios/C.10/files.cli.ts new file mode 100644 index 00000000000..88ee8c1bf0d --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/files.cli.ts @@ -0,0 +1,16 @@ +// `-f`: text files go inline in the prompt text, an image and a binary file as data URLs; one file +// is in a subdirectory. +import { defineCli } from "../../cli/run" +import { server, textStep } from "./fixture" + +export default defineCli({ + args: ["run", "look", "-f", "notes.md", "-f", "pic.png", "--file", "sub/../data.bin", "-f", "latin.txt"], + files: { + "notes.md": "# Notes\nline two\n", + "pic.png": new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + "data.bin": new Uint8Array([0, 1, 2, 3, 250]), + "latin.txt": new Uint8Array([0x68, 0xe9, 0x6c, 0x6c, 0x6f]), + "sub/keep": "", + }, + server: server({ events: () => textStep("Seen.") }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/fixture.ts b/packages/cli-rs/parity/scenarios/C.10/fixture.ts new file mode 100644 index 00000000000..9b4ca673e25 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/fixture.ts @@ -0,0 +1,168 @@ +// A fake server for `run`: one session `ses_run`, an event stream, and a prompt route that pushes the events a +// scenario scripts. The prompt ID is random on both sides, so events and the message list read it from the +// logged prompt request. +import type { Logged, Options, Route } from "../../lib/fake-server" + +export const directory = "/tmp/run" +export const location = { directory, project: { id: "proj_test", directory, canonical: directory } } +export const session = (id = "ses_run", extra: Record = {}) => ({ + id, + title: "", + projectID: "proj_test", + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: 1, updated: 1 }, + location: { directory }, + ...extra, +}) + +let counter = 0 +export const event = (type: string, data: Record, created = 10) => ({ + id: `evt_${type.replace(/\W/g, "")}${String(++counter).padStart(8, "0")}`, + created, + type, + durable: { aggregateID: "ses_run", seq: counter }, + data: { sessionID: "ses_run", ...data }, +}) + +export function promptID(requests: Logged[]) { + const prompt = requests.findLast((entry) => entry.method === "POST" && entry.path.endsWith("/prompt")) + return (prompt?.body as { id?: string } | undefined)?.id ?? "msg_missing" +} + +export const delivered = (id: string) => event("session.inbox.delivered", { inboxID: id }, 5) +export const succeeded = () => event("session.execution.succeeded", {}, 90) + +// A text step of assistant message `msg_a`. +export function textStep(text: string, extra: unknown[] = []) { + return [ + event("session.step.started", { + assistantMessageID: "msg_a", + agent: "build", + model: { id: "model", providerID: "demo" }, + snapshot: "snap_1", + started: 11, + }, 11), + event("session.text.started", { assistantMessageID: "msg_a", ordinal: 0 }, 12), + event("session.text.ended", { assistantMessageID: "msg_a", ordinal: 0, text }, 13), + ...extra, + event("session.step.ended", { + assistantMessageID: "msg_a", + finish: "stop", + cost: 0.0012, + tokens: { input: 5, output: 7, reasoning: 0, cache: { read: 0, write: 0 } }, + snapshot: "snap_2", + }, 20), + ] +} + +export function assistant(content: unknown[], extra: Record = {}) { + return { + id: "msg_a", + type: "assistant", + sessionID: "ses_run", + agent: "build", + model: { providerID: "demo", id: "model" }, + content, + finish: "stop", + cost: 0.0012, + tokens: { input: 5, output: 7, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: 11, completed: 20 }, + ...extra, + } +} + +type Script = { + // Events after the prompt, given its ID. + events?: (id: string) => unknown[] + // Messages after the prompt, oldest first. + messages?: unknown[] + routes?: Route[] + sessionID?: string + // The prompt is promoted (`session.inbox.delivered`) unless false. + delivered?: boolean + // The prompt is in the message list unless false. + listed?: boolean + // The last event, `session.execution.succeeded` by default; `null` for none. + end?: unknown + // Events pushed once the wait has answered. + late?: unknown[] +} + +// The scripted events carry `ses_run`; a script for another session gets its ID. +function retarget(events: unknown[], id: string) { + return events.map((item) => { + const value = item as { data?: { sessionID?: string } } + if (value.data?.sessionID !== "ses_run") return item + return { ...value, data: { ...value.data, sessionID: id } } + }) +} + +// The routes of a run that creates `ses_run` and prompts it. The wait answers late, so the live events are +// read before the run reconciles with the message list. +export function server(script: Script = {}): Options { + const id = script.sessionID ?? "ses_run" + return { + routes: [ + ...(script.routes ?? []), + { path: "/api/location", json: location }, + { method: "POST", path: "/api/session", json: { data: session(id) } }, + { path: "/api/event", events: [{ id: "evt_connected0000", type: "server.connected", data: {} }] }, + { + method: "POST", + path: `/api/session/${id}/prompt`, + json: (entry: Logged) => ({ + data: { + id: (entry.body as { id: string }).id, + sessionID: id, + time: { created: 3 }, + type: "user", + payload: { text: "x" }, + delivery: "steer", + }, + }), + then: (entry: Logged) => { + const prompt = (entry.body as { id: string }).id + return retarget( + [ + ...(script.delivered === false ? [] : [delivered(prompt)]), + ...(script.events?.(prompt) ?? []), + ...(script.end === null ? [] : [script.end ?? succeeded()]), + ], + id, + ) + }, + }, + // Late enough that a reply to a live ask is sent before the wait, on both sides. + { path: `/api/session/${id}/permission`, json: { data: [] }, delay: 150 }, + { path: `/api/session/${id}/form`, json: { data: [] }, delay: 150 }, + { + method: "POST", + path: `/api/experimental/session/${id}/wait`, + status: 204, + delay: 400, + then: () => retarget(script.late ?? [], id), + // After the run has started to reconcile. + thenDelay: 300, + }, + { path: "/api/experimental/job", json: { data: [] } }, + { path: "/api/session/active", json: { data: {} } }, + { path: `/api/session/${id}/inbox`, json: { data: [] } }, + { + path: `/api/session/${id}/message`, + json: (_entry: Logged, requests: Logged[]) => ({ + data: [ + ...(script.messages ?? []).toReversed(), + ...(script.listed === false + ? [] + : [{ id: promptID(requests), type: "user", sessionID: id, text: "x", time: { created: 3 } }]), + ], + cursor: {}, + }), + }, + ], + } +} + +// `reportRunError` and the "not promoted" error stamp `Date.now()`. +export const nowMask = { pattern: /"timestamp":\d{13}/g, replacement: '"timestamp":' } diff --git a/packages/cli-rs/parity/scenarios/C.10/fork-alone.cli.ts b/packages/cli-rs/parity/scenarios/C.10/fork-alone.cli.ts new file mode 100644 index 00000000000..0bab5447c86 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/fork-alone.cli.ts @@ -0,0 +1,5 @@ +// `--fork` needs `--continue` or `--session`. +import { defineCli } from "../../cli/run" +import { nowMask, server } from "./fixture" + +export default defineCli({ args: ["run", "--fork", "--format", "json", "hi"], server: server(), masks: [nowMask] }) diff --git a/packages/cli-rs/parity/scenarios/C.10/fork.cli.ts b/packages/cli-rs/parity/scenarios/C.10/fork.cli.ts new file mode 100644 index 00000000000..22b8f75a25d --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/fork.cli.ts @@ -0,0 +1,18 @@ +// `-s ses_old --fork --archived --format json`: the session is forked, and the fork archived. +import { defineCli } from "../../cli/run" +import { server, session, textStep } from "./fixture" + +export default defineCli({ + args: ["run", "-s", "ses_old", "--fork", "--archived", "--format", "json", "again"], + server: server({ + sessionID: "ses_fork", + events: () => textStep("ok").map((event) => ({ ...event, data: { ...event.data, sessionID: "ses_fork" } })), + routes: [ + { path: "/api/session/ses_old", json: { data: session("ses_old", { agent: "build", model: { providerID: "demo", id: "model" } }) } }, + { method: "POST", path: "/api/session/ses_old/fork", json: { data: session("ses_fork", { agent: "build", model: { providerID: "demo", id: "model" } }) } }, + { method: "POST", path: "/api/session/ses_fork/agent", status: 204 }, + { method: "POST", path: "/api/session/ses_fork/model", status: 204 }, + { method: "PATCH", path: "/api/session/ses_fork", status: 204 }, + ], + }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/form.cli.ts b/packages/cli-rs/parity/scenarios/C.10/form.cli.ts new file mode 100644 index 00000000000..90824d72a9e --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/form.cli.ts @@ -0,0 +1,21 @@ +// Any other form is cancelled and ends the run with exit code 1; the server says it is already settled. +import { defineCli } from "../../cli/run" +import { event, server, textStep } from "./fixture" + +export default defineCli({ + args: ["run", "hello"], + server: server({ + events: () => [ + event("form.created", { form: { id: "frm_2", sessionID: "ses_run", metadata: { kind: "mcp" }, fields: [] } }, 12), + ...textStep("Stopped."), + ], + routes: [ + { + method: "DELETE", + path: "/api/session/ses_run/form/frm_2", + status: 409, + json: { _tag: "FormAlreadySettledError", message: "settled" }, + }, + ], + }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/interrupted.cli.ts b/packages/cli-rs/parity/scenarios/C.10/interrupted.cli.ts new file mode 100644 index 00000000000..c04cc9a4636 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/interrupted.cli.ts @@ -0,0 +1,8 @@ +// An interruption the user did not ask for is an error. +import { defineCli } from "../../cli/run" +import { event, server, textStep } from "./fixture" + +export default defineCli({ + args: ["run", "--format", "json", "hello"], + server: server({ events: () => textStep("partial"), end: event("session.execution.interrupted", { reason: "shutdown" }, 30) }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/json.cli.ts b/packages/cli-rs/parity/scenarios/C.10/json.cli.ts new file mode 100644 index 00000000000..e91ffae0a25 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/json.cli.ts @@ -0,0 +1,14 @@ +// `run --format json --thinking`: text, reasoning, a read tool and the step, as JSON lines on stdout. +import { defineCli } from "../../cli/run" +import { event, server, textStep } from "./fixture" +import { read } from "./text.cli" + +const reasoning = [ + event("session.reasoning.started", { assistantMessageID: "msg_a", ordinal: 0 }, 12), + event("session.reasoning.ended", { assistantMessageID: "msg_a", ordinal: 0, text: "Let me look.", native: { sig: "x" } }, 12), +] + +export default defineCli({ + args: ["run", "--format", "json", "--thinking", "hello"], + server: server({ events: () => textStep("Hello there.", [...reasoning, ...read]) }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/no-message.cli.ts b/packages/cli-rs/parity/scenarios/C.10/no-message.cli.ts new file mode 100644 index 00000000000..e157d345264 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/no-message.cli.ts @@ -0,0 +1,5 @@ +// No words and empty stdin: an error, exit 1, nothing created. +import { defineCli } from "../../cli/run" +import { server } from "./fixture" + +export default defineCli({ args: ["run", " "], server: server() }) diff --git a/packages/cli-rs/parity/scenarios/C.10/not-promoted.cli.ts b/packages/cli-rs/parity/scenarios/C.10/not-promoted.cli.ts new file mode 100644 index 00000000000..a36ca8ff533 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/not-promoted.cli.ts @@ -0,0 +1,9 @@ +// The prompt never reaches the message list: once the stream ends the execution, "Prompt was not +// promoted", exit 1. (Without an event after the wait, TS waits forever; so does Rust.) +import { defineCli } from "../../cli/run" +import { server, succeeded } from "./fixture" + +export default defineCli({ + args: ["run", "hello"], + server: server({ delivered: false, listed: false, end: null, late: [succeeded()] }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/permission-auto.cli.ts b/packages/cli-rs/parity/scenarios/C.10/permission-auto.cli.ts new file mode 100644 index 00000000000..063155be0ef --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/permission-auto.cli.ts @@ -0,0 +1,12 @@ +// `--auto` approves the request once, without a warning line. +import { defineCli } from "../../cli/run" +import { server, textStep } from "./fixture" +import { ask } from "./permission.cli" + +export default defineCli({ + args: ["run", "--auto", "hello"], + server: server({ + events: () => [ask, ...textStep("Edited.")], + routes: [{ method: "POST", path: "/api/session/ses_run/permission/per_1/reply", status: 204 }], + }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/permission-pending.cli.ts b/packages/cli-rs/parity/scenarios/C.10/permission-pending.cli.ts new file mode 100644 index 00000000000..2f8e1ed4c2f --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/permission-pending.cli.ts @@ -0,0 +1,15 @@ +// A request already pending when the prompt is admitted (the list after the prompt) is rejected too; +// `--yolo` is the hidden spelling of `--auto`. +import { defineCli } from "../../cli/run" +import { server, textStep } from "./fixture" + +export default defineCli({ + args: ["run", "--yolo", "hello"], + server: server({ + events: () => textStep("ok"), + routes: [ + { path: "/api/session/ses_run/permission", json: { data: [{ id: "per_2", sessionID: "ses_run", action: "bash", resources: ["ls"] }] } }, + { method: "POST", path: "/api/session/ses_run/permission/per_2/reply", status: 204 }, + ], + }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/permission.cli.ts b/packages/cli-rs/parity/scenarios/C.10/permission.cli.ts new file mode 100644 index 00000000000..eb895d7f0e7 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/permission.cli.ts @@ -0,0 +1,13 @@ +// A permission request for this session is rejected with feedback, and the run goes on. +import { defineCli } from "../../cli/run" +import { event, server, textStep } from "./fixture" + +export const ask = event("permission.asked", { id: "per_1", action: "edit", resources: ["src/a.ts", "src/b.ts"] }, 12) + +export default defineCli({ + args: ["run", "hello"], + server: server({ + events: () => [ask, ...textStep("Skipped the edit.")], + routes: [{ method: "POST", path: "/api/session/ses_run/permission/per_1/reply", status: 204 }], + }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/pre-promotion-error.cli.ts b/packages/cli-rs/parity/scenarios/C.10/pre-promotion-error.cli.ts new file mode 100644 index 00000000000..1bebf3fa927 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/pre-promotion-error.cli.ts @@ -0,0 +1,13 @@ +// The execution fails before the prompt is promoted: that error is reported instead. +import { defineCli } from "../../cli/run" +import { event, nowMask, server } from "./fixture" + +export default defineCli({ + args: ["run", "--format", "json", "hello"], + server: server({ + delivered: false, + listed: false, + end: event("session.execution.failed", { error: { type: "unknown", message: "no provider" } }, 7), + }), + masks: [nowMask], +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/question.cli.ts b/packages/cli-rs/parity/scenarios/C.10/question.cli.ts new file mode 100644 index 00000000000..926132d2e0c --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/question.cli.ts @@ -0,0 +1,14 @@ +// A question form is cancelled with a message, so the model continues; the run succeeds. +import { defineCli } from "../../cli/run" +import { event, server, textStep } from "./fixture" + +export default defineCli({ + args: ["run", "hello"], + server: server({ + events: () => [ + event("form.created", { form: { id: "frm_1", sessionID: "ses_run", metadata: { kind: "question" }, fields: [] } }, 12), + ...textStep("Assumed yes."), + ], + routes: [{ method: "DELETE", path: "/api/session/ses_run/form/frm_1", status: 204 }], + }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/reconcile-json.cli.ts b/packages/cli-rs/parity/scenarios/C.10/reconcile-json.cli.ts new file mode 100644 index 00000000000..765448862bc --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/reconcile-json.cli.ts @@ -0,0 +1,9 @@ +// As `reconcile`, in JSON: step_start, text, tool_use and step_finish built from the projected message. +import { defineCli } from "../../cli/run" +import { assistant, server } from "./fixture" +import { content } from "./reconcile.cli" + +export default defineCli({ + args: ["run", "--format", "json", "--thinking", "hello"], + server: server({ messages: [assistant(content, { snapshot: { start: "s1", end: "s2" } })] }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/reconcile.cli.ts b/packages/cli-rs/parity/scenarios/C.10/reconcile.cli.ts new file mode 100644 index 00000000000..51153413610 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/reconcile.cli.ts @@ -0,0 +1,21 @@ +// The live stream carries only the promotion: text, reasoning (hidden without --thinking), a tool and the +// step come from the message list after the wait. +import { defineCli } from "../../cli/run" +import { assistant, server } from "./fixture" + +export const content = [ + { type: "reasoning", text: "hmm" }, + { type: "text", text: "From the list." }, + { + type: "tool", + id: "call_9", + name: "glob", + state: { status: "completed", input: { pattern: "*.ts" }, metadata: { count: 2 }, content: [{ type: "text", text: "a.ts\nb.ts" }] }, + time: { created: 14, ran: 15, completed: 16 }, + }, +] + +export default defineCli({ + args: ["run", "hello"], + server: server({ messages: [assistant(content)] }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/server-down.cli.ts b/packages/cli-rs/parity/scenarios/C.10/server-down.cli.ts new file mode 100644 index 00000000000..83c3edc99b6 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/server-down.cli.ts @@ -0,0 +1,10 @@ +// The server cannot be reached: the connection error as a JSON envelope, exit 1. +import { defineCli } from "../../cli/run" +import { nowMask } from "./fixture" + +export default defineCli({ + args: ["run", "--format", "json", "hello", "--server", "http://127.0.0.1:9"], + // The cause after the address is the HTTP stack's own text (Bun's fetch, reqwest). + masks: [nowMask, { pattern: /(Could not reach server at [^ ]+:) .*?"\}/, replacement: '$1 "}' }], + stderrLines: 0, +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/session-new.cli.ts b/packages/cli-rs/parity/scenarios/C.10/session-new.cli.ts new file mode 100644 index 00000000000..db410089f1f --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/session-new.cli.ts @@ -0,0 +1,12 @@ +// `-s ses_named` that the server does not know: the session is created with that ID. +import { defineCli } from "../../cli/run" +import { server, textStep } from "./fixture" + +export default defineCli({ + args: ["run", "-s", "ses_named", "hi"], + server: server({ + sessionID: "ses_named", + events: () => textStep("ok").map((event) => ({ ...event, data: { ...event.data, sessionID: "ses_named" } })), + routes: [{ path: "/api/session/ses_named", status: 404, json: { _tag: "SessionNotFoundError", message: "nope" } }], + }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/stdin-only.cli.ts b/packages/cli-rs/parity/scenarios/C.10/stdin-only.cli.ts new file mode 100644 index 00000000000..b99927e752b --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/stdin-only.cli.ts @@ -0,0 +1,9 @@ +// With no words, stdin alone is the message. +import { defineCli } from "../../cli/run" +import { server, textStep } from "./fixture" + +export default defineCli({ + args: ["run"], + stdin: "only stdin", + server: server({ events: () => textStep("ok") }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/stdin.cli.ts b/packages/cli-rs/parity/scenarios/C.10/stdin.cli.ts new file mode 100644 index 00000000000..01da3ae4d11 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/stdin.cli.ts @@ -0,0 +1,9 @@ +// Piped stdin follows the message words after a newline. +import { defineCli } from "../../cli/run" +import { server, textStep } from "./fixture" + +export default defineCli({ + args: ["run", "summarize", "this file"], + stdin: "line one\nline two\n", + server: server({ events: () => textStep("Summary.") }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/step-failed-json.cli.ts b/packages/cli-rs/parity/scenarios/C.10/step-failed-json.cli.ts new file mode 100644 index 00000000000..ce24a1742a6 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/step-failed-json.cli.ts @@ -0,0 +1,9 @@ +// As `step-failed`, in JSON. +import { defineCli } from "../../cli/run" +import { event, server } from "./fixture" +import { failed } from "./step-failed.cli" + +export default defineCli({ + args: ["run", "--format", "json", "hello"], + server: server({ events: () => failed, end: event("session.execution.failed", { error: { type: "provider", message: "rate limited" } }, 13) }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/step-failed.cli.ts b/packages/cli-rs/parity/scenarios/C.10/step-failed.cli.ts new file mode 100644 index 00000000000..deee016c84e --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/step-failed.cli.ts @@ -0,0 +1,13 @@ +// A failed step prints the error and exits 1. +import { defineCli } from "../../cli/run" +import { event, server } from "./fixture" + +export const failed = [ + event("session.step.started", { assistantMessageID: "msg_a", agent: "build", model: { id: "model", providerID: "demo" }, started: 11 }, 11), + event("session.step.failed", { assistantMessageID: "msg_a", error: { type: "provider", message: "Error: rate limited" } }, 12), +] + +export default defineCli({ + args: ["run", "hello"], + server: server({ events: () => failed, end: event("session.execution.failed", { error: { type: "provider", message: "rate limited" } }, 13) }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/text.cli.ts b/packages/cli-rs/parity/scenarios/C.10/text.cli.ts new file mode 100644 index 00000000000..5f1bb29e521 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/text.cli.ts @@ -0,0 +1,26 @@ +// `run hello`: a step with text and a read tool, printed as text (stdout is a pipe, so the text goes there +// and the step and tool lines go to stderr). +import { defineCli } from "../../cli/run" +import { event, server, textStep } from "./fixture" + +export const read = [ + event("session.tool.input.started", { assistantMessageID: "msg_a", id: "call_1", name: "read" }, 14), + event("session.tool.called", { + assistantMessageID: "msg_a", + id: "call_1", + input: { filePath: "/tmp/run/src/a.ts", offset: 1, limit: 20 }, + executed: false, + }, 15), + event("session.tool.success", { + assistantMessageID: "msg_a", + id: "call_1", + content: [{ type: "text", text: "1: const a = 1" }], + metadata: {}, + executed: false, + }, 16), +] + +export default defineCli({ + args: ["run", "hello", "world"], + server: server({ events: () => textStep("Hello there.", read) }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/thinking-text.cli.ts b/packages/cli-rs/parity/scenarios/C.10/thinking-text.cli.ts new file mode 100644 index 00000000000..469912a8640 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/thinking-text.cli.ts @@ -0,0 +1,13 @@ +// `run --thinking`: reasoning prints as a `Thinking:` line on stdout when it is a pipe. +import { defineCli } from "../../cli/run" +import { event, server, textStep } from "./fixture" + +const reasoning = [ + event("session.reasoning.started", { assistantMessageID: "msg_a", ordinal: 0 }, 12), + event("session.reasoning.ended", { assistantMessageID: "msg_a", ordinal: 0, text: " Let me look. " }, 12), +] + +export default defineCli({ + args: ["run", "--thinking", "hello"], + server: server({ events: () => textStep("Done.", reasoning) }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/tool-failed.cli.ts b/packages/cli-rs/parity/scenarios/C.10/tool-failed.cli.ts new file mode 100644 index 00000000000..8058ae2cd69 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/tool-failed.cli.ts @@ -0,0 +1,22 @@ +// A failed shell tool with output: the output as a block, the failure line, then the error. +import { defineCli } from "../../cli/run" +import { event, server, textStep } from "./fixture" + +export default defineCli({ + args: ["run", "hello"], + server: server({ + events: () => + textStep("Tried.", [ + event("session.tool.input.started", { assistantMessageID: "msg_a", id: "call_2", name: "bash" }, 14), + event("session.tool.input.delta", { assistantMessageID: "msg_a", id: "call_2", delta: "{\"command\":" }, 14), + event("session.tool.called", { assistantMessageID: "msg_a", id: "call_2", input: { command: "make test", description: "Run tests" }, executed: false }, 15), + event("session.tool.failed", { + assistantMessageID: "msg_a", + id: "call_2", + error: { type: "tool", message: "exit status 2" }, + content: [{ type: "text", text: "FAIL a_test\n" }], + executed: false, + }, 16), + ]), + }), +}) diff --git a/packages/cli-rs/parity/scenarios/C.10/worktree-continue.cli.ts b/packages/cli-rs/parity/scenarios/C.10/worktree-continue.cli.ts new file mode 100644 index 00000000000..cc8a392d525 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/worktree-continue.cli.ts @@ -0,0 +1,5 @@ +// `-w` starts a new session, so it cannot be combined with `-c`. +import { defineCli } from "../../cli/run" +import { server } from "./fixture" + +export default defineCli({ args: ["run", "-w", "-c", "hi"], server: server() }) diff --git a/packages/cli-rs/parity/scenarios/C.10/worktree.cli.ts b/packages/cli-rs/parity/scenarios/C.10/worktree.cli.ts new file mode 100644 index 00000000000..731fe120eef --- /dev/null +++ b/packages/cli-rs/parity/scenarios/C.10/worktree.cli.ts @@ -0,0 +1,15 @@ +// `-w=feature --title "" --archived`: a worktree of the project, a new session in it titled after the +// message, archived before the prompt. +import { defineCli } from "../../cli/run" +import { server, textStep } from "./fixture" + +export default defineCli({ + args: ["run", "-w=feature", "--title", "", "--archived", "a message that is longer than fifty characters in total, surely"], + server: server({ + events: () => textStep("ok"), + routes: [ + { method: "POST", path: "/api/worktree", json: { directory: "/tmp/wt/feature" } }, + { method: "PATCH", path: "/api/session/ses_run", status: 204 }, + ], + }), +}) diff --git a/packages/cli-rs/script/gen/mime.ts b/packages/cli-rs/script/gen/mime.ts new file mode 100644 index 00000000000..0ff8b645dfe --- /dev/null +++ b/packages/cli-rs/script/gen/mime.ts @@ -0,0 +1,20 @@ +// Writes crates/cli/src/run/mime.rs: the extension table of `mime-types`, which `FSUtil.mimeType` uses to type +// `run -f` attachments (packages/util/src/fs-util.ts). Sorted by extension for a binary search. +import { createRequire } from "node:module" + +const require = createRequire(new URL("../../../util/package.json", import.meta.url).pathname) +const types: Record = require("mime-types").types +const entries = Object.entries(types).toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) +const lines = [ + "// Generated by script/gen/mime.ts from the `mime-types` package. Do not edit.", + "", + "/// `(extension, type)`, sorted by extension.", + "pub const TYPES: &[(&str, &str)] = &[", + ...entries.map(([extension, type]) => ` (${JSON.stringify(extension)}, ${JSON.stringify(type)}),`), + "];", + "", +] + +const file = new URL("../../crates/cli/src/run/mime.rs", import.meta.url).pathname +await Bun.write(file, lines.join("\n")) +console.log(`mime: ${entries.length} extensions`)