//! midas — a workspace of build machines that agents borrow. See DESIGN.md. //! //! One binary in every role: the CLI where agents work (`cargo` there is this //! binary under another name), the hub on the VPS, and the //! node inside each build machine's container. mod accounts; mod admin; mod agents; mod acp; mod ask; mod browser; mod autopilot; mod board; mod bot; mod botconfig; mod botsecrets; mod botsetup; mod builds; mod chart; mod collab; mod check; mod claude; mod cli; mod client; mod conf; mod deploy; mod device; mod discuss; mod events; mod flush; mod focus; mod forward; mod handoff; mod hook; mod host; mod hub; mod codeview; mod graph; mod hosted; mod hubsetup; mod import; mod mcp; mod memory; mod mirror; mod node; mod power; mod sleep; mod nodectl; mod procs; mod push; mod registry; mod release; mod remote; mod runners; mod setup; mod ship; mod sessions; mod setup_macos; mod stats; mod store; mod sshcfg; mod stall; mod talks; mod tap; mod templates; mod tree; mod update; mod usage; mod util; mod zedthreads; mod warm; mod watch; mod ws; mod web; #[cfg(test)] mod tests; use std::path::{Path, PathBuf}; use std::process::ExitCode; use clap::{Parser, Subcommand}; use serde_json::{json, Value}; /// The build this is: the git commit deploy.sh stamped in, so the hub and /// `midas check` can tell when one copy of six is behind. pub const VERSION: &str = match option_env!("MIDAS_BUILD") { Some(v) => v, None => env!("CARGO_PKG_VERSION"), }; #[derive(Parser)] #[command(name = "midas", version = VERSION, about = "A workspace of build machines that agents borrow")] struct Cli { /// Act as this session (default: the worktree you are in). The landing /// gate takes its node as `gate-`. #[arg(long, global = true, env = "MIDAS_OWNER")] owner: Option, #[command(subcommand)] cmd: Cmd, } #[derive(Subcommand)] enum Cmd { /// Take a node and bring it to this worktree; prints its name. If none is /// free, waits in line for --wait seconds, then leaves you queued for `midas wait`. Take { /// Which: any, gpu (any node with a GPU), a machine's name or a node's. #[arg(default_value = "any")] machine: String, /// One node in particular. #[arg(long)] node: Option, /// What it is for, shown in `midas status`. #[arg(long, env = "MIDAS_PURPOSE")] purpose: Option, /// How long to wait in line, in seconds. The default fits inside an /// agent's two-minute command limit; `midas wait` carries on from there. #[arg(long, default_value_t = 90)] wait: u64, /// Of the free nodes, take the one that has run this kind of command /// fastest (its shape in `midas stats`, e.g. `cargo test --workspace`), /// rather than the first listed. #[arg(long)] fastest_for: Option, /// With --node: ask for it next. Its holder is told and keeps it; when /// they release it, it comes to you rather than to whoever is in line. /// For maintenance and urgent work; --purpose says why. #[arg(long, requires = "node")] next: bool, }, /// Run one command on a node: `midas run -- cargo test -p x`. Takes the node /// fastest at it (waiting in line as long as it takes: run it in the /// background), sends the worktree, runs it, exits with its status, and /// lets the node go a minute later if somebody waits. A node you hold /// already is used as it is. Run { /// Which: any, gpu (any node with a GPU), a machine's name or a node's. #[arg(default_value = "any")] machine: String, /// One node in particular. #[arg(long)] node: Option, /// What it is for, shown in `midas status` (the command, if not given). #[arg(long, env = "MIDAS_PURPOSE")] purpose: Option, /// The command, after `--`, as you would give it to ssh. #[arg(last = true, required = true)] command: Vec, }, /// The landing queue: one landing on the warm branch at a time, first come /// first served, so a landing's gate is never made stale by another's push. #[command(subcommand)] Land(LandCmd), /// This checkout's project, as the hub has it (hub.conf `projects`): what /// the shared finish-branch skill gates on. JSON, or one setting raw. Project { /// One setting, printed as it is (empty when unset): gate, gate_nodes, /// pre_land, main, repo. #[arg(long)] get: Option, /// Another repository, `owner/name` (default: this checkout's origin). #[arg(long)] repo: Option, /// Make a project the hub hosts, change one, or read one without a checkout. #[command(subcommand)] act: Option, }, /// The shared workflow skills and the session hooks, in ~/.claude. #[command(subcommand)] Claude(ClaudeCmd), /// Photograph an HTML page as a Sketch round does (tree.rs, browser.rs): /// opened from `root`, checked as the scout's pages are, written to `out`. #[command(hide = true)] SketchShot { page: PathBuf, out: PathBuf, /// The project root the page is opened from. #[arg(long, default_value = ".")] root: PathBuf, /// `phone` (390 × 844) or `wide` (1280 × 800). #[arg(long, default_value = "phone")] frame: String, }, /// An agent session began or ended in this worktree (the session hooks /// say so), for the history of how long sessions take. Never fails. #[command(hide = true)] Session { /// `start`, `end`, or `label` (what to call the session, with --text). phase: String, /// Why: startup, resume, clear, compact; or how it ended. #[arg(long)] reason: Option, /// The label: the start of the session's first prompt (the prompt hook). #[arg(long)] text: Option, }, /// Leave a note: `midas say "…"`, the session by its worktree /// name as `midas who` lists it, or a role, resolved now: @ (its /// holder), @waiting: (everyone in line for it), /// @file: (every session changing it; `dir/` for anything under it). /// `midas say --re "…"` answers a note's sender. They get it with /// their next prompt or tool call; a name the hub does not know is refused. Say { /// The session (or role), then the words; with --re, only the words. #[arg(required = true, trailing_var_arg = true, value_name = "SESSION TEXT")] words: Vec, /// Answer the sender of this note (its id, n12), quoting it. #[arg(long, value_name = "NOTE")] re: Option, }, /// The sessions seen lately: what each is called, its branch, the node it /// holds or waits for, the files it changes and whose it shares, its unread /// notes, when it was last seen. Yours is marked. The names `say` takes. Who { #[arg(long)] json: bool, /// Every session of the last month, ended ones too. #[arg(long)] all: bool, }, /// This session has started changing these files (the tool hook, on an /// edit): the hub adds them to its work and tells both sessions at once /// when another one is changing them too. Prints this session's notes, /// as `notes` does, unless --no-notes (an edit by a subagent). #[command(hide = true)] Editing { #[arg(required = true)] files: Vec, #[arg(long)] hook: Option, #[arg(long)] no_notes: bool, }, /// Put a decision to the person steering the sessions — who gives way, /// whether one session carries on another's work. They are mailed and see /// it on the web page; the answer comes back as a note, to you and to /// every --with session. Prints its id. Ask { #[arg(required = true, trailing_var_arg = true)] question: Vec, /// A choice (repeat; none for a free answer). #[arg(long = "option")] options: Vec, /// Another session the answer concerns (repeat). #[arg(long)] with: Vec, }, /// The person's answer to a decision: an option's number or words. /// Without any, the open decisions and those made this week. Decide { id: Option, #[arg(trailing_var_arg = true)] choice: Vec, #[arg(long)] note: Option, }, /// Open decisions, and those made this week (`decide` with no answer). #[command(hide = true)] Decisions, /// Root on the hub's machine for a while, if the person allows it with /// their passkey: `midas admin "restart caddy" --for 30m`. A note says when /// it is open; `--done` closes it. Without words, how it stands. Admin { #[arg(trailing_var_arg = true)] reason: Vec, /// How long: 30m (the default), 1h; the machine caps it. #[arg(long = "for", default_value = "30m")] minutes: String, /// Through with it: close the window now. #[arg(long, conflicts_with = "reason")] done: bool, }, /// Agent sessions midas runs, which the page starts, follows and steers: /// `run` (in the agent container) runs them; `list`, `start ""`. #[command(subcommand)] Sessions(SessionsCmd), /// Show the person following this session on the Midas hub page a picture, /// a sound or a video, in the conversation (a session started from the page). Show { file: String, #[arg(long)] caption: Option, /// Also keep it on this tech of the research tree (k20) as how it /// works now: a picture of the real thing, where its card had a sketch. #[arg(long)] tech: Option, }, /// Carry on later (a session started from the page): at the time, midas /// tells this session what it was to do, starting it again if it had /// ended, and the page shows the time meanwhile. `midas later --in 4h /// "…"`, `--at 2026-10-30T09:00+01:00 "…"`; set again to move it, /// `--cancel` to drop it. Run it whenever you promise work for later. Later { /// What to do then, in words the session will read. #[arg(trailing_var_arg = true)] text: Vec, /// When: a date, a clock time and its offset from UTC. #[arg(long, conflicts_with = "after")] at: Option, /// How long from now: 90m, 4h, 1d, 1d12h. #[arg(long = "in", id = "after")] after: Option, #[arg(long, conflicts_with_all = ["at", "after"])] cancel: bool, }, /// Wait on the person for something only they can do (a session started /// from the page): the page lists it under Needs you until they give it, /// put it off or decline, and midas tells this session. `midas await /// "Paste a cartopolis.org token" --steps "1. …" --secret remote:pages /// --url https://…/mcp`; `--done` when it waits on nothing any more. Await { /// What it waits for, in a line. #[arg(trailing_var_arg = true)] text: Vec, /// The steps to it, as short Markdown. #[arg(long)] steps: Option, /// A secret's destination: remote: or bot::. #[arg(long)] secret: Option, /// For a remote the hub does not have yet: its MCP endpoint. #[arg(long, requires = "secret")] url: Option, #[arg(long, conflicts_with_all = ["steps", "secret", "url"])] done: bool, }, /// Claude Code as an Agent Client Protocol agent, on stdin and stdout: the /// agent `sessions run` starts unless MIDAS_AGENT names another. Runs /// `claude` (or MIDAS_CLAUDE) with this machine's own Claude login. /// /// `--mirror` puts midas between the editor and that agent, and mirrors /// each session to the hub's Sessions page, where it can be followed and /// steered while it runs here (an editor's agent: `midas acp --mirror`). #[command(hide = true)] Acp { /// Mirror each session to the hub, and take the page's words for it. #[arg(long)] mirror: bool, /// With --mirror: the ACP agent to run behind it, a shell command (default: `midas acp`). #[arg(long, requires = "mirror")] agent: Option, }, /// People's accounts for the web page, with password and one-time codes /// (admin). Machines and agents use caller keys instead. #[command(subcommand)] Account(AccountCmd), /// Follow Zed's archive at the hub once now, as `midas acp --mirror` does /// every 15 seconds (zedthreads.rs). #[command(hide = true)] ZedArchive, /// Agent memory, shared through the hub with every machine (memory.rs). #[command(subcommand)] Memory(MemoryCmd), /// A Claude Code hook's work, its input on stdin (hook.rs): `post-tool-use`, /// `user-prompt-submit`, `session-start`. #[command(hide = true, subcommand)] Hook(HookCmd), /// This session's notes from other sessions and the hub, shown now and left /// unread: a subagent runs this under its session's name. `--hook ` /// (the session's own hooks) hands them over as a Claude Code hook's added /// context, and prints nothing if none; `--sent`, the notes you sent and whether they were read. #[command(hide = true)] Notes { #[arg(long)] hook: Option, #[arg(long, conflicts_with = "hook")] sent: bool, }, /// Say what you are doing with your node and for about how long, so those /// waiting for it can plan. `--clear` takes it back. Intent { #[arg(trailing_var_arg = true)] text: Vec, #[arg(long)] minutes: Option, #[arg(long)] clear: bool, }, /// Give your node back as soon as your current ssh session on it ends (at /// once if none is open). `--undo` keeps it after all. Yield { #[arg(long)] undo: bool, }, /// The next free number in a namespace two branches must not both take (a /// database migration, a wire message kind): after --from (the highest your /// branch sees) and after every number already handed out. Prints it. /// `--list`: the numbers handed out, per namespace, and to whom. Reserve { #[arg(required_unless_present = "list")] namespace: Option, #[arg(long, default_value_t = 0)] from: i64, #[arg(long)] why: Option, #[arg(long, conflicts_with_all = ["namespace", "from", "why"])] list: bool, }, /// The numbers handed out (`reserve --list`). #[command(hide = true)] Reservations, /// Open ends: work left for the next session on a machine (its caller: /// workstation, agent …), shown to that session when it starts. #[command(subcommand)] Todo(TodoCmd), /// Carry on waiting in line for the node a `take` asked for, and take it. /// Prints its name; exits 75 if the time ran out and the place is still kept. Wait { /// How long, in seconds. #[arg(long, default_value_t = 3600)] timeout: u64, }, /// Give back the node this worktree holds. Release { #[arg(long)] node: Option, /// Take a node back from whoever holds it (with --node). #[arg(long)] force: bool, /// Not when it runs a hosted bot (`bot start --agent`), which outlives /// the session: what the session-end hook runs. #[arg(long)] keep_hosted: bool, }, /// Keep this worktree's lease alive (every ssh to a node does this already). #[command(hide = true)] Renew { #[arg(long)] command: Option, }, /// Whose this worktree is, as the hub names it (a landing's turn, a lease). #[command(hide = true)] Whoami, /// The node this worktree holds, as JSON (exit 1 if none). #[command(hide = true)] Mine, /// A free node faster at a command than one you hold: its name, or exit 1 /// when none is (the landing gate asks before gating on a held node). #[command(hide = true)] Faster { /// The node held. #[arg(long)] than: String, /// The kind of node: any, gpu, a machine. #[arg(default_value = "any")] machine: String, #[arg(long)] fastest_for: Option, }, /// Who holds each node, for what, until when, doing what; each node's /// heartbeat; the queue and where you stand in it; who is landing. Status { #[arg(long)] json: bool, /// Each node's last N events, not only what failed lately (the last 3). #[arg(long, value_name = "N")] recent: Option, }, /// Where a waiting worktree stands in line (`status` says it too). #[command(hide = true)] Position, /// Query the event log. Log { /// How far back: 90s, 30m, 2h, 3d. #[arg(long, default_value = "2h")] since: String, /// Comma-separated kinds, e.g. refused,lease_lapsed,guard. #[arg(long, value_delimiter = ',')] kind: Vec, #[arg(long)] node: Option, /// Substring of the acting session or job. #[arg(long)] actor: Option, #[arg(long)] json: bool, }, /// What each machine draws now, and used the last day and week (its chip's power). Power { #[arg(long)] json: bool, }, /// How long builds take, per command and node, cold and warm; waits and warms. Stats { /// How far back: 7d, 30d, 90d … (the build record is kept for good). #[arg(long, default_value = "30d")] since: String, #[arg(long)] node: Option, /// Every command, not only cargo. #[arg(long)] all: bool, #[arg(long)] json: bool, /// Also draw waiting per day against the nodes in the pool, as SVG. #[arg(long)] chart: Option, /// How sessions worked together instead, per week: landings and failed /// gates, notes and how long they waited to be read, overlaps, waits, /// and hours nodes sat held but unused. #[arg(long)] collab: bool, /// What each node used instead: memory (peak, p95, against its limit), /// load against its CPUs, free disk and busy time — kept 90 days. #[arg(long)] nodes: bool, /// With --nodes: one row per this much (1h, 1d …) instead of only the totals. #[arg(long)] step: Option, }, /// The story of one node: who held it, what ran, what waited, what failed. Explain { node: String, #[arg(long, default_value = "24h")] since: String, }, /// `nodes drain`. #[command(hide = true)] Drain { node: String, #[arg(long)] why: String, }, /// `nodes undrain`. #[command(hide = true)] Undrain { node: String }, /// The build machines: add, remove, rename, drain and undrain one. #[command(subcommand)] Nodes(NodesCmd), /// Build a commit that has landed on a node and publish it on the hub's /// machine: one of hub.conf's deploy targets. Without a target, lists them /// and the last week's deploys. Waits and reports each step, unless --no-wait. Deploy { target: Option, /// The commit (default: the tip of the warm branch, fetched now). It must /// be on that branch. #[arg(long)] sha: Option, /// Deploy a commit with no receipt from the landing gate, saying why. #[arg(long, value_name = "WHY")] unverified: Option, #[arg(long)] no_wait: bool, /// Hold the deploys the hub makes after landings, saying why, until a /// person deploys or `--release`s: what lands goes on main, not live. #[arg(long, value_name = "WHY", conflicts_with_all = ["target", "release"])] hold: Option, /// End a hold. #[arg(long, conflicts_with = "target")] release: bool, /// Put off a deploy announced to the sessions at work (one that restarts /// what they use, midas itself), when it would break what this one is doing. #[arg(long, value_name = "TARGET", conflicts_with_all = ["target", "hold", "release"])] defer: Option, /// With --defer: by how long (at most 30 at a time, 60 in all). #[arg(long, default_value_t = 10, requires = "defer")] minutes: i64, /// With --defer: what it would break. #[arg(long, requires = "defer")] why: Option, }, /// Record that the landing gate passed at a commit — what a deploy asks for /// (the finish-branch skill runs it). #[command(hide = true)] Verified { /// Default: this worktree's HEAD. #[arg(long)] sha: Option, #[arg(long)] steps: Option, #[arg(long)] scope: Option, /// The node the gate ran on. #[arg(long)] node: Option, }, /// Is the workspace healthy? Hub, nodes, versions, this container's config, /// the last day's failures. Prints what is wrong; -v everything. The exit /// status counts the problems that are yours to fix. Check { #[arg(short, long)] verbose: bool, }, /// ssh Host blocks for every node (to stdout, or into --write FILE). SshConfig { /// The key this machine logs into nodes with (default: MIDAS_SSH_KEY in /// hub.env, else ~/.ssh/id_ed25519). #[arg(long)] identity: Option, /// Where the nodes' host keys are written (default ~/.config/midas/known_hosts). #[arg(long)] known_hosts: Option, /// The holder check and the worktree barrier (agent containers; not the hub's machine). #[arg(long)] flush: bool, #[arg(long)] write: Option, }, /// Exit 0 if this worktree holds the node; ssh asks before connecting to a node. #[command(hide = true)] Holds { node: String }, /// Bring a node's checkout up to date with this worktree; ssh runs it before connecting. #[command(hide = true)] Flush { node: String }, /// An MCP server on stdio: node and Forgejo tools for an agent. #[command(hide = true)] Mcp, /// Make this machine a build node: a user of its own, a firewall on the machine /// that keeps it off the network, and the node. Run by the machine's owner, as /// root, with a midas they built. Run it again to update or repair. Setup { /// The node's name, as the hub knows it (`midas nodes add`). node: String, /// The hub's ADDRESS:PORT on the tunnel (needed the first time; kept after). #[arg(long)] hub: Option, /// Memory limit, e.g. 10g (default 10g). #[arg(long)] memory: Option, /// CPU limit (default 6). #[arg(long)] cpus: Option, /// The GPU render node, or `none` (default /dev/dri/renderD128). #[arg(long)] gpu: Option, /// HOST_DIR:CONTAINER_DIR, mounted read-only (repeatable). #[arg(long = "mount")] mounts: Vec, /// The user the node runs as (default midas-node). Never your own. #[arg(long)] user: Option, /// Stop the node and take its firewall away (its user and data stay). #[arg(long)] remove: bool, /// macOS: the VM image to build the node from. #[arg(long)] image: Option, /// macOS: the VM's disk size in GB (default 200). #[arg(long)] disk: Option, /// macOS: build the VM again from the image (the node's disk, and its /// warm build directory, start over). #[arg(long)] rebuild: bool, }, /// Bring the build machines' nodes to the midas in your checkout, from your /// own machine: each builds it, installs it and is set up again, with your /// sudo. Machines are reached as MIDAS_MACHINES in hub.env says /// (`deck=deck@192.168.1.50 …`); this machine's own nodes need no entry. /// Without a terminal, sudo asks in a dialog. Exits 75 if a held node was left for later (--wait waits instead). Update { /// Only these machines (default: every machine the hub knows). machines: Vec, /// Update a machine even while somebody holds one of its nodes: setup /// restarts it, which cuts them off. #[arg(long)] force: bool, /// Wait for a machine whose nodes are held: drain them so nobody new /// takes one, tell their holders why, and update once they let go. #[arg(long, conflicts_with = "force")] wait: bool, /// The midas checkout to install (default: MIDAS_SRC in hub.env, else /// the checkout you are in). #[arg(long)] src: Option, }, /// Run a long-lived program (a bot) on a node and talk to it over MCP: start, /// mcp, stop, status; and, by a machine's owner, the bots' secret (setup). #[command(subcommand)] Bot(BotCmd), /// Paired devices: an app on a phone whose tools the sessions call (`list`, `forget`), and /// one as an MCP server for a session (`mcp`, which the runner starts). #[command(subcommand)] Device(DeviceCmd), /// Remote MCP servers the hub signs in to for the sessions, whose tools `midas mcp` /// offers as its own (`list`, `set`). #[command(subcommand)] Remote(RemoteCmd), /// The hub's services. #[command(subcommand)] Hub(HubCmd), /// The owner's release key: signs a build of midas, which the hub's /// self-update can insist on (hub.conf `self_update: "signed"`). #[command(subcommand)] Sign(SignCmd), /// A node on this machine: status, start/stop/restart, logs, a shell. #[command(subcommand)] Node(NodeCmd), } #[derive(Subcommand)] enum TodoCmd { /// Leave one. `--for` names the caller whose next session should do it. Add { #[arg(long = "for", default_value = "any")] target: String, #[arg(required = true, trailing_var_arg = true)] text: Vec, }, /// Every open end, and those done this week. List, /// This session's open ends (the session-start hook asks with `--hook SessionStart`). #[command(hide = true)] Take { #[arg(long)] hook: Option, }, /// Done; `--note` says what came of it. Done { id: String, #[arg(long)] note: Option, }, } #[derive(Subcommand)] enum ClaudeCmd { /// Install the skills and hooks this midas carries into ~/.claude, or bring /// them up to date, and wire the hooks into settings.json. Leaves the /// person's own skills alone and backs up what it replaces. Install { /// Say nothing when nothing changed (the session-start hook). #[arg(long)] quiet: bool, }, /// Take back what install put there. Uninstall, } #[derive(Subcommand)] enum LandCmd { /// Wait for the turn to land, in line behind whoever asked first. Exits 0 /// holding it, 75 if --wait ran out (the place is given up). Take { #[arg(long, env = "MIDAS_PURPOSE")] purpose: Option, /// How long to wait, in seconds. #[arg(long, default_value_t = 7200)] wait: u64, }, /// Keep the turn (it lapses after ten silent minutes), saying what it is doing. Renew { #[arg(long)] step: Option, }, /// Give the turn back, or a place in line; the next in line goes. Release { /// What became of it, for the log: landed, failed, abandoned. #[arg(long)] outcome: Option, /// The commit it landed. #[arg(long)] sha: Option, }, /// Who is landing, and who is in line (`midas status` says it too). #[command(hide = true)] Status, /// Which deploy targets this branch's landing builds: what it changes for /// each since main, the ones it must build, the optional ones it may. The /// proposal for "Shall it land?"; `--pick` changes it, `--record` tells the /// hub (finish-branch's `land --targets` does, before it pushes). Targets { /// What this landing changes is counted from here (default: where the /// branch leaves origin's main). #[arg(long)] base: Option, /// `sim,web` names them; `+wasm` or `-apk` changes the proposal; `all` /// takes every changed one. What a target must stay in step with /// changing builds it whatever is picked. #[arg(long)] pick: Option, /// Tell the hub, for this worktree's HEAD. #[arg(long)] record: bool, #[arg(long)] json: bool, }, } #[derive(Subcommand)] enum RemoteCmd { /// The remote MCP servers and the tools each announced. List, /// On the hub's machine: add or replace one, the token read from stdin (empty removes it). Set { name: String, url: String }, } #[derive(Subcommand)] enum DeviceCmd { /// The paired devices: online or not, and the tools each announced. List, /// Forget a device: its token is void and its link dropped. Forget { id: String }, /// One device as an MCP server on stdio, its tools relayed through the hub. #[command(hide = true)] Mcp { id: String }, /// Pair with a code from the page and stand in for a device, answering `echo`: to try the /// link end to end with no app (`--hub` the hub's URL as a phone reaches it). #[command(hide = true)] Fake { code: String, #[arg(long)] hub: String, #[arg(long, default_value = "Fake device")] name: String, }, } #[derive(Subcommand)] enum BotCmd { /// Take a node in bot mode, start the bot there from its checkout (which /// follows this worktree), and wait until it answers MCP through the relay. /// Prints the node's name. Run it in the background: a first build is long. Start { /// Which: any, gpu, or a machine's name. #[arg(default_value = "any")] machine: String, /// One node in particular. #[arg(long)] node: Option, /// What it is for, shown in `midas status`. #[arg(long, env = "MIDAS_PURPOSE")] purpose: Option, /// The relay: a command on the node whose stdin and stdout are the bot's MCP. #[arg(long)] mcp: String, /// How long to wait in line for a node, in seconds. #[arg(long, default_value_t = 3600)] wait: u64, /// How long the bot may take to answer, in seconds (a first build is long). #[arg(long, default_value_t = 1800)] timeout: u64, /// Host an agent for the bot, here. Alone, midas runs Claude Code /// itself (`midas acp`), fenced to the bot's tools; `--agent=''` /// names another Agent Client Protocol agent (with `=`, so a bare /// `--agent` never takes the next word). It gets the bot's tools and /// nothing else, and what the bot hears as its prompts; it outlives /// this session. #[arg(long, num_args = 0..=1, require_equals = true, value_name = "ACP COMMAND")] agent: Option>, /// The hosted bot's name, for `bot log`, `tell` and `stop`. #[arg(long, default_value = "bot", requires = "agent")] name: String, /// A file with the agent's instructions (its system prompt). #[arg(long, requires = "agent")] brief: Option, /// The agent's own settings, as `_meta` for its session: JSON, or @file. /// midas's own agent has its fence without it (`acp::bot_fence`). #[arg(long, requires = "agent")] agent_meta: Option, /// The bot's tool that waits for input and answers it as the next prompt. #[arg(long, default_value = "inbox", requires = "agent")] inbox: String, /// Stop the hosted bot after this long with nothing to answer (90m, 2h, /// 1d; 0 never). #[arg(long, default_value = "2h", requires = "agent")] idle: String, /// The agent's session mode, one that asks before using a tool (for /// Claude Code: default, which midas's own agent takes without it). /// Set at every start, whatever the agent's own settings say. #[arg(long, requires = "agent")] agent_mode: Option, /// The bot: one word is a shell command, several an argument list. #[arg(last = true, required = true)] command: Vec, }, /// This worktree's bot as an MCP server on stdio (the command an MCP client runs). Mcp, /// Stop this worktree's bot (or the hosted bot --name) and give its node back. Stop { #[arg(long)] name: Option, }, /// Is this worktree's bot running? Since when, what, the last of its log; /// and its host, for a hosted bot. Status { #[arg(long)] name: Option, }, /// What a hosted bot heard, did and thought, from its transcript. Log { /// The hosted bot (default: this worktree's). name: Option, #[arg(short = 'n', long, default_value_t = 40)] lines: usize, }, /// Give a hosted bot's agent a line of your own, with its next prompt. Tell { /// The hosted bot (with --name; default: this worktree's). #[arg(long)] name: Option, text: String, }, /// The host of a hosted bot (`bot start --agent` runs it, detached). #[command(hide = true)] Host { name: String }, /// Give bots a secret, kept by the hub and handed to a bot's environment /// when `bot start` starts it: for a node, a machine, `gpu` or `any`. Read /// with echo off (or one line with --stdin). --list names what is set. Token { /// A node, a machine, gpu or any (not needed with --list). target: Option, /// The variable the bot reads it from, e.g. CARTO_TOKEN. #[arg(long, default_value = "CARTO_TOKEN")] env: String, #[arg(long)] stdin: bool, #[arg(long)] remove: bool, #[arg(long)] list: bool, }, /// Give a node's bots one secret, as NAME=value in their environment (as /// root, on the build machine; read with echo off, never sent to the hub). Setup { node: String, /// The variable's name, e.g. CARTO_TOKEN (needed the first time; kept after). #[arg(long)] env: Option, /// Read the secret from one line of stdin, not the terminal. #[arg(long)] stdin: bool, /// Delete the bots' secret. #[arg(long)] remove: bool, }, } #[derive(Subcommand)] enum NodeBotCmd { /// Start the bot detached and return when it answers MCP (as `build`, in a session). Start { #[arg(long)] mcp: String, #[arg(long, default_value_t = 1800)] timeout: u64, #[arg(last = true, required = true)] command: Vec, /// Read more NAME=value lines from stdin, to EOF (a `bot start` from before 2026-11-21). #[arg(long, hide = true)] env_stdin: bool, /// The bot's name at the hub (Settings ▸ Bots), whose own secrets it starts with. #[arg(long)] bot: Option, }, /// Become the relay to the running bot: MCP on stdin and stdout. Mcp, /// Stop the bot, its whole process group. Stop, /// Running?, since, command, the last of its log. Status, } #[derive(Subcommand)] enum NodesCmd { /// One line per node (`midas status` says more). #[command(hide = true)] List, /// Take a node out of the pool on purpose, until undrained. A current lease runs on. Drain { node: String, #[arg(long)] why: String, }, /// Put a drained node back in the pool. Undrain { node: String }, /// Add a build machine. It joins out of the pool and comes in with its first heartbeat. Add { id: String, /// The machine it runs on; agents can ask for any node on it by this name. #[arg(long)] machine: String, /// The machine's WireGuard address. #[arg(long)] address: String, /// The port on that address agents reach the node on (default: the next free one from 2223). #[arg(long)] port: Option, #[arg(long)] gpu: bool, /// What it renders on, e.g. "AMD Radeon 780M (RADV)". #[arg(long)] renderer: Option, }, /// Remove a machine nobody holds. Remove { id: String }, /// Give a node nobody holds another name. Its machine's owner then runs /// `sudo midas setup `, which keeps the node's data: nothing is copied. Rename { id: String, to: String }, } #[derive(Subcommand)] enum SignCmd { /// A new release key (default ~/.config/midas/release.key, 0600, never over /// an old one); prints its public line for the hub. Keygen { #[arg(long)] key: Option, }, /// The public line of a release key. Public { #[arg(long)] key: Option, }, /// Sign a build: writes .sig beside it. Build { file: std::path::PathBuf, #[arg(long)] key: Option, }, /// Check a build against a public key (default signature: .sig). Verify { file: std::path::PathBuf, #[arg(long)] pubkey: std::path::PathBuf, #[arg(long)] sig: Option, }, } #[derive(Subcommand)] enum HubCmd { /// Make this machine the hub (as root): its user, keys, services. Run it /// again to update the hub to this binary or change a setting. Setup { /// Where the hub answers: this machine's WireGuard address and a port. #[arg(long)] listen: Option, /// The git server to mirror from, ssh://git@host:port. #[arg(long)] forgejo: Option, /// Its API, https://host/api/v1. #[arg(long)] forgejo_api: Option, /// A repository nodes may fetch, owner/name (repeatable; replaces the list). #[arg(long = "repo")] repos: Vec, /// A public key agents log into nodes with (repeatable; replaces the list). #[arg(long = "agent-key")] agent_keys: Vec, /// OS-ARCH=PATH: this same build for nodes of another platform, which /// they take from the hub when free (repeatable; deploy.sh passes it). #[arg(long = "node-binary")] node_binaries: Vec, /// What the hub does with a build of midas it published itself: hub /// (run it as root, the default), signed (only with the release key's /// signature on it), off (never). #[arg(long)] self_update: Option, /// The release key's public line (`midas sign keygen` prints it), a /// file holding it, or - for stdin: goes to /etc/midas/release.pub. #[arg(long)] release_key: Option, }, /// Root's side of admin windows (admin.rs): the user the agents are, the /// page their passkey signs on, the longest window (as root). AdminSetup { #[arg(long)] user: String, /// The page's host: the passkeys' relying party. #[arg(long)] rp_id: String, /// The page's origin (repeat); `https://` when none. #[arg(long = "origin")] origins: Vec, #[arg(long)] max_minutes: Option, }, /// A passkey that may grant windows: the line the page shows after making /// one; `--remove ` takes one away (as root). AdminEnroll { line: Vec, #[arg(long, conflicts_with = "line")] remove: Option, }, /// Close an admin window whose time is up, and open one the person signed /// (midas-admin.service runs it, as root). AdminApply, /// Install the build a deploy of midas published, as hub.conf's self_update /// says (the midas-self-update service runs it, as root). SelfUpdate { /// Where the build waits (default: /usr/local/lib/midas/next). #[arg(long)] next: Option, }, /// Who may change the workspace: one key per caller (as root, on the hub). #[command(subcommand)] Caller(CallerCmd), /// Hold the workspace's state and answer for it (the service runs this). Serve { #[arg(long)] listen: Option, }, /// The hub sshd's command for a node's key (git fetches and LFS auth, /// nothing else), or for a person's or an agent's (`--key`), which also /// pushes the repositories the hub hosts. Git { #[arg(long, required_unless_present = "key")] node: Option, #[arg(long, conflicts_with = "node")] key: Option, }, /// A hosted repository's pre-receive hook: may this key move these refs? PreReceive, /// A hosted repository's post-receive hook: tell the hub what moved. PostReceive, /// The keys that push and fetch the repositories the hub hosts. Run on the /// hub as its user: `sudo -u midas midas hub git-key …`. #[command(subcommand)] GitKey(GitKeyCmd), /// Take a project over from Forgejo (docs/git-hosting.md, step 2): its /// branches, tags and LFS objects, and its landing. Run on the hub as its /// user: `sudo -u midas midas hub import jeroen/x --public`. Import { /// `owner/name`, as hub.conf's `repos` has it. repo: String, /// Readable by anyone at `//`, as it was on Forgejo. #[arg(long)] public: bool, #[arg(long, default_value = "")] description: String, /// Fetch it from here (a path or URL) instead of Forgejo over ssh: for /// a repository the mirror's key does not open, Forgejo's copy staged /// where the hub's user can read it. #[arg(long)] from: Option, /// Take missing LFS objects from this directory, laid out as Forgejo's /// (`data/lfs`), instead of asking Forgejo. #[arg(long)] lfs_from: Option, }, /// Warm every free node that is cold, over its ceiling or stale (a timer runs it), /// then mail any node problem that has lasted an hour. Warm { #[arg(long)] node: Option, #[arg(long)] dry_run: bool, }, /// Fetch a mirrored repository from Forgejo now. Refresh { repo: String }, /// Build the queued deploys on nodes (the deploy service runs it, as the hub's user). DeployBuild, /// Publish the built deploys (the publish service runs it, as root). DeployPublish, /// The hub's state as a gzipped tar on stdout (as root), for another /// machine to keep: `ssh sudo midas hub backup > midas-hub.tar.gz`. Backup, } #[derive(Subcommand)] enum CallerCmd { /// Add a caller (or give it a new key) and print the key. Add { name: String, /// The Forgejo token its /v1/forgejo calls use; `-` reads it from stdin. #[arg(long)] forgejo_token: Option, /// What it may do: viewer, operator, steer or admin (default: steer, /// what agents need — managing accounts takes admin). #[arg(long)] role: Option, }, List, Remove { name: String }, /// Set what a caller key may do: viewer, operator, steer or admin. Role { name: String, role: String }, } #[derive(Subcommand)] enum SessionsCmd { /// Run the sessions the page starts, until stopped: each in a worktree of /// its own off its project's checkout (MIDAS_SESSIONS_REPO when it is that /// one, else cloned into MIDAS_SESSIONS_DIR/repos), with the agent MIDAS_AGENT /// (an Agent Client Protocol command; `midas acp`, Claude Code, by default). Run, /// Answer one code question the runner was handed (its job on stdin), as /// the build installed now: what `run` hands each question to. #[command(hide = true)] Answer, /// Run one round of the research tree's scout the runner was handed (its /// job on stdin), as the build installed now: what `run` hands each round to. #[command(hide = true)] Scout, /// Every session: id, status, branch, title. List, /// This session works in one more project: its worktree, on the session's /// branch, at ./ in the session's folder (a session started from the page). AddProject { /// The project, by name or owner/name. project: String, }, /// Finish this worktree's session, on the person's answer: once the commit /// it landed (`--sha`, what `land --finish` passes) is live, or now with /// `--drop` (nothing landed; its branch is kept). Finished, it is ended and /// filed under Finished. Finish { #[arg(long, conflicts_with = "drop", required_unless_present = "drop")] sha: Option, #[arg(long)] drop: bool, }, /// Start one, as the page does. Prints its id. Start { #[arg(required = true, trailing_var_arg = true)] prompt: Vec, /// The project, by name or owner/name (default: this checkout's, if it /// is one; else the workspace's first). #[arg(long)] project: Option, /// The branch to start from (default main). #[arg(long)] base: Option, /// The mode to start in, as the agent names it (default, acceptEdits, /// plan, auto, bypassPermissions); the agent's first otherwise. #[arg(long)] mode: Option, /// The model: default (Claude Code's own choice), fable, opus, opus-fast (Opus in fast mode), sonnet, haiku, or a model's id. #[arg(long)] model: Option, /// The agent, by its id in hub.conf's agents (default claude: Claude Code). /// Another agent starts in its own mode; --mode applies only if it has it. #[arg(long)] agent: Option, }, /// Create one by name and brief, for tooling: its branch session/ off /// main, the brief its first message. Prints its id, status and branch. Create { /// What the page lists it as (one line, at most 80 characters). #[arg(long)] name: String, /// What it is to do; `-` reads it from stdin (at most 32 KB). #[arg(long)] brief: String, /// The project to start in, by name or owner/name (default: none; its agent adds what it needs). #[arg(long)] project: Option, /// The branch to start from (default main). #[arg(long)] base: Option, }, /// Bring Claude Code conversations had elsewhere to the page, to read and /// search: each transcript an ended session. Run again, it sends only /// those that are new or have grown. Import { /// Transcripts, or directories of them (`~/.claude/projects/`). paths: Vec, /// Every claude.ai/code session too, read from claude.ai with this /// machine's Claude Code login: a claude.ai/code session's own machine /// keeps its transcript 30 days, claude.ai keeps it all. #[arg(long)] claude_ai: bool, /// Only conversations had in a directory whose path has this in it /// (repeatable: any of them). #[arg(long)] cwd: Vec, /// Where they were had, as the page says it (default: this machine's /// name; claude.ai/code for --claude-ai's). #[arg(long)] from: Option, /// Read them and list them, sending nothing. #[arg(long)] dry_run: bool, /// Send again ones the hub has whole already. #[arg(long)] replace: bool, }, } #[derive(Subcommand)] enum HookCmd { /// Before a question card: a landing card waits for a picture. PreToolUse, /// After every tool call: report a first edit of a file, hand over notes. PostToolUse, /// Before every prompt: name the session, sync memory, hand over notes. UserPromptSubmit, /// At a session's start: how builds work, the nodes, what is wrong. SessionStart, /// The files this branch changes, to the hub: run by the other hooks, in the background. Work, /// In a session's folder: hand the event to its projects' own hooks. Projects { /// The Claude Code hook event (PostToolUse, …). event: String, }, } #[derive(Subcommand)] pub enum ProjectCmd { /// A new project, its repository hosted by the hub (docs/git-hosting.md): /// a first commit on main, its landing, and the URL to clone. Then /// `project_add` (or `midas sessions add-project`) brings it into a session. Create { name: String, /// What it is: the README's first line. #[arg(long, default_value = "")] description: String, /// Readable by anyone, without a login. Private (the default) is the /// workspace's only; making a private project public later is the person's. #[arg(long)] public: bool, /// Its landing gate, a command run on a build node (unset: no landing until set). #[arg(long)] gate: Option, #[arg(long)] gate_nodes: Option, /// Whose namespace (default: the workspace's first project's owner). Not /// `--owner`, which is every command's session. #[arg(long)] namespace: Option, }, /// Change a hosted project's landing or description (`--public` is the person's). Set { repo: String, #[arg(long)] gate: Option, #[arg(long)] gate_nodes: Option, #[arg(long)] pre_land: Option, #[arg(long)] description: Option, #[arg(long, conflicts_with = "private")] public: bool, #[arg(long)] private: bool, }, /// Give a hosted project another name: its repository, landing, sessions, /// goals and notes move with it, and the old name still clones and pushes. Rename { repo: String, /// The new name (or `owner/name`). to: String, }, /// Delete a hosted project: the person's, who does it on the page (Map ▸ /// project ▸ Settings); a key is refused and told so. Delete { repo: String }, /// A file or directory of a hosted project, without a checkout. Show { repo: String, #[arg(default_value = "")] path: String, #[arg(long)] rev: Option, }, /// A hosted project's last commits. Log { repo: String, #[arg(long)] rev: Option, #[arg(short, default_value_t = 20)] n: usize, }, } #[derive(Subcommand)] pub enum GitKeyCmd { /// Let a key push and fetch: `--role person` may do anything, `agent` every /// branch but main, and main only from a landing. Add { name: String, #[arg(long)] role: String, /// The public key, `ssh-ed25519 AAAA…`. key: String, }, Remove { name: String }, List, } #[derive(Subcommand)] enum MemoryCmd { /// Merge this checkout's memory directory with the hub's: this repository's /// notes and the workspace's (`workspace--*.md`). The hooks run it. Sync { /// Not again within this many seconds of the last sync. #[arg(long)] every: Option, #[arg(long)] quiet: bool, }, /// The directory this checkout's sessions keep their memory in, and its repository. Where, } #[derive(Subcommand)] enum AccountCmd { /// A person's account. Prints a setup link, good for a day: they choose a /// password there and add the one-time-code secret to an authenticator app. Add { name: String, /// viewer (sees the page), operator (changes the workspace), steer /// (types into agent sessions), admin (manages accounts). #[arg(long, default_value = "operator")] role: String, }, /// Every account: role, set up or not, last seen. List, Role { name: String, role: String }, /// Start an account over — a lost phone, a leaked password: its password, /// code secret, recovery codes and sessions go, and a new setup link is printed. Reset { name: String }, Remove { name: String }, } #[derive(Subcommand)] enum NodeCmd { /// A node on this machine: running?, its firewall, and what the hub sees /// (heartbeat, holder, build). No sudo needed. Status { node: Option }, /// Start the node (sudo). Start { node: Option }, /// Stop the node until it is started again or the machine boots (sudo). Stop { node: Option }, /// Restart the node (sudo). Restart { node: Option }, /// The node's log (sudo). Logs { node: Option, /// Keep following it. #[arg(short, long)] follow: bool, }, /// A shell inside the node, as the user agents work as (sudo). Shell { node: Option }, /// sshd's AuthorizedKeysCommand: operator keys always, the agent key while leased. #[command(hide = true)] AuthorizedKeys { user: String, key: Option }, /// sshd's ForceCommand: warnings, logging, then the command as typed. #[command(hide = true)] Session, /// The GPU's dedicated and shared memory, as the guard reads them. Gpu, /// The GPU memory guard and the node's heartbeat. #[command(hide = true)] Guard, /// Tell the hub this node's git and host keys (the entrypoint runs it). #[command(hide = true)] Register, /// Run the midas the hub runs, once nobody holds this node (as the node's /// root; the entrypoint runs it every five minutes). #[command(hide = true)] Update, /// Send this machine's power to the hub once a minute (as root; the /// service `midas setup` installs runs it). #[command(hide = true)] Power { /// The hub, ADDRESS:PORT on the tunnel. #[arg(long)] hub: String, }, /// macOS machines: carry TCP between the tunnel, the hub and a node's VM /// (a launchd job runs it). Each --pair is LISTEN=TARGET; a TARGET of /// `vm:PORT` is the VM's current address. #[command(hide = true)] Forward { #[arg(long)] vm: String, #[arg(long = "pair", required = true)] pairs: Vec, }, /// Make /work/checkout match what `midas flush` sent on stdin. #[command(hide = true)] Apply, /// The bot on this node (`midas bot` runs these over ssh). #[command(hide = true, subcommand)] Bot(NodeBotCmd), } /// The page's setup address for a token: MIDAS_WEB_URL (hub.env), where the /// page is published, else the hub itself. fn setup_link(v: &Value) -> String { let base = client::setting("MIDAS_WEB_URL").unwrap_or_else(client::hub_url); format!("{}/setup/{}", base.trim_end_matches('/'), v["token"].as_str().unwrap_or("?")) } /// `midas admin`: ask for a window, close it, or say how it stands (admin.rs). fn admin_cmd(owner: &str, reason: &str, minutes: &str, done: bool) -> anyhow::Result { if done { client::post("/v1/admin/close", &json!({"owner": owner}))?; eprintln!("closing: root goes within a minute (sudo stops working, root shells from your logins end)"); return Ok(0); } if reason.trim().is_empty() { let s = client::get("/v1/admin")?; match s["window"]["id"].as_str() { Some(id) => println!("open: {id} for {}, until {} — {}", s["window"]["session"].as_str().unwrap_or("?"), s["window"]["until"], s["window"]["reason"].as_str().unwrap_or("")), None => println!("no window open"), } for r in s["requests"].as_array().into_iter().flatten().filter(|r| r["session"] == owner) { println!("{}: {} — {}", r["id"].as_str().unwrap_or("?"), r["state"].as_str().unwrap_or("?"), r["reason"].as_str().unwrap_or("")); } return Ok(0); } let v = client::post("/v1/admin/request", &json!({"owner": owner, "reason": reason, "minutes": admin::minutes_of(minutes)?}))?; let id = v["id"].as_str().unwrap_or("?"); eprintln!("asked as {id}: the person's phone shows it, and their passkey opens it. A note tells you when root works \ (or that they declined); end your turn rather than wait, and do what does not need root meanwhile."); println!("{id}"); Ok(0) } /// `decide` with no answer: the open decisions, and those made this week. fn decisions() -> anyhow::Result { for d in client::get("/v1/decisions")?.as_array().into_iter().flatten() { let state = match d["answer"].as_str() { Some(a) => format!("decided: {a}"), None => d["options"].as_array().into_iter().flatten().filter_map(Value::as_str).enumerate() .map(|(i, o)| format!("{}. {o}", i + 1)).collect::>().join(" "), }; println!("{} {} ({})\n {state}", d["id"].as_str().unwrap_or("?"), d["question"].as_str().unwrap_or(""), d["by"].as_str().unwrap_or("?")); } Ok(0) } fn since(s: &str) -> anyhow::Result { util::seconds(s).map(|n| chrono::Duration::seconds(n as i64)).ok_or_else(|| anyhow::anyhow!("--since takes 90s, 30m, 2h or 3d, not {s:?}")) } fn run(cmd: Cmd, owner: Option) -> anyhow::Result { // Who "I" am: --owner, MIDAS_OWNER, or the worktree this runs in. let who = || owner.clone().unwrap_or_else(cli::owner); match cmd { Cmd::Take { machine, node, purpose, wait, fastest_for, next } => { let owner = who(); collab::mention_waiting(&owner); cli::take(&cli::Take { owner, machine, node, purpose, wait, mode: registry::Mode::Build, rank: fastest_for, next }) } Cmd::Run { machine, node, purpose, command } => { let owner = who(); collab::mention_waiting(&owner); cli::run(&owner, &machine, node, purpose, &command) } Cmd::Land(LandCmd::Take { purpose, wait }) => cli::land_take(&who(), purpose.as_deref(), wait), Cmd::Land(LandCmd::Renew { step }) => cli::land_renew(&who(), step.as_deref()), Cmd::Land(LandCmd::Release { outcome, sha }) => cli::land_release(&who(), outcome.as_deref(), sha.as_deref()), Cmd::Land(LandCmd::Status) => cli::land_status(), Cmd::Land(LandCmd::Targets { base, pick, record, json }) => cli::land_targets(base.as_deref(), pick.as_deref(), record, json, &who()), Cmd::Project { act: Some(a), .. } => cli::project_act(a, &who()), Cmd::Project { get, repo, act: None } => cli::project(get.as_deref(), repo), Cmd::Claude(c) => { let home = PathBuf::from(std::env::var("HOME").map_err(|_| anyhow::anyhow!("no HOME"))?); match c { ClaudeCmd::Install { quiet } => claude::install(&home, quiet), ClaudeCmd::Uninstall => claude::uninstall(&home), } } Cmd::SketchShot { page, out, root, frame } => { let png = tree::sketch_shot(&root, &std::fs::read_to_string(&page)?, &frame)?; std::fs::write(&out, &png)?; println!("{} ({} KB)", out.display(), png.len() / 1024); Ok(0) } Cmd::Session { phase, reason, text } => { let branch = cli::branch(); match phase.as_str() { "label" => { // One line, short: a name for the session, not its prompt. let label: String = text.unwrap_or_default().split_whitespace().collect::>().join(" "); let label: String = label.chars().take(80).collect(); if !label.is_empty() && !collab::not_a_name(&label) { events::emit("session_label", json!({"actor": who(), "branch": branch, "label": label})); } } "end" => events::emit("session_end", json!({"actor": who(), "branch": branch, "reason": reason})), _ => events::emit("session_start", json!({"actor": who(), "branch": branch, "reason": reason, "repo": cli::repo_in(std::path::Path::new("."))})), } Ok(0) } Cmd::Say { words, re } => collab::say_cmd(&who(), &words, re.as_deref()), Cmd::Who { json, all } => collab::who_cmd(&who(), json, all), Cmd::Editing { files, hook, no_notes } => collab::editing_cmd(&who(), &files, hook.as_deref(), no_notes), Cmd::Ask { question, options, with } => { let v = client::post("/v1/decisions/add", &json!({"owner": who(), "question": question.join(" "), "options": options, "with": with}))?; let id = v["id"].as_str().unwrap_or("?"); eprintln!("asked as {id}: the person is mailed and sees it on the web page. Their answer comes to you{} \ as a note; carry on with what does not depend on it.", if with.is_empty() { String::new() } else { format!(" and {}", with.join(", ")) }); println!("{id}"); Ok(0) } Cmd::Admin { reason, minutes, done } => admin_cmd(&who(), &reason.join(" "), &minutes, done), Cmd::Decide { id: None, .. } | Cmd::Decisions => decisions(), Cmd::Decide { id: Some(id), choice, note } => { if choice.is_empty() { anyhow::bail!("say the answer: midas decide {id} "); } let d = client::post("/v1/decisions/answer", &json!({"owner": who(), "id": id, "choice": choice.join(" "), "note": note}))?; eprintln!("{id}: {} — told to the sessions involved", d["answer"].as_str().unwrap_or("?")); Ok(0) } Cmd::Hook(HookCmd::PreToolUse) => hook::pre_tool_use(), Cmd::Hook(HookCmd::PostToolUse) => hook::post_tool_use(owner.clone()), Cmd::Hook(HookCmd::UserPromptSubmit) => hook::user_prompt_submit(owner.clone()), Cmd::Hook(HookCmd::SessionStart) => hook::session_start(), Cmd::Hook(HookCmd::Work) => hook::work(owner.clone()), Cmd::Hook(HookCmd::Projects { event }) => hook::projects(&event), Cmd::Notes { hook, sent } => collab::notes_cmd(&who(), hook.as_deref(), sent), Cmd::Intent { text, minutes, clear } => { let text = (!clear).then(|| text.join(" ")).filter(|t| !t.trim().is_empty()); if text.is_none() && !clear { anyhow::bail!("say what you are doing: midas intent \"cargo test --workspace\" --minutes 20"); } let v = client::post("/v1/intent", &json!({"owner": who(), "text": text, "minutes": minutes}))?; eprintln!("{}: {}", v["node"].as_str().unwrap_or("?"), if clear { "intent cleared" } else { "those waiting will see it" }); Ok(0) } Cmd::Yield { undo } => { let v = client::post("/v1/yield", &json!({"owner": who(), "on": !undo}))?; let node = v["node"].as_str().unwrap_or("?"); eprintln!("{}", if undo { format!("keeping {node}") } else if v["released"] == true { format!("{node} released: nothing was running on it") } else { format!("{node} goes back when your current session on it ends") }); Ok(0) } Cmd::Reserve { list: true, .. } | Cmd::Reservations => { println!("{}", serde_json::to_string_pretty(&client::get("/v1/reservations")?)?); Ok(0) } Cmd::Reserve { namespace, from, why, .. } => { let v = client::post("/v1/reserve", &json!({"owner": who(), "namespace": namespace, "from": from, "why": why}))?; println!("{}", v["number"]); Ok(0) } Cmd::Todo(TodoCmd::Add { target, text }) => { let v = client::post("/v1/todos/add", &json!({"owner": who(), "for": target, "text": text.join(" ")}))?; eprintln!("left as {} for the next {target} session", v["id"].as_str().unwrap_or("?")); Ok(0) } Cmd::Todo(TodoCmd::List) => { for t in client::get("/v1/todos")?.as_array().into_iter().flatten() { let state = if t["done_at"].is_number() { format!("done by {}", t["done_by"].as_str().unwrap_or("?")) } else if let Some(c) = t["claimed_by"].as_str() { format!("shown to {c}") } else { "open".into() }; println!("{} for {} ({state}) {}", t["id"].as_str().unwrap_or("?"), t["for"].as_str().unwrap_or("?"), t["text"].as_str().unwrap_or("")); } Ok(0) } Cmd::Todo(TodoCmd::Take { hook }) => collab::todo_take_cmd(&who(), hook.as_deref()), Cmd::Todo(TodoCmd::Done { id, note }) => { client::post("/v1/todos/done", &json!({"owner": who(), "id": id, "note": note}))?; eprintln!("{id} done"); Ok(0) } Cmd::Wait { timeout } => { let owner = who(); let r = cli::wait(&owner, timeout); collab::mention_waiting(&owner); r } Cmd::Power { json } => power::show(json), Cmd::Stats { since: s, collab: true, json, .. } => stats::collab(since(&s)?, json), Cmd::Stats { since: s, nodes: true, node, json, step, .. } => { let step = step.as_deref().map(since).transpose()?; stats::nodes(since(&s)?, node.as_deref(), step, json) } Cmd::Stats { since: s, node, all, json, chart, .. } => stats::stats(since(&s)?, node.as_deref(), all, json, chart.as_deref()), Cmd::Release { node, force, keep_hosted } => { let owner = who(); if keep_hosted { if let Some(cfg) = host::hosted_by(&owner) { eprintln!("kept {}: it runs the hosted bot {} (midas bot stop --name {} gives it back)", cfg.node, cfg.name, cfg.name); return Ok(0); } } collab::mention_waiting(&owner); cli::release(&owner, node.as_deref(), force) } Cmd::Renew { command } => cli::renew(&who(), command.as_deref()), Cmd::Mine => cli::mine(&who()), Cmd::Whoami => { println!("{}", who()); Ok(0) } Cmd::Faster { than, machine, fastest_for } => { let enc = crate::hub::pct_encode; let v = client::get(&format!("/v1/faster?owner={}&machine={}&than={}{}", enc(&who()), enc(&machine), enc(&than), fastest_for.map(|f| format!("&rank={}", enc(&f))).unwrap_or_default()))?; match v["node"].as_str() { Some(n) => { println!("{n}"); Ok(0) } None => Ok(1), } } Cmd::Status { json, recent } => cli::status(json, recent, &who()), Cmd::Position => { println!("{}", client::get(&format!("/v1/position?owner={}", who()))?.as_str().unwrap_or("?")); Ok(0) } Cmd::Log { since: s, kind, node, actor, json } => { cli::log(&events::Filter { since: since(&s)?, kinds: kind, node, actor }, json) } Cmd::Explain { node, since: s } => cli::explain(&node, since(&s)?), Cmd::Drain { node, why } | Cmd::Nodes(NodesCmd::Drain { node, why }) => cli::drain(&node, Some(&why), &who()), Cmd::Undrain { node } | Cmd::Nodes(NodesCmd::Undrain { node }) => cli::drain(&node, None, &who()), Cmd::Nodes(NodesCmd::List) => cli::nodes_list(), Cmd::Nodes(NodesCmd::Add { id, machine, address, port, gpu, renderer }) => { client::post("/v1/nodes/add", &json!({ "id": id, "machine": machine, "address": address, "ssh_port": port, "gpu": gpu, "renderer": renderer.unwrap_or_else(|| if gpu { "GPU".into() } else { "CPU".into() }), }))?; println!("{id} added. On that machine its owner runs: sudo midas setup {id}"); Ok(0) } Cmd::Nodes(NodesCmd::Remove { id }) => { client::post("/v1/nodes/remove", &json!({"id": id}))?; println!("{id} removed"); Ok(0) } Cmd::Nodes(NodesCmd::Rename { id, to }) => { client::post("/v1/nodes/rename", &json!({"id": id, "to": to}))?; println!("{id} is now {to}. It is out of the pool until its machine's owner runs: sudo midas setup {to}\n\ (that keeps the node's checkout, build directory and keys; nothing is copied)"); Ok(0) } Cmd::Check { verbose } => check::check(verbose), Cmd::SshConfig { identity, known_hosts, flush, write } => { sshcfg::ssh_config(&sshcfg::Opts::agent(identity, known_hosts, flush, write)) } Cmd::Holds { node } => flush::holds(&node), Cmd::Flush { node } => flush::flush(&node), Cmd::Mcp => mcp::serve(), Cmd::Hub(HubCmd::Serve { listen }) => hub::serve(listen.as_deref()), Cmd::Hub(HubCmd::AdminSetup { user, rp_id, origins, max_minutes }) => admin::setup(&user, &rp_id, &origins, max_minutes), Cmd::Hub(HubCmd::AdminEnroll { line, remove }) => admin::enroll(Some(line.join(" ").as_str()).filter(|l| !l.is_empty()), remove.as_deref()), Cmd::Hub(HubCmd::AdminApply) => admin::apply(), Cmd::Hub(HubCmd::SelfUpdate { next }) => release::self_update(next.as_deref().unwrap_or(std::path::Path::new(release::NEXT))), Cmd::Sign(SignCmd::Keygen { key }) => release::keygen(&key.map(std::path::PathBuf::from).unwrap_or_else(release::default_key)), Cmd::Sign(SignCmd::Public { key }) => release::public(&key.map(std::path::PathBuf::from).unwrap_or_else(release::default_key)), Cmd::Sign(SignCmd::Build { file, key }) => release::sign(&key.map(std::path::PathBuf::from).unwrap_or_else(release::default_key), &file), Cmd::Sign(SignCmd::Verify { file, pubkey, sig }) => release::verify_cmd(&pubkey, &file, sig.as_deref()), Cmd::Hub(HubCmd::Setup { listen, forgejo, forgejo_api, repos, agent_keys, node_binaries, self_update, release_key }) => hubsetup::setup(hubsetup::Args { listen, forgejo_ssh: forgejo, forgejo_api, repos, agent_keys, node_binaries, self_update, release_key, }), Cmd::Hub(HubCmd::Caller(CallerCmd::Add { name, forgejo_token, role })) => hubsetup::caller_add(&name, forgejo_token, role.as_deref()), Cmd::Hub(HubCmd::Caller(CallerCmd::Role { name, role })) => hubsetup::caller_role(&name, &role), Cmd::Acp { mirror: false, .. } => acp::run(), Cmd::Acp { mirror: true, agent } => tap::run(agent), Cmd::Later { text, at, after, cancel } => { let text = text.join(" "); println!("{}", sessions::later_self(at.as_deref(), after.as_deref(), Some(text.as_str()).filter(|t| !t.is_empty()), cancel)?); Ok(0) } Cmd::Await { text, steps, secret, url, done } => { let text = text.join(" "); println!("{}", sessions::await_self(Some(text.as_str()), steps.as_deref(), secret.as_deref(), url.as_deref(), done)?); Ok(0) } Cmd::Show { file, caption, tech } => { println!("{}", sessions::show(&file, caption.as_deref(), tech.as_deref())?); Ok(0) } Cmd::Sessions(SessionsCmd::Run) => sessions::runner(), Cmd::Sessions(SessionsCmd::Answer) => { let mut job = String::new(); std::io::Read::read_to_string(&mut std::io::stdin(), &mut job)?; ask::run(&serde_json::from_str(&job).map_err(|e| anyhow::anyhow!("a question's job, as JSON: {e}"))?); Ok(0) } Cmd::Sessions(SessionsCmd::Scout) => { let mut job = String::new(); std::io::Read::read_to_string(&mut std::io::stdin(), &mut job)?; tree::scout(&serde_json::from_str(&job).map_err(|e| anyhow::anyhow!("a round's job, as JSON: {e}"))?); Ok(0) } Cmd::Sessions(SessionsCmd::List) => sessions::list_cmd(), Cmd::Sessions(SessionsCmd::AddProject { project }) => { println!("{}", sessions::add_project(&project)?); Ok(0) } Cmd::Sessions(SessionsCmd::Finish { sha, drop }) => sessions::finish_cmd(sha.as_deref(), drop), Cmd::Sessions(SessionsCmd::Import { paths, claude_ai, cwd, from, dry_run, replace }) => import::import_cmd(&paths, claude_ai, &cwd, from.as_deref(), dry_run, replace), Cmd::Sessions(SessionsCmd::Create { name, brief, project, base }) => sessions::create_cmd(&name, &brief, project.as_deref(), base.as_deref()), Cmd::Sessions(SessionsCmd::Start { prompt, project, base, mode, model, agent }) => sessions::start_cmd(&prompt.join(" "), project.as_deref(), base.as_deref(), mode.as_deref(), model.as_deref(), agent.as_deref()), Cmd::ZedArchive => zedthreads::once(), Cmd::Memory(MemoryCmd::Sync { every, quiet }) => memory::sync_cmd(every, quiet), Cmd::Memory(MemoryCmd::Where) => memory::where_cmd(), Cmd::Account(AccountCmd::Add { name, role }) => { let v = client::post("/v1/accounts/add", &json!({"name": name, "role": role}))?; println!("{name} ({role}) added. Their setup link, good for a day:\n\n {}\n", setup_link(&v)); Ok(0) } Cmd::Account(AccountCmd::Reset { name }) => { let v = client::post("/v1/accounts/reset", &json!({"name": name}))?; println!("{name} starts over: password, code secret, recovery codes and sessions are gone. Their setup link, good for a day:\n\n {}\n", setup_link(&v)); Ok(0) } Cmd::Account(AccountCmd::Role { name, role }) => { client::post("/v1/accounts/role", &json!({"name": name, "role": role}))?; println!("{name} is {role}"); Ok(0) } Cmd::Account(AccountCmd::Remove { name }) => { client::post("/v1/accounts/remove", &json!({"name": name}))?; println!("{name} removed, and logged out"); Ok(0) } Cmd::Account(AccountCmd::List) => { for a in client::get_auth("/v1/accounts")?.as_array().into_iter().flatten() { let state = if a["locked"] == true { "locked".to_string() } else if a["ready"] == true { format!("{} recovery codes left", a["recovery_left"]) } else { "not set up yet".into() }; let seen = a["last_seen"].as_i64().map(|t| format!(" · seen {}", cli::ago(t))).unwrap_or_default(); println!("{:<16} {:<9} {state}{seen}", a["name"].as_str().unwrap_or("?"), a["role"].as_str().unwrap_or("?")); } Ok(0) } Cmd::Hub(HubCmd::Caller(CallerCmd::List)) => hubsetup::caller_list(), Cmd::Hub(HubCmd::Caller(CallerCmd::Remove { name })) => hubsetup::caller_remove(&name), Cmd::Hub(HubCmd::Git { node: Some(node), .. }) => mirror::serve_git(&node), Cmd::Hub(HubCmd::Git { key, .. }) => mirror::serve_key(&key.unwrap_or_default()), Cmd::Hub(HubCmd::PreReceive) => hosted::pre_receive(), Cmd::Hub(HubCmd::PostReceive) => hosted::post_receive(), Cmd::Hub(HubCmd::GitKey(c)) => cli::git_key(c), Cmd::Hub(HubCmd::Import { repo, public, description, from, lfs_from }) => cli::hub_import(&repo, public, &description, &crate::hosted::Source { git: from.as_deref(), lfs: lfs_from.as_deref() }), Cmd::Hub(HubCmd::Warm { node, dry_run }) => warm::warm(node.as_deref(), dry_run), Cmd::Hub(HubCmd::Backup) => hubsetup::backup(), Cmd::Hub(HubCmd::DeployBuild) => deploy::build_pending(), Cmd::Hub(HubCmd::DeployPublish) => deploy::publish_ready(), Cmd::Deploy { defer: Some(target), minutes, why, .. } => cli::deploy_defer(&target, minutes, why.as_deref().unwrap_or(""), &who()), Cmd::Deploy { hold: Some(why), .. } => cli::deploy_hold(Some(&why), &who()), Cmd::Deploy { release: true, .. } => cli::deploy_hold(None, &who()), Cmd::Deploy { target, sha, unverified, no_wait, .. } => cli::deploy(target.as_deref(), sha.as_deref(), unverified.as_deref(), no_wait, &who()), Cmd::Verified { sha, steps, scope, node } => cli::verified(sha, steps, scope, node, &who()), Cmd::Hub(HubCmd::Refresh { repo }) => mirror::repo_name(&repo).and_then(|r| { mirror::refresh(&r)?; println!("{} is current", mirror::mirror_path(&r).display()); Ok(0) }), Cmd::Update { machines, force, wait, src } => update::update(&machines, force, wait, src), Cmd::Setup { node, hub, memory, cpus, gpu, mounts, user, remove, image, disk, rebuild } => setup::setup(setup::Args { node, hub, memory, cpus, render_node: gpu, mounts, user, remove, image, disk_gb: disk, rebuild }), Cmd::Node(NodeCmd::AuthorizedKeys { user, key }) => node::authorized_keys(&user, key.as_deref()), Cmd::Node(NodeCmd::Session) => node::session(), Cmd::Node(NodeCmd::Gpu) => node::gpu_cmd(), Cmd::Node(NodeCmd::Guard) => node::guard(), Cmd::Node(NodeCmd::Register) => node::register(), Cmd::Node(NodeCmd::Update) => node::update(), Cmd::Node(NodeCmd::Status { node }) => nodectl::status(node.as_deref()), Cmd::Node(NodeCmd::Start { node }) => nodectl::control(node.as_deref(), "start"), Cmd::Node(NodeCmd::Stop { node }) => nodectl::control(node.as_deref(), "stop"), Cmd::Node(NodeCmd::Restart { node }) => nodectl::control(node.as_deref(), "restart"), Cmd::Node(NodeCmd::Logs { node, follow }) => nodectl::logs(node.as_deref(), follow), Cmd::Node(NodeCmd::Shell { node }) => nodectl::shell(node.as_deref()), Cmd::Node(NodeCmd::Forward { vm, pairs }) => forward::forward(&vm, &pairs), Cmd::Node(NodeCmd::Power { hub }) => power::report(&hub), Cmd::Node(NodeCmd::Apply) => flush::apply(), Cmd::Node(NodeCmd::Bot(NodeBotCmd::Start { mcp, timeout, command, env_stdin, bot })) => bot::node_start(&mcp, timeout, &command, env_stdin, bot.as_deref()), Cmd::Node(NodeCmd::Bot(NodeBotCmd::Mcp)) => bot::node_mcp(), Cmd::Node(NodeCmd::Bot(NodeBotCmd::Stop)) => bot::node_stop(), Cmd::Node(NodeCmd::Bot(NodeBotCmd::Status)) => bot::node_status(), Cmd::Bot(BotCmd::Start { machine, node, purpose, mcp, wait, timeout, agent, name, brief, agent_meta, inbox, idle, agent_mode, command }) => { let agent = match agent { Some(other) => { // midas's own Claude Code unless another agent is named. let own = other.is_none(); Some(bot::AgentStart { name, inbox, command: other.unwrap_or_else(acp::command), brief: brief.map(|p| std::fs::read_to_string(&p).map_err(|e| anyhow::anyhow!("reading --brief {}: {e}", p.display()))).transpose()?, meta: match agent_meta { Some(m) => Some(host::parse_meta(&m)?), None => own.then(acp::bot_fence), }, idle_s: host::parse_idle(&idle)?, mode: agent_mode.or_else(|| own.then(|| "default".into())), }) } None => None, }; bot::start(&bot::Start { take: cli::Take { owner: who(), machine, node, purpose, wait, mode: registry::Mode::Bot, rank: None, next: false }, mcp, timeout, command, agent, }) } Cmd::Bot(BotCmd::Mcp) => bot::mcp(&who()), Cmd::Remote(RemoteCmd::List) => remote::cli_list(), Cmd::Remote(RemoteCmd::Set { name, url }) => remote::cli_set(&name, &url), Cmd::Device(DeviceCmd::List) => device::cli_list(), Cmd::Device(DeviceCmd::Forget { id }) => client::post("/v1/devices/forget", &serde_json::json!({"id": id})).map(|_| 0), Cmd::Device(DeviceCmd::Mcp { id }) => device::serve_mcp(&id), Cmd::Device(DeviceCmd::Fake { code, hub, name }) => device::fake(&code, &hub, &name), Cmd::Bot(BotCmd::Token { target, env, stdin, remove, list }) => bot::token(target.as_deref(), &env, stdin, remove, list), Cmd::Bot(BotCmd::Stop { name }) => bot::stop(&who(), name.as_deref()), Cmd::Bot(BotCmd::Status { name }) => bot::status(&who(), name.as_deref()), Cmd::Bot(BotCmd::Log { name, lines }) => match host::find(name.as_deref(), &who()) { Some(cfg) => host::log(&cfg.name, lines), None => { eprintln!("no hosted bot {}", name.as_deref().unwrap_or("for this worktree")); Ok(1) } }, Cmd::Bot(BotCmd::Tell { name, text }) => match host::find(name.as_deref(), &who()) { Some(cfg) => host::tell(&cfg.name, &text), None => { eprintln!("no hosted bot {}", name.as_deref().unwrap_or("for this worktree")); Ok(1) } }, Cmd::Bot(BotCmd::Host { name }) => host::run(&name), Cmd::Bot(BotCmd::Setup { node, env, stdin, remove }) => botsetup::setup(botsetup::Args { node, env, stdin, remove }), } } fn main() -> ExitCode { // `midas status | head` closes the pipe early; that should end us quietly, // as it does any Unix tool, not panic in println!. // SAFETY: restoring a signal's default disposition at startup. unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL) }; let args: Vec = std::env::args().collect(); let name = Path::new(&args[0]).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); // sudo running this midas as its askpass, for `midas update`: the one // argument is sudo's prompt, not a command. let askpass = std::env::var_os(update::ASKPASS).is_some() && args.len() == 2; let result = match cli::as_alias(&name, &args[1..]) { _ if askpass => update::askpass(&args[1]), Some(r) => r, None => { let cli = Cli::parse(); run(cli.cmd, cli.owner) } }; match result { Ok(code) => ExitCode::from(code.clamp(0, 255) as u8), Err(e) => { eprintln!("midas: {e:#}"); ExitCode::from(1) } } }