A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
print: wire background bash, heartbeats, skills, and late receipts like the daemon (#3580)
Sebastian Müllerc20f93f67f80
diff --git a/crates/pa-agent/src/agent.rs b/crates/pa-agent/src/agent.rsindex 9e1bb42934..d60b861cfd 100644--- a/crates/pa-agent/src/agent.rs+++ b/crates/pa-agent/src/agent.rs@@ -278,6 +278,14 @@ type AgentEventListener = Arc<dyn Fn(AgentEvent, AbortSignal) -> crate::BoxFut<'static, anyhow::Result<()>> + Send + Sync,>;+/// Rewrites one `MessageEnd` row just before it lands in agent state and+/// before listeners see the event: the session engine installs it to+/// apply rows parked ahead of their landing message (late+/// `agent_message.send` receipts), so live state and the persistence+/// listener's row both carry the rewrite.+pub type MessageEndTransformFn =+ Arc<dyn Fn(AgentMessage) -> crate::BoxFut<'static, AgentMessage> + Send + Sync>;+/// Unsubscribe handle: dropping it does NOT unsubscribe; call/// [`Subscription::unsubscribe`] explicitly to remove the listener.pub struct Subscription {@@ -327,6 +335,10 @@ struct AgentInner {/// The natural-turn-end continuation hook: settable after construction so the session engine/// can install it. A plain mutex: cloned at run-config build, never held across an await.get_continuation_messages: Mutex<Option<GetContinuationMessagesFn>>,+ /// The `MessageEnd` landing transform: settable after construction so+ /// the session engine can install it. A plain mutex: cloned at event+ /// processing entry, never held across an await.+ message_end_transform: Mutex<Option<MessageEndTransformFn>>,/// Per-run model override; the owner sets it right before starting a routed run and clears it/// before the next dispatch. A plain mutex: read at run-config build, never held across an/// await.@@ -352,7 +364,17 @@ impl AgentInner {async fn process_events(self: &Arc<Self>, event: AgentEvent) -> anyhow::Result<()> {let _delivery = self.event_delivery.lock().await;+ let message_end_transform = self.message_end_transform.lock().unwrap().clone();let mut shared = self.shared.lock().await;+ // The landing transform rewrites a `MessageEnd` row under the same+ // shared lock as the state push: the row lands in state and reaches+ // every listener exactly once, already rewritten.+ let event = match (event, message_end_transform) {+ (AgentEvent::MessageEnd { message }, Some(transform)) => AgentEvent::MessageEnd {+ message: transform(message).await,+ },+ (event, _) => event,+ };match &event {AgentEvent::MessageStart { message } => {@@ -769,6 +791,7 @@ impl Agent {should_stop_after_turn: options.should_stop_after_turn,should_stop_before_turn: options.should_stop_before_turn,get_continuation_messages: Mutex::new(options.get_continuation_messages),+ message_end_transform: Mutex::new(None),model_override: Mutex::new(None),session_id: options.session_id,tool_execution: options@@ -926,6 +949,18 @@ impl Agent {*self.inner.get_continuation_messages.lock().unwrap() = hook;}+ /// Install or replace the `MessageEnd` landing transform: the owner that+ /// parks rows ahead of their landing message (the session engine's+ /// late-receipt seam) wires it after the agent exists. `None` uninstalls+ /// the transform.+ ///+ /// # Panics+ ///+ /// Panics if the `message_end_transform` mutex is poisoned.+ pub fn set_message_end_transform(&self, transform: Option<MessageEndTransformFn>) {+ *self.inner.message_end_transform.lock().unwrap() = transform;+ }+/// # Panics////// Panics if the `follow_up_queue` mutex is poisoned.diff --git a/crates/pa-cli/src/print_boundary/tests.rs b/crates/pa-cli/src/print_boundary/tests.rsindex 91b3ece3cb..f24f6bd747 100644--- a/crates/pa-cli/src/print_boundary/tests.rs+++ b/crates/pa-cli/src/print_boundary/tests.rs@@ -136,6 +136,7 @@ async fn faux_engine_with_telemetry(model_info: Some(model.clone()),prewarm_ipython_kernel: None,on_background_work_settled: None,+ bash_notice_wake: None,queued_goal_context_purge: None,queued_steering_probe: None,should_stop_after_turn: None,diff --git a/crates/pa-cli/src/print_goal.rs b/crates/pa-cli/src/print_goal.rsindex 7c34f65a23..b8457aa319 100644--- a/crates/pa-cli/src/print_goal.rs+++ b/crates/pa-cli/src/print_goal.rs@@ -860,6 +860,7 @@ mod tests {model_info: Some(model.clone()),prewarm_ipython_kernel: None,on_background_work_settled: None,+ bash_notice_wake: None,queued_goal_context_purge: None,queued_steering_probe: None,should_stop_after_turn: None,@@ -1477,6 +1478,7 @@ mod tests {model_info: Some(model.clone()),prewarm_ipython_kernel: None,on_background_work_settled: None,+ bash_notice_wake: None,queued_goal_context_purge: None,queued_steering_probe: None,should_stop_after_turn: None,diff --git a/crates/pa-cli/src/print_rlm.rs b/crates/pa-cli/src/print_rlm.rsindex fcdd1bab33..bf9847cdd1 100644--- a/crates/pa-cli/src/print_rlm.rs+++ b/crates/pa-cli/src/print_rlm.rs@@ -72,6 +72,9 @@ pub(crate) struct InlineSessionNode {/// The session's engine, set right after the build (the host is/// passed into the engine config before the engine exists).engine: OnceLock<Weak<SessionEngine>>,+ /// Receipt callbacks must finish before the print tree can report quiescence.+ pending_receipts: std::sync::atomic::AtomicUsize,+ late_receipt_error: std::sync::Mutex<Option<String>>,/// Fired on every event the quiescence drive waits for: a delivered/// message, a child's settle, a re-run, a disposal.pub(crate) activity: Notify,@@ -196,6 +199,8 @@ pub(crate) fn root_node(parent: None,children: Mutex::new(Vec::new()),engine: OnceLock::new(),+ pending_receipts: std::sync::atomic::AtomicUsize::new(0),+ late_receipt_error: std::sync::Mutex::new(None),activity: Notify::new(),recipe: Arc::new(PrintRecipe {options: options.clone(),@@ -234,10 +239,70 @@ pub(crate) fn inline_subagent_wiring((Arc::new(InlineHost(Arc::clone(node))), handlers)}+/// The late fire-and-forget `agent_message.send` receipt sink: the+/// receipt records through the node's adopted engine (the engine is+/// published by `adopt_built_engine` right after the build).+pub(crate) fn late_sent_agent_message_sink(+ node: &Arc<InlineSessionNode>,+) -> pa_core::LateSentAgentMessageHandler {+ let node = Arc::clone(node);+ Arc::new(move |tool_call_id, message| {+ // Account on the whole ancestor chain before spawning: even a previously+ // settled child may receive a late callback while the root is parking.+ let mut pending_nodes = Vec::new();+ let mut current = Some(Arc::clone(&node));+ while let Some(current_node) = current {+ current_node+ .pending_receipts+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ // Admission must wake an already armed zero-count quiescence scan;+ // waiting only for completion leaves a window for false success.+ current_node.activity.notify_waiters();+ current = current_node.parent_node();+ pending_nodes.push(current_node);+ }+ let node = Arc::clone(&node);+ let tool_call_id = tool_call_id.to_string();+ tokio::spawn(async move {+ let failure = record_late_sent_receipt(node, tool_call_id, message)+ .await+ .err()+ .map(|error| format!("{error:#}"));+ for pending_node in pending_nodes {+ if let Some(error) = &failure {+ *pending_node.late_receipt_error.lock().unwrap() = Some(error.clone());+ }+ pending_node+ .pending_receipts+ .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);+ pending_node.activity.notify_waiters();+ }+ });+ })+}++/// Record one late receipt through the node's adopted engine; the sync+/// sink spawns this, but correctness no longer depends on its timing.+async fn record_late_sent_receipt(+ node: Arc<InlineSessionNode>,+ tool_call_id: String,+ message: pa_core::kernel::shared::KernelSentAgentMessage,+) -> anyhow::Result<()> {+ let Some(engine) = node.engine.get().and_then(Weak::upgrade) else {+ anyhow::bail!("late receipt arrived without a live print session engine");+ };+ engine+ .record_late_sent_agent_message(&tool_call_id, message)+ .await+}+// The quiescence drive/// Whether one child has live work (TS `child.isSessionActive`): not-/// settled, or a delivered row waiting in its lane, or a turn streaming.+/// settled, or a delivered row waiting in its lane, or a turn+/// streaming. (Live background bash is a child's own-drive hold, via+/// [`has_unsettled_rlm_work`]'s engine arm — a child never settles with+/// a live background command, so it needs no arm here.)/// The quiescence predicate, the collect wait, and the roster rows all/// read this one fact — never a second bookkeeping writer — so a/// follow-up delivered to a settled child reads unsettled until its@@ -247,7 +312,13 @@ async fn child_is_unsettled(child: &Arc<InlineChild>) -> bool {if child.node.is_disposed() {return false;}- if !child.state.lock().await.settled {+ if child+ .node+ .pending_receipts+ .load(std::sync::atomic::Ordering::SeqCst)+ > 0+ || !child.state.lock().await.settled+ {return true;}let agent = child.engine.session.agent();@@ -256,11 +327,19 @@ async fn child_is_unsettled(child: &Arc<InlineChild>) -> bool {/// Whether inline subagent work is unsettled (TS/// `_hasUnsettledRlmQuiescenceWork`): a running child, a delivered row-/// waiting in a child's lane, or a row queued on the root's own agent.+/// waiting in a child's lane, or a row queued on the root's own agent,+/// plus live background bash on either (TS `isSessionActive`)./// The goal/autonomous continuation gates and the drive's return read/// this one predicate: the live session state — not a bookkeeping flag/// alone — is the fact (TS `child.isSessionActive`).pub(crate) async fn has_unsettled_rlm_work(node: &Arc<InlineSessionNode>) -> bool {+ if node+ .pending_receipts+ .load(std::sync::atomic::Ordering::SeqCst)+ > 0+ {+ return true;+ }for child in node.children.lock().await.iter() {if child_is_unsettled(child).await {return true;@@ -269,7 +348,9 @@ pub(crate) async fn has_unsettled_rlm_work(node: &Arc<InlineSessionNode>) -> boonode.engine.get().and_then(Weak::upgrade)- .is_some_and(|engine| engine.session.agent().has_queued_messages())+ .is_some_and(|engine| {+ engine.session.agent().has_queued_messages() || engine.has_background_bash()+ })}/// Drive one inline session to quiescence: drain delivered messages as@@ -296,6 +377,9 @@ pub(crate) async fn drive_to_quiescence(let notified = node.activity.notified();tokio::pin!(notified);notified.as_mut().enable();+ if let Some(error) = node.late_receipt_error.lock().unwrap().clone() {+ return Err(error);+ }let agent = engine.session.agent();let streaming = agent.state().await.is_streaming;if !streaming && agent.has_queued_messages() {@@ -700,6 +784,8 @@ impl RlmSubagentHost for InlineHost {parent: Some(Arc::downgrade(&node)),children: Mutex::new(Vec::new()),engine: OnceLock::new(),+ pending_receipts: std::sync::atomic::AtomicUsize::new(0),+ late_receipt_error: std::sync::Mutex::new(None),activity: Notify::new(),recipe: Arc::clone(&recipe),disposed: std::sync::atomic::AtomicBool::new(false),@@ -1208,6 +1294,243 @@ mod tests {assert_eq!(admitted, 0);}+ /// The fake python tool of the landing test: records one late receipt+ /// through the print path (the factored async fn) while its cell's+ /// result row has not landed.+ struct LateReceiptPythonTool {+ node: Arc<InlineSessionNode>,+ }++ impl pa_agent::types::AgentTool for LateReceiptPythonTool {+ fn name(&self) -> &'static str {+ "python_repl"+ }++ fn description(&self) -> &'static str {+ "Runs a python cell."+ }++ fn parameters(&self) -> &serde_json::Value {+ static SCHEMA: std::sync::OnceLock<serde_json::Value> = std::sync::OnceLock::new();+ SCHEMA.get_or_init(|| serde_json::json!({ "type": "object", "properties": {} }))+ }++ fn execute(+ self: Arc<Self>,+ tool_call_id: String,+ _params: serde_json::Value,+ _signal: pa_agent::abort::AbortSignal,+ _on_update: pa_agent::types::AgentToolUpdateCallback,+ ) -> pa_agent::BoxFut<'static, anyhow::Result<pa_agent::types::AgentToolResult>> {+ let node = Arc::clone(&self.node);+ Box::pin(async move {+ record_late_sent_receipt(+ node,+ tool_call_id,+ pa_core::kernel::shared::KernelSentAgentMessage {+ id: "agentmsg_1".to_string(),+ message: "Ping.".to_string(),+ delivery_status: pa_core::kernel::shared::SentDeliveryStatus::Delivered,+ receiver_role: Some(pa_core::kernel::shared::ReceiverRole::Parent),+ target: pa_core::kernel::shared::SentAgentMessageTarget {+ active_session_id: "a1".to_string(),+ session_id: "s1".to_string(),+ session_name: Some("Worker".to_string()),+ },+ },+ )+ .await?;+ Ok(pa_agent::types::AgentToolResult::text("cell done"))+ })+ }+ }++ #[tokio::test]+ async fn detached_receipt_failure_holds_quiescence_and_wakes_the_error_path() {+ let directory = tempfile::tempdir().unwrap();+ let options = run_options(directory.path());+ let manager = pa_core::session::manager::SessionManager::in_memory(directory.path());+ let node = root_node(&options, &manager, None);+ let notified = node.activity.notified();+ tokio::pin!(notified);+ notified.as_mut().enable();+ let sink = late_sent_agent_message_sink(&node);+ sink(+ "call-1",+ pa_core::kernel::shared::KernelSentAgentMessage {+ id: "agentmsg_1".to_string(),+ message: "Ping.".to_string(),+ delivery_status: pa_core::kernel::shared::SentDeliveryStatus::Delivered,+ receiver_role: Some(pa_core::kernel::shared::ReceiverRole::Parent),+ target: pa_core::kernel::shared::SentAgentMessageTarget {+ active_session_id: "a1".to_string(),+ session_id: "s1".to_string(),+ session_name: None,+ },+ },+ );+ assert!(has_unsettled_rlm_work(&node).await);+ assert!(+ tokio::time::timeout(std::time::Duration::ZERO, notified)+ .await+ .is_ok(),+ "admission must wake an armed quiescence scan before the recorder runs"+ );+ let completed = node.activity.notified();+ tokio::pin!(completed);+ completed.as_mut().enable();+ tokio::time::timeout(std::time::Duration::from_secs(5), completed)+ .await+ .expect("receipt completion must wake the parked drive");+ assert_eq!(+ node.pending_receipts+ .load(std::sync::atomic::Ordering::SeqCst),+ 0+ );+ assert!(node+ .late_receipt_error+ .lock()+ .unwrap()+ .as_deref()+ .unwrap()+ .contains("without a live print session engine"));+ }++ #[tokio::test]+ async fn a_receipt_on_an_idle_child_holds_and_wakes_ancestor_quiescence() {+ let directory = tempfile::tempdir().unwrap();+ let options = run_options(directory.path());+ let manager = pa_core::session::manager::SessionManager::in_memory(directory.path());+ let root = root_node(&options, &manager, None);+ let mut child = root_node(&options, &manager, None);+ Arc::get_mut(&mut child).unwrap().parent = Some(Arc::downgrade(&root));+ let notified = root.activity.notified();+ tokio::pin!(notified);+ notified.as_mut().enable();+ late_sent_agent_message_sink(&child)(+ "call-1",+ pa_core::kernel::shared::KernelSentAgentMessage {+ id: "agentmsg_1".to_string(),+ message: "Ping.".to_string(),+ delivery_status: pa_core::kernel::shared::SentDeliveryStatus::Delivered,+ receiver_role: Some(pa_core::kernel::shared::ReceiverRole::Parent),+ target: pa_core::kernel::shared::SentAgentMessageTarget {+ active_session_id: "a1".to_string(),+ session_id: "s1".to_string(),+ session_name: None,+ },+ },+ );+ // Even with no active child turn in the root's roster, pending work holds it.+ assert!(has_unsettled_rlm_work(&root).await);+ assert!(+ tokio::time::timeout(std::time::Duration::ZERO, notified)+ .await+ .is_ok(),+ "child receipt admission must wake the ancestor before recording starts"+ );+ let completed = root.activity.notified();+ tokio::pin!(completed);+ completed.as_mut().enable();+ tokio::time::timeout(std::time::Duration::from_secs(5), completed)+ .await+ .expect("a child's completed recorder must wake its ancestor");+ assert_eq!(+ root.pending_receipts+ .load(std::sync::atomic::Ordering::SeqCst),+ 0+ );+ assert!(root+ .late_receipt_error+ .lock()+ .unwrap()+ .as_deref()+ .unwrap()+ .contains("without a live print session engine"));+ }++ #[tokio::test]+ async fn late_receipts_record_through_the_print_path_apply_on_landing() {+ let directory = tempfile::tempdir().unwrap();+ let options = run_options(directory.path());+ std::fs::create_dir_all(&options.config.agent_dir).unwrap();+ let manager = pa_core::session::manager::SessionManager::persisted(+ directory.path(),+ &directory.path().join("sessions"),+ );+ let script = json!({+ "responses": [+ { "content": [+ { "type": "toolCall", "id": "call-1", "name": "python_repl", "arguments": {} }+ ] },+ "all done",+ ],+ });+ let node = root_node(&options, &manager, Some(script.clone()));+ let headless = crate::print_runtime::build_engine(+ &options,+ Some(&script),+ Some(manager),+ "print",+ &HeadlessEmbedding::Root {+ node: Arc::clone(&node),+ },+ )+ .await+ .unwrap();+ let engine = Arc::new(headless.engine);+ adopt_built_engine(&node, &engine, &headless.model).await;+ // The scripted turn runs a fake python tool in place of the+ // kernel-backed one: the tool records the receipt while its cell's+ // result row has not landed.+ engine+ .session+ .agent()+ .set_tools(vec![Arc::new(LateReceiptPythonTool {+ node: Arc::clone(&node),+ })])+ .await;++ let outcome = engine+ .prompt(+ "run the cell",+ pa_core::session_engine::PromptOptions::default(),+ )+ .await+ .unwrap();+ assert_eq!(outcome, pa_core::session_engine::PromptOutcome::Prompt);+ engine.session.agent().wait_for_idle().await;++ // The landed row carries the receipt in live state.+ let state = engine.session.agent().state().await;+ let result = state+ .messages+ .iter()+ .find_map(|row| match row {+ pa_agent::types::AgentMessage::Standard(pa_agent::types::Message::ToolResult(+ result,+ )) if result.tool_call_id == "call-1" => Some(result.clone()),+ _ => None,+ })+ .expect("the landed tool result");+ let details = result.details.as_ref().expect("the receipt rides the row");+ assert_eq!(+ details["sentAgentMessages"][0]["id"], "agentmsg_1",+ "the live state row carries the receipt"+ );++ let entries = engine.session.entries().await;+ assert!(+ entries.iter().any(|entry| matches!(+ entry,+ pa_types::session::FileEntry::Custom { payload, .. }+ if payload.custom_type == "ipython_sent_agent_message"+ )),+ "the receipt persists as a custom entry"+ );+ engine.dispose_kernel().await;+ }+#[tokio::test]async fn delivery_to_a_disposed_session_rejects_without_queuing() {let directory = tempfile::tempdir().unwrap();diff --git a/crates/pa-cli/src/print_runtime.rs b/crates/pa-cli/src/print_runtime.rsindex ced6690022..68047a9726 100644--- a/crates/pa-cli/src/print_runtime.rs+++ b/crates/pa-cli/src/print_runtime.rs@@ -8,6 +8,7 @@ use pa_core::session::discovery::{find_most_recent_session_for_cwd, resolve_session_path, ResolvedSession, SessionSelectorError,};use pa_types::ai::Model;+use tokio::sync::Notify;use crate::headless_autonomous::{autonomous_runtime_config, HeadlessAutonomous};use crate::mode::{AppMode, MissingSubsystem, RunOptions};@@ -363,6 +364,9 @@ impl From<HeadlessEngine> for pa_daemon::rpc::session::RpcEngineHandle {model: parts.model,api_key: parts.api_key,provider_target: parts.provider_target,+ bash_wake: parts+ .rpc_bash_wake+ .expect("the RPC embedding builds its background-bash wake handle"),session_lease: None,}}@@ -512,6 +516,74 @@ pub(crate) enum ChildLane {Faux(FauxChildQueue),}+/// The per-embedding fields both headless builders (the real provider+/// and the faux script) share: the inline host + agent-message handlers+/// with the RLM depth, the background-bash wake both engine seams fire+/// (the completion row's admission wake and the kernel's+/// background-settle callback), and the late agent-message receipt sink+/// print sessions record through.+pub(crate) struct HeadlessEmbeddingFields {+ pub(crate) rlm_subagent_host:+ Option<Arc<dyn pa_core::session_engine::rlm_host::RlmSubagentHost>>,+ pub(crate) extra_host_handlers: Option<pa_core::kernel::shared::HostRequestHandlers>,+ pub(crate) rlm_depth: Option<u32>,+ pub(crate) bash_wake: pa_core::session_engine::bash_notices::BashNoticeWake,+ /// The RPC mode's wake handle, carried onto the engine handle so the+ /// queue-pump listener parks on it; `None` outside the RPC embedding.+ pub(crate) rpc_bash_wake: Option<Arc<Notify>>,+ /// The late fire-and-forget `agent_message.send` receipt sink+ /// (#10-print); `None` for the RPC embedding (no print node).+ pub(crate) on_late_sent_agent_message: Option<pa_core::LateSentAgentMessageHandler>,+}++/// The embedding-owned fields for one headless engine build: print+/// sessions wake on the inline node's activity (every quiescence park+/// listens on it), the RPC mode on the built handle's notify.+pub(crate) fn headless_embedding_fields(embedding: &HeadlessEmbedding) -> HeadlessEmbeddingFields {+ let node = match embedding {+ HeadlessEmbedding::Root { node } => Some(Arc::clone(node)),+ HeadlessEmbedding::Child(overrides) => Some(Arc::clone(&overrides.node)),+ HeadlessEmbedding::Rpc => None,+ };+ let (rlm_subagent_host, extra_host_handlers) = match &node {+ Some(node) => {+ let (host, handlers) = crate::print_rlm::inline_subagent_wiring(node);+ (Some(host), Some(handlers))+ }+ None => (None, None),+ };+ let (bash_wake, rpc_bash_wake) = if let Some(node) = &node {+ let node = Arc::clone(node);+ (+ Arc::new(move || node.activity.notify_waiters())+ as pa_core::session_engine::bash_notices::BashNoticeWake,+ None,+ )+ } else {+ let notify = Arc::new(Notify::new());+ let wake = {+ let notify = Arc::clone(¬ify);+ Arc::new(move || notify.notify_waiters())+ as pa_core::session_engine::bash_notices::BashNoticeWake+ };+ (wake, Some(notify))+ };+ let on_late_sent_agent_message = node+ .as_ref()+ .map(crate::print_rlm::late_sent_agent_message_sink);+ HeadlessEmbeddingFields {+ rlm_subagent_host,+ extra_host_handlers,+ rlm_depth: match embedding {+ HeadlessEmbedding::Child(overrides) => Some(overrides.node.depth),+ HeadlessEmbedding::Root { .. } | HeadlessEmbedding::Rpc => None,+ },+ bash_wake,+ rpc_bash_wake,+ on_late_sent_agent_message,+ }+}+/// The assembled headless engine, so host transports can drive session-command/// executors (compact/refine) with the session's own model.pub(crate) struct HeadlessEngine {@@ -523,6 +595,9 @@ pub(crate) struct HeadlessEngine {/// re-registration; `set_model` swaps it without rebuilding the/// session).provider_target: ProviderTargetSlot,+ /// The RPC mode's background-bash wake handle; `None` for the print+ /// embeddings (their wake is the node's activity notify).+ pub(crate) rpc_bash_wake: Option<Arc<Notify>>,}/// Transfer the opened lease to its mode before fallible engine assembly.@@ -688,18 +763,15 @@ pub(crate) async fn build_headless_engine_with(// ledger-less but the request ids still go on the wire.let session_manager = session_manager.unwrap_or_else(|| pa_core::session::manager::SessionManager::in_memory(&config.cwd));- let (rlm_subagent_host, extra_host_handlers) = match embedding {- HeadlessEmbedding::Rpc => (None, None),- HeadlessEmbedding::Root { node } => {- let (host, handlers) = crate::print_rlm::inline_subagent_wiring(node);- (Some(host), Some(handlers))- }- HeadlessEmbedding::Child(overrides) => {- let (host, handlers) = crate::print_rlm::inline_subagent_wiring(&overrides.node);- (Some(host), Some(handlers))- }- };- let (semantic_edges, rlm_depth, thinking_level) = match embedding {+ let HeadlessEmbeddingFields {+ rlm_subagent_host,+ extra_host_handlers,+ rlm_depth,+ bash_wake,+ rpc_bash_wake,+ on_late_sent_agent_message,+ } = headless_embedding_fields(embedding);+ let (semantic_edges, thinking_level) = match embedding {HeadlessEmbedding::Child(overrides) => (Some(pa_core::session_engine::semantic_edges::SemanticEdgeIdentity {@@ -713,7 +785,6 @@ pub(crate) async fn build_headless_engine_with(spawned_by_request_id: overrides.spawned_by_request_id.clone(),},),- Some(overrides.node.depth),Some(pa_core::session_engine::provider_adapter::map_thinking_level(overrides.thinking)),),HeadlessEmbedding::Root { .. } | HeadlessEmbedding::Rpc => (@@ -728,13 +799,12 @@ pub(crate) async fn build_headless_engine_with(spawned_by_request_id: None,},),- None,Some(resolve_thinking_level(config, &model)),),};let engine = pa_core::session_engine::engine::create_session(pa_core::session_engine::engine::SessionEngineConfig {- on_late_sent_agent_message: None,+ on_late_sent_agent_message,cron_store: None,semantic_edges,telemetry,@@ -775,7 +845,11 @@ pub(crate) async fn build_headless_engine_with(// child boots lazily on first use.prewarm_ipython_kernel: (!matches!(embedding, HeadlessEmbedding::Child(_))).then_some(true),- on_background_work_settled: None,+ // The background-bash wake pair: the completion row's+ // admission fires it, and the kernel's background settle does+ // too, so the embedding's parked drive or pump re-checks.+ bash_notice_wake: Some(Arc::clone(&bash_wake)),+ on_background_work_settled: Some(bash_wake),queued_goal_context_purge: None,queued_steering_probe: None,should_stop_after_turn: None,@@ -789,6 +863,7 @@ pub(crate) async fn build_headless_engine_with(model,api_key: resolved.api_key,provider_target,+ rpc_bash_wake,})}diff --git a/crates/pa-cli/src/print_runtime/faux.rs b/crates/pa-cli/src/print_runtime/faux.rsindex 30075e580d..a071fad3cd 100644--- a/crates/pa-cli/src/print_runtime/faux.rs+++ b/crates/pa-cli/src/print_runtime/faux.rs@@ -8,7 +8,8 @@ use pa_core::session_engine::provider_adapter::{};use crate::print_runtime::{- ChildLane, HeadlessEmbedding, HeadlessEngine, ProviderTargetSlot, RunOptions,+ ChildLane, HeadlessEmbedding, HeadlessEmbeddingFields, HeadlessEngine, ProviderTargetSlot,+ RunOptions,};/// The parsed `PRIME_AGENT_FAUX_SCRIPT` (the whole-process verification@@ -124,20 +125,17 @@ pub(crate) async fn build_faux_engine_with(let stream_fn = switchable_stream_fn(std::sync::Arc::clone(&provider_target));// The faux path shares the session-manager wiring with the real provider// path so binary-level tests can verify persistence without the network.- let (rlm_subagent_host, extra_host_handlers, rlm_depth) = match embedding {- HeadlessEmbedding::Rpc => (None, None, None),- HeadlessEmbedding::Root { node } => {- let (host, handlers) = crate::print_rlm::inline_subagent_wiring(node);- (Some(host), Some(handlers), None)- }- HeadlessEmbedding::Child(overrides) => {- let (host, handlers) = crate::print_rlm::inline_subagent_wiring(&overrides.node);- (Some(host), Some(handlers), Some(overrides.node.depth))- }- };+ let HeadlessEmbeddingFields {+ rlm_subagent_host,+ extra_host_handlers,+ rlm_depth,+ bash_wake,+ rpc_bash_wake,+ on_late_sent_agent_message,+ } = super::headless_embedding_fields(embedding);let engine = pa_core::session_engine::engine::create_session(pa_core::session_engine::engine::SessionEngineConfig {- on_late_sent_agent_message: None,+ on_late_sent_agent_message,cron_store: None,// Faux verification harness: no product telemetry.semantic_edges: None,@@ -169,7 +167,10 @@ pub(crate) async fn build_faux_engine_with(model_info: Some(model.clone()),// A Rust-only verification harness: no background kernel boot in tests.prewarm_ipython_kernel: None,- on_background_work_settled: None,+ // The background-bash wake pair, the same seam the real+ // provider path wires (the scripted e2es drive the wake).+ bash_notice_wake: Some(std::sync::Arc::clone(&bash_wake)),+ on_background_work_settled: Some(bash_wake),queued_goal_context_purge: None,queued_steering_probe: None,should_stop_after_turn: None,@@ -183,6 +184,7 @@ pub(crate) async fn build_faux_engine_with(model,api_key: None,provider_target,+ rpc_bash_wake,})}diff --git a/crates/pa-cli/src/print_session_command.rs b/crates/pa-cli/src/print_session_command.rsindex fe63356fbd..069e1e4d0c 100644--- a/crates/pa-cli/src/print_session_command.rs+++ b/crates/pa-cli/src/print_session_command.rs@@ -353,6 +353,7 @@ mod tests {model_info: Some(model.clone()),prewarm_ipython_kernel: None,on_background_work_settled: None,+ bash_notice_wake: None,queued_goal_context_purge: None,queued_steering_probe: None,should_stop_after_turn: None,diff --git a/crates/pa-cli/tests/print_inline_subagents_e2e.rs b/crates/pa-cli/tests/print_inline_subagents_e2e.rsindex 3ede60ab2e..dcddd07290 100644--- a/crates/pa-cli/tests/print_inline_subagents_e2e.rs+++ b/crates/pa-cli/tests/print_inline_subagents_e2e.rs@@ -1105,3 +1105,151 @@ Path("cancel-child-finished").write_text("unexpected")"cancelled child's Python process {child_pid} outlived the print run");}++/// The injected `[bash-done]` row in one session file's entries (the+/// `async_bash_completion` custom row the completion handler steers).+fn bash_done_row(entries: &[serde_json::Value]) -> serde_json::Value {+ entries+ .iter()+ .find(|entry| {+ entry.get("type").and_then(|t| t.as_str()) == Some("custom_message")+ && entry.get("customType").and_then(|t| t.as_str()) == Some("async_bash_completion")+ })+ .cloned()+ .unwrap_or_else(|| panic!("the [bash-done] completion row: {entries:?}"))+}++/// The root print session wakes on a background `bash()` completion+/// (audit #3; TS registers `bash.completed` in every mode): turn 1+/// starts a detached command and ends, the run stays open (the+/// quiescence predicate counts live background bash), and the+/// completion row steers onto the agent and runs as the second turn.+#[test]+fn print_root_wakes_on_a_background_bash_completion() {+ let lane = lane();+ let kernel = PrintLane::kernel_python();+ let script = serde_json::json!({+ "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": "h = bash(\"sleep 3; echo BG_DONE\")\nprint(\"STARTED\", h.pid)" } },+ ] },+ "WAITING",+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": "print(\"WOKEN\", \"BG_DONE\" in h.output())" } },+ ] },+ "COMPLETED WOKEN",+ ],+ "repeatLastResponse": true,+ });+ let (stdout, stderr, code) = lane.run(+ &["-p", "run the long command in the background"],+ &script,+ &kernel,+ &[],+ );+ assert_eq!(code, 0, "stderr: {stderr}\nstdout: {stdout}");+ assert_eq!(+ stdout.trim_end(),+ "COMPLETED WOKEN",+ "the completion row ran as the second turn, not the pre-completion \"WAITING\" answer"+ );++ // The injected row is durable in the session transcript.+ let entries = PrintLane::entries(&lane.parent_session_file());+ let row = bash_done_row(&entries);+ assert_eq!(+ row.pointer("/details/exitCode")+ .and_then(serde_json::Value::as_i64),+ Some(0),+ "the row carries the finished exit code: {row}"+ );+}++/// A spawned child's own background `bash()` holds the print run open+/// (TS `child.isSessionActive` includes the kernel's background work):+/// the child's completion row wakes its driver, the reply turn runs,+/// and the parent answers with the combined text before it exits.+#[test]+fn print_inline_child_wakes_on_a_background_bash_completion() {+ let lane = lane();+ let kernel = PrintLane::kernel_python();+ let script = serde_json::json!({+ "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": "kid = await rlm.spawn(\"run the background task\", name=\"bgkid\")\nprint(\"KID\", kid.rlm_child_id)" } },+ ] },+ "WAITING",+ "COMBINED KID-BG-RESULT",+ ],+ "repeatLastResponse": true,+ "children": {+ "bgkid": { "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": "h = bash(\"sleep 3; echo KID_BG\")\nprint(\"KID STARTED\")" } },+ ] },+ "kid waiting",+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": "await agent_message.send(\"KID-BG-RESULT\", receiver_role=\"parent\")\nprint(\"KID WOKEN\", \"KID_BG\" in h.output())" } },+ ] },+ "kid finished",+ ] },+ },+ });+ let (stdout, stderr, code) = lane.run(+ &["-p", "delegate the background work"],+ &script,+ &kernel,+ &[],+ );+ assert_eq!(code, 0, "stderr: {stderr}\nstdout: {stdout}");+ assert_eq!(+ stdout.trim_end(),+ "COMBINED KID-BG-RESULT",+ "the child's completion woke its driver and the reply drained before the exit"+ );++ // The reply the woken child sent is durable in the parent's+ // transcript (on a base tree the parent's "combined" turn runs over+ // the no-reply notice instead).+ let parent_file = lane.parent_session_file();+ let parent_text = serde_json::to_string(&PrintLane::entries(&parent_file)).unwrap();+ assert!(+ parent_text.contains("KID-BG-RESULT"),+ "the woken child's reply reached the parent: {parent_text}"+ );+ let parent_id = Path::new(&parent_file)+ .file_stem()+ .and_then(|stem| stem.to_str())+ .expect("the parent session id")+ .to_string();+ let artifacts = lane.agent_dir.join("session-artifacts").join(&parent_id);+ let child_dirs: Vec<PathBuf> = std::fs::read_dir(&artifacts)+ .expect("the child's session dir exists")+ .flatten()+ .map(|entry| entry.path())+ .filter(|path| {+ path.file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.starts_with("sub-"))+ })+ .collect();+ assert_eq!(child_dirs.len(), 1, "one child session dir: {child_dirs:?}");+ let kid_file: Vec<PathBuf> = std::fs::read_dir(&child_dirs[0])+ .unwrap()+ .flatten()+ .map(|entry| entry.path())+ .filter(|path| path.extension().and_then(|e| e.to_str()) == Some("jsonl"))+ .collect();+ let row = bash_done_row(&PrintLane::entries(&kid_file[0]));+ assert_eq!(+ row.pointer("/details/exitCode")+ .and_then(serde_json::Value::as_i64),+ Some(0),+ "the child's row carries the finished exit code: {row}"+ );+}diff --git a/crates/pa-cli/tests/rpc_mode_e2e.rs b/crates/pa-cli/tests/rpc_mode_e2e.rsindex e75875ac42..c1c9df5493 100644--- a/crates/pa-cli/tests/rpc_mode_e2e.rs+++ b/crates/pa-cli/tests/rpc_mode_e2e.rs@@ -38,12 +38,47 @@ struct RpcChild {impl RpcChild {fn spawn(args: &[&str], script: &Value) -> RpcChild {- Self::spawn_seeded(args, script, None)+ Self::spawn_seeded(args, script, None, None)+ }++ /// Spawn with a live kernel Python: the background-bash lane needs a+ /// real kernel behind the `ipython` tool.+ fn spawn_kernel(args: &[&str], script: &Value) -> RpcChild {+ Self::spawn_seeded(args, script, None, Some(Self::kernel_python()))+ }++ /// The kernel Python with prime-agent-runtime installed; a missing+ /// kernel FAILS the lane loudly (the wake lane's proof).+ fn kernel_python() -> std::path::PathBuf {+ if let Some(explicit) = std::env::var_os("PA_E2E_KERNEL_PYTHON") {+ let explicit = std::path::PathBuf::from(explicit);+ assert!(+ explicit.exists(),+ "PA_E2E_KERNEL_PYTHON {} not found",+ explicit.display()+ );+ return explicit;+ }+ let candidate = std::path::PathBuf::from(std::env::var("HOME").map_or_else(+ |_| "/home/ubuntu/.prime/agent/kernel-venv/bin/python".to_string(),+ |home| format!("{home}/.prime/agent/kernel-venv/bin/python"),+ ));+ assert!(+ candidate.exists(),+ "kernel python {} not found: set PA_E2E_KERNEL_PYTHON",+ candidate.display()+ );+ candidate}/// Spawn with a seeded `models.json`: the faux provider needs its/// provider entry + key to pass the registry's configured-auth gate.- fn spawn_seeded(args: &[&str], script: &Value, models: Option<Value>) -> RpcChild {+ fn spawn_seeded(+ args: &[&str],+ script: &Value,+ models: Option<Value>,+ kernel_python: Option<std::path::PathBuf>,+ ) -> RpcChild {let home = tempfile::TempDir::new().unwrap();if let Some(models) = models {let agent_dir = home.path().join("agent");@@ -51,11 +86,18 @@ impl RpcChild {std::fs::write(agent_dir.join("models.json"), models.to_string()).unwrap();}let bin = env!("CARGO_BIN_EXE_prime-agent");- let mut child = Command::new(bin)+ let mut command = Command::new(bin);+ command.args(args).env("HOME", home.path()).env("PRIME_AGENT_CODING_AGENT_DIR", home.path().join("agent")).env("PRIME_AGENT_FAUX_SCRIPT", script.to_string())+ .env_remove("RLM_DEPTH")+ .env_remove("RLM_MAX_DEPTH");+ if let Some(kernel) = kernel_python {+ command.env("PRIME_AGENT_KERNEL_PYTHON", kernel);+ }+ let mut child = command.current_dir(home.path()).stdin(Stdio::piped()).stdout(Stdio::piped())@@ -638,6 +680,7 @@ fn rpc_get_available_models_lists_the_catalog() {}}})),+ None,);let response = client.request(&json!({ "type": "get_available_models" }));assert_eq!(response["success"], true, "the response: {response}");@@ -869,6 +912,47 @@ fn rpc_failed_replacement_restarts_the_queue_pump() {}}+/// An idle RPC session wakes on a background `bash()` completion+/// (audit #3; TS registers `bash.completed` in every mode): turn 1+/// starts a detached command and settles, and the completion row runs+/// as a second turn with no further client command driving it. The+/// lane must survive a whole-session replacement (the listener serves+/// the live engine's wake).+#[test]+fn rpc_idle_session_runs_a_turn_on_a_background_bash_completion() {+ let mut client = RpcChild::spawn_kernel(+ &["--mode", "rpc", "--no-session"],+ &json!({+ "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": "h = bash(\"sleep 3; echo RPC_BG\")\nprint(\"STARTED\")" } },+ ] },+ "WAITING",+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": "print(\"WOKEN\", \"RPC_BG\" in h.output())" } },+ ] },+ "RPC WOKEN",+ ],+ "repeatLastResponse": true,+ }),+ );+ // Replace the whole session BEFORE the background lane runs: the+ // wake listener must serve the replacement's engine too.+ let fresh = client.request(&json!({ "type": "new_session" }));+ assert_eq!(fresh["data"], json!({ "cancelled": false }));+ let id = client+ .command(&json!({ "type": "prompt", "message": "run the long command in the background" }));+ let (response, _) = client.wait_response(&id, TIMEOUT);+ assert_eq!(response["success"], true, "the response: {response}");+ // Turn 1 settles on the background command still running.+ client.wait_event("agent_end", TIMEOUT);+ // The completion row arrives unprompted: its turn is the second+ // agent_end (the queue pump delivers the steered row).+ client.wait_event("agent_end", Duration::from_secs(30));+}+/// The 143 exit must not queue behind the replacement's settle.#[test]fn rpc_sigterm_during_replacement_exits_promptly() {diff --git a/crates/pa-core/src/kernel/provisioner.rs b/crates/pa-core/src/kernel/provisioner.rsindex 1fe444f3bc..c6e26f5850 100644--- a/crates/pa-core/src/kernel/provisioner.rs+++ b/crates/pa-core/src/kernel/provisioner.rs@@ -278,6 +278,13 @@ impl IpythonKernelProvisioner {self.lock_state().manager.clone()}+ /// The Python skills pre-imported at kernel bootstrap.+ #[cfg(test)]+ #[must_use]+ pub(crate) fn python_skills(&self) -> &[KernelPythonSkill] {+ &self.inner.options.python_skills+ }+/// Result of reviving a prior session's namespace on the last kernel start.#[must_use]pub fn last_restore(&self) -> Option<RestoreResult> {diff --git a/crates/pa-core/src/prompts/system_prompt.rs b/crates/pa-core/src/prompts/system_prompt.rsindex ba664f5705..a6824eccd7 100644--- a/crates/pa-core/src/prompts/system_prompt.rs+++ b/crates/pa-core/src/prompts/system_prompt.rs@@ -87,8 +87,8 @@ pub struct BuildSystemPromptOptions<'a> {/// Human-readable parent name or id for child communication doctrine.pub rlm_parent_agent: Option<&'a str>,/// Whether the session runs without a daemon (no scheduler, no- /// bash-completion wake-ups). The wake-up facts the daemonless line- /// states must match the embedding's wiring.+ /// heartbeat firing). The wake-up facts the daemonless line states+ /// must match the embedding's wiring.pub daemonless: bool,/// Whether `rlm.spawn` can create children in this session (the/// daemonless print host or a daemon worker); a daemonless session@@ -298,24 +298,21 @@ fn session_role_section(options: &BuildSystemPromptOptions, has_ipython: bool) -)];if options.daemonless {lines.push(if options.can_spawn {- "This session has no daemon: heartbeats never fire, and background `bash()` completions do not wake you, so await them before ending your turn. Subagent replies and exit notices still wake you, and the run waits for your subagents before it exits."+ "This session has no daemon: heartbeats never fire, and background `bash()` completions wake you with a queued `[bash-done]` turn; the run waits for live background commands and your subagents before it exits. Subagent replies and exit notices still wake you.".to_string()} else {- "This session has no daemon: `rlm.spawn` is unavailable, heartbeats never fire, and background `bash()` completions do not wake you, so await them before ending your turn."+ "This session has no daemon: `rlm.spawn` is unavailable, heartbeats never fire, and background `bash()` completions wake you with a queued `[bash-done]` turn.".to_string()});}- if !has_ipython {+ if has_ipython {lines.push(- "This session has no Python REPL (`python_repl` tool): the programmatic tools described above are unavailable here."+ "`await bash(cmd)` waits at most `yield_after` seconds (`bash(cmd, yield_after=...)`, default 10, max 300; `None` uses the default, not an unbounded wait). If the command is still running, it returns a snapshot: `r.running` is True, `r.exit_code` is None, `r.output` is the output so far, and `r.handle` is the live handle. A completed result has `r.running` False and an integer `r.exit_code`. The command keeps running after a snapshot; end the turn and collect the final result on the `[bash-done]` notification.".to_string(),);- } else if !options.daemonless {- // The bounded-await runtime half runs only where the host registers- // the bash completion notice (the same sessions the daemonless flag- // excludes), so the contract renders only there.+ } else {lines.push(- "`await bash(cmd)` waits at most `yield_after` seconds (`bash(cmd, yield_after=...)`, default 10, max 300; `None` uses the default, not an unbounded wait). If the command is still running, it returns a snapshot: `r.running` is True, `r.exit_code` is None, `r.output` is the output so far, and `r.handle` is the live handle. A completed result has `r.running` False and an integer `r.exit_code`. The command keeps running after a snapshot; end the turn and collect the final result on the `[bash-done]` notification."+ "This session has no Python REPL (`python_repl` tool): the programmatic tools described above are unavailable here.".to_string(),);}@@ -521,6 +518,20 @@ mod tests {.contains("Enabled generic MCP servers: `t`."));}+ #[test]+ fn daemonless_line_drops_the_stale_no_wake_claim() {+ // The line's one durable contract: it no longer tells daemonless+ // agents that background completions never wake them.+ let mut spawning = base_options();+ spawning.daemonless = true;+ spawning.can_spawn = true;+ assert!(!build_system_prompt(&spawning).contains("completions do not wake you"));++ let mut bare = base_options();+ bare.daemonless = true;+ assert!(!build_system_prompt(&bare).contains("completions do not wake you"));+ }+#[test]fn model_prompt_extras_form_the_last_static_segment() {let mut options = base_options();diff --git a/crates/pa-core/src/session/manager/queries.rs b/crates/pa-core/src/session/manager/queries.rsindex 9f227b12c3..6e636a061b 100644--- a/crates/pa-core/src/session/manager/queries.rs+++ b/crates/pa-core/src/session/manager/queries.rs@@ -425,6 +425,18 @@ impl SessionManager {&self.file_entries}+ /// The persisted late `agent_message.send` receipts on the active+ /// branch, oldest first: an engine build patches them onto the rebuilt+ /// `python_repl` tool results (TS `_restoreLateIpythonSentAgentMessages`).+ #[must_use]+ pub fn late_sent_agent_messages(+ &self,+ ) -> Vec<crate::session_engine::late_sent_messages::PersistedSentAgentMessage> {+ crate::session_engine::late_sent_messages::scan_sent_agent_message_entries(+ self.active_branch_entries(),+ )+ }+#[must_use]pub fn get_leaf_id(&self) -> Option<&str> {self.leaf_id.as_deref()diff --git a/crates/pa-core/src/session_engine/bash_notices.rs b/crates/pa-core/src/session_engine/bash_notices.rsnew file mode 100644index 0000000000..94643383d3--- /dev/null+++ b/crates/pa-core/src/session_engine/bash_notices.rs@@ -0,0 +1,341 @@+//! The detached kernel bash completion notice (the TS async-bash-completion+//! wake: `bash.completed`/`bash.consumed`): the shared notice types, the+//! TS payload validation, and the host-handler registration, plus the+//! in-process sinks a daemonless embedding uses — the completion row+//! steers onto the session's own agent and the embedding's wake fires.++use std::sync::{Arc, Mutex, Weak};++use serde_json::Value;++use crate::kernel::shared::{host_handler, HostRequestHandlers, BASH_COMPLETED_REQUEST_TYPE};+use pa_agent::types::AgentMessage;++use super::messages::{self, ASYNC_BASH_COMPLETION_CUSTOM_TYPE};+use super::{session_message_to_loop, SessionAgentMessage};++/// One detached kernel bash completion (the `bash.completed` host+/// request): the finished command's identity and exit code.+#[derive(Debug, Clone)]+pub struct BashCompletionNotice {+ pub pid: u32,+ pub command: String,+ pub exit_code: i64,+}++/// The queue-admission seam for one completion notice (the daemon+/// worker's steering lane + runner wake + recovery busy-evidence; the+/// in-process sinks below steer onto the session's own agent).+pub type BashCompletionSink = Arc<dyn Fn(BashCompletionNotice) + Send + Sync>;++/// The kernel read a finished command's result before its notice+/// delivered (the `bash.consumed` host request): the queued notice is stale.+#[derive(Debug, Clone)]+pub struct BashConsumedNotice {+ pub pid: u32,+ pub command: String,+}++/// The queue-withdrawal seam for one consumed notice.+pub type BashConsumedSink = Arc<dyn Fn(BashConsumedNotice) + Send + Sync>;++/// The daemonless embedding's wake (TS `resumeIfIdle`): fires after a+/// notice admits its row, so the embedding resumes the idle run.+pub type BashNoticeWake = Arc<dyn Fn() + Send + Sync>;++/// The `bash.completed`/`bash.consumed` kernel host handlers (TS+/// `createAsyncBashCompletionHostHandler`/`createAsyncBashConsumedHostHandler`).+pub fn register_bash_notice_host_handlers(+ completion: BashCompletionSink,+ consumed: BashConsumedSink,+ handlers: &mut HostRequestHandlers,+) {+ handlers.register(+ BASH_COMPLETED_REQUEST_TYPE,+ host_handler(move |payload| {+ let completion = completion.clone();+ Box::pin(async move {+ let notice = validate_completion(&payload.data)?;+ // Any closed-session gate is the sink's (the daemon+ // worker refuses injections after kill/shutdown like TS+ // `_disposed`; the in-process sinks bind a weak agent).+ completion(notice);+ Ok(serde_json::json!({}))+ })+ }),+ );+ handlers.register(+ "bash.consumed",+ host_handler(move |payload| {+ let consumed = consumed.clone();+ Box::pin(async move {+ let notice = validate_consumed(&payload.data)?;+ consumed(notice);+ Ok(serde_json::json!({}))+ })+ }),+ );+}++/// TS `createAsyncBashCompletionHostHandler` validation: a positive+/// integer pid, a non-empty string command, an integer exit code.+fn validate_completion(data: &Value) -> anyhow::Result<BashCompletionNotice> {+ let consumed = validate_consumed(data)?;+ let exit_code = data+ .get("exitCode")+ .and_then(Value::as_i64)+ .ok_or_else(|| anyhow::anyhow!("bash.completed exitCode must be an integer"))?;+ Ok(BashCompletionNotice {+ pid: consumed.pid,+ command: consumed.command,+ exit_code,+ })+}++/// TS `createAsyncBashConsumedHostHandler` validation: a positive integer pid and a+/// non-empty command (pids are reused across handles, so the command disambiguates).+fn validate_consumed(data: &Value) -> anyhow::Result<BashConsumedNotice> {+ let pid = data+ .get("pid")+ .and_then(Value::as_u64)+ .filter(|pid| *pid > 0 && u32::try_from(*pid).is_ok())+ .ok_or_else(|| anyhow::anyhow!("bash.completed pid must be a positive integer"))?+ as u32;+ let command = data+ .get("command")+ .and_then(Value::as_str)+ .filter(|command| !command.is_empty())+ .ok_or_else(|| anyhow::anyhow!("bash.completed command must be a non-empty string"))?+ .to_string();+ Ok(BashConsumedNotice { pid, command })+}++/// The session's agent through which the in-process sinks steer and+/// withdraw: late-bound because the handlers register before the agent+/// exists, and weak so the handler -> agent -> kernel -> handler graph+/// stays acyclic (a dropped session's handlers bind nothing).+pub type BashNoticeAgentSlot = Arc<Mutex<Option<Weak<pa_agent::agent::Agent>>>>;++/// The in-process sinks over one session's own agent (the daemonless+/// embeddings): a completion steers the `[bash-done]` row onto the+/// agent's steering queue and fires the embedding's wake (TS+/// `queueIfBusy: true` + `resumeIfIdle: true` — the row rides the+/// steering lane and the embedding resumes the idle run); a consumed+/// notice withdraws the queued row.+pub fn register_in_process_bash_notice_handlers(+ wake: &BashNoticeWake,+ agent_slot: &BashNoticeAgentSlot,+ handlers: &mut HostRequestHandlers,+) {+ let completion_wake = Arc::clone(wake);+ let completion_slot = Arc::clone(agent_slot);+ let completion: BashCompletionSink = Arc::new(move |notice| {+ let Some(agent) = bound_agent(&completion_slot) else {+ return;+ };+ let row = messages::create_async_bash_completion_message(+ notice.pid,+ ¬ice.command,+ notice.exit_code,+ crate::autonomous::now_millis(),+ );+ let Some(row) = session_message_to_loop(&SessionAgentMessage::Custom(row)) else {+ return;+ };+ agent.steer(row);+ completion_wake();+ });+ let consumed_slot = Arc::clone(agent_slot);+ let consumed: BashConsumedSink = Arc::new(move |notice| {+ let Some(agent) = bound_agent(&consumed_slot) else {+ return;+ };+ // One read withdraws one notice (TS 5865-5869; the daemon's+ // front-most rule): pid reuse can queue an identical key twice+ // and the read belongs to the older handle.+ let withdrawn = std::cell::Cell::new(false);+ agent.remove_queued_messages(|row| {+ !withdrawn.get() && is_queued_completion_row(row, ¬ice) && {+ withdrawn.set(true);+ true+ }+ });+ });+ register_bash_notice_host_handlers(completion, consumed, handlers);+}++/// The bound agent behind the late slot, when the session still lives.+fn bound_agent(slot: &BashNoticeAgentSlot) -> Option<Arc<pa_agent::agent::Agent>> {+ slot.lock()+ .expect("bash notice agent slot lock")+ .as_ref()+ .and_then(Weak::upgrade)+}++/// Whether one queued loop row is the completion notice for this+/// pid+command (the row's details carry both — pids alone are reused).+fn is_queued_completion_row(row: &AgentMessage, notice: &BashConsumedNotice) -> bool {+ let AgentMessage::Custom(custom) = row else {+ return false;+ };+ custom.payload.get("customType").and_then(Value::as_str)+ == Some(ASYNC_BASH_COMPLETION_CUSTOM_TYPE)+ && custom+ .payload+ .pointer("/details/pid")+ .and_then(Value::as_u64)+ == Some(u64::from(notice.pid))+ && custom+ .payload+ .pointer("/details/command")+ .and_then(Value::as_str)+ == Some(notice.command.as_str())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::kernel::shared::{HostHandlerFn, HostRequestPayload};+ use std::sync::atomic::{AtomicUsize, Ordering};++ fn completed_payload(pid: u64, command: &str, exit_code: i64) -> Value {+ serde_json::json!({+ "type": "bash.completed",+ "pid": pid,+ "command": command,+ "exitCode": exit_code,+ })+ }++ async fn dispatch(handler: &HostHandlerFn, data: Value) -> anyhow::Result<Value> {+ handler(HostRequestPayload { data }).await+ }++ fn wired_agent() -> (+ Arc<pa_agent::agent::Agent>,+ BashNoticeAgentSlot,+ Arc<AtomicUsize>,+ HostRequestHandlers,+ ) {+ let agent = Arc::new(pa_agent::agent::Agent::new(+ pa_agent::agent::AgentOptions::default(),+ ));+ let slot: BashNoticeAgentSlot = Arc::new(Mutex::new(Some(Arc::downgrade(&agent))));+ let wakes = Arc::new(AtomicUsize::new(0));+ let wake = {+ let wakes = Arc::clone(&wakes);+ Arc::new(move || {+ wakes.fetch_add(1, Ordering::SeqCst);+ }) as BashNoticeWake+ };+ let mut handlers = HostRequestHandlers::default();+ register_in_process_bash_notice_handlers(&wake, &slot, &mut handlers);+ (agent, slot, wakes, handlers)+ }++ #[tokio::test]+ async fn completed_queues_the_bash_done_row_and_fires_the_wake() {+ let (agent, _slot, wakes, handlers) = wired_agent();+ let handler = handlers+ .get("bash.completed")+ .expect("the completion handler registered")+ .clone();+ let reply = dispatch(&handler, completed_payload(4321, "sleep 1", 7))+ .await+ .expect("the notice is accepted");+ assert_eq!(reply, serde_json::json!({}));+ assert_eq!(+ wakes.load(Ordering::SeqCst),+ 1,+ "the admission fired the wake"+ );+ let queued = agent.remove_queued_messages(|_| true);+ assert_eq!(queued.len(), 1, "one row queued on the agent");+ let AgentMessage::Custom(custom) = &queued[0] else {+ panic!("the queued row is the custom notice: {queued:?}");+ };+ assert_eq!(+ custom.payload.get("customType").and_then(Value::as_str),+ Some(ASYNC_BASH_COMPLETION_CUSTOM_TYPE)+ );+ assert_eq!(+ custom+ .payload+ .pointer("/details/pid")+ .and_then(Value::as_u64),+ Some(4321)+ );+ assert_eq!(+ custom+ .payload+ .pointer("/details/exitCode")+ .and_then(Value::as_i64),+ Some(7)+ );+ assert_eq!(+ custom+ .payload+ .pointer("/details/command")+ .and_then(Value::as_str),+ Some("sleep 1")+ );+ assert!(+ custom+ .payload+ .get("content")+ .and_then(Value::as_str)+ .is_some_and(|text| text.contains("[bash-done pid:4321 exit:7]")),+ "the row carries the notice header: {}",+ custom.payload+ );+ }++ #[tokio::test]+ async fn consumed_withdraws_the_front_most_queued_row() {+ let (agent, _slot, _wakes, handlers) = wired_agent();+ let completed = handlers+ .get("bash.completed")+ .expect("the completion handler registered")+ .clone();+ // Pid reuse queues an identical key twice (the read belongs to+ // the older handle).+ dispatch(&completed, completed_payload(4321, "sleep 1", 0))+ .await+ .expect("the first notice is accepted");+ dispatch(&completed, completed_payload(4321, "sleep 1", 0))+ .await+ .expect("the second notice is accepted");+ assert!(agent.has_queued_messages());++ let consumed = handlers+ .get("bash.consumed")+ .expect("the consumed handler registered")+ .clone();+ dispatch(+ &consumed,+ serde_json::json!({ "type": "bash.consumed", "pid": 4321, "command": "sleep 1" }),+ )+ .await+ .expect("the withdrawal is accepted");+ let remaining = agent.remove_queued_messages(|_| true);+ assert_eq!(+ remaining.len(),+ 1,+ "one read withdrew the front-most row; the second identical row stayed"+ );+ }++ #[test]+ fn completion_validation_matches_the_ts_contract() {+ assert!(validate_completion(&completed_payload(4321, "sleep 1", 0)).is_ok());+ assert!(validate_completion(&completed_payload(0, "sleep 1", 0)).is_err());+ assert!(validate_completion(&completed_payload(4321, "", 0)).is_err());+ assert!(validate_completion(&serde_json::json!({+ "type": "bash.completed",+ "pid": 4321,+ "command": "sleep 1",+ "exitCode": "0",+ }))+ .is_err());+ }+}diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rsindex f8aed98949..a4d3f9f600 100644--- a/crates/pa-core/src/session_engine/engine.rs+++ b/crates/pa-core/src/session_engine/engine.rs@@ -84,6 +84,12 @@ pub struct SessionEngineConfig {/// Fires when the kernel's last live background `bash()` handle/// settles; `None` installs nothing.pub on_background_work_settled: Option<crate::kernel::shared::BackgroundWorkSettledCallback>,+ /// The daemonless bash-completion wake (TS `resumeIfIdle`): with it+ /// the engine registers the `bash.completed`/`bash.consumed`+ /// handlers whose in-process sinks steer the `[bash-done]` row onto+ /// the session's agent and fire the wake. `None` installs nothing —+ /// the daemon keeps its worker-lane sinks via the extra handlers.+ pub bash_notice_wake: Option<super::bash_notices::BashNoticeWake>,/// An externally owned MCP manager: the engine adopts it instead of/// building its own, so ACP-admitted servers reach the prompt's MCP gating.pub mcp_manager: Option<std::sync::Arc<std::sync::Mutex<crate::mcp::McpManager>>>,@@ -314,7 +320,6 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S};let model_context_window = model.context_window;- let python_skills = super::runtime_wiring::kernel_python_skills(&resources.skills);let session_id = wiring.session.lock().await.get_session_id().to_string();let mut handlers = wiring.handlers.clone();if let Some(extra) = config.extra_host_handlers.clone() {@@ -441,6 +446,26 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S)as crate::kernel::provisioner::UnavailableSkillsCallback)};+ // The daemonless bash-completion lane (TS registers the handlers in+ // every mode): the in-process sinks steer the notice row onto this+ // session's agent and fire the embedding's wake once the agent+ // exists (the slot binds below).+ let bash_notice_agent = super::bash_notices::BashNoticeAgentSlot::default();+ if let Some(wake) = config.bash_notice_wake.clone() {+ super::bash_notices::register_in_process_bash_notice_handlers(+ &wake,+ &bash_notice_agent,+ &mut handlers,+ );+ }+ // One model-visible skill list, computed now that the host-handler+ // registry is final (every registration, the refine handlers, and+ // the in-process bash notices are in): a controller-backed bundled+ // skill whose host request never registered drops out (TS+ // `_modelVisibleSkills`).+ let model_visible_skills =+ super::runtime_wiring::model_visible_skills(resources.skills.clone(), &handlers);+ let python_skills = super::runtime_wiring::kernel_python_skills(&model_visible_skills);// TS resolves the serper credential on the host: `!command` key refs// cannot run in-kernel (the websearch skill's auth.json fallback reads// literals and env-var names, not commands). The credential is read@@ -464,7 +489,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Slet provisioner = super::runtime_wiring::kernel_provisioner(session_id,handlers,- python_skills,+ python_skills.clone(),cwd.clone(),&config.agent_dir,kernel_shell_path,@@ -550,7 +575,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S.iter().map(|file| (file.path.display().to_string(), file.content.clone())).collect(),- skills: resources.skills.clone(),+ skills: model_visible_skills.clone(),selected_tools: Some(active_tool_names.iter()@@ -584,7 +609,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S.iter().any(|name| name == PYTHON_TOOL_NAME),include_shell_examples: active_tool_names.iter().any(|name| name == "bash"),- include_refine: resources.skills.iter().any(|skill| {+ include_refine: model_visible_skills.iter().any(|skill| {!skill.disable_model_invocation&& skill.name == crate::prompts::system_prompt::REFINE_SKILL_NAME}),@@ -708,6 +733,11 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S});let agent = Arc::new(agent);+ // The in-process bash-notice sinks bind their agent late: their+ // handlers registered before the agent existed.+ *bash_notice_agent+ .lock()+ .expect("bash notice agent slot lock") = Some(Arc::downgrade(&agent));// TS `_startRlmChildRun`'s spawn anchor: the `rlm.spawn` host handler// names the parent's in-flight turn through this weak seam (the// bridge is built before the agent exists, and a strong edge would@@ -730,6 +760,17 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S.then_some(digest_context.clone()),).await?;+ // Receipts that landed after their cell's tool result persist as+ // custom entries; the build patches them onto the rebuilt tool+ // results (TS `_restoreLateIpythonSentAgentMessages`).+ super::late_sent_messages::restore(&wiring.session, &agent).await;+ // Receipts that record while their cell's row has not landed yet+ // apply as the row lands (TS `_applyLateIpythonSentAgentMessages`):+ // the landing seam runs under the same lock as the state push, so+ // the live row and the persisted one both carry the receipt.+ agent.set_message_end_transform(Some(super::late_sent_messages::landing_transform(+ &wiring.session,+ )));session.set_auto_refine(auto_refine_allowed, auto_refine_gates);session.set_agent_dir(config.agent_dir.clone());// Keep the context descriptor even while disabled, so re-enabling can load it.@@ -771,6 +812,9 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Sstd::sync::Arc::downgrade(&provisioner),));session.set_kernel_state_probe(Some(kernel_state_probe));+ // The admission path's `/skill:` expansion reads the FULL loader+ // inventory (TS `_expandSkillCommand` expands from the loader); the+ // model-visible list only shapes the prompt, pre-import, and counts.session.set_skills(resources.skills.clone());session.set_image_model_router(config.image_model_router.clone());// The semantic-edge handoff: the daemon's child registry and retry@@ -822,9 +866,8 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Slet telemetry = match (config.telemetry.take(), config.rlm_depth.unwrap_or(0)) {(Some(wiring), 0) => {let skill_counts = super::telemetry::SkillCounts {- skill_count: resources.skills.len(),- python_skill_count: super::runtime_wiring::kernel_python_skills(&resources.skills)- .len(),+ skill_count: model_visible_skills.len(),+ python_skill_count: python_skills.len(),};let installed = super::telemetry::install_session_telemetry(&telemetry_agent,@@ -904,6 +947,17 @@ impl SessionEngine {std::sync::Arc::downgrade(&self.provisioner)}+ /// Whether the session's kernel has live background `bash()` work+ /// (TS `isSessionActive`'s `hasBackgroundWork`; the same read the+ /// daemon's liveness probe uses).+ #[must_use]+ pub fn has_background_bash(&self) -> bool {+ self.kernel_provisioner_weak()+ .upgrade()+ .and_then(|provisioner| provisioner.manager())+ .is_some_and(|manager| manager.has_background_work())+ }+/// Expand a `/skill:<name>` submission into its `<skill>` block for/// the accepted-turn row (TS `_expandSkillCommand`; the row the daemon/// emits before admission must match the text the model turn@@ -914,6 +968,28 @@ impl SessionEngine {crate::skills::expand_skill_command(text, &self.skills).0}+ /// Record one late (fire-and-forget) `agent_message.send` receipt (TS+ /// `_recordLateIpythonSentAgentMessage`): the receipt persists as a+ /// custom entry and the newest matching `python_repl` tool result+ /// carries it in its `sentAgentMessages` details.+ ///+ /// # Errors+ ///+ /// Returns the persistence failure so the embedding cannot report successful quiescence.+ pub async fn record_late_sent_agent_message(+ &self,+ tool_call_id: &str,+ message: crate::kernel::shared::KernelSentAgentMessage,+ ) -> anyhow::Result<()> {+ super::late_sent_messages::record(+ self.session.session_handle(),+ self.session.agent(),+ tool_call_id,+ &message,+ )+ .await+ }+/// Withdraw the queued goal-context turns: a minted continuation waiting/// in the embedding's queue never runs behind a paused/cleared/replaced goal.pub fn purge_queued_goal_contexts(&self) {diff --git a/crates/pa-core/src/session_engine/engine/tests.rs b/crates/pa-core/src/session_engine/engine/tests.rsindex 0a2620e78b..a69e042525 100644--- a/crates/pa-core/src/session_engine/engine/tests.rs+++ b/crates/pa-core/src/session_engine/engine/tests.rs@@ -88,6 +88,7 @@ async fn engine_runs_tool_loop_and_persists() {telemetry: None,model_info: None,on_background_work_settled: None,+ bash_notice_wake: None,prewarm_ipython_kernel: None,queued_goal_context_purge: None,})@@ -191,6 +192,7 @@ async fn spawned_child_prompt_stamps_its_depth() {telemetry: None,model_info: None,on_background_work_settled: None,+ bash_notice_wake: None,prewarm_ipython_kernel: None,queued_goal_context_purge: None,})@@ -262,6 +264,7 @@ async fn oauth_creds_unlock_generic_mcp_gating_in_new_sessions() {telemetry: None,model_info: None,on_background_work_settled: None,+ bash_notice_wake: None,prewarm_ipython_kernel: None,queued_goal_context_purge: None,}@@ -333,7 +336,7 @@ async fn oauth_creds_unlock_generic_mcp_gating_in_new_sessions() {}#[tokio::test]-async fn create_session_registers_goal_and_heartbeat_handlers() {+async fn create_session_registers_the_kernel_backed_tools_without_cron_wiring() {let dir = tempfile::TempDir::new().unwrap();let registration =pa_ai::faux::register_faux_provider(pa_ai::faux::RegisterFauxProviderOptions {@@ -450,6 +453,7 @@ async fn create_session_appends_missing_resume_settings_rows() {telemetry: None,model_info: None,on_background_work_settled: None,+ bash_notice_wake: None,prewarm_ipython_kernel: None,queued_goal_context_purge: None,})@@ -472,3 +476,427 @@ async fn create_session_appends_missing_resume_settings_rows() {"entries: {entries:?}");}++// ---------------------------------------------------------------------------+// The model-visible surface follows the wired host handlers (#8) and the+// late agent-message receipts restore onto rebuilt tool results (#10).+// ---------------------------------------------------------------------------++use crate::session_engine::runtime_wiring::KernelCronWiring;++/// Host handlers for the wire names the skill packages send: named+/// no-ops are all the registry filter keys on.+fn handlers(names: &[&str]) -> crate::kernel::shared::HostRequestHandlers {+ let mut handlers = crate::kernel::shared::HostRequestHandlers::default();+ for name in names {+ handlers.register(+ *name,+ crate::kernel::shared::host_handler(|_payload| {+ Box::pin(async { Ok(serde_json::Value::Null) })+ }),+ );+ }+ handlers+}++fn cron_wiring(dir: &std::path::Path) -> KernelCronWiring {+ KernelCronWiring {+ store: std::sync::Arc::new(crate::cron::store::AgentCronJobStore::new(+ dir.join("jobs.json"),+ )),+ binding: None,+ mutation_hook: None,+ }+}++async fn engine_over(+ extra_host_handlers: Option<crate::kernel::shared::HostRequestHandlers>,+ cron_store: Option<KernelCronWiring>,+ daemonless: bool,+) -> (SessionEngine, tempfile::TempDir) {+ let model = pa_agent::types::Model {+ id: "m".into(),+ name: "m".into(),+ api: "test".into(),+ provider: "test".into(),+ base_url: "http://localhost".into(),+ reasoning: false,+ cost: pa_agent::types::UsageCost::default(),+ context_window: 1_000,+ max_tokens: 100,+ max_tokens_explicit: false,+ };+ let provider = Arc::new(ScriptedProvider::new(model.clone()));+ let tmp = tempfile::tempdir().unwrap();+ let cwd = tmp.path().join("project");+ std::fs::create_dir_all(&cwd).unwrap();+ let engine = create_session(SessionEngineConfig {+ cron_store,+ cwd: cwd.clone(),+ agent_dir: tmp.path().join("agent"),+ model: Some(model),+ stream_fn: Some(provider.stream_fn()),+ extra_host_handlers,+ daemonless,+ ..Default::default()+ })+ .await+ .unwrap();+ (engine, tmp)+}++fn prompt_lists_skill(engine: &SessionEngine, name: &str) -> bool {+ engine+ .system_prompt+ .contains(&format!("<name>{name}</name>"))+}++fn kernel_skill_imports(engine: &SessionEngine) -> Vec<String> {+ engine+ .provisioner+ .python_skills()+ .iter()+ .map(|skill| skill.import_name.clone())+ .collect()+}++/// One model-visible surface per embedding, keyed on the wired host+/// handlers (#8): the prompt and the kernel pre-import list only the+/// skills whose host requests registered. Print wires the messaging+/// handlers, RPC none, the daemon shape all three (its cron wiring also+/// serves the heartbeat requests).+#[tokio::test]+async fn model_visible_skills_follow_the_embedding_wiring() {+ let all = ["agent-message", "agent-observe", "rlm-heartbeat"];+ let imports_of = [+ ("agent-message", "agent_message"),+ ("agent-observe", "agent_observe"),+ ("rlm-heartbeat", "rlm_heartbeat"),+ ];+ let cron_dir = tempfile::tempdir().unwrap();+ let daemon_cron = Some(cron_wiring(cron_dir.path()));+ let cases = [+ (+ "print",+ &["agent_message.send"][..],+ None,+ true,+ &["agent-message"][..],+ ),+ ("rpc", &[][..], None, true, &[][..]),+ (+ "daemon",+ &[+ "agent_message.send",+ "agent_observe.list",+ "rlm_heartbeat.create",+ ][..],+ daemon_cron.clone(),+ false,+ &["agent-message", "agent-observe", "rlm-heartbeat"][..],+ ),+ ];+ for (label, wired, cron, daemonless, visible) in cases {+ let (engine, _tmp) = engine_over(Some(handlers(wired)), cron, daemonless).await;+ // The bundled fixtures loaded at all.+ assert!(prompt_lists_skill(&engine, "compact"), "{label}");+ for skill in all {+ assert_eq!(+ prompt_lists_skill(&engine, skill),+ visible.contains(&skill),+ "{label}: {skill}"+ );+ }+ let imports = kernel_skill_imports(&engine);+ for (skill, import) in imports_of {+ assert_eq!(+ imports.iter().any(|name| name == import),+ visible.contains(&skill),+ "{label}: {import}"+ );+ }+ }+}++/// A receipt that landed after its cell's tool result persists as a+/// custom entry; a rebuilt engine patches it onto the tool result (#10).+#[tokio::test]+async fn engine_build_restores_late_sent_agent_message_receipts() {+ let tmp = tempfile::tempdir().unwrap();+ let cwd = tmp.path().join("project");+ std::fs::create_dir_all(&cwd).unwrap();+ let sessions = tmp.path().join("sessions");+ let mut manager = SessionManager::persisted(&cwd, &sessions);+ // The durable-append rule delays non-assistant rows until the first+ // assistant entry, so the history needs one to reach the file.+ manager+ .append_message(pa_types::session::AgentMessage::Assistant(+ serde_json::from_value(serde_json::json!({+ "role": "assistant",+ "content": [{ "type": "text", "text": "history reply" }],+ "api": "test",+ "provider": "test",+ "model": "m",+ "usage": {+ "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0,+ "totalTokens": 0,+ "cost": { "input": 0.0, "output": 0.0, "cacheRead": 0.0, "cacheWrite": 0.0, "total": 0.0 }+ },+ "stopReason": "stop",+ "timestamp": 1,+ }))+ .unwrap(),+ ))+ .unwrap();+ manager+ .append_message(pa_types::session::AgentMessage::ToolResult(+ pa_types::ai::ToolResultMessage {+ tool_call_id: "call-1".to_string(),+ tool_name: "python_repl".to_string(),+ content: Vec::new(),+ details: Some(serde_json::json!({ "status": "ok" })),+ is_error: false,+ timestamp: 1,+ rest: pa_types::JsonMap::new(),+ },+ ))+ .unwrap();+ manager+ .append_custom_entry(+ "ipython_sent_agent_message",+ Some(serde_json::json!({+ "toolCallId": "call-1",+ "message": {+ "id": "agentmsg_1",+ "message": "Ping.",+ "deliveryStatus": "delivered",+ "receiverRole": "parent",+ "target": {+ "activeSessionId": "a1",+ "sessionId": "s1",+ "sessionName": "Worker",+ },+ },+ })),+ )+ .unwrap();+ let session_file = manager+ .get_session_file()+ .expect("the persisted session file")+ .to_path_buf();+ let manager = SessionManager::open(&cwd, &sessions, &session_file);++ let model = pa_agent::types::Model {+ id: "m".into(),+ name: "m".into(),+ api: "test".into(),+ provider: "test".into(),+ base_url: "http://localhost".into(),+ reasoning: false,+ cost: pa_agent::types::UsageCost::default(),+ context_window: 1_000,+ max_tokens: 100,+ max_tokens_explicit: false,+ };+ let provider = Arc::new(ScriptedProvider::new(model.clone()));+ let engine = create_session(SessionEngineConfig {+ cwd: cwd.clone(),+ agent_dir: tmp.path().join("agent"),+ model: Some(model),+ stream_fn: Some(provider.stream_fn()),+ session_manager: Some(manager),+ daemonless: true,+ ..Default::default()+ })+ .await+ .unwrap();++ let state = engine.session.agent().state().await;+ let result = state+ .messages+ .iter()+ .find_map(|row| match row {+ pa_agent::types::AgentMessage::Standard(pa_agent::types::Message::ToolResult(+ result,+ )) if result.tool_call_id == "call-1" => Some(result.clone()),+ _ => None,+ })+ .expect("the rebuilt tool result");+ let details = result.details.as_ref().expect("the tool result details");+ assert_eq!(details["status"], "ok");+ let sent = details["sentAgentMessages"]+ .as_array()+ .expect("the restored receipt");+ assert_eq!(sent.len(), 1);+ assert_eq!(sent[0]["id"], "agentmsg_1");+ assert_eq!(sent[0]["target"]["sessionName"], "Worker");+}++/// The late-receipt race (#10): a receipt recorded while its cell's+/// tool-result row has not landed yet (the kernel callback fires before+/// `execute_ipython` returns) applies to the row as it lands, so the+/// live state row and the persisted one both carry it.+#[tokio::test]+async fn late_receipts_recorded_before_the_row_lands_apply_on_landing() {+ let model = pa_agent::types::Model {+ id: "m".into(),+ name: "m".into(),+ api: "test".into(),+ provider: "test".into(),+ base_url: "http://localhost".into(),+ reasoning: false,+ cost: pa_agent::types::UsageCost::default(),+ context_window: 1_000,+ max_tokens: 100,+ max_tokens_explicit: false,+ };+ let provider = Arc::new(ScriptedProvider::new(model.clone()));+ provider.push_tool_call_turn(+ None,+ vec![("call-1", PYTHON_TOOL_NAME, serde_json::json!({}))],+ );+ provider.push_text_turn("all done");+ let tmp = tempfile::tempdir().unwrap();+ let cwd = tmp.path().join("project");+ std::fs::create_dir_all(&cwd).unwrap();+ // The fake python tool records the receipt through the engine's own+ // seam (like the print sink does); the engine slot binds once the+ // build returns, strictly before the first run executes the tool.+ let engine_slot: Arc<std::sync::Mutex<Option<std::sync::Weak<SessionEngine>>>> = Arc::default();+ let slot = Arc::clone(&engine_slot);+ let receipt = crate::kernel::shared::KernelSentAgentMessage {+ id: "agentmsg_1".to_string(),+ message: "Ping.".to_string(),+ delivery_status: crate::kernel::shared::SentDeliveryStatus::Delivered,+ receiver_role: Some(crate::kernel::shared::ReceiverRole::Parent),+ target: crate::kernel::shared::SentAgentMessageTarget {+ active_session_id: "a1".to_string(),+ session_id: "s1".to_string(),+ session_name: Some("Worker".to_string()),+ },+ };+ let recording_tool = ToolDefinition {+ name: PYTHON_TOOL_NAME.to_string(),+ label: "Python".to_string(),+ description: "Runs a python cell.".to_string(),+ prompt_snippet: String::new(),+ parameters: serde_json::json!({ "type": "object", "properties": {} }),+ execution_mode: Some(ExecutionMode::Sequential),+ prepare_arguments: None,+ execute: Arc::new(move |tool_call_id, _params, _signal, _on_update| {+ let slot = Arc::clone(&slot);+ let receipt = receipt.clone();+ let tool_call_id = tool_call_id.to_string();+ Box::pin(async move {+ let engine = slot+ .lock()+ .unwrap()+ .as_ref()+ .and_then(std::sync::Weak::upgrade)+ .expect("the engine binds before the first run");+ engine+ .record_late_sent_agent_message(&tool_call_id, receipt)+ .await?;+ Ok(ToolExecutionResult::text("cell done"))+ })+ }),+ };+ let engine = create_session(SessionEngineConfig {+ on_late_sent_agent_message: None,+ semantic_edges: None,+ cron_store: None,+ queued_steering_probe: None,+ should_stop_after_turn: None,+ image_model_router: None,+ steering_mode: None,+ follow_up_mode: None,+ cwd: cwd.clone(),+ agent_dir: tmp.path().join("agent"),+ mcp_manager: None,+ model: Some(model),+ thinking_level: None,+ stream_fn: Some(provider.stream_fn()),+ tools: vec![bridge_tool(recording_tool)],+ custom_system_prompt: None,+ prompt_guidelines: vec![],+ generic_mcp_servers: vec![],+ allow_recursion: None,+ session_manager: None,+ extra_host_handlers: None,+ conversation_log_path: None,+ additional_skill_paths: vec![],+ additional_prompt_paths: vec![],+ extra_builtin_skill_overrides: vec![],+ rlm_subagent_host: None,+ rlm_usage_store: None,+ progress_note_emit: None,+ rlm_depth: None,+ daemonless: true,+ telemetry: None,+ model_info: None,+ on_background_work_settled: None,+ bash_notice_wake: None,+ prewarm_ipython_kernel: None,+ queued_goal_context_purge: None,+ })+ .await+ .unwrap();+ let engine = Arc::new(engine);+ *engine_slot.lock().unwrap() = Some(Arc::downgrade(&engine));++ let outcome = engine+ .prompt("run the cell", PromptOptions::default())+ .await+ .unwrap();+ assert_eq!(outcome, PromptOutcome::Prompt);+ engine.session.agent().wait_for_idle().await;++ // The live state row carries the receipt.+ let state = engine.session.agent().state().await;+ let result = state+ .messages+ .iter()+ .find_map(|message| match message {+ pa_agent::types::AgentMessage::Standard(pa_agent::types::Message::ToolResult(+ result,+ )) if result.tool_call_id == "call-1" => Some(result.clone()),+ _ => None,+ })+ .expect("the landed tool result");+ let details = result.details.as_ref().expect("the receipt rides the row");+ assert_eq!(+ details["sentAgentMessages"][0]["id"], "agentmsg_1",+ "the live state row carries the receipt"+ );++ // So does the persisted message row, and the receipt itself persists+ // as a custom entry.+ let entries = engine.session.entries().await;+ let persisted = entries+ .iter()+ .find_map(|entry| match entry {+ pa_types::session::FileEntry::Message {+ message: pa_types::session::AgentMessage::ToolResult(result),+ ..+ } if result.tool_call_id == "call-1" => Some(result.clone()),+ _ => None,+ })+ .expect("the persisted tool result");+ let details = persisted+ .details+ .as_ref()+ .expect("the persisted row's details");+ assert_eq!(+ details["sentAgentMessages"][0]["id"], "agentmsg_1",+ "the persisted row carries the receipt"+ );+ assert!(+ entries.iter().any(|entry| matches!(+ entry,+ pa_types::session::FileEntry::Custom { payload, .. }+ if payload.custom_type+ == crate::session_engine::late_sent_messages::IPYTHON_SENT_AGENT_MESSAGE_CUSTOM_TYPE+ )),+ "the receipt persists as a custom entry"+ );+}diff --git a/crates/pa-core/src/session_engine/late_sent_messages.rs b/crates/pa-core/src/session_engine/late_sent_messages.rsnew file mode 100644index 0000000000..24e40cbce6--- /dev/null+++ b/crates/pa-core/src/session_engine/late_sent_messages.rs@@ -0,0 +1,450 @@+//! Late (fire-and-forget) `agent_message.send` receipts: the persisted+//! custom entry plus the `python_repl` tool-result patch (TS+//! `IPYTHON_SENT_AGENT_MESSAGE_CUSTOM_ENTRY` handling in agent-session.ts).++use std::sync::Arc;++use pa_agent::agent::Agent;+use pa_agent::types::{AgentMessage, Message};+use pa_types::session::FileEntry;+use serde_json::{json, Map, Value};+use tokio::sync::Mutex;++use crate::kernel::shared::{parse_sent_agent_message, KernelSentAgentMessage};+use crate::session::manager::SessionManager;+use crate::tools::ipython::sent_agent_message_json;++/// The persisted row for one receipt that landed after its cell's tool+/// result (TS `IPYTHON_SENT_AGENT_MESSAGE_CUSTOM_ENTRY`).+pub const IPYTHON_SENT_AGENT_MESSAGE_CUSTOM_TYPE: &str = "ipython_sent_agent_message";++/// One persisted receipt parsed off the session branch.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PersistedSentAgentMessage {+ pub tool_call_id: String,+ pub message: KernelSentAgentMessage,+}++/// The custom-entry payload: `{ toolCallId, message }` with the TS wire+/// shape for the message.+#[must_use]+pub fn sent_agent_message_entry(tool_call_id: &str, message: &KernelSentAgentMessage) -> Value {+ json!({+ "toolCallId": tool_call_id,+ "message": sent_agent_message_json(message),+ })+}++/// Parse one persisted receipt payload; `None` on a malformed record.+#[must_use]+pub fn parse_persisted_sent_agent_message(payload: &Value) -> Option<PersistedSentAgentMessage> {+ let tool_call_id = payload.get("toolCallId")?.as_str()?;+ let message = parse_sent_agent_message(payload.get("message")?)?;+ Some(PersistedSentAgentMessage {+ tool_call_id: tool_call_id.to_string(),+ message,+ })+}++/// The receipts on session entries, oldest first.+#[must_use]+pub fn scan_sent_agent_message_entries<'a>(+ entries: impl IntoIterator<Item = &'a FileEntry>,+) -> Vec<PersistedSentAgentMessage> {+ entries+ .into_iter()+ .filter_map(|entry| match entry {+ FileEntry::Custom { payload, .. }+ if payload.custom_type == IPYTHON_SENT_AGENT_MESSAGE_CUSTOM_TYPE =>+ {+ payload+ .data+ .as_ref()+ .and_then(parse_persisted_sent_agent_message)+ }+ _ => None,+ })+ .collect()+}++/// Patch one receipt onto a `python_repl` tool result's `sentAgentMessages`+/// details (TS `appendSentAgentMessageToToolResult`): `true` when the row+/// is the matching tool result, whether or not the receipt is new.+pub(crate) fn append_to_tool_result(+ row: &mut AgentMessage,+ tool_call_id: &str,+ sent: &KernelSentAgentMessage,+) -> bool {+ let AgentMessage::Standard(Message::ToolResult(result)) = row else {+ return false;+ };+ // The python tool's aliases all count (an `ipython`/`python`-named+ // call, and TS-era files, store the name the model called): the+ // receipt patches the row whatever the alias was.+ if result.tool_call_id != tool_call_id || !pa_types::ai::is_python_tool_name(&result.tool_name)+ {+ return false;+ }+ let details = result.details.take().unwrap_or(Value::Null);+ let mut map = match details {+ Value::Object(map) => map,+ _ => Map::new(),+ };+ let mut current = match map.remove("sentAgentMessages") {+ Some(Value::Array(rows)) => rows,+ _ => Vec::new(),+ };+ let already = current+ .iter()+ .any(|entry| entry.get("id").and_then(Value::as_str) == Some(sent.id.as_str()));+ if !already {+ current.push(sent_agent_message_json(sent));+ }+ map.insert("sentAgentMessages".to_string(), Value::Array(current));+ result.details = Some(Value::Object(map));+ true+}++/// Record one late receipt (TS `_recordLateIpythonSentAgentMessage`): the+/// custom entry persists it (once per message id) and the newest matching+/// `python_repl` tool result in agent state carries it.+pub(crate) async fn record(+ session: &Arc<Mutex<SessionManager>>,+ agent: &Arc<Agent>,+ tool_call_id: &str,+ message: &KernelSentAgentMessage,+) -> anyhow::Result<()> {+ let persistence = {+ let mut session = session.lock().await;+ let already = session.late_sent_agent_messages().iter().any(|persisted| {+ persisted.tool_call_id == tool_call_id && persisted.message.id == message.id+ });+ if already {+ Ok(())+ } else {+ session+ .append_custom_entry(+ IPYTHON_SENT_AGENT_MESSAGE_CUSTOM_TYPE,+ Some(sent_agent_message_entry(tool_call_id, message)),+ )+ .map(|_| ())+ .map_err(|error| {+ anyhow::anyhow!("late agent-message receipt not persisted: {error}")+ })+ }+ };+ agent+ .mutate_messages(|rows| {+ for row in rows.iter_mut().rev() {+ if append_to_tool_result(row, tool_call_id, message) {+ break;+ }+ }+ })+ .await;+ persistence+}++/// Patch every persisted receipt onto the rebuilt tool results (TS+/// `_restoreLateIpythonSentAgentMessages`): the engine build's+/// restoration pass over the session's loaded branch.+pub(crate) async fn restore(session: &Arc<Mutex<SessionManager>>, agent: &Arc<Agent>) {+ let persisted = session.lock().await.late_sent_agent_messages();+ if persisted.is_empty() {+ return;+ }+ agent+ .mutate_messages(|rows| {+ for entry in &persisted {+ for row in rows.iter_mut().rev() {+ if append_to_tool_result(row, &entry.tool_call_id, &entry.message) {+ break;+ }+ }+ }+ })+ .await;+}++/// The landing arm (TS `_applyLateIpythonSentAgentMessages`): one row+/// landing through the agent's `MessageEnd` seam picks up every receipt+/// already persisted for its call. The session's custom entries are the+/// single parked-receipt source, so no second map exists here.+pub(crate) fn landing_transform(+ session: &Arc<Mutex<SessionManager>>,+) -> pa_agent::agent::MessageEndTransformFn {+ let session = Arc::clone(session);+ Arc::new(move |message| {+ let session = Arc::clone(&session);+ Box::pin(async move {+ // The cheap filter runs before any lock: only a python tool+ // result can carry receipts. `append_to_tool_result` owns the+ // call-id match.+ if !matches!(+ &message,+ AgentMessage::Standard(Message::ToolResult(result))+ if pa_types::ai::is_python_tool_name(&result.tool_name)+ ) {+ return message;+ }+ let mut message = message;+ for entry in session.lock().await.late_sent_agent_messages() {+ append_to_tool_result(&mut message, &entry.tool_call_id, &entry.message);+ }+ message+ })+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use pa_agent::agent::{Agent, AgentInitialState, AgentOptions};+ use pa_agent::types::{Message, ThinkingLevel, ToolResultMessage};+ use pa_types::ai::PYTHON_TOOL_NAME;++ fn receipt(id: &str) -> KernelSentAgentMessage {+ KernelSentAgentMessage {+ id: id.to_string(),+ message: "Ping.".to_string(),+ delivery_status: crate::kernel::shared::SentDeliveryStatus::Delivered,+ receiver_role: Some(crate::kernel::shared::ReceiverRole::Parent),+ target: crate::kernel::shared::SentAgentMessageTarget {+ active_session_id: "a1".to_string(),+ session_id: "s1".to_string(),+ session_name: Some("Worker".to_string()),+ },+ }+ }++ fn python_tool_result(tool_call_id: &str, details: Option<Value>) -> AgentMessage {+ AgentMessage::Standard(Message::ToolResult(ToolResultMessage {+ tool_call_id: tool_call_id.to_string(),+ tool_name: PYTHON_TOOL_NAME.to_string(),+ content: Vec::new(),+ details,+ is_error: false,+ timestamp: 0,+ }))+ }++ fn agent_with(messages: Vec<AgentMessage>) -> Arc<Agent> {+ Arc::new(Agent::new(AgentOptions {+ initial_state: AgentInitialState {+ system_prompt: Some("s".to_string()),+ model: Some(pa_agent::types::Model {+ id: "m".into(),+ name: "m".into(),+ api: "test".into(),+ provider: "test".into(),+ base_url: "http://localhost".into(),+ reasoning: false,+ cost: pa_agent::types::UsageCost::default(),+ context_window: 1_000,+ max_tokens: 100,+ max_tokens_explicit: false,+ }),+ thinking_level: Some(ThinkingLevel::Off),+ tools: None,+ messages: Some(messages),+ },+ stream_fn: None,+ ..Default::default()+ }))+ }++ fn tool_result_details(row: &AgentMessage) -> Option<&Value> {+ match row {+ AgentMessage::Standard(Message::ToolResult(result)) => result.details.as_ref(),+ _ => None,+ }+ }++ #[test]+ fn append_to_tool_result_patches_only_the_matching_python_repl_row() {+ let mut matching = python_tool_result("call-1", Some(json!({ "status": "ok" })));+ let sent = receipt("agentmsg_1");++ assert!(append_to_tool_result(&mut matching, "call-1", &sent));+ let details = tool_result_details(&matching).expect("details");+ assert_eq!(details["status"], "ok");+ let rows = details["sentAgentMessages"].as_array().expect("receipts");+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0]["id"], "agentmsg_1");+ assert_eq!(rows[0]["target"]["sessionName"], "Worker");++ // The same receipt id does not double-append.+ assert!(append_to_tool_result(&mut matching, "call-1", &sent));+ assert_eq!(+ tool_result_details(&matching).expect("details")["sentAgentMessages"]+ .as_array()+ .expect("receipts")+ .len(),+ 1+ );++ // A row without details gains them; a foreign tool id and a+ // non-python_repl result stay untouched.+ let mut bare = python_tool_result("call-2", None);+ assert!(append_to_tool_result(&mut bare, "call-2", &sent));+ assert_eq!(+ tool_result_details(&bare).expect("details")["sentAgentMessages"]+ .as_array()+ .expect("receipts")+ .len(),+ 1+ );+ assert!(!append_to_tool_result(+ &mut bare,+ "call-9",+ &receipt("agentmsg_2")+ ));+ let mut foreign_tool = AgentMessage::Standard(Message::ToolResult(ToolResultMessage {+ tool_call_id: "call-3".to_string(),+ tool_name: "echo".to_string(),+ content: Vec::new(),+ details: None,+ is_error: false,+ timestamp: 0,+ }));+ assert!(!append_to_tool_result(&mut foreign_tool, "call-3", &sent));+ assert!(tool_result_details(&foreign_tool).is_none());++ // The python tool's aliases count too (an `ipython`-named call,+ // the name TS-era files store).+ let mut aliased = AgentMessage::Standard(Message::ToolResult(ToolResultMessage {+ tool_call_id: "call-4".to_string(),+ tool_name: "ipython".to_string(),+ content: Vec::new(),+ details: None,+ is_error: false,+ timestamp: 0,+ }));+ assert!(append_to_tool_result(&mut aliased, "call-4", &sent));+ assert_eq!(+ tool_result_details(&aliased).expect("details")["sentAgentMessages"]+ .as_array()+ .expect("receipts")+ .len(),+ 1+ );+ }++ #[tokio::test]+ async fn record_persists_one_entry_per_message_and_patches_agent_state() {+ let dir = tempfile::tempdir().unwrap();+ let session = SessionManager::persisted(dir.path(), &dir.path().join("sessions"));+ let session = Arc::new(Mutex::new(session));+ let agent = agent_with(vec![python_tool_result("call-1", None)]);++ record(&session, &agent, "call-1", &receipt("agentmsg_1"))+ .await+ .unwrap();+ record(&session, &agent, "call-1", &receipt("agentmsg_1"))+ .await+ .unwrap();+ record(&session, &agent, "call-1", &receipt("agentmsg_2"))+ .await+ .unwrap();++ let entries = {+ let session = session.lock().await;+ scan_sent_agent_message_entries(session.retained_entries())+ };+ assert_eq!(entries.len(), 2, "one custom entry per message id");+ assert_eq!(entries[0].message.id, "agentmsg_1");+ assert_eq!(entries[1].message.id, "agentmsg_2");++ let state = agent.state().await;+ let details = state+ .messages+ .iter()+ .find_map(tool_result_details)+ .expect("patched details");+ assert_eq!(details["sentAgentMessages"].as_array().unwrap().len(), 2);+ }++ #[tokio::test]+ async fn persistence_failure_is_reported_before_or_after_the_result_lands() {+ for landed in [false, true] {+ let dir = tempfile::tempdir().unwrap();+ let mut session = SessionManager::persisted(dir.path(), &dir.path().join("sessions"));+ session+ .append_message(pa_types::session::AgentMessage::Assistant(+ pa_types::ai::AssistantMessage {+ content: vec![],+ api: "openai-completions".to_string(),+ provider: "fixture".to_string(),+ model: "fixture".to_string(),+ response_model: None,+ response_id: None,+ diagnostics: None,+ usage: pa_types::ai::Usage::default(),+ stop_reason: pa_types::ai::StopReason::Stop,+ stop_reason_raw: None,+ error_message: None,+ timestamp: 0,+ rest: serde_json::Map::default(),+ },+ ))+ .unwrap();+ let file = session.get_session_file().unwrap().to_path_buf();+ std::fs::remove_file(&file).unwrap();+ std::fs::create_dir(&file).unwrap(); // deterministic append failure, even as root+ let session = Arc::new(Mutex::new(session));+ let agent = agent_with(if landed {+ vec![python_tool_result("call-1", None)]+ } else {+ vec![]+ });+ let error = record(&session, &agent, "call-1", &receipt("agentmsg_1"))+ .await+ .expect_err("a failed durable append cannot acknowledge recording");+ assert!(error.to_string().contains("not persisted"));+ assert!(session.lock().await.late_sent_agent_messages().is_empty());+ if landed {+ let state = agent.state().await;+ let details = state.messages.iter().find_map(tool_result_details).unwrap();+ assert_eq!(details["sentAgentMessages"][0]["id"], "agentmsg_1");+ }+ }+ }++ #[tokio::test]+ async fn restore_patches_the_rebuilt_tool_results() {+ let dir = tempfile::tempdir().unwrap();+ let session = SessionManager::persisted(dir.path(), &dir.path().join("sessions"));+ let session = Arc::new(Mutex::new(session));+ record(+ &session,+ &agent_with(Vec::new()),+ "call-1",+ &receipt("agentmsg_1"),+ )+ .await+ .unwrap();+ record(+ &session,+ &agent_with(Vec::new()),+ "call-1",+ &receipt("agentmsg_2"),+ )+ .await+ .unwrap();++ // The rebuilt engine's rows: the tool result alone, without the+ // receipts (they landed after the cell settled).+ let agent = agent_with(vec![python_tool_result("call-1", None)]);+ restore(&session, &agent).await;+ let state = agent.state().await;+ let details = state+ .messages+ .iter()+ .find_map(tool_result_details)+ .expect("patched details");+ let rows = details["sentAgentMessages"].as_array().expect("receipts");+ assert_eq!(rows.len(), 2);+ assert_eq!(rows[0]["id"], "agentmsg_1");+ assert_eq!(rows[1]["id"], "agentmsg_2");+ }+}diff --git a/crates/pa-core/src/session_engine/mod.rs b/crates/pa-core/src/session_engine/mod.rsindex b3772c47d1..8e7485f554 100644--- a/crates/pa-core/src/session_engine/mod.rs+++ b/crates/pa-core/src/session_engine/mod.rs@@ -6,6 +6,7 @@ pub mod agent_messaging;pub mod auto_refine_trigger;pub mod auto_retry;pub mod auxiliary_model;+pub mod bash_notices;pub mod branch_summarization;pub mod compact_session;pub mod compaction;@@ -22,6 +23,7 @@ pub mod headless;pub mod host_requests;pub mod image_model_routing;pub mod ipython_state;+pub mod late_sent_messages;pub mod messages;pub mod provider_adapter;pub mod provider_failover;diff --git a/crates/pa-core/src/session_engine/runtime.rs b/crates/pa-core/src/session_engine/runtime.rsindex 0f9e878ff5..d20fec192c 100644--- a/crates/pa-core/src/session_engine/runtime.rs+++ b/crates/pa-core/src/session_engine/runtime.rs@@ -27,7 +27,7 @@ pub type QueuedGoalContextPurge = Arc<dyn Fn() + Send + Sync>;/// Session-scoped runtime state the kernel bridge reaches.pub struct SessionRuntime {goal_driver: Arc<Mutex<GoalDriver>>,- cron_store: Arc<AgentCronJobStore>,+ cron_store: Option<Arc<AgentCronJobStore>>,active_session_id: String,binding: SessionBinding,/// Invoked after a kernel `goal.complete` settles the goal; `None`@@ -39,10 +39,14 @@ pub struct SessionRuntime {}impl SessionRuntime {- /// Build a runtime around a cron store, rehydrating any persisted goal.+ /// Build a runtime around the embedding's cron store, rehydrating any+ /// persisted goal. `None` is an embedding with no scheduler: kernel+ /// `rlm_heartbeat.*` requests stay unregistered (TS gates on the+ /// heartbeat controller).+ #[must_use]pub fn new(session: &SessionManager,- cron_store: Arc<AgentCronJobStore>,+ cron_store: Option<Arc<AgentCronJobStore>>,active_session_id: String,binding: SessionBinding,) -> Self {@@ -72,12 +76,15 @@ impl SessionRuntime {&self.goal_driver}+ /// The embedding's cron store; `None` when no scheduler is wired.#[must_use]- pub fn cron_store(&self) -> &Arc<AgentCronJobStore> {- &self.cron_store+ pub fn cron_store(&self) -> Option<&Arc<AgentCronJobStore>> {+ self.cron_store.as_ref()}- /// Register the `goal.*` and `rlm_heartbeat.*` handlers onto a handler map.+ /// Register the `goal.*` and `rlm_heartbeat.*` handlers onto a handler+ /// map; the heartbeat handlers register only on a runtime that serves+ /// them (embeddings with cron wiring).pub fn register_host_handlers(&self,session: Arc<Mutex<SessionManager>>,@@ -121,7 +128,10 @@ impl SessionRuntime {}),);}- let store = self.cron_store.clone();+ // Scheduler-less embeddings expose goals but cannot create heartbeat jobs.+ let Some(store) = self.cron_store.clone() else {+ return;+ };let active_session_id = self.active_session_id.clone();let binding_session_id = self.binding.session_id.clone();let binding_session_file = self.binding.session_file.clone();@@ -206,7 +216,9 @@ mod tests {let dir = tempfile::TempDir::new().unwrap();let mut runtime = SessionRuntime::new(&*session.lock().await,- Arc::new(AgentCronJobStore::new(dir.path().join("jobs.json"))),+ Some(Arc::new(AgentCronJobStore::new(+ dir.path().join("jobs.json"),+ ))),"live-1".to_string(),SessionBinding {session_id: "session-1".to_string(),@@ -248,7 +260,9 @@ mod tests {let dir = tempfile::TempDir::new().unwrap();let runtime = SessionRuntime::new(&*session.lock().await,- Arc::new(AgentCronJobStore::new(dir.path().join("jobs.json"))),+ Some(Arc::new(AgentCronJobStore::new(+ dir.path().join("jobs.json"),+ ))),"live-1".to_string(),SessionBinding {session_id: "session-1".to_string(),@@ -302,7 +316,9 @@ mod tests {let dir = tempfile::TempDir::new().unwrap();let runtime = SessionRuntime::new(&*session.lock().await,- Arc::new(AgentCronJobStore::new(dir.path().join("jobs.json"))),+ Some(Arc::new(AgentCronJobStore::new(+ dir.path().join("jobs.json"),+ ))),"live-1".to_string(),SessionBinding {session_id: "session-1".to_string(),@@ -334,7 +350,10 @@ mod tests {.await.unwrap();assert_eq!(response["heartbeat"]["status"], "paused");- let jobs = runtime.cron_store().list_rlm_heartbeats("live-1", true);+ let jobs = runtime+ .cron_store()+ .expect("the wired store")+ .list_rlm_heartbeats("live-1", true);assert_eq!(jobs.len(), 1);}@@ -345,7 +364,9 @@ mod tests {let dir = tempfile::TempDir::new().unwrap();let mut runtime = SessionRuntime::new(&*session.lock().await,- Arc::new(AgentCronJobStore::new(dir.path().join("jobs.json"))),+ Some(Arc::new(AgentCronJobStore::new(+ dir.path().join("jobs.json"),+ ))),"live-1".to_string(),SessionBinding {session_id: "session-1".to_string(),diff --git a/crates/pa-core/src/session_engine/runtime_wiring.rs b/crates/pa-core/src/session_engine/runtime_wiring.rsindex 8215905fa8..b5c2ac0b14 100644--- a/crates/pa-core/src/session_engine/runtime_wiring.rs+++ b/crates/pa-core/src/session_engine/runtime_wiring.rs@@ -9,7 +9,6 @@ use std::pin::Pin;use std::sync::Arc;use super::runtime::QueuedGoalContextPurge;-use crate::cron::store::AgentCronJobStore;use crate::kernel::bootstrap::KernelPythonSkill;use crate::kernel::provisioner::{IpythonKernelProvisioner as KernelProvisioner, IpythonKernelProvisionerOptions,@@ -93,8 +92,9 @@ pub struct SessionKernelWiring {pub rlm_usage: Arc<super::rlm_usage::RlmChildUsageAttributions>,}-/// Build the session runtime and register the `goal.*`, `rlm_heartbeat.*`, and `rlm.*`-/// host handlers; `goal_complete_purge` is the embedding's queued-goal-context purge.+/// Build the session runtime and register the `goal.*`, `rlm.*`, and —+/// only when `cron_store` wiring exists — the `rlm_heartbeat.*` host+/// handlers; `goal_complete_purge` is the embedding's queued-goal-context purge.#[must_use]pub fn wire_session_runtime(session: SessionManager,@@ -134,16 +134,14 @@ pub fn wire_session_runtime(),None => fallback_binding(),};- // An embedding-owned store replaces the engine-private one, so- // kernel `rlm_heartbeat.*` writes reach the daemon catalog; the- // private file store remains the embedded/standalone default.+ // An embedding-owned store, so kernel `rlm_heartbeat.*` writes reach+ // the daemon catalog. Kernel heartbeat requests need the embedding's+ // scheduler to fire the jobs they create: without cron wiring they+ // stay unregistered (TS registers only with the heartbeat controller).let mutation_hook = cron_store.as_ref().and_then(|wiring| wiring.mutation_hook.clone());- let cron_store = cron_store.map_or_else(- || Arc::new(AgentCronJobStore::new(agent_dir.join("cron-jobs.json"))),- |wiring| wiring.store,- );+ let cron_store = cron_store.map(|wiring| wiring.store);let mut runtime = SessionRuntime::new(&session, cron_store, active_session_id, binding);if let Some(purge) = goal_complete_purge {runtime.set_goal_complete_purge(purge);@@ -192,6 +190,33 @@ pub fn wire_session_runtime(}}+/// Bundled skills whose kernel host requests are controller-backed: the+/// skill is model-visible only when its host request is registered (the+/// registry decides, like TS `_modelVisibleSkills` reads its controllers).+const CONTROLLER_BACKED_SKILLS: [(&str, &str); 3] = [+ // skills/agent-message sends `agent_message.send`.+ ("agent-message", "agent_message.send"),+ // skills/agent-observe sends `agent_observe.list`.+ ("agent-observe", "agent_observe.list"),+ // skills/rlm-heartbeat sends `rlm_heartbeat.create`.+ ("rlm-heartbeat", "rlm_heartbeat.create"),+];++/// The model-visible skill list for a final host-handler registry: a+/// controller-backed bundled skill whose host request is not registered+/// (print/RPC builds without that wiring) drops out.+#[must_use]+pub fn model_visible_skills(skills: Vec<Skill>, handlers: &HostRequestHandlers) -> Vec<Skill> {+ skills+ .into_iter()+ .filter(|skill| {+ !CONTROLLER_BACKED_SKILLS+ .iter()+ .any(|(name, request)| skill.name == *name && handlers.get(request).is_none())+ })+ .collect()+}+/// Kernel-side Python skill modules, pre-imported at bootstrap.#[must_use]pub fn kernel_python_skills(skills: &[Skill]) -> Vec<KernelPythonSkill> {@@ -414,3 +439,98 @@ pub fn ipython_tool_options(on_late_sent_agent_message,}}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::cron::store::AgentCronJobStore;+ use crate::kernel::shared::{host_handler, HostRequestHandlers};+ use serde_json::Value;++ fn cron_wiring(dir: &std::path::Path) -> KernelCronWiring {+ KernelCronWiring {+ store: Arc::new(AgentCronJobStore::new(dir.join("jobs.json"))),+ binding: None,+ mutation_hook: None,+ }+ }++ /// An engine build without cron wiring (print/RPC) serves no+ /// `rlm_heartbeat.*` requests: no scheduler fires the jobs they create.+ #[test]+ fn without_cron_wiring_the_rlm_heartbeat_handlers_stay_unregistered() {+ let dir = tempfile::tempdir().unwrap();+ let session = SessionManager::in_memory(dir.path());+ let wiring = wire_session_runtime(session, dir.path(), RlmWiring::default(), None, None);+ assert!(wiring.handlers.get("rlm_heartbeat.create").is_none());+ assert!(wiring.handlers.get("rlm_heartbeat.list").is_none());+ // The goal surface needs no scheduler and stays registered.+ assert!(wiring.handlers.get("goal.get").is_some());+ }++ #[test]+ fn with_cron_wiring_the_rlm_heartbeat_handlers_register() {+ let dir = tempfile::tempdir().unwrap();+ let session = SessionManager::in_memory(dir.path());+ let wiring = wire_session_runtime(+ session,+ dir.path(),+ RlmWiring::default(),+ None,+ Some(cron_wiring(dir.path())),+ );+ assert!(wiring.handlers.get("rlm_heartbeat.create").is_some());+ }++ fn skill_named(name: &str) -> crate::skills::Skill {+ use crate::skills::{create_synthetic_source_info, SkillKind, SourceScope};+ crate::skills::Skill {+ name: name.to_string(),+ description: "a skill".to_string(),+ file_path: std::path::PathBuf::from("/skills/SKILL.md"),+ base_dir: std::path::PathBuf::from("/skills"),+ source_info: create_synthetic_source_info("/skills", "user", SourceScope::User, None),+ disable_model_invocation: false,+ kind: SkillKind::Markdown,+ python: None,+ }+ }++ /// A controller-backed bundled skill whose host request is not+ /// registered drops out; the registered ones and plain skills stay.+ #[test]+ fn model_visible_skills_follow_the_handler_registry() {+ let skills = vec![+ skill_named("agent-message"),+ skill_named("agent-observe"),+ skill_named("rlm-heartbeat"),+ skill_named("websearch"),+ ];+ let mut handlers = HostRequestHandlers::default();+ handlers.register(+ "agent_message.send",+ host_handler(|_payload| Box::pin(async { Ok(Value::Null) })),+ );+ let visible = model_visible_skills(skills, &handlers);+ let names: Vec<&str> = visible.iter().map(|skill| skill.name.as_str()).collect();+ assert_eq!(names, ["agent-message", "websearch"]);++ handlers.register(+ "agent_observe.list",+ host_handler(|_payload| Box::pin(async { Ok(Value::Null) })),+ );+ handlers.register(+ "rlm_heartbeat.create",+ host_handler(|_payload| Box::pin(async { Ok(Value::Null) })),+ );+ let visible = model_visible_skills(+ vec![+ skill_named("agent-message"),+ skill_named("agent-observe"),+ skill_named("rlm-heartbeat"),+ ],+ &handlers,+ );+ assert_eq!(visible.len(), 3);+ }+}diff --git a/crates/pa-core/tests/abort_kernel_cell.rs b/crates/pa-core/tests/abort_kernel_cell.rsindex ef3be7fa2a..bd364b528b 100644--- a/crates/pa-core/tests/abort_kernel_cell.rs+++ b/crates/pa-core/tests/abort_kernel_cell.rs@@ -173,6 +173,7 @@ async fn abort_during_a_kernel_cell_settles_the_turn_immediately() {mcp_manager: None,prewarm_ipython_kernel: None,on_background_work_settled: None,+ bash_notice_wake: None,queued_goal_context_purge: None,queued_steering_probe: None,should_stop_after_turn: None,diff --git a/crates/pa-core/tests/prompt_guards.rs b/crates/pa-core/tests/prompt_guards.rsindex 0af594c52c..79dd571269 100644--- a/crates/pa-core/tests/prompt_guards.rs+++ b/crates/pa-core/tests/prompt_guards.rs@@ -143,8 +143,16 @@ fn cached_prefix_is_stable_across_sessions() {/// Host-request types that are host-internal plumbing, not model-facing/// programmatic tools (the prompt must not document them).-const INTERNAL_HOST_REQUESTS: &[&str] =- &["model.info", "mcp.config", "mcp.refresh", "mcp.begin_login"];+const INTERNAL_HOST_REQUESTS: &[&str] = &[+ "model.info",+ "mcp.config",+ "mcp.refresh",+ "mcp.begin_login",+ // The runtime's detached-bash notice pair (the kernel's bash module+ // fires them; the model never calls them).+ "bash.completed",+ "bash.consumed",+];/// Map one registered host-request type to the prompt token that documents/// it. `None` when the request is host-internal.@@ -230,12 +238,17 @@ fn registered_host_requests() -> BTreeSet<String> {continue;}let source = std::fs::read_to_string(&path).expect("read source");- // Direct registrations: the first string literal after each- // `.register(` (the request type comes first in the call).+ // Direct registrations: the request type is the FIRST+ // argument of each `.register(` — a literal right at the+ // call's head counts; anything after a non-literal first+ // argument is not the request type.for remainder in source.split(".register(").skip(1) {- if let Some(literal) = first_string_literal(remainder) {- if is_request_type_literal(&literal) {- found.insert(literal);+ let rest = remainder.trim_start();+ if rest.starts_with('"') {+ if let Some(literal) = first_string_literal(rest) {+ if is_request_type_literal(&literal) {+ found.insert(literal);+ }}}}@@ -535,11 +548,10 @@ fn bundled_skills_match_the_ts_packaged_set() {);}-/// The bounded-await contract renders only in daemon sessions: the-/// runtime half (the degrade) exists only where the host registers the-/// bash completion notice, so a daemonless prompt must carry no trace of it.+/// The bounded-await contract renders wherever the Python REPL does: every session kind, daemon+/// or daemonless, registers the bash completion notice the degrade relies on.#[test]-fn bounded_await_contract_render_is_daemon_only() {+fn bounded_await_contract_renders_in_daemon_and_daemonless_sessions() {let mut options = BuildSystemPromptOptions {cwd: "/w".to_string(),messages_path: Some("/log.jsonl".to_string()),@@ -547,24 +559,16 @@ fn bounded_await_contract_render_is_daemon_only() {selected_tools: Some(vec!["python_repl"]),..Default::default()};- let daemon = system_prompt_breakdown(&options);- assert!(- daemon.assembled.contains("yield_after")- && daemon.assembled.contains("[bash-done]")- && daemon.assembled.contains("`r.running` is True")- && daemon.assembled.contains("`r.exit_code` is None"),- "the daemon session prompt must carry the bounded-await result contract"- );- options.daemonless = true;- let daemonless = system_prompt_breakdown(&options);- assert!(- !daemonless.assembled.contains("yield_after")- && !daemonless.assembled.contains("[bash-done]")- && !daemonless.assembled.contains("still-running snapshot")- && !daemonless.assembled.contains("about 10 seconds"),- "the daemonless session prompt must not leak the bounded-await contract: {0}",- daemonless.assembled- );+ for daemonless in [false, true] {+ options.daemonless = daemonless;+ let prompt = system_prompt_breakdown(&options).assembled;+ assert!(+ prompt.contains("yield_after")+ && prompt.contains("`r.running` is True")+ && prompt.contains("`r.exit_code` is None"),+ "daemonless={daemonless}: the prompt must carry the bounded-await result contract: {prompt}"+ );+ }}/// The generic mcp skill loads through the normal markdown discovery and renders in thediff --git a/crates/pa-core/tests/turn_boundary_kernel.rs b/crates/pa-core/tests/turn_boundary_kernel.rsindex 10d9eedfc1..764973ab11 100644--- a/crates/pa-core/tests/turn_boundary_kernel.rs+++ b/crates/pa-core/tests/turn_boundary_kernel.rs@@ -209,6 +209,7 @@ async fn turn_boundary_host_requests_round_trip_through_a_real_kernel() {mcp_manager: None,prewarm_ipython_kernel: None,on_background_work_settled: None,+ bash_notice_wake: None,queued_goal_context_purge: None,}).awaitdiff --git a/crates/pa-daemon/src/agent_engine/lifecycle.rs b/crates/pa-daemon/src/agent_engine/lifecycle.rsindex f5e56150ba..b2c54da62e 100644--- a/crates/pa-daemon/src/agent_engine/lifecycle.rs+++ b/crates/pa-daemon/src/agent_engine/lifecycle.rs@@ -1175,6 +1175,7 @@ impl AgentSessionEngine {// Prewarm; the depth gate keeps subagent workers lazy.prewarm_ipython_kernel: Some(true),on_background_work_settled,+ bash_notice_wake: None,// The worker-installed purge withdraws queued minted continuations.queued_goal_context_purge,// The steering lane owns the stop hooks (a queued steer cuts the next turn).diff --git a/crates/pa-daemon/src/bash_notices.rs b/crates/pa-daemon/src/bash_notices.rsindex b1cfee61d3..fd9659b5c6 100644--- a/crates/pa-daemon/src/bash_notices.rs+++ b/crates/pa-daemon/src/bash_notices.rs@@ -1,15 +1,11 @@-//! The detached kernel bash completion notice (the TS async-bash-completion-//! wake: `bash.completed`/`bash.consumed`): on completion the session injects-//! the `[bash-done pid:N exit:M]` custom row with `queueIfBusy` +-//! `resumeIfIdle`; a later kernel read that reaches the model first sends-//! `bash.consumed`, and the undelivered notice withdraws.+//! The daemon worker's bash-notice seams: the notice types, the TS+//! validation, and the handler registration live in pa-core+//! (`session_engine::bash_notices`); the worker keeps its queue-lane+//! sinks here.-use serde_json::Value;--use pa_core::kernel::shared::{host_handler, HostRequestHandlers, BASH_COMPLETED_REQUEST_TYPE};+use pa_core::kernel::shared::HostRequestHandlers;use crate::agent_engine::AgentSessionEngine;-use crate::engine::{BashCompletionNotice, BashConsumedNotice};impl AgentSessionEngine {/// Wire the worker's bash-completion queue seams (called once at@@ -55,95 +51,8 @@ impl AgentSessionEngine {else {return;};- handlers.register(- BASH_COMPLETED_REQUEST_TYPE,- host_handler(move |payload| {- let completion = completion.clone();- Box::pin(async move {- let notice = validate_completion(&payload.data)?;- // The closed-session gate lives in the sink: the worker's kill/shutdown- // set the marker, and the sink refuses the injection like TS `_disposed`.- completion(notice);- Ok(serde_json::json!({}))- })- }),- );- handlers.register(- "bash.consumed",- host_handler(move |payload| {- let consumed = consumed.clone();- Box::pin(async move {- let notice = validate_consumed(&payload.data)?;- consumed(notice);- Ok(serde_json::json!({}))- })- }),+ pa_core::session_engine::bash_notices::register_bash_notice_host_handlers(+ completion, consumed, handlers,);}}--/// TS `createAsyncBashCompletionHostHandler` validation: a positive-/// integer pid, a non-empty string command, an integer exit code.-fn validate_completion(data: &Value) -> anyhow::Result<BashCompletionNotice> {- let consumed = validate_consumed(data)?;- let exit_code = data- .get("exitCode")- .and_then(Value::as_i64)- .ok_or_else(|| anyhow::anyhow!("bash.completed exitCode must be an integer"))?;- Ok(BashCompletionNotice {- pid: consumed.pid,- command: consumed.command,- exit_code,- })-}--/// TS `createAsyncBashConsumedHostHandler` validation: a positive integer pid and a-/// non-empty command (pids are reused across handles, so the command disambiguates).-fn validate_consumed(data: &Value) -> anyhow::Result<BashConsumedNotice> {- let pid = data- .get("pid")- .and_then(Value::as_u64)- .filter(|pid| *pid > 0 && u32::try_from(*pid).is_ok())- .ok_or_else(|| anyhow::anyhow!("bash.completed pid must be a positive integer"))?- as u32;- let command = data- .get("command")- .and_then(Value::as_str)- .filter(|command| !command.is_empty())- .ok_or_else(|| anyhow::anyhow!("bash.completed command must be a non-empty string"))?- .to_string();- Ok(BashConsumedNotice { pid, command })-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn completion_validation_matches_the_ts_contract() {- assert!(validate_completion(&serde_json::json!({- "pid": 4321,- "command": "sleep 1",- "exitCode": 0,- }))- .is_ok());- assert!(validate_completion(&serde_json::json!({- "pid": 0,- "command": "sleep 1",- "exitCode": 0,- }))- .is_err());- assert!(validate_completion(&serde_json::json!({- "pid": 4321,- "command": "",- "exitCode": 0,- }))- .is_err());- assert!(validate_completion(&serde_json::json!({- "pid": 4321,- "command": "sleep 1",- "exitCode": "0",- }))- .is_err());- }-}diff --git a/crates/pa-daemon/src/engine/wire.rs b/crates/pa-daemon/src/engine/wire.rsindex a485a416e5..9bfdc439d2 100644--- a/crates/pa-daemon/src/engine/wire.rs+++ b/crates/pa-daemon/src/engine/wire.rs@@ -241,29 +241,12 @@ pub enum GoalTurnEndWork {/// held suspension owns the next turn boundary, so the goal mint defers.pub type SessionInputProbe = std::sync::Arc<dyn Fn() -> bool + Send + Sync>;-/// One detached kernel bash completion (the `bash.completed` host-/// request): the finished command's identity and exit code.-#[derive(Debug, Clone)]-pub struct BashCompletionNotice {- pub pid: u32,- pub command: String,- pub exit_code: i64,-}--/// The queue-admission seam for one completion notice (the worker's-/// steering lane + runner wake + recovery busy-evidence).-pub type BashCompletionSink = std::sync::Arc<dyn Fn(BashCompletionNotice) + Send + Sync>;--/// The kernel read a finished command's result before its notice-/// delivered (the `bash.consumed` host request): the queued notice is stale.-#[derive(Debug, Clone)]-pub struct BashConsumedNotice {- pub pid: u32,- pub command: String,-}--/// The queue-withdrawal seam for a consumed notice.-pub type BashConsumedSink = std::sync::Arc<dyn Fn(BashConsumedNotice) + Send + Sync>;+// The bash-notice plumbing lives in pa-core+// (`session_engine::bash_notices`); the re-export keeps the+// `crate::engine::*` paths the worker's queue lanes compile against.+pub use pa_core::session_engine::bash_notices::{+ BashCompletionNotice, BashCompletionSink, BashConsumedNotice, BashConsumedSink,+};/// The worker's goal admission sink: the queue lanes admit a minted goal/// follow-up, the `goal_update` surfaces, and the runner wakes.diff --git a/crates/pa-daemon/src/rpc/commands.rs b/crates/pa-daemon/src/rpc/commands.rsindex 94c916e7f5..7c7d9e7e73 100644--- a/crates/pa-daemon/src/rpc/commands.rs+++ b/crates/pa-daemon/src/rpc/commands.rs@@ -120,6 +120,7 @@ pub fn kick_queue_pump(tokio::spawn(async move {let _lane = state.queue_pump.lock().await;if state.session.pump_generation() != generation+ || state.session.shutdown_fired()|| !state.session.engine_is_live(&engine).await|| state.session.is_replacing(){@@ -128,6 +129,7 @@ pub fn kick_queue_pump(let agent = engine.session.agent();loop {if state.session.pump_generation() != generation+ || state.session.shutdown_fired()|| !state.session.engine_is_live(&engine).await|| state.session.is_replacing(){@@ -177,6 +179,32 @@ pub fn kick_queue_pump(});}+/// Serve the live engine's background-bash wakes: every wake kicks the+/// queued-work pump, so the `[bash-done]` row a completion steers onto+/// the agent runs as a turn with no client command driving it. The+/// handle's wake is re-read each cycle, so a replacement rebinds.+pub fn serve_background_bash_wakes(state: &Arc<RpcState>) {+ let state = Arc::clone(state);+ tokio::spawn(async move {+ loop {+ let (bash_wake, engine) = {+ let handle = state.session.handle().await;+ (Arc::clone(&handle.bash_wake), Arc::clone(&handle.engine))+ };+ let notified = bash_wake.notified();+ tokio::pin!(notified);+ notified.as_mut().enable();+ // A wake that fired between the handle read and the armed+ // park already queued its row: kick before parking.+ if engine.session.agent().has_queued_messages() {+ kick_queue_pump(&state, &engine);+ }+ notified.await;+ kick_queue_pump(&state, &engine);+ }+ });+}+/// Dispatch one command to its handler; the unknown-type error answers with no id.pub async fn handle_command(state: &Arc<RpcState>, command: protocol::RpcCommand) -> Value {let id = command.id.clone();diff --git a/crates/pa-daemon/src/rpc/mod.rs b/crates/pa-daemon/src/rpc/mod.rsindex 1f30778829..d9e2b245e6 100644--- a/crates/pa-daemon/src/rpc/mod.rs+++ b/crates/pa-daemon/src/rpc/mod.rs@@ -147,6 +147,10 @@ pub async fn run_rpc_mode(options: RpcOptions) -> anyhow::Result<i32> {model_ops: Arc::new(tokio::sync::Mutex::new(())),session_ops: Arc::new(tokio::sync::Mutex::new(())),});+ // The background-bash completion lane: each built engine's wake+ // kicks the queued-work pump, so an idle session runs the+ // completion row's turn.+ commands::serve_background_bash_wakes(&state);// With no create command, the FIRST `get_available_models` would pay// the whole awaited refresh chain; this spawn warms the caches early.tokio::spawn(async move {diff --git a/crates/pa-daemon/src/rpc/session.rs b/crates/pa-daemon/src/rpc/session.rsindex cece0fe8a2..2a1a75483c 100644--- a/crates/pa-daemon/src/rpc/session.rs+++ b/crates/pa-daemon/src/rpc/session.rs@@ -24,6 +24,9 @@ pub struct RpcEngineHandle {pub model: Model,pub api_key: Option<String>,pub provider_target: Arc<std::sync::RwLock<Option<ProviderTarget>>>,+ /// The built engine's background-bash wake: its completion and+ /// settle seams fire it, and the pump listener parks on it.+ pub bash_wake: Arc<tokio::sync::Notify>,/// The cross-process ownership lease on the opened session file/// (`None` for fresh/in-memory sessions the factory created itself).pub session_lease: Option<crate::lease::SessionLease>,@@ -344,7 +347,13 @@ impl RpcSession {if adopted_lease.is_some() {replacement.session_lease = adopted_lease;}+ // The background-bash listener parks on the retired handle's wake:+ // fire it so the listener re-reads the LIVE handle (a stored+ // permit, because it may not be parked yet). Its kick against the+ // retired engine is dropped by the pump's liveness checks.+ let retired_bash_wake = Arc::clone(&handle.bash_wake);*handle = replacement;+ retired_bash_wake.notify_one();*self.subscription.lock().await = Some(subscription);Ok(())}diff --git a/scripts/review_late_message_receipt_parity.py b/scripts/review_late_message_receipt_parity.pynew file mode 100644index 0000000000..72d03f435f--- /dev/null+++ b/scripts/review_late_message_receipt_parity.py@@ -0,0 +1,245 @@+#!/usr/bin/env python3+"""Actual TS/Rust print child fire-and-forget receipt after its REPL result lands.++The child send waits on a loopback gate. Only the child's second real model+request (containing its finished tool result) opens it. The parent remains in+its model request until the child's durable late receipt appears. This tests+late delivery/persistence without arbitrary task sleeps or stub host handlers.+"""+import argparse+import http.server+import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import threading+import time++from review_draft_disconnect_parity import env_for, digest, TS_ARCHIVE_SHA256+from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish+from review_restore_notice_parity import texts, probe_from++MESSAGE = 'LATE_RECEIPT_FIXTURE_MESSAGE'+PARENT_CELL = "late_child = await rlm.spawn('LATE_RECEIPT_CHILD', name='late-child')\nprint('LATE_SPAWN_HANDLE=' + __import__('json').dumps({'rlm_child_id': late_child.rlm_child_id, 'session_dir': str(late_child.session_dir)}))"+++def late_entries(root):+ entries = []+ for path in root.rglob('*.jsonl'):+ for line in path.read_text().splitlines(keepends=True):+ if not line.strip():+ continue # session readers also permit blank JSONL separators+ if not line.endswith('\n'):+ continue # an in-progress append is not an observed complete entry+ row = json.loads(line)+ if row.get('type') == 'custom' and row.get('customType') == 'ipython_sent_agent_message':+ entries.append({'file': str(path), 'entry': row})+ return entries+++class Provider(http.server.ThreadingHTTPServer):+ daemon_threads = True++ def __init__(self, root):+ super().__init__(('127.0.0.1', 0), Handler)+ self.root = root+ self.gate = threading.Event()+ self.requests = {'parent': [], 'child': []}+ self.errors = []+ self.child_result_seen_before_release = False+++class Handler(http.server.BaseHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ def do_GET(self):+ if self.path != '/send-gate' or not self.server.gate.wait(75):+ self.send_error(504)+ return+ self.send_response(200)+ self.send_header('Content-Length', '2')+ self.end_headers()+ self.wfile.write(b'OK')++ def do_POST(self):+ if self.path != '/v1/chat/completions':+ self.send_error(404)+ return+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ child = any('LATE_RECEIPT_CHILD' in ''.join(texts(m.get('content')))+ for m in body.get('messages', []) if m.get('role') == 'user')+ lane = 'child' if child else 'parent'+ requests = self.server.requests[lane]+ requests.append(body)+ count = len(requests)+ code = None+ if count == 1:+ if child:+ code = f'''import asyncio, urllib.request+async def fixture_delayed_send():+ await asyncio.to_thread(lambda: urllib.request.urlopen('http://127.0.0.1:{self.server.server_port}/send-gate', timeout=90).read())+ await agent_message.send('{MESSAGE}', receiver_role='parent')+fixture_send_task = asyncio.create_task(fixture_delayed_send())+print('LATE_CHILD_CELL_FINISHED')'''+ else:+ code = PARENT_CELL+ elif child and count == 2:+ results = [m for m in body.get('messages', []) if m.get('role') == 'tool'+ and m.get('tool_call_id') == 'late_child_cell']+ if len(results) != 1 or 'LATE_CHILD_CELL_FINISHED' not in ''.join(texts(results[0].get('content'))):+ self.server.errors.append('gate opened without the actual completed child cell')+ else:+ self.server.child_result_seen_before_release = True+ self.server.gate.set()+ elif not child and count == 2:+ deadline = time.monotonic() + 60+ while time.monotonic() < deadline:+ if late_entries(self.server.root):+ break+ threading.Event().wait(0.025)+ else:+ self.server.errors.append('actual late receipt never persisted')+ if code:+ offered = {tool['function']['name'] for tool in body.get('tools', [])}+ name = next((n for n in ('python_repl', 'ipython') if n in offered), None)+ if name is None:+ self.send_error(422)+ return+ delta = {'tool_calls': [{'index': 0, 'id': 'late_child_cell' if child else 'late_parent_cell',+ 'type': 'function', 'function': {'name': name, 'arguments': json.dumps({'code': code})}}]}+ reason = 'tool_calls'+ else:+ delta, reason = {'content': 'Child complete.' if child else 'Parent complete.'}, 'stop'+ def chunk(delta, reason=None):+ return {'id': 'late-receipt-fixture', 'object': 'chat.completion.chunk', 'created': 1,+ 'model': 'late-receipt-fixture', 'choices': [{'index': 0, 'delta': delta, 'finish_reason': reason}]}+ wire = ''.join('data: ' + json.dumps(row) + '\n\n' for row in (+ chunk({'role': 'assistant', **delta}), chunk({}, reason))) + 'data: [DONE]\n\n'+ self.send_response(200)+ self.send_header('Content-Type', 'text/event-stream')+ self.send_header('Content-Length', str(len(wire.encode())))+ self.end_headers()+ self.wfile.write(wire.encode())+++def validate(observed):+ assert observed['child_result_seen_before_release'] is True+ assert observed['child_request_count'] == 2+ assert 2 <= observed['parent_request_count'] <= 4+ rows = observed['late_entries']+ assert len(rows) == 1, 'missing/duplicate persisted late receipt'+ payload = rows[0]['entry']['data']+ assert payload['toolCallId'] == 'late_child_cell', payload+ message = payload['message']+ assert message['message'] == MESSAGE and message['receiverRole'] == 'parent', message+ assert isinstance(message['id'], str) and message['id'], message+ assert message['deliveryStatus'] in ('delivered', 'queued'), message+ assert message['target']['sessionId'] == observed['parent_session_id'], message+ # TS print hosts allocate a runtime activeSessionId distinct from the+ # durable UUID. The durable target and child-parent edge below identify+ # the recipient; retain the volatile runtime ID without equating the two.+ active_id = message['target'].get('activeSessionId')+ assert isinstance(active_id, str) and active_id.strip(), message+ assert rows[0]['file'] != observed['parent_session_file'], 'receipt must belong to child'+ handle = observed['spawn_handle']+ assert handle['rlm_child_id'] and handle['rlm_child_id'] in Path(handle['session_dir']).parts, handle+ assert Path(rows[0]['file']).parent.resolve() == Path(handle['session_dir']).resolve(), 'receipt not in actual spawned child session directory'+ header = observed['child_header']+ assert header.get('type') == 'session' and header.get('id'), header+ assert Path(header['parentSession']).resolve() == Path(observed['parent_session_file']).resolve(), 'wrong durable child-parent edge'+ return {key: message[key] for key in ('message', 'receiverRole', 'deliveryStatus')}+++def observe(binary, kind, root, observed):+ env = env_for(root, kind)+ env[TAG] = str(root)+ library = Path(os.environ['PI_PACKAGE_DIR']) / 'skills'+ env['PYTHONPATH'] = os.pathsep.join(sorted(str(p) for p in library.glob('*/src') if p.is_dir()))+ observed['fixture_pythonpath'] = env['PYTHONPATH']+ provider = Provider(root)+ thread = threading.Thread(target=provider.serve_forever, daemon=True)+ thread.start()+ (root / 'agent/settings.json').write_text(json.dumps({'prewarmPythonKernel': False}))+ (root / 'agent/models.json').write_text(json.dumps({'providers': {'fixture': {+ 'api': 'openai-completions', 'apiKey': 'fixture-only',+ 'baseUrl': f'http://127.0.0.1:{provider.server_port}/v1', 'models': [{+ 'id': 'late-receipt-fixture', 'name': 'Late receipt fixture', 'reasoning': False,+ 'contextWindow': 128000, 'maxTokens': 4096}]}}}))+ scope = OwnedProcesses(binary, root, root / 'unused.sock')+ process = None+ output = (root / 'stdout.jsonl').open('w')+ error_log = (root / 'stderr.log').open('w')+ try:+ command = [str(binary), '--mode', 'json', '--provider', 'fixture', '--model',+ 'late-receipt-fixture', '--session-dir', str(root / 'sessions'), 'Run LATE_RECEIPT_PARENT.']+ process = subprocess.Popen(command, cwd=root, env=env, stdout=output,+ stderr=error_log, start_new_session=True)+ scope.register(process, command)+ process.wait(timeout=120)+ assert process.returncode == 0, process.returncode+ assert not provider.errors, provider.errors+ parents = list((root / 'sessions').glob('*.jsonl'))+ assert len(parents) == 1, parents+ header = json.loads(parents[0].read_text().splitlines()[0])+ assert header.get('type') == 'session', header+ observed.update(parent_session_id=header['id'], parent_session_file=str(parents[0]),+ child_result_seen_before_release=provider.child_result_seen_before_release,+ child_request_count=len(provider.requests['child']), parent_request_count=len(provider.requests['parent']),+ late_entries=late_entries(root))+ observed['spawn_handle'] = probe_from(provider.requests['parent'], 'LATE_SPAWN_HANDLE=')+ assert len(observed['late_entries']) == 1, observed['late_entries']+ child_file = Path(observed['late_entries'][0]['file'])+ observed['child_header'] = json.loads(child_file.read_text().splitlines()[0])+ observed['semantic_receipt'] = validate(observed)+ finally:+ provider.gate.set()+ observed['provider_requests'] = provider.requests+ finish(scope, None, None, observed)+ output.close()+ error_log.close()+ observed['stdout'] = (root / 'stdout.jsonl').read_text(errors='replace')+ observed['stderr'] = (root / 'stderr.log').read_text(errors='replace')[-10000:]+ provider.shutdown()+ provider.server_close()+ thread.join(timeout=2)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--receipt', type=Path, required=True)+ args = parser.parse_args()+ result = {'verified': False, 'runs': {}, 'scope': __doc__,+ 'fixture_prerequisite': 'Both kernels receive the same pinned TS skill libraries through PYTHONPATH; this tests host receipt delivery, not native skill packaging.',+ 'not_verified': [+ 'pre-result receipt landing (Rust regression)', 'I/O failure (Rust regression)',+ 'compaction/tree-navigation receipt restoration', 'receipt event/frame equality',+ 'all volatile generated target identifiers are retained, not compared as equal']}+ try:+ assert sys.platform == 'linux'+ assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256+ result['ts_archive_sha256'] = TS_ARCHIVE_SHA256+ with tempfile.TemporaryDirectory(prefix='pa-late-receipt-', dir='/tmp') as folder:+ for kind in ('ts', 'rust'):+ binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()+ observed = result['runs'][kind] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, kind, Path(folder) / kind, observed)+ observed['behavior_verified'] = True+ except Exception as error:+ observed['error'] = str(error)+ assert all(r.get('behavior_verified') and r.get('cleanup_verified') and 'error' not in r+ for r in result['runs'].values()), 'actual late receipt observation failed'+ assert result['runs']['ts']['semantic_receipt'] == result['runs']['rust']['semantic_receipt']+ result['verified'] = True+ except Exception as error:+ result['error'] = str(error)+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ args.receipt.write_text(json.dumps(result, ensure_ascii=False, indent=2))+ return 0 if result['verified'] else 1+++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/review_print_bash_parity.py b/scripts/review_print_bash_parity.pynew file mode 100644index 0000000000..2ab670622e--- /dev/null+++ b/scripts/review_print_bash_parity.py@@ -0,0 +1,230 @@+#!/usr/bin/env python3+"""Actual TS/Rust print background completion wake, held until the first turn ends.++Both binaries receive identical REPL cells. A loopback HTTP gate holds the+background process. Expected difference: TS 0.9.8 --print exits after its+first turn without waiting for the command, so its gate opens only when the+process is gone (no wake, no notice); Rust print waits for it on purpose, so+its gate opens once the first turn ended, and the completion must wake a+second turn and persist the notice.+"""+import argparse+import http.server+import json+import os+from pathlib import Path+import shlex+import subprocess+import sys+import tempfile+import threading++from review_draft_disconnect_parity import env_for, digest, TS_ARCHIVE_SHA256+from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish+from review_restore_notice_parity import texts, probe_from++START = 'PRINT_BASH_STARTED='+DONE = 'PRINT_BASH_FINISHED='+++class Provider(http.server.ThreadingHTTPServer):+ daemon_threads = True++ def __init__(self):+ super().__init__(('127.0.0.1', 0), Handler)+ self.release = threading.Event()+ self.requests = []+ self.errors = []+ self.waiting_seen = False+ self.first_turn_ended = False+ self.gate_timed_out = False+++class Handler(http.server.BaseHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ def do_GET(self):+ if self.path != '/background':+ self.send_error(404)+ return+ if not self.server.release.wait(75):+ self.server.gate_timed_out = True+ self.send_error(504)+ return+ payload = b'BG_DONE'+ self.send_response(200)+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++ def do_POST(self):+ if self.path != '/v1/chat/completions':+ self.send_error(404)+ return+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ self.server.requests.append(body)+ count = len(self.server.requests)+ offered = {tool['function']['name'] for tool in body.get('tools', [])}+ name = next((n for n in ('python_repl', 'ipython') if n in offered), None)+ if count == 1:+ command = shlex.join(['python3', '-c',+ f"import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:{self.server.server_port}/background', timeout=90).read().decode())"])+ code = 'h = bash(' + repr(command) + ")\nprint('PRINT_BASH_STARTED=' + __import__('json').dumps({'pid': h.pid}))"+ elif count == 3:+ notice = [t for m in body.get('messages', []) if m.get('role') == 'user'+ for t in texts(m.get('content')) if '[bash-done pid:' in t]+ if not notice:+ self.server.errors.append('wake request lacks actual bash completion notice')+ code = "print('PRINT_BASH_FINISHED=' + __import__('json').dumps({'completed': 'BG_DONE' in h.output()}))"+ else:+ code = None+ if count not in (1, 2, 3, 4) or (code and name is None):+ self.server.errors.append('unexpected provider sequence')+ self.send_error(422)+ return+ if code:+ delta = {'tool_calls': [{'index': 0, 'id': 'print_bash_' + str(count), 'type': 'function',+ 'function': {'name': name, 'arguments': json.dumps({'code': code})}}]}+ reason = 'tool_calls'+ else:+ delta, reason = {'content': 'WAITING' if count == 2 else 'COMPLETED WOKEN'}, 'stop'+ def chunk(delta, reason=None):+ return {'id': 'print-bash-fixture', 'object': 'chat.completion.chunk', 'created': 1,+ 'model': 'print-bash-fixture', 'choices': [{'index': 0, 'delta': delta, 'finish_reason': reason}]}+ wire = ''.join('data: ' + json.dumps(row) + '\n\n' for row in (+ chunk({'role': 'assistant', **delta}), chunk({}, reason))) + 'data: [DONE]\n\n'+ self.send_response(200)+ self.send_header('Content-Type', 'text/event-stream')+ self.send_header('Content-Length', str(len(wire.encode())))+ self.end_headers()+ self.wfile.write(wire.encode())+++def validate(observed):+ assert observed['first_turn_ended_before_release'] is True+ assert observed['request_count'] == 4+ assert observed['finished'] == {'completed': True}+ assert observed['notice']['exit_code'] == 0+ assert observed['notice']['display'] is True+ assert observed['notice']['matches_started_pid'] is True+++def validate_ts(observed):+ # TS --print ends with its first turn: no wake request, no notice.+ assert observed['first_turn_ended_before_release'] is True+ assert observed['request_count'] == 2+ assert observed['notice_count'] == 0+ assert observed['gate_timed_out'] is False+++def observe(binary, kind, root, observed):+ env = env_for(root, kind)+ env[TAG] = str(root)+ provider = Provider()+ thread = threading.Thread(target=provider.serve_forever, daemon=True)+ thread.start()+ (root / 'agent/settings.json').write_text(json.dumps({'prewarmPythonKernel': False}))+ (root / 'agent/models.json').write_text(json.dumps({'providers': {'fixture': {+ 'api': 'openai-completions', 'apiKey': 'fixture-only',+ 'baseUrl': f'http://127.0.0.1:{provider.server_port}/v1', 'models': [{+ 'id': 'print-bash-fixture', 'name': 'Print bash fixture', 'reasoning': False,+ 'contextWindow': 128000, 'maxTokens': 4096}]}}}))+ scope = OwnedProcesses(binary, root, root / 'unused.sock')+ process = None+ events = []+ stderr_path = root / 'stderr.log'+ stderr = stderr_path.open('w')+ try:+ command = [str(binary), '--mode', 'json', '--provider', 'fixture', '--model',+ 'print-bash-fixture', '--session-dir', str(root / 'sessions'), 'Run the print bash fixture.']+ process = subprocess.Popen(command, cwd=root, env=env, stdout=subprocess.PIPE,+ stderr=stderr, text=True, start_new_session=True)+ scope.register(process, command)+ def read_events():+ for line in process.stdout:+ try:+ event = json.loads(line)+ except ValueError:+ events.append({'unparsed': line})+ continue+ events.append(event)+ message = event.get('message', {})+ if event.get('type') == 'message_end' and message.get('role') == 'assistant':+ if list(texts(message.get('content'))) == ['WAITING']:+ provider.waiting_seen = True+ if event.get('type') == 'turn_end' and provider.waiting_seen and not provider.first_turn_ended:+ provider.first_turn_ended = True+ if kind != 'ts':+ provider.release.set()+ reader = threading.Thread(target=read_events, daemon=True)+ reader.start()+ process.wait(timeout=110)+ reader.join(timeout=5)+ assert not reader.is_alive(), 'stdout reader never finished'+ assert process.returncode == 0, process.returncode+ assert not provider.errors, provider.errors+ started = probe_from(provider.requests, START)+ rows = [json.loads(line) for path in (root / 'sessions').rglob('*.jsonl')+ for line in path.read_text().splitlines()]+ notices = [row for row in rows if row.get('type') == 'custom_message'+ and row.get('customType') == 'async_bash_completion']+ if kind == 'ts':+ observed.update(first_turn_ended_before_release=provider.first_turn_ended,+ request_count=len(provider.requests), notice_count=len(notices),+ gate_timed_out=provider.gate_timed_out)+ validate_ts(observed)+ return+ finished = probe_from(provider.requests, DONE)+ assert len(notices) == 1, notices+ notice = notices[0]+ observed.update(first_turn_ended_before_release=provider.first_turn_ended,+ request_count=len(provider.requests), finished=finished,+ raw_notice=notice, notice={'exit_code': notice.get('details', {}).get('exitCode'),+ 'display': notice.get('display'),+ 'matches_started_pid': f"[bash-done pid:{started['pid']} exit:0]" in '\n'.join(texts(notice.get('content')))})+ validate(observed)+ finally:+ provider.release.set()+ observed['provider_requests'] = provider.requests+ observed['events'] = events+ finish(scope, None, None, observed)+ stderr.close()+ observed['stderr'] = stderr_path.read_text(errors='replace')[-10000:]+ provider.shutdown()+ provider.server_close()+ thread.join(timeout=2)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--receipt', type=Path, required=True)+ args = parser.parse_args()+ result = {'verified': False, 'runs': {}, 'scope': __doc__, 'not_verified': [+ 'RPC wake/replacement (Rust e2e)', 'inline child background wake (Rust e2e)',+ 'late agent-message receipt delivery (Rust regression)', 'full prompt/frame parity']}+ try:+ assert sys.platform == 'linux'+ assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256+ result['ts_archive_sha256'] = TS_ARCHIVE_SHA256+ with tempfile.TemporaryDirectory(prefix='pa-print-bash-', dir='/tmp') as folder:+ for kind in ('ts', 'rust'):+ binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()+ observed = result['runs'][kind] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, kind, Path(folder) / kind, observed)+ observed['behavior_verified'] = True+ except Exception as error:+ observed['error'] = str(error)+ assert all(r.get('behavior_verified') and r.get('cleanup_verified') and 'error' not in r+ for r in result['runs'].values()), 'actual print bash observation failed'+ result['verified'] = True+ except Exception as error:+ result['error'] = str(error)+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ args.receipt.write_text(json.dumps(result, ensure_ascii=False, indent=2))+ return 0 if result['verified'] else 1+++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/review_restore_notice_parity.py b/scripts/review_restore_notice_parity.pyindex 56b747b72a..02c5faf87d 100644--- a/scripts/review_restore_notice_parity.py+++ b/scripts/review_restore_notice_parity.py@@ -10,6 +10,7 @@ import argparseimport http.serverimport jsonimport os+import refrom pathlib import Pathimport signalimport subprocess@@ -23,7 +24,13 @@ from review_goal_backoff_parity import TS_ARCHIVE_SHA256, sha256RESET = ("The working directory and environment variables were reset to the session defaults; ""re-apply any os.chdir(...) or os.environ[...] changes you still need.")PROBE = "RESTORE_PARITY_RESULT="-SETUP = """import os+SKILL_PROBE = 'HEADLESS_SKILL_AVAILABILITY='+SKILLS = {'agent-message': 'agent_message', 'agent-observe': 'agent_observe',+ 'rlm-heartbeat': 'rlm_heartbeat'}+SETUP = """print('HEADLESS_SKILL_AVAILABILITY=' + __import__('json').dumps({name: name in globals() for name in ('agent_message', 'agent_observe', 'rlm_heartbeat')}))+# Explicit equal fixture imports isolate restore from the deliberate headless skill gate.+import agent_observe, rlm_heartbeat+import osrestore_parity_marker = 'namespace-survived'os.mkdir('moved')os.chdir('moved')@@ -137,6 +144,29 @@ def notices_in(request):for text in texts(message.get('content')) if '[python-state-restored]' in text]++def skill_availability(requests):+ preimports = probe_from(requests, SKILL_PROBE)+ system = '\n'.join(text for message in requests[0].get('messages', [])+ if message.get('role') == 'system'+ for text in texts(message.get('content')))+ inventory = re.search(r'<available_skills>(.*?)</available_skills>', system, re.S)+ assert inventory, 'missing actual model-visible skill inventory'+ names = set(re.findall(r'<name>(.*?)</name>', inventory.group(1)))+ return {'preimports': preimports,+ 'model_visible': {name: name in names for name in SKILLS}}+++def validate_skill_availability(runs):+ for label, expected in [('ts', True), ('rust', False)]:+ actual = runs[label]['skill_availability']+ assert actual == {+ 'preimports': {'agent_message': True, 'agent_observe': expected,+ 'rlm_heartbeat': expected},+ 'model_visible': {'agent-message': True, 'agent-observe': expected,+ 'rlm-heartbeat': expected}}, (label, actual)++def run_case(binary, label, root, observation):for name in ('home', 'agent', 'sessions', 'work', 'tmp'):(root / name).mkdir(parents=True)@@ -174,6 +204,7 @@ def run_case(binary, label, root, observation):observation.update(setup_stdout=setup['stdout'], setup_stderr=setup['stderr'],setup_requests=server.requests['setup'],snapshot_ready_before_setup_completion=server.snapshot_ready)+ observation['skill_availability'] = skill_availability(server.requests['setup'])setup_probe = probe_from(server.requests['setup'], 'RESTORE_PARITY_SETUP=')observation['setup'] = setup_probeassert setup_probe == {'cwd': str(cwd / 'moved'), 'env': 'changed'}, setup_probe@@ -245,7 +276,7 @@ def main():'fixture_prerequisites': ['Wait for observable nonempty debounced snapshot before setup final answer in both binaries.','Existing Rust print shutdown disposes descendants but does not await root snapshot; no disposal parity claimed.',- 'Both kernels receive the same pinned TS skills/src library via PYTHONPATH; this is fixture setup, not a production namespace claim.'],+ 'Both kernels receive the same pinned TS skills/src library via PYTHONPATH; initial preimports and prompt inventory are separately asserted before explicit equal restore imports.'],'runs': {}, 'verified': False}try:with tempfile.TemporaryDirectory(prefix='restore-notice-parity-') as temp:@@ -259,6 +290,7 @@ def main():ts, rust = result['runs']['ts'], result['runs']['rust']errors = {label: run['error'] for label, run in result['runs'].items() if 'error' in run}assert not errors, errors+ validate_skill_availability(result['runs'])assert rust['notice'].removesuffix('\n' + RESET) == ts['notice'], 'additional notice difference'assert rust['restored'] == ts['restored'], 'restored state differs'assert rust['request_counts'] == ts['request_counts'] == {'setup': 2, 'resume': 3}@@ -271,6 +303,23 @@ def main():result['error'] = str(error)args.receipt.parent.mkdir(parents=True, exist_ok=True)args.receipt.write_text(json.dumps(result, indent=2) + '\n')+ availability = {+ 'ts_release_archive_sha256': archive_hash,+ 'binaries': result['binaries'],+ 'scope': 'Actual initial print REPL preimports and model-visible inventory, before equal restore fixture imports.',+ 'intended_difference': 'Rust hides unwired agent-observe and rlm-heartbeat; TS print exposes them. agent-message stays visible.',+ 'not_verified': ['RPC/daemon skill availability', 'controller handler operation',+ 'background bash wake/quiescence', 'late-receipt delivery'],+ 'runs': {label: run.get('skill_availability') for label, run in result['runs'].items()},+ 'verified': False,+ }+ try:+ validate_skill_availability(result['runs'])+ availability['verified'] = True+ except Exception as error:+ availability['error'] = str(error)+ args.receipt.with_name('headless_skill_availability.json').write_text(+ json.dumps(availability, indent=2) + '\n')print(json.dumps({'receipt': str(args.receipt), 'verified': result['verified'],'error': result.get('error')}))return 0 if result['verified'] else 1diff --git a/scripts/test_review_late_message_receipt_parity.py b/scripts/test_review_late_message_receipt_parity.pynew file mode 100644index 0000000000..48e127b99e--- /dev/null+++ b/scripts/test_review_late_message_receipt_parity.py@@ -0,0 +1,97 @@+#!/usr/bin/env python3+import ast+import asyncio+import contextlib+import io+import json+from pathlib import Path+import tempfile+import types+import copy+import unittest+from review_late_message_receipt_parity import MESSAGE, PARENT_CELL, late_entries, validate+++class LateReceiptGuards(unittest.TestCase):+ def good(self):+ return {'child_result_seen_before_release': True, 'child_request_count': 2,+ 'parent_request_count': 3, 'parent_session_id': 'fixture-parent',+ 'parent_session_file': '/fixture/parent.jsonl',+ 'spawn_handle': {'rlm_child_id': 'fixture-child', 'session_dir': '/fixture/fixture-child'},+ 'child_header': {'type': 'session', 'id': 'child-durable', 'parentSession': '/fixture/parent.jsonl'},+ 'late_entries': [{'file': '/fixture/fixture-child/child.jsonl', 'entry': {'data': {+ 'toolCallId': 'late_child_cell', 'message': {'id': 'fixture-id',+ 'message': MESSAGE, 'receiverRole': 'parent', 'deliveryStatus': 'queued',+ 'target': {'sessionId': 'fixture-parent', 'activeSessionId': 'fixture-parent'}}}}}]}++ def test_spawn_handle_cell_serializes_actual_path_objects(self):+ async def spawn(*args, **kwargs):+ return types.SimpleNamespace(rlm_child_id='child-fixture',+ session_dir=Path('/fixture/child-fixture'))+ code = compile(PARENT_CELL, 'spawn-cell', 'exec', flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)+ output = io.StringIO()+ with contextlib.redirect_stdout(output):+ asyncio.run(eval(code, {'rlm': types.SimpleNamespace(spawn=spawn)}))+ self.assertEqual(json.loads(output.getvalue().strip().removeprefix('LATE_SPAWN_HANDLE=')),+ {'rlm_child_id': 'child-fixture', 'session_dir': '/fixture/child-fixture'})++ def test_blank_and_partial_jsonl_are_not_complete_receipts(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / 'child.jsonl'+ row = {'type': 'custom', 'customType': 'ipython_sent_agent_message', 'data': {}}+ path.write_text('\n' + json.dumps(row) + '\n' + '{"partial":')+ self.assertEqual(late_entries(Path(directory)), [{'file': str(path), 'entry': row}])+ path.write_text('{malformed complete row}\n')+ with self.assertRaises(json.JSONDecodeError):+ late_entries(Path(directory))++ def test_runtime_and_durable_parent_ids_may_differ(self):+ changed = self.good()+ changed['late_entries'][0]['entry']['data']['message']['target']['activeSessionId'] = 'runtime-parent'+ self.assertEqual(validate(changed), validate(self.good()))+ for active_id in ['', ' ', None, 42]:+ changed['late_entries'][0]['entry']['data']['message']['target']['activeSessionId'] = active_id+ with self.assertRaises(AssertionError):+ validate(changed)+ del changed['late_entries'][0]['entry']['data']['message']['target']['activeSessionId']+ with self.assertRaises(AssertionError):+ validate(changed)++ def test_actual_late_payload_and_readiness_are_required(self):+ validate(self.good())+ for key, value in [('child_result_seen_before_release', False),+ ('child_request_count', 1), ('parent_request_count', 1),+ ('late_entries', [])]:+ changed = {**self.good(), key: value}+ with self.assertRaises(AssertionError):+ validate(changed)+ for key, value in [('message', 'foreign'), ('receiverRole', 'child'),+ ('deliveryStatus', 'failed'), ('id', '')]:+ changed = self.good()+ changed['late_entries'][0]['entry']['data']['message'][key] = value+ with self.assertRaises(AssertionError):+ validate(changed)+ changed = self.good()+ changed['late_entries'][0]['entry']['data']['message']['target']['sessionId'] = 'foreign'+ with self.assertRaises(AssertionError):+ validate(changed)+ changed = self.good()+ changed['late_entries'].append(copy.deepcopy(changed['late_entries'][0]))+ with self.assertRaises(AssertionError):+ validate(changed)+ changed = self.good()+ changed['late_entries'][0]['file'] = '/fixture/foreign/child.jsonl'+ with self.assertRaises(AssertionError):+ validate(changed)+ changed = self.good()+ changed['child_header']['parentSession'] = '/fixture/foreign-parent.jsonl'+ with self.assertRaises(AssertionError):+ validate(changed)+ changed = self.good()+ changed['late_entries'][0]['entry']['data']['toolCallId'] = 'historical'+ with self.assertRaises(AssertionError):+ validate(changed)+++if __name__ == '__main__':+ unittest.main()diff --git a/scripts/test_review_print_bash_parity.py b/scripts/test_review_print_bash_parity.pynew file mode 100644index 0000000000..a650ca6223--- /dev/null+++ b/scripts/test_review_print_bash_parity.py@@ -0,0 +1,35 @@+#!/usr/bin/env python3+import copy+import unittest+from review_print_bash_parity import validate, validate_ts+++class PrintBashGuards(unittest.TestCase):+ def test_requires_release_after_first_turn_and_one_real_completion(self):+ good = {'first_turn_ended_before_release': True, 'request_count': 4,+ 'finished': {'completed': True}, 'notice': {+ 'exit_code': 0, 'display': True, 'matches_started_pid': True}}+ validate(good)+ for key, value in [('first_turn_ended_before_release', False),+ ('request_count', 2), ('request_count', 5),+ ('finished', {'completed': False})]:+ changed = {**copy.deepcopy(good), key: value}+ with self.assertRaises(AssertionError):+ validate(changed)+ for key, value in [('exit_code', 1), ('display', False), ('matches_started_pid', False)]:+ changed = copy.deepcopy(good)+ changed['notice'][key] = value+ with self.assertRaises(AssertionError):+ validate(changed)++ def test_ts_print_exits_after_its_first_turn_without_a_notice(self):+ exited = {'first_turn_ended_before_release': True, 'request_count': 2, 'notice_count': 0,+ 'gate_timed_out': False}+ validate_ts(exited)+ for key, value in [('request_count', 4), ('notice_count', 1), ('gate_timed_out', True)]:+ with self.assertRaises(AssertionError):+ validate_ts({**exited, key: value})+++if __name__ == '__main__':+ unittest.main()diff --git a/scripts/test_review_restore_notice_parity.py b/scripts/test_review_restore_notice_parity.pynew file mode 100644index 0000000000..c097d08dd7--- /dev/null+++ b/scripts/test_review_restore_notice_parity.py@@ -0,0 +1,47 @@+#!/usr/bin/env python3+"""Guard scope separation between initial headless availability and restored state."""+import copy+import unittest++from review_restore_notice_parity import SKILL_PROBE, skill_availability, validate_skill_availability+++def run(available):+ return {'skill_availability': {+ 'preimports': {'agent_message': True, 'agent_observe': available,+ 'rlm_heartbeat': available},+ 'model_visible': {'agent-message': True, 'agent-observe': available,+ 'rlm-heartbeat': available}}}+++class AvailabilityTests(unittest.TestCase):+ def test_declared_initial_difference_is_exact(self):+ validate_skill_availability({'ts': run(True), 'rust': run(False)})++ def test_unexpected_inventory_or_preimport_changes_fail(self):+ for label in ['ts', 'rust']:+ for kind in ['preimports', 'model_visible']:+ for name in run(True)['skill_availability'][kind]:+ rows = {'ts': run(True), 'rust': run(False)}+ actual = rows[label]['skill_availability'][kind]+ actual[name] = not actual[name]+ with self.assertRaises(AssertionError):+ validate_skill_availability(rows)++ def test_observation_uses_actual_tool_result_and_inventory(self):+ requests = [+ {'messages': [{'role': 'system', 'content': '<available_skills><skill><name>agent-message</name></skill></available_skills>'}]},+ {'messages': [{'role': 'tool', 'content': SKILL_PROBE + '{"agent_message":true,"agent_observe":false,"rlm_heartbeat":false}'}]}]+ self.assertEqual(skill_availability(requests), run(False)['skill_availability'])+ broken = copy.deepcopy(requests)+ broken[0]['messages'][0]['content'] = 'agent-message'+ with self.assertRaises(AssertionError):+ skill_availability(broken)+ broken = copy.deepcopy(requests)+ broken[1]['messages'][0]['role'] = 'assistant'+ with self.assertRaises(AssertionError):+ skill_availability(broken)+++if __name__ == '__main__':+ unittest.main()