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.
This commit is contained in:
Simon Klee 2026-11-04 23:40:53 +01:00
parent 2314d94f2b
commit ff7fa63d0d
No known key found for this signature in database
GPG key ID: B91696044D47BEA3
43 changed files with 3666 additions and 11 deletions

View file

@ -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",

View file

@ -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(|_| ())
}

View file

@ -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"] }

View file

@ -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<Connected> {
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<Connected> {
/// `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<Connected> {
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<Connected> {
let transport: Arc<dyn Transport> = 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");
}

View file

@ -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<String>,
}
impl<T: std::fmt::Display> From<T> 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<Cell<u8>>,
) -> 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::<Result<Vec<_>, _>>()?;
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<String> {
let argv: Vec<String> = 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<String> {
let value = words
.iter()
.map(|word| {
if word.contains(' ') {
format!("\"{}\"", word.replace('"', "\\\""))
} else {
word.clone()
}
})
.collect::<Vec<_>>()
.join(" ");
(!value.is_empty()).then_some(value)
}
fn merge_input(message: Option<String>, piped: Option<String>) -> Option<String> {
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<u16> = 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<u8>, 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) + "...");
}
}

View file

@ -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 {
/// `<file name="…">` 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<Prepared, String> {
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<u8>) -> 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!("<file name=\"{name}\">\n{text}\n</file>"));
}
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("<file name=\"a.md\">\n# hi\n\n</file>".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("<file name=\"a.txt\">\nh\u{fffd}\n</file>".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"));
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -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}")]);
}

View file

@ -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() })

View file

@ -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 },
],
}),
})

View file

@ -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") }),
})

View file

@ -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(),
})

View file

@ -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(),
})

View file

@ -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],
})

View file

@ -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.") }),
})

View file

@ -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<string, unknown> = {}) => ({
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<string, unknown>, 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<string, unknown> = {}) {
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":<now>' }

View file

@ -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] })

View file

@ -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 },
],
}),
})

View file

@ -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" },
},
],
}),
})

View file

@ -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) }),
})

View file

@ -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]) }),
})

View file

@ -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() })

View file

@ -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()] }),
})

View file

@ -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 }],
}),
})

View file

@ -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 },
],
}),
})

View file

@ -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 }],
}),
})

View file

@ -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],
})

View file

@ -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 }],
}),
})

View file

@ -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" } })] }),
})

View file

@ -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)] }),
})

View file

@ -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 <cause>"}' }],
stderrLines: 0,
})

View file

@ -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" } }],
}),
})

View file

@ -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") }),
})

View file

@ -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.") }),
})

View file

@ -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) }),
})

View file

@ -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) }),
})

View file

@ -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) }),
})

View file

@ -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) }),
})

View file

@ -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),
]),
}),
})

View file

@ -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() })

View file

@ -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 },
],
}),
})

View file

@ -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<string, string> = 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`)