cargo.build, the WASI test runner, the console, and core.notify ordering
- cargo.build (native): one source copy, tests under WASI, release build to /state/cargo/builds/<n>/, process groups killed on cancel. The host writes the SDK copy to /plugins/cargo/sdk/ at start. - sausage test-runner: one instance per test, in parallel, with its own mount table (empty world, package folder at its path); answers core.lock, core.unlock, core.notify, core.log. - The console: rustyline, notifications while typing, ls/cat through the process view, methods, ps, log, activate, revert, stop, kill. - core.notify on stdout is handled in order, before the response.
This commit is contained in:
+320
-19
@@ -1,24 +1,325 @@
|
||||
//! The minimal console reads explicit JSON-RPC calls and the quit command.
|
||||
//! Console commands, readable results, and line editing with live notifications.
|
||||
use crate::Host;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use anyhow::{Result, bail};
|
||||
use rustyline::{DefaultEditor, ExternalPrinter, error::ReadlineError};
|
||||
use sausage_vfs::{Layer, Open};
|
||||
use serde_json::{Value, json};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// Read console lines until EOF or quit, and print each call's result.
|
||||
pub async fn run_input(host: Host) -> anyhow::Result<()> {
|
||||
let mut lines = BufReader::new(tokio::io::stdin()).lines();
|
||||
while let Some(line) = lines.next_line().await? {
|
||||
if line == "quit" {
|
||||
break;
|
||||
}
|
||||
let (method, params) = line.split_once(' ').unwrap_or((&line, "{}"));
|
||||
match serde_json::from_str(params) {
|
||||
Ok(params) => {
|
||||
let value = match host.call(method, params).await {
|
||||
Ok(value) | Err(value) => value,
|
||||
};
|
||||
println!("{value}");
|
||||
}
|
||||
Err(error) => eprintln!("{error}"),
|
||||
const HELP: &str = "text chat with the agent
|
||||
plugin.method {json} call a plugin
|
||||
ls [path] list a folder (default /)
|
||||
cat <path> read a file
|
||||
methods <plugin> show methods, params, types, and docs
|
||||
ps show pid, plugin, method, parent, state, age
|
||||
log [plugin or pid] [-n N] read the journal
|
||||
activate <plugin> <wasm> activate a version
|
||||
revert <plugin> restore the previous version
|
||||
stop <pid> request a graceful stop
|
||||
kill <pid> kill a process
|
||||
help show this help
|
||||
quit leave the console";
|
||||
|
||||
async fn read(host: &Host, path: &str) -> Result<Vec<u8>> {
|
||||
let fs = host.filesystem().await?;
|
||||
let file = fs
|
||||
.open(
|
||||
path,
|
||||
Open {
|
||||
follow: true,
|
||||
..Open::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let mut bytes = Vec::new();
|
||||
loop {
|
||||
let chunk = file.read(bytes.len() as u64, 65536).await?;
|
||||
if chunk.is_empty() {
|
||||
return Ok(bytes);
|
||||
}
|
||||
bytes.extend(chunk);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn pretty(value: &Value) -> Result<String> {
|
||||
Ok(serde_json::to_string_pretty(value)?)
|
||||
}
|
||||
async fn call(host: &Host, method: &str, params: Value, chat: bool) -> Result<String> {
|
||||
match host.call(method, params).await {
|
||||
Ok(value) if chat => Ok(value["text"]
|
||||
.as_str()
|
||||
.or_else(|| value.as_str())
|
||||
.map(str::to_owned)
|
||||
.unwrap_or(pretty(&value)?)),
|
||||
Ok(value) => pretty(&value),
|
||||
Err(error) => Ok(format!("error: {}", pretty(&error)?)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute one input line without terminal IO. The caller handles quit after printing.
|
||||
pub async fn execute_line(host: &Host, line: &str) -> Result<String> {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let (command, rest) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
|
||||
let rest = rest.trim();
|
||||
let words: Vec<_> = rest.split_whitespace().collect();
|
||||
match command {
|
||||
"help" if words.is_empty() => Ok(HELP.into()),
|
||||
"quit" if words.is_empty() => Ok("Goodbye.".into()),
|
||||
"ls" if words.len() <= 1 => {
|
||||
let fs = host.filesystem().await?;
|
||||
let mut entries = fs.list(words.first().copied().unwrap_or("/")).await?;
|
||||
entries.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.map(|e| format!("{}{}", e.name, if e.directory { "/" } else { "" }))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"))
|
||||
}
|
||||
"cat" if !rest.is_empty() => Ok(String::from_utf8(read(host, rest).await?)?),
|
||||
"methods" if words.len() == 1 => {
|
||||
host.refresh_graph()
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||
let document: Value = serde_json::from_slice(
|
||||
&read(
|
||||
host,
|
||||
&format!("/proc/core/plugins/{}/discover.json", words[0]),
|
||||
)
|
||||
.await?,
|
||||
)?;
|
||||
let mut lines = Vec::new();
|
||||
for method in document["methods"]
|
||||
.as_array()
|
||||
.ok_or_else(|| anyhow::anyhow!("discovery document has no methods"))?
|
||||
{
|
||||
let params = method["params"]
|
||||
.as_array()
|
||||
.map(|params| {
|
||||
params
|
||||
.iter()
|
||||
.map(|p| {
|
||||
format!(
|
||||
"{}: {}",
|
||||
p["name"].as_str().unwrap_or("?"),
|
||||
p["schema"]["type"].as_str().unwrap_or("any")
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
})
|
||||
.unwrap_or_default();
|
||||
lines.push(format!(
|
||||
"{}.{}({}) -> {}",
|
||||
words[0],
|
||||
method["name"].as_str().unwrap_or("?"),
|
||||
params,
|
||||
method["result"]["schema"]["type"].as_str().unwrap_or("any")
|
||||
));
|
||||
for field in ["summary", "description"] {
|
||||
if let Some(doc) = method[field].as_str() {
|
||||
lines.push(format!(" {doc}"));
|
||||
}
|
||||
}
|
||||
if let Some(params) = method["params"].as_array() {
|
||||
for p in params {
|
||||
if let Some(doc) = p["description"].as_str() {
|
||||
lines.push(format!(" {}: {doc}", p["name"].as_str().unwrap_or("?")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(lines.join("\n"))
|
||||
}
|
||||
"ps" if words.is_empty() => {
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();
|
||||
let mut processes: Vec<_> = host.processes().into_iter().collect();
|
||||
processes.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
let mut lines = vec!["PID PLUGIN METHOD PARENT STATE AGE".into()];
|
||||
lines.extend(processes.into_iter().map(|(pid, p)| {
|
||||
format!(
|
||||
"{} {} {} {} {} {}s",
|
||||
pid,
|
||||
p.plugin,
|
||||
p.method,
|
||||
p.parent.as_deref().unwrap_or("-"),
|
||||
p.state,
|
||||
now.saturating_sub(p.start_time) / 1000
|
||||
)
|
||||
}));
|
||||
Ok(lines.join("\n"))
|
||||
}
|
||||
"log" => {
|
||||
let mut params = json!({});
|
||||
let mut i = 0;
|
||||
while i < words.len() {
|
||||
if words[i] == "-n" {
|
||||
i += 1;
|
||||
let count: u64 = words
|
||||
.get(i)
|
||||
.ok_or_else(|| anyhow::anyhow!("log -n requires a count"))?
|
||||
.parse()?;
|
||||
params["limit"] = json!(count);
|
||||
} else if params.get("pid").is_none() && params.get("plugin").is_none() {
|
||||
let key = if words[i].len() > 36
|
||||
&& words[i]
|
||||
.get(words[i].len() - 36..)
|
||||
.is_some_and(|suffix| uuid::Uuid::try_parse(suffix).is_ok())
|
||||
{
|
||||
"pid"
|
||||
} else {
|
||||
"plugin"
|
||||
};
|
||||
params[key] = json!(words[i]);
|
||||
} else {
|
||||
bail!("usage: log [plugin or pid] [-n N]");
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
call(host, "core.log", params, false).await
|
||||
}
|
||||
"activate" if words.len() == 2 => {
|
||||
call(
|
||||
host,
|
||||
"core.activate",
|
||||
json!({"plugin":words[0],"wasm":words[1]}),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
}
|
||||
"revert" if words.len() == 1 => {
|
||||
call(host, "core.revert", json!({"plugin":words[0]}), false).await
|
||||
}
|
||||
"stop" | "kill" if words.len() == 1 => {
|
||||
call(
|
||||
host,
|
||||
&format!("core.{command}"),
|
||||
json!({"pid":words[0]}),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
}
|
||||
"help" | "quit" | "ls" | "methods" | "ps" | "activate" | "revert" | "stop" | "kill"
|
||||
| "cat" => bail!("invalid arguments for {command}; use help"),
|
||||
_ if command
|
||||
.split_once('.')
|
||||
.is_some_and(|(plugin, method)| !plugin.is_empty() && !method.is_empty()) =>
|
||||
{
|
||||
call(
|
||||
host,
|
||||
command,
|
||||
if rest.is_empty() {
|
||||
json!({})
|
||||
} else {
|
||||
serde_json::from_str(rest)?
|
||||
},
|
||||
false,
|
||||
)
|
||||
.await
|
||||
}
|
||||
_ => call(host, "agent.chat", json!({"text":line}), true).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Format text notifications dimly, while preserving other notification payloads.
|
||||
pub fn notification_text(notification: &Value) -> String {
|
||||
let params = ¬ification["params"];
|
||||
if params["name"] == "text" {
|
||||
let payload = ¶ms["params"];
|
||||
let text = payload["text"]
|
||||
.as_str()
|
||||
.or_else(|| payload.as_str())
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| payload.to_string());
|
||||
format!("\x1b[2m{text}\x1b[0m")
|
||||
} else {
|
||||
notification.to_string()
|
||||
}
|
||||
}
|
||||
fn indent(text: &str) -> String {
|
||||
text.lines()
|
||||
.map(|line| format!(" {line}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
/// Run the line editor on a dedicated thread, with notifications through its external printer.
|
||||
pub async fn run_input(host: Host) -> Result<()> {
|
||||
let history = host.0.world.state_dir("core").join("history");
|
||||
let (ready, started) = tokio::sync::oneshot::channel();
|
||||
let (sender, mut lines) = tokio::sync::mpsc::unbounded_channel::<
|
||||
Result<(String, tokio::sync::oneshot::Sender<bool>)>,
|
||||
>();
|
||||
// A detached terminal thread does not hold Tokio shutdown open at a blocked readline.
|
||||
std::thread::spawn(move || {
|
||||
let setup = (|| -> Result<_> {
|
||||
let mut editor = DefaultEditor::new()?;
|
||||
let _ = editor.load_history(&history);
|
||||
let printer = editor.create_external_printer()?;
|
||||
Ok((editor, printer))
|
||||
})();
|
||||
let (mut editor, printer) = match setup {
|
||||
Ok(value) => value,
|
||||
Err(error) => {
|
||||
let _ = ready.send(Err(error));
|
||||
return;
|
||||
}
|
||||
};
|
||||
if ready.send(Ok(printer)).is_err() {
|
||||
return;
|
||||
}
|
||||
let result = (|| -> Result<()> {
|
||||
loop {
|
||||
match editor.readline("> ") {
|
||||
Ok(line) => {
|
||||
editor.add_history_entry(&line)?;
|
||||
editor.save_history(&history)?;
|
||||
let (done, wait) = tokio::sync::oneshot::channel();
|
||||
if sender.send(Ok((line, done))).is_err()
|
||||
|| !wait.blocking_recv().unwrap_or(false)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(ReadlineError::Interrupted) => break,
|
||||
Err(ReadlineError::Eof) => break,
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = result {
|
||||
let _ = sender.send(Err(error));
|
||||
}
|
||||
});
|
||||
let mut printer = started.await??;
|
||||
let mut notifications = host.subscribe();
|
||||
let print_notifications = async move {
|
||||
loop {
|
||||
match notifications.recv().await {
|
||||
Ok(value) => printer.print(format!("{}\n", indent(¬ification_text(&value))))?,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => return Ok(()),
|
||||
}
|
||||
}
|
||||
};
|
||||
let commands = async {
|
||||
while let Some(line) = lines.recv().await {
|
||||
let (line, done) = line?;
|
||||
let text = execute_line(&host, &line)
|
||||
.await
|
||||
.unwrap_or_else(|error| format!("error: {error}"));
|
||||
if !text.is_empty() {
|
||||
println!("{}", indent(&text));
|
||||
}
|
||||
let quit = line.trim() == "quit";
|
||||
let _ = done.send(!quit);
|
||||
if quit {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
tokio::select! {result=commands=>result,result=print_notifications=>result}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user