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/feed.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 / feed.rs` 527 lines · 36882 bytes Raw Blame History 1 use crate::{privacy::{label, public_text}, source::{self, Cursor}}; 2 use chrono::{DateTime, SecondsFormat, Utc}; 3 use hmac::{Hmac, Mac}; 4 use serde::Serialize; 5 use serde_json::Value; 6 use sha2::Sha256; 7 use std::{collections::{BTreeMap, HashMap, HashSet, VecDeque}, path::{Path, PathBuf}}; 8 9 pub fn timestamp(ms: i64) -> String { DateTime::::from_timestamp_millis(ms).unwrap_or(DateTime::::UNIX_EPOCH).to_rfc3339_opts(SecondsFormat::Millis, true) } 10 pub fn milliseconds(value: &Value) -> Option { value.as_i64().or_else(|| value.as_str().and_then(|s| DateTime::parse_from_rfc3339(s).ok()).map(|t| t.timestamp_millis())) } 11 fn text<'a>(v: &'a Value, key: &str) -> &'a str { v[key].as_str().unwrap_or("") } 12 fn safe_date(v: &Value) -> Option { milliseconds(v).map(timestamp) } 13 /// Text parts only: tool calls, tool results, images and reasoning are never joined. 14 fn joined_text(content: &Value) -> String { 15 if let Some(s) = content.as_str() { return s.to_owned(); } 16 let mut joined = String::new(); 17 for part in content.as_array().into_iter().flatten() { 18 if !matches!(text(part,"type"), "text" | "input_text" | "output_text") { continue; } 19 if let Some(t) = part["text"].as_str() { if !joined.is_empty() { joined.push('\n'); } joined.push_str(t); } 20 } 21 joined 22 } 23 24 #[derive(Clone, Serialize)] 25 pub struct Agent { 26 pub id: String, pub parent_id: Option, pub name: String, pub runtime: String, 27 pub provider: String, pub model: String, pub role: String, pub task: String, pub status: String, 28 pub activity: String, pub activity_state: String, pub started_at: Option, pub updated_at: Option, pub observed_at: String, 29 } 30 /// Claude Code and Codex transcript directories are listed this often, and a 31 /// transcript counts as a live session while written within the active window. 32 const TRANSCRIPT_RESCAN_MS: i64 = 10_000; 33 const TRANSCRIPT_ACTIVE_MS: i64 = 15 * 60_000; 34 /// The receiver, the client validator and this collector share one window size. 35 const INTERACTION_WINDOW: usize = 100; 36 #[derive(Clone, Serialize)] 37 pub struct Interaction { pub id: String, pub agent_id: String, pub role: String, pub text: String, pub at: String, pub runtime: String, pub provider: String, pub model: String } 38 #[derive(Serialize)] 39 pub struct Coverage { label: &'static str, roots: usize, agents: usize, complete: bool, notice: String } 40 #[derive(Serialize)] 41 pub struct Feed { schema_version: u8, generated_at: String, sequence: String, poll_ms: u32, stale_after_ms: u32, coverage: Coverage, agents: Vec, interactions: Vec } 42 /// Why an agent stopped making progress, read from its own runtime's error 43 /// record (never from human text). `until` is when the provider said it lifts. 44 #[derive(Clone, Copy, Debug, PartialEq)] 45 pub enum Stop { Usage, Capacity } 46 /// Where the limit came from. A token window lifts on a later under-100 count. 47 /// A turn's usage or capacity limit lifts on a finished turn, or when `until` passes. 48 #[derive(Clone, Copy, Debug, PartialEq)] 49 pub enum LimitSource { TokenWindow, Turn } 50 /// The record only. The idle sentence is derived on each poll and never stored. 51 #[derive(Clone, Copy, Debug, PartialEq)] 52 pub struct Limit { pub stop: Stop, pub until: Option, pub source: LimitSource } 53 /// The two public sentence openings. The page's universe view keys its rings on these exact 54 /// prefixes; a test reads om/hive-page/hive-js.om so a wording change fails loudly. 55 pub const USAGE_PREFIX: &str = "Idle: provider usage limit"; 56 pub const CAPACITY_PREFIX: &str = "Idle: provider at capacity"; 57 /// Classify a runtime error message. Only fixed phrases and a number are read; 58 /// the message itself is never published. 59 pub fn classify(message: &str, at: i64) -> Option { 60 let m = message.to_ascii_lowercase(); 61 let stop = if m.contains("usage limit") || m.contains("hit your limit") || m.contains("limit reached") || m.contains("rate_limit_reached") { Stop::Usage } 62 else if m.contains("at capacity") || m.contains("overloaded") { Stop::Capacity } else { return None; }; 63 // "try again in ~90 min", "try again in 4 hours and 31 minutes": every number must name its unit. 64 let wait = m.find("try again in").and_then(|i| { 65 let mut total = 0i64; let mut seen = false; 66 for part in m[i + 12..].split(" and ") { 67 let part = part.trim_start_matches(['~', ' ']); 68 let digits: String = part.chars().take_while(|c| c.is_ascii_digit()).collect(); 69 let Ok(n) = digits.parse::() else { break; }; 70 let unit = part[digits.len()..].trim_start(); 71 let scale = if unit.starts_with("min") { 60_000 } else if unit.starts_with("hour") { 3_600_000 } else if unit.starts_with("sec") { 1000 } else if unit.starts_with("day") { 86_400_000 } else { return None; }; 72 total = total.checked_add(n.checked_mul(scale)?)?; seen = true; 73 } 74 if seen { at.checked_add(total) } else { None } 75 }); 76 let epoch = m.find("limit reached|").and_then(|i| m[i + 14..].chars().take_while(|c| c.is_ascii_digit()).collect::().parse::().ok()).and_then(|s| s.checked_mul(1000)); 77 Some(Limit { stop, until: wait.or(epoch), source: LimitSource::Turn }) 78 } 79 /// Codex reports its windows with every token count: a window at 100 percent, 80 /// or a named reached type, is a usage limit until the latest such reset. 81 pub fn codex_limit(r: &Value) -> Option { 82 let full: Vec<&Value> = ["primary","secondary"].iter().map(|w| &r[*w]).filter(|w| w["used_percent"].as_f64().is_some_and(|u| u >= 100.0)).collect(); 83 let reached = r["rate_limit_reached_type"].as_str().is_some_and(|t| !t.is_empty()); 84 if full.is_empty() && !reached { return None; } 85 let until = full.iter().filter_map(|w| w["resets_at"].as_i64()).max().and_then(|s| s.checked_mul(1000)); 86 Some(Limit { stop: Stop::Usage, until, source: LimitSource::TokenWindow }) 87 } 88 /// A branch the tests turn off. `SentenceSkip` publishes the idle sentence with no 89 /// filter. `UniverseSkip` publishes the universe title from the raw fields. 90 #[derive(Clone, Copy, PartialEq, Eq)] 91 pub enum PathMutant { None, SentenceSkip, #[cfg(test)] UniverseSkip } 92 93 /// The same filter as every other public string. A skipped gate returns the raw text. 94 pub fn screen(text: &str, mutant: PathMutant) -> String { 95 if mutant == PathMutant::SentenceSkip { return text.to_owned(); } 96 public_text(text, 4_000).unwrap_or_else(|| "No action observed".into()) 97 } 98 99 /// The title the universe view writes from the name, status and activity it reads 100 /// off the rendered feed. Each field is screened unless the gate is skipped. 101 #[cfg(test)] 102 pub fn universe_title(name: &str, status: &str, activity: &str, mutant: PathMutant) -> String { 103 let show = |part: &str| if mutant == PathMutant::UniverseSkip { part.to_owned() } else { screen(part, PathMutant::None) }; 104 [show(name), show(status), show(activity)].into_iter().filter(|s| !s.is_empty()).collect::>().join(" | ") 105 } 106 107 /// The idle sentence before the filter. `screened_sentence` is what a poll publishes. 108 pub fn stop_sentence(limit: &Limit) -> String { 109 let when = limit.until.and_then(DateTime::::from_timestamp_millis).map(|t| t.format("%Y-%m-%d %H:%M UTC").to_string()); 110 match (limit.stop, when) { 111 (Stop::Usage, Some(t)) => format!("{USAGE_PREFIX} reached; the provider says it resets about {t}"), 112 (Stop::Usage, None) => format!("{USAGE_PREFIX} reached; reset time not reported"), 113 (Stop::Capacity, _) => format!("{CAPACITY_PREFIX}; the agent's last request was refused"), 114 } 115 } 116 117 pub fn screened_sentence(limit: &Limit, mutant: PathMutant) -> String { 118 screen(&stop_sentence(limit), mutant) 119 } 120 struct Node { public: Agent, root: String, seen: i64, terminal: Option, tools: BTreeMap, placeholder: bool, unavailable: Option<(String,String)>, limit: Option } 121 pub struct Collector { 122 salt: Vec, since: i64, sequence: u64, nodes: BTreeMap, cursors: HashMap, 123 interactions: VecDeque, seen_events: HashSet, known_hosts: HashMap, task_summaries: HashMap, 124 /// Agents' final replies are public by default (Drake, 2026-11-14: "everything I 125 /// am doing is public"); --hold-replies turns them off. Human messages never publish. 126 replies: bool, 127 /// Claude Code and Codex transcript directories, observed while recently written. 128 transcripts: Vec<(source::Transcript, PathBuf)>, active_transcripts: Vec<(source::Transcript, PathBuf, i64)>, transcript_scan: Option, 129 } 130 impl Collector { 131 pub fn new(salt: Vec, since: i64) -> Self { Self { replies: true, salt, since, sequence: 0, nodes: BTreeMap::new(), cursors: HashMap::new(), interactions: VecDeque::new(), seen_events: HashSet::new(), known_hosts: HashMap::new(), task_summaries: HashMap::new(), transcripts: Vec::new(), active_transcripts: Vec::new(), transcript_scan: None } } 132 pub fn with_replies(mut self, on: bool) -> Self { self.replies = on; self } 133 /// Also observe Claude Code or Codex transcripts under `dir`. 134 pub fn with_transcripts(mut self, kind: source::Transcript, dir: PathBuf) -> Self { self.transcripts.push((kind,dir)); self } 135 fn id(&self, private: &str) -> String { 136 let mut mac = Hmac::::new_from_slice(&self.salt).expect("HMAC accepts any key length"); mac.update(private.as_bytes()); 137 let digest = mac.finalize().into_bytes(); let mut out = String::from("h"); 138 for byte in &digest[..16] { use std::fmt::Write; let _ = write!(out, "{byte:02x}"); } out 139 } 140 fn ensure(&mut self, key: &str, root: &str, parent: Option<&str>, name: &str, now: i64) { 141 if self.nodes.contains_key(key) { return; } 142 let id = self.id(key); let parent_id = parent.map(|p| self.id(p)); 143 let summary = self.task_summaries.get(key); 144 self.nodes.insert(key.to_owned(), Node { public: Agent { id, parent_id, name: label(name, "Agent"), runtime: "OMP".into(), provider: "unknown".into(), model: "unknown".into(), role: if parent.is_some() { "worker" } else { "root" }.into(), task: summary.cloned().unwrap_or_else(|| label(name, "Task label withheld")), status: "unknown".into(), activity: "No action observed".into(), activity_state: "unknown".into(), started_at: None, updated_at: None, observed_at: timestamp(now) }, root: root.to_owned(), seen: now, terminal: None, tools: BTreeMap::new(), placeholder: true, unavailable: None, limit: None }); 145 } 146 fn model(node: &mut Node, raw: &str, provider: Option<&str>) { 147 let (p,m) = if let Some(p) = provider { (p,raw) } else { raw.split_once('/').unwrap_or(("unknown",raw)) }; 148 node.public.provider = label(p, "withheld"); node.public.model = label(m, "withheld"); 149 } 150 fn child_key(root: &str, parent: &str, name: &str) -> String { 151 if name.contains('.') || parent == root { format!("{root}/{name}") } else { format!("{parent}.{name}") } 152 } 153 fn assignment_summaries(&mut self, args: &Value, root: &str, parent: &str) { 154 let Some(tasks) = args["tasks"].as_array() else { return; }; 155 for task in tasks { 156 let name = text(task,"name"); 157 if name.trim().is_empty() { continue; } 158 // This is the sole public assignment-summary field. Never use task, 159 // context or any other tool argument as a display fallback. 160 let Some(summary) = public_text(text(task,"solutionSpace"),180) else { continue; }; 161 let key = Self::child_key(root,parent,name); 162 if let Some(node) = self.nodes.get_mut(&key) { 163 node.public.task = summary.clone(); 164 } 165 // Do not create a live worker merely because a spawn was requested. 166 self.task_summaries.insert(key,summary); 167 } 168 } 169 /// A finished turn lifts whatever limit is recorded. The sentence was never stored. 170 fn finish_turn(node: &mut Node) { node.limit = None; } 171 /// Activity and status for this poll. A tool still in the map counts only while its 172 /// transcript is readable; a missing file is not a running tool. Host busy hides 173 /// the sentence on that host session only. Anything else with a live limit is the 174 /// sentence and idle. 175 fn shown(node: &Node, now: i64, transcript: bool, host_busy: bool) -> (String, String) { 176 let running = transcript && (node.public.activity_state == "running" || !node.tools.is_empty()); 177 if !running && !host_busy { 178 if let Some(limit) = node.limit.filter(|l| l.until.is_none_or(|u| now < u)) { 179 return (screened_sentence(&limit, PathMutant::None), "idle".into()); 180 } 181 } 182 let activity = if node.public.activity.starts_with(USAGE_PREFIX) || node.public.activity.starts_with(CAPACITY_PREFIX) { "No action observed" } else { node.public.activity.as_str() }; 183 (activity.to_owned(), node.public.status.clone()) 184 } 185 fn terminal(&mut self, key: &str, status: &str, now: i64) { 186 if let Some(node) = self.nodes.get_mut(key) { 187 node.public.status = status.into(); node.public.activity_state = "finished".into(); node.tools.clear(); node.terminal = Some(now); 188 } 189 } 190 fn event(&mut self, key: &str, value: &Value, now: i64) { 191 let Some(root) = self.nodes.get(key).map(|n| n.root.clone()) else { return; }; 192 let kind = text(value,"type"); let custom = text(value,"customType"); 193 let at = safe_date(&value["timestamp"]); 194 let event_time = milliseconds(&value["timestamp"]).unwrap_or(now); 195 if let Some(node) = self.nodes.get_mut(key) { 196 node.placeholder = false; 197 // Session titles ("title" events, host sessionName) are generated from 198 // the human's first prompt, so they are never published. 199 if kind == "session" { node.public.started_at = at.clone(); } 200 if kind == "session_init" { 201 node.public.role = label(text(value,"agent"), "worker"); 202 Self::model(node, text(value,"resolvedModel"), None); 203 node.public.status = "working".into(); 204 } 205 if kind == "model_usage" { 206 let data = value.get("data").unwrap_or(value); 207 if let Some(model) = data["model"].as_str() { Self::model(node, model, data["provider"].as_str()); } 208 } 209 if custom == "tool_execution_start" { 210 let d = &value["data"]; let tool = label(text(d,"toolName"), "tool"); 211 let intent = text(d,"intent"); 212 // Both halves are filtered. When the joined "tool: intent" would read as a label and 213 // value (a tool named "password"), the halves are joined with " · " instead. 214 let action = public_text(intent, 180).map(|i| { 215 let joined = format!("{tool}: {i}"); 216 let joined = if crate::privacy::redact(&joined, &std::collections::HashSet::new()) == joined { joined } else { format!("{tool} · {i}") }; 217 crate::privacy::cut(&joined, 180) 218 }).unwrap_or_else(|| tool.clone()); 219 let date = safe_date(&d["startedAt"]).or(at.clone()); 220 node.tools.insert(text(d,"toolCallId").to_owned(), (action.clone(), date.clone().unwrap_or_default())); 221 node.public.activity = action; node.public.activity_state = "running".into(); node.public.status = "working".into(); node.public.updated_at = date; node.terminal = None; 222 } 223 } 224 if custom == "tool_execution_start" && value["data"]["toolName"] == "task" { 225 self.assignment_summaries(&value["data"]["args"],&root,key); 226 } 227 if custom == "session_exit" { 228 let d = &value["data"]; 229 let pending = d["pendingToolCalls"].as_array().is_some_and(|a| !a.is_empty()); 230 let state = if text(d,"kind") == "normal" && !pending { "completed" } else if matches!(text(d,"kind"), "fatal" | "signal" | "process_exit") { "failed" } else { "unknown" }; 231 self.terminal(key, state, event_time); 232 } 233 let m = value.get("message").unwrap_or(value); 234 let role = text(m,"role"); 235 // Side jobs (captions, widgets, titles) carry a purpose; their failure does not stop the agent. 236 if role == "assistant" && kind == "message" && text(value,"purpose").is_empty() && text(m,"purpose").is_empty() { 237 let stop = text(m,"stopReason"); 238 if let Some(node) = self.nodes.get_mut(key) { 239 if stop == "error" { if let Some(l) = classify(text(m,"errorMessage"), event_time) { node.limit = Some(l); } } 240 else if !stop.is_empty() { Self::finish_turn(node); } 241 } 242 } 243 if role == "assistant" { 244 if let Some(parts) = m["content"].as_array() { 245 for part in parts { 246 if part["type"] == "toolCall" && part["name"] == "task" { 247 self.assignment_summaries(&part["arguments"],&root,key); 248 } 249 } 250 } 251 } 252 if role == "toolResult" { 253 if let Some(node) = self.nodes.get_mut(key) { 254 let finished = node.tools.remove(text(m,"toolCallId")); 255 node.public.updated_at = safe_date(&m["timestamp"]).or(at.clone()); 256 if let Some((_,(action,date))) = node.tools.iter().max_by_key(|(_,(_,date))| date) { 257 node.public.activity = action.clone(); node.public.activity_state = "running".into(); 258 if !date.is_empty() { node.public.updated_at = Some(date.clone()); } 259 } else { 260 node.public.activity = finished.map(|(a,_)| a).unwrap_or_else(|| label(text(m,"toolName"), "tool")); 261 if m["isError"] == true { node.public.activity.push_str(" (reported error)"); } 262 node.public.activity_state = "finished".into(); 263 } 264 } 265 if text(m,"toolName") == "task" { 266 if let Some(progress) = m["details"]["progress"].as_array() { 267 for child in progress { 268 let name = text(child,"id"); if name.is_empty() { continue; } 269 let ck = Self::child_key(&root,key,name); self.ensure(&ck,&root,Some(key),name,now); 270 let n = self.nodes.get_mut(&ck).unwrap(); n.public.role = label(text(child,"agent"), "worker"); 271 match text(child,"status") { "pending" | "running" => { if n.placeholder { n.public.status = "waiting".into(); } }, "completed" => self.terminal(&ck,"completed",event_time), "failed" | "error" | "cancelled" => self.terminal(&ck,"failed",event_time), _ => {} } 272 } 273 } 274 } 275 } 276 if text(m,"customType") == "async-result" || custom == "async-result" { 277 let empty = Value::Null; 278 let details = m.get("details").or_else(|| value.get("data")).unwrap_or(&empty); 279 if let Some(jobs) = details["jobs"].as_array() { 280 for job in jobs { 281 if text(job,"type") != "task" { continue; } 282 let name = text(job,"agentId"); if name.is_empty() { continue; } 283 let ck = Self::child_key(&root,key,name); self.ensure(&ck,&root,Some(key),name,now); 284 match text(job,"status") { "completed" => self.terminal(&ck,"completed",event_time), "failed" | "error" | "cancelled" => self.terminal(&ck,"failed",event_time), _ => {} } 285 } 286 } 287 } 288 // Only the final text of a completed turn is a reply; narration before 289 // tool calls, tool output and reasoning stay unpublished. 290 if role != "assistant" || text(m,"stopReason") != "stop" { return; } 291 let Some(time) = milliseconds(&m["timestamp"]).or_else(|| milliseconds(&value["timestamp"])) else { return; }; 292 let joined = joined_text(&m["content"]); 293 let seed = format!("interaction:{key}:{}:{time}:{joined}", text(value,"id")); 294 self.publish(key, &joined, time, &seed, "OMP", label(text(m,"provider"),"unknown"), label(text(m,"model"),"unknown")); 295 } 296 /// Publish one agent reply after the secret filter. The public role is 297 /// always "assistant"; no other role is ever emitted. 298 #[allow(clippy::too_many_arguments)] 299 fn publish(&mut self, key: &str, reply: &str, time: i64, seed: &str, runtime: &str, provider: String, model: String) { 300 if !self.replies { return; } 301 if time < self.since || reply.trim().is_empty() { return; } 302 let Some(public) = public_text(reply,4000) else { return; }; 303 let eid = self.id(seed); 304 if !self.seen_events.insert(eid.clone()) { return; } 305 self.interactions.push_back(Interaction { id: eid, agent_id: self.id(key), role: "assistant".into(), text: public, at: timestamp(time), runtime: runtime.into(), provider, model }); 306 self.interactions.make_contiguous().sort_by(|a,b| a.at.cmp(&b.at).then(a.id.cmp(&b.id))); 307 // Flood protection balanced across agents: one busy agent must not push 308 // every other agent out of the window. Evict the oldest reply of the 309 // agent holding the most replies. 310 while self.interactions.len() > INTERACTION_WINDOW { 311 let mut counts: HashMap<&str,usize> = HashMap::new(); 312 for i in &self.interactions { *counts.entry(i.agent_id.as_str()).or_default() += 1; } 313 let most = counts.values().copied().max().unwrap_or(0); 314 let victim = self.interactions.iter().position(|i| counts[i.agent_id.as_str()] == most).unwrap_or(0); 315 if let Some(old) = self.interactions.remove(victim) { self.seen_events.remove(&old.id); } 316 } 317 } 318 fn read_transcript(&mut self, kind: source::Transcript, key: &str, path: &Path, now: i64) -> bool { 319 let cursor = self.cursors.entry(path.to_owned()).or_default(); 320 let Ok(values) = cursor.read(path) else { return false; }; 321 if let Some(n) = self.nodes.get_mut(key) { n.placeholder = false; } 322 for value in values { 323 match kind { source::Transcript::Claude => self.claude_event(key,&value), source::Transcript::Codex => self.codex_event(key,&value,now) } 324 } 325 true 326 } 327 /// Claude Code: human prompts are `user` entries with text content (tool 328 /// results excluded); a reply is the text of an `assistant` entry whose 329 /// message ended the turn (`stop_reason` `end_turn`). Sidechains are skipped. 330 fn claude_event(&mut self, key: &str, value: &Value) { 331 if value["isSidechain"] == true { return; } 332 let m = &value["message"]; 333 if text(value,"type") != "assistant" { return; } 334 if let Some(n) = self.nodes.get_mut(key) { 335 if value["isApiErrorMessage"] == true { 336 let at = milliseconds(&value["timestamp"]).unwrap_or(0); 337 let code = if text(value,"error") == "rate_limit" { "usage limit" } else { "" }; 338 if let Some(l) = classify(&format!("{code} {}", joined_text(&m["content"])), at) { n.limit = Some(l); } 339 return; 340 } 341 Self::finish_turn(n); 342 if let Some(model) = m["model"].as_str() { Self::model(n,model,Some("anthropic")); } 343 } 344 if text(m,"stop_reason") != "end_turn" { return; } 345 let Some(time) = milliseconds(&value["timestamp"]) else { return; }; 346 let seed = format!("interaction:{key}:{}", text(value,"uuid")); 347 self.publish(key,&joined_text(&m["content"]),time,&seed,"Claude Code","anthropic".into(),label(text(m,"model"),"unknown")); 348 } 349 /// Codex: human prompts are `user_message` events and user response items; 350 /// a reply is `task_complete.last_agent_message`, the final text of a turn. 351 fn codex_event(&mut self, key: &str, value: &Value, _now: i64) { 352 let p = &value["payload"]; 353 match (text(value,"type"), text(p,"type")) { 354 ("session_meta", _) => if let Some(n) = self.nodes.get_mut(key) { n.public.provider = label(text(p,"model_provider"),"unknown"); }, 355 ("turn_context", _) => if let Some(n) = self.nodes.get_mut(key) { n.public.model = label(text(p,"model"),"unknown"); }, 356 ("event_msg", "token_count") => if let Some(n) = self.nodes.get_mut(key) { 357 // A full window must not replace a turn's capacity record. 358 if !n.limit.is_some_and(|l| l.stop == Stop::Capacity && l.source == LimitSource::Turn) { 359 if let Some(limit) = codex_limit(&p["rate_limits"]) { n.limit = Some(limit); } 360 else if n.limit.is_some_and(|l| l.source == LimitSource::TokenWindow) { n.limit = None; } 361 } 362 }, 363 ("event_msg", "error") => if let Some(n) = self.nodes.get_mut(key) { if let Some(l) = classify(text(p,"message"), milliseconds(&value["timestamp"]).unwrap_or(0)) { n.limit = Some(l); } }, 364 ("event_msg", "task_complete") => { 365 let Some(time) = milliseconds(&value["timestamp"]) else { return; }; 366 if let Some(n) = self.nodes.get_mut(key) { Self::finish_turn(n); } 367 let (provider,model) = self.nodes.get(key).map(|n| (n.public.provider.clone(),n.public.model.clone())).unwrap_or_else(|| ("unknown".into(),"unknown".into())); 368 let seed = format!("interaction:{key}:{time}:{}", text(p,"turn_id")); 369 self.publish(key,text(p,"last_agent_message"),time,&seed,"Codex",provider,model); 370 } 371 _ => {} 372 } 373 } 374 fn read_node(&mut self, key: &str, path: &Path, now: i64) -> bool { 375 let terminal = self.nodes.get(key).and_then(|n| n.terminal.map(|t| (t,n.public.status.clone()))); 376 let cursor = self.cursors.entry(path.to_owned()).or_default(); 377 let result = cursor.read(path); let damaged = cursor.damaged; 378 match result { 379 Ok(values) => { 380 if !damaged { 381 if let Some(node) = self.nodes.get_mut(key) { if let Some((status,activity)) = node.unavailable.take() { node.public.status = status; node.public.activity_state = activity; } } 382 } 383 let latest = values.iter().filter(|v| v["customType"] == "tool_execution_start" || v["customType"] == "session_exit").filter_map(|v| milliseconds(&v["timestamp"])).max().unwrap_or(0); 384 for value in values { self.event(key,&value,now); } 385 if let Some((time,status)) = terminal { if latest <= time { self.terminal(key,&status,time); } } 386 !damaged 387 }, 388 Err(_) => false, 389 } 390 } 391 pub fn poll(&mut self, sessions: &Path, fixture: Option<&Path>, now: i64) -> Feed { 392 self.sequence += 1; 393 let absent: Vec<_> = self.cursors.keys().filter(|p| !p.exists()).cloned().collect(); 394 for path in absent { if let Some(cursor) = self.cursors.get_mut(&path) { cursor.forget(); } } 395 let mut faults = 0usize; let mut roots = HashSet::new(); let mut host_pids = HashMap::new(); let mut authoritative = HashMap::new(); 396 let mut observed = HashSet::new(); let mut readable = HashSet::new(); let mut host_busy = HashSet::new(); 397 let result = source::hosts(fixture); 398 let source_ok = result.is_ok(); 399 if let Ok(source) = result { 400 for host in source["hosts"].as_array().unwrap() { 401 let key = text(host,"sessionId"); if key.is_empty() { faults += 1; continue; } 402 roots.insert(key.to_owned()); self.ensure(key,key,None,"Coding session",now); 403 observed.insert(key.to_owned()); 404 if let Some(pid) = host["pid"].as_u64() { host_pids.insert(pid as u32,key.to_owned()); } 405 let n = self.nodes.get_mut(key).unwrap(); n.seen = now; n.terminal = None; 406 n.public.task = "Coding session".into(); n.public.name = n.public.task.clone(); 407 n.public.started_at = safe_date(&host["startedAt"]); 408 Self::model(n,text(&host["model"],"id"),host["model"]["provider"].as_str()); 409 n.public.status = if host["inputRequired"] == true { "waiting" } else { match host["busy"].as_bool() { Some(true) => "working", Some(false) => "idle", None => "unknown" } }.into(); 410 if host["busy"] == true { host_busy.insert(key.to_owned()); } 411 authoritative.insert(key.to_owned(), (n.public.status.clone(), n.public.provider.clone(), n.public.model.clone(), n.public.task.clone())); 412 } 413 self.known_hosts = host_pids.clone(); 414 } else { faults += 1; host_pids = self.known_hosts.clone(); } 415 let paths = source::root_paths(sessions,&roots); 416 let mut found = HashSet::new(); 417 if let Ok(paths) = paths { 418 for (root,path) in paths { 419 found.insert(root.clone()); 420 if !self.read_node(&root,&path,now) { 421 faults += 1; 422 if let Some(n) = self.nodes.get_mut(&root) { n.public.activity_state = "unknown".into(); } 423 } else { readable.insert(root.clone()); } 424 let stem = path.with_extension(""); 425 match source::descendants(&stem) { 426 Ok(children) => for child in children { 427 let Some(name) = child.file_stem().and_then(|n| n.to_str()) else { continue; }; 428 let key = format!("{root}/{name}"); 429 let parent_name = child.parent().filter(|p| *p != stem.as_path()).and_then(|p| p.file_name()).and_then(|p| p.to_str()); 430 let parent = parent_name.map(|p| format!("{root}/{p}")).unwrap_or_else(|| root.clone()); 431 self.ensure(&key,&root,Some(&parent),name,now); 432 if !self.read_node(&key,&child,now) { faults += 1; } else { 433 observed.insert(key.clone()); readable.insert(key.clone()); 434 if let Some(n) = self.nodes.get_mut(&key) { n.seen = now; } 435 } 436 }, Err(_) => faults += 1, 437 } 438 } 439 } else { faults += 1; } 440 faults += roots.difference(&found).count(); 441 // Process-only sessions are actual live processes, not historical transcript guesses. 442 // Their task, activity and absent model metadata remain explicitly unknown. 443 if fixture.is_none() { 444 match source::processes() { 445 Ok(processes) => { 446 let process_ids: HashMap<_,_> = processes.iter().map(|p| (p.pid,p.key.clone())).chain(host_pids.iter().map(|(p,k)| (*p,k.clone()))).collect(); 447 for p in processes { 448 if host_pids.contains_key(&p.pid) { continue; } 449 let ancestor = source::nearest_parent(p.parent,&process_ids); 450 let parent = ancestor.as_deref(); 451 self.ensure(&p.key,&p.key,parent,"Process-observed session",now); 452 observed.insert(p.key.clone()); 453 let n = self.nodes.get_mut(&p.key).unwrap(); n.seen = now; 454 n.public.runtime = p.runtime.into(); n.public.role = if p.headless { "headless worker" } else { "process-observed session" }.into(); 455 n.public.task = "Task unavailable from process metadata".into(); n.public.status = "unknown".into(); 456 Self::model(n,&p.model,None); roots.insert(p.key); 457 } 458 }, Err(_) => faults += 1, 459 } 460 } 461 // Claude Code and Codex sessions are observed through their own 462 // transcripts while those are being written. Only final replies publish. 463 if !self.transcripts.is_empty() { 464 if self.transcript_scan.is_none_or(|t| now - t >= TRANSCRIPT_RESCAN_MS) { 465 self.transcript_scan = Some(now); 466 let mut active = Vec::new(); 467 for (kind,dir) in &self.transcripts { 468 match source::recent_transcripts(*kind,dir,now,TRANSCRIPT_ACTIVE_MS) { 469 Ok(found) => active.extend(found.into_iter().map(|(p,m)| (*kind,p,m))), 470 Err(_) => faults += 1, 471 } 472 } 473 self.active_transcripts = active; 474 } 475 for (kind,path,_) in self.active_transcripts.clone() { 476 let key = format!("{}:{}", kind.runtime(), path.display()); 477 self.ensure(&key,&key,None,&format!("{} session", kind.runtime()),now); 478 if let Some(n) = self.nodes.get_mut(&key) { n.public.runtime = kind.runtime().into(); n.public.role = "transcript-observed session".into(); } 479 if !self.read_transcript(kind,&key,&path,now) { faults += 1; continue; } 480 observed.insert(key.clone()); readable.insert(key.clone()); roots.insert(key.clone()); 481 let modified = std::fs::metadata(&path).ok().and_then(|m| m.modified().ok()).and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_millis() as i64); 482 if let Some(n) = self.nodes.get_mut(&key) { 483 n.seen = now; 484 n.public.status = if modified.is_some_and(|m| now - m < 60_000) { "working" } else { "unknown" }.into(); 485 n.public.updated_at = modified.map(timestamp); 486 } 487 } 488 } 489 for (key,node) in &mut self.nodes { 490 if observed.contains(key) { 491 node.public.observed_at = timestamp(now); 492 } else if !(node.placeholder && roots.contains(&node.root) && source_ok) && (node.terminal.is_none() || !source_ok) { 493 if node.unavailable.is_none() { node.unavailable = Some((node.public.status.clone(),node.public.activity_state.clone())); } 494 node.public.status = "unknown".into(); node.public.activity_state = "unknown".into(); 495 } 496 if let Some((status,provider,model,task)) = authoritative.get(key) { 497 node.public.status = status.clone(); node.public.provider = provider.clone(); node.public.model = model.clone(); node.public.task = task.clone(); node.terminal = None; 498 if !found.contains(key) { node.public.activity_state = "unknown".into(); } 499 } 500 if node.limit.as_ref().is_some_and(|l| l.until.is_some_and(|u| now >= u)) { node.limit = None; } 501 } 502 let interaction_agents: HashSet<_> = self.interactions.iter().map(|i| i.agent_id.clone()).collect(); 503 let mut visible: HashSet = self.nodes.values().filter(|n| { 504 (n.terminal.is_none_or(|t| now - t < 120_000) && ((n.placeholder && roots.contains(&n.root)) || now - n.seen < 120_000)) || interaction_agents.contains(&n.public.id) 505 }).map(|n| n.public.id.clone()).collect(); 506 // Preserve ancestor identities so the public tree never contains dangling edges. 507 loop { 508 let before = visible.len(); 509 for n in self.nodes.values() { if visible.contains(&n.public.id) { if let Some(p) = &n.public.parent_id { visible.insert(p.clone()); } } } 510 if visible.len() == before { break; } 511 } 512 self.nodes.retain(|_,n| roots.contains(&n.root) || visible.contains(&n.public.id)); 513 let agents: Vec<_> = self.nodes.iter().filter(|(_,n)| visible.contains(&n.public.id)).map(|(key,n)| { 514 let mut agent = n.public.clone(); 515 let (activity, status) = Self::shown(n, now, readable.contains(key), host_busy.contains(key)); 516 agent.activity = activity; agent.status = status; agent 517 }).collect(); 518 let mut interactions: Vec<_> = self.interactions.iter().cloned().collect(); interactions.sort_by(|a,b| a.at.cmp(&b.at)); 519 Feed { schema_version: 1, generated_at: timestamp(now), sequence: self.id(&format!("snapshot:{now}:{}",self.sequence)), poll_ms: 1000, stale_after_ms: 15000, 520 coverage: Coverage { label: "Observed live coding sessions", roots: agents.iter().filter(|a| a.parent_id.is_none()).count(), agents: agents.len(), complete: false, 521 notice: format!("OMP collaboration trees, Claude Code and Codex transcripts being written, and recognized live coding processes. {}; human messages never are. Process-only workers have limited metadata. Other runtimes and disconnected sessions may be unobserved. {faults} source gaps this snapshot. Disappearance is unknown, not completion.", if self.replies { "Only agents' final replies are published, and a reply may quote a person's message as written" } else { "Agents' replies are held" }) }, agents, interactions } 522 } 523 } 524 525 #[cfg(test)] 526 #[path = "tests.rs"] 527 mod tests;