git clone https://garage44.eu/jeroen/pinnacle.git.. /ui/src/command.rs
//! Starting a command as the terminal does: the commands built into the
//! system, or an installed app by name, as a std program is started
//! (`abi::STD_START` and a start message), its stdin, stdout and stderr on
//! channels of their own and its exit code watched. The terminal starts
//! them for the person at the screen, the p2p service for a contact allowed
//! to run commands here (`docs/terminal-and-agent.md`): the same commands,
//! and nothing else, either way.
use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_json::Value;
use pinnacle_records::start::{self, Start};
use pinnacle_rt::abi::STD_START;
use pinnacle_rt::fs::File;
use pinnacle_rt::{Channel, Handle, Process, fs};
/// The commands that come with the system, and what each does: `help`
/// lists them.
pub const COMMANDS: &[(&str, &str)] = &[
("help", "These commands"),
("info", "This device: cores, memory, time up"),
("devices", "The hardware found, and the driver of each"),
("echo", "Its words, back"),
("std-check", "Rust's std at work: a plain program's output"),
("ask", "Three questions, answered here"),
("palette", "The system's colours, as an image"),
(
"frits",
"Frits scripts: frits run <script>, test, check, examples; alone, type lines",
),
(
"verbs",
"The services that say what they can do: each one's name is a command",
),
(
"agent",
"Ask the agent: +service and @file give it those, the rest is the task; agent undo undoes the last",
),
("ls", "The files in a folder: ls, or ls and its path"),
("cat", "What a file holds, as text"),
("mkdir", "A new folder"),
(
"rm",
"Removes a file; rm -r a folder and all in it, once you say yes",
),
("cp", "A file copied: cp from to"),
("mv", "A file moved or renamed: mv from to"),
("touch", "An empty file, if there is none"),
(
"head",
"A file's first lines: head file, head -n 20 file; after a |, the first rows",
),
(
"tail",
"A file's last lines, read from its end: tail -n 50 file; after a |, the last rows",
),
(
"grep",
"The lines of files that hold a text: grep error file, grep -r -i error folder",
),
("wc", "Lines, words and bytes of files; after a |, how many rows"),
(
"find",
"Files and folders by name, everywhere under a folder: find . txt",
),
(
"du",
"How much each folder holds, all in it counted: du, du data:/",
),
("df", "The disks: how large, how full"),
(
"hex",
"A file's bytes as hex, 512 of them from an offset: hex file 4096",
),
("ps", "The programs that run: number, threads, memory, time up"),
(
"kill",
"Ends a program, by its number from ps or its name; asks first for a system one",
),
(
"services",
"The services programs registered, which commands and apps reach",
),
(
"log",
"What the kernel and the programs wrote: log, log 200, log error",
),
(
"apps",
"The installed apps, their versions and the rights they have",
),
(
"net",
"The network: address, router, name server, IPv6; net on, net off",
),
(
"lookup",
"A name's address, from the name server: lookup example.org",
),
(
"ping",
"Whether a host answers, and how fast: four HTTPS requests (HTTP on another port given)",
),
(
"fetch",
"A URL over HTTP(S): its text, or saved to a file: fetch url file",
),
("date", "The date and time here, and in UTC"),
("env", "The environment a command gets"),
("restart", "Restarts the device, once you say yes"),
("clear", "An empty screen"),
];
/// The file commands: one program, `files`, which tells them apart by the
/// name it was started as.
pub const FILE_COMMANDS: [&str; 15] = [
"ls", "cat", "mkdir", "rm", "cp", "mv", "touch", "head", "tail", "grep", "wc", "find", "du", "df", "hex",
];
/// The system's commands: one program, `admin`, told apart the same way.
pub const ADMIN_COMMANDS: [&str; 12] = [
"ps", "kill", "services", "log", "apps", "net", "lookup", "ping", "fetch", "date", "env", "restart",
];
/// What [`copy_file`] moves at a time.
const CHUNK: usize = 256 * 1024;
/// Year, month and day from days since 1970 (Howard Hinnant's
/// civil-from-days).
fn civil(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(yoe + era * 400 + i64::from(month <= 2), month, day)
}
/// When a file changed, in UTC; nothing without a clock.
pub fn when(seconds: u64) -> String {
if seconds == 0 {
return String::new();
}
let (y, m, d) = civil((seconds / 86_400) as i64);
let minute = seconds % 86_400 / 60;
alloc::format!("{y}-{m:02}-{d:02} {:02}:{:02}", minute / 60, minute % 60)
}
/// A file's size, said: bytes, then KB, MB, GB, TB to one decimal.
pub fn size(bytes: u64) -> String {
const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"];
if bytes < 1024 {
return alloc::format!("{bytes} B");
}
let (mut value, mut unit) = (bytes as f64 / 1024.0, 0);
while value >= 1024.0 && unit < UNITS.len() - 1 {
value /= 1024.0;
unit += 1;
}
alloc::format!("{value:.1} {}", UNITS[unit])
}
/// The file `from` copied to the path `to` (made, or emptied first), a
/// quarter megabyte at a time: one call copies at most 16 MiB. What went
/// wrong, said, if it could not be.
pub fn copy_file(from: &str, to: &str) -> Result<(), String> {
let total = fs::stat(from).map_or(0, |s| s.size);
if !fs::write(to, &[]) {
return Err(alloc::format!("{to} could not be written"));
}
let mut at = 0u64;
while at < total {
let Some(part) = fs::read_at(from, at, CHUNK.min((total - at) as usize)) else {
return Err(alloc::format!("{from} could not be read"));
};
if part.is_empty() || !fs::write_at(to, at, &part) {
return Err(alloc::format!("{to} could not be written"));
}
at += part.len() as u64;
}
Ok(())
}
/// Where `cd` with nothing after it goes: the data vault once it is open,
/// else the system disk.
pub fn home() -> &'static str {
if fs::disk("data").is_some() {
"data:/"
} else {
"system:/"
}
}
/// The installed apps a command line may name.
pub fn apps() -> Vec<String> {
// Each a folder, listed with a `/` after its name.
fs::list("system:/apps")
.unwrap_or_default()
.into_iter()
.map(|a| String::from(a.trim_end_matches('/')))
.collect()
}
/// A command that runs: its stdout, stderr, and the channel its exit code
/// comes on, each dropped by its holder as it closes; its stdin. In a
/// pipeline these are the last command's, but stdin, which is the
/// first's: a question asked before the `|` is answered there.
pub struct Run {
pub process: Process,
pub streams: [Option<Channel>; 3],
pub input: Channel,
/// The commands before the last `|`, if any.
pub upstream: Upstream,
}
impl Run {
/// Ends the command, and every one before it in its pipeline.
pub fn kill(&self) -> bool {
self.upstream.kill();
self.process.kill()
}
}
/// The commands of a pipeline before its last: ended when the last is
/// let go, for then nothing reads what they give.
#[derive(Default)]
pub struct Upstream(pub Vec<Process>);
impl Upstream {
pub fn kill(&self) {
for process in &self.0 {
process.kill();
}
}
}
impl Drop for Upstream {
fn drop(&mut self) {
self.kill();
}
}
/// Starts `line`'s command; the reason when it cannot start.
pub fn start(line: &str) -> Result<Run, String> {
start_in(line, home())
}
/// Starts `line`'s command in the folder `cwd` (`disk:/path`): what its
/// relative paths are relative to. Commands joined by `|` make a
/// pipeline: each one's stdout the next one's stdin
/// (`pinnacle_records::pipe`).
pub fn start_in(line: &str, cwd: &str) -> Result<Run, String> {
if line.split_whitespace().next() == Some("agent") {
let words: Vec<String> = line.split_whitespace().skip(1).map(String::from).collect();
return start_agent(&words);
}
use pinnacle_records::pipe;
let stages = pipe::stages(line);
if stages.len() > 1 && stages.iter().any(|s| s.is_empty()) {
return Err("A | goes between two commands: ls | sort Size".into());
}
let mut commands: Vec<Vec<String>> = Vec::new();
for (i, stage) in stages.iter().enumerate() {
let words = pipe::lex(stage);
// `> file` at the line's end: what the last command gives goes
// through `save` into the file.
match pipe::redirect(&words)? {
Some(_) if i + 1 < stages.len() => {
return Err("> goes at the line's end: ls | sort Size > list.txt".into());
}
Some((words, file, append)) => {
if words.is_empty() {
return Err("A command before the >: ls > list.txt".into());
}
commands.push(words);
let mut save = alloc::vec![String::from("save")];
if append {
save.push("-a".into());
}
save.push(file);
commands.push(save);
}
None => commands.push(words.into_iter().map(|w| w.text).collect()),
}
}
let (input, mut stdin) = Channel::pair();
let mut upstream = Upstream::default();
let count = commands.len();
for (i, words) in commands.into_iter().enumerate() {
let last = i + 1 == count;
let (process, out, err, watch) = spawn(words, cwd, stdin, i > 0, last)?;
if last {
return Ok(Run {
process,
streams: [Some(out), err, Some(watch)],
input,
upstream,
});
}
// What it gives is what the next one reads.
upstream.0.push(process);
stdin = out;
}
Err("No command".into())
}
/// One command of a line, started with `stdin` (the program's end of it),
/// `PIPED` set when that is the command before it, and stderr only when
/// `stderr` (the last of a pipeline): its process, stdout, stderr and the
/// channel its exit code comes on.
fn spawn(
mut words: Vec<String>,
cwd: &str,
stdin: Channel,
piped: bool,
stderr: bool,
) -> Result<(Process, Channel, Option<Channel>, Channel), String> {
// A service's name runs its verbs, through the command `verbs`.
// `p2p`, or `p2p@Bo`: the same service on a contact's device.
if words.first().is_some_and(|w| {
let service = w.split('@').next().unwrap_or(w);
crate::verbs::SERVICES.iter().any(|(s, _)| *s == service)
}) {
words.insert(0, "verbs".into());
}
let Some(name) = words.first().map(String::as_str) else {
return Err("No command".into());
};
if name == "agent" {
return Err("The agent takes no part in a pipeline: start it alone".into());
}
// After a `|`, `head`, `tail`, `grep` and `wc` read what comes in,
// unless they are given files: `head 5`, `grep error`, but `grep error
// log.txt` reads the file.
let given: Vec<&String> = words[1..]
.iter()
.filter(|w| !w.starts_with('-') && w.parse::<usize>().is_err())
.collect();
let files_given = given.len() > usize::from(name == "grep");
let as_filter = piped && !files_given && pinnacle_records::pipe::AS_FILTERS.contains(&name);
let program = if as_filter || pinnacle_records::pipe::FILTERS.iter().any(|(f, _)| *f == name) {
"filter"
} else if FILE_COMMANDS.contains(&name) {
"files"
} else if ADMIN_COMMANDS.contains(&name) {
"admin"
} else {
name
};
let builtin = (COMMANDS.iter().any(|(c, _)| *c == name) && !matches!(name, "help" | "clear"))
|| matches!(program, "filter" | "files" | "admin");
let installed =
!name.contains(['/', ':', '.']) && fs::stat(&alloc::format!("system:/apps/{name}/program")).is_some();
if !builtin && !installed {
return Err(alloc::format!("No command named “{name}”: try help"));
}
let (out, their_out) = Channel::pair();
let (first, theirs) = Channel::pair();
let mut env = alloc::vec![(String::from(start::PWD), String::from(cwd))];
if piped {
env.push((pinnacle_records::pipe::PIPED.into(), "1".into()));
}
let mut handles = alloc::vec![stdin.0, their_out.0];
// Before the last `|`, stderr goes nowhere: the terminal reads the
// last command's only, and one that fails says so in its status, which
// the command after it passes on.
let err = stderr.then(|| {
let (err, their_err) = Channel::pair();
handles.push(their_err.0);
err
});
let message = Start {
args: words.clone(),
env,
streams: [
start::CHANNEL,
start::CHANNEL,
if stderr { start::CHANNEL } else { start::NULL },
],
};
// It waits on the channel the program gets as handle 1.
first.send(&message.encode(), handles);
let (_, process, watch) = pinnacle_rt::spawn_watched(program, STD_START, alloc::vec![theirs.0])
.ok_or_else(|| alloc::format!("“{name}” would not start"))?;
Ok((process, out, err, watch))
}
/// A service by the name a command line gives it: `p2p` here, or
/// `workbench@Bench` on the contact named Bench's device, through the p2p
/// service (`crate::p2p::remote_service`).
pub fn connect_service(name: &str) -> Option<Channel> {
match name.split_once('@') {
None => pinnacle_rt::connect(name),
Some((service, contact)) => {
let client = crate::p2p::Client::connect(2000)?;
let key = client
.contacts(&mut Vec::new())
.into_iter()
.find(|c| c.name.eq_ignore_ascii_case(contact))?
.key;
crate::p2p::remote_service(&key, service)
}
}
}
/// What the agent's gatekeeper is given for a task (`docs/agent-environment.md`):
/// these and nothing else, for it is started sealed.
pub struct Grants {
pub model: Channel,
/// To the display server's confirmation (`crate::confirm`).
pub confirm: Channel,
/// The task's log, to read and add to.
pub log: File,
pub services: Vec<(String, Channel)>,
/// Each file by the name the model sees, with its path for the log.
pub files: Vec<(String, String, File)>,
/// Fewer actions than the gatekeeper's own budget.
pub actions: Option<u32>,
}
/// Where each task's log is kept, one file a task, in the vault when
/// there is one.
pub fn tasks() -> &'static str {
if fs::disk("data").is_some() {
"data:/agent/tasks"
} else {
"system:/agent/tasks"
}
}
/// The task's first entry, which the starter writes: what was asked and
/// what it was given, files by their paths, so `agent undo` can give the
/// same again.
pub fn begin_log(request: &str, grants: &Grants) {
let files = grants
.files
.iter()
.map(|(name, path, _)| {
Value::object([("name", name.as_str().into()), ("path", path.as_str().into())])
})
.collect();
let services = grants
.services
.iter()
.map(|(name, _)| Value::from(name.as_str()))
.collect();
let entry = Value::object([
("task", request.into()),
("services", Value::Array(services)),
("files", Value::Array(files)),
("time", pinnacle_rt::clock().into()),
]);
let empty = grants.log.stat().is_some_and(|s| s.size == 0);
grants.log.append(&pinnacle_records::log::entry(
alloc::format!("{entry}").as_bytes(),
empty,
));
}
/// A new task's log, in [`tasks`].
pub fn new_log() -> Option<File> {
let dir = tasks();
fs::create_dir(&dir[..dir.len() - "/tasks".len()]);
fs::create_dir(dir);
let name = pinnacle_rt::clock() * 1000 + pinnacle_rt::time() % 1000;
File::open(&alloc::format!("{dir}/{name:015}"), fs::READ | fs::APPEND)
}
/// `agent …` from a command line: first `+name` gives it a service, `@path`
/// a file (in the vault without a label), then the task; `agent undo`
/// undoes the last task, given what it was given.
fn start_agent(words: &[String]) -> Result<Run, String> {
let model = crate::model::connect().ok_or("The model service is not running")?;
let confirm =
pinnacle_rt::connect(crate::confirm::SERVICE).ok_or("Nothing can ask you: no display server")?;
if words.first().is_some_and(|w| w == "undo") {
return undo_last(model, confirm);
}
let mut services = Vec::new();
let mut files = Vec::new();
let mut request = Vec::new();
for word in words {
// Grants come first: from the task's first word on, a `+` or an
// `@` is the task's own text (`1 + 1`, an address).
if !request.is_empty() {
request.push(word.clone());
} else if let Some(name) = word.strip_prefix('+').filter(|n| !n.is_empty()) {
let channel = connect_service(name).ok_or_else(|| alloc::format!("No service named “{name}”"))?;
services.push((String::from(name), channel));
} else if let Some(path) = word.strip_prefix('@').filter(|p| !p.is_empty()) {
let path = match path.contains(':') {
true => String::from(path),
false if fs::disk("data").is_some() => {
alloc::format!("data:/{}", path.trim_start_matches('/'))
}
false => alloc::format!("system:/{}", path.trim_start_matches('/')),
};
let file =
File::open(&path, fs::READ | fs::WRITE).ok_or_else(|| alloc::format!("No file {path}"))?;
let name = String::from(path.rsplit('/').next().unwrap_or(&path));
files.push((name, path, file));
} else {
request.push(word.clone());
}
}
if request.is_empty() {
return Err("agent and what to do: agent +p2p Tell Anna I am late".into());
}
let request = request.join(" ");
let log = new_log().ok_or("The task's log could not be made")?;
let grants = Grants {
model,
confirm,
log,
services,
files,
actions: None,
};
begin_log(&request, &grants);
let mut args = alloc::vec![String::from("agent")];
args.extend(request.split(' ').map(String::from));
start_agent_with(args, grants)
}
/// `agent undo`: the newest task's log, and what it was given, again.
fn undo_last(model: Channel, confirm: Channel) -> Result<Run, String> {
let newest = fs::list(tasks())
.and_then(|names| names.into_iter().filter(|n| !n.ends_with('/')).max())
.ok_or("No task to undo")?;
let path = alloc::format!("{}/{newest}", tasks());
let log = File::open(&path, fs::READ | fs::APPEND).ok_or("The task's log could not be read")?;
let (services, files) = granted_in(&log)?;
let grants = Grants {
model,
confirm,
log,
services,
files,
actions: None,
};
start_agent_with(alloc::vec!["agent".into(), "undo".into()], grants)
}
/// What the task whose log this is was given, given again.
#[allow(clippy::type_complexity)]
pub fn granted_in(log: &File) -> Result<(Vec<(String, Channel)>, Vec<(String, String, File)>), String> {
let data = log.read().unwrap_or_default();
let first = pinnacle_records::log::entries(&data)
.and_then(|e| e.first().copied())
.and_then(|e| pinnacle_json::parse(core::str::from_utf8(e).ok()?).ok())
.ok_or("The task's log is empty")?;
let mut services = Vec::new();
for name in first.get("services").as_array().unwrap_or(&[]) {
let name = name.as_str().unwrap_or("");
let channel =
connect_service(name).ok_or_else(|| alloc::format!("{name} is not there to undo with"))?;
services.push((String::from(name), channel));
}
let mut files = Vec::new();
for f in first.get("files").as_array().unwrap_or(&[]) {
let (name, path) = (
f.get("name").as_str().unwrap_or(""),
f.get("path").as_str().unwrap_or(""),
);
let file = File::open(path, fs::READ | fs::WRITE).ok_or_else(|| alloc::format!("No file {path}"))?;
files.push((String::from(name), String::from(path), file));
}
Ok((services, files))
}
/// Starts the gatekeeper, sealed, with `args` and `grants`: the handles
/// after its streams, named in order by `AGENT_GRANTS`, those that do not
/// fit the start message in messages after it.
pub fn start_agent_with(args: Vec<String>, grants: Grants) -> Result<Run, String> {
let mut names = alloc::vec![String::from("model"), "confirm".into(), "log".into()];
let mut extra: Vec<Handle> = alloc::vec![grants.model.0, grants.confirm.0, grants.log.0];
for (name, channel) in grants.services {
names.push(alloc::format!("service:{name}"));
extra.push(channel.0);
}
for (name, _, file) in grants.files {
names.push(alloc::format!("file:{name}"));
extra.push(file.0);
}
let (input, their_in) = Channel::pair();
let (out, their_out) = Channel::pair();
let (err, their_err) = Channel::pair();
let (first, theirs) = Channel::pair();
let room = pinnacle_rt::abi::MAX_MESSAGE_HANDLES - 3;
let later: Vec<Handle> = if extra.len() > room {
extra.split_off(room)
} else {
Vec::new()
};
let batches = later.len().div_ceil(pinnacle_rt::abi::MAX_MESSAGE_HANDLES);
let mut env = alloc::vec![
(String::from("AGENT_GRANTS"), names.join(" ")),
("EXTRA_MESSAGES".into(), alloc::format!("{batches}")),
];
if let Some(actions) = grants.actions {
env.push(("AGENT_ACTIONS".into(), alloc::format!("{actions}")));
}
let message = Start {
args,
env,
streams: [start::CHANNEL, start::CHANNEL, start::CHANNEL],
};
let mut handles = alloc::vec![their_in.0, their_out.0, their_err.0];
handles.extend(extra);
first.send(&message.encode(), handles);
let mut later = later.into_iter();
for _ in 0..batches {
let batch: Vec<Handle> = later
.by_ref()
.take(pinnacle_rt::abi::MAX_MESSAGE_HANDLES)
.collect();
first.send(b"grants", batch);
}
let (_, process, watch) = pinnacle_rt::spawn_sealed("agent", STD_START, alloc::vec![theirs.0])
.ok_or("The agent would not start")?;
Ok(Run {
process,
streams: [Some(out), Some(err), Some(watch)],
input,
upstream: Upstream::default(),
})
}