A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
acp: TypeScript-parity follow-up to #3264 (subagent/refine/agent-message updates, stop failures, MCP owner, input pause) (#3348)
Sebastian Müllerda8a80a52921
diff --git a/crates/pa-cli/src/print_boundary/tests.rs b/crates/pa-cli/src/print_boundary/tests.rsindex 1d3e0339d5..0403bbaac6 100644--- a/crates/pa-cli/src/print_boundary/tests.rs+++ b/crates/pa-cli/src/print_boundary/tests.rs@@ -115,6 +115,7 @@ async fn faux_engine_with_telemetry(}).expect("a session manager");let engine = create_session(SessionEngineConfig {+ on_late_sent_agent_message: None,semantic_edges: None,cron_store: None,steering_mode: None,diff --git a/crates/pa-cli/src/print_goal.rs b/crates/pa-cli/src/print_goal.rsindex f66b2c5fb4..5a560aced9 100644--- a/crates/pa-cli/src/print_goal.rs+++ b/crates/pa-cli/src/print_goal.rs@@ -896,6 +896,7 @@ mod tests {let engine = Arc::new(pa_core::session_engine::engine::create_session(pa_core::session_engine::engine::SessionEngineConfig {+ on_late_sent_agent_message: None,semantic_edges: None,cron_store: None,telemetry: None,@@ -1459,6 +1460,7 @@ mod tests {let engine = Arc::new(pa_core::session_engine::engine::create_session(pa_core::session_engine::engine::SessionEngineConfig {+ on_late_sent_agent_message: None,semantic_edges: None,cron_store: None,telemetry: None,diff --git a/crates/pa-cli/src/print_runtime.rs b/crates/pa-cli/src/print_runtime.rsindex 96a2b2be53..9fc625607c 100644--- a/crates/pa-cli/src/print_runtime.rs+++ b/crates/pa-cli/src/print_runtime.rs@@ -639,6 +639,7 @@ async fn build_headless_engine_with();let engine = pa_core::session_engine::engine::create_session(pa_core::session_engine::engine::SessionEngineConfig {+ on_late_sent_agent_message: None,cron_store: None,semantic_edges,telemetry,@@ -1730,6 +1731,7 @@ async fn build_faux_engine_with(// tests can verify persistence without the network.let engine = pa_core::session_engine::engine::create_session(pa_core::session_engine::engine::SessionEngineConfig {+ on_late_sent_agent_message: None,cron_store: None,// Faux verification harness: no product telemetry.semantic_edges: None,diff --git a/crates/pa-cli/src/print_session_command.rs b/crates/pa-cli/src/print_session_command.rsindex 40bcc82403..b0f4425bc0 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 {let engine = Arc::new(pa_core::session_engine::engine::create_session(pa_core::session_engine::engine::SessionEngineConfig {+ on_late_sent_agent_message: None,semantic_edges: None,cron_store: None,telemetry: None,diff --git a/crates/pa-cli/tests/acp_mode_e2e.rs b/crates/pa-cli/tests/acp_mode_e2e.rsindex 52fdf4e1b7..08794441ea 100644--- a/crates/pa-cli/tests/acp_mode_e2e.rs+++ b/crates/pa-cli/tests/acp_mode_e2e.rs@@ -771,6 +771,118 @@ fn acp_mcp_long_names_fail_at_tool_derivation_with_internal_error() {);}+#[test]+fn acp_daemon_attached_close_clears_the_connection_mcp_servers() {+ let script = json!({ "engine": "faux", "responses": ["unused"] });+ let mut client = AcpChild::spawn(&["--mode", "acp", "--no-session"], &script);+ let socket = client.socket.clone();+ let init = client.request("initialize", &initialize_params());+ let _ = client.wait_response(init, TIMEOUT);+ let new = client.request(+ "session/new",+ &json!({ "mcpServers": [+ { "name": "close-clear", "type": "http", "url": "https://mcp.invalid/close-clear", "headers": [] },+ ]}),+ );+ let (new_response, _) = client.wait_response(new, TIMEOUT);+ let session_id = new_response["result"]["sessionId"]+ .as_str()+ .expect("admission succeeds")+ .to_string();+ let active_session_id = wait_live_session(&socket)["activeSessionId"]+ .as_str()+ .expect("the daemon session id")+ .to_string();+ let owned = probe_acp_mcp_servers(&socket, &active_session_id);+ assert_eq!(+ owned["success"], false,+ "the open session owns its admitted servers: {owned}"+ );+ assert_eq!(+ owned["error"],+ "ACP MCP configuration is owned by another client"+ );+ let close = client.request("session/close", &json!({ "sessionId": session_id }));+ let (close_response, _) = client.wait_response(close, TIMEOUT);+ assert_eq!(close_response["result"], json!({}));+ let released = probe_acp_mcp_servers(&socket, &active_session_id);+ assert_eq!(+ released["success"], true,+ "session/close released the connection's servers: {released}"+ );+}++#[test]+fn acp_daemon_attached_eof_teardown_clears_the_connection_mcp_servers() {+ let script = json!({ "engine": "faux", "responses": ["unused"] });+ let mut client = AcpChild::spawn(&["--mode", "acp"], &script);+ let socket = client.socket.clone();+ let init = client.request("initialize", &initialize_params());+ let _ = client.wait_response(init, TIMEOUT);+ let new = client.request(+ "session/new",+ &json!({ "mcpServers": [+ { "name": "eof-clear", "type": "http", "url": "https://mcp.invalid/eof-clear", "headers": [] },+ ]}),+ );+ let (new_response, _) = client.wait_response(new, TIMEOUT);+ assert!(+ new_response["result"]["sessionId"].is_string(),+ "admission succeeds: {new_response}"+ );+ let active_session_id = wait_live_session(&socket)["activeSessionId"]+ .as_str()+ .expect("the daemon session id")+ .to_string();+ let owned = probe_acp_mcp_servers(&socket, &active_session_id);+ assert_eq!(+ owned["success"], false,+ "the open session owns its admitted servers: {owned}"+ );+ client.close_stdin();+ assert!(client.child.wait().expect("the ACP child exits").success());+ let released = probe_acp_mcp_servers(&socket, &active_session_id);+ assert_eq!(+ released["success"], true,+ "the EOF teardown released the connection's servers: {released}"+ );+}++#[test]+fn acp_mode_daemon_unreachable_exits_1_without_fallback() {+ let home = tempfile::TempDir::new().unwrap();+ let socket = home.path().join("daemon.sock");+ std::fs::write(&socket, "not a socket").unwrap();+ std::fs::write(+ home.path().join("worker-script.json"),+ json!({ "engine": "faux", "responses": ["unused"] }).to_string(),+ )+ .unwrap();+ let output = daemon_attached_command(home.path(), &socket, &["--mode", "acp", "--no-session"])+ .output()+ .expect("binary present");+ assert_eq!(+ output.status.code(),+ Some(1),+ "exit 1: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(+ output.stdout.is_empty(),+ "no ACP frames on stdout: {}",+ String::from_utf8_lossy(&output.stdout)+ );+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("Error: "),+ "the startup failure is an error line: {stderr}"+ );+ assert!(+ stderr.contains("Timed out waiting for the Prime Agent daemon to start"),+ "the daemon never became reachable: {stderr}"+ );+}+#[test]fn acp_daemon_attached_cancels_mid_turn() {// A scripted worker with a slow turn: the cancel lands while the@@ -947,6 +1059,41 @@ fn live_sessions(socket: &std::path::Path) -> Vec<Value> {.clone()}+fn probe_acp_mcp_servers(socket: &std::path::Path, active_session_id: &str) -> Value {+ daemon_request(+ socket,+ "acp-mcp-replace",+ &json!({+ "type": "replace_acp_mcp_servers",+ "activeSessionId": active_session_id,+ "ownerId": "acp-e2e-probe",+ "servers": [{+ "type": "http",+ "name": "probe",+ "url": "https://mcp.invalid/probe",+ "headers": {},+ }],+ }),+ )+}++fn wait_live_session(socket: &std::path::Path) -> Value {+ let deadline = Instant::now() + TIMEOUT;+ loop {+ let sessions = live_sessions(socket);+ if let Some(session) = sessions.first() {+ return session.clone();+ }+ let timeout_left = deadline.saturating_duration_since(Instant::now());+ assert!(+ !timeout_left.is_zero(),+ "no daemon session ever registered on {}",+ socket.display()+ );+ std::thread::sleep(Duration::from_millis(50));+ }+}+#[test]fn acp_daemon_attached_default_session_persists_and_resumes() {// Without --no-session the daemon session is saved and resident: it@@ -2308,3 +2455,112 @@ fn acp_user_bash_maps_to_a_synthetic_tool_call() {});assert!(end["params"]["update"].get("content").is_none(), "{end}");}++#[cfg(unix)]+#[test]+fn acp_daemon_attached_close_stop_failure_fences_the_session() {+ let mut client = AcpChild::spawn(+ &["--mode", "acp", "--no-session"],+ &json!({ "engine": "faux", "responses": ["unused"] }),+ );+ let session_id = initialize_and_new_session(&mut client);+ let probe =+ pa_types::platform::transport::connect_blocking(&client.socket).expect("daemon socket");+ let reader = probe.try_clone_box().expect("daemon socket clone");+ let _ = reader.set_read_timeout(Duration::from_mins(2));+ let hello = BufReader::new(reader)+ .lines()+ .map(|line| {+ serde_json::from_str::<Value>(&line.expect("daemon line")).expect("daemon JSON")+ })+ .find(|frame| frame["type"] == json!("daemon_hello"))+ .expect("the daemon closed without a hello");+ let pid = hello["supervisorPid"].as_u64().expect("supervisor pid");+ drop(probe);+ let killed = std::process::Command::new("kill")+ .args(["-9", &pid.to_string()])+ .status()+ .expect("kill the supervisor");+ assert!(killed.success(), "the supervisor crash did not run");++ let close = client.request("session/close", &json!({ "sessionId": session_id }));+ let (close_response, _) = client.wait_response(close, TIMEOUT);+ assert_eq!(+ close_response["error"]["code"], -32603,+ "the failed stop errors the close: {close_response}"+ );+ let stop_failure = close_response["error"]["data"]["details"]+ .as_str()+ .unwrap_or_default()+ .to_string();+ assert!(+ stop_failure.contains("the daemon connection"),+ "the stop error is the fence's message: {stop_failure}"+ );++ let prompt = client.request(+ "session/prompt",+ &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "after the failed stop" }] }),+ );+ let (prompt_response, _) = client.wait_response(prompt, TIMEOUT);+ assert_eq!(+ prompt_response["error"]["data"]["details"],+ format!("ACP session stop failed: {stop_failure}"),+ "a prompt while the stop failed answers the TS fence: {prompt_response}"+ );++ let refused = client.request("session/new", &json!({ "mcpServers": [] }));+ let (refused_response, _) = client.wait_response(refused, TIMEOUT);+ assert_eq!(+ refused_response["error"]["data"]["details"],+ "prime-agent ACP mode hosts one session per connection; start another prime-agent process for a second session",+ "the close-failed session keeps the single-session slot: {refused_response}"+ );++ let close_again = client.request("session/close", &json!({ "sessionId": session_id }));+ let (again_response, _) = client.wait_response(close_again, TIMEOUT);+ assert_eq!(again_response["error"]["code"], -32603);+ assert_ne!(+ again_response["error"]["data"]["details"],+ format!("Unknown ACP session: {session_id}"),+ "the session stays bound after the failed close: {again_response}"+ );+ drop(client);+}++#[test]+fn acp_daemon_attached_close_holds_the_input_pause_until_the_next_session_new() {+ let mut client = AcpChild::spawn(+ &["--mode", "acp", "--no-session"],+ &json!({ "engine": "faux", "responses": ["first", { "text": "FOREIGN", "delayMs": 150_000 }] }),+ );+ let socket = client.socket.clone();+ let session_id = initialize_and_new_session(&mut client);+ assert_prompt_ends_turn(&mut client, &session_id, "one");++ let close = client.request("session/close", &json!({ "sessionId": session_id }));+ let (close_response, _) = client.wait_response(close, TIMEOUT);+ assert_eq!(close_response["result"], json!({}));++ let active_session_id = live_sessions(&socket)[0]["activeSessionId"]+ .as_str()+ .expect("the resident session")+ .to_string();+ let _ = daemon_request(+ &socket,+ "foreign-follow-up",+ &json!({ "type": "follow_up", "activeSessionId": active_session_id, "message": "foreign" }),+ );+ let idle = daemon_request(+ &socket,+ "foreign-idle",+ &json!({ "type": "wait_for_idle", "activeSessionId": active_session_id }),+ );+ assert!(+ idle["success"] == json!(true),+ "no foreign turn runs on the resident session while the close holds the input pause: {idle}"+ );++ let _second = new_session(&mut client);+ drop(client);+}diff --git a/crates/pa-core/src/lib.rs b/crates/pa-core/src/lib.rsindex dda352b185..af564faa9f 100644--- a/crates/pa-core/src/lib.rs+++ b/crates/pa-core/src/lib.rs@@ -61,9 +61,10 @@ pub use tools::edit::{// ipython tool: definition + kernel lifecycle seam (RLM bootstrap included).pub use tools::ipython::{- create_ipython_tool_definition, ExecuteResult, ExecuteStatus, IpythonKernelProvisioner,- IpythonToolOptions, IpythonToolUi, KernelAttachment, KernelBusyAfterInterruptError,- KernelErrorInfo, KernelExecError, KernelExecutor,+ create_ipython_tool_definition, sent_agent_message_json, ExecuteResult, ExecuteStatus,+ IpythonKernelProvisioner, IpythonToolOptions, IpythonToolUi, KernelAttachment,+ KernelBusyAfterInterruptError, KernelErrorInfo, KernelExecError, KernelExecutor,+ LateSentAgentMessageHandler,};pub use tools::rlm_bootstrap::{build_rlm_bootstrap_code, PythonSkillRuntimeInfo};// RLM kernel subsystem: persistent IPython kernel lifecycle.diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rsindex fb8a53ab23..887d6c40cc 100644--- a/crates/pa-core/src/session_engine/engine.rs+++ b/crates/pa-core/src/session_engine/engine.rs@@ -129,6 +129,7 @@ pub struct SessionEngineConfig {/// spawn provenance. `None` keeps the session off the ledger (no/// request ids on the wire).pub semantic_edges: Option<super::semantic_edges::SemanticEdgeIdentity>,+ pub on_late_sent_agent_message: Option<crate::tools::ipython::LateSentAgentMessageHandler>,}/// An assembled, running session.@@ -495,7 +496,10 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Sif !tools.iter().any(|tool| tool.name() == "ipython") {let definition = crate::tools::ipython::create_ipython_tool_definition(&cwd.to_string_lossy(),- super::runtime_wiring::ipython_tool_options(provisioner.clone()),+ super::runtime_wiring::ipython_tool_options(+ provisioner.clone(),+ config.on_late_sent_agent_message.clone(),+ ),);tools.push(Arc::new(crate::session_engine::tool_bridge::ToolDefinitionBridge::new(definition),diff --git a/crates/pa-core/src/session_engine/engine/tests.rs b/crates/pa-core/src/session_engine/engine/tests.rsindex c9bfb24223..ab94a8a112 100644--- a/crates/pa-core/src/session_engine/engine/tests.rs+++ b/crates/pa-core/src/session_engine/engine/tests.rs@@ -55,6 +55,7 @@ async fn engine_runs_tool_loop_and_persists() {let cwd = tmp.path().join("project");std::fs::create_dir_all(&cwd).unwrap();let engine = create_session(SessionEngineConfig {+ on_late_sent_agent_message: None,semantic_edges: None,cron_store: None,queued_steering_probe: None,@@ -155,6 +156,7 @@ async fn spawned_child_prompt_stamps_its_depth() {let cwd = tmp.path().join("project");std::fs::create_dir_all(&cwd).unwrap();let engine = create_session(SessionEngineConfig {+ on_late_sent_agent_message: None,semantic_edges: None,cron_store: None,queued_steering_probe: None,@@ -222,6 +224,7 @@ async fn oauth_creds_unlock_generic_mcp_gating_in_new_sessions() {stream_fn: pa_agent::stream::StreamFn,) -> SessionEngineConfig {SessionEngineConfig {+ on_late_sent_agent_message: None,semantic_edges: None,cron_store: None,queued_steering_probe: None,diff --git a/crates/pa-core/src/session_engine/runtime_wiring.rs b/crates/pa-core/src/session_engine/runtime_wiring.rsindex 8eaca9b1a2..c9523f8173 100644--- a/crates/pa-core/src/session_engine/runtime_wiring.rs+++ b/crates/pa-core/src/session_engine/runtime_wiring.rs@@ -317,12 +317,14 @@ impl KernelExecutor for KernelManagerExecutor {let manager = self.manager.clone();let code = code.to_string();let signal = options.signal;+ let on_late_sent_agent_message = options.on_late_sent_agent_message;Box::pin(async move {let result = manager.execute(&code,crate::kernel::shared::ExecuteOptions {signal: signal.map(crate::kernel::cancellation::AbortSignal::from_token),+ on_late_sent_agent_message,..Default::default()},)@@ -376,9 +378,13 @@ fn convert_execute_result(/// Build the ipython tool options for a wired kernel provisioner.#[must_use]-pub fn ipython_tool_options(provisioner: Arc<KernelProvisioner>) -> IpythonToolOptions {+pub fn ipython_tool_options(+ provisioner: Arc<KernelProvisioner>,+ on_late_sent_agent_message: Option<crate::tools::ipython::LateSentAgentMessageHandler>,+) -> IpythonToolOptions {IpythonToolOptions {provisioner,ui: None,+ on_late_sent_agent_message,}}diff --git a/crates/pa-core/src/tools/golden_replay.rs b/crates/pa-core/src/tools/golden_replay.rsindex 34d0b3c0cf..344c10f387 100644--- a/crates/pa-core/src/tools/golden_replay.rs+++ b/crates/pa-core/src/tools/golden_replay.rs@@ -561,10 +561,16 @@ async fn golden_ipython_group_matches_ts() {} else {None},+ on_late_sent_agent_message: None,};- let result =- ipython::execute_ipython(&options, case["code"].as_str().expect("code"), None, None)- .await;+ let result = ipython::execute_ipython(+ &options,+ case["code"].as_str().expect("code"),+ None,+ None,+ None,+ )+ .await;let recorded = &case["result"];match result {Ok(result) => {@@ -625,6 +631,7 @@ fn golden_schema_group_matches_ts() {"ipython" => crate::tools::ipython::create_ipython_tool_definition("/tmp",IpythonToolOptions {+ on_late_sent_agent_message: None,provisioner: Arc::new(MockProvisioner {kernel: Arc::new(MockKernel {executions: Mutex::new(Vec::new()),diff --git a/crates/pa-core/src/tools/ipython.rs b/crates/pa-core/src/tools/ipython.rsindex 02b2a32a02..cdf83b136a 100644--- a/crates/pa-core/src/tools/ipython.rs+++ b/crates/pa-core/src/tools/ipython.rs@@ -73,6 +73,7 @@ pub struct ExecuteResult {/// The wire form of one sent agent message (TS `KernelSentAgentMessage`):/// `id`, `message`, `deliveryStatus`, `receiverRole` when present, and the/// `target` endpoint (`sessionName` only when present).+#[must_use]pub fn sent_agent_message_json(sent: &crate::kernel::shared::KernelSentAgentMessage,) -> serde_json::Value {@@ -162,10 +163,14 @@ impl KernelExecError {/// Options for one kernel execute call.pub type StreamFn<'a> = Option<&'a (dyn Fn(&str, &'static str) + Send + Sync)>;+pub type LateSentAgentMessageHandler =+ std::sync::Arc<dyn Fn(&str, crate::kernel::shared::KernelSentAgentMessage) + Send + Sync>;+pub struct KernelExecuteOptions<'a> {pub signal: Option<AbortSignal>,/// Streams cell output while the cell runs.pub on_stream: StreamFn<'a>,+ pub on_late_sent_agent_message: Option<crate::kernel::shared::LateSentAgentMessageCallback>,}type ExecuteCellFuture =@@ -284,30 +289,34 @@ async fn execute_with_busy_kernel_choice(provisioner: &dyn IpythonKernelProvisioner,report_startup_progress: &BootstrapProgressHandler,code: &str,- signal: Option<AbortSignal>,- on_stream: StreamFn<'_>,+ execute: KernelExecuteOptions<'_>,on_working_message: &(dyn Fn(Option<&str>) + Send + Sync),ui: Option<&Arc<dyn IpythonToolUi>>,) -> Result<(ExecuteResult, bool), KernelExecError> {let mut kernel_restarted = false;loop {let manager = provisioner- .ensure(Some(report_startup_progress.clone()), signal.clone())+ .ensure(+ Some(report_startup_progress.clone()),+ execute.signal.clone(),+ ).await.map_err(KernelExecError::Other)?;let result = manager.execute(code,KernelExecuteOptions {- signal: signal.clone(),- on_stream,+ signal: execute.signal.clone(),+ on_stream: execute.on_stream,+ on_late_sent_agent_message: execute.on_late_sent_agent_message.clone(),},).await;match result {Ok(result) => return Ok((result, kernel_restarted)),Err(err) => {- let aborted = signal+ let aborted = execute+ .signal.as_ref().is_some_and(tokio_util::sync::CancellationToken::is_cancelled);if !err.is_busy_after_interrupt() || aborted {@@ -321,7 +330,7 @@ async fn execute_with_busy_kernel_choice(.select(&busy_kernel_prompt(),&[BUSY_KERNEL_WAIT_CHOICE, BUSY_KERNEL_KILL_CHOICE],- signal.as_ref(),+ execute.signal.as_ref(),).await;match choice.as_deref() {@@ -346,6 +355,7 @@ pub struct IpythonToolOptions {pub provisioner: Arc<dyn IpythonKernelProvisioner>,/// UI surface; `None` in headless sessions.pub ui: Option<Arc<dyn IpythonToolUi>>,+ pub on_late_sent_agent_message: Option<LateSentAgentMessageHandler>,}pub fn ipython_tool_schema() -> serde_json::Value {@@ -369,7 +379,7 @@ pub fn ipython_tool_description() -> &'static str {#[tracing::instrument(level = "debug",name = "tool_ipython_execute",- skip(options, on_update)+ skip(options, on_update, on_late_sent_agent_message)fields(code),)]pub async fn execute_ipython(@@ -377,6 +387,7 @@ pub async fn execute_ipython(code: &str,signal: Option<AbortSignal>,on_update: Option<OnUpdate>,+ on_late_sent_agent_message: Option<crate::kernel::shared::LateSentAgentMessageCallback>,) -> anyhow::Result<ToolExecutionResult> {let set_tool_working_message = |message: Option<&str>| {if let Some(ui) = &options.ui {@@ -415,8 +426,11 @@ pub async fn execute_ipython(options.provisioner.as_ref(),&report_startup_progress,code,- signal,- Some(&stream_update),+ KernelExecuteOptions {+ signal,+ on_stream: Some(&stream_update),+ on_late_sent_agent_message,+ },&|message| {set_tool_working_message(message);},@@ -500,15 +514,29 @@ pub fn create_ipython_tool_definition(_cwd: &str, options: IpythonToolOptions) -let options = Arc::new(options);let execute: crate::tools::tool_definition::ExecuteFn = {let options = options;- Arc::new(move |_tool_call_id, params, signal, on_update| {+ Arc::new(move |tool_call_id, params, signal, on_update| {let options = options.clone();+ let on_late_sent_agent_message =+ options.on_late_sent_agent_message.as_ref().map(|handler| {+ let handler = std::sync::Arc::clone(handler);+ let tool_call_id = tool_call_id.to_string();+ std::sync::Arc::new(move |message| handler(&tool_call_id, message))+ as crate::kernel::shared::LateSentAgentMessageCallback+ });Box::pin(async move {let code = params.get("code").and_then(serde_json::Value::as_str).ok_or_else(|| anyhow::anyhow!("ipython tool requires a code string"))?.to_string();- execute_ipython(&options, &code, signal, on_update).await+ execute_ipython(+ &options,+ &code,+ signal,+ on_update,+ on_late_sent_agent_message,+ )+ .await})})};diff --git a/crates/pa-core/tests/abort_kernel_cell.rs b/crates/pa-core/tests/abort_kernel_cell.rsindex 7f10e87313..a1e73cb6d6 100644--- a/crates/pa-core/tests/abort_kernel_cell.rs+++ b/crates/pa-core/tests/abort_kernel_cell.rs@@ -153,6 +153,7 @@ async fn abort_during_a_kernel_cell_settles_the_turn_immediately() {provider.push_text_turn("the cell completed");let engine = create_session(SessionEngineConfig {+ on_late_sent_agent_message: None,semantic_edges: None,cron_store: None,steering_mode: None,diff --git a/crates/pa-core/tests/turn_boundary_kernel.rs b/crates/pa-core/tests/turn_boundary_kernel.rsindex e030b82dde..4b5ceb44a0 100644--- a/crates/pa-core/tests/turn_boundary_kernel.rs+++ b/crates/pa-core/tests/turn_boundary_kernel.rs@@ -193,6 +193,7 @@ async fn turn_boundary_host_requests_round_trip_through_a_real_kernel() {provider.push_text_turn("boundary reached");let engine = create_session(SessionEngineConfig {+ on_late_sent_agent_message: None,semantic_edges: None,cron_store: None,queued_steering_probe: None,diff --git a/crates/pa-daemon/src/acp/daemon.rs b/crates/pa-daemon/src/acp/daemon.rsindex 341e0c0b6d..b884bd8052 100644--- a/crates/pa-daemon/src/acp/daemon.rs+++ b/crates/pa-daemon/src/acp/daemon.rs@@ -171,6 +171,16 @@ impl DaemonLink {self.exchange(command, Some(REQUEST_TIMEOUT)).await}+ pub(crate) async fn request_ok(&self, command: DaemonCommand) -> anyhow::Result<()> {+ let response = self.request(command).await?;+ if !response.success {+ anyhow::bail!(response+ .error+ .unwrap_or_else(|| "unknown error".to_string()));+ }+ Ok(())+ }+/// Send one command envelope with no fixed cap: the response or the/// link close ends the wait (turn-long commands — declared/// divergence, TS caps them at 24 h; the link-close signal is the@@ -248,10 +258,11 @@ struct DaemonBinding {/// The create's `client_owned` lifecycle (`--no-session`): the/// session ends with the connection.client_owned: bool,+ mcp_owner_id: String,}-/// The hosted daemon session: the ACP identity, the daemon routing id, the-/// update producer, and the per-connection MCP owner state.+/// The hosted daemon session: the ACP identity, the daemon routing id,+/// the update producer, and the stop state.pub(crate) struct HostedSession {pub(crate) acp_session_id: String,pub(crate) daemon_active_session_id: String,@@ -259,15 +270,19 @@ pub(crate) struct HostedSession {/// The picker state (TS `AcpSessionEntry`'s configOptions/models) and/// the serialized config queue (`configTask`).pub(crate) config: Arc<HostedConfig>,- mcp_owner_id: String,- mcp_server_names: Vec<String>,+ cancelling: bool,+ stop_failure: Option<String>,+ input_pause_key: Option<String>,+ input_pause_id: Option<String>,+ cancel_task: Option<tokio::sync::watch::Receiver<bool>>,/// The running prompt turn; one at a time. A cancelled turn keeps- /// the slot until its stop sequence finishes (TS `entry.cancelling`).+ /// the slot until its cancel stop finishes.turn: Option<ActiveTurn>,/// The newest assistant stop reason observed on the event stream.assistant_stop_reason: Option<String>,/// The event mapping state lives and dies with the session, like TS.mapping: WireMappingState,+ observed_children: std::collections::HashSet<String>,}struct ActiveTurn {@@ -275,9 +290,6 @@ struct ActiveTurn {admission_id: String,/// TS the per-turn `AbortController`.cancelled: bool,- /// Resolves when the stop sequence finished; the cancelled turn's- /// response waits for it, so the next prompt never sees "cancelling".- stop_done_rx: Option<oneshot::Receiver<()>>,}/// The ACP transport state: one hosted session at most.@@ -285,7 +297,10 @@ struct ActiveTurn {pub(crate) struct DaemonAcpState {pub(crate) session: Option<HostedSession>,pub(crate) session_new_in_flight: bool,- pub(crate) session_close_in_flight: bool,+ pub(crate) session_close_done: Option<tokio::sync::watch::Receiver<bool>>,+ pub(crate) closed_input_pause_id: Option<String>,+ pub(crate) closed_input_pause_key: Option<String>,+ pub(crate) mcp_server_names: Vec<String>,}/// Serve the daemon-attached ACP mode until stdin closes. The caller@@ -352,6 +367,16 @@ pub async fn run_daemon_attached_acp_mode(options: DaemonAcpOptions) -> anyhow::if let Some(stop) = wire_events::assistant_stop(&event) {current.assistant_stop_reason = stop.stop_reason;}+ if event.get("type").and_then(Value::as_str) == Some("rlm_child_update")+ {+ if let Some(id) = event+ .get("child")+ .and_then(|child| child.get("id"))+ .and_then(Value::as_str)+ {+ current.observed_children.insert(id.to_string());+ }+ }let turn_id = current.producer.active_prompt_turn().await;for update in wire_events::wire_updates(&event, &mut current.mapping) {let _ = current@@ -495,20 +520,40 @@ pub async fn run_daemon_attached_acp_mode(options: DaemonAcpOptions) -> anyhow::.await;});}- // A refused prompt answers from the prefix; the running turn- // is untouched.+ // A refused prompt or close answers from the prefix; the+ // running turn is untouched.FrameOrder::Refused { id, message } => {let _ = tx.send(super::internal_error(&id, &message));}- // A cancel arms the stop task (the notification form has no- // response).- FrameOrder::Cancel(stop) => {- if let Some(stop) = stop {- let link = Arc::clone(&link);- tokio::spawn(async move {- run_cancel_stop(stop, &link).await;- });- }+ FrameOrder::Close { id, params, done } => {+ let link = Arc::clone(&link);+ let state = Arc::clone(&state);+ let options_tx = tx.clone();+ let owner_id = binding.mcp_owner_id.clone();+ tokio::spawn(async move {+ handle_session_close(id, params, &link, &state, options_tx, done, owner_id)+ .await;+ });+ }+ FrameOrder::Cancel(order) => {+ let link = Arc::clone(&link);+ let state = Arc::clone(&state);+ tokio::spawn(async move {+ let mut order = order;+ loop {+ order = match order {+ CancelOrder::None => return,+ CancelOrder::Armed(stop) => {+ run_cancel_stop(stop, &link, &state).await;+ return;+ }+ CancelOrder::WaitForClose { session_id } => {+ wait_for_session_close(&state).await;+ cancel_order(&json!({ "sessionId": session_id }), &state).await+ }+ };+ }+ });}}// Reap finished prompt handlers.@@ -516,6 +561,9 @@ pub async fn run_daemon_attached_acp_mode(options: DaemonAcpOptions) -> anyhow::}handlers.shutdown().await;+ // A close frame is reserved synchronously but its stop runs detached.+ // Let it finish before EOF teardown takes the hosted session away.+ wait_for_session_close(&state).await;teardown(&link, &state, &binding).await;drop(tx);let _ = writer.await;@@ -550,6 +598,7 @@ async fn bind_daemon_session(.unwrap_or_default().to_string(),client_owned,+ mcp_owner_id: uuid::Uuid::new_v4().to_string(),};let attached = link.request(DaemonCommand::Attach {@@ -592,13 +641,25 @@ enum FrameOrder {id: Value,message: String,},- Cancel(Option<CancelStop>),+ Close {+ id: Value,+ params: Value,+ done: tokio::sync::watch::Sender<bool>,+ },+ Cancel(CancelOrder),+}++enum CancelOrder {+ None,+ Armed(CancelStop),+ WaitForClose { session_id: String },}struct CancelStop {+ acp_session_id: String,daemon_session_id: String,- admission_id: String,- stop_done_tx: oneshot::Sender<()>,+ admission_id: Option<String>,+ done: tokio::sync::watch::Sender<bool>,}/// Prompt admission and cancel marking, in the client's frame order.@@ -617,15 +678,47 @@ async fn frame_order_prefix(incoming: &Incoming, state: &Arc<Mutex<DaemonAcpStat},}}+ Incoming::Request { id, method, params } if method == "session/close" => {+ let session_id = params+ .get("sessionId")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ let (done_tx, done_rx) = tokio::sync::watch::channel(false);+ let mut guard = state.lock().await;+ if guard+ .session+ .as_ref()+ .is_none_or(|hosted| hosted.acp_session_id != session_id)+ {+ return FrameOrder::Refused {+ id: id.clone(),+ message: format!("Unknown ACP session: {session_id}"),+ };+ }+ if guard.session_close_done.is_some() {+ return FrameOrder::Refused {+ id: id.clone(),+ message: format!("ACP session is already closing: {session_id}"),+ };+ }+ guard.session_close_done = Some(done_rx);+ FrameOrder::Close {+ id: id.clone(),+ params: params.clone(),+ done: done_tx,+ }+ }Incoming::Notification { method, params } if method == "session/cancel" => {- FrameOrder::Cancel(arm_cancel(params, state).await)+ FrameOrder::Cancel(cancel_order(params, state).await)}_ => FrameOrder::Spawn,}}/// Reserve the turn slot for one prompt. `Err` is the refusal message,-/// checked in TS order: unknown session, cancelling, turn running.+/// checked in TS order: unknown session, closing, cancelling, stop+/// failure, turn running.async fn admit_prompt(params: &Value,state: &Arc<Mutex<DaemonAcpState>>,@@ -635,6 +728,7 @@ async fn admit_prompt(.and_then(Value::as_str).unwrap_or_default();let mut guard = state.lock().await;+ let session_closing = guard.session_close_done.is_some();let Some(hosted) = guard.session.as_mut()@@ -642,53 +736,128 @@ async fn admit_prompt(else {return Err(format!("Unknown ACP session: {session_id}"));};- match &hosted.turn {- Some(turn) if turn.cancelled => {- return Err(format!("ACP session is cancelling: {session_id}"));- }- Some(_) => {- return Err("A prompt turn is already running for this ACP session".to_string());- }- None => {}+ if session_closing {+ return Err(format!("ACP session is closing: {session_id}"));+ }+ if hosted.cancelling {+ return Err(format!("ACP session is cancelling: {session_id}"));+ }+ if let Some(stop_failure) = hosted.stop_failure.as_ref() {+ return Err(format!("ACP session stop failed: {stop_failure}"));+ }+ if hosted.turn.is_some() {+ return Err("A prompt turn is already running for this ACP session".to_string());}let admission_id = format!("prompt-admission:{}", uuid::Uuid::new_v4());hosted.turn = Some(ActiveTurn {admission_id: admission_id.clone(),cancelled: false,- stop_done_rx: None,});Ok(admission_id)}-/// Mark the addressed turn cancelled and arm its stop sequence. `None`-/// when there is no running turn or it is already cancelled.-async fn arm_cancel(params: &Value, state: &Arc<Mutex<DaemonAcpState>>) -> Option<CancelStop> {- let session_id = params.get("sessionId").and_then(Value::as_str)?;+async fn cancel_order(params: &Value, state: &Arc<Mutex<DaemonAcpState>>) -> CancelOrder {+ let Some(session_id) = params.get("sessionId").and_then(Value::as_str) else {+ return CancelOrder::None;+ };let mut guard = state.lock().await;- let hosted = guard+ if guard.session_close_done.is_some() {+ return CancelOrder::WaitForClose {+ session_id: session_id.to_string(),+ };+ }+ arm_cancel_locked(session_id, &mut guard)+}++fn arm_cancel_locked(session_id: &str, guard: &mut DaemonAcpState) -> CancelOrder {+ let Some(hosted) = guard.session.as_mut()- .filter(|hosted| hosted.acp_session_id == session_id)?;- let daemon_session_id = hosted.daemon_active_session_id.clone();- let turn = hosted.turn.as_mut()?;- if turn.cancelled {- return None;+ .filter(|hosted| hosted.acp_session_id == session_id)+ else {+ return CancelOrder::None;+ };+ if hosted.cancelling {+ return CancelOrder::None;}- turn.cancelled = true;- let (stop_done_tx, stop_done_rx) = oneshot::channel();- turn.stop_done_rx = Some(stop_done_rx);- Some(CancelStop {- daemon_session_id,- admission_id: turn.admission_id.clone(),- stop_done_tx,+ let admission_id = match hosted.turn.as_mut() {+ Some(turn) => {+ turn.cancelled = true;+ Some(turn.admission_id.clone())+ }+ None if hosted.stop_failure.is_none() => return CancelOrder::None,+ None => None,+ };+ let (done_tx, done_rx) = tokio::sync::watch::channel(false);+ hosted.cancel_task = Some(done_rx);+ hosted.cancelling = true;+ CancelOrder::Armed(CancelStop {+ acp_session_id: hosted.acp_session_id.clone(),+ daemon_session_id: hosted.daemon_active_session_id.clone(),+ admission_id,+ done: done_tx,})}-/// The cancelled turn's stop sequence. Dropping `stop_done_tx` releases-/// the cancelled turn's response.-async fn run_cancel_stop(stop: CancelStop, link: &Arc<DaemonLink>) {- stop_session_work(link, &stop.daemon_session_id, Some(stop.admission_id)).await;- drop(stop.stop_done_tx);+async fn wait_for_session_close(state: &Arc<Mutex<DaemonAcpState>>) {+ let close_done = { state.lock().await.session_close_done.clone() };+ if let Some(mut done) = close_done {+ let _ = done.wait_for(|finished| *finished).await;+ }+}++async fn run_cancel_stop(+ stop: CancelStop,+ link: &Arc<DaemonLink>,+ state: &Arc<Mutex<DaemonAcpState>>,+) {+ let outcome = match acquire_stop_input_pause(link, state, &stop.acp_session_id).await {+ Ok(lease) => {+ match stop_session_work(link, &stop.daemon_session_id, stop.admission_id.as_deref())+ .await+ {+ Ok(()) => {+ release_session_input_pause(link, &stop.daemon_session_id, &lease.pause_id)+ .await+ .map(|()| lease)+ }+ Err(error) => Err(error),+ }+ }+ Err(error) => Err(error),+ };+ {+ let mut guard = state.lock().await;+ let released_closed = matches!(+ &outcome,+ Ok(lease) if guard.closed_input_pause_id.as_deref() == Some(&lease.pause_id)+ );+ if let Some(hosted) = guard+ .session+ .as_mut()+ .filter(|hosted| hosted.acp_session_id == stop.acp_session_id)+ {+ hosted.cancelling = false;+ hosted.cancel_task = None;+ match &outcome {+ Ok(lease) => {+ if hosted.input_pause_id.as_deref() == Some(&lease.pause_id) {+ hosted.input_pause_id = None;+ }+ if hosted.input_pause_key.as_deref() == Some(&lease.lease_key) {+ hosted.input_pause_key = None;+ }+ hosted.stop_failure = None;+ }+ Err(error) => hosted.stop_failure = Some(error.to_string()),+ }+ }+ if released_closed {+ guard.closed_input_pause_id = None;+ guard.closed_input_pause_key = None;+ }+ }+ let _ = stop.done.send(true);}/// TS `stopSessionWork`: abort the worker's running and queued work, stop@@ -697,53 +866,57 @@ async fn run_cancel_stop(stop: CancelStop, link: &Arc<DaemonLink>) {async fn stop_session_work(link: &Arc<DaemonLink>,daemon_session_id: &str,- admission_id: Option<String>,-) {- let _ = link- .request(DaemonCommand::AbortAndClearQueue {- id: None,- active_session_id: daemon_session_id.to_string(),- rest: Map::default(),- })- .await;+ admission_id: Option<&str>,+) -> anyhow::Result<()> {+ link.request_ok(DaemonCommand::AbortAndClearQueue {+ id: None,+ active_session_id: daemon_session_id.to_string(),+ rest: Map::default(),+ })+ .await?;if let Some(admission_id) = admission_id {cancel_owned_admission(link, daemon_session_id, admission_id).await;}- let _ = link- .request(DaemonCommand::WaitForIdle {- id: None,- active_session_id: daemon_session_id.to_string(),- wait_for_rlm_quiescence: None,- rest: Map::default(),- })- .await;- cancel_outstanding_rlm_children(link, daemon_session_id).await;+ link.request_ok(DaemonCommand::WaitForIdle {+ id: None,+ active_session_id: daemon_session_id.to_string(),+ wait_for_rlm_quiescence: None,+ rest: Map::default(),+ })+ .await?;+ cancel_outstanding_rlm_children(link, daemon_session_id).await}/// TS `cancelOutstandingRlmChildren`: cancel every roster row, no status/// filter — a row already settling keeps its own settle, and the cancels/// run one after another (TS `Promise.allSettled` is the declared-/// divergence). A failed roster fetch or cancel is ignored, like every-/// other stop step.-async fn cancel_outstanding_rlm_children(link: &Arc<DaemonLink>, daemon_session_id: &str) {- let Ok(children) = fetch_rlm_children(link, daemon_session_id).await else {- return;- };+/// divergence). A failed roster fetch or the first failed cancel fails the+/// stop; every row still gets its cancel.+async fn cancel_outstanding_rlm_children(+ link: &Arc<DaemonLink>,+ daemon_session_id: &str,+) -> anyhow::Result<()> {+ let children = fetch_rlm_children(link, daemon_session_id).await?;+ let mut failure = None;for child in children {let child_id = child.get("id").and_then(Value::as_str).unwrap_or_default().to_string();- let _ = link- .request(DaemonCommand::CancelRlmChild {+ if let Err(error) = link+ .request_ok(DaemonCommand::CancelRlmChild {id: None,active_session_id: daemon_session_id.to_string(),child_id,rest: Map::default(),})- .await;+ .await+ {+ failure.get_or_insert(error);+ }}+ failure.map_or(Ok(()), Err)}/// TS `cancel_prompt_admission` with `cancelOwned`: a committed prompt's@@ -751,19 +924,95 @@ async fn cancel_outstanding_rlm_children(link: &Arc<DaemonLink>, daemon_session_async fn cancel_owned_admission(link: &Arc<DaemonLink>,daemon_session_id: &str,- admission_id: String,+ admission_id: &str,) {let _ = link.request(DaemonCommand::CancelPromptAdmission {id: None,active_session_id: daemon_session_id.to_string(),- admission_id,+ admission_id: admission_id.to_string(),cancel_owned: Some(true),rest: Map::default(),}).await;}+struct InputPauseLease {+ pause_id: String,+ lease_key: String,+}++async fn acquire_stop_input_pause(+ link: &Arc<DaemonLink>,+ state: &Arc<Mutex<DaemonAcpState>>,+ acp_session_id: &str,+) -> anyhow::Result<InputPauseLease> {+ let (daemon_session_id, lease_key) = {+ let mut guard = state.lock().await;+ let Some(hosted) = guard+ .session+ .as_mut()+ .filter(|hosted| hosted.acp_session_id == acp_session_id)+ else {+ anyhow::bail!("Unknown ACP session: {acp_session_id}");+ };+ let lease_key = hosted+ .input_pause_key+ .clone()+ .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());+ hosted.input_pause_key = Some(lease_key.clone());+ (hosted.daemon_active_session_id.clone(), lease_key)+ };+ let response = link+ .request(DaemonCommand::AcquireSessionInputPause {+ id: None,+ active_session_id: daemon_session_id.clone(),+ lease_key: lease_key.clone(),+ rest: Map::default(),+ })+ .await?;+ if !response.success {+ anyhow::bail!(response+ .error+ .unwrap_or_else(|| "unknown error".to_string()));+ }+ let pause_id = response+ .data+ .unwrap_or(Value::Null)+ .get("pauseId")+ .and_then(Value::as_str)+ .map(str::to_string)+ .ok_or_else(|| anyhow::anyhow!("the daemon returned no session input pause id"))?;+ {+ let mut guard = state.lock().await;+ if let Some(hosted) = guard+ .session+ .as_mut()+ .filter(|hosted| hosted.acp_session_id == acp_session_id)+ {+ hosted.input_pause_id = Some(pause_id.clone());+ }+ }+ Ok(InputPauseLease {+ pause_id,+ lease_key,+ })+}++async fn release_session_input_pause(+ link: &Arc<DaemonLink>,+ daemon_session_id: &str,+ pause_id: &str,+) -> anyhow::Result<()> {+ link.request_ok(DaemonCommand::ReleaseSessionInputPause {+ id: None,+ active_session_id: daemon_session_id.to_string(),+ pause_id: pause_id.to_string(),+ rest: Map::default(),+ })+ .await+}+/// One incoming ACP frame. Requests answer.async fn handle_incoming(incoming: Incoming,@@ -786,9 +1035,6 @@ async fn handle_incoming("session/set_config_option" => {handle_set_config_option(id, params, link, state, tx).await;}- "session/close" => {- handle_session_close(id, params, link, state, tx).await;- }other => {let _ = tx.send(jsonrpc::error_response(&id,@@ -849,7 +1095,10 @@ async fn handle_session_new() {{let mut guard = state.lock().await;- if guard.session.is_some() || guard.session_new_in_flight || guard.session_close_in_flight {+ if guard.session.is_some()+ || guard.session_new_in_flight+ || guard.session_close_done.is_some()+ {let _ = tx.send(super::internal_error(&id,"prime-agent ACP mode hosts one session per connection; start another prime-agent process for a second session",@@ -861,13 +1110,27 @@ async fn handle_session_new(// Failures below clear the in-flight flag on the way out; on success// the hosted session takes the slot.let params = types::NewSessionParams::parse(¶ms);- // MCP admission runs first: a rejected list fails the request with- // the same error payloads.+ if !state.lock().await.mcp_server_names.is_empty() {+ if let Err(error) = clear_connection_servers(+ link,+ &binding.active_session_id,+ &binding.mcp_owner_id,+ state,+ )+ .await+ {+ state.lock().await.session_new_in_flight = false;+ let _ = tx.send(super::internal_error(&id, &error.to_string()));+ return;+ }+ }+ // MCP admission runs after the pending-clear retry: a rejected list+ // fails the request with the same error payloads.let resolved =match super::mcp::resolve_acp_mcp_servers(¶ms.mcp_servers, &options.actual_cwd) {Ok(resolved) => resolved,Err(reason) => {- *state.lock().await = DaemonAcpState::default();+ state.lock().await.session_new_in_flight = false;let _ = tx.send(jsonrpc::error_response(&id,jsonrpc::INVALID_PARAMS,@@ -878,7 +1141,7 @@ async fn handle_session_new(}};if let Err(details) = super::mcp::acp_mcp_tool_names(&resolved) {- *state.lock().await = DaemonAcpState::default();+ state.lock().await.session_new_in_flight = false;let _ = tx.send(super::internal_error(&id, &details));return;}@@ -900,34 +1163,59 @@ async fn handle_session_new(published: tokio::sync::Mutex::new(published),models: tokio::sync::Mutex::new(models),});- let mcp_owner_id = uuid::Uuid::new_v4().to_string();let mut hosted = HostedSession {acp_session_id: acp_session_id.clone(),daemon_active_session_id: binding.active_session_id.clone(),producer,config,- mcp_owner_id,- mcp_server_names: Vec::new(),+ cancelling: false,+ stop_failure: None,+ input_pause_key: None,+ input_pause_id: None,+ cancel_task: None,turn: None,assistant_stop_reason: None,mapping: WireMappingState::default(),+ observed_children: std::collections::HashSet::new(),};// The ACP MCP servers ride the wire command, not a local manager.- if let Err(error) = replace_session_servers(link, &hosted, &resolved).await {- // The worker may have applied the list before this failed (a lost- // acknowledgement); the clear is best-effort, like TS.+ let replace_skipped = resolved.is_empty() && state.lock().await.mcp_server_names.is_empty();+ if !replace_skipped {+ // A failed response does not prove the worker rejected this list.+ // Keep the names until a clear is acknowledged, even if the+ // best-effort clear below also loses its acknowledgement.if !resolved.is_empty() {- let _ = replace_session_servers(link, &hosted, &[]).await;+ state.lock().await.mcp_server_names = resolved+ .iter()+ .map(pa_core::mcp::AcpMcpServerConfig::name)+ .map(str::to_string)+ .collect();+ }+ if let Err(error) = replace_connection_servers(+ link,+ &binding.active_session_id,+ &binding.mcp_owner_id,+ &resolved,+ )+ .await+ {+ // The worker may have applied the list before this failed (a+ // lost acknowledgement); the clear is best-effort, like TS.+ let _ = clear_connection_servers(+ link,+ &binding.active_session_id,+ &binding.mcp_owner_id,+ state,+ )+ .await;+ state.lock().await.session_new_in_flight = false;+ let _ = tx.send(super::internal_error(&id, &error.to_string()));+ return;+ }+ if resolved.is_empty() {+ state.lock().await.mcp_server_names.clear();}- *state.lock().await = DaemonAcpState::default();- let _ = tx.send(super::internal_error(&id, &error.to_string()));- return;}- hosted.mcp_server_names = resolved- .iter()- .map(pa_core::mcp::AcpMcpServerConfig::name)- .map(str::to_string)- .collect();// The admission response is queued below, after the session takes its// slot and before the producer gate opens.@@ -954,35 +1242,115 @@ async fn handle_session_new(// producer gate opens only after the response is queued on the// sink, so no held update can precede the admission response.let producer = Arc::clone(&hosted.producer);- {+ let inherited_pause = {let mut guard = state.lock().await;guard.session_new_in_flight = false;+ if let Some(pause_id) = guard.closed_input_pause_id.clone() {+ hosted.input_pause_id = Some(pause_id);+ hosted.input_pause_key = guard.closed_input_pause_key.clone();+ }guard.session = Some(hosted);+ guard+ .closed_input_pause_id+ .clone()+ .zip(guard.closed_input_pause_key.clone())+ };+ let children = match fetch_rlm_children(link, &binding.active_session_id).await {+ Ok(children) => children,+ Err(error) => {+ let _ = clear_connection_servers(+ link,+ &binding.active_session_id,+ &binding.mcp_owner_id,+ state,+ )+ .await;+ let mut guard = state.lock().await;+ guard.session = None;+ guard.session_new_in_flight = false;+ drop(guard);+ let _ = tx.send(super::internal_error(&id, &error.to_string()));+ return;+ }+ };+ {+ let mut guard = state.lock().await;+ if let Some(current) = guard.session.as_mut() {+ for child in children {+ let id = child.get("id").and_then(Value::as_str).unwrap_or_default();+ if !current.observed_children.insert(id.to_string()) {+ continue;+ }+ let event = json!({ "type": "rlm_child_update", "child": child });+ for update in wire_events::wire_updates(&event, &mut current.mapping) {+ let _ = current+ .producer+ .publish(&update, 0, PrimeAgentEventPhase::Event, None)+ .await;+ }+ }+ }}let _ = tx.send(jsonrpc::response(&id, &result));+ if let Some((pause_id, lease_key)) = inherited_pause {+ match release_session_input_pause(link, &binding.active_session_id, &pause_id).await {+ Ok(()) => {+ let mut guard = state.lock().await;+ if guard.closed_input_pause_id.as_deref() == Some(&pause_id) {+ guard.closed_input_pause_id = None;+ guard.closed_input_pause_key = None;+ }+ if let Some(hosted) = guard+ .session+ .as_mut()+ .filter(|hosted| hosted.input_pause_id.as_deref() == Some(&pause_id))+ {+ hosted.input_pause_id = None;+ if hosted.input_pause_key.as_deref() == Some(&lease_key) {+ hosted.input_pause_key = None;+ }+ }+ }+ Err(error) => {+ if let Some(hosted) = state+ .lock()+ .await+ .session+ .as_mut()+ .filter(|hosted| hosted.input_pause_id.as_deref() == Some(&pause_id))+ {+ hosted.stop_failure = Some(error.to_string());+ }+ }+ }+ }producer.commit_session_new_response().await;}-/// Send the MCP replacement for one hosted session.-async fn replace_session_servers(+async fn replace_connection_servers(link: &Arc<DaemonLink>,- hosted: &HostedSession,+ daemon_session_id: &str,+ owner_id: &str,resolved: &[pa_core::mcp::AcpMcpServerConfig],) -> anyhow::Result<()> {- let response = link- .request(DaemonCommand::ReplaceAcpMcpServers {- id: None,- active_session_id: hosted.daemon_active_session_id.clone(),- owner_id: hosted.mcp_owner_id.clone(),- servers: serde_json::to_value(resolved)?,- rest: Map::default(),- })- .await?;- if !response.success {- anyhow::bail!(response- .error- .unwrap_or_else(|| "unknown error".to_string()));- }+ link.request_ok(DaemonCommand::ReplaceAcpMcpServers {+ id: None,+ active_session_id: daemon_session_id.to_string(),+ owner_id: owner_id.to_string(),+ servers: serde_json::to_value(resolved)?,+ rest: Map::default(),+ })+ .await+}++async fn clear_connection_servers(+ link: &Arc<DaemonLink>,+ daemon_session_id: &str,+ owner_id: &str,+ state: &Arc<Mutex<DaemonAcpState>>,+) -> anyhow::Result<()> {+ replace_connection_servers(link, daemon_session_id, owner_id, &[]).await?;+ state.lock().await.mcp_server_names.clear();Ok(())}@@ -1003,23 +1371,22 @@ async fn handle_session_prompt(/// cancelled. A slot holding another prompt's turn (close + new while/// this prompt ran) is left alone.async fn release_turn_slot(state: &Arc<Mutex<DaemonAcpState>>, admission_id: &str) {- let stop_done = {+ let mut cancel_task = {let mut guard = state.lock().await;let Some(hosted) = guard.session.as_mut() else {return;};- let stop_done = match hosted.turn.as_mut() {- Some(turn) if turn.admission_id != admission_id => return,- Some(turn) => turn.stop_done_rx.take(),- None => return,- };- let Some(stop_done) = stop_done else {- hosted.turn = None;+ let Some(turn) = hosted.turn.as_mut() else {return;};- stop_done+ if turn.admission_id != admission_id {+ return;+ }+ hosted.cancel_task.clone()};- let _ = stop_done.await;+ if let Some(cancel_task) = cancel_task.as_mut() {+ let _ = cancel_task.changed().await;+ }if let Some(hosted) = state.lock().await.session.as_mut() {hosted.turn@@ -1415,50 +1782,115 @@ fn quiescence_meta(}}-/// Close: stop the session's work, release the servers, and fence the-/// producer. The daemon session stays; a later `session/new` binds it-/// again (TS `closeSession`).async fn handle_session_close(id: Value,params: Value,link: &Arc<DaemonLink>,state: &Arc<Mutex<DaemonAcpState>>,tx: producer::FrameSink,+ close_done: tokio::sync::watch::Sender<bool>,+ owner_id: String,) {let session_id = params.get("sessionId").and_then(Value::as_str).unwrap_or_default().to_string();- let taken = {+ let cancel_task = {+ let guard = state.lock().await;+ guard+ .session+ .as_ref()+ .filter(|hosted| hosted.acp_session_id == session_id)+ .and_then(|hosted| hosted.cancel_task.clone())+ };+ if let Some(mut cancel_task) = cancel_task {+ let _ = cancel_task.changed().await;+ }+ let (acp_session_id, daemon_session_id, config, producer, admission_id) = {let mut guard = state.lock().await;- let taken = guard+ let Some(hosted) = guard.session- .take_if(|hosted| hosted.acp_session_id == session_id);- if taken.is_some() {- guard.session_close_in_flight = true;+ .as_mut()+ .filter(|hosted| hosted.acp_session_id == session_id)+ else {+ drop(guard);+ state.lock().await.session_close_done = None;+ let _ = close_done.send(true);+ return;+ };+ hosted.cancelling = true;+ if let Some(turn) = hosted.turn.as_mut() {+ turn.cancelled = true;}- taken+ let admission_id = hosted.turn.as_ref().map(|turn| turn.admission_id.clone());+ (+ hosted.acp_session_id.clone(),+ hosted.daemon_active_session_id.clone(),+ Arc::clone(&hosted.config),+ Arc::clone(&hosted.producer),+ admission_id,+ )};- let Some(hosted) = taken else {- let _ = tx.send(super::internal_error(- &id,- &format!("Unknown ACP session: {session_id}"),- ));- return;+ let close_result = match acquire_stop_input_pause(link, state, &acp_session_id).await {+ Ok(lease) => {+ match stop_session_work(link, &daemon_session_id, admission_id.as_deref()).await {+ Ok(()) => {+ // The serialized config work settles before the+ // producer fences (TS `await configTask`).+ let _ = config.queue.lock().await;+ producer.close().await;+ let _ =+ clear_connection_servers(link, &daemon_session_id, &owner_id, state).await;+ let mut guard = state.lock().await;+ guard.closed_input_pause_id = Some(lease.pause_id.clone());+ guard.closed_input_pause_key = Some(lease.lease_key.clone());+ if let Some(hosted) = guard+ .session+ .as_mut()+ .filter(|hosted| hosted.acp_session_id == session_id)+ {+ if hosted.input_pause_id.as_deref() == Some(&lease.pause_id) {+ hosted.input_pause_id = None;+ }+ if hosted.input_pause_key.as_deref() == Some(&lease.lease_key) {+ hosted.input_pause_key = None;+ }+ hosted.stop_failure = None;+ }+ guard+ .session+ .take_if(|hosted| hosted.acp_session_id == session_id);+ Ok(())+ }+ Err(error) => Err(error),+ }+ }+ Err(error) => Err(error),};- let admission_id = hosted.turn.as_ref().map(|turn| turn.admission_id.clone());- stop_session_work(link, &hosted.daemon_active_session_id, admission_id).await;- if !hosted.mcp_server_names.is_empty() {- let _ = replace_session_servers(link, &hosted, &[]).await;+ {+ let mut guard = state.lock().await;+ if let Some(hosted) = guard+ .session+ .as_mut()+ .filter(|hosted| hosted.acp_session_id == acp_session_id)+ {+ hosted.cancelling = false;+ if let Err(error) = &close_result {+ hosted.stop_failure = Some(error.to_string());+ }+ }+ guard.session_close_done = None;+ }+ let _ = close_done.send(true);+ match close_result {+ Ok(()) => {+ let _ = tx.send(jsonrpc::response(&id, &json!({})));+ }+ Err(error) => {+ let _ = tx.send(super::internal_error(&id, &error.to_string()));+ }}- // The serialized config work settles before the producer fences (TS- // `await configTask`).- let _ = hosted.config.queue.lock().await;- hosted.producer.close().await;- let _ = tx.send(jsonrpc::response(&id, &json!({})));- let mut guard = state.lock().await;- guard.session_close_in_flight = false;}/// Release the connection's hold after stdin closes (TS dispose): the@@ -1472,14 +1904,29 @@ async fn teardown(binding: &DaemonBinding,) {let hosted = state.lock().await.session.take();- if let Some(turn) = hosted.as_ref().and_then(|hosted| hosted.turn.as_ref()) {- cancel_owned_admission(link, &binding.active_session_id, turn.admission_id.clone()).await;- }- if let Some(hosted) = &hosted {- if !hosted.mcp_server_names.is_empty() {- let _ = replace_session_servers(link, hosted, &[]).await;+ if let Some(hosted) = hosted.as_ref() {+ if let Some(turn) = hosted.turn.as_ref() {+ cancel_owned_admission(link, &binding.active_session_id, &turn.admission_id).await;+ }+ if let Some(pause_id) = hosted.input_pause_id.as_ref() {+ let _ = release_session_input_pause(link, &binding.active_session_id, pause_id).await;}}+ let closed_pause = {+ let mut guard = state.lock().await;+ guard.closed_input_pause_key = None;+ guard.closed_input_pause_id.take()+ };+ if let Some(pause_id) = closed_pause {+ let _ = release_session_input_pause(link, &binding.active_session_id, &pause_id).await;+ }+ let _ = clear_connection_servers(+ link,+ &binding.active_session_id,+ &binding.mcp_owner_id,+ state,+ )+ .await;// The owned worker stops before the config queue drains: a stalled// config operation holding the queue on a wire request fails fast.if binding.client_owned {@@ -1496,3 +1943,295 @@ async fn teardown(hosted.producer.close().await;}}++#[cfg(test)]+mod tests {+ use super::*;++ fn hosted_session() -> HostedSession {+ let (sink, _drain) = mpsc::unbounded_channel();+ HostedSession {+ acp_session_id: "acp-1".to_string(),+ daemon_active_session_id: "daemon-1".to_string(),+ producer: UpdateProducer::new("acp-1", sink),+ config: Arc::new(HostedConfig {+ queue: tokio::sync::Mutex::new(()),+ published: tokio::sync::Mutex::new(Vec::new()),+ models: tokio::sync::Mutex::new(Vec::new()),+ }),+ cancelling: false,+ stop_failure: None,+ input_pause_key: None,+ input_pause_id: None,+ cancel_task: None,+ turn: None,+ assistant_stop_reason: None,+ mapping: WireMappingState::default(),+ observed_children: std::collections::HashSet::new(),+ }+ }++ fn state(session: Option<HostedSession>) -> DaemonAcpState {+ DaemonAcpState {+ session,+ ..DaemonAcpState::default()+ }+ }++ #[tokio::test]+ async fn eof_waits_for_a_reserved_close_before_taking_the_session() {+ let state = Arc::new(Mutex::new(state(Some(hosted_session()))));+ let order = frame_order_prefix(+ &Incoming::Request {+ id: json!(1),+ method: "session/close".to_string(),+ params: json!({ "sessionId": "acp-1" }),+ },+ &state,+ )+ .await;+ let FrameOrder::Close { done, .. } = order else {+ panic!("the close should reserve its stop");+ };+ let eof = tokio::spawn({+ let state = Arc::clone(&state);+ async move {+ wait_for_session_close(&state).await;+ state.lock().await.session.take().is_some()+ }+ });+ tokio::task::yield_now().await;+ assert!(+ !eof.is_finished(),+ "EOF must not take the session before close finishes"+ );+ assert!(state.lock().await.session.is_some());+ done.send(true).unwrap();+ state.lock().await.session_close_done = None;+ assert!(eof.await.unwrap());++ // A close can settle before EOF checks the state. No stale watch+ // should be awaited, and the hosted session is still available.+ let (done, mut done_rx) = tokio::sync::watch::channel(false);+ let settled = Arc::new(Mutex::new(self::state(Some(hosted_session()))));+ done.send(true).unwrap();+ assert!(*done_rx.borrow_and_update());+ settled.lock().await.session_close_done = Some(done_rx);+ tokio::time::timeout(+ std::time::Duration::from_secs(2),+ wait_for_session_close(&settled),+ )+ .await+ .expect("an already completed close must not strand EOF");+ }++ #[tokio::test]+ async fn lost_replace_and_clear_ack_retries_clear_before_an_empty_session() {+ let (writer, mut commands) = mpsc::unbounded_channel::<String>();+ let (_frames_tx, frames) = mpsc::unbounded_channel();+ let pending = Arc::new(std::sync::Mutex::new(HashMap::new()));+ let link = Arc::new(DaemonLink {+ writer,+ pending: Arc::clone(&pending),+ closed: Arc::new(std::sync::atomic::AtomicBool::new(false)),+ frames: Mutex::new(frames),+ protocol_version: DAEMON_PROTOCOL_VERSION,+ next_request_id: std::sync::atomic::AtomicU64::new(0),+ });+ let worker = tokio::spawn(async move {+ let mut replacements = Vec::new();+ let mut installed = Vec::<String>::new();+ while let Some(line) = commands.recv().await {+ let envelope: DaemonCommandEnvelope = serde_json::from_str(&line).unwrap();+ let id = envelope.id;+ let (command, data, lose_ack) = match envelope.command {+ DaemonCommand::GetConnectionState { .. } => {+ ("get_connection_state", None, false)+ }+ DaemonCommand::GetAvailableModels { .. } => {+ ("get_available_models", Some(json!({ "models": [] })), false)+ }+ DaemonCommand::GetRlmChildren { .. } => {+ ("get_rlm_children", Some(json!({ "children": [] })), false)+ }+ DaemonCommand::ReplaceAcpMcpServers { servers, .. } => {+ installed = servers+ .as_array()+ .unwrap()+ .iter()+ .map(|server| server.get("name").unwrap().as_str().unwrap().to_string())+ .collect();+ replacements.push(installed.clone());+ ("replace_acp_mcp_servers", None, replacements.len() <= 2)+ }+ other => panic!("unexpected command: {other:?}"),+ };+ let reply = pending.lock().unwrap().remove(&id).unwrap();+ if !lose_ack {+ reply+ .send(DaemonResponse {+ id: Some(id),+ command: command.to_string(),+ success: true,+ data,+ error: None,+ error_info: None,+ })+ .unwrap();+ }+ // Dropping the reply simulates an applied command whose+ // acknowledgement never reaches the ACP connection.+ }+ (replacements, installed)+ });+ let state = Arc::new(Mutex::new(state(None)));+ let binding = DaemonBinding {+ active_session_id: "daemon-1".to_string(),+ client_owned: false,+ mcp_owner_id: "owner-1".to_string(),+ };+ let options = DaemonAcpOptions {+ socket_path: PathBuf::new(),+ actual_cwd: PathBuf::from("/tmp"),+ product_version: "test".to_string(),+ create: DaemonCommand::GetConnectionState {+ id: None,+ active_session_id: "daemon-1".to_string(),+ rest: Map::default(),+ },+ };+ let (tx, mut responses) = mpsc::unbounded_channel();+ handle_session_new(+ json!(1),+ json!({ "mcpServers": [{ "name": "example", "command": "echo", "args": [], "env": [] }] }),+ &link, &state, &options, &binding, tx.clone(),+ ).await;+ assert!(responses.recv().await.unwrap().get("error").is_some());+ assert_eq!(state.lock().await.mcp_server_names, vec!["example"]);++ handle_session_new(+ json!(2),+ json!({ "mcpServers": [] }),+ &link,+ &state,+ &options,+ &binding,+ tx,+ )+ .await;+ assert!(responses.recv().await.unwrap().get("result").is_some());+ assert!(state.lock().await.mcp_server_names.is_empty());+ drop(link);+ let (replacements, installed) = worker.await.unwrap();+ assert_eq!(replacements, vec![vec!["example"], vec![], vec![]]);+ assert!(installed.is_empty());+ }++ #[tokio::test]+ async fn admit_prompt_matches_the_ts_refusal_order() {+ let none = Arc::new(Mutex::new(state(None)));+ assert_eq!(+ admit_prompt(&json!({ "sessionId": "nope" }), &none)+ .await+ .unwrap_err(),+ "Unknown ACP session: nope"+ );++ let closing = Arc::new(Mutex::new({+ let mut state = state(Some(hosted_session()));+ let (_done_tx, done_rx) = tokio::sync::watch::channel(false);+ state.session_close_done = Some(done_rx);+ state+ }));+ assert_eq!(+ admit_prompt(&json!({ "sessionId": "acp-1" }), &closing)+ .await+ .unwrap_err(),+ "ACP session is closing: acp-1"+ );++ let mut cancelling = state(Some(hosted_session()));+ cancelling.session.as_mut().unwrap().cancelling = true;+ let cancelling = Arc::new(Mutex::new(cancelling));+ assert_eq!(+ admit_prompt(&json!({ "sessionId": "acp-1" }), &cancelling)+ .await+ .unwrap_err(),+ "ACP session is cancelling: acp-1"+ );++ let mut failed = state(Some(hosted_session()));+ failed.session.as_mut().unwrap().stop_failure = Some("boom".to_string());+ failed.session.as_mut().unwrap().turn = Some(ActiveTurn {+ admission_id: "prompt-admission:1".to_string(),+ cancelled: false,+ });+ let failed = Arc::new(Mutex::new(failed));+ assert_eq!(+ admit_prompt(&json!({ "sessionId": "acp-1" }), &failed)+ .await+ .unwrap_err(),+ "ACP session stop failed: boom"+ );++ let clean = Arc::new(Mutex::new(state(Some(hosted_session()))));+ let admitted = admit_prompt(&json!({ "sessionId": "acp-1" }), &clean)+ .await+ .unwrap();+ assert!(admitted.starts_with("prompt-admission:"));+ assert_eq!(+ admit_prompt(&json!({ "sessionId": "acp-1" }), &clean)+ .await+ .unwrap_err(),+ "A prompt turn is already running for this ACP session"+ );+ }++ #[test]+ fn arm_cancel_arms_a_running_turn_a_stop_retry_or_nothing() {+ let mut running = state(Some(hosted_session()));+ running.session.as_mut().unwrap().turn = Some(ActiveTurn {+ admission_id: "prompt-admission:1".to_string(),+ cancelled: false,+ });+ let CancelOrder::Armed(stop) = arm_cancel_locked("acp-1", &mut running) else {+ panic!("a running turn arms its stop");+ };+ assert_eq!(stop.admission_id.as_deref(), Some("prompt-admission:1"));+ let turn = running.session.as_ref().unwrap().turn.as_ref().unwrap();+ assert!(turn.cancelled);+ assert!(running.session.as_ref().unwrap().cancelling);+ assert!(running.session.as_ref().unwrap().cancel_task.is_some());++ let mut idle = state(Some(hosted_session()));+ assert!(matches!(+ arm_cancel_locked("acp-1", &mut idle),+ CancelOrder::None+ ));+ assert!(idle.session.as_ref().unwrap().turn.is_none());++ let mut failed = state(Some(hosted_session()));+ failed.session.as_mut().unwrap().stop_failure = Some("boom".to_string());+ let CancelOrder::Armed(stop) = arm_cancel_locked("acp-1", &mut failed) else {+ panic!("a stop failure arms the retry");+ };+ assert!(stop.admission_id.is_none());+ assert!(failed.session.as_ref().unwrap().turn.is_none());+ assert!(failed.session.as_ref().unwrap().cancelling);+ assert!(failed.session.as_ref().unwrap().cancel_task.is_some());+ }++ #[test]+ fn a_cancel_while_a_stop_runs_never_arms_a_second_stop() {+ let mut stopping = state(Some(hosted_session()));+ stopping.session.as_mut().unwrap().cancelling = true;+ stopping.session.as_mut().unwrap().turn = Some(ActiveTurn {+ admission_id: "prompt-admission:1".to_string(),+ cancelled: true,+ });+ assert!(matches!(+ arm_cancel_locked("acp-1", &mut stopping),+ CancelOrder::None+ ));+ }+}diff --git a/crates/pa-daemon/src/acp/wire_config.rs b/crates/pa-daemon/src/acp/wire_config.rsindex abd552c7b3..1ccdf38ae6 100644--- a/crates/pa-daemon/src/acp/wire_config.rs+++ b/crates/pa-daemon/src/acp/wire_config.rs@@ -75,7 +75,7 @@ pub(super) async fn handle_set_config_option(// `sessionCloseInFlight`).let live = {let guard = state.lock().await;- !guard.session_close_in_flight+ guard.session_close_done.is_none()&& guard.session.as_ref()diff --git a/crates/pa-daemon/src/acp/wire_events.rs b/crates/pa-daemon/src/acp/wire_events.rsindex 14a76aa008..677d0be7b3 100644--- a/crates/pa-daemon/src/acp/wire_events.rs+++ b/crates/pa-daemon/src/acp/wire_events.rs@@ -292,6 +292,118 @@ pub fn wire_updates(event: &Value, state: &mut WireMappingState) -> Vec<AcpSessi}),}]}+ "rlm_child_update" => {+ let child = event.get("child");+ vec![AcpSessionUpdate::SessionInfoUpdate {+ meta: prime_agent_meta(&PrimeAgentSessionMeta {+ subagents: Some(vec![super::meta::PrimeAgentSubagentMeta {+ id: child+ .and_then(|child| child.get("id"))+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string(),+ session_name: child+ .and_then(|child| child.get("sessionName"))+ .and_then(Value::as_str)+ .map(str::to_string),+ status: child+ .and_then(|child| child.get("status"))+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string(),+ model: child+ .and_then(|child| child.get("model"))+ .and_then(Value::as_str)+ .map(str::to_string),+ depth: None,+ token_count: child+ .and_then(|child| child.get("tokenCount"))+ .and_then(Value::as_u64),+ error: child+ .and_then(|child| child.get("error"))+ .and_then(Value::as_str)+ .map(str::to_string),+ }]),+ ..Default::default()+ }),+ }]+ }+ "refine_complete" => {+ let result = event.get("result");+ let changes = result+ .and_then(|result| result.get("appliedEdits"))+ .and_then(Value::as_array)+ .map(|edits| {+ edits+ .iter()+ .filter(|edit| edit.get("applied") == Some(&json!(true)))+ .filter_map(|edit| {+ let action = edit.get("action").and_then(Value::as_str)?;+ let kind = edit.get("kind").and_then(Value::as_str)?;+ let id = edit.get("id").and_then(Value::as_str)?;+ Some(format!("{action} {kind}:{id}"))+ })+ .collect::<Vec<String>>()+ });+ vec![AcpSessionUpdate::SessionInfoUpdate {+ meta: prime_agent_meta(&PrimeAgentSessionMeta {+ refinement: Some(super::meta::PrimeAgentRefinementMeta {+ status: "complete".to_string(),+ summary: result+ .and_then(|result| result.get("summary"))+ .and_then(Value::as_str)+ .map(str::to_string),+ changes,+ error: None,+ }),+ ..Default::default()+ }),+ }]+ }+ "refine_failed" => {+ vec![AcpSessionUpdate::SessionInfoUpdate {+ meta: prime_agent_meta(&PrimeAgentSessionMeta {+ refinement: Some(super::meta::PrimeAgentRefinementMeta {+ status: "failed".to_string(),+ summary: None,+ changes: None,+ error: event+ .get("error")+ .and_then(Value::as_str)+ .map(str::to_string),+ }),+ ..Default::default()+ }),+ }]+ }+ "ipython_sent_agent_message" => {+ let message = event.get("message");+ vec![AcpSessionUpdate::SessionInfoUpdate {+ meta: prime_agent_meta(&PrimeAgentSessionMeta {+ agent_message: Some(super::meta::PrimeAgentAgentMessageMeta {+ tool_call_id: event+ .get("toolCallId")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string(),+ target: message+ .and_then(|message| message.get("target"))+ .and_then(|target| {+ target+ .get("sessionName")+ .or_else(|| target.get("sessionId"))+ })+ .and_then(Value::as_str)+ .map(str::to_string),+ delivery_status: message+ .and_then(|message| message.get("deliveryStatus"))+ .and_then(Value::as_str)+ .map(str::to_string),+ }),+ ..Default::default()+ }),+ }]+ }_ => Vec::new(),}}@@ -581,4 +693,166 @@ mod tests {let value = serde_json::to_value(&updates[0]).unwrap();assert_eq!(value["content"][0]["content"]["text"], "a");}++ fn namespaced(update: &AcpSessionUpdate) -> Value {+ update.to_bare_value()["_meta"]["ai.primeintellect.prime-agent"].clone()+ }++ #[test]+ fn rlm_child_update_maps_to_the_subagents_meta() {+ let mut state = WireMappingState::default();+ let updates = wire_updates(+ &json!({+ "type": "rlm_child_update",+ "child": {+ "id": "child-1",+ "parentId": "node-1",+ "activeSessionId": "child-live",+ "sessionName": "worker-a",+ "model": "z-ai/glm-5.3-flash",+ "label": "run the lane task",+ "status": "running",+ "durationMs": 500,+ "sessionDir": "/sessions/child-1",+ },+ }),+ &mut state,+ );+ let value = updates[0].to_bare_value();+ assert_eq!(value["sessionUpdate"], "session_info_update");+ assert_eq!(+ namespaced(&updates[0])["subagents"],+ json!([{+ "id": "child-1",+ "sessionName": "worker-a",+ "status": "running",+ "model": "z-ai/glm-5.3-flash",+ }])+ );+ let updates = wire_updates(+ &json!({+ "type": "rlm_child_update",+ "child": {+ "id": "child-2",+ "status": "cancelled",+ "error": "Deleted by parent orchestrator",+ },+ }),+ &mut state,+ );+ assert_eq!(+ namespaced(&updates[0])["subagents"],+ json!([{+ "id": "child-2",+ "status": "cancelled",+ "error": "Deleted by parent orchestrator",+ }])+ );+ }++ #[test]+ fn refine_complete_maps_the_applied_edits_changes() {+ let mut state = WireMappingState::default();+ let updates = wire_updates(+ &json!({+ "type": "refine_complete",+ "result": {+ "id": "ref-1",+ "summary": "applied 2 edits",+ "appliedEdits": [+ { "action": "create", "kind": "memory", "id": "x", "applied": true },+ { "action": "update", "kind": "skill", "id": "y", "applied": true },+ { "action": "delete", "kind": "prompt", "id": "z", "applied": false },+ ],+ },+ }),+ &mut state,+ );+ assert_eq!(+ namespaced(&updates[0])["refinement"],+ json!({+ "status": "complete",+ "summary": "applied 2 edits",+ "changes": ["create memory:x", "update skill:y"],+ })+ );+ let updates = wire_updates(+ &json!({+ "type": "refine_complete",+ "result": { "id": "ref-2", "summary": "no edits" },+ }),+ &mut state,+ );+ assert_eq!(+ namespaced(&updates[0])["refinement"],+ json!({ "status": "complete", "summary": "no edits" })+ );+ }++ #[test]+ fn refine_failed_maps_the_error_meta() {+ let mut state = WireMappingState::default();+ let updates = wire_updates(+ &json!({ "type": "refine_failed", "error": "Summarization failed: no responses" }),+ &mut state,+ );+ assert_eq!(+ namespaced(&updates[0])["refinement"],+ json!({ "status": "failed", "error": "Summarization failed: no responses" })+ );+ }++ #[test]+ fn ipython_sent_agent_message_maps_the_target_fallback() {+ let mut state = WireMappingState::default();+ let updates = wire_updates(+ &json!({+ "type": "ipython_sent_agent_message",+ "toolCallId": "t7",+ "message": {+ "id": "agentmsg_1",+ "message": "Ping.",+ "deliveryStatus": "delivered",+ "target": {+ "activeSessionId": "peer-live",+ "sessionId": "peer-session",+ "sessionName": "Worker",+ },+ },+ }),+ &mut state,+ );+ assert_eq!(+ namespaced(&updates[0])["agentMessage"],+ json!({+ "toolCallId": "t7",+ "target": "Worker",+ "deliveryStatus": "delivered",+ })+ );+ let updates = wire_updates(+ &json!({+ "type": "ipython_sent_agent_message",+ "toolCallId": "t8",+ "message": {+ "id": "agentmsg_2",+ "message": "Ping.",+ "deliveryStatus": "queued",+ "target": {+ "activeSessionId": "peer-live",+ "sessionId": "peer-session",+ },+ },+ }),+ &mut state,+ );+ assert_eq!(+ namespaced(&updates[0])["agentMessage"],+ json!({+ "toolCallId": "t8",+ "target": "peer-session",+ "deliveryStatus": "queued",+ })+ );+ }}diff --git a/crates/pa-daemon/src/agent_engine.rs b/crates/pa-daemon/src/agent_engine.rsindex 59305d10ed..4286ec07e8 100644--- a/crates/pa-daemon/src/agent_engine.rs+++ b/crates/pa-daemon/src/agent_engine.rs@@ -153,6 +153,8 @@ pub struct AgentSessionEngine {/// emits on state change, so unchanged states (e.g. `/goal status`)/// stay silent.pub(crate) published_goal: std::sync::Mutex<Option<pa_core::goals::GoalState>>,+ pub(crate) late_agent_message_sink:+ std::sync::Mutex<Option<pa_core::LateSentAgentMessageHandler>>,/// The session's goal driver and session-manager handles, mirrored from/// the core session at build time: the core session's own mutex is held/// across a turn's admission, so goal checks inside emit callbacksdiff --git a/crates/pa-daemon/src/agent_engine/lifecycle.rs b/crates/pa-daemon/src/agent_engine/lifecycle.rsindex 97adf46ff3..22382635e2 100644--- a/crates/pa-daemon/src/agent_engine/lifecycle.rs+++ b/crates/pa-daemon/src/agent_engine/lifecycle.rs@@ -152,6 +152,7 @@ impl AgentSessionEngine {config,mcp,published_goal: std::sync::Mutex::new(None),+ late_agent_message_sink: std::sync::Mutex::new(None),goal_runtime: std::sync::Mutex::new(None),pending_goal_continuation: std::sync::Mutex::new(None),goal_budget_crossed: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),@@ -1144,7 +1145,13 @@ impl AgentSessionEngine {.lock().expect("semantic identity lock").clone();+ let on_late_sent_agent_message = self+ .late_agent_message_sink+ .lock()+ .expect("late agent message sink lock")+ .clone();pa_core::session_engine::engine::create_session(SessionEngineConfig {+ on_late_sent_agent_message,semantic_edges,telemetry,cwd,diff --git a/crates/pa-daemon/src/agent_engine/turn/boundary.rs b/crates/pa-daemon/src/agent_engine/turn/boundary.rsindex e9018163e8..784f384674 100644--- a/crates/pa-daemon/src/agent_engine/turn/boundary.rs+++ b/crates/pa-daemon/src/agent_engine/turn/boundary.rs@@ -228,11 +228,19 @@ impl AgentSessionEngine {return BoundaryRun::Cancelled;}}+ if let Ok(result) = serde_json::to_value(&refinement) {+ if !emit(EngineEvent::RefineComplete { result }) {+ return BoundaryRun::Cancelled;+ }+ }}- // TS emits `refine_failed` on the wire; the Rust daemon wire- // has no refine event yet — the worker log keeps the failure.Some(Err(error)) => {eprintln!("pa-daemon: requested refinement failed: {error:#}");+ if !emit(EngineEvent::RefineFailed {+ error: format!("{error:#}"),+ }) {+ return BoundaryRun::Cancelled;+ }}None => {}}diff --git a/crates/pa-daemon/src/compact_autorefine.rs b/crates/pa-daemon/src/compact_autorefine.rsindex ca542fbe1f..0de34b8ef6 100644--- a/crates/pa-daemon/src/compact_autorefine.rs+++ b/crates/pa-daemon/src/compact_autorefine.rs@@ -480,4 +480,85 @@ mod tests {"the review consumed the queued decline");}++ #[test]+ fn refine_session_command_emits_the_refine_events() {+ let _faux = FAUX_TEST_LOCK+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let plan = r#"{"summary":"one edit","edits":[{"action":"create","kind":"memory","id":"m1","title":"t","content":"c"}]}"#;+ let (engine, _dir) = trigger_engine(&json!({ "responses": [ {"text": plan} ] }), 1, true);+ let mut events: Vec<EngineEvent> = Vec::new();+ let execution = crate::session_commands::run_session_command(+ &engine,+ &refine_command(),+ &mut |event| {+ events.push(event);+ true+ },+ );+ assert!(execution.is_some(), "the /refine command ran");+ let results: Vec<&serde_json::Value> = events+ .iter()+ .filter_map(|event| match event {+ EngineEvent::RefineComplete { result } => Some(result),+ _ => None,+ })+ .collect();+ assert_eq!(results.len(), 1, "events: {events:?}");+ assert_eq!(results[0]["summary"], "one edit");+ assert_eq!(results[0]["appliedEdits"][0]["applied"], json!(true));+ let complete_index = events+ .iter()+ .position(|event| matches!(event, EngineEvent::RefineComplete { .. }))+ .expect("the complete event");+ let result_row_index = events+ .iter()+ .rposition(|event| matches!(+ event,+ EngineEvent::CustomMessage(row) if row["customType"] == "session_slash_command_result"+ ))+ .expect("the result row");+ assert!(+ complete_index < result_row_index,+ "the event precedes the result row: {events:?}"+ );+ assert!(+ events+ .iter()+ .all(|event| !matches!(event, EngineEvent::RefineFailed { .. })),+ "a successful run emits no failure: {events:?}"+ );++ let (engine, _dir) =+ trigger_engine(&json!({ "responses": [ {"text": "not json"} ] }), 1, true);+ let mut events: Vec<EngineEvent> = Vec::new();+ crate::session_commands::run_session_command(&engine, &refine_command(), &mut |event| {+ events.push(event);+ true+ });+ let errors: Vec<String> = events+ .iter()+ .filter_map(|event| match event {+ EngineEvent::RefineFailed { error } => Some(error.clone()),+ _ => None,+ })+ .collect();+ assert_eq!(errors.len(), 1, "events: {events:?}");+ assert_eq!(errors[0], "Refiner did not return a JSON object");+ assert!(+ events+ .iter()+ .all(|event| !matches!(event, EngineEvent::RefineComplete { .. })),+ "a failed run emits no completion: {events:?}"+ );+ }++ fn refine_command() -> pa_core::session_engine::slash_commands::SessionSlashCommand {+ use pa_core::session_engine::slash_commands::{+ parse_session_command, SlashCommandRegistry,+ };+ parse_session_command(&SlashCommandRegistry::builtin(), "/refine")+ .expect("the test text is a session command")+ }}diff --git a/crates/pa-daemon/src/engine/wire.rs b/crates/pa-daemon/src/engine/wire.rsindex c21eca5272..8de4962e2c 100644--- a/crates/pa-daemon/src/engine/wire.rs+++ b/crates/pa-daemon/src/engine/wire.rs@@ -129,7 +129,9 @@ pub enum EngineEvent {/// carry the aborted/error row), like the TS session's loop-event/// forwarding. The rows themselves persist and broadcast through/// their own events; this frame carries only the accumulated payload.- AgentEnd { messages: Vec<Value> },+ AgentEnd {+ messages: Vec<Value>,+ },/// A durable custom message (wire `role: "custom"`): recorded into the/// session store and shown to attached clients. Emitted as a/// `message_start` + `message_end` pair, matching the TS session's@@ -138,12 +140,17 @@ pub enum EngineEvent {/// A compaction run started (TS `compaction_start` wire event); the/// payload is the complete event. Emitted before the summarizer runs so/// attached clients can swap their loader to the compaction label.- CompactionStart { event: Value },+ CompactionStart {+ event: Value,+ },/// A compaction settled (TS `compaction_end` wire event): `entry` is the/// `compaction` record to persist (null when the run skipped or/// failed), `event` the complete client-facing event (result on/// success, errorMessage with its severity otherwise).- Compaction { entry: Value, event: Value },+ Compaction {+ entry: Value,+ event: Value,+ },/// The prompt completed (successfully or not).Done(std::result::Result<(), String>),/// The prompt settled as aborted: the run was aborted before an@@ -157,7 +164,9 @@ pub enum EngineEvent {/// `goal_update`: the session goal state changed (TS wire event; the/// ACP adapter surfaces it as the namespaced `_meta.goal` update)./// The payload is the TS `GoalState` wire object.- GoalUpdate { goal: Value },+ GoalUpdate {+ goal: Value,+ },/// `auto_retry_start`: a provider failure is being retried (TS wire/// event; the interactive transcript shows the retry countdown). A/// `Backup` reason is a provider-failover switch: the failed turn@@ -179,6 +188,12 @@ pub enum EngineEvent {final_error: Option<String>,restored_model: Option<String>,},+ RefineComplete {+ result: Value,+ },+ RefineFailed {+ error: String,+ },}/// A streamed assistant message: already in wire form, or the loop's typeddiff --git a/crates/pa-daemon/src/goal_continuation.rs b/crates/pa-daemon/src/goal_continuation.rsindex e99abbefcd..e7de17e1a2 100644--- a/crates/pa-daemon/src/goal_continuation.rs+++ b/crates/pa-daemon/src/goal_continuation.rs@@ -78,6 +78,13 @@ impl AgentSessionEngine {}));}+ pub(crate) fn set_late_agent_message_sink(&self, sink: pa_core::LateSentAgentMessageHandler) {+ *self+ .late_agent_message_sink+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sink);+ }+/// Wire the registered-jobs gate (TS #2483's/// `canPassivateSettledSession` `hasRegisteredCronJob`): the worker calls/// this once with a probe over the shared cron store; the settled-childdiff --git a/crates/pa-daemon/src/rlm_children.rs b/crates/pa-daemon/src/rlm_children.rsindex 901ad40568..d690378b1a 100644--- a/crates/pa-daemon/src/rlm_children.rs+++ b/crates/pa-daemon/src/rlm_children.rs@@ -169,6 +169,7 @@ struct ChildRecord {active_session_id: String,session_id: Option<String>,session_dir: String,+ model: String,label: String,started_at_ms: u64,/// Terminal state (`done` | `error` | `cancelled`); running while@@ -221,6 +222,7 @@ struct ChildRecord {/// Serializes usage emissions for this child (read, cursor advance,/// and sink delivery) without holding the record lock across them.emit_lock: std::sync::Arc<tokio::sync::Mutex<()>>,+ last_emitted_status: Option<&'static str>,/// Serializes parent-directed rename and delete for this child.rename_lock: std::sync::Arc<tokio::sync::Mutex<()>>,}@@ -231,6 +233,28 @@ impl ChildRecord {self.settled_status.unwrap_or("running")}+ fn snapshot_value(&self) -> Value {+ let mut snapshot = json!({+ "id": self.rlm_child_id,+ "activeSessionId": self.active_session_id,+ "sessionName": self.session_name,+ "label": self.label,+ "status": self.status(),+ "durationMs": now_ms().saturating_sub(self.started_at_ms),+ "sessionDir": self.session_dir,+ });+ if !self.model.is_empty() {+ snapshot["model"] = json!(self.model);+ }+ if let Some(answer) = &self.answer_preview {+ snapshot["answerPreview"] = json!(answer);+ }+ if let Some(error) = &self.error {+ snapshot["error"] = json!(error);+ }+ snapshot+ }+/// Kernel-roster status: `running` | `completed` | `error` |/// `cancelled` (TS keeps a cancelled run's status verbatim in the/// registry row).@@ -328,6 +352,8 @@ pub struct SupervisorChildSessions {/// with the deleted child's id.pub type DeleteNotifier = std::sync::Arc<dyn Fn(&str) + Send + Sync>;+pub(crate) type ChildUpdateSink = std::sync::Arc<dyn Fn(Value) + Send + Sync>;+struct SupervisorChildSessionsInner {link: Arc<SupervisorLink>,agent_dir: PathBuf,@@ -388,6 +414,7 @@ struct SupervisorChildSessionsInner {/// `/context` children immediately, not ride out the next background/// refresh.delete_notifier: std::sync::Mutex<Option<DeleteNotifier>>,+ child_update_sink: std::sync::Mutex<Option<ChildUpdateSink>>,/// The parent session's semantic-edge recorder (wired once the session/// engine is built; the settle watcher records a returned child's last/// committed request into it). `None` until the build or for sessions@@ -429,6 +456,7 @@ impl SupervisorChildSessions {model_refusal_telemetry,usage_sink: std::sync::Mutex::new(None),delete_notifier: std::sync::Mutex::new(None),+ child_update_sink: std::sync::Mutex::new(None),semantic_edges: std::sync::Mutex::new(None),}),}@@ -450,6 +478,14 @@ impl SupervisorChildSessions {.expect("delete notifier lock") = Some(notifier);}+ pub(crate) fn set_child_update_sink(&self, sink: ChildUpdateSink) {+ *self+ .inner+ .child_update_sink+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sink);+ }+/// The worker saw the parent's turn end: release prompt tasks waiting/// on the boundary (called once per `EngineEvent::Done`).pub fn notify_turn_done(&self) {@@ -620,39 +656,12 @@ impl SupervisorChildSessions {/// run status, elapsed duration, answer preview, and session dir./// `parent_id` (the parent's own RLM node id) is overlaid by the/// worker, which owns that identity.- ///- /// # Panics- ///- /// Panics when the identity mutex is poisoned (a holder panicked- /// while holding the lock).pub async fn child_snapshots(&self) -> Vec<Value> {- let model = self- .inner- .identity- .lock()- .expect("identity lock")- .model- .clone();let children = self.inner.children.lock().await;let mut snapshots = Vec::new();for record in children.iter() {let record = record.lock().await;- let mut snapshot = json!({- "id": record.rlm_child_id,- "activeSessionId": record.active_session_id,- "sessionName": record.session_name,- "label": record.label,- "status": record.status(),- "durationMs": now_ms().saturating_sub(record.started_at_ms),- "sessionDir": record.session_dir,- });- if let Some(model) = &model {- snapshot["model"] = json!(model);- }- if let Some(answer) = &record.answer_preview {- snapshot["answerPreview"] = json!(answer);- }- snapshots.push(snapshot);+ snapshots.push(record.snapshot_value());}snapshots}@@ -734,6 +743,7 @@ impl SupervisorChildSessions {active_session_id: identity.active_session_id,session_id: identity.session_id,session_dir: String::new(),+ model: String::new(),label: String::new(),started_at_ms: 0,settled_status: None,@@ -750,6 +760,7 @@ impl SupervisorChildSessions {usage_watch_live: false,usage_rearm: false,emit_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ last_emitted_status: None,rename_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),})));}@@ -908,6 +919,51 @@ impl SupervisorChildSessionsInner {});}+ pub(crate) async fn emit_child_update(&self, record: &Arc<Mutex<ChildRecord>>) {+ let sink = self+ .child_update_sink+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .clone();+ let Some(sink) = sink else {+ return;+ };+ let row = {+ let mut record = record.lock().await;+ let status = record.status();+ if record.last_emitted_status == Some(status) {+ return;+ }+ record.last_emitted_status = Some(status);+ record.snapshot_value()+ };+ sink(row);+ }++ pub(crate) async fn emit_child_removal(&self, record: &Arc<Mutex<ChildRecord>>) {+ let sink = self+ .child_update_sink+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .clone();+ let Some(sink) = sink else {+ return;+ };+ let row = {+ let record = record.lock().await;+ json!({+ "id": record.rlm_child_id,+ "activeSessionId": record.active_session_id,+ "sessionName": record.session_name,+ "label": record.session_name,+ "status": "cancelled",+ "sessionDir": record.session_dir,+ "error": "Deleted by parent orchestrator",+ })+ };+ sink(row);+ }+/// Wait for the parent turn that spawned a task to complete (generation/// strictly greater than the one captured at spawn admission). Bounded:/// a turn that never settles releases the child anyway.diff --git a/crates/pa-daemon/src/rlm_children/host.rs b/crates/pa-daemon/src/rlm_children/host.rsindex e37561adb0..b56d5f5595 100644--- a/crates/pa-daemon/src/rlm_children/host.rs+++ b/crates/pa-daemon/src/rlm_children/host.rs@@ -135,6 +135,7 @@ impl RlmSubagentHost for SupervisorChildSessions {active_session_id: created.active_session_id.clone(),session_id: created.session_id.clone(),session_dir: created.session_dir.clone(),+ model: model.clone(),label: rlm_child_label(&request.prompt),started_at_ms: now_ms(),settled_status: None,@@ -151,11 +152,13 @@ impl RlmSubagentHost for SupervisorChildSessions {usage_watch_live: false,usage_rearm: false,emit_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ last_emitted_status: None,rename_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),};let record = Arc::new(Mutex::new(record));this.children.lock().await.push(Arc::clone(&record));this.refresh_running().await;+ this.emit_child_update(&record).await;anyhow::Ok((record, created, model))}.await;@@ -371,7 +374,14 @@ impl RlmSubagentHost for SupervisorChildSessions {this.forget_child_usage(&record).await;// The watcher owns an Arc to this record; deleting the roster// row alone cannot stop its polling loop.- record.lock().await.closed_by_parent = true;+ {+ let mut record = record.lock().await;+ record.closed_by_parent = true;+ if was_running {+ record.settled_status = Some("cancelled");+ record.error = Some("Deleted by parent orchestrator".to_string());+ }+ }let entry = {let record = record.lock().await;SupervisorChildSessions::entry(&record)@@ -385,6 +395,11 @@ impl RlmSubagentHost for SupervisorChildSessions {let record = record.lock().await;this.remember_deleted_child(&record);}+ if was_running {+ this.emit_child_update(&record).await;+ } else {+ this.emit_child_removal(&record).await;+ }// The deletion commits BEFORE the best-effort terminal// notice: the notice's supervisor delivery can ride its full// timeout, and a deleted child must leave the registry and thediff --git a/crates/pa-daemon/src/rlm_children/lifecycle.rs b/crates/pa-daemon/src/rlm_children/lifecycle.rsindex a1639aab16..8906df72fb 100644--- a/crates/pa-daemon/src/rlm_children/lifecycle.rs+++ b/crates/pa-daemon/src/rlm_children/lifecycle.rs@@ -472,6 +472,7 @@ impl SupervisorChildSessionsInner {// pending edge must be on the parent's ledger before the// notice's follow-up turn mints its own request.self.record_child_return(record).await;+ self.emit_child_update(record).await;// Only a successful run completes the display (TS// `completeRlmSubagentRuntime`); a cancelled or failed run// stays `running`, which a restart relists as `error`.@@ -657,6 +658,7 @@ impl SupervisorChildSessionsInner {record.error = Some(error);message};+ self.emit_child_update(record).await;// TS records a failed child's return too (`recordChildReturned` in// the thrown-run arm): a child that committed requests before// failing still returns them; a zero-commit child records nothing.diff --git a/crates/pa-daemon/src/rlm_children/registry.rs b/crates/pa-daemon/src/rlm_children/registry.rsindex cac72e1bbb..558d92d342 100644--- a/crates/pa-daemon/src/rlm_children/registry.rs+++ b/crates/pa-daemon/src/rlm_children/registry.rs@@ -85,6 +85,7 @@ impl SupervisorChildSessionsInner {record.settled_status = Some("cancelled");record.error = Some("Cancelled by user".to_string());}+ self.emit_child_update(record).await;// Capture before the abort: the completed turns' usage (the// aborted turn's partial row folds nowhere — TS skips// error/aborted completions) must not die with the run.@@ -165,6 +166,7 @@ impl SupervisorChildSessionsInner {let record = record.lock().await;self.remember_deleted_child(&record);}+ self.emit_child_removal(record).await;self.children.lock().await@@ -369,6 +371,17 @@ fn ledger_child_records(.parent().map(|dir| dir.to_string_lossy().into_owned()).unwrap_or_default(),+ model: display+ .as_ref()+ .and_then(|display| display.model.as_ref())+ .and_then(|model| {+ Some(format!(+ "{}/{}",+ model.get("provider")?.as_str()?,+ model.get("modelId")?.as_str()?+ ))+ })+ .unwrap_or_default(),label: rlm_child_label(display.as_ref()@@ -408,6 +421,7 @@ fn ledger_child_records(usage_watch_live: false,usage_rearm: false,emit_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ last_emitted_status: None,rename_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),});}diff --git a/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs b/crates/pa-daemon/src/rlm_children/usage_emit_tests.rsindex d49c62ac3f..28cbb1712a 100644--- a/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs+++ b/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs@@ -33,6 +33,7 @@ fn record_with_file(child_id: &str, session_file: &Path) -> Arc<Mutex<ChildRecoractive_session_id: "child-live".to_string(),session_id: None,session_dir: String::new(),+ model: String::new(),label: "child".to_string(),started_at_ms: 0,settled_status: None,@@ -49,6 +50,7 @@ fn record_with_file(child_id: &str, session_file: &Path) -> Arc<Mutex<ChildRecorusage_watch_live: false,usage_rearm: false,emit_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ last_emitted_status: None,rename_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),}))}diff --git a/crates/pa-daemon/src/rlm_children/watch_tests.rs b/crates/pa-daemon/src/rlm_children/watch_tests.rsindex 7083bf9cc3..d9fdd74ede 100644--- a/crates/pa-daemon/src/rlm_children/watch_tests.rs+++ b/crates/pa-daemon/src/rlm_children/watch_tests.rs@@ -396,6 +396,56 @@ async fn a_worker_leaving_inside_the_settle_grace_keeps_the_verdict() {.is_some_and(|content| content.contains("the child final answer")));}+#[tokio::test]+async fn child_updates_surface_through_the_sink() {+ let (follow_up_tx, _follow_up_rx) = mpsc::unbounded_channel();+ let (sessions, _kill_rx) =+ sessions_with_fake_supervisor(follow_up_tx, 0, FakeKill::Success, FakeChild::Healthy).await;+ let rows: Arc<std::sync::Mutex<Vec<Value>>> = Arc::new(std::sync::Mutex::new(Vec::new()));+ let sink_rows = Arc::clone(&rows);+ sessions.set_child_update_sink(Arc::new(move |child| {+ sink_rows.lock().unwrap().push(child);+ }));+ let settled = sessions.settle_notified();+ let handle = spawn_child(&sessions).await;+ sessions.notify_turn_done();+ tokio::time::timeout(Duration::from_secs(10), settled)+ .await+ .expect("the child settles");+ let result = sessions+ .delete_subagent(handle.rlm_child_id.clone())+ .await+ .expect("the settled child deletes");+ assert_eq!(result.outcome, Some("deleted"));+ let rows = rows.lock().unwrap().clone();+ assert!(+ rows.iter().any(|row| {+ row["id"] == json!(handle.rlm_child_id)+ && row["status"] == json!("running")+ && row["sessionName"] == json!("f20-worker")+ && row["model"] == json!("mock/mock-1")+ && row["sessionDir"].is_string()+ }),+ "the admission row carries the snapshot: {rows:?}"+ );+ assert!(+ rows.iter().any(|row| {+ row["id"] == json!(handle.rlm_child_id)+ && row["status"] == json!("done")+ && row["answerPreview"] == json!("the child final answer")+ }),+ "the settle row carries the terminal status: {rows:?}"+ );+ assert!(+ rows.iter().any(|row| {+ row["id"] == json!(handle.rlm_child_id)+ && row["status"] == json!("cancelled")+ && row["error"] == json!("Deleted by parent orchestrator")+ }),+ "the delete surfaces the removal row: {rows:?}"+ );+}+/// A cancelled run's watcher settle leaves the display `running`, so a/// restart relists the child as `error` instead of `completed`.#[tokio::test]@@ -1004,6 +1054,7 @@ fn an_already_settled_child_never_re_scores_as_an_unreachable_error() {active_session_id: "child-live".to_string(),session_id: Some("child-file".to_string()),session_dir: "/tmp".to_string(),+ model: String::new(),label: "task".to_string(),started_at_ms: 0,settled_status: None,@@ -1020,6 +1071,7 @@ fn an_already_settled_child_never_re_scores_as_an_unreachable_error() {usage_watch_live: false,usage_rearm: false,emit_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ last_emitted_status: None,rename_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),};// A running child that goes unreachable is the error class.diff --git a/crates/pa-daemon/src/session_commands.rs b/crates/pa-daemon/src/session_commands.rsindex bf034c234b..cd4eb89084 100644--- a/crates/pa-daemon/src/session_commands.rs+++ b/crates/pa-daemon/src/session_commands.rs@@ -105,6 +105,20 @@ pub(crate) fn run_session_command(if command.name == "autonomous" {engine.clear_autonomous_continuations();}+ if let Some(refinement) = &execution.refinement {+ if let Ok(result) = serde_json::to_value(refinement) {+ if !emit(EngineEvent::RefineComplete { result }) {+ return None;+ }+ }+ }+ if let Some(error) = &execution.refinement_failed {+ if !emit(EngineEvent::RefineFailed {+ error: error.clone(),+ }) {+ return None;+ }+ }// The executor's first row is the echo (already emitted); the rest of// the durable rows follow in order.for message in execution.messages.iter().skip(1) {diff --git a/crates/pa-daemon/src/session_custom.rs b/crates/pa-daemon/src/session_custom.rsindex b587898b2b..e8134bd347 100644--- a/crates/pa-daemon/src/session_custom.rs+++ b/crates/pa-daemon/src/session_custom.rs@@ -301,6 +301,10 @@ impl Worker {let result = match result {Ok(result) => result,Err(error) => {+ self.emit_worker_event(json!({+ "type": "refine_failed",+ "error": format!("{error:#}"),+ }));return response_failure(None, "refine", &format!("{error:#}"), None);}};@@ -328,6 +332,11 @@ impl Worker {self.emit_custom_row(&value);}}+ crate::user_bash::emit_session_event_frame(+ &self.core,+ &self.events,+ crate::worker::refine_complete_event(&typed),+ );}response_success(None, "refine", Some(result))}@@ -978,6 +987,7 @@ mod tests {#[tokio::test]async fn refine_surfaces_the_engine_failure() {let worker = created_worker().await;+ let mut subscription = worker.events.subscribe();let response = worker.dispatch("refine",@@ -989,6 +999,22 @@ mod tests {response.error.as_deref(),Some("This session does not support refinement"));+ let mut failures = Vec::new();+ while let Ok(frame) = subscription.try_recv() {+ if frame.outbound_type == "session_event" {+ let event: Value = serde_json::from_slice(&frame.payload).unwrap();+ if event["event"]["type"] == "refine_failed" {+ failures.push(event["event"].clone());+ }+ }+ }+ assert_eq!(+ failures,+ vec![json!({+ "type": "refine_failed",+ "error": "This session does not support refinement",+ })]+ );}/// `reload` answers the TS success (the live inputs this portdiff --git a/crates/pa-daemon/src/session_input_pause.rs b/crates/pa-daemon/src/session_input_pause.rsindex 8582498f1b..e8aa63cfb8 100644--- a/crates/pa-daemon/src/session_input_pause.rs+++ b/crates/pa-daemon/src/session_input_pause.rs@@ -154,6 +154,7 @@ impl Worker {let pause_id = self.input_pauses.acquire(&active_session_id, &owner_client_id, lease_key);+ self.idle_notify.notify_waiters();response_success(None,"acquire_session_input_pause",@@ -248,6 +249,51 @@ mod tests {worker}+ #[tokio::test]+ async fn a_pause_wakes_idle_wait_holding_queued_input() {+ let worker = created_worker().await;+ {+ let mut core = worker.core.lock().unwrap();+ core.queued_input_suspended = true;+ core.follow_up.push_back(crate::worker::QueuedItem {+ priority: crate::worker::QueuePriority::Human,+ preview: None,+ message: "held follow-up".to_string(),+ custom_message: None,+ agent_message: None,+ queue_key: None,+ admission_id: None,+ images: Vec::new(),+ done: None,+ queue_visible: true,+ policy: crate::worker::TurnPolicy::Queued,+ forced_batch: false,+ });+ }+ // Clear a create-time permit so acquisition must wake this waiter.+ worker.idle_notify.notify_one();+ worker.idle_notify.notified().await;+ let waiting = tokio::spawn({+ let worker = Arc::clone(&worker);+ async move { worker.wait_until_idle().await }+ });+ tokio::task::yield_now().await;+ assert!(!waiting.is_finished(), "queued input holds the idle wait");+ let pause = worker+ .dispatch(+ "acquire_session_input_pause",+ &json!({+ "activeSessionId": "pause-session", "leaseKey": "idle-wake", "clientId": "test"+ }),+ )+ .await;+ assert!(pause.success, "pause failed: {pause:?}");+ tokio::time::timeout(std::time::Duration::from_secs(2), waiting)+ .await+ .expect("pause acquisition did not wake the idle waiter")+ .expect("idle waiter panicked");+ }+/// Wire shape: acquire answers `{ pauseId }`, the same lease/// deduplicates to the same id, a different lease mints a new one.#[tokio::test]diff --git a/crates/pa-daemon/src/worker.rs b/crates/pa-daemon/src/worker.rsindex 15fdb2e294..99041d5f7a 100644--- a/crates/pa-daemon/src/worker.rs+++ b/crates/pa-daemon/src/worker.rs@@ -131,7 +131,7 @@ pub struct Worker {/// carries the counter's value for the supervisor's stale-delta gate.roster_delta_sequence: std::sync::Arc<std::sync::atomic::AtomicU64>,pub(crate) work_notify: Arc<Notify>,- idle_notify: Arc<Notify>,+ pub(crate) idle_notify: Arc<Notify>,/// The per-connection session-attach registry (the fresh bots'/// release findings): connection tokens -> the client ids their/// `attach` retained. The release is connection-scoped on EVERY@@ -623,6 +623,22 @@ impl Worker {);});concrete.set_goal_admission(probe, sink, queue_purge);+ let late_core = Arc::clone(&core);+ let late_events = Arc::clone(&events);+ concrete.set_late_agent_message_sink(std::sync::Arc::new(+ move |tool_call_id, message| {+ let wire = pa_core::sent_agent_message_json(&message);+ crate::user_bash::emit_session_event_frame(+ &late_core,+ &late_events,+ serde_json::json!({+ "type": "ipython_sent_agent_message",+ "toolCallId": tool_call_id,+ "message": wire,+ }),+ );+ },+ ));// The settled-child kernel release's registered-jobs gate// (TS #2483's `canPassivateSettledSession`// `hasRegisteredCronJob`): the release defers while this@@ -901,6 +917,47 @@ impl Worker {/// level: sequence + meta under the core lock, then one broadcast (the/// free-standing form of `Worker::emit_worker_event`, shared with the/// goal admission sink).+pub(crate) fn refine_complete_event(+ result: &pa_core::refinement::RefinementResult,+) -> serde_json::Value {+ json!({+ "type": "refine_complete",+ "result": serde_json::to_value(result).unwrap_or(Value::Null),+ })+}++/// Send a background refinement result only if the session that started+/// the review is still current. Hold the core lock through the broadcast so+/// navigation cannot move the event onto a different session.+fn emit_refinement_event_for_session(+ core: &Arc<Mutex<SessionCore>>,+ events: &Arc<EventPump>,+ review_session_id: &str,+ event: Value,+) -> bool {+ let mut core = core.lock().unwrap();+ if core.store.as_ref().map(SessionFile::session_id) != Some(review_session_id) {+ return false;+ }+ let sequence = core.last_event_sequence + 1;+ core.last_event_sequence = sequence;+ let meta = crate::protocol::create_daemon_event_meta(+ &core.active_session_id,+ sequence,+ None,+ Some(&core.generation),+ );+ let outbound = crate::protocol::DaemonOutbound::SessionEvent {+ active_session_id: core.active_session_id.clone(),+ event,+ meta: Some(meta),+ rest: Map::default(),+ };+ let payload = serde_json::to_vec(&outbound).unwrap_or_default();+ events.send(OutboundFrame::session_event(payload));+ true+}+/// Record one durable custom row of the background compact-trigger/// review and broadcast its `message_start`/`message_end` pair (the TS/// `_emit` for rows the session appends outside a turn): the same shapediff --git a/crates/pa-daemon/src/worker/create.rs b/crates/pa-daemon/src/worker/create.rsindex dc9d05b81d..bdab51b15b 100644--- a/crates/pa-daemon/src/worker/create.rs+++ b/crates/pa-daemon/src/worker/create.rs@@ -735,6 +735,18 @@ impl Worker {children.set_delete_notifier(std::sync::Arc::new(move |child_id| {cache.invalidate_child(child_id);}));+ let core = std::sync::Arc::clone(&self.core);+ let events = self.events.clone();+ children.set_child_update_sink(std::sync::Arc::new(move |mut child| {+ if let Some(parent_id) = core.lock().unwrap().rlm_child_id.clone() {+ child["parentId"] = json!(parent_id);+ }+ crate::user_bash::emit_session_event_frame(+ &core,+ &events,+ json!({ "type": "rlm_child_update", "child": child }),+ );+ }));}}let mut data = serde_json::to_value(&summary).unwrap_or(Value::Null);diff --git a/crates/pa-daemon/src/worker/lifecycle.rs b/crates/pa-daemon/src/worker/lifecycle.rsindex d444bc9896..246d21809a 100644--- a/crates/pa-daemon/src/worker/lifecycle.rs+++ b/crates/pa-daemon/src/worker/lifecycle.rs@@ -633,10 +633,19 @@ impl Worker {self.emit_custom_row(&value);}}+ crate::user_bash::emit_session_event_frame(+ &self.core,+ &self.events,+ crate::worker::refine_complete_event(&result),+ );}Ok(None) => {}Err(error) => {eprintln!("pa-daemon: auto-refinement after compaction failed: {error:#}");+ self.emit_worker_event(json!({+ "type": "refine_failed",+ "error": format!("{error:#}"),+ }));}}response_success(None, "compact", Some(run.result))@@ -657,12 +666,17 @@ impl Worker {/// register the permit before the flag check, or a turn that settles/// between the check and the await loses its wake/// (`notify_waiters` only reaches registered futures).- async fn wait_until_idle(&self) {+ pub(crate) async fn wait_until_idle(&self) {loop {let idle = self.idle_notify.notified();+ tokio::pin!(idle);+ idle.as_mut().enable();{let core = self.core.lock().unwrap();- if !core.busy && core.steering.is_empty() && core.follow_up.is_empty() {+ if !core.busy+ && (core.steering.is_empty() && core.follow_up.is_empty()+ || self.input_pauses.paused())+ {return;}}diff --git a/crates/pa-daemon/src/worker/tests.rs b/crates/pa-daemon/src/worker/tests.rsindex 39f614c16b..315a8b31ba 100644--- a/crates/pa-daemon/src/worker/tests.rs+++ b/crates/pa-daemon/src/worker/tests.rs@@ -52,3 +52,47 @@ mod kill_broadcast_tests;mod queue_tests;mod summary_tests;mod warning_marker_tests;+#[tokio::test]+async fn background_refinement_event_is_fenced_to_its_review_session() {+ let dir = std::env::temp_dir().join(format!("pa-refine-event-{}", uuid::Uuid::new_v4()));+ let worker = Worker::new(+ WorkerConfig {+ socket_path: dir.join("worker.sock"),+ supervisor_socket_path: std::path::PathBuf::new(),+ token: "token".to_string(),+ worker_instance_id: String::new(),+ active_session_id: "refinement-session".to_string(),+ agent_dir: dir.join("agent"),+ recovery_journal_path: dir.join("recovery.jsonl"),+ telemetry_disabled: None,+ script: Some(json!({ "responses": [] })),+ },+ None,+ );+ let mut subscription = worker.events.subscribe();+ let original = SessionFile::create("/tmp", None, 0);+ let original_id = original.session_id().to_string();+ worker.core.lock().unwrap().store = Some(original);+ assert!(emit_refinement_event_for_session(+ &worker.core,+ &worker.events,+ &original_id,+ json!({ "type": "refine_complete" }),+ ));+ assert_eq!(session_events_since(&mut subscription).len(), 1);++ worker.core.lock().unwrap().store = Some(SessionFile::create("/tmp", None, 0));+ assert!(!emit_refinement_event_for_session(+ &worker.core,+ &worker.events,+ &original_id,+ json!({ "type": "refine_complete" }),+ ));+ assert!(!emit_refinement_event_for_session(+ &worker.core,+ &worker.events,+ &original_id,+ json!({ "type": "refine_failed", "error": "old session" }),+ ));+ assert!(session_events_since(&mut subscription).is_empty());+}diff --git a/crates/pa-daemon/src/worker/turn.rs b/crates/pa-daemon/src/worker/turn.rsindex 4549a7b58a..76115b7fc0 100644--- a/crates/pa-daemon/src/worker/turn.rs+++ b/crates/pa-daemon/src/worker/turn.rs@@ -1,11 +1,12 @@//! One agent turn: the runner that admits queued input, drives the//! engine, and settles the result.use super::{- checkpoint_queue_recovery, compact_action_label, create_daemon_event_meta, emit_refinement_row,- gather_delivery_batch, json, oneshot, session_snapshot, AssistantSnapshot, DaemonOutbound,- EngineEvent, EventPump, Lane, Map, Notify, OutboundFrame, PromptRequest, QueueCheckpoint,- QueuedItem, Result, SessionActionSnapshot, SessionCore, SessionEngine, TurnSettle, Value,- WorkerRecoveryJournal, ABORTED_TURN_SETTLE_ERROR,+ checkpoint_queue_recovery, compact_action_label, create_daemon_event_meta,+ emit_refinement_event_for_session, emit_refinement_row, gather_delivery_batch, json, oneshot,+ session_snapshot, AssistantSnapshot, DaemonOutbound, EngineEvent, EventPump, Lane, Map, Notify,+ OutboundFrame, PromptRequest, QueueCheckpoint, QueuedItem, Result, SessionActionSnapshot,+ SessionCore, SessionEngine, TurnSettle, Value, WorkerRecoveryJournal,+ ABORTED_TURN_SETTLE_ERROR,};use std::sync::{Arc, Mutex};@@ -1007,6 +1008,14 @@ impl TurnRunner {"type": "goal_update","goal": goal,})],+ EngineEvent::RefineComplete { result } => vec![json!({+ "type": "refine_complete",+ "result": result,+ })],+ EngineEvent::RefineFailed { error } => vec![json!({+ "type": "refine_failed",+ "error": error,+ })],// The loop's run-boundary frames (TS `agent_start`/// `agent_end`): the run's whole message set rides// `agent_end` (one frame per agent run — retried and@@ -1396,10 +1405,22 @@ impl TurnRunner {emit_refinement_row(&core, &events, &review_session_id, &value);}}+ emit_refinement_event_for_session(+ &core,+ &events,+ &review_session_id,+ crate::worker::refine_complete_event(&result),+ );}Ok(None) => {}Err(error) => {eprintln!("pa-daemon: auto-refinement after compaction failed: {error:#}");+ emit_refinement_event_for_session(+ &core,+ &events,+ &review_session_id,+ json!({ "type": "refine_failed", "error": format!("{error:#}") }),+ );}}});