diff --git a/packages/cli-rs/Cargo.lock b/packages/cli-rs/Cargo.lock index 08f8f8faa35..1b11fb28c25 100644 --- a/packages/cli-rs/Cargo.lock +++ b/packages/cli-rs/Cargo.lock @@ -11,6 +11,62 @@ dependencies = [ "memchr", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + [[package]] name = "atomic-waker" version = "1.1.2" @@ -108,6 +164,56 @@ dependencies = [ "rand_core", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", + "terminal_size", +] + +[[package]] +name = "clap_complete" +version = "4.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f" +dependencies = [ + "clap", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + [[package]] name = "cmake" version = "0.1.58" @@ -117,6 +223,12 @@ dependencies = [ "cc", ] +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "combine" version = "4.6.9" @@ -362,6 +474,12 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "http" version = "1.5.0" @@ -590,6 +708,12 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itoa" version = "1.0.18" @@ -672,6 +796,12 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.3" @@ -713,6 +843,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "opencode-acp" version = "0.1.0" @@ -744,6 +880,9 @@ dependencies = [ name = "opencode-cli" version = "0.1.0" dependencies = [ + "anyhow", + "clap", + "clap_complete", "opencode-acp", "opencode-api", "opencode-drive", @@ -753,6 +892,8 @@ dependencies = [ "opencode-store", "opencode-tui", "opencode-ui", + "serde_json", + "url", ] [[package]] @@ -1101,6 +1242,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.46" @@ -1351,6 +1505,12 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "subtle" version = "2.6.1" @@ -1399,6 +1559,16 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "terminal_size" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" +dependencies = [ + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "2.0.21" @@ -1698,6 +1868,12 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "utf_types" version = "1.0.0" diff --git a/packages/cli-rs/crates/cli/Cargo.toml b/packages/cli-rs/crates/cli/Cargo.toml index 408c9d227fa..5f957dc913c 100644 --- a/packages/cli-rs/crates/cli/Cargo.toml +++ b/packages/cli-rs/crates/cli/Cargo.toml @@ -14,6 +14,10 @@ path = "src/main.rs" workspace = true [dependencies] +anyhow.workspace = true +clap = { workspace = true, features = ["string"] } +clap_complete.workspace = true +url.workspace = true opencode-acp.workspace = true opencode-api.workspace = true opencode-drive.workspace = true @@ -23,3 +27,6 @@ opencode-service.workspace = true opencode-store.workspace = true opencode-tui.workspace = true opencode-ui.workspace = true + +[dev-dependencies] +serde_json.workspace = true diff --git a/packages/cli-rs/crates/cli/src/args.rs b/packages/cli-rs/crates/cli/src/args.rs new file mode 100644 index 00000000000..2dc61ec72da --- /dev/null +++ b/packages/cli-rs/crates/cli/src/args.rs @@ -0,0 +1,1107 @@ +//! The command tree of `packages/cli/src/commands/commands.ts`, with the same commands, flags, and descriptions. +//! `src/tests/tree.rs` proves it against a dump of the TypeScript tree. Effect CLI parses a few things differently +//! from clap; `normalize` and `validate` keep those behaviors (docs/C.0.md). + +use std::collections::HashSet; +use std::ffi::OsString; + +use clap::parser::ValueSource; +use clap::{ArgAction, ArgMatches, Args, Parser, Subcommand, ValueEnum}; + +#[derive(Parser, Debug)] +#[command(name = "opencode-rs", about = "OpenCode command line interface")] +pub struct Cli { + #[command(flatten)] + pub root: RootArgs, + #[command(flatten)] + pub global: GlobalArgs, + #[command(subcommand)] + pub command: Option, +} + +/// The Effect CLI built-ins and `--print-logs`, accepted by every command. +#[derive(Args, Debug, Clone, Default)] +pub struct GlobalArgs { + #[arg(short = 'h', long, global = true, action = ArgAction::Help, help = "Show help information")] + pub help: Option, + #[arg(short = 'v', long, global = true, help = "Show version information")] + pub version: bool, + #[arg(long, global = true, help = "Start wizard mode for a command")] + pub wizard: bool, + #[arg( + long, + global = true, + value_name = "shell", + help = "Print shell completion script" + )] + pub completions: Option, + #[arg( + long, + global = true, + value_name = "level", + help = "Sets the minimum log level" + )] + pub log_level: Option, + #[arg( + long, + global = true, + help = "Print logs to stderr (server logs require --standalone)" + )] + pub print_logs: bool, +} + +#[derive(Args, Debug, Clone)] +pub struct RootArgs { + // Own ids: clap copies the values of global args to every level by id, and `validate` must tell the + // root's `--server` from that of the selected command. + #[arg(id = "root_standalone", long = "standalone", help = STANDALONE)] + pub standalone: bool, + #[arg(id = "root_server", long = "server", value_name = "string", help = SERVER)] + pub server: Option, + #[command(flatten)] + pub permissions: PermissionFlags, + #[arg(value_name = "directory", help = "Directory to start OpenCode in")] + pub directory: Option, + #[arg(short = 'c', long = "continue", help = "Continue the last session")] + pub continue_: bool, + #[arg(short = 's', long, value_name = "string", help = SESSION)] + pub session: Option, + #[arg(long, value_name = "string", help = "Prompt to use")] + pub prompt: Option, +} + +const STANDALONE: &str = "Run with a private server instead of the background service"; +const SERVER: &str = "Connect to a server URL instead of the background service"; +const SESSION: &str = "Session ID to continue, or to create if it does not exist"; + +/// `--standalone` and `--server` on a command that declares them; they apply to its subcommands too. +#[derive(Args, Debug, Clone, Default)] +pub struct ServerFlags { + #[arg(long, global = true, help = STANDALONE)] + pub standalone: bool, + #[arg(long, global = true, value_name = "string", help = SERVER)] + pub server: Option, +} + +/// `debug heap-dump` takes `--server` without `--standalone`. +#[derive(Args, Debug, Clone, Default)] +pub struct ServerOnly { + #[arg(long, global = true, value_name = "string", help = SERVER)] + pub server: Option, +} + +#[derive(Args, Debug, Clone, Default)] +pub struct PermissionFlags { + #[arg(long, help = "Auto-approve permissions that are not explicitly denied")] + pub auto: bool, + #[arg(long, hide = true)] + pub yolo: bool, + #[arg(long, hide = true)] + pub dangerously_skip_permissions: bool, +} + +#[allow(dead_code, reason = "read by the handlers of later steps")] +impl PermissionFlags { + /// `--yolo` and `--dangerously-skip-permissions` are hidden spellings of `--auto`. + pub fn auto(&self) -> bool { + self.auto || self.yolo || self.dangerously_skip_permissions + } +} + +#[derive(Subcommand, Debug)] +pub enum Command { + #[command( + about = "Upgrade OpenCode to the latest or a specific version", + visible_alias = "update" + )] + Upgrade(UpgradeArgs), + #[command(about = "Uninstall OpenCode, keeping session data, configuration, and state")] + Uninstall(UninstallArgs), + #[command(about = "Start an Agent Client Protocol server")] + Acp(AcpArgs), + #[command(about = "Make a request to the running server")] + Api(ApiArgs), + #[command(about = "Debugging and troubleshooting tools")] + Debug(DebugArgs), + #[command(about = "manage integrations and credentials")] + Auth(AuthArgs), + #[command(about = "Manage MCP (Model Context Protocol) servers")] + Mcp(McpArgs), + #[command(about = "Manage plugins")] + Plugin(PluginArgs), + #[command(about = "List all available models")] + Models(ServerArgs), + #[command(about = "Show shareable usage statistics")] + Stats(StatsArgs), + #[command(about = "Start the minimal interactive interface")] + Mini(MiniArgs), + #[command(about = "Run OpenCode with a message")] + Run(RunArgs), + #[command(about = "Manage sessions")] + Session(SessionArgs), + #[command(about = "Manage the background server")] + Service(ServiceArgs), + #[command(about = "Reload configuration")] + Reload(ServerArgs), + #[command(about = "Print one-time links to connect a browser or app")] + Pair(PairArgs), + #[command(about = "Start the v2 API and web server")] + Serve(ServeArgs), +} + +/// A command whose only flags are `--standalone` and `--server`. +#[derive(Args, Debug, Clone, Default)] +pub struct ServerArgs { + #[command(flatten)] + pub server: ServerFlags, +} + +#[derive(Args, Debug)] +pub struct UpgradeArgs { + #[arg( + value_name = "target", + help = "Version to upgrade to (with or without a leading v)" + )] + pub target: Option, + #[arg( + short = 'm', + long, + value_name = "choice", + help = "Installation method to use" + )] + pub method: Option, +} + +#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)] +pub enum UpgradeMethod { + Curl, + Npm, + Pnpm, + Bun, + Yarn, + Vp, + Brew, + Winget, +} + +#[derive(Args, Debug)] +pub struct UninstallArgs { + #[arg(long, help = "Show what would be removed without removing")] + pub dry_run: bool, + #[arg(short = 'f', long, help = "Skip confirmation prompts")] + pub force: bool, +} + +#[derive(Args, Debug)] +pub struct AcpArgs { + #[arg(long, help = "Run auth login instead of starting the server")] + pub login: bool, +} + +#[derive(Args, Debug)] +pub struct ApiArgs { + #[arg( + value_name = "operation | method path", + required = true, + num_args = 1..=2, + help = "OpenAPI operation ID, or an HTTP method followed by a path" + )] + pub request: Vec, + #[arg(short = 'd', long, value_name = "string", help = "Request body")] + pub data: Option, + #[arg(short = 'H', long, value_name = "string", action = ArgAction::Append, help = "Request header in name:value form")] + pub header: Vec, + #[arg(long, value_name = "key=value", action = ArgAction::Append, value_parser = key_value, help = "OpenAPI path or query parameter")] + pub param: Vec<(String, String)>, + #[command(flatten)] + pub server: ServerFlags, +} + +#[derive(Args, Debug)] +pub struct DebugArgs { + #[command(subcommand)] + pub command: Option, +} + +#[derive(Subcommand, Debug)] +pub enum DebugCommand { + #[command(about = "List all agents")] + Agents(ServerArgs), + #[command(about = "List configuration sources")] + Config(ServerArgs), + #[command(about = "Write a heap snapshot of the running server and print its path")] + HeapDump(HeapDumpArgs), + #[command(about = "Show global paths (data, config, cache, state)")] + Paths(PathsArgs), +} + +#[derive(Args, Debug)] +pub struct HeapDumpArgs { + #[arg( + long, + value_name = "string", + help = "Directory to write the snapshot into instead of the server's log directory" + )] + pub directory: Option, + #[command(flatten)] + pub server: ServerOnly, +} + +#[derive(Args, Debug)] +pub struct PathsArgs { + #[arg( + value_name = "name", + help = "Print only one path: db, home, data, config, cache, state, tmp, bin, log, repos" + )] + pub name: Option, +} + +#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)] +pub enum PathName { + Db, + Home, + Data, + Config, + Cache, + State, + Tmp, + Bin, + Log, + Repos, +} + +#[derive(Args, Debug)] +pub struct AuthArgs { + #[command(subcommand)] + pub command: Option, + #[command(flatten)] + pub server: ServerFlags, +} + +#[derive(Subcommand, Debug)] +pub enum AuthCommand { + #[command(about = "list integrations and credentials")] + List(AuthListArgs), + #[command(about = "connect an integration")] + Login(AuthLoginArgs), + #[command(about = "log out of a saved account")] + Logout(AuthAccountArgs), + #[command(about = "print stored credentials, including secrets, as JSON")] + Export(AuthExportArgs), + #[command(about = "import credentials exported by auth export")] + Import(AuthImportArgs), + #[command(about = "switch the active account for an integration")] + Switch(AuthAccountArgs), +} + +#[derive(Args, Debug)] +pub struct AuthListArgs { + #[arg( + long, + value_name = "choice", + default_value = "default", + help = "Output format" + )] + pub format: OutputFormat, +} + +#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)] +pub enum OutputFormat { + Default, + Json, +} + +#[derive(Args, Debug)] +pub struct AuthLoginArgs { + #[arg( + value_name = "target", + help = "Integration ID, name, or well-known provider URL" + )] + pub target: Option, + #[arg(long, value_name = "string", help = "Authentication method ID")] + pub method: Option, + #[arg( + long, + value_name = "string", + action = ArgAction::Append, + help = "Provider form answer (key=value; repeat for multiple fields)" + )] + pub answer: Vec, +} + +/// `auth logout` and `auth switch`. +#[derive(Args, Debug)] +pub struct AuthAccountArgs { + #[arg(value_name = "target", help = "Integration ID or name")] + pub target: Option, + #[arg( + value_name = "credential", + help = "Credential ID or label (opens an account picker when omitted)" + )] + pub credential: Option, +} + +#[derive(Args, Debug)] +pub struct AuthExportArgs { + #[arg( + value_name = "target", + help = "Integration ID or name (exports every integration when omitted)" + )] + pub target: Option, +} + +#[derive(Args, Debug)] +pub struct AuthImportArgs { + #[arg( + value_name = "file", + help = "JSON file to import (reads stdin when omitted)" + )] + pub file: Option, +} + +#[derive(Args, Debug)] +pub struct McpArgs { + #[command(subcommand)] + pub command: Option, +} + +#[derive(Subcommand, Debug)] +pub enum McpCommand { + #[command(about = "List configured MCP servers and their status")] + List(ServerArgs), + #[command(about = "Add an MCP server to your configuration")] + Add(McpAddArgs), + #[command(about = "Authenticate with an OAuth-capable remote MCP server")] + Auth(McpAuthArgs), + #[command(about = "Remove stored OAuth credentials for an MCP server")] + Logout(McpLogoutArgs), +} + +#[derive(Args, Debug)] +pub struct McpAddArgs { + #[arg(value_name = "name", help = "Name of the MCP server")] + pub name: String, + #[arg( + value_name = "command", + help = "Command and arguments for a local server, passed after --" + )] + pub command: Vec, + #[arg(long, value_name = "string", help = "URL for a remote MCP server")] + pub url: Option, + #[arg(long, value_name = "key=value", action = ArgAction::Append, value_parser = key_value, help = "HTTP header for a remote server, as name=value")] + pub header: Vec<(String, String)>, + #[arg(long, value_name = "key=value", action = ArgAction::Append, value_parser = key_value, help = "Environment variable for a local server, as name=value")] + pub env: Vec<(String, String)>, + #[arg( + long, + help = "Write to the global config instead of the project config" + )] + pub global: bool, +} + +#[derive(Args, Debug)] +pub struct McpAuthArgs { + #[arg(value_name = "name", help = "Name of the MCP server")] + pub name: Option, + #[command(flatten)] + pub server: ServerFlags, +} + +#[derive(Args, Debug)] +pub struct McpLogoutArgs { + #[arg(value_name = "name", help = "Name of the MCP server")] + pub name: String, + #[command(flatten)] + pub server: ServerFlags, +} + +#[derive(Args, Debug)] +pub struct PluginArgs { + #[command(subcommand)] + pub command: Option, +} + +#[derive(Subcommand, Debug)] +pub enum PluginCommand { + #[command(about = "List plugins")] + List(PluginListArgs), + #[command(about = "Install a plugin and add it to the global configuration")] + Add(PluginAddArgs), + #[command(about = "Check package plugins for updates")] + Check(PluginCheckArgs), + #[command(about = "Update package plugins")] + Update(PluginUpdateArgs), + #[command(about = "Remove a plugin from global configuration")] + Remove(PluginRemoveArgs), +} + +#[derive(Args, Debug)] +pub struct PluginListArgs { + #[arg(long, help = "Include built-in server plugins")] + pub builtin: bool, + #[command(flatten)] + pub server: ServerFlags, +} + +#[derive(Args, Debug)] +pub struct PluginAddArgs { + #[arg(value_name = "package", help = "npm registry or Git package specifier")] + pub package: String, +} + +#[derive(Args, Debug)] +pub struct PluginCheckArgs { + #[arg(value_name = "target", help = "Configured package target")] + pub target: Option, + #[command(flatten)] + pub server: ServerFlags, +} + +#[derive(Args, Debug)] +pub struct PluginUpdateArgs { + #[arg( + value_name = "target", + help = "Configured package target; omit to update all outdated plugins" + )] + pub target: Option, + #[command(flatten)] + pub server: ServerFlags, +} + +#[derive(Args, Debug)] +pub struct PluginRemoveArgs { + #[arg(value_name = "package", help = "configured package specifier")] + pub package: String, +} + +#[derive(Args, Debug)] +pub struct StatsArgs { + #[arg(long, value_name = "integer", value_parser = clap::value_parser!(u32), help = "Show the last N days; 0 means today")] + pub days: Option, + #[arg(long, value_name = "integer", value_parser = clap::value_parser!(u16).range(1970..=9999), help = "Show a calendar year")] + pub year: Option, + #[arg(long, help = "Show lifetime statistics")] + pub all: bool, + #[arg( + long, + value_name = "string", + help = "Filter by project ID, or use \".\" for the current project" + )] + pub project: Option, + #[arg(long, help = "Show model usage")] + pub models: bool, + #[arg(long, help = "Show tool reliability")] + pub tools: bool, + #[arg(long, help = "Show cost and token details")] + pub cost: bool, + #[arg(long, help = "Show every detailed section")] + pub full: bool, + #[arg(long, value_name = "integer", default_value = "5", value_parser = clap::value_parser!(u32).range(1..), help = "Number of rows in detailed sections")] + pub limit: u32, + #[arg(long, help = "Output statistics as JSON")] + pub json: bool, + #[command(flatten)] + pub server: ServerFlags, +} + +#[derive(Args, Debug)] +pub struct MiniArgs { + #[arg(short = 'c', long = "continue", help = "Continue the last session")] + pub continue_: bool, + #[arg(short = 's', long, value_name = "string", help = SESSION)] + pub session: Option, + #[arg(long, help = "Fork the session when continuing")] + pub fork: bool, + #[arg( + long, + help = "Restore session history on resume and resize (disable with --no-replay)" + )] + pub replay: bool, + // Set by `normalize` for `--no-replay` and `--replay=false`, so `replay()` can tell false from absent. + #[arg(long = "no-replay", hide = true)] + pub no_replay: bool, + #[arg( + long, + value_name = "integer", + help = "Limit replay to the newest N messages (default: 200)" + )] + pub replay_limit: Option, + #[arg( + short = 'm', + long, + value_name = "string", + help = "Model to use in the format provider/model" + )] + pub model: Option, + #[arg(long, value_name = "string", help = "Agent to use")] + pub agent: Option, + #[arg(long, value_name = "string", help = "Prompt to use")] + pub prompt: Option, + #[arg(long, hide = true)] + pub demo: bool, + #[command(flatten)] + pub server: ServerFlags, +} + +#[allow(dead_code, reason = "read by the handlers of later steps")] +impl MiniArgs { + pub fn replay(&self) -> Option { + match (self.replay, self.no_replay) { + (true, _) => Some(true), + (_, true) => Some(false), + _ => None, + } + } +} + +#[derive(Args, Debug)] +pub struct RunArgs { + #[arg(value_name = "message", help = "Message to send")] + pub message: Vec, + #[arg(short = 'c', long = "continue", help = "Continue the last session")] + pub continue_: bool, + #[arg(short = 's', long, value_name = "string", help = SESSION)] + pub session: Option, + #[arg(long, help = "Fork the session before continuing")] + pub fork: bool, + // A value only with `=`: `run -w "fix it"` keeps "fix it" as the message (framework/flag.ts:3-4). + #[arg( + short = 'w', + long, + value_name = "name", + num_args = 0..=1, + require_equals = true, + default_missing_value = "", + help = "Start a new session in a new git worktree, optionally with this name" + )] + pub worktree: Option, + #[arg( + short = 'm', + long, + value_name = "string", + help = "Model to use in the format provider/model#variant" + )] + pub model: Option, + #[arg(long, value_name = "string", help = "Agent to use")] + pub agent: Option, + #[arg( + long, + value_name = "choice", + default_value = "default", + help = "Output format" + )] + pub format: OutputFormat, + #[arg(short = 'f', long, value_name = "string", action = ArgAction::Append, help = "File to attach to the message")] + pub file: Vec, + #[arg(long, value_name = "string", help = "Session title")] + pub title: Option, + #[arg( + long, + help = "Create the session archived so it stays out of session lists (useful for scripted or CI runs)" + )] + pub archived: bool, + #[arg(long, help = "Show thinking blocks")] + pub thinking: bool, + #[command(flatten)] + pub permissions: PermissionFlags, + #[command(flatten)] + pub server: ServerFlags, +} + +#[allow(dead_code, reason = "read by the handlers of later steps")] +impl RunArgs { + /// `None` without `-w`; `Some(None)` for `-w` without a name. + pub fn worktree(&self) -> Option> { + self.worktree + .as_deref() + .map(|name| Some(name).filter(|name| !name.is_empty())) + } +} + +#[derive(Args, Debug)] +pub struct SessionArgs { + #[command(subcommand)] + pub command: Option, + #[command(flatten)] + pub server: ServerFlags, +} + +#[derive(Subcommand, Debug)] +pub enum SessionCommand { + #[command(about = "List top-level sessions in the current project, newest first")] + List(SessionListArgs), + #[command(about = "Delete a session and its child sessions")] + Delete(SessionDeleteArgs), + #[command(about = "Export session data as JSON")] + Export(SessionExportArgs), + #[command(about = "Import session data from a JSON file or URL")] + Import(SessionImportArgs), +} + +#[derive(Args, Debug)] +pub struct SessionListArgs { + #[arg(short = 'n', long, value_name = "integer", value_parser = clap::value_parser!(u32).range(1..), help = "Limit to N most recent sessions (default: 100)")] + pub max_count: Option, + #[arg( + long, + value_name = "choice", + default_value = "table", + help = "Output format" + )] + pub format: SessionListFormat, +} + +#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)] +pub enum SessionListFormat { + Table, + Json, +} + +#[derive(Args, Debug)] +pub struct SessionDeleteArgs { + #[arg(value_name = "sessionID", help = "Session ID to delete")] + pub session_id: String, +} + +#[derive(Args, Debug)] +pub struct SessionExportArgs { + #[arg(value_name = "session", help = "Session ID to export")] + pub session: Option, + #[arg(long, help = "Redact sensitive transcript and file data")] + pub sanitize: bool, +} + +#[derive(Args, Debug)] +pub struct SessionImportArgs { + #[arg(value_name = "file", help = "JSON file or URL to import")] + pub file: String, + #[arg( + long, + value_name = "string", + help = "Directory in which to import the session" + )] + pub directory: Option, +} + +#[derive(Args, Debug)] +pub struct ServiceArgs { + #[command(subcommand)] + pub command: Option, +} + +#[derive(Subcommand, Debug)] +pub enum ServiceCommand { + #[command(about = "Start the background server")] + Start, + #[command(about = "Restart the background server")] + Restart, + #[command(about = "Show background server status")] + Status, + #[command(about = "Stop the background server")] + Stop, + #[command(about = "Get service configuration")] + Get(ServiceGetArgs), + #[command(about = "Set service configuration")] + Set(ServiceSetArgs), + #[command(about = "Unset service configuration")] + Unset(ServiceUnsetArgs), +} + +#[derive(Args, Debug)] +pub struct ServiceGetArgs { + #[arg(value_name = "key", help = "Service setting or env")] + pub key: Option, + #[arg(value_name = "name", help = "Environment variable name")] + pub name: Option, +} + +#[derive(Args, Debug)] +pub struct ServiceSetArgs { + #[arg(value_name = "key", help = "Service setting or env")] + pub key: String, + #[arg( + value_name = "value", + help = "Setting value or environment variable name" + )] + pub value: String, + #[arg(value_name = "env-value", help = "Environment variable value")] + pub env_value: Option, +} + +#[derive(Args, Debug)] +pub struct ServiceUnsetArgs { + #[arg(value_name = "key", help = "Service setting or env")] + pub key: String, + #[arg(value_name = "name", help = "Environment variable name")] + pub name: Option, +} + +#[derive(Args, Debug)] +pub struct PairArgs { + #[arg(long, value_name = "string", value_parser = pairing_url, help = "Use an external HTTP(S) server URL in pairing links")] + pub url: Option, + #[arg( + long, + help = "Pair through the OpenTunnel remote address, enabling remote access if needed (exposes the server to the internet)" + )] + pub remote: bool, + #[arg( + short = 'y', + long, + help = "Accept exposing the server to the internet when --remote enables remote access for the first time (required without an interactive terminal)" + )] + pub yes: bool, +} + +#[derive(Args, Debug)] +pub struct ServeArgs { + #[arg(long, value_name = "string")] + pub hostname: Option, + #[arg(long, value_name = "integer")] + pub port: Option, + #[arg( + long, + value_name = "string", + action = ArgAction::Append, + value_parser = clap::builder::NonEmptyStringValueParser::new(), + help = "Additional allowed CORS origin (repeat for multiple origins)" + )] + pub cors: Vec, + #[arg(long)] + pub service: bool, + #[arg(long)] + pub stdio: bool, +} + +#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)] +pub enum Shell { + Bash, + Zsh, + Fish, + Powershell, + Sh, + Pwsh, +} + +#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)] +pub enum LogLevel { + All, + Trace, + Debug, + Info, + Warn, + Warning, + Error, + Fatal, + None, +} + +fn key_value(value: &str) -> Result<(String, String), String> { + let Some((key, val)) = value.split_once('=') else { + return Err(format!( + "Invalid key=value format. Expected format: key=value, got: {value}" + )); + }; + if key.is_empty() || val.is_empty() { + return Err(format!( + "Invalid key=value format. Both key and value must be non-empty. Got: {value}" + )); + } + Ok((key.to_string(), val.to_string())) +} + +// commands.ts:551-561: an HTTP(S) URL without credentials, query, or fragment, without trailing slashes. +fn pairing_url(value: &str) -> Result { + let error = + "Expected an HTTP(S) server URL without credentials, query parameters, or a fragment"; + let url = url::Url::parse(value).map_err(|_| error.to_string())?; + let plain = matches!(url.scheme(), "http" | "https") + && url.username().is_empty() + && url.password().is_none() + && url.query().is_none() + && url.fragment().is_none(); + if !plain { + return Err(error.to_string()); + } + Ok(url.as_str().trim_end_matches('/').to_string()) +} + +/// Rewrites Effect CLI boolean forms into ones clap accepts, walking the arguments with `command` (built, so +/// global flags are visible at every level) the way Effect's parser does: only the first word at each level +/// can name a subcommand, and everything after `--` is left alone. +/// +/// - `--flag=`, `--flag ` (`true yes on 1 y`, `false no off 0 n`) set the boolean. +/// - `--no-flag` sets it to false; a value after it is an error. +/// - A boolean given twice is an error, as Effect reports "at most 1 value". +/// - Short clusters split into single flags (`-cf` is `-c -f`), as Effect's lexer does. +/// +/// A false boolean is dropped, or becomes the hidden `--no-` where the command has one. +pub fn normalize(command: &clap::Command, args: Vec) -> Result, String> { + let mut input = args.into_iter(); + let mut out: Vec = input.next().into_iter().collect(); + let mut tokens: Vec = Vec::new(); + let mut rest: Vec = Vec::new(); + for arg in input.by_ref() { + if arg == "--" { + rest.push(arg); + break; + } + match arg.to_str().and_then(cluster) { + Some(split) => tokens.extend(split.into_iter().map(OsString::from)), + None => tokens.push(arg), + } + } + rest.extend(input); + + let mut node = command; + let mut first = true; + let mut seen = HashSet::new(); + let mut tokens = tokens.into_iter().peekable(); + while let Some(token) = tokens.next() { + let Some(text) = token.to_str().filter(|text| is_flag(text)) else { + match token.to_str().and_then(|name| find_subcommand(node, name)) { + Some(sub) if first => node = sub, + _ => first = false, + } + out.push(token); + continue; + }; + let (name, value) = match text.split_once('=') { + Some((name, value)) => (name, Some(value)), + None => (text, None), + }; + let negated = name + .strip_prefix("--no-") + .and_then(|long| find_long(node, long).filter(|arg| is_bool(arg))); + if let Some(arg) = negated { + let literal = value + .map(str::to_string) + .or_else(|| take_literal(&mut tokens)); + if let Some(literal) = literal { + let long = arg.get_long().unwrap_or_default(); + return Err(format!( + "Invalid value for flag --{long}: \"{literal}\". Expected: omit the value and use {name} by itself to set --{long} to false" + )); + } + record(&mut seen, arg)?; + push_bool(&mut out, node, arg, false); + continue; + } + let Some(arg) = find_flag(node, name) else { + out.push(token); + continue; + }; + if is_bool(arg) { + let literal = value + .map(str::to_string) + .or_else(|| take_literal(&mut tokens)); + let enabled = match literal.as_deref() { + None => true, + Some(literal) => parse_bool(literal).ok_or_else(|| { + format!( + "Invalid value for flag --{}: \"{literal}\". Expected: boolean", + arg.get_long().unwrap_or_default() + ) + })?, + }; + record(&mut seen, arg)?; + push_bool(&mut out, node, arg, enabled); + continue; + } + // A flag that takes the next word: keep that word out of subcommand detection. + let takes_next = value.is_none() + && !arg.is_require_equals_set() + && arg + .get_num_args() + .is_some_and(|range| range.min_values() > 0); + out.push(token); + if takes_next + && let Some(next) = + tokens.next_if(|next| next.to_str().is_none_or(|next| !is_flag(next))) + { + out.push(next); + } + } + out.extend(rest); + Ok(out) +} + +// Effect's lexer: a word starting with `-` is a flag unless it is `-` alone or a negative number. +fn is_flag(text: &str) -> bool { + text.len() > 1 + && text.starts_with('-') + && text != "--" + && !text.starts_with("--=") + && !is_negative_number(text) +} + +// lexer.ts:49, `^-(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$`. +fn is_negative_number(text: &str) -> bool { + let digits = |part: &str| part.chars().all(|char| char.is_ascii_digit()); + let number = &text[1..]; + let (mantissa, exponent) = match number.split_once(['e', 'E']) { + Some((mantissa, exponent)) => (mantissa, Some(exponent)), + None => (number, None), + }; + let mantissa = match mantissa.split_once('.') { + Some((int, frac)) => digits(int) && digits(frac) && !(int.is_empty() && frac.is_empty()), + None => !mantissa.is_empty() && digits(mantissa), + }; + let exponent = exponent.is_none_or(|exponent| { + let exponent = exponent.strip_prefix(['+', '-']).unwrap_or(exponent); + !exponent.is_empty() && digits(exponent) + }); + mantissa && exponent +} + +/// `-abc` is `-a -b -c`, and `-ab=v` is `-a -b=v`. +fn cluster(text: &str) -> Option> { + if !is_flag(text) || text.starts_with("--") { + return None; + } + let (flags, value) = match text[1..].split_once('=') { + Some((flags, value)) => (flags, Some(value)), + None => (&text[1..], None), + }; + if flags.chars().count() < 2 { + return None; + } + let mut split: Vec = flags.chars().map(|char| format!("-{char}")).collect(); + if let (Some(last), Some(value)) = (split.last_mut(), value) { + last.push('='); + last.push_str(value); + } + Some(split) +} + +fn find_subcommand<'a>(node: &'a clap::Command, name: &str) -> Option<&'a clap::Command> { + node.get_subcommands() + .find(|sub| sub.get_name() == name || sub.get_all_aliases().any(|alias| alias == name)) +} + +fn find_long<'a>(node: &'a clap::Command, long: &str) -> Option<&'a clap::Arg> { + node.get_arguments() + .find(|arg| arg.get_long() == Some(long)) +} + +fn find_flag<'a>(node: &'a clap::Command, name: &str) -> Option<&'a clap::Arg> { + if let Some(long) = name.strip_prefix("--") { + return find_long(node, long); + } + let mut chars = name[1..].chars(); + let short = chars.next().filter(|_| chars.next().is_none())?; + node.get_arguments() + .find(|arg| arg.get_short() == Some(short)) +} + +fn is_bool(arg: &clap::Arg) -> bool { + matches!(arg.get_action(), ArgAction::SetTrue) +} + +fn parse_bool(text: &str) -> Option { + match text { + "true" | "yes" | "on" | "1" | "y" => Some(true), + "false" | "no" | "off" | "0" | "n" => Some(false), + _ => None, + } +} + +fn take_literal( + tokens: &mut std::iter::Peekable>, +) -> Option { + tokens + .next_if(|next| next.to_str().and_then(parse_bool).is_some()) + .and_then(|next| next.into_string().ok()) +} + +fn record(seen: &mut HashSet, arg: &clap::Arg) -> Result<(), String> { + let long = arg.get_long().unwrap_or_default(); + if seen.insert(long.to_string()) { + return Ok(()); + } + Err(format!( + "Invalid value for flag --{long}: \"2 occurrences\". Expected: at most 1 value" + )) +} + +fn push_bool(out: &mut Vec, node: &clap::Command, arg: &clap::Arg, enabled: bool) { + let long = arg.get_long().unwrap_or_default(); + if enabled { + out.push(format!("--{long}").into()); + return; + } + if find_long(node, &format!("no-{long}")).is_some() { + out.push(format!("--no-{long}").into()); + } +} + +/// Checks Effect CLI rules clap does not know, after clap parsed `matches` of `command` (built). Returns the +/// `--standalone` and `--server` that apply to the selected command: the root's own, or those of the +/// command that declares them, which may be given before the subcommand (`opencode --server URL session list`). +pub fn validate(command: &clap::Command, matches: &ArgMatches) -> Result { + let mut path = vec![command]; + let mut leaf = matches; + while let Some((name, sub)) = leaf.subcommand() { + path.push( + path.last() + .and_then(|node| node.find_subcommand(name)) + .expect("clap matched it"), + ); + leaf = sub; + } + let names: Vec<&str> = path.iter().map(|node| node.get_name()).collect(); + if path.len() == 1 { + return Ok(ServerFlags { + standalone: matches.get_flag("root_standalone"), + server: matches.get_one::("root_server").cloned(), + }); + } + let mut flags = ServerFlags { + standalone: leaf + .try_get_one::("standalone") + .ok() + .flatten() + .copied() + .unwrap_or(false), + server: leaf.try_get_one::("server").ok().flatten().cloned(), + }; + let root_flags = command + .get_arguments() + .filter(|arg| !arg.is_global_set() && !arg.is_positional()); + for arg in root_flags { + let id = arg.get_id().as_str(); + if matches.value_source(id) != Some(ValueSource::CommandLine) { + continue; + } + let long = arg.get_long().unwrap_or(id); + // Effect CLI does not pass a command's own flags to its subcommands; only declared globals apply. + if !matches!(long, "standalone" | "server") || leaf.try_contains_id(long).is_err() { + return Err(format!( + "Unrecognized flag: --{long} in command {}", + names.join(" ") + )); + } + if leaf.value_source(long) == Some(ValueSource::CommandLine) { + return Err(format!( + "Invalid value for flag --{long}: \"2 occurrences\". Expected: at most 1 value" + )); + } + match long { + "standalone" => flags.standalone = true, + _ => flags.server = matches.get_one::(id).cloned(), + } + } + // Flag.atMost(100) in commands.ts. + let limited = [("api", "header"), ("login", "answer"), ("run", "file")]; + if let Some((_, id)) = limited.iter().find(|(name, _)| names.last() == Some(name)) { + let count = leaf + .get_raw_occurrences(id) + .map_or(0, |values| values.count()); + if count > 100 { + return Err(format!( + "Invalid value for flag --{id}: \"{count} occurrences\". Expected: at most 100 values" + )); + } + } + Ok(flags) +} diff --git a/packages/cli-rs/crates/cli/src/askpass.rs b/packages/cli-rs/crates/cli/src/askpass.rs new file mode 100644 index 00000000000..bbc2bf4ce1b --- /dev/null +++ b/packages/cli-rs/crates/cli/src/askpass.rs @@ -0,0 +1 @@ +//! SSH askpass helper mode. Step C.14. diff --git a/packages/cli-rs/crates/cli/src/commands/acp.rs b/packages/cli-rs/crates/cli/src/commands/acp.rs new file mode 100644 index 00000000000..8dfb0b6d9f3 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/acp.rs @@ -0,0 +1,8 @@ +//! `acp`: the Agent Client Protocol server. + +use super::{Context, not_built}; +use crate::args::AcpArgs; + +pub fn run(_context: &Context, _args: &AcpArgs) -> anyhow::Result<()> { + not_built("acp", "C.11") +} diff --git a/packages/cli-rs/crates/cli/src/commands/api.rs b/packages/cli-rs/crates/cli/src/commands/api.rs new file mode 100644 index 00000000000..2aeadafe3d4 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/api.rs @@ -0,0 +1,8 @@ +//! `api`: a request to the running server. + +use super::{Context, not_built}; +use crate::args::ApiArgs; + +pub fn run(_context: &Context, _args: &ApiArgs) -> anyhow::Result<()> { + not_built("api", "C.4") +} diff --git a/packages/cli-rs/crates/cli/src/commands/auth.rs b/packages/cli-rs/crates/cli/src/commands/auth.rs new file mode 100644 index 00000000000..1e602a9789d --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/auth.rs @@ -0,0 +1,16 @@ +//! `auth`: integrations and credentials. + +use super::{Context, not_built}; +use crate::args::{AuthArgs, AuthCommand}; + +pub fn run(_context: &Context, args: &AuthArgs) -> anyhow::Result<()> { + match &args.command { + None => crate::help::print(&["auth"]), + Some(AuthCommand::List(_)) => not_built("auth list", "C.5"), + Some(AuthCommand::Login(_)) => not_built("auth login", "C.5"), + Some(AuthCommand::Logout(_)) => not_built("auth logout", "C.5"), + Some(AuthCommand::Export(_)) => not_built("auth export", "C.5"), + Some(AuthCommand::Import(_)) => not_built("auth import", "C.5"), + Some(AuthCommand::Switch(_)) => not_built("auth switch", "C.5"), + } +} diff --git a/packages/cli-rs/crates/cli/src/commands/debug.rs b/packages/cli-rs/crates/cli/src/commands/debug.rs new file mode 100644 index 00000000000..0359865e1a4 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/debug.rs @@ -0,0 +1,14 @@ +//! `debug`: debugging and troubleshooting tools. + +use super::{Context, not_built}; +use crate::args::{DebugArgs, DebugCommand}; + +pub fn run(_context: &Context, args: &DebugArgs) -> anyhow::Result<()> { + match &args.command { + None => crate::help::print(&["debug"]), + Some(DebugCommand::Agents(_)) => not_built("debug agents", "C.1"), + Some(DebugCommand::Config(_)) => not_built("debug config", "C.1"), + Some(DebugCommand::HeapDump(_)) => not_built("debug heap-dump", "C.1"), + Some(DebugCommand::Paths(_)) => not_built("debug paths", "C.1"), + } +} diff --git a/packages/cli-rs/crates/cli/src/commands/default.rs b/packages/cli-rs/crates/cli/src/commands/default.rs new file mode 100644 index 00000000000..564bee77464 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/default.rs @@ -0,0 +1,8 @@ +//! The root command, which opens the TUI. T.1 takes this file over, then C.13. + +use super::Context; +use crate::args::RootArgs; + +pub fn run(_context: &Context, _args: &RootArgs) -> anyhow::Result<()> { + anyhow::bail!("the TUI is not built yet (plan step T.1)") +} diff --git a/packages/cli-rs/crates/cli/src/commands/mcp.rs b/packages/cli-rs/crates/cli/src/commands/mcp.rs new file mode 100644 index 00000000000..eaa9c3479fd --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/mcp.rs @@ -0,0 +1,14 @@ +//! `mcp`: MCP servers. + +use super::{Context, not_built}; +use crate::args::{McpArgs, McpCommand}; + +pub fn run(_context: &Context, args: &McpArgs) -> anyhow::Result<()> { + match &args.command { + None => crate::help::print(&["mcp"]), + Some(McpCommand::List(_)) => not_built("mcp list", "C.6"), + Some(McpCommand::Add(_)) => not_built("mcp add", "C.6"), + Some(McpCommand::Auth(_)) => not_built("mcp auth", "C.6"), + Some(McpCommand::Logout(_)) => not_built("mcp logout", "C.6"), + } +} diff --git a/packages/cli-rs/crates/cli/src/commands/mini.rs b/packages/cli-rs/crates/cli/src/commands/mini.rs new file mode 100644 index 00000000000..36013067d68 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/mini.rs @@ -0,0 +1,8 @@ +//! `mini`: the minimal interactive interface. + +use super::{Context, not_built}; +use crate::args::MiniArgs; + +pub fn run(_context: &Context, _args: &MiniArgs) -> anyhow::Result<()> { + not_built("mini", "M.1") +} diff --git a/packages/cli-rs/crates/cli/src/commands/mod.rs b/packages/cli-rs/crates/cli/src/commands/mod.rs new file mode 100644 index 00000000000..35336b3e84e --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/mod.rs @@ -0,0 +1,64 @@ +//! One module per top-level command. Each step fills its own module (plan 8.4); a stub reports that its command +//! is not built yet. + +pub mod acp; +pub mod api; +pub mod auth; +pub mod debug; +pub mod default; +pub mod mcp; +pub mod mini; +pub mod models; +pub mod pair; +pub mod plugin; +pub mod reload; +pub mod run; +pub mod serve; +pub mod service; +pub mod session; +pub mod stats; +pub mod uninstall; +pub mod upgrade; + +use crate::args::{Cli, Command, GlobalArgs, ServerFlags}; + +/// What every handler gets besides its own arguments. +#[allow(dead_code, reason = "read by the handlers of later steps")] +pub struct Context { + pub global: GlobalArgs, + /// `--standalone` and `--server` for the selected command, wherever they were given (`args::validate`). + pub server: ServerFlags, +} + +pub fn run(context: &Context, cli: &Cli) -> anyhow::Result<()> { + let Some(command) = &cli.command else { + return default::run(context, &cli.root); + }; + match command { + Command::Upgrade(args) => upgrade::run(context, args), + Command::Uninstall(args) => uninstall::run(context, args), + Command::Acp(args) => acp::run(context, args), + Command::Api(args) => api::run(context, args), + Command::Debug(args) => debug::run(context, args), + Command::Auth(args) => auth::run(context, args), + Command::Mcp(args) => mcp::run(context, args), + Command::Plugin(args) => plugin::run(context, args), + Command::Models(_) => models::run(context), + Command::Stats(args) => stats::run(context, args), + Command::Mini(args) => mini::run(context, args), + Command::Run(args) => run::run(context, args), + Command::Session(args) => session::run(context, args), + Command::Service(args) => service::run(context, args), + Command::Reload(_) => reload::run(context), + Command::Pair(args) => pair::run(context, args), + Command::Serve(args) => serve::run(context, args), + } +} + +/// The result of a command whose step has not landed yet. +pub fn not_built(command: &str, step: &str) -> anyhow::Result<()> { + anyhow::bail!( + "`{} {command}` is not built yet (plan step {step})", + crate::help::name() + ) +} diff --git a/packages/cli-rs/crates/cli/src/commands/models.rs b/packages/cli-rs/crates/cli/src/commands/models.rs new file mode 100644 index 00000000000..c3c29f43544 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/models.rs @@ -0,0 +1,7 @@ +//! `models`: list the available models. + +use super::{Context, not_built}; + +pub fn run(_context: &Context) -> anyhow::Result<()> { + not_built("models", "C.1") +} diff --git a/packages/cli-rs/crates/cli/src/commands/pair.rs b/packages/cli-rs/crates/cli/src/commands/pair.rs new file mode 100644 index 00000000000..f0c47e1c00d --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/pair.rs @@ -0,0 +1,8 @@ +//! `pair`: one-time links for a browser or app. + +use super::{Context, not_built}; +use crate::args::PairArgs; + +pub fn run(_context: &Context, _args: &PairArgs) -> anyhow::Result<()> { + not_built("pair", "C.9") +} diff --git a/packages/cli-rs/crates/cli/src/commands/plugin.rs b/packages/cli-rs/crates/cli/src/commands/plugin.rs new file mode 100644 index 00000000000..bb019f5de39 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/plugin.rs @@ -0,0 +1,15 @@ +//! `plugin`, delegated to the TypeScript CLI. + +use super::{Context, not_built}; +use crate::args::{PluginArgs, PluginCommand}; + +pub fn run(_context: &Context, args: &PluginArgs) -> anyhow::Result<()> { + match &args.command { + None => crate::help::print(&["plugin"]), + Some(PluginCommand::List(_)) => not_built("plugin list", "D.1"), + Some(PluginCommand::Add(_)) => not_built("plugin add", "D.1"), + Some(PluginCommand::Check(_)) => not_built("plugin check", "D.1"), + Some(PluginCommand::Update(_)) => not_built("plugin update", "D.1"), + Some(PluginCommand::Remove(_)) => not_built("plugin remove", "D.1"), + } +} diff --git a/packages/cli-rs/crates/cli/src/commands/reload.rs b/packages/cli-rs/crates/cli/src/commands/reload.rs new file mode 100644 index 00000000000..2ab611e2a5b --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/reload.rs @@ -0,0 +1,7 @@ +//! `reload`: reload the server configuration. + +use super::{Context, not_built}; + +pub fn run(_context: &Context) -> anyhow::Result<()> { + not_built("reload", "C.1") +} diff --git a/packages/cli-rs/crates/cli/src/commands/run.rs b/packages/cli-rs/crates/cli/src/commands/run.rs new file mode 100644 index 00000000000..9e20903ff34 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/run.rs @@ -0,0 +1,8 @@ +//! `run`: send a message and print the reply. + +use super::{Context, not_built}; +use crate::args::RunArgs; + +pub fn run(_context: &Context, _args: &RunArgs) -> anyhow::Result<()> { + not_built("run", "C.10") +} diff --git a/packages/cli-rs/crates/cli/src/commands/serve.rs b/packages/cli-rs/crates/cli/src/commands/serve.rs new file mode 100644 index 00000000000..ee6ffabc7f1 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/serve.rs @@ -0,0 +1,8 @@ +//! `serve`, delegated to the TypeScript CLI. + +use super::{Context, not_built}; +use crate::args::ServeArgs; + +pub fn run(_context: &Context, _args: &ServeArgs) -> anyhow::Result<()> { + not_built("serve", "D.1") +} diff --git a/packages/cli-rs/crates/cli/src/commands/service.rs b/packages/cli-rs/crates/cli/src/commands/service.rs new file mode 100644 index 00000000000..99ed7b9bdd9 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/service.rs @@ -0,0 +1,17 @@ +//! `service`: the background server. + +use super::{Context, not_built}; +use crate::args::{ServiceArgs, ServiceCommand}; + +pub fn run(_context: &Context, args: &ServiceArgs) -> anyhow::Result<()> { + match &args.command { + None => crate::help::print(&["service"]), + Some(ServiceCommand::Start) => not_built("service start", "C.8"), + Some(ServiceCommand::Restart) => not_built("service restart", "C.8"), + Some(ServiceCommand::Status) => not_built("service status", "C.8"), + Some(ServiceCommand::Stop) => not_built("service stop", "C.8"), + Some(ServiceCommand::Get(_)) => not_built("service get", "C.8"), + Some(ServiceCommand::Set(_)) => not_built("service set", "C.8"), + Some(ServiceCommand::Unset(_)) => not_built("service unset", "C.8"), + } +} diff --git a/packages/cli-rs/crates/cli/src/commands/session.rs b/packages/cli-rs/crates/cli/src/commands/session.rs new file mode 100644 index 00000000000..43e6025f830 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/session.rs @@ -0,0 +1,14 @@ +//! `session`: list, delete, export, and import sessions. + +use super::{Context, not_built}; +use crate::args::{SessionArgs, SessionCommand}; + +pub fn run(_context: &Context, args: &SessionArgs) -> anyhow::Result<()> { + match &args.command { + None => crate::help::print(&["session"]), + Some(SessionCommand::List(_)) => not_built("session list", "C.2"), + Some(SessionCommand::Delete(_)) => not_built("session delete", "C.2"), + Some(SessionCommand::Export(_)) => not_built("session export", "C.2"), + Some(SessionCommand::Import(_)) => not_built("session import", "C.2"), + } +} diff --git a/packages/cli-rs/crates/cli/src/commands/stats.rs b/packages/cli-rs/crates/cli/src/commands/stats.rs new file mode 100644 index 00000000000..1d222cd2079 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/stats.rs @@ -0,0 +1,8 @@ +//! `stats`: usage statistics. + +use super::{Context, not_built}; +use crate::args::StatsArgs; + +pub fn run(_context: &Context, _args: &StatsArgs) -> anyhow::Result<()> { + not_built("stats", "C.3") +} diff --git a/packages/cli-rs/crates/cli/src/commands/uninstall.rs b/packages/cli-rs/crates/cli/src/commands/uninstall.rs new file mode 100644 index 00000000000..731f1c35f78 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/uninstall.rs @@ -0,0 +1,8 @@ +//! `uninstall`, delegated to the TypeScript CLI. + +use super::{Context, not_built}; +use crate::args::UninstallArgs; + +pub fn run(_context: &Context, _args: &UninstallArgs) -> anyhow::Result<()> { + not_built("uninstall", "D.1") +} diff --git a/packages/cli-rs/crates/cli/src/commands/upgrade.rs b/packages/cli-rs/crates/cli/src/commands/upgrade.rs new file mode 100644 index 00000000000..e93fcf00e24 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/commands/upgrade.rs @@ -0,0 +1,8 @@ +//! `upgrade` (alias `update`), delegated to the TypeScript CLI. + +use super::{Context, not_built}; +use crate::args::UpgradeArgs; + +pub fn run(_context: &Context, _args: &UpgradeArgs) -> anyhow::Result<()> { + not_built("upgrade", "D.1") +} diff --git a/packages/cli-rs/crates/cli/src/env.rs b/packages/cli-rs/crates/cli/src/env.rs new file mode 100644 index 00000000000..d007efca02c --- /dev/null +++ b/packages/cli-rs/crates/cli/src/env.rs @@ -0,0 +1 @@ +//! Process environment: NO_PROXY and OPENCODE_CLIENT. Step C.14. diff --git a/packages/cli-rs/crates/cli/src/help.rs b/packages/cli-rs/crates/cli/src/help.rs new file mode 100644 index 00000000000..2fc3aa3549d --- /dev/null +++ b/packages/cli-rs/crates/cli/src/help.rs @@ -0,0 +1,92 @@ +//! The clap command built from `args::Cli`, and the output of the built-in flags: help, version, completions. + +use std::io::IsTerminal; + +use clap::CommandFactory; + +use crate::args::{Cli, Shell}; +use crate::output; + +// Like the TypeScript CLI, a build without OPENCODE_VERSION reports "local". +pub const VERSION: &str = match option_env!("OPENCODE_VERSION") { + Some(version) => version, + None => "local", +}; + +/// The program name in help, version, and completions (plan 6.1). +pub fn name() -> String { + std::env::var("OPENCODE_CLI_NAME") + .ok() + .filter(|name| !name.is_empty()) + .unwrap_or_else(|| "opencode-rs".into()) +} + +/// The unbuilt tree: each command holds only the arguments it declares. +pub fn tree() -> clap::Command { + let name = name(); + configure(Cli::command()).name(name.clone()).bin_name(name) +} + +/// The tree with global flags propagated to every command, as parsing sees it. +pub fn command() -> clap::Command { + let mut command = tree(); + command.build(); + headings(command) +} + +// Like Effect CLI's help, a command's own flags come first and the global flags after them, each under a +// heading. Propagated globals keep the root's display order, which would mix them into the command's own. +fn headings(command: clap::Command) -> clap::Command { + command + .mut_args(|arg| match (arg.is_global_set(), arg.is_positional()) { + (true, _) => { + let order = arg.get_display_order(); + arg.help_heading("Global flags").display_order(1000 + order) + } + (false, true) => arg, + (false, false) => arg.help_heading("Flags"), + }) + .mut_subcommands(headings) +} + +// Effect CLI has no `help` subcommand, describes `--help` itself (args::GlobalArgs), and reads `-1` as a value. +fn configure(command: clap::Command) -> clap::Command { + command + .disable_help_flag(true) + .disable_version_flag(true) + .disable_help_subcommand(true) + .allow_negative_numbers(true) + .mut_subcommands(configure) +} + +/// Prints the help of the command at `path` (names below the root) to stdout. +pub fn print(path: &[&str]) -> anyhow::Result<()> { + let mut command = command(); + let node = path.iter().fold(&mut command, |node, name| { + node.find_subcommand_mut(name) + .expect("help path names a command") + }); + let help = node.render_help(); + match std::io::stdout().is_terminal() { + true => output::print(&help.ansi().to_string()), + false => output::print(&help.to_string()), + } +} + +pub fn version() -> anyhow::Result<()> { + output::print(&format!("{} v{VERSION}\n", name())) +} + +/// `sh` means bash and `pwsh` PowerShell, as in Effect CLI (GlobalFlag.ts:226-227). +pub fn completions(shell: Shell) -> anyhow::Result<()> { + let shell = match shell { + Shell::Bash | Shell::Sh => clap_complete::Shell::Bash, + Shell::Zsh => clap_complete::Shell::Zsh, + Shell::Fish => clap_complete::Shell::Fish, + Shell::Powershell | Shell::Pwsh => clap_complete::Shell::PowerShell, + }; + let mut command = command(); + let mut script = Vec::new(); + clap_complete::generate(shell, &mut command, name(), &mut script); + output::print(&String::from_utf8_lossy(&script)) +} diff --git a/packages/cli-rs/crates/cli/src/main.rs b/packages/cli-rs/crates/cli/src/main.rs index ddf7893fea6..8f8e40f707c 100644 --- a/packages/cli-rs/crates/cli/src/main.rs +++ b/packages/cli-rs/crates/cli/src/main.rs @@ -1,17 +1,82 @@ -//! The opencode-rs binary. C.0 replaces this with the command tree. +//! The opencode-rs binary. -// Like the TypeScript CLI, a build without OPENCODE_VERSION reports "local". -const VERSION: &str = match option_env!("OPENCODE_VERSION") { - Some(version) => version, - None => "local", -}; +mod args; +mod askpass; +mod commands; +mod env; +mod help; +mod output; +mod prompt; +mod signals; +mod telemetry; +mod update; +mod wizard; -fn main() { - match std::env::args().nth(1).as_deref() { - Some("--version") => println!("{VERSION}"), - _ => { - eprintln!("usage: opencode-rs --version"); - std::process::exit(1); +#[cfg(test)] +mod tests; + +use std::process::ExitCode; + +use clap::FromArgMatches; + +fn main() -> ExitCode { + let command = help::command(); + let argv = match args::normalize(&command, std::env::args_os().collect()) { + Ok(argv) => argv, + Err(message) => return usage_error(&message), + }; + let matches = match command.clone().try_get_matches_from(argv) { + Ok(matches) => matches, + Err(error) => { + // Effect CLI exits 1 on a usage error; clap would exit 2. Help output (`--help`) exits 0. + let _ = error.print(); + return ExitCode::from(u8::from(error.use_stderr())); } + }; + let cli = match args::Cli::from_arg_matches(&matches) { + Ok(cli) => cli, + Err(error) => return usage_error(&error.to_string()), + }; + let server = match args::validate(&command, &matches) { + Ok(server) => server, + Err(message) => return usage_error(&message), + }; + let result = match &cli.global { + // Effect CLI runs the first action flag given, in this order, instead of the command. + global if global.version => help::version(), + global if global.wizard => wizard::run(), + args::GlobalArgs { + completions: Some(shell), + .. + } => help::completions(*shell), + global => { + if global.print_logs { + set_print_logs(); + } + commands::run( + &commands::Context { + global: global.clone(), + server, + }, + &cli, + ) + } + }; + match result { + Ok(()) => ExitCode::SUCCESS, + Err(error) => ExitCode::from(output::fail(error)), } } + +fn usage_error(message: &str) -> ExitCode { + eprintln!("error: {message}\n\nFor more information, try '--help'."); + ExitCode::from(1) +} + +// The TypeScript CLI sets OPENCODE_PRINT_LOGS for its logger and for the servers it starts +// (framework/runtime.ts:98). +#[allow(unsafe_code)] +fn set_print_logs() { + // SAFETY: no other thread runs yet; handlers start their runtimes after this. + unsafe { std::env::set_var("OPENCODE_PRINT_LOGS", "1") }; +} diff --git a/packages/cli-rs/crates/cli/src/output.rs b/packages/cli-rs/crates/cli/src/output.rs new file mode 100644 index 00000000000..583625162a8 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/output.rs @@ -0,0 +1,38 @@ +//! Writing to stdout, and how errors end the process. + +use std::io::{ErrorKind, Write}; + +/// Writes `text` to stdout. A closed pipe (`opencode-rs ... | head`) is not an error, as in +/// `packages/cli/src/node/index.ts:4-7`; `print!` would panic instead. +pub fn print(text: &str) -> anyhow::Result<()> { + let mut stdout = std::io::stdout().lock(); + match stdout + .write_all(text.as_bytes()) + .and_then(|()| stdout.flush()) + { + Err(error) if error.kind() != ErrorKind::BrokenPipe => Err(error.into()), + _ => Ok(()), + } +} + +/// An error that ends the process with `code` after the handler has reported what happened itself. +#[derive(Debug)] +pub struct Exit(pub u8); + +impl std::fmt::Display for Exit { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "exit {}", self.0) + } +} + +impl std::error::Error for Exit {} + +/// The exit code for a failed handler: `Exit` keeps its code and prints nothing; any other error prints to +/// stderr and exits 1. +pub fn fail(error: anyhow::Error) -> u8 { + if let Some(exit) = error.downcast_ref::() { + return exit.0; + } + eprintln!("Error: {error:#}"); + 1 +} diff --git a/packages/cli-rs/crates/cli/src/prompt/mod.rs b/packages/cli-rs/crates/cli/src/prompt/mod.rs new file mode 100644 index 00000000000..06bd35df4f9 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/prompt/mod.rs @@ -0,0 +1 @@ +//! Interactive prompts like @clack/prompts. Step C.p. diff --git a/packages/cli-rs/crates/cli/src/signals.rs b/packages/cli-rs/crates/cli/src/signals.rs new file mode 100644 index 00000000000..eb32d41cdfa --- /dev/null +++ b/packages/cli-rs/crates/cli/src/signals.rs @@ -0,0 +1 @@ +//! Shutdown deadline and SIGHUP. Step C.14. diff --git a/packages/cli-rs/crates/cli/src/telemetry.rs b/packages/cli-rs/crates/cli/src/telemetry.rs new file mode 100644 index 00000000000..398f2098c87 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/telemetry.rs @@ -0,0 +1 @@ +//! OpenTelemetry export and log files. Step C.14. diff --git a/packages/cli-rs/crates/cli/src/tests/mod.rs b/packages/cli-rs/crates/cli/src/tests/mod.rs new file mode 100644 index 00000000000..27c8508ede4 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/tests/mod.rs @@ -0,0 +1,2 @@ +mod parse; +mod tree; diff --git a/packages/cli-rs/crates/cli/src/tests/parse.rs b/packages/cli-rs/crates/cli/src/tests/parse.rs new file mode 100644 index 00000000000..ce2a4ea3bb5 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/tests/parse.rs @@ -0,0 +1,356 @@ +//! The Effect CLI parsing behaviors scripts can see (docs/C.0.md), one test each. + +use clap::FromArgMatches; + +use crate::args::{self, Cli, Command, McpCommand, ServerFlags, SessionCommand}; +use crate::help; + +fn parse(line: &[&str]) -> Result<(Cli, ServerFlags), String> { + let command = help::command(); + let argv = std::iter::once("opencode-rs") + .chain(line.iter().copied()) + .map(Into::into) + .collect(); + let argv = args::normalize(&command, argv)?; + let matches = command + .clone() + .try_get_matches_from(argv) + .map_err(|error| error.to_string())?; + let cli = Cli::from_arg_matches(&matches).map_err(|error| error.to_string())?; + let server = args::validate(&command, &matches)?; + Ok((cli, server)) +} + +fn error(line: &[&str]) -> String { + match parse(line) { + Ok(_) => panic!("{line:?} parsed"), + Err(error) => error, + } +} + +macro_rules! command { + ($line:expr, $pattern:pat => $value:expr) => { + match parse($line).unwrap().0.command { + Some($pattern) => $value, + other => panic!("{:?} parsed as {other:?}", $line), + } + }; +} + +#[test] +fn negation_sets_a_boolean_to_false() { + assert_eq!( + command!(&["mini", "--no-replay"], Command::Mini(args) => args.replay()), + Some(false) + ); + assert_eq!( + command!(&["mini", "--replay"], Command::Mini(args) => args.replay()), + Some(true) + ); + assert_eq!( + command!(&["mini"], Command::Mini(args) => args.replay()), + None + ); + assert!(!command!(&["run", "--no-thinking", "hi"], Command::Run(args) => args.thinking)); + assert!(!parse(&["--no-print-logs"]).unwrap().0.global.print_logs); + assert!( + error(&["mini", "--no-replay=true"]) + .contains("omit the value and use --no-replay by itself") + ); + assert!(error(&["mini", "--no-replay", "true"]).contains("omit the value")); +} + +#[test] +fn boolean_takes_a_literal() { + let run = + |line: &[&str]| command!(line, Command::Run(args) => (args.permissions.auto, args.message)); + assert_eq!( + run(&["run", "--auto", "false", "hi"]), + (false, vec!["hi".to_string()]) + ); + assert_eq!(run(&["run", "--auto", "yes"]), (true, vec![])); + assert_eq!(run(&["run", "--auto=0"]), (false, vec![])); + assert_eq!( + run(&["run", "--auto", "hello"]), + (true, vec!["hello".to_string()]) + ); + assert_eq!( + command!(&["mini", "--replay=off"], Command::Mini(args) => args.replay()), + Some(false) + ); + assert!(!command!(&["uninstall", "-f", "n"], Command::Uninstall(args) => args.force)); + assert!(error(&["run", "--auto=maybe"]).contains("Expected: boolean")); +} + +#[test] +fn a_flag_given_twice_is_an_error() { + assert!(error(&["uninstall", "--dry-run", "--dry-run"]).contains("2 occurrences")); + assert!(error(&["mini", "--replay", "--no-replay"]).contains("2 occurrences")); + assert!(error(&["run", "-c", "--continue"]).contains("2 occurrences")); + assert!(error(&["run", "-s", "a", "-s", "b"]).contains("cannot be used multiple times")); +} + +#[test] +fn repeatable_flags_collect_in_order_up_to_their_bound() { + let files = + command!(&["run", "-f", "a", "--file", "b", "-f=c", "hi"], Command::Run(args) => args.file); + assert_eq!(files, ["a", "b", "c"]); + let headers = + command!(&["api", "op", "-H", "a:1", "-H", "b:2"], Command::Api(args) => args.header); + assert_eq!(headers, ["a:1", "b:2"]); + let mut line = vec!["api", "op"]; + line.extend(std::iter::repeat_n(["-H", "x:1"], 101).flatten()); + assert!(error(&line).contains("at most 100 values")); + let cors = + command!(&["serve", "--cors", "a", "--cors", "b"], Command::Serve(args) => args.cors); + assert_eq!(cors, ["a", "b"]); +} + +#[test] +fn key_value_flags_need_a_key_and_a_value() { + let params = command!(&["api", "op", "--param", "a=1", "--param", "b==2"], Command::Api(args) => args.param); + assert_eq!( + params, + [("a".into(), "1".into()), ("b".into(), "=2".into())] + ); + let env = command!(&["mcp", "add", "x", "--env", "K=V"], Command::Mcp(args) => match args.command { + Some(McpCommand::Add(add)) => add.env, + other => panic!("{other:?}"), + }); + assert_eq!(env, [("K".into(), "V".into())]); + assert!(error(&["api", "op", "--param", "novalue"]).contains("Expected format: key=value")); + assert!(error(&["api", "op", "--param", "=1"]).contains("must be non-empty")); + assert!(error(&["mcp", "add", "x", "--header", "k="]).contains("must be non-empty")); +} + +#[test] +fn worktree_takes_a_value_only_with_equals() { + let run = |line: &[&str]| command!(line, Command::Run(args) => (args.worktree().map(|name| name.map(String::from)), args.message)); + assert_eq!( + run(&["run", "-w", "fix", "it"]), + (Some(None), vec!["fix".into(), "it".into()]) + ); + assert_eq!( + run(&["run", "--worktree", "fix"]), + (Some(None), vec!["fix".into()]) + ); + assert_eq!( + run(&["run", "-w=feature", "go"]), + (Some(Some("feature".into())), vec!["go".into()]) + ); + assert_eq!( + run(&["run", "--worktree=feature"]), + (Some(Some("feature".into())), vec![]) + ); + assert_eq!(run(&["run", "--worktree="]), (Some(None), vec![])); + assert_eq!(run(&["run", "go"]), (None, vec!["go".into()])); +} + +#[test] +fn words_after_double_dash_are_arguments() { + let run = command!(&["run", "a", "--", "--model", "x", "-c"], Command::Run(args) => args); + assert_eq!(run.message, ["a", "--model", "x", "-c"]); + assert!(run.model.is_none() && !run.continue_); + let add = command!(&["mcp", "add", "fs", "--", "npx", "-y", "pkg"], Command::Mcp(args) => match args.command { + Some(McpCommand::Add(add)) => add, + other => panic!("{other:?}"), + }); + assert_eq!( + (add.name.as_str(), add.command), + ("fs", vec!["npx".into(), "-y".into(), "pkg".into()]) + ); + assert_eq!( + parse(&["--", "run"]).unwrap().0.root.directory.as_deref(), + Some("run") + ); +} + +#[test] +fn hidden_flags_parse_but_stay_out_of_help() { + assert!(command!(&["run", "--yolo"], Command::Run(args) => args.permissions.auto())); + assert!( + command!(&["run", "--dangerously-skip-permissions"], Command::Run(args) => args.permissions.auto()) + ); + assert!(command!(&["mini", "--demo"], Command::Mini(args) => args.demo)); + assert!(parse(&["--yolo"]).unwrap().0.root.permissions.auto()); + let mut command = help::command(); + let run = command + .find_subcommand_mut("run") + .unwrap() + .render_help() + .to_string(); + let mini = command + .find_subcommand_mut("mini") + .unwrap() + .render_help() + .to_string(); + assert!(run.contains("--auto") && !run.contains("yolo") && !run.contains("dangerously")); + assert!( + mini.contains("--replay") && !mini.contains("--demo") && !mini.contains("--no-replay ") + ); +} + +#[test] +fn server_flags_apply_where_declared() { + let server = |line: &[&str]| parse(line).unwrap().1; + assert_eq!( + server(&["--server", "http://a", "session", "list"]) + .server + .as_deref(), + Some("http://a") + ); + assert_eq!( + server(&["session", "--server", "http://a", "list"]) + .server + .as_deref(), + Some("http://a") + ); + assert_eq!( + server(&["session", "list", "--server", "http://a"]) + .server + .as_deref(), + Some("http://a") + ); + assert!(server(&["--standalone", "run", "hi"]).standalone); + assert!(server(&["run", "hi", "--standalone"]).standalone); + assert_eq!( + server(&["--server", "http://a"]).server.as_deref(), + Some("http://a") + ); + assert_eq!( + server(&["debug", "heap-dump", "--server", "http://a"]) + .server + .as_deref(), + Some("http://a") + ); + assert!( + error(&["--server", "http://a", "upgrade"]) + .contains("Unrecognized flag: --server in command") + ); + assert!( + error(&["--standalone", "debug", "heap-dump"]).contains("Unrecognized flag: --standalone") + ); + assert!(error(&["upgrade", "--server", "http://a"]).contains("--server")); + assert!( + error(&["--server", "a", "session", "list", "--server", "b"]).contains("2 occurrences") + ); + assert!(error(&["--standalone", "auth", "list", "--standalone"]).contains("2 occurrences")); +} + +#[test] +fn root_flags_do_not_pass_to_subcommands() { + assert!( + error(&["-c", "upgrade"]) + .contains("Unrecognized flag: --continue in command opencode-rs upgrade") + ); + assert!(error(&["--prompt", "hi", "run"]).contains("Unrecognized flag: --prompt")); + assert!(error(&["--auto", "session", "list"]).contains("Unrecognized flag: --auto")); +} + +#[test] +fn global_flags_go_anywhere() { + assert!( + parse(&["--print-logs", "session", "list"]) + .unwrap() + .0 + .global + .print_logs + ); + assert!( + parse(&["session", "list", "--print-logs"]) + .unwrap() + .0 + .global + .print_logs + ); + assert!( + parse(&["debug", "paths", "--version"]) + .unwrap() + .0 + .global + .version + ); + assert!(parse(&["run", "-v"]).unwrap().0.global.version); + assert_eq!( + parse(&["auth", "--log-level", "debug"]) + .unwrap() + .0 + .global + .log_level, + Some(args::LogLevel::Debug) + ); + assert!( + parse(&["service", "status", "--wizard"]) + .unwrap() + .0 + .global + .wizard + ); +} + +#[test] +fn short_flags_cluster() { + let run = command!(&["run", "-cf", "a.txt", "hi"], Command::Run(args) => args); + assert!(run.continue_); + assert_eq!( + (run.file, run.message), + (vec!["a.txt".to_string()], vec!["hi".to_string()]) + ); + assert!(command!(&["pair", "-y"], Command::Pair(args) => args.yes)); +} + +#[test] +fn negative_numbers_are_values() { + assert_eq!( + command!(&["mini", "--replay-limit", "-5"], Command::Mini(args) => args.replay_limit), + Some(-5) + ); + assert!(error(&["stats", "--days", "-1"]).contains("-1")); + assert_eq!( + command!(&["run", "-1.5e3"], Command::Run(args) => args.message), + ["-1.5e3"] + ); + assert!(error(&["stats", "--year", "1969"]).contains("1969")); + assert_eq!(command!(&["stats"], Command::Stats(args) => args.limit), 5); +} + +#[test] +fn only_the_first_word_names_a_subcommand() { + assert_eq!( + command!(&["run", "session", "list"], Command::Run(args) => args.message), + ["session", "list"] + ); + assert_eq!( + parse(&["project"]).unwrap().0.root.directory.as_deref(), + Some("project") + ); + assert_eq!( + command!(&["run", "-m", "session", "hi"], Command::Run(args) => args.message), + ["hi"] + ); + assert!( + command!(&["session", "list", "-n", "3"], Command::Session(args) => matches!( + args.command, + Some(SessionCommand::List(list)) if list.max_count == Some(3) + )) + ); + assert!(parse(&["debug", "nope"]).is_err()); + assert!(parse(&["api", "a", "b", "c"]).is_err()); + assert!(parse(&["api"]).is_err()); +} + +#[test] +fn aliases_and_values_match() { + assert!( + command!(&["update", "1.2.3", "-m", "brew"], Command::Upgrade(args) => args.target.is_some()) + ); + assert!(error(&["upgrade", "--method", "apt"]).contains("apt")); + let url = + command!(&["pair", "--url", "https://example.com/base//"], Command::Pair(args) => args.url); + assert_eq!(url.as_deref(), Some("https://example.com/base")); + assert!( + error(&["pair", "--url", "https://user:secret@example.com"]) + .contains("without credentials") + ); + assert!(error(&["pair", "--url", "ftp://example.com"]).contains("HTTP(S)")); +} diff --git a/packages/cli-rs/crates/cli/src/tests/tree.rs b/packages/cli-rs/crates/cli/src/tests/tree.rs new file mode 100644 index 00000000000..e3a3d4ce2b9 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/tests/tree.rs @@ -0,0 +1,325 @@ +//! The clap tree against `tests/fixtures/commands.json`, the TypeScript `Spec` tree dumped by +//! `script/gen/commands.ts`: names, aliases, descriptions, arguments, and flags with their types. + +use clap::ArgAction; +use serde_json::Value; + +use crate::help; + +fn fixture() -> Value { + serde_json::from_str(include_str!("../../tests/fixtures/commands.json")).unwrap() +} + +fn diff(fixture: &Value) -> Vec { + let tree = help::tree(); + let mut diffs = Vec::new(); + let builtins = tree + .get_arguments() + .filter(|arg| arg.is_global_set()) + .collect::>(); + compare_flags("builtins", &fixture["builtins"], &builtins, &mut diffs); + compare_command("opencode", &fixture["root"], &tree, &mut diffs); + diffs +} + +#[test] +fn tree_matches_the_typescript_cli() { + let fixture = fixture(); + let nodes = count(&fixture["root"]); + assert_eq!(nodes, 48, "commands.ts has 48 Spec nodes"); + let diffs = diff(&fixture); + assert!( + diffs.is_empty(), + "the clap tree differs from the TypeScript tree:\n{}", + diffs.join("\n") + ); +} + +// The comparison sees each kind of change in the TypeScript tree. +#[test] +fn tree_comparison_reports_changes() { + type Edit = fn(&mut Value); + let edits: [(&str, Edit); 7] = [ + ("description", |tree| { + tree["root"]["commands"][0]["description"] = "changed".into() + }), + ("alias", |tree| { + tree["root"]["commands"][0]["aliases"] = serde_json::json!([]) + }), + ("flag", |tree| { + tree["root"]["flags"] + .as_array_mut() + .unwrap() + .pop() + .map(drop) + .unwrap() + }), + ("hidden", |tree| { + tree["root"]["flags"][3]["hidden"] = false.into() + }), + ("type", |tree| { + tree["root"]["commands"][3]["flags"][0]["type"] = "Int".into() + }), + ("argument", |tree| { + tree["root"]["arguments"][0]["optional"] = false.into() + }), + ("command", |tree| { + tree["root"]["commands"] + .as_array_mut() + .unwrap() + .pop() + .map(drop) + .unwrap() + }), + ]; + for (what, edit) in edits { + let mut fixture = fixture(); + edit(&mut fixture); + assert_eq!( + diff(&fixture).len(), + 1, + "a changed {what} gives one difference" + ); + } +} + +fn count(node: &Value) -> usize { + 1 + node["commands"] + .as_array() + .unwrap() + .iter() + .map(count) + .sum::() +} + +#[test] +fn tree_passes_clap_checks() { + help::command().debug_assert(); +} + +fn compare_command(path: &str, ts: &Value, command: &clap::Command, diffs: &mut Vec) { + let mut check = |what: &str, expected: Value, actual: Value| { + if expected != actual { + diffs.push(format!( + "{path}: {what}: TypeScript {expected}, Rust {actual}" + )); + } + }; + let root = path == "opencode"; + if !root { + check("name", ts["name"].clone(), command.get_name().into()); + } + let aliases: Vec<&str> = command.get_visible_aliases().collect(); + check("aliases", ts["aliases"].clone(), aliases.into()); + let about = command + .get_about() + .map(|about| about.to_string()) + .unwrap_or_default(); + check("description", ts["description"].clone(), about.into()); + + let globals: Vec<&str> = match root { + // The root's built-ins are compared with the fixture's `builtins`. + true => Vec::new(), + false => command + .get_arguments() + .filter(|arg| arg.is_global_set()) + .filter_map(|arg| arg.get_long()) + .collect(), + }; + check("global flags", ts["globalFlags"].clone(), globals.into()); + + let positionals: Vec = command.get_positionals().map(positional).collect(); + let expected: Vec = ts["arguments"] + .as_array() + .unwrap() + .iter() + .map(expected_positional) + .collect(); + check("arguments", expected.into(), positionals.into()); + + let flags: Vec<&clap::Arg> = command + .get_arguments() + .filter(|arg| !arg.is_positional() && !arg.is_global_set() && !is_negation(command, arg)) + .collect(); + compare_flags(path, &ts["flags"], &flags, diffs); + + let children: Vec<&str> = command + .get_subcommands() + .map(|sub| sub.get_name()) + .collect(); + let expected: Vec<&str> = ts["commands"] + .as_array() + .unwrap() + .iter() + .filter_map(|sub| sub["name"].as_str()) + .collect(); + if children != expected { + diffs.push(format!( + "{path}: subcommands: TypeScript {expected:?}, Rust {children:?}" + )); + return; + } + for (ts, sub) in ts["commands"] + .as_array() + .unwrap() + .iter() + .zip(command.get_subcommands()) + { + compare_command(&format!("{path} {}", sub.get_name()), ts, sub, diffs); + } +} + +fn compare_flags(path: &str, ts: &Value, flags: &[&clap::Arg], diffs: &mut Vec) { + let expected: Vec = ts.as_array().unwrap().iter().map(expected_flag).collect(); + let actual: Vec = flags.iter().map(|arg| flag(arg)).collect(); + let name = |flag: &Value| flag["name"].as_str().unwrap_or_default().to_string(); + let missing: Vec = expected + .iter() + .filter(|flag| !actual.iter().any(|a| name(a) == name(flag))) + .map(name) + .collect(); + let extra: Vec = actual + .iter() + .filter(|flag| !expected.iter().any(|e| name(e) == name(flag))) + .map(name) + .collect(); + if !missing.is_empty() || !extra.is_empty() { + diffs.push(format!( + "{path}: flags missing in Rust {missing:?}, only in Rust {extra:?}" + )); + } + for expected in &expected { + if let Some(actual) = actual.iter().find(|actual| name(actual) == name(expected)) + && actual != expected + { + diffs.push(format!( + "{path}: flag --{}:\n TypeScript {expected}\n Rust {actual}", + name(expected) + )); + } + } +} + +// The facts the TypeScript dump has, in the same shape, from a clap argument. +fn flag(arg: &clap::Arg) -> Value { + let action = arg.get_action(); + let boolean = matches!(action, ArgAction::SetTrue | ArgAction::Help); + let value_name = arg + .get_value_names() + .and_then(|names| names.first()) + .map(|name| name.to_string()); + let choices = choices(arg); + let kind = match value_name.as_deref() { + _ if boolean => "Boolean", + Some("string") => "String", + Some("integer") => "Int", + Some("key=value") => "KeyValuePair", + Some("choice") => "Choice", + Some("name") => "name", + // `--completions` and `--log-level`: Effect CLI shows the choices as the metavariable. + _ if !choices.is_empty() => "metavar", + _ => "unknown", + }; + let mut aliases: Vec = arg.get_short().map(String::from).into_iter().collect(); + aliases.extend( + arg.get_visible_aliases() + .unwrap_or_default() + .into_iter() + .map(String::from), + ); + let default = match boolean { + true => Value::Null, + false => arg + .get_default_values() + .first() + .map_or(Value::Null, |value| value.to_string_lossy().into()), + }; + serde_json::json!({ + "name": arg.get_long().unwrap_or_default(), + "aliases": aliases, + "type": kind, + "choices": choices, + "description": arg.get_help().map(|help| help.to_string()).unwrap_or_default(), + "hidden": arg.is_hide_set(), + "optional": !arg.is_required_set(), + "repeated": matches!(action, ArgAction::Append), + "optionalValue": arg.is_require_equals_set() && arg.get_num_args().is_some_and(|range| range.min_values() == 0), + "default": default, + }) +} + +fn expected_flag(ts: &Value) -> Value { + let kind = match ts["type"].as_str().unwrap_or_default() { + metavar if metavar.starts_with('<') => "metavar", + kind => kind, + }; + let default = match &ts["default"] { + Value::Bool(_) | Value::Null => Value::Null, + value => value.to_string().trim_matches('"').into(), + }; + serde_json::json!({ + "name": ts["name"], + "aliases": ts["aliases"], + "type": kind, + "choices": ts["choices"], + "description": ts["description"], + "hidden": ts["hidden"], + "optional": ts["optional"], + "repeated": ts["repeated"], + "optionalValue": ts["optionalValue"], + "default": default, + }) +} + +fn positional(arg: &clap::Arg) -> Value { + let range = arg.get_num_args(); + let variadic = matches!(arg.get_action(), ArgAction::Append) + || range.is_some_and(|range| range.max_values() > 1); + let choices = choices(arg); + serde_json::json!({ + "name": arg.get_value_names().and_then(|names| names.first()).map(|name| name.to_string()), + "type": if choices.is_empty() { "String" } else { "Choice" }, + "choices": choices, + "description": arg.get_help().map(|help| help.to_string()).unwrap_or_default(), + "required": arg.is_required_set(), + "variadic": variadic, + "max": range.map(|range| range.max_values()).filter(|max| *max != usize::MAX), + }) +} + +fn expected_positional(ts: &Value) -> Value { + let variadic = ts["variadic"].as_bool().unwrap_or(false); + let min = ts["min"].as_u64().unwrap_or(0); + serde_json::json!({ + "name": ts["name"], + "type": ts["type"], + "choices": ts["choices"], + "description": ts["description"], + "required": !ts["optional"].as_bool().unwrap_or(false) && (!variadic || min > 0), + "variadic": variadic, + "max": ts["max"], + }) +} + +fn choices(arg: &clap::Arg) -> Vec { + if matches!(arg.get_action(), ArgAction::SetTrue | ArgAction::Help) { + return Vec::new(); + } + arg.get_possible_values() + .iter() + .map(|value| value.get_name().to_string()) + .collect() +} + +// `--no-replay` is the hidden negation that `args::normalize` emits; Effect CLI has it built into `--replay`. +fn is_negation(command: &clap::Command, arg: &clap::Arg) -> bool { + arg.is_hide_set() + && arg + .get_long() + .and_then(|long| long.strip_prefix("no-")) + .is_some_and(|long| { + command + .get_arguments() + .any(|other| other.get_long() == Some(long)) + }) +} diff --git a/packages/cli-rs/crates/cli/src/update/mod.rs b/packages/cli-rs/crates/cli/src/update/mod.rs new file mode 100644 index 00000000000..771007cf308 --- /dev/null +++ b/packages/cli-rs/crates/cli/src/update/mod.rs @@ -0,0 +1 @@ +//! Update checks and the update handoff. Step D.2. diff --git a/packages/cli-rs/crates/cli/src/wizard.rs b/packages/cli-rs/crates/cli/src/wizard.rs new file mode 100644 index 00000000000..94471eb8bed --- /dev/null +++ b/packages/cli-rs/crates/cli/src/wizard.rs @@ -0,0 +1,5 @@ +//! `--wizard`. Step C.15; until then the flag is accepted and reports that it is not supported (O-11). + +pub fn run() -> anyhow::Result<()> { + anyhow::bail!("--wizard is not supported yet (plan step C.15)") +} diff --git a/packages/cli-rs/docs/C.0.md b/packages/cli-rs/docs/C.0.md index 09536b22c62..d76d020cfe6 100644 --- a/packages/cli-rs/docs/C.0.md +++ b/packages/cli-rs/docs/C.0.md @@ -10,7 +10,7 @@ the same commands, aliases, arguments, flags, and descriptions. The help layout `help` so they equal the TypeScript strings. - `script/gen/commands.ts` dumps the TypeScript `Spec` tree to `crates/cli/tests/fixtures/commands.json`: per node its name, aliases, description, global flags, arguments, and flags (name, aliases, type, choices, - description, hidden, optional, repeated with bounds, optional value, default). `crates/cli/tests/tree.rs` + description, hidden, optional, repeated with bounds, optional value, default). `crates/cli/src/tests/tree.rs` walks the clap `Command` and compares the same facts. A change on either side fails the test until the other side follows. - The type of a flag is carried by its clap value name, which help shows: `string`, `integer`, `key=value`, diff --git a/packages/cli-rs/script/gen/commands.ts b/packages/cli-rs/script/gen/commands.ts index aebb607c97b..3580e091a1c 100644 --- a/packages/cli-rs/script/gen/commands.ts +++ b/packages/cli-rs/script/gen/commands.ts @@ -1,5 +1,5 @@ // Dumps the TypeScript CLI command tree (packages/cli/src/commands/commands.ts) to JSON. The Rust test -// crates/cli/tests/tree.rs compares the clap tree against it: names, aliases, descriptions, arguments, flags. +// crates/cli/src/tests/tree.rs compares the clap tree against it: names, aliases, descriptions, arguments, flags. import { Effect, Exit, Option } from "effect" import { GlobalFlag } from "effect/cli" import { Commands, PrintLogs } from "../../../cli/src/commands/commands"