AnyBot/src/intents.rs

230 lines
12 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! 捷徑優先於 GUI (C6): the operations a person does with one key press, registered as one
//! step for the bot.
//!
//! The bench said it plainly: 「把音量調小」 took 9 model steps through the GUI (about two
//! minutes) and one shell command (four seconds). Volume, Wi-Fi, the lock, dark mode — these
//! have supported command-line doors; a bot that clicks menus is a bot that didn't know the
//! door existed. So the registry here is the knowledge, the computer's facts line advertises
//! it every turn (cached by the prompt cache), and the computer tool's `intent` action walks
//! through: one call, one command, no screenshot.
//!
//! A script is a constant chosen from a validated name and argument — the model never writes
//! the command, it picks a name. That is why this can run where clicks run, with the same
//! approval, and why 「體積 set 999; rm -rf /」 is not a thing: the argument is checked against
//! the intent's grammar (a number 0–100, on/off, dark/light) before any script is built.
use serde_json::Value;
/// One registered shortcut: what it's called, how to say it, which machines have it.
pub struct Intent {
pub name: &'static str,
/// How to call it, shown in the computer's facts line.
pub usage: &'static str,
/// Does this computer have it? kernel: "Darwin"/"Linux"; desktop: a window system is
/// running (a headless box has no volume knob the person hears).
pub has: fn(kernel: &str, desktop: bool) -> bool,
}
pub const INTENTS: &[Intent] = &[
Intent {
name: "volume",
usage: "volume(音量:arg=set 0-100 / up / down / mute / unmute)",
has: |k, desktop| matches!(k, "Darwin") || (k == "Linux" && desktop),
},
Intent {
name: "wifi",
usage: "wifi(Wi-Fi 開關:arg=on / off)",
has: |k, desktop| matches!(k, "Darwin") || (k == "Linux" && desktop),
},
Intent {
name: "lock",
usage: "lock(鎖螢幕/關螢幕:不用 arg)",
has: |k, desktop| matches!(k, "Darwin") || (k == "Linux" && desktop),
},
Intent {
name: "dark",
usage: "dark(深淺色:arg=dark / light / toggle)",
has: |k, desktop| matches!(k, "Darwin") || (k == "Linux" && desktop),
},
Intent {
name: "trash",
usage: "trash(清空資源筒/垃圾桶:不用 arg)",
has: |k, desktop| matches!(k, "Darwin") || (k == "Linux" && desktop),
},
Intent {
name: "eject",
usage: "eject(退出所有可退出磁碟:不用 arg,Mac)",
has: |k, _| k == "Darwin",
},
];
pub fn find(name: &str) -> Option<&'static Intent> {
INTENTS.iter().find(|i| i.name == name)
}
/// The names this kind of computer answers to — the facts line and the tool's error both
/// speak this.
pub fn names_for(kernel: &str, desktop: bool) -> Vec<&'static str> {
INTENTS.iter().filter(|i| (i.has)(kernel, desktop)).map(|i| i.name).collect()
}
/// The sentence in a computer's facts: names and grammar, so the model can pick without
/// guessing. Empty for a headless box (its "volume" is nobody's volume).
pub fn facts_line(kernel: &str, desktop: bool, own_box: bool) -> String {
if own_box {
return String::new();
}
let list = names_for(kernel, desktop);
if list.is_empty() {
return String::new();
}
let usages: Vec<&str> = INTENTS.iter().filter(|i| list.contains(&i.name)).map(|i| i.usage).collect();
format!("系統捷徑(有捷徑先捷徑,一步完成,不要用 GUI 點擊;用 computer 工具 action=intent,參數 intent_name+intent_arg):{}", usages.join(";"))
}
fn is_num(s: &str) -> Option<u32> {
let n: u32 = s.parse().ok()?;
if n <= 100 {
Some(n)
} else {
None
}
}
/// The script for one validated pick. Constants and (checked) numbers only — the model's
/// words never reach the shell.
pub fn script(name: &str, arg: &str) -> Result<String, String> {
// Windows hands exist (C9), Windows shortcuts don't yet: the scripts here are sh.
if cfg!(target_os = "windows") {
return Err("系統捷徑目前支援 macOS 和 Linux;這台 Windows 請用截圖與滑鼠。".into());
}
if find(name).is_none() {
return Err(format!("沒有捷徑「{name}」。"));
}
let a = arg.trim();
// One script for both systems: `case` picks the branch on the machine that runs it. (The
// Mac command used to land in the Linux branch and the Linux one after it as a stray
// pattern, with a `)` left over: every shortcut was a syntax error on every machine.)
let on = |mac: &str, linux: &str| format!("case \"$(uname -s)\" in Darwin) {mac} ;; Linux) {linux} ;; esac");
Ok(match (name, a) {
("volume", "up") => on(
"osascript -e 'set u to (output volume of (get volume settings)) + 15' -e 'if u > 100 then set u to 100' -e 'set volume output volume u'",
"pactl set-sink-volume @DEFAULT_SINK@ +15% 2>/dev/null || amixer -q sset Master 15%+",
),
("volume", "down") => on(
"osascript -e 'set u to (output volume of (get volume settings)) - 15' -e 'if u < 0 then set u to 0' -e 'set volume output volume u'",
"pactl set-sink-volume @DEFAULT_SINK@ -15% 2>/dev/null || amixer -q sset Master 15%-",
),
("volume", "mute") => on(
"osascript -e 'set m to muted of (get volume settings)' -e 'set volume output muted (not m)'",
"pactl set-sink-mute @DEFAULT_SINK@ toggle 2>/dev/null || amixer -q sset Master toggle",
),
("volume", "unmute") => on("osascript -e 'set volume output muted false'", "pactl set-sink-mute @DEFAULT_SINK@ 0 2>/dev/null || amixer -q sset Master unmute"),
("volume", set) => {
// "set 40" as the facts line teaches; a bare "40" is kindly taken too.
let Some(n) = is_num(set.strip_prefix("set ").unwrap_or(set).trim()) else {
return Err("volume 的 arg 要写成 set 0-100(如 set 40)或 up/down/mute/unmute。".into());
};
on(&format!("osascript -e 'set volume output volume {n}'"), &format!("pactl set-sink-volume @DEFAULT_SINK@ {n}% 2>/dev/null || amixer -q sset Master {n}%"))
}
("wifi", "on") => on("networksetup -setairportpower en0 on", "nmcli radio wifi on 2>/dev/null || rfkill unblock wifi"),
("wifi", "off") => on("networksetup -setairportpower en0 off", "nmcli radio wifi off 2>/dev/null || rfkill block wifi"),
("lock", "") => on("pmset displaysleepnow", "loginctl lock-session 2>/dev/null || xset dpms force off"),
("dark", "dark") => on("osascript -e 'tell application \"System Events\" to tell appearance preferences to set dark mode to true'", "gsettings set org.gnome.desktop.interface color-scheme prefer-dark"),
("dark", "light") => on("osascript -e 'tell application \"System Events\" to tell appearance preferences to set dark mode to false'", "gsettings set org.gnome.desktop.interface color-scheme prefer-light"),
("dark", "toggle") => on(
"osascript -e 'tell application \"System Events\" to tell appearance preferences to set dark mode to not (dark mode)'",
"gsettings set org.gnome.desktop.interface color-scheme \"$( [ \"$(gsettings get org.gnome.desktop.interface color-scheme)\" = \"'prefer-dark'\" ] && echo prefer-light || echo prefer-dark )\"",
),
("trash", "") => on("osascript -e 'tell application \"Finder\" to empty trash'", "rm -rf \"$HOME/.local/share/Trash/files\" \"$HOME/.local/share/Trash/info\""),
("eject", "") => on("osascript -e 'tell application \"Finder\" to eject (every disk whose ejectable is true)'", "echo 只有 Mac 有這個捷徑"),
(_, "") => return Err(format!("「{name}」不需要 arg。")),
(_, _) => return Err(format!("「{name}」的 arg 不對。看捷徑說明:{}", find(name).map(|i| i.usage).unwrap_or(""))),
})
}
/// The computer tool's `intent` action: pick, build, run, report. Runs where the computer
/// tool runs — the bot's box is excluded by the facts line (it advertises no shortcuts).
pub fn tool(v: &Value) -> Result<(String, Option<String>), String> {
let name = v["intent_name"].as_str().unwrap_or("").trim();
let arg = v["intent_arg"].as_str().unwrap_or("").trim();
if name.is_empty() {
return Err(format!("要 intent_name。這台電腦的捷徑:{}", INTENTS.iter().map(|i| i.name).collect::<Vec<_>>().join("、")));
}
let sh = script(name, arg)?;
let out = std::process::Command::new("/bin/sh").arg("-c").arg(&sh).env("PATH", crate::cloudbox::tool_path()).output().map_err(|e| format!("捷徑跑不起來:{e}"))?;
let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)).trim().to_string();
if out.status.success() {
Ok((format!("捷徑 {name}{}完成。{}", if arg.is_empty() { String::new() } else { format!("({arg})") }, if text.is_empty() { String::new() } else { format!(" 系統說:{text}") }), None))
} else {
Ok((format!("捷徑 {name} 的指令回來了但沒成功(這台電腦可能沒有對應的系統指令):{text}"), None))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_mac_and_a_linux_desktop_get_their_shortcuts() {
let mac = names_for("Darwin", true);
for n in ["volume", "wifi", "lock", "dark", "trash", "eject"] {
assert!(mac.contains(&n), "{n}");
}
let linux = names_for("Linux", true);
assert!(linux.contains(&"volume") && !linux.contains(&"eject"));
// A headless box advertises none: nobody hears its volume. The facts line says so.
assert!(names_for("Linux", false).is_empty());
assert!(facts_line("Linux", true, true).is_empty(), "the bot's own box: no shortcuts");
let line = facts_line("Darwin", true, false);
for want in ["系統捷徑", "volume", "intent_name", "不要用 GUI 點擊", "eject"] {
assert!(line.contains(want), "{want}: {line}");
}
}
#[test]
fn words_never_reach_the_shell() {
// The model picks a name; the script is built from constants and checked numbers.
assert!(script("volume", "set 40").unwrap().contains("output volume 40"));
for bad in ["set 101", "set -5", "set 40; rm -rf /", "set 40$(id)", "set x", "999", "up; reboot"] {
assert!(script("volume", bad).is_err(), "{bad} must not build a script");
}
assert!(script("wifi", "on").unwrap().contains("networksetup"));
assert!(script("wifi", "on; rm -rf /").is_err());
assert!(script("lock", "").unwrap().contains("pmset"));
assert!(script("lock", "now").is_err(), "lock takes no arg");
assert!(script("dark", "toggle").unwrap().contains("dark mode to not"));
assert!(script("nope", "").is_err());
// The tool says which names exist when the name is missing.
let e = tool(&serde_json::json!({})).unwrap_err();
assert!(e.contains("volume") && e.contains("intent_name"), "{e}");
}
#[test]
fn every_script_is_a_script_the_shell_can_read() {
// Parsed, never run (`sh -n`): running one here would lock the screen or change the
// volume of whoever runs the tests. The test that ran `lock` passed for the wrong
// reason — every script was a syntax error, and the failure sentence starts with the
// same words as the success one.
if cfg!(target_os = "windows") {
return;
}
let all = [
("volume", "up"), ("volume", "down"), ("volume", "mute"), ("volume", "unmute"), ("volume", "set 40"), ("volume", "40"),
("wifi", "on"), ("wifi", "off"), ("lock", ""), ("dark", "dark"), ("dark", "light"), ("dark", "toggle"), ("trash", ""), ("eject", ""),
];
for (name, arg) in all {
let sh = script(name, arg).unwrap();
let out = std::process::Command::new("/bin/sh").arg("-n").arg("-c").arg(&sh).output().unwrap();
assert!(out.status.success(), "{name} {arg}: {}\n{sh}", String::from_utf8_lossy(&out.stderr));
// Each system gets its own command, in its own branch.
let (mac, linux) = sh.split_once(" ;; Linux) ").unwrap();
assert!(mac.starts_with("case \"$(uname -s)\" in Darwin) ") && mac.len() > 40 && linux.ends_with(" ;; esac") && linux.len() > 20, "{sh}");
}
// Every registered shortcut is covered above.
for i in INTENTS {
assert!(all.iter().any(|(n, _)| *n == i.name), "{}", i.name);
}
}
}