A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(rlm): agent_observe.recent_messages reads members no worker holds (#3778)
Sebastian Müller680c7475be64
diff --git a/Cargo.lock b/Cargo.lockindex 5e7bf30988..2d1c0945ab 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1562,6 +1562,7 @@ dependencies = ["anyhow","filetime","futures",+ "globset","nix","pa-agent","pa-ai",diff --git a/crates/pa-core/src/session/window.rs b/crates/pa-core/src/session/window.rsindex 4f43f827ca..ebc90dc62e 100644--- a/crates/pa-core/src/session/window.rs+++ b/crates/pa-core/src/session/window.rs@@ -135,6 +135,21 @@ pub struct WindowStats {pub cache_write: u64,#[serde(with = "super::window_cache::float_bits")]pub cost: f64,+ /// The prefix's display-transcript rows by [`display_role`].+ pub display_rows: HashMap<String, usize>,+}++/// The role a session row shows under in the display transcript: a message row's own role,+/// `custom` for a `custom_message` row, `compactionSummary` for a compaction; `None` for+/// rows the transcript does not show.+#[must_use]+pub fn display_role<'a>(entry_type: &str, message_role: Option<&'a str>) -> Option<&'a str> {+ match entry_type {+ "message" => message_role,+ "custom_message" => Some("custom"),+ "compaction" => Some("compactionSummary"),+ _ => None,+ }}/// One older-path assistant row's spend-relevant usage: an attribution@@ -356,6 +371,16 @@ impl WindowedSessionStore {}let on_path = expected.as_deref() == Some(id);if on_path {+ let role = display_role(+ &meta.kind,+ meta.message.as_ref().map(|message| message.role.as_str()),+ );+ if let Some(role) = role.filter(|_| window_done) {+ *older_path_stats+ .display_rows+ .entry(role.to_owned())+ .or_default() += 1;+ }if window_done && meta.kind == "message" {if let Some(message) = &meta.message {older_path_stats.total_messages += 1;diff --git a/crates/pa-core/src/session/window_cache.rs b/crates/pa-core/src/session/window_cache.rsindex 5fff3f2ede..78f2d1f1bd 100644--- a/crates/pa-core/src/session/window_cache.rs+++ b/crates/pa-core/src/session/window_cache.rs@@ -53,7 +53,7 @@ impl Generation {/// version (any other version is rebuilt by the full walk). A served/// snapshot's `WindowStats` already folds the child usage attributions,/// and unread keys are ignored on load (no `deny_unknown_fields`).-pub(super) const SNAPSHOT_VERSION: u32 = 7;+pub(super) const SNAPSHOT_VERSION: u32 = 8;// `retained_whole_file` is `#[serde(default)]` false: older sidecars// deserialize it as false and skip the full-history fast paths until the// next walk rewrites the sidecar (a version bump would force a re-walk).diff --git a/crates/pa-core/src/session_engine/agent_messaging/observe.rs b/crates/pa-core/src/session_engine/agent_messaging/observe.rsindex edaa09375e..9993d2f495 100644--- a/crates/pa-core/src/session_engine/agent_messaging/observe.rs+++ b/crates/pa-core/src/session_engine/agent_messaging/observe.rs@@ -86,6 +86,8 @@ pub struct AgentObserveSummary {/// The session's first user message, preview-capped (an inactive/// child's identity signal; TS `firstMessage`).pub first_message: Option<String>,+ /// The session's file: a transcript read of a member no worker holds opens it.+ pub session_file: Option<String>,}impl AgentObserveSummary {diff --git a/crates/pa-core/src/session_engine/agent_messaging/tests.rs b/crates/pa-core/src/session_engine/agent_messaging/tests.rsindex 10886f152a..1fa0b50634 100644--- a/crates/pa-core/src/session_engine/agent_messaging/tests.rs+++ b/crates/pa-core/src/session_engine/agent_messaging/tests.rs@@ -26,6 +26,7 @@ fn observe_rows_carry_the_typed_status_and_activity() {parent_session_id: None,rlm_child_id: None,first_message: None,+ session_file: None,};let value = row.to_value();assert_eq!(value["status"], "running");@@ -471,6 +472,7 @@ fn observe_row(active_session_id: &str, is_current: bool) -> AgentObserveSummaryparent_session_id: None,rlm_child_id: None,first_message: None,+ session_file: None,}}diff --git a/crates/pa-daemon/Cargo.toml b/crates/pa-daemon/Cargo.tomlindex 3f8a059e82..a23e65523b 100644--- a/crates/pa-daemon/Cargo.toml+++ b/crates/pa-daemon/Cargo.toml@@ -13,6 +13,7 @@ pa-ai = { path = "../pa-ai" }pa-telemetry = { path = "../pa-telemetry" }anyhow = { workspace = true }futures = { workspace = true }+globset = "0.4"serde = { workspace = true }serde_json = { workspace = true, features = ["raw_value"] }thiserror = { workspace = true }diff --git a/crates/pa-daemon/src/agent_messaging.rs b/crates/pa-daemon/src/agent_messaging.rsindex 30c15c7a46..bdfee41063 100644--- a/crates/pa-daemon/src/agent_messaging.rs+++ b/crates/pa-daemon/src/agent_messaging.rs@@ -191,7 +191,7 @@ mod message;mod observe;pub use message::LinkAgentMessageController;-pub(crate) use observe::LinkAgentObserveController;+pub use observe::LinkAgentObserveController;#[cfg(test)]mod controller_tests;diff --git a/crates/pa-daemon/src/agent_messaging/controller_tests.rs b/crates/pa-daemon/src/agent_messaging/controller_tests.rsindex d3795f7d48..e29aeacd31 100644--- a/crates/pa-daemon/src/agent_messaging/controller_tests.rs+++ b/crates/pa-daemon/src/agent_messaging/controller_tests.rs@@ -60,7 +60,8 @@ async fn spawn_fake_supervisor(),// Target-specific transcripts let resolver regressions prove// which worker was read; older fixtures retain their five-row tail.- "get_messages" => {+ // Serves the tail reads (`start = -limit`) recent messages sends.+ "get_session_messages" => {let active = command["activeSessionId"].as_str().unwrap_or_default();let messages = roster["messagesByActiveSessionId"].get(active)@@ -71,13 +72,23 @@ async fn spawn_fake_supervisor({ "role": "user", "content": "m1", "timestamp": 11 },{ "role": "user", "content": "m2", "timestamp": 12 },{ "role": "user", "content": "m3", "timestamp": 13 },- { "role": "user", "content": "m4", "timestamp": 14 },+ { "role": "compactionSummary", "summary": "m4", "timestamp": 14 },])});+ let messages = messages.as_array().unwrap();+ let tail = usize::try_from(command["limit"].as_u64().unwrap()).unwrap();+ let begin = messages.len().saturating_sub(tail);+ let rows: Vec<Value> = messages[begin..]+ .iter()+ .enumerate()+ .map(|(offset, message)| {+ json!({ "index": begin + offset, "id": "", "message": message })+ })+ .collect();response_success(Some(&id),- "get_messages",- Some(json!({ "messages": messages })),+ "get_session_messages",+ Some(json!({ "messages": rows, "total": messages.len() })),)}"get_worker_peer_transport" => match ticket_response.clone() {@@ -1051,11 +1062,77 @@ async fn recent_messages_resolves_by_name_and_reports_the_envelope() {assert_eq!(recent.messages.len(), 2);assert_eq!(recent.messages[0].index, 3);assert_eq!(recent.messages[0].text, "m3");+ assert_eq!(+ recent.messages[1].text, "m4",+ "the compaction summary previews"+ );// A target outside the nuclear family never reaches the transcript read.let error = observer.recent_messages("ghost", 2, 90).await.unwrap_err();assert_eq!(error.to_string(), "agent ghost is not reachable");}+/// The display reader keeps a custom row's stored ISO timestamp. Its+/// public observe preview must preserve that timestamp as epoch milliseconds.+#[tokio::test]+async fn recent_messages_preserves_custom_transcript_timestamps() {+ let mut store = crate::session_store::SessionFile::create("/fixture", None, 0);+ store.append_message(&json!({"role": "user", "content": "hello", "timestamp": 13}));+ store.append_entry(+ "custom_message",+ json!({+ "customType": "agent_message", "content": "notice", "display": true,+ }),+ );+ store.entries.last_mut().unwrap().timestamp = "2004-07-21T00:47:44.465Z".to_string();+ let transcript = store+ .session_messages(-10, 10, |_| true, &std::collections::HashSet::new())+ .unwrap()+ .into_reply();+ let messages: Vec<Value> = transcript["messages"]+ .as_array()+ .unwrap()+ .iter()+ .map(|row| row["message"].clone())+ .collect();+ let dir = tempfile::TempDir::new().unwrap();+ let socket = dir.path().join("sup.sock");+ spawn_fake_supervisor(socket.clone(), json!({+ "sessions": [+ {"activeSessionId": "aaa111", "sessionId": "sess-a"},+ {"activeSessionId": "ddd444", "sessionId": "sess-d", "sessionName": "kid",+ "runtimeKind": "subagent", "parentActiveSessionId": "aaa111", "parentSessionId": "sess-a"},+ ],+ "messagesByActiveSessionId": {"ddd444": messages},+ }), None).await;+ let recent = observe_controller(socket)+ .recent_messages("kid", 10, 90)+ .await+ .unwrap();+ assert_eq!(+ recent.messages,+ vec![+ AgentObserveMessagePreview {+ index: 0,+ role: "user".into(),+ timestamp: Some(13),+ text: "hello".into(),+ truncated: false,+ tool_calls: Vec::new(),+ custom_type: None,+ },+ AgentObserveMessagePreview {+ index: 1,+ role: "custom".into(),+ timestamp: Some(1_090_370_864_465),+ text: "notice".into(),+ truncated: false,+ tool_calls: Vec::new(),+ custom_type: Some("agent_message".into()),+ },+ ]+ );+}+#[tokio::test]async fn recent_messages_reads_a_degraded_live_sibling_but_not_a_foreign_stub() {let dir = tempfile::TempDir::new().unwrap();diff --git a/crates/pa-daemon/src/agent_messaging/observe.rs b/crates/pa-daemon/src/agent_messaging/observe.rsindex 33132ac6fe..ed00d10a0a 100644--- a/crates/pa-daemon/src/agent_messaging/observe.rs+++ b/crates/pa-daemon/src/agent_messaging/observe.rs@@ -12,7 +12,7 @@ use super::{/// full session summaries from the supervisor. The roster this controller/// reports is the caller's NUCLEAR FAMILY, derived from the same durable/// parent edges `agent_message.send` resolves through — never the whole daemon.-pub(crate) struct LinkAgentObserveController {+pub struct LinkAgentObserveController {link: Arc<SupervisorLink>,/// This worker's live active session id (the family-scope anchor).active_session_id: String,@@ -24,7 +24,7 @@ pub(crate) struct LinkAgentObserveController {}impl LinkAgentObserveController {- pub(crate) fn new(+ pub fn new(link: Arc<SupervisorLink>,active_session_id: String,own_summary: Arc<std::sync::Mutex<Option<Value>>>,@@ -86,6 +86,39 @@ impl LinkAgentObserveController {Ok(summaries_from_roster(sessions, &identity, &child_ids))}+ /// The family member `target` names: the one resolution and permission check+ /// every read of another session goes through.+ async fn family_target(&self, target: &str) -> anyhow::Result<AgentObserveSummary> {+ find_target(self.family_summaries().await?, target)?+ .ok_or_else(|| anyhow::anyhow!("agent {target} is not reachable"))+ }++ /// One `get_session_messages` read of `agent`'s transcript: its worker answers when one+ /// holds the session, otherwise the supervisor reads the session file.+ async fn request_session_messages(+ &self,+ agent: &AgentObserveSummary,+ start: i64,+ limit: u64,+ roles: Vec<String>,+ ) -> anyhow::Result<Value> {+ let command = pa_types::daemon::DaemonCommand::GetSessionMessages {+ id: None,+ active_session_id: agent.active_session_id.clone().unwrap_or_default(),+ start,+ limit,+ roles,+ session_file: agent.session_file.clone(),+ rest: serde_json::Map::default(),+ };+ self.link+ .request_success(+ serde_json::to_value(command)?,+ std::time::Duration::from_secs(30),+ )+ .await+ }+/// The caller's own summary from its pushed state alone, no roster/// read: the row `list_agents` serves when the walk missed this/// session's live row.@@ -185,69 +218,67 @@ impl AgentObserveController for LinkAgentObserveController {limit: usize,max_chars: usize,) -> anyhow::Result<AgentObserveRecentMessagesResult> {- let agent = find_target(self.family_summaries().await?, target)?- .ok_or_else(|| anyhow::anyhow!("agent {target} is not reachable"))?;- // A family member with no live session (a passivated child) has no- // worker to read; TS hydrates it first, the roster walk errors. A- // live member whose `get_state` degraded shows the offline stub- // (empty sessionId, no activeSessionId — classified Inactive): its- // row still carries the session id, so read the transcript through- // it instead of refusing a session that is live, just slow.- let degraded_stub = agent.session_id.is_empty();- let Some(live_session_id) = agent- .active_session_id- .as_deref()- .filter(|_| degraded_stub || agent.status != AgentFamilyStatus::Inactive)- else {- anyhow::bail!("agent {target} has no live session");- };+ let agent = self.family_target(target).await?;let data = self- .link- .request_success(- json!({- "type": "get_messages",- "activeSessionId": live_session_id,- }),- std::time::Duration::from_secs(30),+ .request_session_messages(+ &agent,+ -i64::try_from(limit)?,+ u64::try_from(limit)?,+ vec!["*".to_string()],).await?;- let messages = data- .get("messages")- .and_then(Value::as_array)- .cloned()- .unwrap_or_default();- let total = messages.len();- let start = total.saturating_sub(limit);- let mut previews = Vec::new();- for (index, message) in messages.iter().enumerate().skip(start) {- let full_text = message_preview_text(message);- previews.push(AgentObserveMessagePreview {- index,- role: message- .get("role")- .and_then(Value::as_str)- .unwrap_or_default()- .to_string(),- timestamp: message.get("timestamp").and_then(Value::as_u64),- text: truncate_chars(&full_text, max_chars),- truncated: full_text.chars().count() > max_chars,- tool_calls: Vec::new(),- custom_type: message- .get("customType")- .and_then(Value::as_str)- .map(str::to_string),- });- }+ let reply: SessionMessagesReply = serde_json::from_value(data)?;+ let truncated = reply.total > reply.messages.len();+ let previews = reply+ .messages+ .into_iter()+ .map(|SessionMessageRow { index, message }| {+ let full_text = message_preview_text(&message);+ AgentObserveMessagePreview {+ index,+ role: message+ .get("role")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string(),+ timestamp: message.get("timestamp").and_then(|value| {+ value+ .as_u64()+ .or_else(|| value.as_str().and_then(crate::util::iso_to_unix_ms))+ }),+ text: truncate_chars(&full_text, max_chars),+ truncated: full_text.chars().count() > max_chars,+ tool_calls: Vec::new(),+ custom_type: message+ .get("customType")+ .and_then(Value::as_str)+ .map(str::to_string),+ }+ })+ .collect();Ok(AgentObserveRecentMessagesResult {agent,messages: previews,limit,max_chars,- truncated: start > 0,+ truncated,})}}+/// The `get_session_messages` reply fields a preview reads.+#[derive(serde::Deserialize)]+struct SessionMessagesReply {+ messages: Vec<SessionMessageRow>,+ total: usize,+}++#[derive(serde::Deserialize)]+struct SessionMessageRow {+ index: usize,+ message: Value,+}+/// Flatten the supervisor's roster rows into observation summaries of the caller's NUCLEAR/// FAMILY: the caller's own row, its parent, its siblings, and its direct children. The/// relationship derives from the durable edges, never the row's runtime kind.@@ -379,6 +410,7 @@ pub(super) fn summaries_from_roster(rlm_child_id: row_str(&session, "rlmChildId").map(str::to_string),first_message: row_str(&session, "firstMessage").map(|text| truncate_chars(text, AGENT_OBSERVE_PREVIEW_MAX_CHARS)),+ session_file: row_str(&session, "sessionFile").map(str::to_string),})}).collect()@@ -393,7 +425,12 @@ fn message_preview_text(message: &Value) -> String {.filter_map(|block| block.get("text").and_then(Value::as_str)).collect::<Vec<_>>().join(""),- _ => String::new(),+ // A `compactionSummary` row keeps its text in `summary`.+ _ => message+ .get("summary")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string(),}}diff --git a/crates/pa-daemon/src/protocol.rs b/crates/pa-daemon/src/protocol.rsindex 17909b97c3..c9fbdb7781 100644--- a/crates/pa-daemon/src/protocol.rs+++ b/crates/pa-daemon/src/protocol.rs@@ -168,6 +168,7 @@ pub const KNOWN_COMMAND_TYPES: &[&str] = &["list_persistent_shells","tail_persistent_shell","kill_persistent_shell",+ "get_session_messages",];/// Parsed client command envelope.@@ -706,6 +707,9 @@ pub fn command_active_session_id(command: &DaemonCommand) -> Option<&str> {| DaemonCommand::GetMessages {active_session_id, ..}+ | DaemonCommand::GetSessionMessages {+ active_session_id, ..+ }| DaemonCommand::GetRlmChildren {active_session_id, ..}@@ -993,6 +997,7 @@ pub fn command_type_name(command: &DaemonCommand) -> &'static str {DaemonCommand::GetState { .. } => "get_state",DaemonCommand::GetConnectionState { .. } => "get_connection_state",DaemonCommand::GetMessages { .. } => "get_messages",+ DaemonCommand::GetSessionMessages { .. } => "get_session_messages",DaemonCommand::GetRlmChildren { .. } => "get_rlm_children",DaemonCommand::GetSessionStats { .. } => "get_session_stats",DaemonCommand::GetContextTree { .. } => "get_context_tree",diff --git a/crates/pa-daemon/src/session_store.rs b/crates/pa-daemon/src/session_store.rsindex 46d0691186..7dce1be957 100644--- a/crates/pa-daemon/src/session_store.rs+++ b/crates/pa-daemon/src/session_store.rs@@ -114,6 +114,94 @@ pub struct TranscriptPageRows {pub more: bool,}+/// One display-transcript slice ([`SessionFile::session_messages`]).+#[derive(Debug, Clone)]+pub struct SessionMessages {+ /// Each row's index among the matching rows, entry id, and wire message, oldest first.+ pub rows: Vec<(usize, String, Value)>,+ /// How many rows match on the active branch.+ pub total: usize,+}++impl SessionMessages {+ /// The `get_session_messages` reply `{messages: [{index, id, message}], total}`,+ /// snapshot image payloads left out.+ #[must_use]+ pub fn into_reply(self) -> Value {+ let messages: Vec<Value> = self+ .rows+ .into_iter()+ .map(|(index, id, mut message)| {+ crate::snapshot_stream::elide_snapshot_image_payloads(std::slice::from_mut(+ &mut message,+ ));+ json!({ "index": index, "id": id, "message": message })+ })+ .collect();+ json!({ "messages": messages, "total": self.total })+ }+}++/// One `get_session_messages` request: the slice bounds and the compiled role globs.+pub struct SessionMessagesQuery {+ start: i64,+ limit: usize,+ roles: globset::GlobSet,+}++impl SessionMessagesQuery {+ /// Compile the role globs.+ ///+ /// # Errors+ ///+ /// Returns an error when a role is not a valid glob.+ pub fn new(start: i64, limit: u64, roles: &[String]) -> Result<Self, globset::Error> {+ let mut globs = globset::GlobSetBuilder::new();+ for role in roles {+ globs.add(globset::Glob::new(role)?);+ }+ Ok(Self {+ start,+ limit: usize::try_from(limit).unwrap_or(usize::MAX),+ roles: globs.build()?,+ })+ }++ /// The slice from `store`; `None` when it reaches a windowed store's unloaded prefix.+ #[must_use]+ pub fn read(+ &self,+ store: &SessionFile,+ running_calls: &std::collections::HashSet<String>,+ ) -> Option<SessionMessages> {+ store.session_messages(+ self.start,+ self.limit,+ |role| self.roles.is_match(role),+ running_calls,+ )+ }++ /// The slice from a session file no worker holds, read-only: no lease and no+ /// session-file write (the windowed open may refresh its window-cache sidecar).+ /// The windowed open serves slices inside the window; one that reaches the+ /// unloaded prefix reads the full file. Nothing runs, so nothing is in flight.+ ///+ /// # Errors+ ///+ /// Returns an error when the file cannot be read.+ pub fn read_file(&self, path: &Path) -> Result<SessionMessages> {+ let idle = std::collections::HashSet::new();+ if let Some(slice) = self.read(&SessionFile::open_windowed(path)?, &idle) {+ return Ok(slice);+ }+ let slice = self.read(&SessionFile::open(path)?, &idle);+ // The whole-file load was transient: release its freed heap.+ pa_types::memory_release::trim_freed_heap();+ slice.ok_or_else(|| anyhow!("Session history is unavailable"))+ }+}+/// The windowed sequence's summary scalars (newest timestamp, message count),/// from [`SessionFile::scan_message_scalars`] without materializing the fold.#[derive(Debug, Default, Clone, Copy, PartialEq)]diff --git a/crates/pa-daemon/src/session_store/view.rs b/crates/pa-daemon/src/session_store/view.rsindex 497210c26f..c028133809 100644--- a/crates/pa-daemon/src/session_store/view.rs+++ b/crates/pa-daemon/src/session_store/view.rs@@ -1,7 +1,10 @@//! The loaded-session view: the branch walks, the window/settings reads, the//! compacted message fold and its scalars, and the wire-shape message helpers.-use super::{json, MessageWindowScalars, SessionEntry, SessionFile, TranscriptPageRows, Value};+use super::{+ json, MessageWindowScalars, SessionEntry, SessionFile, SessionMessages, TranscriptPageRows,+ Value,+};use pa_types::daemon::TranscriptPage;/// One display-transcript row: its entry id and wire message.@@ -584,6 +587,93 @@ impl SessionFile {Some((page, false))}+ /// `rows[start:][:limit]` (Python slice semantics) over the active branch's display+ /// transcript filtered to the roles `keep_role` accepts, each row with its index among+ /// those rows. The total is a window's prefix counts plus one walk over the loaded+ /// branch; only the returned rows materialize. `None` when the slice reaches into a+ /// windowed store's unloaded prefix: the caller hydrates and reads again.+ #[must_use]+ pub fn session_messages(+ &self,+ start: i64,+ limit: usize,+ keep_role: impl Fn(&str) -> bool,+ running_calls: &std::collections::HashSet<String>,+ ) -> Option<SessionMessages> {+ let in_flight = self.in_flight(running_calls);+ let kept = |position: &usize| {+ Some(*position) != in_flight && self.display_role(*position).is_some_and(&keep_role)+ };+ let prefix: usize = self.window.as_ref().map_or(0, |window| {+ window+ .older_path_stats+ .display_rows+ .iter()+ .filter(|(role, _)| keep_role(role))+ .map(|(_, count)| count)+ .sum()+ });+ let total = prefix + self.walk_back(self.branch_leaf()).filter(kept).count();+ let begin = if start < 0 {+ total.saturating_sub(usize::try_from(start.unsigned_abs()).unwrap_or(usize::MAX))+ } else {+ usize::try_from(start).map_or(total, |start| start.min(total))+ };+ let end = total.min(begin.saturating_add(limit));+ if begin < end && begin < prefix {+ return None;+ }+ let mut rows: Vec<(usize, String, Value)> = self+ .walk_back(self.branch_leaf())+ .filter(kept)+ .skip(total - end)+ .take(end - begin)+ .zip((begin..end).rev())+ .filter_map(|(position, index)| {+ let (id, message) = self.display_row(position)?;+ Some((index, id.to_string(), message.into_owned()))+ })+ .collect();+ rows.reverse();+ Some(SessionMessages { rows, total })+ }++ /// The role a branch position shows under in the display transcript.+ fn display_role(&self, position: usize) -> Option<&str> {+ let entry = &self.entries[position];+ pa_core::session::window::display_role(+ &entry.type_,+ entry.fields.get("message").and_then(message_role),+ )+ }++ /// The step in flight: the newest assistant row, while one of its tool calls is still+ /// running. Only that row can hold a running call (the engine awaits every call before+ /// the next model call); it is not transcript yet.+ fn in_flight(&self, running_calls: &std::collections::HashSet<String>) -> Option<usize> {+ if running_calls.is_empty() {+ return None;+ }+ self.walk_back(self.branch_leaf())+ .find(|&position| self.display_role(position) == Some("assistant"))+ .filter(|&position| {+ self.entries[position]+ .fields+ .get("message")+ .and_then(|message| message.get("content"))+ .and_then(Value::as_array)+ .is_some_and(|content| {+ content.iter().any(|block| {+ block.get("type").and_then(Value::as_str) == Some("toolCall")+ && block+ .get("id")+ .and_then(Value::as_str)+ .is_some_and(|id| running_calls.contains(id))+ })+ })+ })+ }+/// The newest user prompt's time on the branch (the attach snapshot's marker); the walk/// reaches back only as far as that prompt.#[must_use]diff --git a/crates/pa-daemon/src/supervisor/routing.rs b/crates/pa-daemon/src/supervisor/routing.rsindex f95dab5e49..9bc290d9ac 100644--- a/crates/pa-daemon/src/supervisor/routing.rs+++ b/crates/pa-daemon/src/supervisor/routing.rs@@ -414,6 +414,31 @@ impl Supervisor {);}}+ } else if let DaemonCommand::GetSessionMessages {+ start,+ limit,+ roles,+ session_file: Some(session_file),+ ..+ } = command+ {+ // A family member's read of a session no worker holds (a+ // passivated child): a read-only open of its file, never a wake.+ let response =+ match saved_session_messages(session_file, *start, *limit, roles)+ .await+ {+ Ok(data) => {+ response_success(Some(&command_id), &type_name, Some(data))+ }+ Err(error) => response_failure(+ Some(&command_id),+ &type_name,+ &format!("{error:#}"),+ None,+ ),+ };+ return (vec![response_line(&response)], false);} else if let DaemonCommand::Kill { rest, .. } = command {if let Some(reason) = rest.get("rlmLedgerDelete")@@ -1152,6 +1177,20 @@ impl Supervisor {}}+/// `get_session_messages` over a session file no worker holds; the file I/O runs off+/// the async runtime.+async fn saved_session_messages(+ session_file: &str,+ start: i64,+ limit: u64,+ roles: &[String],+) -> Result<Value> {+ let query = crate::session_store::SessionMessagesQuery::new(start, limit, roles)?;+ let path = std::path::PathBuf::from(session_file);+ let slice = tokio::task::spawn_blocking(move || query.read_file(&path)).await??;+ Ok(slice.into_reply())+}+/// The ledger edge a delete addresses, as `(child_id, child_file)`. `rlmChildId` is the durable/// key; the selector is the child's LIVE id, NOT the file stem. Order: (1a) edge matching BOTH/// the stem and the id; (1b) the LAST edge carrying the id; (2) the stem-matching edge.diff --git a/crates/pa-daemon/src/worker/commands.rs b/crates/pa-daemon/src/worker/commands.rsindex be735dbd5c..7866c55ab8 100644--- a/crates/pa-daemon/src/worker/commands.rs+++ b/crates/pa-daemon/src/worker/commands.rs@@ -9,6 +9,7 @@ use super::{use serde_json::Value;use crate::protocol::DaemonResponse;+use crate::session_store::SessionMessagesQuery;impl Worker {pub(crate) async fn dispatch(&self, command_type: &str, payload: &Value) -> DaemonResponse {@@ -16,7 +17,7 @@ impl Worker {// Cancellation is deliberately excluded: it must reach the live turn immediately.let history_page = command_type == "get_messages"&& transcript_page(payload).is_some_and(|page| page.reads_history());- if (history_page+ if history_page|| matches!(command_type,"get_session_tree"@@ -27,43 +28,11 @@ impl Worker {| "fork"| "export_html"| "export_jsonl"- ))- && self- .core- .lock()- .unwrap()- .store- .as_ref()- .is_some_and(|store| store.window.is_some())+ ){- let path = self- .core- .lock()- .unwrap()- .store- .as_ref()- .unwrap()- .path- .clone();- let load_path = path.clone();- let hydrated = tokio::task::spawn_blocking(move || SessionFile::open(&load_path))- .await- .map_err(anyhow::Error::from)- .and_then(|result| result);- match hydrated {- Ok(full) => {- let mut core = self.core.lock().unwrap();- if let Some(store) = core.store.as_mut().filter(|store| store.path == path) {- store.install_full_history(full);- }- }- Err(error) => {- return response_failure(None, command_type, &error.to_string(), None);- }+ if let Err(error) = self.hydrate_history().await {+ return response_failure(None, command_type, &error.to_string(), None);}- // The hydrated full file was a transient whole-file copy on- // top of the installed history: release its freed heap.- pa_types::memory_release::trim_freed_heap();}match command_type {"create" => self.handle_create(payload).await,@@ -99,6 +68,7 @@ impl Worker {}"get_state" => self.handle_get_state(),"get_messages" => self.handle_get_messages(payload),+ "get_session_messages" => self.handle_get_session_messages(payload).await,"get_session_header" => self.handle_get_session_header(),"get_session_stats" => self.handle_get_session_stats(),"get_model_catalog" => self.handle_get_model_catalog(),@@ -525,6 +495,81 @@ impl Worker {)}+ /// `get_session_messages`: one slice of the session's display transcript, filtered by+ /// role globs; a slice into a windowed store's unloaded prefix hydrates the store first.+ async fn handle_get_session_messages(&self, payload: &Value) -> DaemonResponse {+ const NAME: &str = "get_session_messages";+ if let Err(response) = self.require_created(NAME) {+ return response;+ }+ let roles: Vec<String> = payload+ .get("roles")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .map(str::to_string)+ .collect();+ let query = match SessionMessagesQuery::new(+ payload.get("start").and_then(Value::as_i64).unwrap_or(0),+ payload.get("limit").and_then(Value::as_u64).unwrap_or(0),+ &roles,+ ) {+ Ok(query) => query,+ Err(error) => return response_failure(None, NAME, &error.to_string(), None),+ };+ let read = || {+ let core = self.core.lock().unwrap();+ let slice = core+ .store+ .as_ref()+ .and_then(|store| query.read(store, &core.running_tool_calls));+ slice+ };+ let mut slice = read();+ if slice.is_none() {+ if let Err(error) = self.hydrate_history().await {+ return response_failure(None, NAME, &error.to_string(), None);+ }+ slice = read();+ }+ let Some(slice) = slice else {+ return response_failure(None, NAME, "Session history is unavailable", None);+ };+ response_success(None, NAME, Some(slice.into_reply()))+ }++ /// Load a windowed store's full history in place; a full store stays as it is.+ async fn hydrate_history(&self) -> Result<()> {+ let Some(path) = self+ .core+ .lock()+ .unwrap()+ .store+ .as_ref()+ .filter(|store| store.window.is_some())+ .map(|store| store.path.clone())+ else {+ return Ok(());+ };+ let load_path = path.clone();+ let full = tokio::task::spawn_blocking(move || SessionFile::open(&load_path)).await??;+ if let Some(store) = self+ .core+ .lock()+ .unwrap()+ .store+ .as_mut()+ .filter(|store| store.path == path)+ {+ store.install_full_history(full);+ }+ // The hydrated full file was a transient whole-file copy on+ // top of the installed history: release its freed heap.+ pa_types::memory_release::trim_freed_heap();+ Ok(())+ }+fn handle_get_queue(&self) -> DaemonResponse {if let Err(response) = self.require_created("get_queue") {return response;diff --git a/crates/pa-daemon/src/worker/tests/windowed_attach_tests.rs b/crates/pa-daemon/src/worker/tests/windowed_attach_tests.rsindex 9b6d73182d..9cb663a898 100644--- a/crates/pa-daemon/src/worker/tests/windowed_attach_tests.rs+++ b/crates/pa-daemon/src/worker/tests/windowed_attach_tests.rs@@ -386,6 +386,107 @@ async fn pages_continue_into_pre_compaction_history_with_one_summary() {);}+/// `get_session_messages` reads a slice inside the window without hydrating, its indexes+/// counting the unloaded prefix; a slice reaching into the prefix hydrates the store.+#[tokio::test]+async fn session_messages_hydrate_only_for_the_unloaded_prefix() {+ let dir = session_dir();+ let path = dir.join("session-messages.jsonl");+ let mut fixture = Fixture {+ content: header_line("session-messages"),+ prev: None,+ id: 0,+ };+ let user = |text: &str| json!({ "role": "user", "content": text, "timestamp": 1000u64 });+ // The window's walk reads the model from the newest assistant row.+ let assistant = |text: &str| {+ let mut message = assistant_message(text);+ message["provider"] = json!("p");+ message["model"] = json!("m");+ message+ };+ let conversation = |fixture: &mut Fixture, prefix: &str| {+ fixture.row(|prev, id| message_row(prev, id, &user(&format!("{prefix}0"))));+ fixture.row(|prev, id| message_row(prev, id, &assistant(&format!("{prefix}1"))));+ };+ conversation(&mut fixture, "p");+ fixture.row(custom_row);+ conversation(&mut fixture, "p");+ fixture.row(custom_row);+ fixture.row(|prev, id| message_row(prev, id, &user("r0")));+ let first_kept = fixture.prev.clone().expect("retained start");+ fixture.row(|prev, id| message_row(prev, id, &assistant("r1")));+ fixture.row(|prev, id| {+ format!(+ "{{\"type\":\"compaction\",\"summary\":\"the story\",\"firstKeptEntryId\":\"{first_kept}\",\"tokensBefore\":4000,\"id\":\"{id}\",\"parentId\":{},\"timestamp\":\"2026-01-01T00:00:00.000Z\"}}\n",+ parent_json(prev),+ )+ });+ conversation(&mut fixture, "q");+ std::fs::write(&path, fixture.content).unwrap();++ let worker = worker_over(&dir, &path).await;+ let windowed = || {+ worker+ .core+ .lock()+ .unwrap()+ .store+ .as_ref()+ .is_some_and(|store| store.window.is_some())+ };+ let read = |start: i64, limit: u64, roles: Value| {+ let worker = std::sync::Arc::clone(&worker);+ async move {+ let response = worker+ .dispatch(+ "get_session_messages",+ &json!({ "start": start, "limit": limit, "roles": roles }),+ )+ .await;+ assert!(response.success, "the read failed: {response:?}");+ let data = response.data.expect("slice data");+ let rows: Vec<(u64, String)> = data["messages"]+ .as_array()+ .expect("rows")+ .iter()+ .map(|row| {+ let message = &row["message"];+ let text = message["content"]+ .as_str()+ .or_else(|| message["content"][0]["text"].as_str())+ .unwrap_or_default();+ (row["index"].as_u64().unwrap(), text.to_string())+ })+ .collect();+ (rows, data["total"].as_u64().unwrap())+ }+ };+ assert!(windowed(), "the session opens windowed");++ let tail = read(-3, 3, json!(["user", "assist*"])).await;+ assert_eq!(+ tail,+ (+ vec![+ (5, "r1".to_string()),+ (6, "q0".to_string()),+ (7, "q1".to_string())+ ],+ 8+ )+ );+ assert_eq!(read(0, 0, json!(["c*"])).await, (Vec::new(), 3));+ assert!(windowed(), "reads inside the window leave it in place");++ let head = read(0, 2, json!(["*"])).await;+ assert_eq!(+ head,+ (vec![(0, "p0".to_string()), (1, "p1".to_string())], 11)+ );+ assert!(!windowed(), "a read into the prefix hydrated the store");+}+#[tokio::test]async fn a_windowed_attach_preserves_iso_and_fractional_prompt_times() {for timestamp in [diff --git a/crates/pa-daemon/tests/agent_family_e2e.rs b/crates/pa-daemon/tests/agent_family_e2e.rsindex 1e88ffc25c..ee82cd0fd1 100644--- a/crates/pa-daemon/tests/agent_family_e2e.rs+++ b/crates/pa-daemon/tests/agent_family_e2e.rs@@ -31,10 +31,11 @@ use std::time::{Duration, Instant};use pa_core::kernel::shared::{HostRequestHandlers, HostRequestPayload};use pa_core::session_engine::agent_messaging::{- register_agent_message_host_handlers, AgentFamilyRelationship, AgentMessageController,+ register_agent_message_host_handlers, register_agent_observe_host_handlers,+ AgentFamilyRelationship, AgentMessageController,};use pa_core::session_engine::rlm_host::{RlmSpawnRequest, RlmSubagentHost};-use pa_daemon::agent_messaging::LinkAgentMessageController;+use pa_daemon::agent_messaging::{LinkAgentMessageController, LinkAgentObserveController};use pa_daemon::rlm_children::{ParentIdentity, SupervisorChildSessions};use pa_daemon::supervisor_link::SupervisorLink;use serde_json::{json, Value};@@ -1292,3 +1293,213 @@ async fn parent_renames_a_child_end_to_end() {.expect("the child's ledger edge");assert_eq!(edge.name, "bench-runner", "the ledger rename landed");}++/// `agent_observe.recent_messages` on a family member through the real handler.+async fn recent_member(+ handlers: &HostRequestHandlers,+ target: &str,+ limit: u64,+) -> anyhow::Result<Value> {+ let recent = handlers+ .get("agent_observe.recent")+ .expect("the recent-messages handler")+ .clone();+ recent(HostRequestPayload {+ data: json!({ "target": target, "limit": limit }),+ })+ .await+}++/// The observe handlers a worker wires, for the session `own_summary` describes.+fn observe_handlers(+ link: &Arc<SupervisorLink>,+ own_summary: Value,+ children: Option<Arc<SupervisorChildSessions>>,+) -> HostRequestHandlers {+ let active_session_id = own_summary["activeSessionId"]+ .as_str()+ .expect("own active id")+ .to_string();+ let controller = Arc::new(LinkAgentObserveController::new(+ Arc::clone(link),+ active_session_id,+ Arc::new(std::sync::Mutex::new(Some(own_summary))),+ children,+ ));+ let mut handlers = HostRequestHandlers::default();+ register_agent_observe_host_handlers(controller, &mut handlers);+ handlers+}++/// The live residents' durable session ids (`list` without `all`).+fn resident_session_ids(client: &mut Client, id: &str) -> Vec<String> {+ client.send_command(id, &json!({ "type": "list" }));+ let response = client.read_response(id);+ assert_eq!(response["success"], true, "list failed: {response}");+ response["data"]["sessions"]+ .as_array()+ .expect("sessions")+ .iter()+ .filter_map(|row| row["sessionId"].as_str().map(str::to_string))+ .collect()+}++/// A parent's `agent_observe.recent_messages` of its child reads the same+/// previews after the child is passivated: the supervisor reads the child's+/// session file, and no worker comes back for it.+#[tokio::test]+async fn passivated_child_recent_messages_reads_its_file_end_to_end() {+ let Some(kernel_python) = kernel_python() else {+ return;+ };+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("daemon.sock");+ let agent_dir = dir.path().join("agent");+ let sessions_dir = agent_dir.join("sessions");+ std::fs::create_dir_all(&sessions_dir).expect("sessions dir");+ // Idle passivation is on, so the test can passivate kid-a.+ std::fs::write(+ agent_dir.join("settings.json"),+ json!({ "idleEvictionMinutes": 1 }).to_string(),+ )+ .expect("write settings");+ let root_script = write_faux_script(dir.path(), "root", &json!([{ "text": "root turn done" }]));+ let kid_script = write_faux_script(dir.path(), "kid", &json!([{ "text": "kid spawned" }]));++ let _daemon = spawn_supervisor(&socket, &agent_dir, &kernel_python);+ wait_socket_ready(&socket);+ let (mut client, hello) = Client::connect(&socket);+ assert_eq!(hello["type"], "daemon_hello");+ let link = Arc::new(SupervisorLink::new(socket.clone()));++ client.send_command(+ "create-parent",+ &json!({+ "type": "create",+ "name": "parent",+ "config": {+ "cwd": dir.path().to_string_lossy(),+ "sessionDir": sessions_dir.to_string_lossy(),+ "script": root_script.to_string_lossy(),+ },+ }),+ );+ let created = client.read_response("create-parent");+ assert_eq!(created["success"], true, "create parent failed: {created}");+ let data = &created["data"];+ let parent_summary = json!({+ "activeSessionId": data["activeSessionId"].as_str().or_else(|| data["id"].as_str()),+ "sessionId": data["sessionId"],+ "sessionFile": data["sessionFile"],+ "sessionName": "parent",+ "runtimeKind": "top-level",+ });+ let children = Arc::new(SupervisorChildSessions::new(+ Arc::clone(&link),+ agent_dir.clone(),+ parent_summary["activeSessionId"]+ .as_str()+ .expect("active id")+ .to_string(),+ std::sync::Arc::new(pa_daemon::model_allowlist::ModelRefusalTelemetry::new(+ agent_dir.clone(),+ /*telemetry_disabled*/ true,+ )),+ String::new(),+ ));+ children.set_identity(ParentIdentity {+ rlm_depth: 0,+ rlm_max_depth: 2,+ model: Some("faux/faux-1".to_string()),+ cwd: Some(dir.path().to_string_lossy().to_string()),+ session_id: parent_summary["sessionId"].as_str().map(str::to_string),+ session_file: parent_summary["sessionFile"].as_str().map(str::to_string),+ thinking: None,+ child_script: Some(kid_script.to_string_lossy().to_string()),+ });+ children+ .spawn(RlmSpawnRequest {+ prompt: "kid-a work".to_string(),+ name: Some("kid-a".to_string()),+ model: None,+ thinking: None,+ spawned_by_request_id: None,+ })+ .await+ .expect("spawn kid-a");+ children.notify_turn_done();+ let deadline = Instant::now() + Duration::from_secs(60);+ let kid_a = loop {+ let rows = children.list_subagents().await.expect("child roster");+ if let Some(row) = rows.into_iter().find(|row| row.status == "completed") {+ break row;+ }+ assert!(+ Instant::now() < deadline,+ "kid-a never settled; daemon log tail: {}",+ daemon_log_tail(&dir.path().join("receipts"))+ );+ tokio::time::sleep(Duration::from_millis(50)).await;+ };+ let kid_a_active = kid_a.active_session_id.clone().expect("kid-a active id");+ let kid_a_session = kid_a.session_id.clone().expect("kid-a session id");+ let parent_reads = observe_handlers(&link, parent_summary, Some(children));++ // The resident kid-a answers through its worker: everything, then the newest row.+ let all = recent_member(&parent_reads, "kid-a", 50)+ .await+ .expect("kid-a recent messages");+ let previews = all["messages"].as_array().expect("previews");+ assert!(+ previews[0]["text"]+ .as_str()+ .is_some_and(|text| text.contains("kid-a work")),+ "{all}"+ );+ let indexes: Vec<u64> = previews+ .iter()+ .map(|preview| preview["index"].as_u64().expect("index"))+ .collect();+ assert_eq!(+ indexes,+ (0..previews.len() as u64).collect::<Vec<_>>(),+ "{all}"+ );+ assert_eq!(all["truncated"], false, "{all}");+ let newest = recent_member(&parent_reads, "kid-a", 1)+ .await+ .expect("kid-a newest message");+ assert_eq!(+ newest["messages"],+ json!([previews.last().expect("a preview")]),+ "{newest}"+ );+ assert_eq!(newest["truncated"], true, "{newest}");++ // A passivated kid-a reads the same from its file, and no worker comes back for it.+ client.send_command(+ "passivate-kid-a",+ &json!({+ "type": "worker_idle_passivation",+ "workerToken": parent_worker_token(&agent_dir, &kid_a_active),+ "idleMinutes": 1,+ }),+ );+ let passivated = client.read_response("passivate-kid-a");+ assert_eq!(passivated["success"], true, "passivation: {passivated}");+ assert!(+ !resident_session_ids(&mut client, "list-before").contains(&kid_a_session),+ "the passivation stopped kid-a's worker"+ );+ for (limit, resident) in [(50, &all), (1, &newest)] {+ let saved = recent_member(&parent_reads, "kid-a", limit)+ .await+ .expect("recent messages of the passivated kid-a");+ assert_eq!(saved["messages"], resident["messages"], "{saved}");+ assert_eq!(saved["truncated"], resident["truncated"], "{saved}");+ }+ assert!(+ !resident_session_ids(&mut client, "list-after").contains(&kid_a_session),+ "the read never revives kid-a"+ );+}diff --git a/crates/pa-daemon/tests/command_breadth.rs b/crates/pa-daemon/tests/command_breadth.rsindex e3ebaf05f5..3474f6632c 100644--- a/crates/pa-daemon/tests/command_breadth.rs+++ b/crates/pa-daemon/tests/command_breadth.rs@@ -532,6 +532,10 @@ const WIRE_FIXTURES: &[(&str, &str)] = &["kill_persistent_shell",r#"{"type": "kill_persistent_shell", "shellId": "s"}"#,),+ (+ "get_session_messages",+ r#"{"type": "get_session_messages", "activeSessionId": "sess", "start": -10, "limit": 10, "roles": ["*"]}"#,+ ),];/// The accept list is the TS list, in TS order, then the Rust-native supervisor/worker frames.@@ -563,6 +567,7 @@ fn known_command_types_match_the_ts_list() {| "list_persistent_shells"| "tail_persistent_shell"| "kill_persistent_shell"+ | "get_session_messages"),"unexpected non-TS command type: {extra}");diff --git a/crates/pa-types/src/daemon/command.rs b/crates/pa-types/src/daemon/command.rsindex fb6bcaa378..76be1c800e 100644--- a/crates/pa-types/src/daemon/command.rs+++ b/crates/pa-types/src/daemon/command.rs@@ -665,6 +665,23 @@ pub enum DaemonCommand {#[serde(flatten)]rest: JsonMap,},+ /// One slice of the session's display transcript:+ /// `rows[start:][:limit]` over the rows whose role matches a `roles` glob.+ /// Rust-native extension.+ GetSessionMessages {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ id: Option<String>,+ active_session_id: String,+ start: i64,+ limit: u64,+ roles: Vec<String>,+ /// The session's file, which the supervisor reads when no worker holds the+ /// session (a family member's read).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ session_file: Option<String>,+ #[serde(flatten)]+ rest: JsonMap,+ },GetRlmChildren {#[serde(default, skip_serializing_if = "Option::is_none")]id: Option<String>,diff --git a/crates/pa-types/src/daemon/plane.rs b/crates/pa-types/src/daemon/plane.rsindex 7d70510fb4..11649486a2 100644--- a/crates/pa-types/src/daemon/plane.rs+++ b/crates/pa-types/src/daemon/plane.rs@@ -129,6 +129,7 @@ const READ_ONLY_DAEMON_COMMANDS: &[&str] = &["get_state","get_connection_state","get_messages",+ "get_session_messages","get_rlm_children","get_session_stats","get_context_tree",diff --git a/skills/agent-observe/SKILL.md b/skills/agent-observe/SKILL.mdindex 28ccac0dba..c9ec6ef9b6 100644--- a/skills/agent-observe/SKILL.md+++ b/skills/agent-observe/SKILL.md@@ -8,9 +8,10 @@ description: Read-only roster and observation of an agent's parent, siblings, anObserve the current agent's nuclear family through the local daemon: parent,siblings, direct children, and self. `list_agents` is the one family roster andcovers every member `agent_message.send` can reach. `get_agent` also returns an-inactive child's roster row. `recent_messages` reads live sessions only; it-does not rehydrate an inactive member. They cannot read a root sibling that has-no live session in this worker.+inactive child's roster row. `recent_messages` also reads a member no worker+holds (a passivated or finished child) from its session file, read-only,+without waking it. They cannot read a root sibling that has no live session in+this worker.This skill is read-only: it can list family sessions, inspect one session, and fetchbounded recent message previews. It cannot prompt, steer, clear, kill, rename, orotherwise mutate another session.@@ -52,8 +53,8 @@ if child is not None:returns `agent` (the target's summary), `messages` (up to `limit` recentbounded previews), the clamped `limit` and `maxChars`, and `truncated`(true when older messages exist beyond the returned window). `limit` must be- 1-50, and `max_chars` must be 80-2000. The target must be a live family- member: a member with no live session errors instead of hydrating.+ 1-50, and `max_chars` must be 80-2000. Each preview's `index` is the+ message's position in the full transcript.## Safetydiff --git a/skills/agent-observe/src/agent_observe/__init__.py b/skills/agent-observe/src/agent_observe/__init__.pyindex 5b4d2737d9..cf4576a377 100644--- a/skills/agent-observe/src/agent_observe/__init__.py+++ b/skills/agent-observe/src/agent_observe/__init__.py@@ -29,7 +29,7 @@ async def recent_messages(limit: int = 8,max_chars: int = 800,) -> dict[str, Any]:- """Read bounded recent message previews from an active session.+ """Read bounded recent message previews from a family member's session.Args:target: Active session id, session id/name, or unambiguous id suffix.