use by_your_leave::config::Config;
use by_your_leave::human;
use by_your_leave::kernel::{CrashPoint, Kernel, KernelOptions};
use by_your_leave::protocol::human::{
AdapterView, EscalationView, HumanRequest, HumanResponse, PackView, StatusView,
};
use by_your_leave::sandbox::{self, Sandbox};
use by_your_leave::state::GoalStatus;
use serde_json::Value;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let rest = args.get(1..).unwrap_or_default();
let result = match args.first().map(String::as_str) {
Some("sandbox") => sandbox_cmd(rest),
Some("run") => run(rest),
Some(
cmd @ ("submit" | "undo" | "status" | "escalations" | "answer" | "policy" | "pack"
| "kill" | "release" | "events" | "watch" | "result" | "cancel" | "log"
| "trace" | "tree" | "samples" | "review" | "knowledge" | "replay" | "replays"
| "device" | "withdraw"),
) => client(cmd, rest),
Some("verify") => verify(rest),
_ => Err(USAGE.into()),
};
match result {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("{e}");
ExitCode::FAILURE
}
}
}
const USAGE: &str = "usage:
byleave sandbox install | remove | remove-old
byleave sandbox check --data DIR
byleave run --data DIR --config FILE [--goal TEXT] [--pack NAME] [--project NAME]
[--simulate] [--until-idle]
byleave submit --data DIR [--pack NAME] [--project NAME] [--simulate] TEXT
byleave undo --data DIR ACTION
byleave status --data DIR
byleave escalations --data DIR [--raw]
byleave answer --data DIR ID ANSWER [--note TEXT]
byleave policy --data DIR [set KEY VALUE] [--pack NAME | --global]
byleave result --data DIR GOAL
byleave pack --data DIR [load NAME | remove NAME]
byleave cancel --data DIR GOAL --reason TEXT
byleave kill --data DIR --reason TEXT
byleave release --data DIR --reason TEXT
byleave events --data DIR --goal ID
byleave watch --data DIR [--after SEQ]
byleave log --data DIR [--type TYPE] [--goal ID] [--text TEXT] [--after SEQ] [--limit N]
byleave trace --data DIR EVENT
byleave tree --data DIR GOAL
byleave samples --data DIR [--all]
Actions a role proposed that ran without asking, sampled for you to
review. The kernel's own runs of a pack's check criteria are not sampled.
byleave review --data DIR SAMPLE ok|concern [--note TEXT]
byleave knowledge --data DIR [accept ID [--note TEXT] | reject ID --reason TEXT
| revert SKILL --reason TEXT]
byleave replay --data DIR INVOCATION [--model BINDING]
byleave replays --data DIR [--invocation ID]
byleave verify --data DIR
byleave device --data DIR [enrol NAME [--recover] | revoke NAME --reason TEXT]
The owner devices that sign. Enrol the first one, or recover, from a
terminal run as administrator. Once one is enrolled, every command that
decides something is signed with Windows Hello.
byleave withdraw --data DIR ACTION --reason TEXT
Withdraw the approval of a class 3 action still in its delay.";
const VALUED: [&str; 13] = [
"--pack",
"--data",
"--config",
"--goal",
"--note",
"--reason",
"--after",
"--project",
"--type",
"--text",
"--limit",
"--model",
"--invocation",
];
fn flag(args: &[String], name: &str) -> Option<String> {
args.iter()
.position(|a| a == name)
.and_then(|i| args.get(i + 1).cloned())
}
fn has(args: &[String], name: &str) -> bool {
args.iter().any(|a| a == name)
}
fn positionals(args: &[String]) -> Vec<String> {
let mut out = Vec::new();
let mut skip = false;
for a in args {
if skip {
skip = false;
} else if VALUED.contains(&a.as_str()) {
skip = true;
} else if !a.starts_with("--") {
out.push(a.clone());
}
}
out
}
fn data_dir(args: &[String]) -> Result<PathBuf, String> {
flag(args, "--data")
.map(PathBuf::from)
.ok_or_else(|| USAGE.into())
}
fn sandbox_cmd(args: &[String]) -> Result<(), String> {
match args.first().map(String::as_str) {
#[cfg(windows)]
Some("install") => {
for line in sandbox::wfp::install()? {
println!("{line}");
}
println!(
"Agent network block installed for profile `{}`.",
sandbox::PROFILE
);
Ok(())
}
#[cfg(windows)]
Some("remove") => {
for line in sandbox::wfp::remove()? {
println!("{line}");
}
println!("Agent network block removed.");
Ok(())
}
#[cfg(windows)]
Some("remove-old") => {
for line in sandbox::wfp::remove_old()? {
println!("{line}");
}
println!("The network block Prospero installed is removed (D-72).");
Ok(())
}
Some("check") => {
let data = data_dir(args)?;
std::fs::create_dir_all(&data).map_err(|e| e.to_string())?;
drop(
by_your_leave::log::EventLog::open(data.join("log.db"))
.map_err(|e| e.to_string())?,
);
let options = KernelOptions::beside_current_exe().map_err(|e| e.to_string())?;
let sb = Sandbox::prepare(&options.agent_exe, &data.join("sandbox").join("bin"))?;
let report = sandbox::self_test(&sb, &data.join("log.db"), &data)?;
for c in &report.checks {
let verdict = match (c.result.open, sandbox::KNOWN_LIMITS.contains(&c.route)) {
(false, _) => "closed",
(true, true) => "KNOWN ",
(true, false) => "OPEN ",
};
println!("{verdict} {:<36} {}", c.route, c.result.detail);
}
if !report.known_open().is_empty() {
println!(
"\nKNOWN: open on every Windows machine, and not closed by By Your Leave (D-44)."
);
}
let open = report.open_routes();
if open.is_empty() {
println!("\nEvery route is closed.");
Ok(())
} else {
Err(format!(
"\n{} route(s) open. The kernel will refuse to start.",
open.len()
))
}
}
_ => Err(USAGE.into()),
}
}
fn run(args: &[String]) -> Result<(), String> {
let data = data_dir(args)?;
let config = Config::load(&PathBuf::from(flag(args, "--config").ok_or(USAGE)?))?;
#[allow(unused_mut)]
let mut options = KernelOptions::beside_current_exe().map_err(|e| e.to_string())?;
#[cfg(debug_assertions)]
if let Ok(spec) = std::env::var("BYLEAVE_TEST_CRASH") {
options.crash = CrashPoint::parse(&spec);
}
let _ = CrashPoint::parse;
let mut kernel = Kernel::open(&data, config, options).map_err(|e| e.to_string())?;
let goal = match flag(args, "--goal") {
Some(text) => Some(
kernel
.submit_to(
flag(args, "--pack").as_deref(),
&text,
flag(args, "--project").as_deref(),
has(args, "--simulate"),
)
.map_err(|e| e.to_string())?,
),
None => None,
};
if has(args, "--until-idle") {
kernel.run_until_idle().map_err(|e| e.to_string())?;
} else {
if goal.is_none() {
println!("Kernel running on {}. Stop it with Ctrl+C.", data.display());
if !kernel.config().clients.is_empty() {
println!(
"Client channel: {}",
human::client_pipe_name(&data).unwrap_or_default()
);
}
}
let mut shown = BTreeSet::new();
kernel
.serve(|k| {
for id in k.state().pending_escalations() {
if shown.insert(id) {
println!(
"waiting for you: escalation {id}\n see it with `byleave escalations --data {}`",
data.display()
);
}
}
goal.is_some_and(|g| k.goal_finished(g))
})
.map_err(|e| e.to_string())?;
}
report(&kernel, goal);
Ok(())
}
fn report(kernel: &Kernel, only: Option<by_your_leave::log::GoalId>) {
for (id, g) in &kernel.state().goals {
if only.is_some_and(|x| x != *id) {
continue;
}
let status = match &g.status {
GoalStatus::Submitted => "submitted".to_owned(),
GoalStatus::Working => "working".to_owned(),
GoalStatus::Produced { .. } if kernel.goal_finished(*id) => "work produced".to_owned(),
GoalStatus::Produced { .. } => "work produced, waiting for its check".to_owned(),
GoalStatus::Completed { .. } => "completed: work produced and checked".to_owned(),
GoalStatus::Failed { reason } => format!("failed: {reason}"),
};
println!("goal {id}: {status}");
if let Ok(Some((_, Some(output)))) = kernel.goal_result(*id) {
println!(
"{}",
serde_json::to_string_pretty(&output).unwrap_or_default()
);
}
if let Some(u) = kernel.state().usage.get(id) {
println!(
"model calls: {}, tokens in/out: {}/{}, cost: ${:.6}",
u.model_calls,
u.input_tokens,
u.output_tokens,
u.cost_micros as f64 / 1e6
);
}
}
}
fn send(data: &Path, request: HumanRequest) -> Result<Value, String> {
match human::request(data, request)? {
HumanResponse::Ok { result } => Ok(result),
HumanResponse::Error { message } => Err(message),
HumanResponse::Event { .. } => Err("unexpected event from the kernel".into()),
}
}
fn ask(data: &Path, request: HumanRequest) -> Result<Value, String> {
let may_decide = matches!(
request,
HumanRequest::Answer { .. }
| HumanRequest::SetPolicy { .. }
| HumanRequest::Undo { .. }
| HumanRequest::LoadPack { .. }
| HumanRequest::RemovePack { .. }
| HumanRequest::ReleaseKillSwitch { .. }
| HumanRequest::AcceptKnowledge { .. }
| HumanRequest::RejectKnowledge { .. }
| HumanRequest::RevertKnowledge { .. }
| HumanRequest::RevokeDevice { .. }
| HumanRequest::EnrolDevice { .. }
);
if !may_decide {
return send(data, request);
}
match local_device(data)? {
Ok(Some(device)) => signed(data, request, &device),
Ok(None) => send(data, request),
Err(enrolled) => send(data, request).map_err(|e| {
if e.contains("must be signed") {
format!(
"{e}. The enrolled devices are {}, and none of their keys is on this \
machine",
enrolled.join(", ")
)
} else {
e
}
}),
}
}
#[cfg(windows)]
fn local_device(data: &Path) -> Result<Result<Option<String>, Vec<String>>, String> {
use by_your_leave::hello;
let devices = send(data, HumanRequest::Devices)?;
let active: Vec<&str> = devices
.as_array()
.into_iter()
.flatten()
.filter(|d| d["revoked"].is_null())
.filter_map(|d| d["name"].as_str())
.collect();
if active.is_empty() {
return Ok(Ok(None));
}
for name in &active {
if hello::exists(&hello::find_key(data, name)?) {
return Ok(Ok(Some((*name).to_owned())));
}
}
Ok(Err(active.iter().map(|n| (*n).to_owned()).collect()))
}
#[cfg(not(windows))]
fn local_device(_data: &Path) -> Result<Result<Option<String>, Vec<String>>, String> {
Ok(Ok(None))
}
#[cfg(windows)]
fn signed(data: &Path, request: HumanRequest, device: &str) -> Result<Value, String> {
sign_as(data, request, device, device)
}
#[cfg(not(windows))]
fn signed(_data: &Path, _request: HumanRequest, _device: &str) -> Result<Value, String> {
Err("signing needs Windows Hello (D-64)".into())
}
#[cfg(windows)]
fn sign_as(
data: &Path,
request: HumanRequest,
device: &str,
key_of: &str,
) -> Result<Value, String> {
use by_your_leave::hello;
let prepared = send(
data,
HumanRequest::Prepare {
request: Box::new(request.clone()),
device: device.to_owned(),
},
);
let prepared = match prepared {
Ok(p) => p,
Err(e) if e.contains("is not an authority operation") => return send(data, request),
Err(e) => return Err(e),
};
let statement = prepared["statement"].as_str().unwrap_or_default();
let challenge = prepared["challenge"].as_str().unwrap_or_default();
print_prepared(&prepared["view"], statement);
println!("Windows Hello will ask you to confirm, as device `{device}`.");
let signature = hello::sign(&hello::find_key(data, key_of)?, statement.as_bytes())?;
send(
data,
HumanRequest::Signed {
challenge: challenge.to_owned(),
signature,
},
)
}
#[cfg(windows)]
fn print_prepared(view: &Value, statement: &str) {
let said: Value = serde_json::from_str(statement).unwrap_or_default();
println!(
"You are signing: {}",
said["operation"].as_str().unwrap_or("?")
);
if let Some(tool) = view["tool"].as_str() {
println!(
" action: `{tool}` (class {}) in pack `{}`",
view["class"],
view["pack"].as_str().unwrap_or("?")
);
println!(
" arguments: {}",
serde_json::to_string_pretty(&view["arguments"]).unwrap_or_default()
);
println!(
" role `{}`, goal {}; {} raw events behind it (byleave escalations --raw)",
view["role"].as_str().unwrap_or("?"),
view["goal"].as_str().unwrap_or("-"),
view["events"].as_array().map_or(0, Vec::len)
);
} else if let Some(q) = view["question"].as_str() {
println!(" {q}");
}
println!(
" request: {}",
serde_json::to_string(&said["request"]).unwrap_or_default()
);
println!(
" subject: {}",
serde_json::to_string(&said["subject"]).unwrap_or_default()
);
println!(
" valid until {} (Unix ms)",
said["expires_ms"].as_i64().unwrap_or(0)
);
}
#[cfg(windows)]
fn enrol(data: &Path, name: &str, recover: bool) -> Result<Value, String> {
use by_your_leave::hello;
if !hello::supported()? {
return Err(
"Windows Hello is not set up for this account: set up a PIN in Settings, Accounts, \
Sign-in options, then try again"
.into(),
);
}
let devices = send(data, HumanRequest::Devices)?;
let any = devices
.as_array()
.into_iter()
.flatten()
.any(|d| d["revoked"].is_null());
if recover || !any {
match human::current_elevation()? {
human::Elevation::Prompted => {}
human::Elevation::No => {
return Err(
"the first device, and a recovery, are enrolled only from an \
elevated `byleave` (D-67): run it from a terminal opened as \
administrator"
.into(),
);
}
human::Elevation::Silent => {
return Err(
"this terminal is elevated, but User Account Control elevates \
without asking, so the kernel will refuse the enrolment (D-67): set \
it to ask, on the secure desktop (CHAT_SETUP.md, stage B, step 2)"
.into(),
);
}
}
}
let key = hello::key_name(data, name)?;
println!("Windows Hello will ask you to confirm, to make the key for `{name}`.");
let public_key = hello::create(&key)?;
let request = HumanRequest::EnrolDevice {
name: name.to_owned(),
public_key,
recover,
};
let result = if recover || !any {
sign_as(data, request, name, name)
} else {
match local_device(data)? {
Ok(Some(signer)) => sign_as(data, request, &signer, &signer),
_ => Err("no enrolled device's key is on this machine to sign for it".into()),
}
};
if result.is_err() {
let _ = hello::delete(&key);
}
result
}
#[cfg(not(windows))]
fn enrol(_data: &Path, _name: &str, _recover: bool) -> Result<Value, String> {
Err("devices need Windows Hello (D-64)".into())
}
fn client(cmd: &str, args: &[String]) -> Result<(), String> {
let data = data_dir(args)?;
let pos = positionals(args);
let need = |name: &str| flag(args, name).ok_or_else(|| format!("{cmd} needs {name}"));
match cmd {
"submit" => {
let text = pos.join(" ");
let r = ask(
&data,
HumanRequest::SubmitGoal {
description: text,
project: flag(args, "--project"),
simulate: has(args, "--simulate"),
pack: flag(args, "--pack"),
},
)?;
println!("goal {}", r["goal"].as_str().unwrap_or("?"));
}
"result" => {
let [goal, ..] = pos.as_slice() else {
return Err("usage: byleave result --data DIR GOAL".into());
};
let r = ask(&data, HumanRequest::GoalResult { goal: goal.clone() })?;
println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());
}
"undo" => {
let [action, ..] = pos.as_slice() else {
return Err("usage: byleave undo --data DIR ACTION".into());
};
let r = ask(
&data,
HumanRequest::Undo {
action: action.clone(),
},
)?;
println!("undone ({})", r["undone"].as_str().unwrap_or("?"));
}
"status" => {
let v: StatusView = parse(ask(&data, HumanRequest::Status)?)?;
for g in &v.goals {
let detail = g
.detail
.as_deref()
.map(|d| format!(" ({d})"))
.unwrap_or_default();
println!(
"goal {} {}{detail} [{}]\n {}",
g.id, g.status, g.pack, g.description
);
if let Some(parent) = &g.parent {
println!(
" for goal {parent} (root {})",
g.root.as_deref().unwrap_or("?")
);
}
}
println!();
for d in &v.days {
let whose = if d.scope == "kernel" {
"every pack together".to_owned()
} else if let Some(c) = d.scope.strip_prefix("client:") {
format!("client `{c}`")
} else {
format!("pack `{}`", d.scope)
};
let dollars = |m: u64| format!("${:.2}", m as f64 / 1e6);
let of = |limit: Option<u64>, show: &dyn Fn(u64) -> String| {
limit.map_or_else(|| "no limit".to_owned(), |l| format!("of {}", show(l)))
};
println!(
"today (UTC), {whose}: {} spent ({}), {} ({}), {} ({})",
dollars(d.used_spend_micros),
of(d.spend_micros, &dollars),
count(d.used_model_calls, "model call", "model calls"),
of(d.model_calls, &|n| n.to_string()),
count(d.used_actions, "action", "actions"),
of(d.actions, &|n| n.to_string()),
);
}
for p in &v.packs {
println!(
"pack `{}`: actions of class {} and above wait for you",
p.pack, p.threshold
);
}
match &v.kill_switch {
Some(reason) => println!("kill switch ENGAGED: {reason}"),
None => println!("kill switch released"),
}
if let Some(t) = &v.tool_sandbox {
match (&t.engine, &t.reason) {
(Some(engine), _) => println!("tool sandbox {} on engine {engine}", t.state),
(None, Some(reason)) => println!("tool sandbox {}: {reason}", t.state),
(None, None) => println!("tool sandbox {}", t.state),
}
}
for a in &v.adapters {
println!("{}", adapter_line(a));
}
println!("{} escalation(s) waiting", v.escalations.len());
}
"escalations" => {
let views: Vec<EscalationView> = parse(ask(&data, HumanRequest::Escalations)?)?;
if views.is_empty() {
println!("Nothing is waiting for you.");
}
for v in &views {
print_escalation(v, has(args, "--raw"));
}
}
"answer" => {
let [id, answer, ..] = pos.as_slice() else {
return Err("usage: byleave answer --data DIR ID ANSWER [--note TEXT]".into());
};
ask(
&data,
HumanRequest::Answer {
escalation: id.clone(),
answer: answer.clone(),
note: flag(args, "--note"),
},
)?;
println!("answered");
}
"policy" => match pos.as_slice() {
[] => {
let packs: Vec<PackView> = parse(ask(&data, HumanRequest::Packs)?)?;
for p in packs
.iter()
.filter(|p| flag(args, "--pack").is_none_or(|name| name == p.name))
{
let v = &p.policy;
println!(
"pack `{}`: threshold {} (actions of that class and above wait for you)",
v.pack, v.threshold
);
println!(
" budgets per root goal: ${:.2} of model spend (budget.spend_micros = \
{}), {} model calls (budget.model_calls), {} actions (budget.actions)",
v.budget_spend_micros as f64 / 1e6,
v.budget_spend_micros,
v.budget_model_calls,
v.budget_actions
);
println!(
" class 3 approvals wait {} s before the action runs \
(class3.delay_seconds), once a device signs them",
v.class3_delay_seconds
);
}
}
[set, key, value] if set == "set" => {
let value: Value =
serde_json::from_str(value).unwrap_or_else(|_| Value::String(value.clone()));
let r = ask(
&data,
HumanRequest::SetPolicy {
key: key.clone(),
value,
pack: flag(args, "--pack"),
global: has(args, "--global"),
},
)?;
if r["changed"] == true {
println!("policy changed and logged");
} else {
println!("already set to that value");
}
}
_ => {
return Err(
"usage: byleave policy --data DIR [set KEY VALUE] [--pack NAME | --global]"
.into(),
);
}
},
"pack" => match pos.as_slice() {
[] => {
let packs: Vec<PackView> = parse(ask(&data, HumanRequest::Packs)?)?;
for p in &packs {
println!(
"pack `{}` {} ({} open goal(s))",
p.name, p.version, p.open_goals
);
if let Some(d) = &p.description {
println!(" {d}");
}
}
}
[op, name] if op == "load" => {
let r = ask(&data, HumanRequest::LoadPack { name: name.clone() })?;
if r["changed"] == true {
println!(
"pack `{name}` {} loaded and logged",
r["version"].as_str().unwrap_or("?")
);
} else {
println!("pack `{name}` is already loaded at that version");
}
if let Some(state) = r["tool_sandbox"]["state"].as_str() {
match r["tool_sandbox"]["reason"].as_str() {
Some(reason) => println!("tool sandbox {state}: {reason}"),
None => println!("tool sandbox {state}"),
}
}
}
[op, name] if op == "remove" => {
ask(&data, HumanRequest::RemovePack { name: name.clone() })?;
println!("pack `{name}` removed");
}
_ => return Err("usage: byleave pack --data DIR [load NAME | remove NAME]".into()),
},
"cancel" => {
let [goal] = pos.as_slice() else {
return Err("usage: byleave cancel --data DIR GOAL --reason TEXT".into());
};
let r = ask(
&data,
HumanRequest::CancelGoal {
goal: goal.clone(),
reason: need("--reason")?,
},
)?;
for g in r["cancelled"].as_array().into_iter().flatten() {
println!("goal {} cancelled", g.as_str().unwrap_or_default());
}
}
"kill" => {
ask(
&data,
HumanRequest::EngageKillSwitch {
reason: need("--reason")?,
},
)?;
println!("kill switch engaged: no action will execute until it is released");
}
"release" => {
ask(
&data,
HumanRequest::ReleaseKillSwitch {
reason: need("--reason")?,
},
)?;
println!("kill switch released");
}
"events" => {
let events = ask(
&data,
HumanRequest::GoalEvents {
goal: need("--goal")?,
},
)?;
for e in events.as_array().into_iter().flatten() {
println!("{}", event_line(e));
}
}
"watch" => {
let after = flag(args, "--after")
.and_then(|a| a.parse().ok())
.unwrap_or(0);
human::subscribe(&data, after, |e| {
println!("{}", event_line(&e));
true
})?;
}
"log" => {
let number = |name: &str| -> Result<Option<u64>, String> {
flag(args, name)
.map(|v| v.parse().map_err(|_| format!("{name} takes a number")))
.transpose()
};
let r = ask(
&data,
HumanRequest::SearchLog {
event_type: flag(args, "--type"),
goal: flag(args, "--goal"),
text: flag(args, "--text"),
after_seq: number("--after")?,
limit: number("--limit")?,
},
)?;
let events = r["events"].as_array().cloned().unwrap_or_default();
for e in &events {
println!(
"{} {}",
event_line(e),
e["id"].as_str().unwrap_or_default()
);
}
if r["more"] == true
&& let Some(last) = events.last()
{
println!("... more: --after {}", last["seq"]);
}
}
"trace" => {
let [event] = pos.as_slice() else {
return Err("usage: byleave trace --data DIR EVENT".into());
};
let r = ask(
&data,
HumanRequest::Trace {
event: event.clone(),
},
)?;
println!("caused by:");
for e in r["causes"].as_array().into_iter().flatten() {
println!(" {}", event_line(e));
}
println!("the event:\n> {}", event_line(&r["event"]));
println!("what it caused:");
print_effects(&r["effects"], 1);
if r["complete"] == false {
println!(" ... (cut short: follow a later event with `byleave trace`)");
}
}
"tree" => {
let [goal] = pos.as_slice() else {
return Err("usage: byleave tree --data DIR GOAL".into());
};
let r = ask(&data, HumanRequest::GoalTree { goal: goal.clone() })?;
print_tree(&r, 0);
}
"samples" => {
let r = ask(
&data,
HumanRequest::Samples {
all: has(args, "--all"),
},
)?;
let samples = r.as_array().cloned().unwrap_or_default();
if samples.is_empty() {
println!("no sampled action waits for review");
}
for s in &samples {
let review = match s["reviewed"].as_object() {
Some(r) => format!(
"reviewed: {}{}",
r["verdict"].as_str().unwrap_or("?"),
r["note"]
.as_str()
.map(|n| format!(" ({n})"))
.unwrap_or_default()
),
None => "not reviewed".to_owned(),
};
println!(
"sample {} [{review}] {} by role `{}` (class {}), pack `{}`",
s["id"].as_str().unwrap_or("?"),
s["tool"].as_str().unwrap_or("?"),
s["role"].as_str().unwrap_or("?"),
s["class"],
s["pack"].as_str().unwrap_or("?"),
);
println!(" arguments: {}", s["arguments"]);
println!(" result: {}", s["result"]);
for e in s["events"].as_array().into_iter().flatten() {
println!(" {}", event_line(e));
}
println!();
}
}
"review" => {
let [sample, verdict] = pos.as_slice() else {
return Err(
"usage: byleave review --data DIR SAMPLE ok|concern [--note TEXT]".into(),
);
};
ask(
&data,
HumanRequest::ReviewSample {
sample: sample.clone(),
verdict: verdict.clone(),
note: flag(args, "--note"),
},
)?;
println!("sample {sample} reviewed: {verdict}");
}
"knowledge" => match pos.as_slice() {
[] => {
let r = ask(&data, HumanRequest::Knowledge)?;
let items = r.as_array().cloned().unwrap_or_default();
if items.is_empty() {
println!("the learner has proposed nothing");
}
for p in &items {
println!(
"proposal {} {} skill `{}`, file `{}`{}",
p["id"].as_str().unwrap_or("?"),
p["status"].as_str().unwrap_or("?"),
p["skill"].as_str().unwrap_or("?"),
p["file"].as_str().unwrap_or("?"),
if p["from_observation"] == true {
" (built from content from the environment)"
} else {
""
},
);
println!(" why: {}", p["rationale"].as_str().unwrap_or(""));
if let Some(r) = p["reason"].as_str() {
println!(" {}: {r}", p["status"].as_str().unwrap_or(""));
}
if p["status"] == "proposed" {
println!(" the change, `-` the text now, `+` the text proposed:");
print_diff(
p["base_content"].as_str().unwrap_or(""),
p["content"].as_str().unwrap_or(""),
);
}
println!();
}
}
[op, id] if op == "accept" => {
let r = ask(
&data,
HumanRequest::AcceptKnowledge {
proposal: id.clone(),
note: flag(args, "--note"),
},
)?;
println!(
"accepted: roles are given version {} from their next load",
r["version"].as_str().unwrap_or("?")
);
}
[op, id] if op == "reject" => {
ask(
&data,
HumanRequest::RejectKnowledge {
proposal: id.clone(),
reason: need("--reason")?,
},
)?;
println!("rejected");
}
[op, skill] if op == "revert" => {
let r = ask(
&data,
HumanRequest::RevertKnowledge {
skill: skill.clone(),
reason: need("--reason")?,
},
)?;
println!(
"reverted: skill `{skill}` is at version {} again",
r["version"].as_str().unwrap_or("?")
);
}
_ => {
return Err(
"usage: byleave knowledge --data DIR [accept ID | reject ID \
--reason TEXT | revert SKILL --reason TEXT]"
.into(),
);
}
},
"replay" => {
let [invocation] = pos.as_slice() else {
return Err("usage: byleave replay --data DIR INVOCATION [--model BINDING]".into());
};
let r = ask(
&data,
HumanRequest::Replay {
invocation: invocation.clone(),
model: flag(args, "--model"),
},
)?;
print_replay(&r);
}
"replays" => {
let r = ask(
&data,
HumanRequest::Replays {
invocation: flag(args, "--invocation"),
},
)?;
for replay in r.as_array().into_iter().flatten() {
print_replay(replay);
}
}
"device" => match pos.as_slice() {
[] => {
let devices = ask(&data, HumanRequest::Devices)?;
let list = devices.as_array().cloned().unwrap_or_default();
if list.is_empty() {
println!(
"no device is enrolled: nothing is signed, and class 3 actions are \
rejected (D-58)"
);
}
for d in list {
let state = match d["revoked"].as_str() {
Some(r) => format!("revoked by {r}"),
None => "enrolled".to_owned(),
};
let key = d["key"].as_str().unwrap_or("?");
println!(
"{} {state} key {}",
d["name"].as_str().unwrap_or("?"),
&key[..key.len().min(16)]
);
}
}
[op, name] if op == "enrol" => {
let r = enrol(&data, name, has(args, "--recover"))?;
println!("device `{name}` enrolled");
for other in r["revoked"].as_array().into_iter().flatten() {
println!("device `{}` revoked", other.as_str().unwrap_or("?"));
}
}
[op, name] if op == "revoke" => {
ask(
&data,
HumanRequest::RevokeDevice {
name: name.clone(),
reason: need("--reason")?,
},
)?;
println!("device `{name}` revoked");
}
_ => {
return Err(
"usage: byleave device --data DIR [enrol NAME [--recover] | revoke NAME \
--reason TEXT]"
.into(),
);
}
},
"withdraw" => {
let [action] = pos.as_slice() else {
return Err("usage: byleave withdraw --data DIR ACTION --reason TEXT".into());
};
ask(
&data,
HumanRequest::WithdrawApproval {
action: action.clone(),
reason: need("--reason")?,
},
)?;
println!("approval withdrawn: the action is rejected");
}
_ => return Err(USAGE.into()),
}
Ok(())
}
fn verify(args: &[String]) -> Result<(), String> {
let data = data_dir(args)?;
let report = match ask(&data, HumanRequest::Verify) {
Ok(r) => r,
Err(e) if e.starts_with("the log was altered") => return Err(e),
Err(_) => serde_json::to_value(
by_your_leave::log::verify(data.join("log.db"))
.map_err(|e| format!("the log was altered: {e}"))?,
)
.map_err(|e| e.to_string())?,
};
match report["chained_from"].as_u64() {
Some(1) => println!(
"the log holds together: {} events, each chained to the one before",
report["events"]
),
Some(n) => println!(
"the log holds together: {} events, chained from event {n}; the {} before it \
were written before the chain began",
report["events"],
n - 1
),
None => println!(
"the log holds {} events, none of them chained yet",
report["events"]
),
}
match report["signatures"].as_u64() {
Some(0) | None => {}
Some(1) => println!("1 device signature checked against the keys enrolled in it"),
Some(n) => println!("{n} device signatures checked against the keys enrolled in it"),
}
Ok(())
}
fn adapter_line(a: &AdapterView) -> String {
let sandboxed = if a.sandbox { ", sandboxed" } else { "" };
let network = match a.network.as_deref() {
None => "network not declared".to_owned(),
Some([]) => "no network".to_owned(),
Some(d) => format!("reaches {}", d.join(", ")),
};
format!("{} adapter `{}`{sandboxed}: {network}", a.kind, a.name)
}
fn count(n: u64, one: &str, many: &str) -> String {
format!("{n} {}", if n == 1 { one } else { many })
}
fn print_diff(old: &str, new: &str) {
for line in diff_lines(old, new) {
println!(" {line}");
}
}
fn diff_lines(old: &str, new: &str) -> Vec<String> {
let mut out = Vec::new();
let (a, b): (Vec<&str>, Vec<&str>) = (old.lines().collect(), new.lines().collect());
let mut lcs = vec![vec![0usize; b.len() + 1]; a.len() + 1];
for i in (0..a.len()).rev() {
for j in (0..b.len()).rev() {
lcs[i][j] = if a[i] == b[j] {
lcs[i + 1][j + 1] + 1
} else {
lcs[i + 1][j].max(lcs[i][j + 1])
};
}
}
let mut ops: Vec<(char, &str)> = Vec::new();
let (mut i, mut j) = (0, 0);
while i < a.len() || j < b.len() {
if i < a.len() && j < b.len() && a[i] == b[j] {
ops.push((' ', a[i]));
i += 1;
j += 1;
} else if j < b.len() && (i == a.len() || lcs[i][j + 1] > lcs[i + 1][j]) {
ops.push(('+', b[j]));
j += 1;
} else {
ops.push(('-', a[i]));
i += 1;
}
}
let near = |k: usize| {
ops[k.saturating_sub(2)..(k + 3).min(ops.len())]
.iter()
.any(|(op, _)| *op != ' ')
};
let mut skipped = false;
for (k, (op, line)) in ops.iter().enumerate() {
if near(k) {
if skipped {
out.push("...".to_owned());
skipped = false;
}
out.push(format!("{op} {line}"));
} else {
skipped = true;
}
}
out
}
fn print_effects(effects: &Value, depth: usize) {
for e in effects.as_array().into_iter().flatten() {
println!("{}{}", " ".repeat(depth), event_line(&e["event"]));
print_effects(&e["effects"], depth + 1);
}
}
fn print_tree(t: &Value, depth: usize) {
let pad = " ".repeat(depth);
let g = &t["goal"];
println!(
"{pad}goal {} {} [{}]\n{pad} {}",
g["id"].as_str().unwrap_or("?"),
g["status"].as_str().unwrap_or("?"),
g["pack"].as_str().unwrap_or("?"),
g["description"].as_str().unwrap_or("")
);
for task in t["tasks"].as_array().into_iter().flatten() {
let after: Vec<&str> = task["after"]
.as_array()
.into_iter()
.flatten()
.filter_map(|a| a.as_str())
.collect();
println!(
"{pad} task `{}` ({}) {}, {} events{}",
task["item"].as_str().unwrap_or("?"),
task["role"].as_str().unwrap_or("?"),
task["status"].as_str().unwrap_or("?"),
task["events"],
if after.is_empty() {
String::new()
} else {
format!(", after {}", after.join(", "))
}
);
}
for child in t["goals"].as_array().into_iter().flatten() {
print_tree(child, depth + 1);
}
}
fn print_replay(r: &Value) {
println!(
"replay {} of invocation {}, on model `{}`",
r["id"].as_str().unwrap_or("?"),
r["invocation"].as_str().unwrap_or("?"),
r["model"].as_str().unwrap_or("?")
);
match r["identical"].as_bool() {
Some(true) => {
println!(" on the recorded responses: every model request was the recorded one")
}
Some(false) => {
println!(" on the recorded responses: the requests differed from the record")
}
None => {}
}
println!(
" {}, ${:.6}",
count(
r["calls"].as_array().map_or(0, |c| c.len()) as u64,
"model call",
"model calls"
),
r["cost_micros"].as_u64().unwrap_or(0) as f64 / 1e6
);
if let Some(e) = r["error"].as_str() {
println!(" no proposal: {e}");
} else {
println!(" proposed (not acted on): {}", r["proposal"]);
}
println!(
" originally: {} {}",
r["original"]["type"].as_str().unwrap_or("?"),
r["original"]["payload"]
);
println!();
}
fn parse<T: serde::de::DeserializeOwned>(v: Value) -> Result<T, String> {
serde_json::from_value(v).map_err(|e| format!("the kernel sent an unexpected answer: {e}"))
}
fn actor_name(actor: &Value) -> String {
match actor["kind"].as_str().or_else(|| actor.as_str()) {
Some(k) => match actor["name"].as_str() {
Some(n) => format!("{k}:{n}"),
None => k.to_owned(),
},
None => actor.to_string(),
}
}
fn event_line(e: &Value) -> String {
format!(
"{:>5} {:<22} {:<22} {:<13} {}",
e["seq"],
e["event_type"].as_str().unwrap_or("?"),
actor_name(&e["actor"]),
e["trust"].as_str().unwrap_or("?"),
serde_json::to_string(&e["payload"]).unwrap_or_default()
)
}
fn print_escalation(v: &EscalationView, raw: bool) {
println!("escalation {} ({})", v.id, v.kind);
println!(" {}", v.question);
if let Some(tool) = &v.tool {
println!(" tool: {tool}");
}
if let Some(args) = &v.arguments {
println!(
" arguments: {}",
serde_json::to_string_pretty(args)
.unwrap_or_default()
.replace('\n', "\n ")
);
}
if let (Some(c), Some(b)) = (v.class, &v.basis) {
println!(" class {c}: {b}");
}
if !v.options.is_empty() {
println!(" options: {}", v.options.join(" | "));
}
println!(" events behind it:");
for e in &v.events {
if raw {
println!(
" {}",
serde_json::to_string_pretty(e)
.unwrap_or_default()
.replace('\n', "\n ")
);
} else {
println!(" {}", event_line(e));
}
}
println!();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_diff_shows_the_changed_lines_with_two_lines_around_them() {
let old = "a\nb\nc\nd\ne\nf\ng\nh\n";
let new = "a\nb\nc\nd\nE\nf\ng\nh\nI\n";
assert_eq!(
diff_lines(old, new),
[
"...", " c", " d", "- e", "+ E", " f", " g", " h", "+ I"
]
);
assert!(diff_lines("same\n", "same\n").is_empty());
}
#[test]
fn one_is_singular() {
assert_eq!(count(1, "model call", "model calls"), "1 model call");
assert_eq!(count(2, "model call", "model calls"), "2 model calls");
assert_eq!(count(0, "action", "actions"), "0 actions");
}
}