Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/crates/hive-feed/src/main.rs # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / crates / hive-feed / src / main.rs` 120 lines ยท 7807 bytes Raw Blame History 1 mod feed; 2 mod privacy; 3 mod source; 4 5 use chrono::{DateTime, Utc}; 6 use std::{fs::{self, File, OpenOptions}, io::{self, Read, Write}, os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}, path::{Path, PathBuf}, time::{Duration, Instant}}; 7 8 struct Options { replies: bool, once: bool, out: PathBuf, sessions: PathBuf, hosts: Option, since: i64, salt: PathBuf, claude: PathBuf, codex: PathBuf, own_emails: PathBuf } 9 fn options() -> Result { 10 let home = std::env::var_os("HOME").map(PathBuf::from).ok_or("HOME is unavailable")?; 11 parse(std::env::args().skip(1), &home) 12 } 13 fn parse(mut args: impl Iterator, home: &Path) -> Result { 14 let mut opts = Options { replies: true, once: false, out: PathBuf::new(), sessions: home.join(".omp/agent/sessions"), hosts: None, since: Utc::now().timestamp_millis(), salt: home.join(".local/state/hive-feed/salt"), claude: home.join(".claude/projects"), codex: home.join(".codex/sessions"), own_emails: home.join(".local/state/aienos-hive/own-emails.txt") }; 15 while let Some(arg) = args.next() { 16 if arg == "--once" { opts.once = true; continue; } 17 if arg == "--hold-replies" { opts.replies = false; continue; } 18 if arg == "--help" { println!("hive-feed [--once] [--hold-replies] --out PATH [--sessions DIR] [--claude DIR] [--codex DIR] [--own-emails PATH] [--hosts-file PATH] [--since RFC3339] [--salt PATH]\nDefault: poll every second. Conversation starts at startup unless --since is supplied. Agents, their states and their final replies are published (--hold-replies stops replies); human messages never. One filter screens every published string by the one sentence at the top of privacy.rs, and that sentence is the whole rule. The operator's own addresses, one per line in --own-emails (a missing file lists none), publish as written. Keep --salt private. No raw transcript, arguments or source errors are logged."); std::process::exit(0); } 19 let value = args.next().ok_or("missing option value")?; 20 match arg.as_str() { 21 "--out" => opts.out = value.into(), "--sessions" => opts.sessions = value.into(), "--hosts-file" => opts.hosts = Some(value.into()), "--salt" => opts.salt = value.into(), 22 "--claude" => opts.claude = value.into(), "--codex" => opts.codex = value.into(), "--own-emails" => opts.own_emails = value.into(), 23 "--since" => opts.since = DateTime::parse_from_rfc3339(&value).map_err(|_| "invalid --since timestamp")?.timestamp_millis(), 24 _ => return Err("unknown option"), 25 } 26 } 27 if opts.out.as_os_str().is_empty() { return Err("--out is required"); } 28 if opts.out == opts.salt { return Err("output and private salt must be separate"); } 29 Ok(opts) 30 } 31 fn salt(path: &Path) -> io::Result> { 32 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { fs::create_dir_all(parent)?; } 33 match OpenOptions::new().write(true).create_new(true).mode(0o600).open(path) { 34 Ok(mut f) => { let mut bytes = [0u8;32]; File::open("/dev/urandom")?.read_exact(&mut bytes)?; f.write_all(&bytes)?; f.sync_all()?; Ok(bytes.to_vec()) }, 35 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { 36 let meta = fs::symlink_metadata(path)?; 37 if !meta.is_file() || meta.permissions().mode() & 0o077 != 0 || meta.nlink() != 1 { return Err(io::Error::other("unsafe private salt")); } 38 let bytes = fs::read(path)?; 39 if bytes.len() != 32 { return Err(io::Error::other("invalid private salt")); } 40 Ok(bytes) 41 }, Err(e) => Err(e), 42 } 43 } 44 /// The operator's own email addresses, one per line; `#` starts a comment line. 45 /// A missing file lists none, so every address is withheld. 46 fn own_emails(path: &Path) -> io::Result> { 47 match fs::read_to_string(path) { 48 Ok(text) => Ok(text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).map(str::to_owned).collect()), 49 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(Vec::new()), 50 Err(e) => Err(e), 51 } 52 } 53 fn publish(path: &Path, bytes: &[u8]) -> io::Result<()> { 54 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { fs::create_dir_all(parent)?; } 55 let tmp = path.with_extension(format!("hive-{}.tmp",std::process::id())); 56 let mut f = OpenOptions::new().write(true).create_new(true).mode(0o644).open(&tmp)?; 57 // Ephemeral feed: runtime atomicity only, no crash durability; fsync stalls the 1 s cadence. 58 let result = f.write_all(bytes).and_then(|_| fs::rename(&tmp,path)); 59 if result.is_err() { let _ = fs::remove_file(&tmp); } 60 result 61 } 62 fn run() -> Result<(), &'static str> { 63 let opts = options()?; 64 let key = salt(&opts.salt).map_err(|_| "private salt unavailable or unsafe")?; 65 let own = own_emails(&opts.own_emails).map_err(|_| "own email list unreadable")?; 66 if own.is_empty() { eprintln!("hive-feed: the own email list is missing or empty, so every address is withheld"); } 67 privacy::set_own_emails(own)?; 68 let mut collector = feed::Collector::new(key,opts.since).with_replies(opts.replies); 69 if opts.hosts.is_none() { 70 collector = collector.with_transcripts(source::Transcript::Claude, opts.claude).with_transcripts(source::Transcript::Codex, opts.codex); 71 } 72 loop { 73 let start = Instant::now(); 74 let snapshot = collector.poll(&opts.sessions,opts.hosts.as_deref(),Utc::now().timestamp_millis()); 75 let bytes = serde_json::to_vec(&snapshot).map_err(|_| "snapshot encoding failed")?; 76 if publish(&opts.out,&bytes).is_err() { if opts.once { return Err("snapshot publication failed"); } eprintln!("hive-feed: snapshot publication failed"); } 77 if opts.once { return Ok(()); } 78 std::thread::sleep(Duration::from_secs(1).saturating_sub(start.elapsed())); 79 } 80 } 81 fn main() { if let Err(error) = run() { eprintln!("hive-feed: {error}"); std::process::exit(1); } } 82 83 #[cfg(test)] 84 mod config_tests { 85 use super::*; 86 #[test] 87 fn missing_own_email_list_lists_none() { 88 let file = std::env::temp_dir().join(format!("hive-missing-own-emails-{}", std::process::id())); 89 assert!(!file.exists()); 90 assert!(own_emails(&file).unwrap().is_empty()); 91 } 92 #[test] 93 fn own_email_list_skips_blanks_and_comments() { 94 let file = std::env::temp_dir().join(format!("hive-own-emails-{}", std::process::id())); 95 fs::write(&file, "# mine\n\n owner@example.org \n").unwrap(); 96 let result = own_emails(&file); 97 fs::remove_file(&file).unwrap(); 98 assert_eq!(result.unwrap(), vec!["owner@example.org".to_owned()]); 99 } 100 #[test] 101 fn unreadable_own_email_list_is_refused() { 102 let dir = std::env::temp_dir().join(format!("hive-own-emails-dir-{}", std::process::id())); 103 fs::create_dir(&dir).unwrap(); 104 let result = own_emails(&dir); 105 fs::remove_dir(&dir).unwrap(); 106 assert!(result.is_err()); 107 } 108 fn args(list: &[&str]) -> impl Iterator { list.iter().map(|a| a.to_string()).collect::>().into_iter() } 109 #[test] 110 fn replies_are_on_unless_held() { 111 let home = Path::new("/home/test"); 112 let opts = parse(args(&["--out", "/tmp/live.json"]), home).unwrap(); 113 assert!(opts.replies); 114 assert_eq!(opts.own_emails, home.join(".local/state/aienos-hive/own-emails.txt")); 115 assert!(!parse(args(&["--hold-replies", "--out", "/tmp/live.json"]), home).unwrap().replies); 116 assert_eq!(parse(args(&["--own-emails", "/tmp/o.txt", "--out", "/tmp/l.json"]), home).unwrap().own_emails, PathBuf::from("/tmp/o.txt")); 117 assert!(parse(args(&["--replies"]), home).is_err()); 118 assert!(parse(args(&[]), home).is_err()); 119 } 120 }