Add mind_body::chat_gate and clap-free mind-chat CLI
Add host Matrix mouth gate and dual-mode Engine (chat-gate.json atomic state, 0600 Unix socket outside bwrap, persona pinning, seen_event_id only on pending/tail display, RoomMoved refusal without blind cursor bump, 1800s unsettled pending_send + --resend, MIND_RUN_BACKSTOP via heartbeat::line_facts, UTC daily outbound cap) plus clap-free mind-chat.
This commit is contained in:
parent
3f352681a7
commit
29f1926be3
5 changed files with 1634 additions and 0 deletions
|
|
@ -94,3 +94,7 @@ path = "src/bin/mind-persona.rs"
|
|||
[[bin]]
|
||||
name = "mind-heartbeat"
|
||||
path = "src/bin/mind-heartbeat.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "mind-chat"
|
||||
path = "src/bin/mind-chat.rs"
|
||||
|
|
|
|||
317
crates/mind-body/src/bin/mind-chat.rs
Normal file
317
crates/mind-body/src/bin/mind-chat.rs
Normal file
|
|
@ -0,0 +1,317 @@
|
|||
//! `mind-chat`: dual-mode Matrix mouth gate and sandbox/host client CLI.
|
||||
//!
|
||||
//! Host gate mode (outside `bwrap`):
|
||||
//! `mind-chat gate --instance <slug> --socket <path> --state-dir <dir> --minds <csv> --operators <csv> --own-sender <mxid> [--daily-cap <n>]`
|
||||
//!
|
||||
//! Client modes (sandboxed via `MIND_CHAT_SOCKET`, or direct host RUDP when unset):
|
||||
//! `mind-chat pending [--ack]`
|
||||
//! `mind-chat tail [--room <room>]`
|
||||
//! `mind-chat say --room <room> (--text <text> | --resend <request_id>)`
|
||||
//! `mind-chat ack --through <seq>`
|
||||
//! `mind-chat mark-read --room <room_id> --event <event_id> --at <unix_ms>`
|
||||
//! `mind-chat open-direct --user <mxid> --text <text>`
|
||||
//! `mind-chat status`
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use chrono::Utc;
|
||||
use eureka_pipeline::Slug;
|
||||
use mind_body::chat_gate::{Answer, Config, Engine, Request, call_socket, serve_gate};
|
||||
use mind_body::chat_rudp::{RudpChat, connection_id};
|
||||
|
||||
const CHAT_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
const USAGE: &str = "\
|
||||
usage:
|
||||
mind-chat gate --instance <slug> --socket <path> --state-dir <dir> --minds <csv> --operators <csv> --own-sender <mxid> [--daily-cap <n>]
|
||||
mind-chat pending [--ack]
|
||||
mind-chat tail [--room <room>]
|
||||
mind-chat say --room <room> (--text <text> | --resend <request_id>)
|
||||
mind-chat ack --through <seq>
|
||||
mind-chat mark-read --room <room_id> --event <event_id> --at <unix_ms>
|
||||
mind-chat open-direct --user <mxid> --text <text>
|
||||
mind-chat status";
|
||||
|
||||
#[cfg(unix)]
|
||||
fn restrict_umask() {
|
||||
// SAFETY: umask only sets this process's file-creation mask.
|
||||
unsafe {
|
||||
libc::umask(0o077);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn restrict_umask() {}
|
||||
|
||||
#[allow(clippy::disallowed_methods, reason = "the binary reads its own environment, and hands it to the library")]
|
||||
fn setting(name: &str) -> Option<String> {
|
||||
std::env::var(name).ok().filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn required_env(name: &str) -> Result<String> {
|
||||
setting(name).ok_or_else(|| anyhow!("{name} is not set"))
|
||||
}
|
||||
|
||||
fn split_csv(raw: &str) -> Vec<String> {
|
||||
raw.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
|
||||
}
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
u64::try_from(Utc::now().timestamp_millis()).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn open_rudp(instance: &str) -> Result<RudpChat> {
|
||||
let endpoint_raw = required_env("BIFROST_CHAT_ENDPOINT")?;
|
||||
let endpoint: SocketAddr = endpoint_raw
|
||||
.strip_prefix("rudp://")
|
||||
.and_then(|addr| addr.parse().ok())
|
||||
.ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT is not rudp://<ip>:<port>"))?;
|
||||
let key_path = required_env("BIFROST_CHAT_KEY_FILE")?;
|
||||
let key_text = std::fs::read_to_string(&key_path)
|
||||
.with_context(|| format!("failed to read BIFROST_CHAT_KEY_FILE {key_path}"))?;
|
||||
let conn_id = connection_id(&key_text);
|
||||
Ok(RudpChat::new(endpoint, conn_id, instance, CHAT_TIMEOUT).with_reply_link(true))
|
||||
}
|
||||
|
||||
fn run_gate(args: &[String]) -> Result<()> {
|
||||
let (mut instance, mut socket, mut state_dir, mut minds, mut operators, mut own_sender, mut daily_cap) =
|
||||
(None, None, None, None, None, None, None);
|
||||
let mut it = args.iter();
|
||||
while let Some(flag) = it.next() {
|
||||
let mut val = || it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"));
|
||||
match flag.as_str() {
|
||||
"--instance" => instance = Some(val()?),
|
||||
"--socket" => socket = Some(PathBuf::from(val()?)),
|
||||
"--state-dir" => state_dir = Some(PathBuf::from(val()?)),
|
||||
"--minds" => minds = Some(split_csv(&val()?)),
|
||||
"--operators" => operators = Some(split_csv(&val()?)),
|
||||
"--own-sender" => own_sender = Some(val()?),
|
||||
"--daily-cap" => {
|
||||
let parsed: u32 = val()?.parse().map_err(|_| anyhow!("--daily-cap must be an integer"))?;
|
||||
daily_cap = Some(parsed);
|
||||
}
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
}
|
||||
let instance = Slug(instance.ok_or_else(|| anyhow!("--instance is required"))?);
|
||||
let socket = socket.ok_or_else(|| anyhow!("--socket is required"))?;
|
||||
let state_dir = state_dir.ok_or_else(|| anyhow!("--state-dir is required"))?;
|
||||
let minds = minds.unwrap_or_else(|| setting("MIND_PERSONA_MINDS").map(|s| split_csv(&s)).unwrap_or_default());
|
||||
let operators = operators.unwrap_or_else(|| setting("MIND_PERSONA_OPERATOR").map(|s| split_csv(&s)).unwrap_or_default());
|
||||
let own_sender = own_sender
|
||||
.or_else(|| setting("MIND_PERSONA_SELF_SENDER"))
|
||||
.ok_or_else(|| anyhow!("--own-sender is required"))?;
|
||||
let daily_cap = match daily_cap {
|
||||
Some(cap) => Some(cap),
|
||||
None => setting("MIND_CHAT_DAILY_CAP")
|
||||
.map(|v| v.parse::<u32>().map_err(|_| anyhow!("MIND_CHAT_DAILY_CAP must be an integer")))
|
||||
.transpose()?,
|
||||
};
|
||||
let chat = open_rudp(&instance.0)?;
|
||||
let config = Config { instance, state_dir, minds, operators, own_sender, daily_cap };
|
||||
serve_gate(config, chat, &socket, now_ms)
|
||||
}
|
||||
|
||||
fn parse_client_request(cmd: &str, args: &[String]) -> Result<Request> {
|
||||
let mut it = args.iter();
|
||||
match cmd {
|
||||
"pending" => {
|
||||
let mut ack = false;
|
||||
while let Some(flag) = it.next() {
|
||||
match flag.as_str() {
|
||||
"--ack" if !ack => ack = true,
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
}
|
||||
Ok(Request::Pending { ack })
|
||||
}
|
||||
"tail" => {
|
||||
let mut room = None;
|
||||
while let Some(flag) = it.next() {
|
||||
match flag.as_str() {
|
||||
"--room" => {
|
||||
let val = it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"))?;
|
||||
if room.replace(val).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
}
|
||||
Ok(Request::Tail { room })
|
||||
}
|
||||
"say" => {
|
||||
let (mut room, mut text, mut resend) = (None, None, None);
|
||||
while let Some(flag) = it.next() {
|
||||
let val = it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"))?;
|
||||
let slot = match flag.as_str() {
|
||||
"--room" => &mut room,
|
||||
"--text" => &mut text,
|
||||
"--resend" => &mut resend,
|
||||
_ => bail!("{USAGE}"),
|
||||
};
|
||||
if slot.replace(val).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
let room = room.ok_or_else(|| anyhow!("{USAGE}"))?;
|
||||
if text.is_some() == resend.is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
Ok(Request::Say { room, text, resend })
|
||||
}
|
||||
"ack" => {
|
||||
let mut through = None;
|
||||
while let Some(flag) = it.next() {
|
||||
match flag.as_str() {
|
||||
"--through" => {
|
||||
let raw = it.next().ok_or_else(|| anyhow!("{USAGE}"))?;
|
||||
let parsed = raw.parse::<u64>().map_err(|_| anyhow!("--through must be u64"))?;
|
||||
if through.replace(parsed).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
}
|
||||
Ok(Request::Ack { through: through.ok_or_else(|| anyhow!("{USAGE}"))? })
|
||||
}
|
||||
"mark-read" => {
|
||||
let (mut room, mut event, mut at) = (None, None, None);
|
||||
while let Some(flag) = it.next() {
|
||||
let val = it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"))?;
|
||||
match flag.as_str() {
|
||||
"--room" => {
|
||||
if room.replace(val).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
"--event" => {
|
||||
if event.replace(val).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
"--at" => {
|
||||
let parsed = val.parse::<u64>().map_err(|_| anyhow!("--at must be u64"))?;
|
||||
if at.replace(parsed).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
}
|
||||
Ok(Request::MarkRead {
|
||||
room: room.ok_or_else(|| anyhow!("{USAGE}"))?,
|
||||
event: event.ok_or_else(|| anyhow!("{USAGE}"))?,
|
||||
at_unix_ms: at.ok_or_else(|| anyhow!("{USAGE}"))?,
|
||||
})
|
||||
}
|
||||
"open-direct" => {
|
||||
let (mut user, mut text) = (None, None);
|
||||
while let Some(flag) = it.next() {
|
||||
let val = it.next().cloned().ok_or_else(|| anyhow!("{USAGE}"))?;
|
||||
let slot = match flag.as_str() {
|
||||
"--user" => &mut user,
|
||||
"--text" => &mut text,
|
||||
_ => bail!("{USAGE}"),
|
||||
};
|
||||
if slot.replace(val).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
Ok(Request::OpenDirect {
|
||||
user: user.ok_or_else(|| anyhow!("{USAGE}"))?,
|
||||
text: text.ok_or_else(|| anyhow!("{USAGE}"))?,
|
||||
})
|
||||
}
|
||||
"status" => {
|
||||
if !args.is_empty() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
Ok(Request::Status)
|
||||
}
|
||||
_ => bail!("{USAGE}"),
|
||||
}
|
||||
}
|
||||
|
||||
enum DirectFailure {
|
||||
Misconfigured(anyhow::Error),
|
||||
Unavailable(anyhow::Error),
|
||||
}
|
||||
|
||||
fn run_direct(request: Request) -> std::result::Result<Answer, DirectFailure> {
|
||||
let load_config = || -> Result<(Config, RudpChat)> {
|
||||
let instance = Slug(required_env("EUREKA_INSTANCE")?);
|
||||
instance.validate_slug().map_err(|r| anyhow!("invalid EUREKA_INSTANCE: {r:?}"))?;
|
||||
let state_dir = PathBuf::from(required_env("STATE_DIRECTORY")?);
|
||||
let minds = setting("MIND_PERSONA_MINDS").map(|s| split_csv(&s)).unwrap_or_default();
|
||||
let operators = setting("MIND_PERSONA_OPERATOR").map(|s| split_csv(&s)).unwrap_or_default();
|
||||
let own_sender = setting("MIND_PERSONA_SELF_SENDER").unwrap_or_else(|| format!("@{}:gamecult.org", instance.0));
|
||||
let daily_cap = setting("MIND_CHAT_DAILY_CAP")
|
||||
.map(|v| v.parse::<u32>().map_err(|_| anyhow!("MIND_CHAT_DAILY_CAP must be an integer")))
|
||||
.transpose()?;
|
||||
let chat = open_rudp(&instance.0)?;
|
||||
Ok((Config { instance, state_dir, minds, operators, own_sender, daily_cap }, chat))
|
||||
};
|
||||
let (config, chat) = load_config().map_err(DirectFailure::Misconfigured)?;
|
||||
let mut engine = Engine::open(config, chat, now_ms()).map_err(DirectFailure::Unavailable)?;
|
||||
engine.handle(request, now_ms()).map_err(DirectFailure::Unavailable)
|
||||
}
|
||||
|
||||
#[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments")]
|
||||
fn main() {
|
||||
restrict_umask();
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if args.is_empty() || matches!(args[0].as_str(), "-h" | "--help" | "help") {
|
||||
println!("{USAGE}");
|
||||
return;
|
||||
}
|
||||
if args[0] == "gate" {
|
||||
if let Err(error) = run_gate(&args[1..]) {
|
||||
eprintln!("mind-chat: {error:#}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let request = match parse_client_request(&args[0], &args[1..]) {
|
||||
Ok(req) => req,
|
||||
Err(error) => {
|
||||
eprintln!("InvalidInput: {error:#}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
|
||||
let answer = if let Some(socket) = setting("MIND_CHAT_SOCKET") {
|
||||
match call_socket(Path::new(&socket), &request) {
|
||||
Ok(ans) => ans,
|
||||
Err(error) => {
|
||||
eprintln!("Unavailable: {error:#}");
|
||||
std::process::exit(3);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match run_direct(request) {
|
||||
Ok(ans) => ans,
|
||||
Err(DirectFailure::Misconfigured(error)) => {
|
||||
eprintln!("Misconfigured: {error:#}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
Err(DirectFailure::Unavailable(error)) => {
|
||||
eprintln!("Unavailable: {error:#}");
|
||||
std::process::exit(3);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if !answer.stdout.is_empty() {
|
||||
println!("{}", answer.stdout);
|
||||
}
|
||||
if !answer.stderr.is_empty() {
|
||||
eprintln!("{}", answer.stderr);
|
||||
}
|
||||
std::process::exit(i32::from(answer.exit));
|
||||
}
|
||||
1299
crates/mind-body/src/chat_gate.rs
Normal file
1299
crates/mind-body/src/chat_gate.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -35,6 +35,7 @@
|
|||
|
||||
mod address;
|
||||
pub mod chat_client;
|
||||
pub mod chat_gate;
|
||||
#[allow(dead_code, reason = "the loader is kept for the three-stage turn's perception (map C3): its first caller removes this allow; `Image` is live through `self_run::session`")]
|
||||
mod chat_image;
|
||||
pub mod chat_rudp;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
mind_body: mod chat_client
|
||||
mind_body: mod chat_gate
|
||||
mind_body: mod chat_rudp
|
||||
mind_body: mod cli
|
||||
mind_body: mod connector
|
||||
|
|
@ -100,6 +101,18 @@ mind_body::chat_client: struct MouthRefused # [derive (Clone , Copy , Debug , Pa
|
|||
mind_body::chat_client: struct ReplyTo # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[event_id: String, sender: String, excerpt: Option < String >, at_cap: bool]
|
||||
mind_body::chat_client: struct SendBasis # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[seen_event_id: Option < String >, since_unix_ms: u64]
|
||||
mind_body::chat_client: struct TailLine # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[room: String, event_id: String, at_unix_ms: u64, sender: String, form: Form, basis: Option < Basis >, body: String, reply_to: ReplyLink]
|
||||
mind_body::chat_gate: # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] # [serde (tag = "op" , rename_all = "snake_case" , deny_unknown_fields)] pub enum Request { Pending { ack : bool , } , Tail { room : Option < String > , } , Say { room : String , text : Option < String > , resend : Option < String > , } , Ack { through : u64 , } , MarkRead { room : String , event : String , at_unix_ms : u64 , } , OpenDirect { user : String , text : String , } , Status , }
|
||||
mind_body::chat_gate: const STATE_FILE : & str
|
||||
mind_body::chat_gate: const UNSETTLED_WINDOW_S : i64
|
||||
mind_body::chat_gate: fn call_socket (socket : & Path , request : & Request) -> Result < Answer >
|
||||
mind_body::chat_gate: fn serve_gate (config : Config , chat : impl Chat , socket : & Path , now_ms : impl Fn () -> u64) -> Result < () >
|
||||
mind_body::chat_gate: impl Answer
|
||||
mind_body::chat_gate: impl< C : Chat > Engine < C >
|
||||
mind_body::chat_gate: impl< C : Chat > Engine < C >: fn handle (& mut self , request : Request , now_ms : u64) -> Result < Answer >
|
||||
mind_body::chat_gate: impl< C : Chat > Engine < C >: fn open (config : Config , chat : C , now_ms : u64) -> Result < Self >
|
||||
mind_body::chat_gate: struct Answer # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[exit: u8, stdout: String, stderr: String]
|
||||
mind_body::chat_gate: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[instance: Slug, state_dir: PathBuf, minds: Vec < String >, operators: Vec < String >, own_sender: String, daily_cap: Option < u32 >]
|
||||
mind_body::chat_gate: struct Engine< C : Chat > pub-fields[]
|
||||
mind_body::chat_image: impl Skip
|
||||
mind_body::chat_rudp: fn connection_id (key_file_text : & str) -> u32
|
||||
mind_body::chat_rudp: impl Chat for RudpChat
|
||||
|
|
|
|||
Loading…
Reference in a new issue