A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
print: inline (daemonless) RLM subagents; the run waits for them (#3487)
Sebastian Müller9eec445aa08a
diff --git a/crates/pa-cli/README.md b/crates/pa-cli/README.mdindex d70e9606fb..9734f3ed15 100644--- a/crates/pa-cli/README.md+++ b/crates/pa-cli/README.md@@ -36,6 +36,16 @@ the first turn; the in-loop continuation hook runs an active goal's naturalcontinuations inside the one agent run; the budget-limit steer and thethreshold-held continuation drain as this invocation's follow-up runswith the TS session-action phase frames.+Inline subagents (print_rlm.rs): the daemonless print session hosts+`rlm.spawn` children in-process over a tree of session nodes — the+`RlmSubagentHost` impl (depth gate, name uniqueness, model resolution,+the child session/engine build, the kickoff row), the+`AgentMessageController` (family roster, one steer-lane delivery path),+the quiescence drive that holds the run open until every admitted+descendant settles and its replies and notices drain (the #2270 fix),+the goal/autonomous deferral behind unsettled work, and the exit+disposal (kernels snapshotted, drivers joined; no child outlives the+process).Session slash commands (`print_session_command.rs`, the #253 residue): printprompts that are `/compact`, `/refine`, `/goal`, or `/autonomous` executethrough the pa-core session-command executor (the daemon worker's seam — nodiff --git a/crates/pa-cli/src/headless_autonomous.rs b/crates/pa-cli/src/headless_autonomous.rsindex cd5a2919a0..2f22c87695 100644--- a/crates/pa-cli/src/headless_autonomous.rs+++ b/crates/pa-cli/src/headless_autonomous.rs@@ -48,6 +48,10 @@ pub struct HeadlessAutonomous {/// The continuation the threshold arm minted ahead of its compaction,/// held for the settled boundary's queued `followUp` admission.held: tokio::sync::Mutex<Option<String>>,+ /// A continuation is held behind unsettled inline-subagent work (TS+ /// `_holdAutonomousContinuationForRlmWork`): the flag only — the+ /// decision and its count happen at the post-settle delivery.+ awaits_rlm_work: std::sync::atomic::AtomicBool,}impl HeadlessAutonomous {@@ -70,6 +74,7 @@ impl HeadlessAutonomous {state: Arc::new(tokio::sync::Mutex::new(state)),driver: ShellAutonomousDriver::new(cwd),held: tokio::sync::Mutex::new(None),+ awaits_rlm_work: std::sync::atomic::AtomicBool::new(false),}}@@ -135,8 +140,59 @@ impl HeadlessAutonomous {*self.held.lock().await = Some(text);}+ /// Hold the continuation while inline-subagent work settles (TS+ /// `_holdAutonomousContinuationForRlmWork`): nothing is spent on the+ /// pre-settle turn — a disabled mode or a spent run holds nothing, so+ /// the normal mint applies their stop. Returns whether the hold owns+ /// the boundary (the hook mints no row).+ pub(crate) async fn hold_rlm_continuation(&self) -> bool {+ let state = self.state.lock().await;+ if !state.enabled || autonomous_limit_reason(&state, now_millis()).is_some() {+ return false;+ }+ self.awaits_rlm_work+ .store(true, std::sync::atomic::Ordering::SeqCst);+ true+ }++ /// The RLM settle site (the daemon's `autonomous_children_settled`):+ /// deliver the held continuation once the descendants settled —+ /// decided fresh from the latest settled turn and counted at the+ /// delivery, dropped behind a goal that owns the wake-up. Returns+ /// whether a held flag was consumed.+ pub(crate) async fn deliver_rlm_continuation(+ &self,+ engine: &SessionEngine,+ boundary: &mut crate::print_boundary::TurnBoundary,+ model: &Model,+ api_key: Option<String>,+ global_harness_dir: PathBuf,+ ) -> Result<bool, String> {+ if !self+ .awaits_rlm_work+ .swap(false, std::sync::atomic::Ordering::SeqCst)+ {+ return Ok(false);+ }+ // An active goal's own continuation loop owns the wake-up: the+ // held turn is dropped behind it.+ if engine.goal_owns_continuation_wakeup().await {+ return Ok(true);+ }+ let Some(message) = engine.latest_settled_assistant().await else {+ return Ok(true);+ };+ if let Some(text) = self.follow_up_text(&message).await {+ boundary+ .admit_continuation(engine, model, api_key, &text, global_harness_dir)+ .await?;+ }+ Ok(true)+ }+/// The settled boundary's autonomous drain: each held continuation runs as- /// this invocation's follow-up turn; a re-crossing threshold holds the next.+ /// this invocation's follow-up turn; a re-crossing threshold holds the+ /// next. Returns whether any turn ran.#[allow(clippy::too_many_arguments)]pub(crate) async fn drive_boundary(&self,@@ -145,7 +201,8 @@ impl HeadlessAutonomous {model: &Model,api_key: Option<String>,global_harness_dir: PathBuf,- ) -> Result<(), String> {+ ) -> Result<bool, String> {+ let mut ran = false;while let Some(text) = self.held.lock().await.take() {boundary.admit_continuation(@@ -156,8 +213,9 @@ impl HeadlessAutonomous {global_harness_dir.clone(),).await?;+ ran = true;}- Ok(())+ Ok(ran)}/// The print-mode exit contract: stderr text when the run must exitdiff --git a/crates/pa-cli/src/lib.rs b/crates/pa-cli/src/lib.rsindex ef17f38b6f..bb954da1dd 100644--- a/crates/pa-cli/src/lib.rs+++ b/crates/pa-cli/src/lib.rs@@ -59,6 +59,7 @@ pub(crate) mod piped_stdin;pub(crate) mod print_autonomous;pub(crate) mod print_boundary;pub(crate) mod print_goal;+pub(crate) mod print_rlm;pub mod print_runtime;pub(crate) mod print_session_command;pub mod update_flow;diff --git a/crates/pa-cli/src/print_autonomous.rs b/crates/pa-cli/src/print_autonomous.rsindex b465fd1cf6..cd0b05309f 100644--- a/crates/pa-cli/src/print_autonomous.rs+++ b/crates/pa-cli/src/print_autonomous.rs@@ -16,25 +16,28 @@ use pa_types::ai::Model;use crate::headless_autonomous::HeadlessAutonomous;use crate::print_goal::{NaturalContinuation, PrintGoalSurface};-/// Install the composed natural-turn-end continuation hook: the goal arm-/// runs first (an active goal's mint owns the turn), the autonomous arm-/// consults on the fall-through. The threshold arm mints the owed-/// continuation ahead of the loop stop and holds it for the admission.+/// Install the composed natural-turn-end continuation hook: the goal+/// arm first, the autonomous arm on the fall-through. Both defer behind+/// unsettled inline-subagent work; the quiescence drive delivers after+/// the settle.pub(crate) fn wire_continuation_hook(engine: &Arc<SessionEngine>,agent: &Arc<Agent>,model: &Model,goal: &Arc<PrintGoalSurface>,autonomous: &Arc<HeadlessAutonomous>,+ root_node: Option<&Arc<crate::print_rlm::InlineSessionNode>>,) {let weak_engine = Arc::downgrade(engine);let weak_goal = Arc::downgrade(goal);let weak_autonomous = Arc::downgrade(autonomous);+ let weak_root = root_node.map(Arc::downgrade);let model = Arc::new(model.clone());agent.set_continuation_hook(Some(Arc::new(move |context, _signal| {let weak_engine = weak_engine.clone();let weak_goal = weak_goal.clone();let weak_autonomous = weak_autonomous.clone();+ let weak_root = weak_root.clone();let model = Arc::clone(&model);Box::pin(async move {let (Some(engine), Some(goal), Some(autonomous)) = (@@ -44,11 +47,27 @@ pub(crate) fn wire_continuation_hook() else {return Ok(Vec::new());};- match goal.natural_continuation(&engine, &model).await {+ // Without the inline-subagent runtime no descendant work+ // exists: both arms mint as before.+ let unsettled_rlm_work = match weak_root.as_ref().and_then(std::sync::Weak::upgrade) {+ Some(root) => crate::print_rlm::has_unsettled_rlm_work(&root).await,+ None => false,+ };+ match goal+ .natural_continuation(&engine, &model, unsettled_rlm_work)+ .await+ {NaturalContinuation::QueuedInput | NaturalContinuation::RequestedCompaction => {Ok(Vec::new())}NaturalContinuation::ThresholdDue => {+ // Unsettled inline-subagent work holds the mint (the+ // daemon checks it before the threshold arm): the+ // post-settle drive decides, the boundary still+ // compacts.+ if unsettled_rlm_work && autonomous.hold_rlm_continuation().await {+ return Ok(Vec::new());+ }// The autonomous continuation the threshold arm owes: the run ends,// the boundary compacts, the driver admits the held turn.if let Some(text) = autonomous.follow_up_text(&context.message).await {@@ -56,10 +75,21 @@ pub(crate) fn wire_continuation_hook(}Ok(Vec::new())}+ NaturalContinuation::HeldForRlmWork => {+ // The goal deferral rides the driver's owed flag; the+ // run ends and the quiescence drive delivers it after+ // the settle.+ Ok(Vec::new())+ }NaturalContinuation::GoalRow(row) => Ok(vec![*row]),NaturalContinuation::FallThrough => {- // The natural autonomous mint: the continuation user- // row runs as the next turn of the same run.+ // The natural autonomous mint runs as the next turn+ // of the same run; while inline-subagent work is+ // unsettled only a flag is held (nothing is spent+ // pre-settle) and the drive decides after the settle.+ if unsettled_rlm_work && autonomous.hold_rlm_continuation().await {+ return Ok(Vec::new());+ }match autonomous.follow_up_text(&context.message).await {Some(text) => Ok(vec![autonomous_continuation_row(&text)]),None => Ok(Vec::new()),diff --git a/crates/pa-cli/src/print_boundary/tests.rs b/crates/pa-cli/src/print_boundary/tests.rsindex 9ee2c4096f..70ca6e12e7 100644--- a/crates/pa-cli/src/print_boundary/tests.rs+++ b/crates/pa-cli/src/print_boundary/tests.rs@@ -130,6 +130,7 @@ async fn faux_engine_with_telemetry(extra_builtin_skill_overrides: Vec::new(),rlm_subagent_host: None,rlm_depth: None,+ daemonless: true,model_info: Some(model.clone()),prewarm_ipython_kernel: None,on_background_work_settled: None,@@ -541,6 +542,7 @@ async fn autonomous_continuation_turns_cross_the_boundary_arms() {&model,&goal,&run,+ /*root_node*/ None,);admit(&mut boundary,diff --git a/crates/pa-cli/src/print_goal.rs b/crates/pa-cli/src/print_goal.rsindex 2b639747b7..decf0bc367 100644--- a/crates/pa-cli/src/print_goal.rs+++ b/crates/pa-cli/src/print_goal.rs@@ -52,6 +52,10 @@ pub(crate) enum NaturalContinuation {/// A threshold compaction is due: the loop stops (any owed mint is held for the post-compaction/// admission), the boundary compacts.ThresholdDue,+ /// Unsettled inline-subagent work holds the mint (TS quiescence): the+ /// deferral is armed on the goal driver, and the quiescence drive+ /// delivers it after the descendants settle.+ HeldForRlmWork,/// The goal minted its next continuation row.GoalRow(Box<pa_agent::types::AgentMessage>),/// No goal work owns the boundary: the autonomous arm may consult.@@ -453,14 +457,17 @@ impl PrintGoalSurface {.await}- /// The goal arm of the natural-turn-end consult: queued input (the armed- /// steer) and a compaction due gate the mint — the threshold arm mints- /// ahead of the compaction and holds it — and an active goal mints its- /// next continuation turn inside the same agent run.+ /// The goal arm of the natural-turn-end consult: queued input (the+ /// armed steer) and a compaction due gate the mint; an owning goal+ /// defers behind unsettled descendant work, an ownerless boundary+ /// drops its deferral; the threshold arm mints ahead of the+ /// compaction and holds it; an active goal mints its next+ /// continuation turn inside the same agent run.pub(crate) async fn natural_continuation(&self,engine: &Arc<SessionEngine>,model: &pa_types::ai::Model,+ unsettled_rlm_work: bool,) -> NaturalContinuation {// Queued session input owns the boundary before any goal work — the armed budget steer ends// the run so the queue drains it.@@ -470,6 +477,18 @@ impl PrintGoalSurface {if engine.turn_boundary.compaction_scheduled().await {return NaturalContinuation::RequestedCompaction;}+ // The daemon's consult order: a goal that does not own the+ // wake-up drops any armed RLM deferral (the deferral dies with+ // the goal's loop); only an owning goal gates behind unsettled+ // descendant work — an ownerless boundary never starves the+ // autonomous arm.+ let owns_wakeup = engine.goal_owns_continuation_wakeup().await;+ if !owns_wakeup {+ engine.drop_owed_goal_continuation().await;+ } else if unsettled_rlm_work {+ engine.mark_goal_continuation_owed().await;+ return NaturalContinuation::HeldForRlmWork;+ }// The threshold arm: the crossing turn mints BEFORE the loop stops; the// boundary compacts, and the driver runs the held turn post-compaction.if engine.session.auto_compaction_due(model).await {@@ -479,6 +498,9 @@ impl PrintGoalSurface {}return NaturalContinuation::ThresholdDue;}+ if !owns_wakeup {+ return NaturalContinuation::FallThrough;+ }// The natural continuation mint: the goal's context turn runs as the next// turn of the same run; a row that cannot convert drops the mint.if let Some(message) = engine.mint_goal_continuation().await {@@ -494,8 +516,9 @@ impl PrintGoalSurface {/// The settled boundary's goal drain: the held continuation and the armed/// budget steer run as this invocation's follow-up turns; a turn that- /// still ends in a terminal error fails an active goal. Returns whether- /// an active goal still owns the boundary.+ /// still ends in a terminal error fails an active goal. Returns+ /// whether any turn ran (the drive loop re-enters quiescence for+ /// whatever the turns left behind).#[allow(clippy::too_many_arguments)]pub(crate) async fn drive_boundary(&self,@@ -505,6 +528,7 @@ impl PrintGoalSurface {api_key: Option<String>,global_harness_dir: std::path::PathBuf,) -> Result<bool, String> {+ let mut ran = false;loop {if let Some(message) = self.take_threshold_continuation().await {// A goal that went inactive mid-turn drops its queued continuation.@@ -518,6 +542,7 @@ impl PrintGoalSurface {&message,).await?;+ ran = true;continue;}}@@ -531,6 +556,7 @@ impl PrintGoalSurface {&steer,).await?;+ ran = true;continue;}if let Some(message) = crate::headless_autonomous::latest_assistant_error(engine).await@@ -555,9 +581,10 @@ impl PrintGoalSurface {global_harness_dir.clone(),).await?;+ ran = true;continue;}- return Ok(engine.goal_state().await.status == pa_types::goal::GoalStatus::Active);+ return Ok(ran);}}@@ -826,6 +853,7 @@ mod tests {additional_prompt_paths: Vec::new(),extra_builtin_skill_overrides: Vec::new(),rlm_subagent_host: None,+ daemonless: true,rlm_depth: None,model_info: Some(model.clone()),prewarm_ipython_kernel: None,@@ -861,6 +889,7 @@ mod tests {&model,&surface,&autonomous_run,+ /*root_node*/ None,);let harness_dir = dir.path().join("harness");GoalBed {@@ -916,7 +945,8 @@ mod tests {self.harness_dir.clone(),).await- .unwrap()+ .unwrap();+ self.engine.goal_owns_continuation_wakeup().await}}@@ -1437,6 +1467,7 @@ mod tests {additional_prompt_paths: Vec::new(),extra_builtin_skill_overrides: Vec::new(),rlm_subagent_host: None,+ daemonless: true,rlm_depth: None,model_info: Some(model.clone()),prewarm_ipython_kernel: None,@@ -1471,6 +1502,7 @@ mod tests {&model,&surface,&autonomous_run,+ /*root_node*/ None,);GoalBed {engine,diff --git a/crates/pa-cli/src/print_rlm.rs b/crates/pa-cli/src/print_rlm.rsnew file mode 100644index 0000000000..81467bf167--- /dev/null+++ b/crates/pa-cli/src/print_rlm.rs@@ -0,0 +1,1256 @@+//! Inline (daemonless) RLM subagents for the print runtime: the+//! in-process child-session host over a tree of session nodes, the+//! agent-messaging controller for that tree, the quiescence drive that+//! holds a print run open until every admitted descendant settles, and+//! the exit disposal. TS parity is `_createInlineRlmSubagentRuntime` ++//! `waitForRlmQuiescence` minus the #2270 bug (print must wait for RLM+//! quiescence, not just headless idle).++use std::sync::{Arc, OnceLock, Weak};+use std::time::Duration;++use pa_core::session_engine::agent_messaging::{+ create_agent_session_message_id, create_agent_session_message_prompt,+ create_agent_session_message_row, AgentFamilyMember, AgentFamilyRelationship,+ AgentMessageController, AgentMessageDeliveryStatus, AgentMessagePromptPayload,+ AgentMessageReceipt, AgentMessageSendInput, AgentSessionMessageRowPayload,+};+use pa_core::session_engine::engine::SessionEngine;+use pa_core::session_engine::goal_boundary::custom_message_to_loop_row;+use pa_core::session_engine::provider_adapter::model_thinking_level;+use pa_core::session_engine::rlm_host::{+ resolve_rlm_max_depth, rlm_child_session_dir, rlm_create_session_daemonless_error,+ rlm_depth_limit_error, spawn_name_unavailable_error, RlmChildResult, RlmCreateSessionHandle,+ RlmCreateSessionRequest, RlmDeleteSubagentResult, RlmHostFuture, RlmSpawnHandle,+ RlmSpawnRequest, RlmSubagentEntry, RlmSubagentHost,+};++use pa_core::session_engine::rlm_notices::{+ create_rlm_child_failure_message, create_rlm_child_terminal_notice, RlmChildTerminalNotice,+};+use pa_daemon::rlm_child_model::{cap_text, compact_rlm_text, ANSWER_TEXT_MAX_CHARS};+use pa_types::ai::Model;+use pa_types::session::CustomMessage;+use serde_json::{json, Value};+use tokio::sync::{Mutex, Notify};++use crate::print_boundary::TurnBoundary;+use crate::print_runtime::{ChildEngineOverrides, ChildLane, FauxChildQueue, HeadlessEmbedding};++/// Everything a spawned child inherits from the print invocation: the+/// invocation's own config (cwd, agent dir, prompt/skill paths) and the+/// parsed faux script when the run is scripted.+pub(crate) struct PrintRecipe {+ pub options: crate::mode::RunOptions,+ pub faux: Option<Value>,+}++/// One inline session in the print process: the root print session or a+/// spawned child. The node tree is the one ownership graph behind the+/// host, the messaging controller, and the quiescence drive.+pub(crate) struct InlineSessionNode {+ /// The durable session id (family addressing, the artifacts tree).+ pub(crate) session_id: String,+ pub(crate) session_file: Option<String>,+ /// The session's directory (the spawn handle and roster rows carry it).+ pub(crate) session_dir: String,+ /// The recorded session name (children: the spawn name).+ session_name: std::sync::Mutex<Option<String>>,+ /// Serializes same-parent spawn admissions (the name check through+ /// the children push); host requests run as detached tasks.+ spawn_gate: tokio::sync::Mutex<()>,+ /// Serializes message admission with disposal; never held across an await.+ delivery_gate: std::sync::Mutex<()>,+ pub(crate) depth: u32,+ pub(crate) max_depth: u32,+ /// The session's model selector (`provider/id`), inherited by children.+ model_selector: std::sync::Mutex<Option<String>>,+ /// The session's effective thinking level, inherited by children.+ thinking: std::sync::Mutex<Option<pa_types::ai::ModelThinkingLevel>>,+ pub(crate) parent: Option<Weak<InlineSessionNode>>,+ pub(crate) children: Mutex<Vec<Arc<InlineChild>>>,+ /// The session's engine, set right after the build (the host is+ /// passed into the engine config before the engine exists).+ engine: OnceLock<Weak<SessionEngine>>,+ /// Fired on every event the quiescence drive waits for: a delivered+ /// message, a child's settle, a re-run, a disposal.+ pub(crate) activity: Notify,+ pub(crate) recipe: Arc<PrintRecipe>,+ /// Set by `rlm.delete_subagent` and the exit disposal: the drive+ /// loops and the driver task observe it and stop.+ disposed: std::sync::atomic::AtomicBool,+}++impl InlineSessionNode {+ /// The live parent node, when this node is a spawned child.+ fn parent_node(&self) -> Option<Arc<InlineSessionNode>> {+ self.parent.as_ref().and_then(Weak::upgrade)+ }++ pub(crate) fn is_disposed(&self) -> bool {+ self.disposed.load(std::sync::atomic::Ordering::SeqCst)+ }++ pub(crate) fn session_name(&self) -> Option<String> {+ self.session_name.lock().unwrap().clone()+ }++ /// The endpoint block a delivered row's `from`/`target` fields carry.+ fn endpoint(&self) -> Value {+ let mut endpoint = json!({+ "activeSessionId": self.session_id,+ "sessionId": self.session_id,+ });+ if let Some(name) = self.session_name() {+ endpoint["sessionName"] = json!(name);+ }+ endpoint+ }++ /// The session's own name for prompts (the recorded name, else the id).+ fn sender_name(&self) -> String {+ self.session_name()+ .unwrap_or_else(|| self.session_id.clone())+ }++ /// Resolve one direct child by every selector the roster exposes.+ async fn find_child(&self, target: &str) -> Result<Arc<InlineChild>, String> {+ let children: Vec<Arc<InlineChild>> = self.children.lock().await.clone();+ let mut matches = Vec::new();+ for child in &children {+ let name = child.node.session_name();+ if child.rlm_child_id == target+ || child.node.session_id == target+ || name.as_deref() == Some(target)+ {+ matches.push(Arc::clone(child));+ }+ }+ match matches.len() {+ 0 => Err(format!(+ "No direct RLM child matches \"{target}\" in the current parent session"+ )),+ 1 => Ok(matches.into_iter().next().expect("one match")),+ _ => Err(format!(+ "RLM child selector \"{target}\" is ambiguous in the current parent session"+ )),+ }+ }+}++/// One spawned child: its node, engine, driver task, and live state.+pub(crate) struct InlineChild {+ pub(crate) rlm_child_id: String,+ pub(crate) node: Arc<InlineSessionNode>,+ pub(crate) engine: Arc<SessionEngine>,+ /// The child's model and request auth (the drive's boundary calls).+ model: Model,+ api_key: Option<String>,+ driver: Mutex<Option<tokio::task::JoinHandle<()>>>,+ state: Mutex<InlineChildState>,+}++struct InlineChildState {+ /// `running` | `done` | `error` | `cancelled`.+ status: &'static str,+ settled: bool,+ /// The full final-answer text, bounded by [`ANSWER_TEXT_MAX_CHARS`].+ answer_text: Option<String>,+ error: Option<String>,+ started_at_ms: u64,+ /// An agent message to the parent arrived since the task was+ /// admitted; the no-reply terminal notice is withheld once set.+ replied_since_task: bool,+}++/// The print root's node: the max-depth bound resolves here (chat+/// override > global setting > env > default — the print root inherits+/// nothing).+pub(crate) fn root_node(+ options: &crate::mode::RunOptions,+ session_manager: &pa_core::session::manager::SessionManager,+ faux: Option<Value>,+) -> Arc<InlineSessionNode> {+ let (max_depth, _) = resolve_rlm_max_depth(+ session_manager+ .get_session_file()+ .map(|path| path.display().to_string())+ .as_deref(),+ /*inherited*/ None,+ &options.config.cwd,+ &options.config.agent_dir,+ );+ Arc::new(InlineSessionNode {+ session_id: session_manager.get_session_id().to_string(),+ session_file: session_manager+ .get_session_file()+ .map(|path| path.display().to_string()),+ session_dir: session_manager.get_session_dir().display().to_string(),+ session_name: std::sync::Mutex::new(None),+ spawn_gate: tokio::sync::Mutex::new(()),+ delivery_gate: std::sync::Mutex::new(()),+ depth: 0,+ max_depth: u32::try_from(max_depth).unwrap_or(u32::MAX),+ model_selector: std::sync::Mutex::new(None),+ thinking: std::sync::Mutex::new(None),+ parent: None,+ children: Mutex::new(Vec::new()),+ engine: OnceLock::new(),+ activity: Notify::new(),+ recipe: Arc::new(PrintRecipe {+ options: options.clone(),+ faux,+ }),+ disposed: std::sync::atomic::AtomicBool::new(false),+ })+}++/// Publish the built engine onto its node: the host and the messaging+/// controller reach the session through this weak edge.+pub(crate) async fn adopt_built_engine(+ node: &Arc<InlineSessionNode>,+ engine: &Arc<SessionEngine>,+ model: &Model,+) {+ let _ = node.engine.set(Arc::downgrade(engine));+ *node.model_selector.lock().unwrap() = Some(format!("{}/{}", model.provider, model.id));+ let level = engine.session.agent().state().await.thinking_level;+ *node.thinking.lock().unwrap() = Some(model_thinking_level(level));+}++/// The inline host and the agent-message handlers one engine build wires+/// over its node (the root and every child get both).+pub(crate) fn inline_subagent_wiring(+ node: &Arc<InlineSessionNode>,+) -> (+ Arc<dyn RlmSubagentHost>,+ pa_core::kernel::shared::HostRequestHandlers,+) {+ let mut handlers = pa_core::kernel::shared::HostRequestHandlers::default();+ pa_core::session_engine::agent_messaging::register_agent_message_host_handlers(+ std::sync::Arc::new(InlineMessages(Arc::clone(node))),+ &mut handlers,+ );+ (Arc::new(InlineHost(Arc::clone(node))), handlers)+}++// The quiescence drive++/// Whether one child has live work (TS `child.isSessionActive`): not+/// settled, or a delivered row waiting in its lane, or a turn streaming.+/// The quiescence predicate, the collect wait, and the roster rows all+/// read this one fact — never a second bookkeeping writer — so a+/// follow-up delivered to a settled child reads unsettled until its+/// driver re-admits the run. A disposed child keeps no live work: its+/// terminal verdict stands.+async fn child_is_unsettled(child: &Arc<InlineChild>) -> bool {+ if child.node.is_disposed() {+ return false;+ }+ if !child.state.lock().await.settled {+ return true;+ }+ let agent = child.engine.session.agent();+ agent.has_queued_messages() || agent.state().await.is_streaming+}++/// Whether inline subagent work is unsettled (TS+/// `_hasUnsettledRlmQuiescenceWork`): a running child, a delivered row+/// waiting in a child's lane, or a row queued on the root's own agent.+/// The goal/autonomous continuation gates and the drive's return read+/// this one predicate: the live session state — not a bookkeeping flag+/// alone — is the fact (TS `child.isSessionActive`).+pub(crate) async fn has_unsettled_rlm_work(node: &Arc<InlineSessionNode>) -> bool {+ for child in node.children.lock().await.iter() {+ if child_is_unsettled(child).await {+ return true;+ }+ }+ node.engine+ .get()+ .and_then(Weak::upgrade)+ .is_some_and(|engine| engine.session.agent().has_queued_messages())+}++/// Drive one inline session to quiescence: drain delivered messages as+/// turns (through the print turn-boundary pair), wait out unsettled+/// descendants, and return once the session is idle with an empty queue+/// and a settled subtree — `true` when any turn drained (the drive loop+/// re-enters the boundary so the turns it armed drain).+pub(crate) async fn drive_to_quiescence(+ node: &Arc<InlineSessionNode>,+ engine: &Arc<SessionEngine>,+ boundary: &mut TurnBoundary,+ model: &Model,+ api_key: Option<String>,+ global_harness_dir: std::path::PathBuf,+) -> Result<bool, String> {+ let mut drained = false;+ loop {+ if node.is_disposed() {+ return Ok(drained);+ }+ // The wake registers before the checks (the enable-then-check+ // pattern): a settle or delivery that lands mid-scan still wakes+ // the parked drive; `notify_waiters` is the one event source.+ let notified = node.activity.notified();+ tokio::pin!(notified);+ notified.as_mut().enable();+ let agent = engine.session.agent();+ let streaming = agent.state().await.is_streaming;+ if !streaming && agent.has_queued_messages() {+ boundary+ .run_pre_turn(engine, model, api_key.clone())+ .await?;+ agent+ .continue_run()+ .await+ .map_err(|error| format!("{error:#}"))?;+ agent.wait_for_idle().await;+ boundary+ .run_at_settled_turn(engine, model, api_key.clone(), global_harness_dir.clone())+ .await?;+ drained = true;+ continue;+ }+ if !streaming && !has_unsettled_rlm_work(node).await {+ // A settle that landed mid-scan fires the armed wake: poll+ // it once instead of returning a false quiescence (the zero+ // timeout is the one non-blocking poll).+ if tokio::time::timeout(std::time::Duration::ZERO, notified.as_mut())+ .await+ .is_ok()+ {+ continue;+ }+ return Ok(drained);+ }+ notified.await;+ }+}++/// One child's driver task: run its task to quiescence, settle it, then+/// keep listening — a settled child re-runs on a later message until it+/// is disposed or deleted (TS `child.isSessionActive`).+async fn drive_child(child: Arc<InlineChild>) {+ let global_harness_dir = pa_core::refinement::get_global_harness_state_dir(+ &child.node.recipe.options.config.agent_dir,+ );+ loop {+ let mut boundary = TurnBoundary::new(/*json_mode*/ false);+ let run_error = drive_to_quiescence(+ &child.node,+ &child.engine,+ &mut boundary,+ &child.model,+ child.api_key.clone(),+ global_harness_dir.clone(),+ )+ .await+ .err();+ if child.node.is_disposed() {+ return;+ }+ settle_child(&child, run_error).await;+ // A settled child keeps listening: the enable-then-check park —+ // a delivered row that lands mid-scan still wakes the driver.+ loop {+ let notified = child.node.activity.notified();+ tokio::pin!(notified);+ notified.as_mut().enable();+ if child.node.is_disposed() {+ return;+ }+ if child.engine.session.agent().has_queued_messages() {+ break;+ }+ notified.await;+ }+ let mut state = child.state.lock().await;+ state.settled = false;+ state.status = "running";+ state.started_at_ms = crate::util_time::now_ms();+ state.error = None;+ }+}++/// Settle one child: capture its last assistant text as the answer,+/// publish the terminal status, deliver the no-reply notice or the+/// failure row to the parent, and fire the parent's activity. A terminal+/// assistant row that stopped on a provider error settles failed like a+/// drive error (the run path itself returns `Ok` for it).+async fn settle_child(child: &Arc<InlineChild>, run_error: Option<String>) {+ // The last assistant row: its text is the answer the collect envelope+ // and the no-reply notice carry (trailing non-assistant rows are+ // skipped); a provider-error stop on it is the terminal error.+ let (answer, terminal_error) =+ if let Some(pa_types::session::AgentMessage::Assistant(assistant)) =+ child.engine.session.last_assistant_message().await+ {+ let text = assistant+ .content+ .iter()+ .filter_map(|block| match block {+ pa_types::ai::AssistantContentBlock::Text(text) => Some(text.text.clone()),+ pa_types::ai::AssistantContentBlock::Thinking(_)+ | pa_types::ai::AssistantContentBlock::ToolCall(_) => None,+ })+ .collect::<String>();+ let terminal_error = if assistant.stop_reason == pa_types::ai::StopReason::Error {+ Some(+ assistant+ .error_message+ .unwrap_or_else(|| "Assistant response failed".to_string()),+ )+ } else {+ None+ };+ ((!text.is_empty()).then_some(text), terminal_error)+ } else {+ (None, None)+ };+ let name = child+ .node+ .session_name()+ .unwrap_or_else(|| child.rlm_child_id.clone());+ let parent = child.node.parent_node();+ {+ let mut state = child.state.lock().await;+ if state.settled || child.node.is_disposed() {+ return;+ }+ state.settled = true;+ state.answer_text = answer.map(|text| cap_text(&text, ANSWER_TEXT_MAX_CHARS));+ let notice = if let Some(error) = run_error.or(terminal_error) {+ state.status = "error";+ state.error = Some(error.clone());+ Some(create_rlm_child_failure_message(+ &child.rlm_child_id,+ &name,+ &error,+ crate::util_time::now_ms(),+ ))+ } else {+ state.status = "done";+ (!state.replied_since_task).then(|| {+ create_rlm_child_terminal_notice(+ &RlmChildTerminalNotice::CompletedWithoutReply {+ child_id: child.rlm_child_id.clone(),+ session_name: name.clone(),+ last_assistant_text_preview: state+ .answer_text+ .as_deref()+ .map(compact_rlm_text),+ },+ crate::util_time::now_ms(),+ )+ })+ };+ // The notice queues on the parent's lane while this lock is held:+ // every reader of `settled` reads it under this same lock, so none+ // can observe the settled child before the parent's queue holds its+ // row — the quiescence check reads the child state before the+ // parent's queue and cannot return through the gap.+ if let (Some(parent), Some(notice)) = (&parent, notice) {+ let delivered = match serde_json::to_value(notice) {+ Ok(value) => deliver_row(parent, value),+ Err(error) => Err(anyhow::anyhow!(+ "the notice failed its wire conversion: {error}"+ )),+ };+ if let Err(error) = delivered {+ eprintln!("pa-cli: RLM child notice was not delivered: {error:#}");+ }+ }+ }+ if let Some(parent) = parent {+ parent.activity.notify_waiters();+ }+}++/// Deliver one custom row to a node's session: steer the loop form into+/// the agent's steering lane (a streaming target picks it up at its next+/// turn boundary; the quiescence drive drains it when idle), then fire+/// the node's activity. One delivery path for kickoffs, replies, and+/// notices alike.+fn deliver_row(node: &Arc<InlineSessionNode>, row: Value) -> anyhow::Result<()> {+ let _delivery_guard = node.delivery_gate.lock().unwrap();+ if node.is_disposed() {+ anyhow::bail!("Cannot deliver to a disposed inline session");+ }+ let custom: CustomMessage = serde_json::from_value(row).map_err(|error| {+ anyhow::anyhow!("the delivered row failed its wire conversion: {error}")+ })?;+ let engine = node+ .engine+ .get()+ .and_then(Weak::upgrade)+ .ok_or_else(|| anyhow::anyhow!("the target session is not running"))?;+ let loop_row = custom_message_to_loop_row(&custom)+ .ok_or_else(|| anyhow::anyhow!("the delivered row failed its loop conversion"))?;+ engine.session.agent().steer(loop_row);+ node.activity.notify_waiters();+ Ok(())+}++// The exit disposal (TS `disposeHostedSubagentRuntimes`)++/// Tear one inline child down, its subtree with it: mark it disposed,+/// abort any running turn, dispose the kernel with a final namespace+/// snapshot, and join the driver task. No child kernel may outlive the+/// print process.+async fn dispose_child(child: &Arc<InlineChild>) {+ let mut pending = vec![Arc::clone(child)];+ while let Some(current) = pending.pop() {+ {+ let _delivery_guard = current.node.delivery_gate.lock().unwrap();+ current+ .node+ .disposed+ .store(true, std::sync::atomic::Ordering::SeqCst);+ }+ current.node.activity.notify_waiters();+ current.engine.session.agent().abort();+ current.engine.dispose_kernel().await;+ if let Some(driver) = current.driver.lock().await.take() {+ let _ = driver.await;+ }+ pending.extend(std::mem::take(&mut *current.node.children.lock().await));+ }+}++/// Tear every inline descendant of the root down.+pub(crate) async fn dispose_inline_subagents(root: &Arc<InlineSessionNode>) {+ {+ let _delivery_guard = root.delivery_gate.lock().unwrap();+ root.disposed+ .store(true, std::sync::atomic::Ordering::SeqCst);+ }+ root.activity.notify_waiters();+ let children = std::mem::take(&mut *root.children.lock().await);+ for child in children {+ dispose_child(&child).await;+ }+}++// The host (the `rlm.*` kernel surface)++/// The inline child-session host: one node per parent, its children in+/// the same process, driven by the quiescence loop.+struct InlineHost(Arc<InlineSessionNode>);++impl RlmSubagentHost for InlineHost {+ /// Admit one inline child (TS `_startRlmChildRun` minus the usage+ /// attribution the daemonless host does not keep): depth gate, name+ /// uniqueness, model resolution, the child session + engine, the+ /// kickoff row, and the driver task. Returns at admission; the task+ /// run is the driver's.+ fn spawn(&self, request: RlmSpawnRequest) -> RlmHostFuture<RlmSpawnHandle> {+ let node = Arc::clone(&self.0);+ Box::pin(async move {+ if node.depth >= node.max_depth {+ return Err(rlm_depth_limit_error(node.depth, node.max_depth));+ }+ let recipe = Arc::clone(&node.recipe);+ let config = &recipe.options.config;+ let child_id = format!("sub-{}", &uuid::Uuid::new_v4().simple().to_string()[..8]);+ let name = request.name.clone().unwrap_or_else(|| {+ pa_core::kernel::rlm_runtime::create_default_rlm_subagent_session_name(+ &request.prompt,+ &child_id,+ )+ });+ // Host requests run as detached tasks: same-parent spawns+ // serialize on the node's spawn gate so the name check and the+ // push are atomic.+ let spawn_gate = node.spawn_gate.lock().await;+ if node.is_disposed() {+ anyhow::bail!("Cannot spawn from a disposed inline session");+ }+ {+ let children = node.children.lock().await.clone();+ for child in &children {+ if child.node.session_name().as_deref() == Some(name.as_str()) {+ return Err(spawn_name_unavailable_error(&name, node.depth + 1));+ }+ }+ }+ // The child's thinking: the requested level, else the parent's+ // effective one; a real-provider child clamps it to what its+ // model supports.+ let thinking = request+ .thinking+ .as_deref()+ .and_then(pa_ai::models::thinking_level_from_str)+ .or(*node.thinking.lock().unwrap())+ .unwrap_or(pa_types::ai::ModelThinkingLevel::Medium);+ // The model lane: a scripted child runs its own faux queue under+ // `children.<spawn name>`; a real-provider child resolves against+ // the catalog, inheriting the parent's selector.+ let (selector, lane, thinking) = if let Some(script) = recipe.faux.as_ref() {+ let queue = script+ .get("children")+ .and_then(|children| children.get(&name))+ .ok_or_else(|| {+ anyhow::anyhow!(+ "PRIME_AGENT_FAUX_SCRIPT has no \"children.{name}\" entry: a scripted print run \+ must script every spawned child"+ )+ })?;+ let steps = crate::print_runtime::faux_response_steps(+ queue+ .get("responses")+ .and_then(Value::as_array)+ .ok_or_else(|| {+ anyhow::anyhow!(+ "PRIME_AGENT_FAUX_SCRIPT children.{name} requires a responses array"+ )+ })?,+ )+ .map_err(anyhow::Error::msg)?;+ let repeat_last = queue+ .get("repeatLastResponse")+ .and_then(Value::as_bool)+ .unwrap_or(false);+ (+ "faux/faux-1".to_string(),+ ChildLane::Faux(FauxChildQueue {+ child_id: child_id.clone(),+ steps,+ repeat_last,+ }),+ thinking,+ )+ } else {+ let selector = pa_daemon::rlm_child_model::resolve_child_model_unchecked(+ &config.agent_dir,+ request.model.as_deref(),+ node.model_selector.lock().unwrap().as_deref(),+ "subagent",+ )+ .map_err(|error| anyhow::anyhow!("{error:#}"))?;+ pa_daemon::rlm_child_model::assert_thinking_supported(+ &config.agent_dir,+ request.thinking.as_deref(),+ &selector,+ )+ .map_err(|error| anyhow::anyhow!("{error:#}"))?;+ let auth = pa_core::auth::AuthStorage::create(&config.agent_dir);+ let mut registry = pa_core::models::ModelRegistry::create(+ auth,+ config.agent_dir.join("models.json"),+ );+ registry.load_private_authorization_from_cache();+ let all: Vec<Model> = registry.get_all().to_vec();+ let resolved =+ pa_core::models::resolve_cli_model(/*cli_provider*/ None, &selector, &all);+ if let Some(error) = resolved.error {+ return Err(anyhow::Error::msg(error));+ }+ let Some(model) = resolved.model else {+ return Err(anyhow::Error::msg("No matching model found."));+ };+ let thinking = pa_ai::models::clamp_thinking_level(&model, thinking);+ (selector, ChildLane::Real(Box::new(model)), thinking)+ };+ // The child's session: its own directory under the parent's+ // artifacts tree; a persisted parent gives the child its own file+ // with the parent edge, a no-session parent keeps the child in+ // memory (TS `_createInlineRlmSubagentRuntime`), still pinned to+ // the child's dir for its artifacts.+ let child_dir = rlm_child_session_dir(+ &config.agent_dir,+ node.session_file+ .is_some()+ .then(|| node.session_id.clone())+ .as_deref(),+ &child_id,+ )?;+ let mut child_manager = if let Some(parent_file) = &node.session_file {+ let mut manager =+ pa_core::session::manager::SessionManager::persisted(&config.cwd, &child_dir);+ manager.new_session(&pa_core::session::manager::NewSessionOptions {+ parent_session: Some(parent_file.clone()),+ rlm_depth: Some(u64::from(node.depth + 1)),+ ..Default::default()+ });+ manager+ } else {+ pa_core::session::manager::SessionManager::in_memory_in_session_dir(+ &config.cwd,+ &child_dir,+ )+ };+ child_manager+ .append_session_info(&name)+ .map_err(anyhow::Error::from)?;+ let child_node = Arc::new(InlineSessionNode {+ session_id: child_manager.get_session_id().to_string(),+ session_file: child_manager+ .get_session_file()+ .map(|path| path.display().to_string()),+ session_dir: child_dir.display().to_string(),+ session_name: std::sync::Mutex::new(Some(name.clone())),+ spawn_gate: tokio::sync::Mutex::new(()),+ delivery_gate: std::sync::Mutex::new(()),+ depth: node.depth + 1,+ max_depth: node.max_depth,+ model_selector: std::sync::Mutex::new(Some(selector.clone())),+ thinking: std::sync::Mutex::new(Some(thinking)),+ parent: Some(Arc::downgrade(&node)),+ children: Mutex::new(Vec::new()),+ engine: OnceLock::new(),+ activity: Notify::new(),+ recipe: Arc::clone(&recipe),+ disposed: std::sync::atomic::AtomicBool::new(false),+ });+ let overrides = ChildEngineOverrides {+ node: Arc::clone(&child_node),+ lane,+ thinking,+ semantic_parent_session_id: Some(node.session_id.clone()),+ spawned_by_request_id: request.spawned_by_request_id.clone(),+ };+ let headless = crate::print_runtime::build_engine(+ &recipe.options,+ recipe.faux.as_ref(),+ Some(child_manager),+ "subagent",+ &HeadlessEmbedding::Child(Box::new(overrides)),+ )+ .await+ .map_err(anyhow::Error::msg)?;+ let engine = Arc::new(headless.engine);+ let _ = child_node.engine.set(Arc::downgrade(&engine));+ let child = Arc::new(InlineChild {+ rlm_child_id: child_id.clone(),+ node: Arc::clone(&child_node),+ engine: Arc::clone(&engine),+ model: headless.model,+ api_key: headless.api_key,+ driver: Mutex::new(None),+ state: Mutex::new(InlineChildState {+ status: "running",+ settled: false,+ answer_text: None,+ error: None,+ started_at_ms: crate::util_time::now_ms(),+ replied_since_task: false,+ }),+ });+ // Teardown can run while the engine is being built. Check while+ // holding the roster lock so disposal either takes this child or+ // admission rejects it; no child can land after the teardown drain.+ let mut children = node.children.lock().await;+ if node.is_disposed() {+ drop(children);+ engine.dispose_kernel().await;+ anyhow::bail!("Cannot spawn from a disposed inline session");+ }+ children.push(Arc::clone(&child));+ drop(children);+ drop(spawn_gate);+ // The kickoff: the task prompt rides the parent's `agent_message` row+ // (TS `spawnMessage`), delivered through the one steer path.+ let kickoff_content = format!("[task from parent]\n\n{}", request.prompt);+ let kickoff_row = create_agent_session_message_row(&AgentSessionMessageRowPayload {+ id: &format!("spawn:{child_id}"),+ prompt: &kickoff_content,+ message: &request.prompt,+ from: &node.endpoint(),+ from_relationship: Some(AgentFamilyRelationship::Parent),+ target: None,+ timestamp: crate::util_time::now_ms(),+ });+ deliver_row(&child_node, kickoff_row)?;+ let driver = tokio::spawn(drive_child(Arc::clone(&child)));+ *child.driver.lock().await = Some(driver);+ Ok(RlmSpawnHandle {+ rlm_child_id: child_id,+ name,+ session_dir: child_node.session_dir.clone(),+ model: selector,+ })+ })+ }++ fn create_session(+ &self,+ _request: RlmCreateSessionRequest,+ ) -> RlmHostFuture<RlmCreateSessionHandle> {+ Box::pin(async { Err(rlm_create_session_daemonless_error()) })+ }++ fn list_subagents(&self) -> RlmHostFuture<Vec<RlmSubagentEntry>> {+ let node = Arc::clone(&self.0);+ Box::pin(async move {+ let children = node.children.lock().await.clone();+ let mut entries = Vec::with_capacity(children.len());+ for child in &children {+ let unsettled = child_is_unsettled(child).await;+ let state = child.state.lock().await;+ entries.push(roster_entry(child, &state, unsettled));+ }+ Ok(entries)+ })+ }++ fn delete_subagent(&self, target: String) -> RlmHostFuture<RlmDeleteSubagentResult> {+ let node = Arc::clone(&self.0);+ Box::pin(async move {+ let child = node.find_child(&target).await.map_err(anyhow::Error::msg)?;+ let was_running = !child.state.lock().await.settled;+ // Cancel the child and its subtree: runs abort, kernels get+ // their final snapshots, drivers join.+ dispose_child(&child).await;+ let unsettled = child_is_unsettled(&child).await;+ let entry = {+ let mut state = child.state.lock().await;+ state.settled = true;+ if was_running {+ state.status = "cancelled";+ state.error = Some("Deleted by parent orchestrator".to_string());+ }+ roster_entry(&child, &state, unsettled)+ };+ node.children+ .lock()+ .await+ .retain(|other| !Arc::ptr_eq(other, &child));+ // The settle that the parked parent drive waits for.+ node.activity.notify_waiters();+ Ok(RlmDeleteSubagentResult {+ subagent: entry,+ outcome: Some("deleted"),+ })+ })+ }++ fn collect(&self, targets: Vec<String>, timeout_ms: u64) -> RlmHostFuture<Vec<RlmChildResult>> {+ let node = Arc::clone(&self.0);+ Box::pin(async move {+ let children: Vec<Arc<InlineChild>> = if targets.is_empty() {+ node.children.lock().await.clone()+ } else {+ let mut resolved = Vec::with_capacity(targets.len());+ for target in &targets {+ resolved.push(node.find_child(target).await.map_err(anyhow::Error::msg)?);+ }+ resolved+ };+ let deadline = tokio::time::Instant::now() + Duration::from_millis(timeout_ms);+ loop {+ // The wake registers before the snapshot: a settle that+ // lands mid-scan still wakes the collect.+ let notified = node.activity.notified();+ tokio::pin!(notified);+ notified.as_mut().enable();+ let mut all_settled = true;+ let mut results = Vec::with_capacity(children.len());+ for child in &children {+ let unsettled = child_is_unsettled(child).await;+ let state = child.state.lock().await;+ all_settled &= !unsettled;+ results.push(RlmChildResult {+ rlm_child_id: child.rlm_child_id.clone(),+ session_name: Some(+ child+ .node+ .session_name()+ .unwrap_or_else(|| child.rlm_child_id.clone()),+ ),+ session_dir: Some(child.node.session_dir.clone()),+ status: if unsettled { "running" } else { state.status },+ settled: !unsettled,+ answer_preview: state.answer_text.as_deref().map(compact_rlm_text),+ answer_text: state.answer_text.clone(),+ error: state.error.clone(),+ duration_ms: Some(+ crate::util_time::now_ms().saturating_sub(state.started_at_ms),+ ),+ tool_use_count: None,+ replied_since_task: Some(state.replied_since_task),+ });+ }+ if all_settled || deadline <= tokio::time::Instant::now() {+ return Ok(results);+ }+ let _ = tokio::time::timeout_at(deadline, notified.as_mut()).await;+ }+ })+ }++ fn rename(&self, name: String, session_id: Option<String>) -> RlmHostFuture<String> {+ let node = Arc::clone(&self.0);+ Box::pin(async move {+ let self_target = session_id+ .as_deref()+ .is_none_or(|target| target == node.session_id);+ if self_target {+ rename_session(&node, &name).await?;+ return Ok(name);+ }+ let target = session_id.unwrap_or_default();+ let children = node.children.lock().await.clone();+ let mut by_ids = None;+ let mut by_name = false;+ for child in &children {+ if child.node.session_id == target || child.rlm_child_id == target {+ by_ids = Some(Arc::clone(child));+ break;+ }+ if child.node.session_name().as_deref() == Some(target.as_str()) {+ by_name = true;+ }+ }+ let Some(child) = by_ids else {+ if by_name {+ anyhow::bail!(+ "rlm.rename session_id \"{target}\" must be the full session id or a child handle, not a session name or id suffix"+ );+ }+ anyhow::bail!(+ "rlm.rename can only rename the current session or one of its direct children"+ );+ };+ rename_session(&child.node, &name).await?;+ Ok(name)+ })+ }+}++/// Append one durable `session_info` name row to a node's session.+async fn rename_session(node: &Arc<InlineSessionNode>, name: &str) -> anyhow::Result<()> {+ let parent = node.parent_node();+ let _name_guard = if let Some(parent) = &parent {+ Some(parent.spawn_gate.lock().await)+ } else {+ None+ };+ if let Some(parent) = &parent {+ for sibling in parent.children.lock().await.iter() {+ if !Arc::ptr_eq(&sibling.node, node)+ && sibling.node.session_name().as_deref() == Some(name)+ {+ return Err(spawn_name_unavailable_error(name, node.depth));+ }+ }+ }+ let engine = node+ .engine+ .get()+ .and_then(Weak::upgrade)+ .ok_or_else(|| anyhow::anyhow!("the target session is not running"))?;+ let persistence = engine.session.shared_persistence();+ let mut session = persistence.lock().await;+ session+ .append_session_info(name)+ .map_err(anyhow::Error::from)?;+ *node.session_name.lock().unwrap() = Some(name.to_string());+ Ok(())+}++fn roster_entry(+ child: &Arc<InlineChild>,+ state: &InlineChildState,+ unsettled: bool,+) -> RlmSubagentEntry {+ RlmSubagentEntry {+ rlm_child_id: child.rlm_child_id.clone(),+ active_session_id: Some(child.node.session_id.clone()),+ session_id: Some(child.node.session_id.clone()),+ session_name: child+ .node+ .session_name()+ .unwrap_or_else(|| child.rlm_child_id.clone()),+ session_dir: child.node.session_dir.clone(),+ status: if unsettled {+ "running"+ } else {+ match state.status {+ "done" => "completed",+ other => other,+ }+ },+ activity: None,+ tool_use_count: None,+ duration_ms: Some(crate::util_time::now_ms().saturating_sub(state.started_at_ms)),+ answer_preview: state.answer_text.as_deref().map(compact_rlm_text),+ replied_since_task: Some(state.replied_since_task),+ progress_note: None,+ label: None,+ last_activity_at: Some(state.started_at_ms),+ activity_stale_ms: None,+ }+}++// The messaging controller (the `agent_message.*` kernel surface)++/// The family roster and delivery controller over one node's tree+/// position: the parent, the siblings, and the children.+struct InlineMessages(Arc<InlineSessionNode>);++impl AgentMessageController for InlineMessages {+ async fn family(&self) -> anyhow::Result<Vec<AgentFamilyMember>> {+ let node = &self.0;+ let mut members = Vec::new();+ let mut siblings = Vec::new();+ if let Some(parent) = node.parent_node() {+ members.push(AgentFamilyMember {+ relationship: AgentFamilyRelationship::Parent,+ id: parent.session_id.clone(),+ name: parent.session_name().filter(|name| !name.is_empty()),+ aliases: Vec::new(),+ });+ for sibling in parent.children.lock().await.clone() {+ if Arc::ptr_eq(&sibling.node, node) {+ continue;+ }+ siblings.push(AgentFamilyMember {+ relationship: AgentFamilyRelationship::Sibling,+ id: sibling.node.session_id.clone(),+ name: sibling.node.session_name(),+ aliases: vec![sibling.rlm_child_id.clone()],+ });+ }+ }+ siblings.sort_by(|left, right| left.member_name().cmp(right.member_name()));+ let mut children = Vec::new();+ for child in node.children.lock().await.clone() {+ children.push(AgentFamilyMember {+ relationship: AgentFamilyRelationship::Child,+ id: child.node.session_id.clone(),+ name: child.node.session_name(),+ aliases: vec![child.rlm_child_id.clone()],+ });+ }+ children.sort_by(|left, right| left.member_name().cmp(right.member_name()));+ members.extend(siblings);+ members.extend(children);+ Ok(members)+ }++ async fn send_agent_message(+ &self,+ input: AgentMessageSendInput,+ ) -> anyhow::Result<AgentMessageReceipt> {+ let node = &self.0;+ if input.target == node.session_id {+ anyhow::bail!("Agent messaging cannot target the sending session");+ }+ // The sender's relationship to the target: the parent (the+ // sender is its child), a sibling, or one of the sender's own+ // children (the sender is their parent).+ let mut target: Option<(Arc<InlineSessionNode>, AgentFamilyRelationship)> = None;+ if let Some(parent) = node.parent_node() {+ if parent.session_id == input.target {+ target = Some((Arc::clone(&parent), AgentFamilyRelationship::Child));+ }+ if target.is_none() {+ for sibling in parent.children.lock().await.iter() {+ if !Arc::ptr_eq(&sibling.node, node) && sibling.node.session_id == input.target+ {+ target =+ Some((Arc::clone(&sibling.node), AgentFamilyRelationship::Sibling));+ break;+ }+ }+ }+ }+ if target.is_none() {+ for child in node.children.lock().await.iter() {+ if child.node.session_id == input.target {+ target = Some((Arc::clone(&child.node), AgentFamilyRelationship::Parent));+ break;+ }+ }+ }+ let Some((target_node, relationship)) = target else {+ anyhow::bail!("No family member matches \"{}\"", input.target);+ };+ // Marked before the delivery, so a fast child's reply cannot race+ // the marking: a reply to the parent withholds the no-reply+ // notice; a fresh task from the parent means silence this round+ // earns it.+ match relationship {+ AgentFamilyRelationship::Child => {+ for child in target_node.children.lock().await.iter() {+ if Arc::ptr_eq(&child.node, node) {+ child.state.lock().await.replied_since_task = true;+ }+ }+ }+ AgentFamilyRelationship::Parent => {+ for child in node.children.lock().await.iter() {+ if Arc::ptr_eq(&child.node, &target_node) {+ child.state.lock().await.replied_since_task = false;+ }+ }+ }+ AgentFamilyRelationship::Sibling => {}+ }+ let prompt = create_agent_session_message_prompt(&AgentMessagePromptPayload {+ message: input.message.clone(),+ sender_name: node.sender_name(),+ from_relationship: Some(relationship),+ });+ let id = create_agent_session_message_id();+ let row = create_agent_session_message_row(&AgentSessionMessageRowPayload {+ id: &id,+ prompt: &prompt,+ message: &input.message,+ from: &node.endpoint(),+ from_relationship: Some(relationship),+ target: Some(&target_node.endpoint()),+ timestamp: crate::util_time::now_ms(),+ });+ let engine = target_node+ .engine+ .get()+ .and_then(Weak::upgrade)+ .ok_or_else(|| anyhow::anyhow!("the target session is not running"))?;+ // One delivery path: the steer lane; a streaming target picks+ // the row up at its next turn boundary, the drive drains it when+ // idle.+ let streaming = engine.session.agent().state().await.is_streaming;+ deliver_row(&target_node, row)?;+ let (delivered_at, queued_at, status) = if streaming {+ (+ None,+ Some(crate::util_time::now_iso8601()),+ AgentMessageDeliveryStatus::Queued,+ )+ } else {+ (+ Some(crate::util_time::now_iso8601()),+ None,+ AgentMessageDeliveryStatus::Delivered,+ )+ };+ Ok(AgentMessageReceipt {+ id,+ target: target_node.session_id.clone(),+ target_session_id: Some(target_node.session_id.clone()),+ target_session_name: target_node.session_name().filter(|name| !name.is_empty()),+ target_runtime_kind: None,+ message: input.message.clone(),+ delivery_status: status,+ delivery_mode: Some("steer"),+ receiver_role: input.receiver_role,+ delivered_at,+ queued_at,+ })+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn run_options(directory: &std::path::Path) -> crate::mode::RunOptions {+ crate::mode::RunOptions {+ app_mode: crate::mode::AppMode::Print,+ config: crate::mode::RuntimeConfig {+ cwd: directory.to_path_buf(),+ agent_dir: directory.join("agent"),+ ..Default::default()+ },+ session: crate::mode::SessionOptions::default(),+ messages: Vec::new(),+ file_args: Vec::new(),+ daemon_socket: None,+ list_models: None,+ initial_message: None,+ initial_images: Vec::new(),+ verbose: false,+ offline: true,+ agents_view_requested: false,+ attach_agent: None,+ }+ }++ #[tokio::test]+ async fn spawn_waiting_for_admission_rejects_a_disposed_parent() {+ let directory = tempfile::tempdir().unwrap();+ let options = run_options(directory.path());+ std::fs::create_dir_all(&options.config.agent_dir).unwrap();+ let manager = pa_core::session::manager::SessionManager::in_memory(directory.path());+ let mut node = root_node(+ &options,+ &manager,+ Some(json!({+ "responses": ["parent"],+ "children": { "late": { "responses": ["child"] } },+ })),+ );+ Arc::get_mut(&mut node).unwrap().max_depth = 2;+ let gate = node.spawn_gate.lock().await;+ let mut spawn = InlineHost(Arc::clone(&node)).spawn(RlmSpawnRequest {+ prompt: "finish the task".to_string(),+ name: Some("late".to_string()),+ model: None,+ thinking: None,+ decision_child: false,+ spawned_by_request_id: None,+ cell_source_code: None,+ });+ std::future::poll_fn(|context| {+ assert!(spawn.as_mut().poll(context).is_pending());+ std::task::Poll::Ready(())+ })+ .await;+ node.disposed+ .store(true, std::sync::atomic::Ordering::SeqCst);+ drop(gate);+ let result = spawn.await;+ let admitted = node.children.lock().await.len();+ dispose_inline_subagents(&node).await;+ let error = result.expect_err("a disposed parent must not admit a queued spawn");+ assert!(error.to_string().contains("disposed"), "{error:#}");+ assert_eq!(admitted, 0);+ }++ #[tokio::test]+ async fn delivery_to_a_disposed_session_rejects_without_queuing() {+ let directory = tempfile::tempdir().unwrap();+ let options = run_options(directory.path());+ std::fs::create_dir_all(&options.config.agent_dir).unwrap();+ let manager = pa_core::session::manager::SessionManager::in_memory(directory.path());+ let script = json!({ "responses": ["parent"] });+ let node = root_node(&options, &manager, Some(script.clone()));+ let headless = crate::print_runtime::build_engine(+ &options,+ Some(&script),+ Some(manager),+ "print",+ &HeadlessEmbedding::Root {+ node: Arc::clone(&node),+ },+ )+ .await+ .unwrap();+ let engine = Arc::new(headless.engine);+ adopt_built_engine(&node, &engine, &headless.model).await;+ let endpoint = node.endpoint();+ let row = create_agent_session_message_row(&AgentSessionMessageRowPayload {+ id: "late-message",+ prompt: "late message",+ message: "late message",+ from: &endpoint,+ from_relationship: None,+ target: Some(&endpoint),+ timestamp: 0,+ });+ dispose_inline_subagents(&node).await;+ assert!(!engine.session.agent().has_queued_messages());+ let result = deliver_row(&node, row);+ let queued = engine.session.agent().has_queued_messages();+ engine.dispose_kernel().await;+ let error = result.expect_err("a disposed session must reject a retained delivery target");+ assert!(error.to_string().contains("disposed"), "{error:#}");+ assert!(+ !queued,+ "rejected delivery must not enqueue an unread message"+ );+ }+}diff --git a/crates/pa-cli/src/print_runtime.rs b/crates/pa-cli/src/print_runtime.rsindex 47cafe8801..a538ec39b8 100644--- a/crates/pa-cli/src/print_runtime.rs+++ b/crates/pa-cli/src/print_runtime.rs@@ -325,11 +325,14 @@ fn rpc_engine_factory(options: &RunOptions) -> pa_daemon::rpc::session::RpcEngin(manager, lease)}};- let engine = if let Ok(script) = std::env::var("PRIME_AGENT_FAUX_SCRIPT") {- build_faux_engine_with(&options, &script, Some(manager), "rpc").await?- } else {- build_headless_engine_with(&options, Some(manager), "rpc").await?- };+ let engine = build_engine(+ &options,+ faux_script_env()?.as_ref(),+ Some(manager),+ "rpc",+ &HeadlessEmbedding::Rpc,+ )+ .await?;let mut handle = pa_daemon::rpc::session::RpcEngineHandle::from(engine);handle.session_lease = opened_lease;Ok(handle)@@ -393,8 +396,29 @@ async fn print_mode_main() -> Result<i32, String> {// `print` or `json`: the telemetry execution mode is the app mode (TS// main.ts `executionMode: appMode`).- let headless = build_headless_engine_parts(options, options.app_mode.as_str(), lease).await?;+ crate::telemetry_notice::print_if_due(&options.config);+ let (session_manager, opened_lease) = select_session_manager_with_lease(options)?;+ *lease = opened_lease;+ let session_manager = session_manager.unwrap_or_else(|| {+ pa_core::session::manager::SessionManager::in_memory(&options.config.cwd)+ });+ // The print root's inline-subagent node: the quiescence drive, the+ // host, and the messaging controller all hang off it. The faux+ // script (when scripted) rides the recipe down to every child.+ let faux = faux_script_env()?;+ let root_node = crate::print_rlm::root_node(options, &session_manager, faux.clone());+ let headless = build_engine(+ options,+ faux.as_ref(),+ Some(session_manager),+ options.app_mode.as_str(),+ &HeadlessEmbedding::Root {+ node: std::sync::Arc::clone(&root_node),+ },+ )+ .await?;let engine = std::sync::Arc::new(headless.engine);+ crate::print_rlm::adopt_built_engine(&root_node, &engine, &headless.model).await;// The CLI `--goal` seed: a fresh root branch starts the goal; a resumed// branch keeps its persisted goal. Depth 0 only — the print session is a root.if let Some(goal) = &options.config.initial_goal {@@ -403,24 +427,89 @@ async fn print_mode_main(.await.map_err(|error| format!("{error:#}"))?;}- run_prompts_and_emit(&engine, &headless.model, headless.api_key.clone(), options).await+ let exit = run_prompts_and_emit(+ &engine,+ &headless.model,+ headless.api_key.clone(),+ options,+ &root_node,+ )+ .await;+ // No inline descendant outlives the print process: kernels get their+ // final snapshot, drivers join, runs abort (every exit path).+ crate::print_rlm::dispose_inline_subagents(&root_node).await;+ exit+}++/// One engine build for every headless embedding: the scripted+/// verification seam when a faux script is set, the real provider+/// otherwise.+pub(crate) async fn build_engine(+ options: &RunOptions,+ faux: Option<&serde_json::Value>,+ session_manager: Option<pa_core::session::manager::SessionManager>,+ execution_mode: &str,+ embedding: &HeadlessEmbedding,+) -> Result<HeadlessEngine, String> {+ match faux {+ Some(script) => {+ build_faux_engine_with(options, script, session_manager, execution_mode, embedding)+ .await+ }+ None => {+ build_headless_engine_with(options, session_manager, execution_mode, embedding).await+ }+ }}-/// Assemble the in-process session engine for a headless run: model-/// resolution, session persistence, and the engine facade. The faux-script-/// seam (`PRIME_AGENT_FAUX_SCRIPT`) drives the same assembly without the-/// network; verification harness only, never set by the product.-///+/// The faux-script verification seam (`PRIME_AGENT_FAUX_SCRIPT`; never+/// set by the product): the script env parse, the per-child queues, and+/// the scripted engine build.+mod faux;++pub(crate) use faux::{+ build_faux_engine_with, faux_response_steps, faux_script_env, FauxChildQueue,+};+/// The switchable provider target the session's stream reads per call/// (shared with the RPC mode, whose picker model switches swap it live).pub type ProviderTargetSlot = std::sync::Arc<std::sync::RwLock<Option<ProviderTarget>>>;+/// What one engine build varies by session: the print root (inline+/// subagents over its node), a spawned inline child (its own model,+/// auth, and session), or the RPC mode (no inline subagents — today's+/// behavior).+pub(crate) enum HeadlessEmbedding {+ Root {+ node: std::sync::Arc<crate::print_rlm::InlineSessionNode>,+ },+ Child(Box<ChildEngineOverrides>),+ Rpc,+}++/// One spawned inline child's engine deltas: its model lane, the+/// thinking level it runs, and the parent-edge identity.+pub(crate) struct ChildEngineOverrides {+ pub node: std::sync::Arc<crate::print_rlm::InlineSessionNode>,+ pub lane: ChildLane,+ pub thinking: pa_types::ai::ModelThinkingLevel,+ pub semantic_parent_session_id: Option<String>,+ pub spawned_by_request_id: Option<String>,+}++/// A child's model source: a real-provider child carries its resolved+/// model; a scripted child runs its own faux queue.+pub(crate) enum ChildLane {+ Real(Box<Model>),+ Faux(FauxChildQueue),+}+/// The assembled headless engine, so host transports can drive session-command/// executors (compact/refine) with the session's own model.-struct HeadlessEngine {- engine: pa_core::session_engine::engine::SessionEngine,- model: Model,- api_key: Option<String>,+pub(crate) struct HeadlessEngine {+ pub(crate) engine: pa_core::session_engine::engine::SessionEngine,+ pub(crate) model: Model,+ pub(crate) api_key: Option<String>,/// The live provider target: the stream reads it per call, and the/// RPC mode's picker switches swap it (TS `setModel`'s stream/// re-registration; `set_model` swaps it without rebuilding the@@ -441,10 +530,14 @@ async fn build_headless_engine_parts(crate::telemetry_notice::print_if_due(&options.config);let (session_manager, opened_lease) = select_session_manager_with_lease(options)?;*lease = opened_lease;- if let Ok(script) = std::env::var("PRIME_AGENT_FAUX_SCRIPT") {- return build_faux_engine_with(options, &script, session_manager, execution_mode).await;- }- build_headless_engine_with(options, session_manager, execution_mode).await+ build_engine(+ options,+ faux_script_env()?.as_ref(),+ session_manager,+ execution_mode,+ &HeadlessEmbedding::Rpc,+ )+ .await}/// The session-manager selection every engine build shares, returning the opened session's runtime@@ -465,27 +558,38 @@ fn select_session_manager_with_lease(Ok((Some(manager), lease))}-/// The real-provider engine assembly over one session-manager selection.-async fn build_headless_engine_with(+/// The real-provider engine assembly over one session-manager selection:+/// model resolution, session persistence, and the engine facade.+pub(crate) async fn build_headless_engine_with(options: &RunOptions,session_manager: Option<pa_core::session::manager::SessionManager>,execution_mode: &str,+ embedding: &HeadlessEmbedding,) -> Result<HeadlessEngine, String> {let config = &options.config;- // Model registry: composed catalog + models.json with real auth.+ // Model registry: composed catalog + models.json with real auth. A+ // spawned child carries its already-resolved model and request auth+ // (the spawn resolved them against this same catalog).let auth = pa_core::auth::AuthStorage::create(&config.agent_dir);let mut registry =pa_core::models::ModelRegistry::create(auth, config.agent_dir.join("models.json"));registry.load_private_authorization_from_cache();- let model = select_model(- &mut registry,- config.provider.as_deref(),- config.model.as_deref(),- )?;-+ let model = match embedding {+ HeadlessEmbedding::Child(overrides) => match &overrides.lane {+ ChildLane::Real(model) => (**model).clone(),+ ChildLane::Faux(_) => {+ return Err("a scripted child builds through the faux builder".to_string());+ }+ },+ HeadlessEmbedding::Root { .. } | HeadlessEmbedding::Rpc => select_model(+ &mut registry,+ config.provider.as_deref(),+ config.model.as_deref(),+ )?,+ };// Resolve request auth once: the stored team / `PRIME_TEAM_ID` reach the wire through these- // headers.+ // headers (children resolve against the same catalog the spawn used).let resolved = registry.get_api_key_and_headers(&model, model.headers.as_ref());let provider_target: ProviderTargetSlot =@@ -495,27 +599,47 @@ async fn build_headless_engine_with(service_tier: None,headers: resolved.headers.clone(),})));- // While an episode is armed the stream serves THIS target, so a concurrent- // `set_model` picker write cannot redirect an in-flight routed turn.- let armed_target: std::sync::Arc<std::sync::Mutex<Option<ProviderTarget>>> =- std::sync::Arc::new(std::sync::Mutex::new(None));- let stream_fn = route_authoritative_stream_fn(- std::sync::Arc::clone(&provider_target),- std::sync::Arc::clone(&armed_target),- );- // TS settings.imageModel routing: image-attaching batches on a session model- // without image input route to the configured image model or refuse.- let image_model_router = headless_image_model_router(- &provider_target,- std::sync::Arc::clone(&armed_target),- config.cwd.clone(),- config.agent_dir.clone(),- model.clone(),- );let agent_model: AgentModel = json_round_trip(&model).ok_or("model conversion failed")?;+ // Children serve their own provider target (the route-authoritative+ // stream would serve the parent's model, and children have no+ // image-model routing).+ let (stream_fn, image_model_router) = if matches!(embedding, HeadlessEmbedding::Child(_)) {+ (+ switchable_stream_fn(std::sync::Arc::clone(&provider_target)),+ None,+ )+ } else {+ // While an episode is armed the stream serves THIS target, so a concurrent+ // `set_model` picker write cannot redirect an in-flight routed turn.+ let armed_target: std::sync::Arc<std::sync::Mutex<Option<ProviderTarget>>> =+ std::sync::Arc::new(std::sync::Mutex::new(None));+ let stream_fn = route_authoritative_stream_fn(+ std::sync::Arc::clone(&provider_target),+ std::sync::Arc::clone(&armed_target),+ );+ // TS settings.imageModel routing: image-attaching batches on a session model+ // without image input route to the configured image model or refuse.+ (+ stream_fn,+ Some(headless_image_model_router(+ &provider_target,+ armed_target,+ config.cwd.clone(),+ config.agent_dir.clone(),+ model.clone(),+ )),+ )+ };+// Telemetry: the CLI's env/settings opt-out decides; depth 0 only, enforced by the engine.- let telemetry = (!config.telemetry_disabled).then(|| {+ // A spawned child never reports (the engine's depth gate holds anyway).+ let telemetry = (!config.telemetry_disabled+ && matches!(+ embedding,+ HeadlessEmbedding::Root { .. } | HeadlessEmbedding::Rpc+ ))+ .then(|| {let settings = pa_core::settings::SettingsManager::create(&config.cwd, &config.agent_dir);pa_core::session_engine::telemetry::TelemetryWiring {client: pa_core::session_engine::telemetry::build_client(&settings, &config.agent_dir),@@ -553,17 +677,50 @@ async fn build_headless_engine_with(// ledger-less but the request ids still go on the wire.let session_manager = session_manager.unwrap_or_else(|| pa_core::session::manager::SessionManager::in_memory(&config.cwd));- let semantic_edges = Some(- pa_core::session_engine::semantic_edges::SemanticEdgeIdentity {- session_id: session_manager.get_session_id().to_string(),- ledger_path: pa_core::session_engine::semantic_edges::semantic_edge_ledger_path(- None,- session_manager.get_session_artifact_dir().as_deref(),+ let (rlm_subagent_host, extra_host_handlers) = match embedding {+ HeadlessEmbedding::Rpc => (None, None),+ HeadlessEmbedding::Root { node } => {+ let (host, handlers) = crate::print_rlm::inline_subagent_wiring(node);+ (Some(host), Some(handlers))+ }+ HeadlessEmbedding::Child(overrides) => {+ let (host, handlers) = crate::print_rlm::inline_subagent_wiring(&overrides.node);+ (Some(host), Some(handlers))+ }+ };+ let (semantic_edges, rlm_depth, thinking_level) = match embedding {+ HeadlessEmbedding::Child(overrides) => (+ Some(+ pa_core::session_engine::semantic_edges::SemanticEdgeIdentity {+ session_id: session_manager.get_session_id().to_string(),+ // A spawned child's ledger lives in its rlm session dir.+ ledger_path: pa_core::session_engine::semantic_edges::semantic_edge_ledger_path(+ Some(std::path::Path::new(&overrides.node.session_dir)),+ session_manager.get_session_artifact_dir().as_deref(),+ ),+ parent_session_id: overrides.semantic_parent_session_id.clone(),+ spawned_by_request_id: overrides.spawned_by_request_id.clone(),+ },),- parent_session_id: None,- spawned_by_request_id: None,- },- );+ Some(overrides.node.depth),+ Some(pa_core::session_engine::provider_adapter::map_thinking_level(overrides.thinking)),+ ),+ HeadlessEmbedding::Root { .. } | HeadlessEmbedding::Rpc => (+ Some(+ pa_core::session_engine::semantic_edges::SemanticEdgeIdentity {+ session_id: session_manager.get_session_id().to_string(),+ ledger_path: pa_core::session_engine::semantic_edges::semantic_edge_ledger_path(+ None,+ session_manager.get_session_artifact_dir().as_deref(),+ ),+ parent_session_id: None,+ spawned_by_request_id: None,+ },+ ),+ None,+ Some(resolve_thinking_level(config, &model)),+ ),+ };let engine = pa_core::session_engine::engine::create_session(pa_core::session_engine::engine::SessionEngineConfig {on_late_sent_agent_message: None,@@ -576,7 +733,7 @@ async fn build_headless_engine_with(agent_dir: config.agent_dir.clone(),mcp_manager: Some(mcp_manager),model: Some(agent_model),- thinking_level: Some(resolve_thinking_level(config, &model)),+ thinking_level,stream_fn: Some(stream_fn),tools: builtin_tools(&config.cwd),custom_system_prompt: config.system_prompt.clone(),@@ -584,7 +741,7 @@ async fn build_headless_engine_with(generic_mcp_servers: vec![],allow_recursion: None,session_manager: Some(session_manager),- extra_host_handlers: None,+ extra_host_handlers,conversation_log_path: None,additional_skill_paths: config.skills@@ -597,15 +754,18 @@ async fn build_headless_engine_with(.map(|path| path.display().to_string()).collect(),extra_builtin_skill_overrides: vec![],- rlm_subagent_host: None,- rlm_depth: None,+ rlm_subagent_host,+ rlm_depth,+ daemonless: true,model_info: Some(model.clone()),- // The kernel boots in the background at creation.- prewarm_ipython_kernel: Some(true),+ // The kernel boots in the background at creation; a spawned+ // child boots lazily on first use.+ prewarm_ipython_kernel: (!matches!(embedding, HeadlessEmbedding::Child(_)))+ .then_some(true),on_background_work_settled: None,queued_goal_context_purge: None,queued_steering_probe: None,- image_model_router: Some(image_model_router),+ image_model_router,},).await@@ -1189,6 +1349,7 @@ async fn run_prompts_and_emit(model: &Model,api_key: Option<String>,options: &RunOptions,+ root_node: &std::sync::Arc<crate::print_rlm::InlineSessionNode>,) -> Result<i32, String> {let json_mode = options.app_mode == AppMode::Json;let mut unsubscribe: Option<pa_agent::agent::Subscription> = None;@@ -1224,14 +1385,16 @@ async fn run_prompts_and_emit(None => HeadlessAutonomous::disabled(&options.config.cwd),});let accounting = autonomous.wire_accounting(engine.session.agent()).await;- // The composed natural-turn-end hook: the goal arm first (exclusive priority), the autonomous- // arm on the fall-through.+ // The composed natural-turn-end hook: the goal arm first (exclusive priority), the+ // autonomous arm on the fall-through; both arms defer while inline-subagent work is+ // unsettled.crate::print_autonomous::wire_continuation_hook(engine,engine.session.agent(),model,&goal,&autonomous,+ Some(root_node),);let global_harness_dir =pa_core::refinement::get_global_harness_state_dir(&options.config.agent_dir);@@ -1307,18 +1470,17 @@ async fn run_prompts_and_emit(boundary.run_at_settled_turn(engine, model, api_key.clone(), global_harness_dir.clone()).await?;- let goal_owns_boundary = goal- .drive_boundary(- engine,- &mut boundary,- model,- api_key.clone(),- global_harness_dir.clone(),- )- .await?;+ goal.drive_boundary(+ engine,+ &mut boundary,+ model,+ api_key.clone(),+ global_harness_dir.clone(),+ )+ .await?;// The autonomous arm runs only when the goal does not own the boundary (the goal arm takes// exclusive priority).- if !goal_owns_boundary {+ if !engine.goal_owns_continuation_wakeup().await {// The held threshold continuation drains as this invocation's follow-up// turn; the stop surfaces only through the exit contract.autonomous@@ -1333,20 +1495,101 @@ async fn run_prompts_and_emit(.map_err(|error| format!("{error:#}"))?;}}- goal_accounting.unsubscribe().await;- accounting.unsubscribe().await;- if let Some(subscription) = unsubscribe {- subscription.unsubscribe().await;- }// The rejected prompt wait: print the raw command error to stderr and// exit 1 — no later prompts ran, and the disposal drain still runs.if let Some(error) = command_failure {eprintln!("{error}");+ goal_accounting.unsubscribe().await;+ accounting.unsubscribe().await;+ if let Some(subscription) = unsubscribe {+ subscription.unsubscribe().await;+ }boundary.drain_compact_auto_refine_at_disposal(engine, model, api_key, global_harness_dir).await;return Ok(1);}+ // The #2270 fix: print waits for RLM quiescence — every admitted+ // descendant settles and its replies and notices drain as turns —+ // before the terminal result is selected (json mode keeps streaming;+ // the subscription lives until after the drive). One drive loop then+ // keeps the run alive while deferred work exists: the deferred+ // goal/autonomous continuations deliver after the settle ("no+ // front": the settling child's terminal notice is read first), and+ // the boundary drain runs whatever turns it drained armed — a+ // threshold continuation, a budget steer, more descendants.+ loop {+ if crate::print_rlm::drive_to_quiescence(+ root_node,+ engine,+ &mut boundary,+ model,+ api_key.clone(),+ global_harness_dir.clone(),+ )+ .await?+ {+ continue;+ }+ if let Some(continuation) = engine.take_owed_goal_continuation().await {+ goal.publish_goal_update(engine).await;+ goal.run_queued_turn(+ engine,+ &mut boundary,+ model,+ api_key.clone(),+ global_harness_dir.clone(),+ &continuation,+ )+ .await?;+ continue;+ }+ if autonomous+ .deliver_rlm_continuation(+ engine,+ &mut boundary,+ model,+ api_key.clone(),+ global_harness_dir.clone(),+ )+ .await?+ {+ continue;+ }+ // The boundary drain: turns it ran may spawn descendants or arm+ // more holds, so it reports whether it ran and the loop goes+ // around — the leading quiescence pass then waits for whatever+ // they left behind.+ let mut boundary_ran = goal+ .drive_boundary(+ engine,+ &mut boundary,+ model,+ api_key.clone(),+ global_harness_dir.clone(),+ )+ .await?;+ if !engine.goal_owns_continuation_wakeup().await {+ boundary_ran |= autonomous+ .drive_boundary(+ engine,+ &mut boundary,+ model,+ api_key.clone(),+ global_harness_dir.clone(),+ )+ .await?;+ }+ if boundary_ran {+ continue;+ }+ break;+ }+ goal_accounting.unsubscribe().await;+ accounting.unsubscribe().await;+ if let Some(subscription) = unsubscribe {+ subscription.unsubscribe().await;+ }let state = engine.session.agent().state().await;let messages: Vec<pa_types::session::AgentMessage> =state.messages.iter().filter_map(json_round_trip).collect();@@ -1395,158 +1638,6 @@ async fn run_prompts_and_emit(Ok(exit_code)}-/// The faux-script engine: identical session assembly, scripted provider.-async fn build_faux_engine_with(- options: &RunOptions,- script: &str,- session_manager: Option<pa_core::session::manager::SessionManager>,- // The execution mode label carries through the real path only.- _execution_mode: &str,-) -> Result<HeadlessEngine, String> {- let config = &options.config;- let script: serde_json::Value = serde_json::from_str(script)- .map_err(|error| format!("invalid PRIME_AGENT_FAUX_SCRIPT: {error}"))?;- // Response entries: a plain string answers with fixed text; `{"systemPrompt":- // true}` answers with the request's system prompt; other objects go through the- // shared faux-script parser.- let response_steps: Vec<pa_ai::faux::FauxResponseStep> = script- .get("responses")- .and_then(serde_json::Value::as_array)- .map(|entries| {- entries- .iter()- .map(|entry| match entry {- serde_json::Value::String(text) => Ok(pa_ai::faux::FauxResponseStep::Message(- pa_ai::faux::faux_assistant_text_message(- text,- pa_ai::faux::FauxAssistantMessageOptions::default(),- ),- )),- serde_json::Value::Object(map)- if map.get("systemPrompt").and_then(serde_json::Value::as_bool)- == Some(true) =>- {- Ok(pa_ai::faux::FauxResponseStep::Factory(std::sync::Arc::new(- |context, _options, _call, _model| {- Ok(pa_ai::faux::faux_assistant_text_message(- context.system_prompt.as_deref().unwrap_or_default(),- pa_ai::faux::FauxAssistantMessageOptions::default(),- ))- },- )))- }- serde_json::Value::Object(_) => {- pa_ai::faux::script::parse_faux_script(&serde_json::json!({- "responses": [entry]- }))- .map(|parsed| {- let mut steps = parsed.responses.into_iter();- let first = steps- .next()- .expect("an object entry parses into one response step");- debug_assert!(steps.next().is_none());- first- })- }- _ => Ok(pa_ai::faux::FauxResponseStep::Message(- pa_ai::faux::faux_assistant_text_message(- "",- pa_ai::faux::FauxAssistantMessageOptions::default(),- ),- )),- })- .collect::<Result<Vec<_>, String>>()- })- .ok_or_else(|| "PRIME_AGENT_FAUX_SCRIPT requires a responses array".to_string())??;- // A `reasoning` model makes the harness script thinking-capable turns so- // thinking-level resolution can be verified without the network.- let reasoning = script- .get("reasoning")- .and_then(serde_json::Value::as_bool)- .unwrap_or(false);- // The script pins the context window: threshold/overflow verifiers size it to the probe they- // run.- let context_window = script- .get("contextWindow")- .and_then(serde_json::Value::as_u64)- .unwrap_or(100_000);- // The stable faux identity (`api: "faux"`, `provider: "faux"`): fixtures can declare- // faux-provider models in models.json.- let registration =- pa_ai::faux::register_faux_provider(pa_ai::faux::RegisterFauxProviderOptions {- api: Some("faux".to_string()),- provider: Some("faux".to_string()),- models: Some(vec![pa_ai::faux::FauxModelDefinition {- id: "faux-1".to_string(),- name: Some("Faux Model".to_string()),- reasoning: Some(reasoning),- input: Some(vec![pa_types::ai::ModelInput::Text]),- cost: None,- context_window: Some(context_window),- max_tokens: Some(4_096),- }]),- ..Default::default()- });- registration.set_responses(response_steps);- let model = registration.get_model();- let agent_model = json_round_trip(&model).ok_or("model conversion failed")?;- let provider_target: ProviderTargetSlot =- std::sync::Arc::new(std::sync::RwLock::new(Some(ProviderTarget {- api_key: None,- model: model.clone(),- service_tier: None,- headers: None,- })));- let stream_fn = switchable_stream_fn(std::sync::Arc::clone(&provider_target));- // The faux path shares the session-manager wiring with the real provider- // path so binary-level tests can verify persistence without the network.- let 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,- steering_mode: None,- follow_up_mode: None,- telemetry: None,- cwd: config.cwd.clone(),- agent_dir: config.agent_dir.clone(),- mcp_manager: None,- model: Some(agent_model),- thinking_level: Some(resolve_thinking_level(config, &model)),- stream_fn: Some(stream_fn),- tools: builtin_tools(&config.cwd),- custom_system_prompt: config.system_prompt.clone(),- prompt_guidelines: config.append_system_prompt.clone(),- generic_mcp_servers: vec![],- allow_recursion: None,- session_manager,- extra_host_handlers: None,- conversation_log_path: None,- additional_skill_paths: vec![],- additional_prompt_paths: vec![],- extra_builtin_skill_overrides: vec![],- rlm_subagent_host: None,- rlm_depth: None,- model_info: Some(model.clone()),- // A Rust-only verification harness: no background kernel boot in tests.- prewarm_ipython_kernel: None,- on_background_work_settled: None,- queued_goal_context_purge: None,- queued_steering_probe: None,- image_model_router: None,- },- )- .await- .map_err(|error| format!("{error:#}"))?;- Ok(HeadlessEngine {- engine,- model,- api_key: None,- provider_target,- })-}-#[cfg(test)]mod tests {diff --git a/crates/pa-cli/src/print_runtime/faux.rs b/crates/pa-cli/src/print_runtime/faux.rsnew file mode 100644index 0000000000..801dea967c--- /dev/null+++ b/crates/pa-cli/src/print_runtime/faux.rs@@ -0,0 +1,234 @@+//! The faux-script verification seam (`PRIME_AGENT_FAUX_SCRIPT`): the+//! script env parse, one per-child response queue per spawned child, the+//! scripted engine build, and the response-step parser. Never set by the+//! product.++use pa_core::session_engine::provider_adapter::{+ json_round_trip, switchable_stream_fn, ProviderTarget,+};++use crate::print_runtime::{+ ChildLane, HeadlessEmbedding, HeadlessEngine, ProviderTargetSlot, RunOptions,+};++/// The parsed `PRIME_AGENT_FAUX_SCRIPT` (the whole-process verification+/// seam; never set by the product): `None` on a live run, an error when+/// the script does not parse.+pub(crate) fn faux_script_env() -> Result<Option<serde_json::Value>, String> {+ match std::env::var("PRIME_AGENT_FAUX_SCRIPT") {+ Ok(script) => serde_json::from_str(&script)+ .map(Some)+ .map_err(|error| format!("invalid PRIME_AGENT_FAUX_SCRIPT: {error}")),+ Err(_) => Ok(None),+ }+}++/// The per-child faux queue: its own registered provider (keyed by the+/// child id, so siblings never share a response lane) and its steps.+pub(crate) struct FauxChildQueue {+ pub child_id: String,+ pub steps: Vec<pa_ai::faux::FauxResponseStep>,+ pub repeat_last: bool,+}++/// The faux-script engine: identical session assembly, scripted provider.+/// A spawned child in a scripted run registers its OWN provider (keyed by+/// the child id) with the queue under `children.<spawn name>`, so+/// multi-child runs stay deterministic (the registry is process-global).+pub(crate) async fn build_faux_engine_with(+ options: &RunOptions,+ script: &serde_json::Value,+ session_manager: Option<pa_core::session::manager::SessionManager>,+ // The execution mode label carries through the real path only.+ _execution_mode: &str,+ embedding: &HeadlessEmbedding,+) -> Result<HeadlessEngine, String> {+ let config = &options.config;+ // Response entries: a plain string answers with fixed text; `{"systemPrompt":+ // true}` answers with the request's system prompt; other objects go through the+ // shared faux-script parser.+ let response_steps = faux_response_steps(+ script+ .get("responses")+ .and_then(serde_json::Value::as_array)+ .ok_or_else(|| "PRIME_AGENT_FAUX_SCRIPT requires a responses array".to_string())?,+ )?;+ // A `reasoning` model makes the harness script thinking-capable turns so+ // thinking-level resolution can be verified without the network.+ let reasoning = script+ .get("reasoning")+ .and_then(serde_json::Value::as_bool)+ .unwrap_or(false);+ // The script pins the context window: threshold/overflow verifiers size it to the probe they+ // run.+ let context_window = script+ .get("contextWindow")+ .and_then(serde_json::Value::as_u64)+ .unwrap_or(100_000);+ // The stable faux identity (`api: "faux"`, `provider: "faux"`): fixtures can declare+ // faux-provider models in models.json. A spawned child gets its own api+ // lane so its queue never interleaves with its parent's.+ let (api, child_queue) = match embedding {+ HeadlessEmbedding::Child(overrides) => match &overrides.lane {+ ChildLane::Faux(queue) => (format!("faux-{}", queue.child_id), Some(queue)),+ ChildLane::Real(_) => {+ return Err("a real-provider child builds through the headless builder".to_string());+ }+ },+ HeadlessEmbedding::Root { .. } | HeadlessEmbedding::Rpc => ("faux".to_string(), None),+ };+ let registration =+ pa_ai::faux::register_faux_provider(pa_ai::faux::RegisterFauxProviderOptions {+ api: Some(api),+ provider: Some("faux".to_string()),+ models: Some(vec![pa_ai::faux::FauxModelDefinition {+ id: "faux-1".to_string(),+ name: Some("Faux Model".to_string()),+ reasoning: Some(reasoning),+ input: Some(vec![pa_types::ai::ModelInput::Text]),+ cost: None,+ context_window: Some(context_window),+ max_tokens: Some(4_096),+ }]),+ ..Default::default()+ });+ if let Some(queue) = child_queue {+ registration.set_responses(queue.steps.clone());+ registration.set_repeat_last_response(queue.repeat_last);+ } else {+ registration.set_responses(response_steps);+ registration.set_repeat_last_response(+ script+ .get("repeatLastResponse")+ .and_then(serde_json::Value::as_bool)+ .unwrap_or(false),+ );+ }+ let model = registration.get_model();+ let thinking_level = match embedding {+ HeadlessEmbedding::Child(overrides) => {+ Some(pa_core::session_engine::provider_adapter::map_thinking_level(overrides.thinking))+ }+ HeadlessEmbedding::Root { .. } | HeadlessEmbedding::Rpc => {+ Some(super::resolve_thinking_level(config, &model))+ }+ };+ let agent_model = json_round_trip(&model).ok_or("model conversion failed")?;+ let provider_target: ProviderTargetSlot =+ std::sync::Arc::new(std::sync::RwLock::new(Some(ProviderTarget {+ api_key: None,+ model: model.clone(),+ service_tier: None,+ headers: None,+ })));+ let stream_fn = switchable_stream_fn(std::sync::Arc::clone(&provider_target));+ // The faux path shares the session-manager wiring with the real provider+ // path so binary-level tests can verify persistence without the network.+ let (rlm_subagent_host, extra_host_handlers, rlm_depth) = match embedding {+ HeadlessEmbedding::Rpc => (None, None, None),+ HeadlessEmbedding::Root { node } => {+ let (host, handlers) = crate::print_rlm::inline_subagent_wiring(node);+ (Some(host), Some(handlers), None)+ }+ HeadlessEmbedding::Child(overrides) => {+ let (host, handlers) = crate::print_rlm::inline_subagent_wiring(&overrides.node);+ (Some(host), Some(handlers), Some(overrides.node.depth))+ }+ };+ let 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,+ steering_mode: None,+ follow_up_mode: None,+ telemetry: None,+ cwd: config.cwd.clone(),+ agent_dir: config.agent_dir.clone(),+ mcp_manager: None,+ model: Some(agent_model),+ thinking_level,+ stream_fn: Some(stream_fn),+ tools: super::builtin_tools(&config.cwd),+ custom_system_prompt: config.system_prompt.clone(),+ prompt_guidelines: config.append_system_prompt.clone(),+ generic_mcp_servers: vec![],+ allow_recursion: None,+ session_manager,+ extra_host_handlers,+ conversation_log_path: None,+ additional_skill_paths: vec![],+ additional_prompt_paths: vec![],+ extra_builtin_skill_overrides: vec![],+ rlm_subagent_host,+ rlm_depth,+ daemonless: true,+ model_info: Some(model.clone()),+ // A Rust-only verification harness: no background kernel boot in tests.+ prewarm_ipython_kernel: None,+ on_background_work_settled: None,+ queued_goal_context_purge: None,+ queued_steering_probe: None,+ image_model_router: None,+ },+ )+ .await+ .map_err(|error| format!("{error:#}"))?;+ Ok(HeadlessEngine {+ engine,+ model,+ api_key: None,+ provider_target,+ })+}++/// One scripted response entry: a plain string answers with fixed text;+/// `{"systemPrompt": true}` answers with the request's system prompt;+/// other objects go through the shared faux-script parser.+pub(crate) fn faux_response_steps(+ entries: &[serde_json::Value],+) -> Result<Vec<pa_ai::faux::FauxResponseStep>, String> {+ entries+ .iter()+ .map(|entry| match entry {+ serde_json::Value::String(text) => Ok(pa_ai::faux::FauxResponseStep::Message(+ pa_ai::faux::faux_assistant_text_message(+ text,+ pa_ai::faux::FauxAssistantMessageOptions::default(),+ ),+ )),+ serde_json::Value::Object(map)+ if map.get("systemPrompt").and_then(serde_json::Value::as_bool) == Some(true) =>+ {+ Ok(pa_ai::faux::FauxResponseStep::Factory(std::sync::Arc::new(+ |context, _options, _call, _model| {+ Ok(pa_ai::faux::faux_assistant_text_message(+ context.system_prompt.as_deref().unwrap_or_default(),+ pa_ai::faux::FauxAssistantMessageOptions::default(),+ ))+ },+ )))+ }+ serde_json::Value::Object(_) => {+ pa_ai::faux::script::parse_faux_script(&serde_json::json!({+ "responses": [entry]+ }))+ .map(|parsed| {+ let mut steps = parsed.responses.into_iter();+ let first = steps+ .next()+ .expect("an object entry parses into one response step");+ debug_assert!(steps.next().is_none());+ first+ })+ }+ _ => Ok(pa_ai::faux::FauxResponseStep::Message(+ pa_ai::faux::faux_assistant_text_message(+ "",+ pa_ai::faux::FauxAssistantMessageOptions::default(),+ ),+ )),+ })+ .collect()+}diff --git a/crates/pa-cli/src/print_session_command.rs b/crates/pa-cli/src/print_session_command.rsindex 8bfbe73b5b..a79955bdd0 100644--- a/crates/pa-cli/src/print_session_command.rs+++ b/crates/pa-cli/src/print_session_command.rs@@ -345,6 +345,7 @@ mod tests {additional_prompt_paths: Vec::new(),extra_builtin_skill_overrides: Vec::new(),rlm_subagent_host: None,+ daemonless: true,rlm_depth: None,model_info: Some(model.clone()),prewarm_ipython_kernel: None,@@ -372,6 +373,7 @@ mod tests {&model,&goal,&run,+ /*root_node*/ None,);let autonomous = run.state_handle();Bed {diff --git a/crates/pa-cli/tests/clipboard_auth_commands_e2e.rs b/crates/pa-cli/tests/clipboard_auth_commands_e2e.rsindex 8865163f7f..eb3c4274cf 100644--- a/crates/pa-cli/tests/clipboard_auth_commands_e2e.rs+++ b/crates/pa-cli/tests/clipboard_auth_commands_e2e.rs@@ -124,6 +124,7 @@ fn spawn_supervisor(dir: &Path) -> Supervisor {let socket = dir.join("daemon.sock");let agent_dir = dir.join("agent");std::fs::create_dir_all(&agent_dir).expect("agent dir");+ let stderr_path = dir.join("supervisor.stderr");let mut command = Command::new(env!("CARGO_BIN_EXE_prime-agent"));command.args(["--mode", "daemon", "--daemon-socket"])@@ -131,7 +132,7 @@ fn spawn_supervisor(dir: &Path) -> Supervisor {.env("PRIME_AGENT_CODING_AGENT_DIR", &agent_dir).stdin(Stdio::null()).stdout(Stdio::null())- .stderr(Stdio::null());+ .stderr(std::fs::File::create(&stderr_path).expect("supervisor stderr"));for var in [pa_daemon::worker::WORKER_ROLE_ENV,pa_daemon::worker::WORKER_TOKEN_ENV,@@ -156,15 +157,22 @@ fn spawn_supervisor(dir: &Path) -> Supervisor {pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,"15000",);- let child = command.spawn().expect("spawn prime-agent --mode daemon");+ let mut child = command.spawn().expect("spawn prime-agent --mode daemon");let deadline = Instant::now() + Duration::from_secs(15);while Instant::now() < deadline {- if socket.exists() {+ if let Some(status) = child.try_wait().expect("check supervisor exit") {+ let stderr = std::fs::read_to_string(&stderr_path).unwrap_or_default();+ panic!("supervisor exited before accepting connections ({status}); stderr: {stderr}");+ }+ if std::os::unix::net::UnixStream::connect(&socket).is_ok() {return Supervisor { child, socket };}std::thread::sleep(Duration::from_millis(20));}- panic!("supervisor socket never appeared");+ let _ = child.kill();+ let _ = child.wait();+ let stderr = std::fs::read_to_string(&stderr_path).unwrap_or_default();+ panic!("supervisor never accepted a connection within 15s; stderr: {stderr}");}// Scripted hooks (composition-root seams; the verifier drives the traits directly).diff --git a/crates/pa-cli/tests/print_inline_subagents_e2e.rs b/crates/pa-cli/tests/print_inline_subagents_e2e.rsnew file mode 100644index 0000000000..3ede60ab2e--- /dev/null+++ b/crates/pa-cli/tests/print_inline_subagents_e2e.rs@@ -0,0 +1,1107 @@+// large_futures: stack futures on hot paths by design.+// too_many_lines: style gate, not correctness. Casts: 64-bit targets;+// narrowing sits at bounded OS/OS-protocol boundaries.+#![allow(+ clippy::large_futures,+ clippy::too_many_lines,+ clippy::cast_possible_truncation,+ clippy::cast_possible_wrap,+ clippy::cast_sign_loss,+ clippy::cast_precision_loss+)]++//! End-to-end inline (daemonless) RLM subagents in print mode: the real+//! binary, a scripted faux provider, and a real Python kernel drive the+//! full in-process tree — spawn, child reply turns, the #2270 quiescence+//! wait, the depth gate, and the exit disposal.++use std::path::{Path, PathBuf};++/// One isolated print run: a hermetic HOME + agent dir, the faux script+/// as the environment seam, and the kernel Python for the ipython lanes.+struct PrintLane {+ home: tempfile::TempDir,+ agent_dir: PathBuf,+}++fn lane() -> PrintLane {+ let home = tempfile::TempDir::new().unwrap();+ let agent_dir = home.path().join("agent");+ std::fs::create_dir_all(&agent_dir).unwrap();+ PrintLane { home, agent_dir }+}++impl PrintLane {+ /// The kernel Python with prime-agent-runtime installed; set+ /// `PA_E2E_KERNEL_PYTHON` to point at an explicit interpreter. A+ /// missing kernel FAILS the lane loudly (these e2es are the+ /// subagent surface's proof — a skip would read green while+ /// proving nothing).+ fn kernel_python() -> PathBuf {+ if let Some(explicit) = std::env::var_os("PA_E2E_KERNEL_PYTHON") {+ let explicit = PathBuf::from(explicit);+ assert!(+ explicit.exists(),+ "PA_E2E_KERNEL_PYTHON {} not found",+ explicit.display()+ );+ return explicit;+ }+ let candidate = PathBuf::from(std::env::var("HOME").map_or_else(+ |_| "/home/ubuntu/.prime/agent/kernel-venv/bin/python".to_string(),+ |home| format!("{home}/.prime/agent/kernel-venv/bin/python"),+ ));+ assert!(+ candidate.exists(),+ "kernel python {} not found: set PA_E2E_KERNEL_PYTHON (the kernel-venv layout the \+ product's own bootstrap creates) — the inline-subagent e2es cannot run without one",+ candidate.display()+ );+ candidate+ }++ fn run(+ &self,+ args: &[&str],+ script: &serde_json::Value,+ kernel_python: &Path,+ env_extra: &[(&str, &str)],+ ) -> (String, String, i32) {+ let bin = env!("CARGO_BIN_EXE_prime-agent");+ // An explicitly selected kernel bypasses skill installation. Exercise+ // the checkout's messaging and goal skills even in a fresh kernel venv.+ let skills = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../skills");+ let mut python_paths = vec![skills.join("agent-message/src"), skills.join("goal/src")];+ if let Some(existing) = std::env::var_os("PYTHONPATH") {+ python_paths.extend(std::env::split_paths(&existing));+ }+ let mut command = std::process::Command::new(bin);+ command+ .args(args)+ .env("HOME", self.home.path())+ .env("PRIME_AGENT_CODING_AGENT_DIR", &self.agent_dir)+ .env("PRIME_AGENT_FAUX_SCRIPT", script.to_string())+ .env("PRIME_AGENT_KERNEL_PYTHON", kernel_python)+ .env(+ "PYTHONPATH",+ std::env::join_paths(python_paths).expect("skill import paths"),+ )+ .env_remove("RLM_DEPTH")+ .env_remove("RLM_MAX_DEPTH")+ .env_remove("PRIME_AGENT_SESSION_DIR")+ .env_remove("PRIME_AGENT_CODING_AGENT_SESSION_DIR")+ .current_dir(self.home.path());+ for (key, value) in env_extra {+ command.env(key, value);+ }+ // Bound a broken quiescence loop without waiting for the entire CI+ // shard to expire. Files retain diagnostics even when the child hangs.+ let stdout_path = self.home.path().join("stdout.log");+ let stderr_path = self.home.path().join("stderr.log");+ command+ .stdout(std::fs::File::create(&stdout_path).unwrap())+ .stderr(std::fs::File::create(&stderr_path).unwrap());+ pa_core::platform::set_new_process_group(&mut command);+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap();+ let status = runtime.block_on(async {+ let mut child = tokio::process::Command::from(command)+ .kill_on_drop(true)+ .spawn()+ .expect("binary present");+ let pid = child.id().expect("running child") as i32;+ if let Ok(status) =+ tokio::time::timeout(std::time::Duration::from_secs(120), child.wait()).await+ {+ Some(status.expect("print run exits"))+ } else {+ let _ = pa_core::platform::kill_process_group_or_pid(pid);+ let _ = child.wait().await;+ None+ }+ });+ let stdout = std::fs::read_to_string(stdout_path).unwrap();+ let stderr = std::fs::read_to_string(stderr_path).unwrap();+ let status = status.unwrap_or_else(|| {+ panic!("print run exceeded 120s; stderr: {stderr}\nstdout: {stdout}")+ });+ (stdout, stderr, status.code().unwrap_or(-1))+ }++ /// The one persisted parent session file the print run wrote.+ fn parent_session_file(&self) -> PathBuf {+ let sessions = self.agent_dir.join("sessions");+ let listing = std::fs::read_dir(&sessions).unwrap_or_else(|error| {+ panic!(+ "the print run persisted its session ({}): {error}; agent dir: {:?}",+ sessions.display(),+ std::fs::read_dir(self.home.path())+ .map(|entries| entries+ .flatten()+ .map(|entry| entry.path())+ .collect::<Vec<_>>())+ .unwrap_or_default()+ )+ });+ let mut files: Vec<PathBuf> = listing+ .flatten()+ .map(|entry| entry.path())+ .filter(|path| path.extension().and_then(|e| e.to_str()) == Some("jsonl"))+ .collect();+ files.sort();+ assert_eq!(files.len(), 1, "one parent session file: {files:?}");+ files.into_iter().next().unwrap()+ }++ /// The session entries of one jsonl file.+ fn entries(path: &Path) -> Vec<serde_json::Value> {+ std::fs::read_to_string(path)+ .expect("the session file is readable")+ .lines()+ .map(serde_json::from_str)+ .collect::<Result<_, _>>()+ .expect("the session file is valid jsonl")+ }+}++/// The parent's spawn cell (turn 1): two named children, then the turn+/// ends while both still run — the #2270 scenario.+fn spawn_cell() -> String {+ "a = await rlm.spawn(\"run the alpha task\", name=\"alpha\")\n\+ b = await rlm.spawn(\"run the beta task\", name=\"beta\")\n\+ print(\"SPAWNED\", a.rlm_child_id, b.rlm_child_id)"+ .to_string()+}++/// One child's reply cell: the ipython lane sends the parent a message+/// (the reply that must survive the print run staying open).+fn reply_cell(child: &str) -> String {+ format!(+ "await agent_message.send(\"{child}-RESULT\", receiver_role=\"parent\")\nprint(\"{child} REPLIED\")"+ )+}++/// The parent script whose every later turn answers with the combined+/// text: the replies may drain as one or two turns (the steering queue+/// batches per delivery), so the terminal result must be the same+/// either way (`repeatLastResponse` keeps the queue deterministic).+fn combined_parent_script() -> serde_json::Value {+ serde_json::json!({+ // Turn 2 answers the spawn turn itself ("WAITING"); the+ // repeat-last turn only runs once the replies were processed —+ // so the printed answer proves the parent turned AFTER them.+ "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": spawn_cell() } },+ ] },+ "WAITING",+ "COMBINED ALPHA-RESULT BETA-RESULT",+ ],+ "repeatLastResponse": true,+ "children": {+ "alpha": { "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": reply_cell("ALPHA") } },+ ] },+ "alpha finished",+ ] },+ "beta": { "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": reply_cell("BETA") } },+ ] },+ "beta finished",+ ] },+ },+ })+}++/// The #2270 scenario: the parent spawns two children and ends its turn;+/// both reply from their kernels; the print run waits for the replies,+/// answers with the combined text, and disposes the child kernels (the+/// final namespace snapshots land in the children's artifact dirs).+#[test]+fn print_inline_subagents_wait_for_replies_and_combine_them() {+ let lane = lane();+ let kernel = PrintLane::kernel_python();+ let (stdout, stderr, code) = lane.run(+ &["-p", "delegate the work"],+ &combined_parent_script(),+ &kernel,+ &[],+ );+ assert_eq!(code, 0, "stderr: {stderr}\nstdout: {stdout}");+ assert_eq!(stdout.trim_end(), "COMBINED ALPHA-RESULT BETA-RESULT");++ // The parent's durable transcript holds both replies as+ // `agent_message` rows from the children.+ let parent_file = lane.parent_session_file();+ let parent_entries = PrintLane::entries(&parent_file);+ let messages: Vec<&serde_json::Value> = parent_entries+ .iter()+ .filter(|entry| entry.get("type").and_then(|t| t.as_str()) == Some("custom_message"))+ .filter(|entry| entry.get("customType").and_then(|t| t.as_str()) == Some("agent_message"))+ .collect();+ let mut reply_rows: Vec<&str> = messages+ .iter()+ .filter_map(|row| row.pointer("/details/message").and_then(|m| m.as_str()))+ .filter(|message| message.ends_with("-RESULT"))+ .collect();+ // The two children run concurrently; the reply rows land in any order.+ reply_rows.sort_unstable();+ assert_eq!(+ reply_rows,+ ["ALPHA-RESULT", "BETA-RESULT"],+ "both child replies landed as agent_message rows"+ );+ for row in messages {+ let message = row+ .pointer("/details/message")+ .and_then(|m| m.as_str())+ .unwrap_or_default();+ if message.ends_with("-RESULT") {+ assert_eq!(+ row.pointer("/details/fromRelationship")+ .and_then(|r| r.as_str()),+ Some("child"),+ "the reply row is labeled from the child: {row}"+ );+ }+ }++ // Both child sessions live under the parent's artifacts tree, with+ // the parent edge in their headers, their terminal assistant rows+ // (never cancelled), and the disposed kernel's final snapshot.+ let parent_id = Path::new(&parent_file)+ .file_stem()+ .and_then(|stem| stem.to_str())+ .expect("the parent session id")+ .to_string();+ let artifacts = lane.agent_dir.join("session-artifacts").join(&parent_id);+ let mut child_dirs: Vec<PathBuf> = std::fs::read_dir(&artifacts)+ .expect("the parent's session-artifacts tree")+ .flatten()+ .map(|entry| entry.path())+ .filter(|path| {+ path.file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.starts_with("sub-"))+ })+ .collect();+ child_dirs.sort();+ assert_eq!(+ child_dirs.len(),+ 2,+ "two child session dirs: {child_dirs:?}"+ );+ for child_dir in &child_dirs {+ let child_files: Vec<PathBuf> = std::fs::read_dir(child_dir)+ .expect("the child session dir")+ .flatten()+ .map(|entry| entry.path())+ .filter(|path| path.extension().and_then(|e| e.to_str()) == Some("jsonl"))+ .collect();+ assert_eq!(+ child_files.len(),+ 1,+ "one child session file in {child_dir:?}"+ );+ let entries = PrintLane::entries(&child_files[0]);+ let header = entries+ .iter()+ .find(|entry| entry.get("type").and_then(|t| t.as_str()) == Some("session"))+ .expect("the child header row");+ assert_eq!(+ header.get("rlmDepth").and_then(serde_json::Value::as_u64),+ Some(1),+ "the child header records depth 1: {header}"+ );+ assert_eq!(+ header.get("parentSession").and_then(|p| p.as_str()),+ Some(parent_file.display().to_string().as_str()),+ "the child header names the parent session file: {header}"+ );+ // The child ran to its scripted terminal answer (never cancelled).+ let last_assistant = entries+ .iter()+ .rev()+ .find_map(|entry| {+ (entry.get("type").and_then(|t| t.as_str()) == Some("message")+ && entry.pointer("/message/role").and_then(|r| r.as_str()) == Some("assistant"))+ .then(|| entry.clone())+ })+ .expect("the child's terminal assistant row");+ let text = last_assistant+ .pointer("/message/content/0/text")+ .and_then(|t| t.as_str())+ .unwrap_or_default();+ assert!(+ text.contains("finished"),+ "the child finished its task: {text}"+ );+ // The exit disposal proof: the child's kernel was disposed with+ // its final namespace snapshot BEFORE the process exited. The+ // child's artifact dir follows the shared+ // `dirname(sessionDir)/session-artifacts/<session id>` layout, so+ // it lands beside the child's session dir (under the parent's+ // artifacts tree), not inside it.+ let child_id = child_files[0]+ .file_stem()+ .and_then(|stem| stem.to_str())+ .expect("the child session id")+ .to_string();+ let snapshot = artifacts+ .join("session-artifacts")+ .join(&child_id)+ .join("kernel-state.dill");+ assert!(+ snapshot.exists(),+ "the disposed kernel's final snapshot landed at {}",+ snapshot.display()+ );+ }+}++/// The depth gate: with `RLM_MAX_DEPTH=1`, a depth-1 child's own spawn+/// fails with the shared depth-limit error in its tool result, and the+/// print run still completes.+#[test]+fn print_inline_subagents_enforce_the_depth_limit() {+ let lane = lane();+ let kernel = PrintLane::kernel_python();+ let spawn_attempt = "try:\n g = await rlm.spawn(\"run the grandkid task\", name=\"grandkid\")\n print(\"SPAWN_OK\", g.rlm_child_id)\nexcept Exception as error:\n print(\"SPAWN_FAILED:\", error)".to_string();+ let script = serde_json::json!({+ "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": "kid = await rlm.spawn(\"run the kid task\", name=\"kid\")\nprint(\"KID\", kid.rlm_child_id)" } },+ ] },+ "PARENT DONE",+ ],+ "repeatLastResponse": true,+ "children": {+ "kid": { "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": spawn_attempt } },+ ] },+ "kid finished",+ ] },+ },+ });+ let (stdout, stderr, code) = lane.run(+ &["-p", "delegate once"],+ &script,+ &kernel,+ &[("RLM_MAX_DEPTH", "1")],+ );+ assert_eq!(code, 0, "stderr: {stderr}\nstdout: {stdout}");+ assert_eq!(stdout.trim_end(), "PARENT DONE");++ // The child's transcript carries the refused spawn in its tool result.+ let parent_file = lane.parent_session_file();+ let parent_id = Path::new(&parent_file)+ .file_stem()+ .and_then(|stem| stem.to_str())+ .expect("the parent session id")+ .to_string();+ let artifacts = lane.agent_dir.join("session-artifacts").join(&parent_id);+ let child_dirs: Vec<PathBuf> = std::fs::read_dir(&artifacts)+ .expect("the kid's session dir exists")+ .flatten()+ .map(|entry| entry.path())+ .filter(|path| {+ path.file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.starts_with("sub-"))+ })+ .collect();+ assert_eq!(child_dirs.len(), 1, "one child session dir: {child_dirs:?}");+ let kid_file: Vec<PathBuf> = std::fs::read_dir(&child_dirs[0])+ .unwrap()+ .flatten()+ .map(|entry| entry.path())+ .filter(|path| path.extension().and_then(|e| e.to_str()) == Some("jsonl"))+ .collect();+ let kid_entries = PrintLane::entries(&kid_file[0]);+ let kid_text = serde_json::to_string(&kid_entries).unwrap();+ assert!(+ kid_text.contains("RLM recursion depth limit reached (RLM_DEPTH=1, RLM_MAX_DEPTH=1)"),+ "the depth-1 child's spawn carried the shared depth-limit error"+ );+ // The kid never replied: the parent's transcript holds the no-reply+ // terminal notice (drained as a turn by the quiescence drive).+ let parent_text = serde_json::to_string(&PrintLane::entries(&parent_file)).unwrap();+ assert!(+ parent_text.contains("[child-exited: no-reply child:kid]"),+ "the parent read the no-reply notice: {parent_text}"+ );+}++/// A settled child re-tasked by its parent must keep the run open: the+/// parent sends the follow-up, ends its turn, and the print run waits+/// for the re-tasked child's second reply before the terminal answer.+/// The quiescence predicate reads the child's live session state (the+/// queued follow-up row), so the run cannot exit while the row sits in+/// the settled child's steering lane.+#[test]+fn print_inline_subagents_wait_for_a_retasked_child() {+ let lane = lane();+ let kernel = PrintLane::kernel_python();+ let follow_up_cell = "collected = await rlm.collect([\"kid\"], timeout_ms=60000)\nprint(\"FIRST-TASK\", collected[0].status, collected[0].settled, collected[0].answer_text)\nawait agent_message.send(\"SECOND-RESULT\", receiver_role=\"child\", receiver_name=\"kid\")\nretasked = await rlm.collect([\"kid\"], timeout_ms=60000)\nprint(\"SECOND-TASK\", retasked[0].status, retasked[0].settled, retasked[0].answer_text)".to_string();+ let script = serde_json::json!({+ "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": "kid = await rlm.spawn(\"run the kid task\", name=\"kid\")\nprint(\"KID\", kid.rlm_child_id)" } },+ ] },+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": follow_up_cell } },+ ] },+ "WAITING",+ "ALL REPLIES READ",+ ],+ "repeatLastResponse": true,+ "children": {+ "kid": { "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": reply_cell("FIRST") } },+ ] },+ "kid finished the first task",+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": reply_cell("SECOND") } },+ ] },+ "kid finished the second task",+ ] },+ },+ });+ let (stdout, stderr, code) = lane.run(&["-p", "delegate twice"], &script, &kernel, &[]);+ assert_eq!(code, 0, "stderr: {stderr}\nstdout: {stdout}");+ assert_eq!(+ stdout.trim_end(),+ "ALL REPLIES READ",+ "the terminal answer ran after the second reply, not the pre-replies \"WAITING\" turn"+ );++ // Both replies landed in the parent's transcript.+ let parent_file = lane.parent_session_file();+ let parent_entries = PrintLane::entries(&parent_file);+ let mut reply_rows: Vec<&str> = parent_entries+ .iter()+ .filter(|entry| entry.get("type").and_then(|t| t.as_str()) == Some("custom_message"))+ .filter(|entry| entry.get("customType").and_then(|t| t.as_str()) == Some("agent_message"))+ .filter_map(|row| row.pointer("/details/message").and_then(|m| m.as_str()))+ .filter(|message| message.ends_with("-RESULT"))+ .collect();+ reply_rows.sort_unstable();+ assert_eq!(+ reply_rows,+ ["FIRST-RESULT", "SECOND-RESULT"],+ "the re-tasked child processed the follow-up and replied again"+ );++ // The in-turn collects: the follow-up's collect waits past the+ // re-tasked run and returns the SECOND task's answer — never the+ // settled child's stale first answer.+ let parent_text = serde_json::to_string(&parent_entries).unwrap();+ assert!(+ parent_text.contains("FIRST-TASK done True kid finished the first task"),+ "the collect before the follow-up read the first task's settled answer: {parent_text}"+ );+ assert!(+ parent_text.contains("SECOND-TASK done True kid finished the second task"),+ "the collect after the follow-up returned the second task's answer: {parent_text}"+ );+}++/// A child whose task turn dies on a provider error settles FAILED, not+/// done: the parent reads the failure row (never a completed-without-+/// reply notice), and a re-tasked child that succeeds collects `done`+/// with no stale error from the failed run. The child's error response is+/// delayed past the parent's spawn turn, so its failure row drains through+/// the quiescence drive, not the spawn turn's steering poll.+#[test]+fn print_inline_subagents_report_a_failed_child_then_a_clean_retry() {+ let lane = lane();+ let kernel = PrintLane::kernel_python();+ // The turn over the failure row: read the failed verdict, then+ // re-task the child from the parent.+ let retask_cell = "collected = await rlm.collect([\"flaky\"], timeout_ms=60000)\nprint(\"FIRST-COLLECT\", collected[0].status, collected[0].error)\nawait agent_message.send(\"retry the task\", receiver_role=\"child\", receiver_name=\"flaky\")".to_string();+ // The turn over the second reply: collect the clean retry.+ let second_collect_cell =+ "collected = await rlm.collect([\"flaky\"], timeout_ms=60000)\nprint(\"SECOND-COLLECT\", collected[0].status, collected[0].error)".to_string();+ let script = serde_json::json!({+ // Turn 1 spawns and ends ("WAITING"); the failed task's failure+ // row drains as turn 2 (the re-task), the second reply drains as+ // turn 3, and its collect reads the clean retry.+ "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": "kid = await rlm.spawn(\"run the kid task\", name=\"flaky\")\nprint(\"KID\", kid.rlm_child_id)" } },+ ] },+ "WAITING",+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": retask_cell } },+ ] },+ "RETASKED",+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": second_collect_cell } },+ ] },+ "RETRY CLEAN",+ ],+ "repeatLastResponse": true,+ "children": {+ "flaky": { "responses": [+ // The task turn dies on a provider error; the run path+ // itself returns `Ok` for the row, so only its stop+ // reason marks the failure.+ { "text": "the provider exploded mid-task", "stopReason": "error",+ "errorMessage": "faux provider exploded", "delayMs": 3000 },+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": reply_cell("SECOND") } },+ ] },+ "kid finished the retry",+ ] },+ },+ });+ let (stdout, stderr, code) =+ lane.run(&["-p", "delegate the flaky task"], &script, &kernel, &[]);+ assert_eq!(code, 0, "stderr: {stderr}\nstdout: {stdout}");+ assert_eq!(stdout.trim_end(), "RETRY CLEAN");++ let parent_file = lane.parent_session_file();+ let entries = PrintLane::entries(&parent_file);+ let parent_text = serde_json::to_string(&entries).unwrap();+ // The failed task surfaces as the failure row — never as a+ // completed-without-reply notice.+ let failure_at = entries+ .iter()+ .position(|entry| {+ entry.get("type").and_then(|t| t.as_str()) == Some("custom_message")+ && entry.get("customType").and_then(|t| t.as_str()) == Some("rlm_child_failure")+ })+ .expect("the parent read the failed child's failure row");+ assert_eq!(+ entries[failure_at]+ .pointer("/details/error")+ .and_then(|e| e.as_str()),+ Some("faux provider exploded"),+ "the failure row carries the terminal error: {}",+ entries[failure_at]+ );+ assert!(+ !parent_text.contains("no-reply child:"),+ "the failed run never read as a completed-without-reply notice: {parent_text}"+ );+ // The re-task turn read the failed verdict before re-tasking, and the+ // retry collected done with NO stale error.+ assert!(+ parent_text.contains("FIRST-COLLECT error faux provider exploded"),+ "the collect after the failure read the error status: {parent_text}"+ );+ let reply_at = custom_row_at(&entries, "agent_message", Some("SECOND-RESULT"))+ .expect("the re-tasked child replied again");+ assert!(+ failure_at < reply_at,+ "the failure row (row {failure_at}) landed before the second reply (row {reply_at})"+ );+ assert!(+ parent_text.contains("SECOND-COLLECT done None"),+ "the retry collected done with no stale error: {parent_text}"+ );+}++/// The position of the first custom row of one type carrying a message+/// detail (`goal_context` continuations, the child's `agent_message`+/// reply) — the landing order of these rows is the deferral proof.+fn custom_row_at(+ entries: &[serde_json::Value],+ custom_type: &str,+ message: Option<&str>,+) -> Option<usize> {+ entries.iter().position(|entry| {+ entry.get("type").and_then(|t| t.as_str()) == Some("custom_message")+ && entry.get("customType").and_then(|t| t.as_str()) == Some(custom_type)+ && message.is_none_or(|expected| {+ entry.pointer("/details/message").and_then(|m| m.as_str()) == Some(expected)+ })+ })+}++/// The positions of every `goal_context` row: the seeded continuation+/// rides the first prompt, so the row after the first one is the owed+/// delivery's (the LAST row is not a proof — goal rows keep minting+/// after the reply either way).+fn goal_context_positions(entries: &[serde_json::Value]) -> Vec<usize> {+ entries+ .iter()+ .enumerate()+ .filter(|(_, entry)| {+ entry.get("type").and_then(|t| t.as_str()) == Some("custom_message")+ && entry.get("customType").and_then(|t| t.as_str()) == Some("goal_context")+ })+ .map(|(at, _)| at)+ .collect()+}++/// The position of the first persisted user row whose text starts with+/// the autonomous continuation marker.+fn autonomous_continuation_row_at(entries: &[serde_json::Value]) -> Option<usize> {+ entries.iter().position(|entry| {+ if entry.get("type").and_then(|t| t.as_str()) != Some("message")+ || entry.pointer("/message/role").and_then(|r| r.as_str()) != Some("user")+ {+ return false;+ }+ serde_json::to_string(entry)+ .unwrap_or_default()+ .contains("[autonomous-continuation")+ })+}++/// The goal continuation defers while an inline child is unsettled and+/// delivers after its reply drains: the parent spawns `kid` and ends its+/// turn mid-child-run; the owed continuation turn — the FIRST+/// `goal_context` row after the seeded one — lands only AFTER the+/// child's reply row, and its turn completes the goal, so the printed+/// answer is the post-reply turn. No backoff sleeps: the continuation+/// turn produces output and calls `goal.complete()`.+#[test]+fn print_inline_goal_continuation_waits_for_the_child_reply() {+ let lane = lane();+ let kernel = PrintLane::kernel_python();+ let complete_cell = "done = await goal.complete()\nprint(\"GOAL COMPLETED\")".to_string();+ let script = serde_json::json!({+ // Turn 1 spawns and ends ("WAITING"); the reply drains as turn 2;+ // the owed goal continuation runs as the post-reply turn, calls+ // `goal.complete()`, and ends deterministically.+ "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": "kid = await rlm.spawn(\"run the kid task\", name=\"kid\")\nprint(\"KID\", kid.rlm_child_id)" } },+ ] },+ "WAITING",+ "READ THE REPLY",+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": complete_cell } },+ ] },+ "GOAL DONE AFTER REPLY",+ ],+ "repeatLastResponse": true,+ "children": {+ "kid": { "responses": [+ // The delayed reply holds the child open: the parent's+ // goal gate sees it unsettled at the spawn turn's end.+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": reply_cell("KID") } },+ ], "delayMs": 3000 },+ "kid done",+ ] },+ },+ });+ let (stdout, stderr, code) = lane.run(+ &[+ "--goal",+ "finish the delegated work",+ "-p",+ "delegate then finish",+ ],+ &script,+ &kernel,+ &[],+ );+ assert_eq!(code, 0, "stderr: {stderr}\nstdout: {stdout}");+ assert_eq!(+ stdout.trim_end(),+ "GOAL DONE AFTER REPLY",+ "the terminal answer is the post-reply goal continuation turn"+ );++ // The deferral proof: the first goal continuation row after the+ // seeded one lands AFTER the child's reply row — no continuation+ // turn interleaved before the reply.+ let parent_file = lane.parent_session_file();+ let entries = PrintLane::entries(&parent_file);+ let goal_rows = goal_context_positions(&entries);+ assert!(+ goal_rows.len() >= 2,+ "the seeded continuation and the owed delivery landed: {goal_rows:?}"+ );+ let reply_at = custom_row_at(&entries, "agent_message", Some("KID-RESULT"))+ .expect("the child reply row landed in the parent transcript");+ assert!(+ goal_rows[1] > reply_at,+ "the owed goal continuation (row {}) landed after the child reply (row {})",+ goal_rows[1],+ reply_at+ );+}++/// The autonomous continuation holds behind unsettled inline-subagent+/// work and delivers after the child's reply (no goal): the spawn turn's+/// end holds a FLAG — nothing is spent on the pre-settle turn — and the+/// continuation turn only runs once the reply drained: its user row+/// lands after the reply row, and the printed answer is the post-reply+/// turn. A passing gate ends the run deterministically.+#[test]+fn print_inline_autonomous_continuation_waits_for_the_child_reply() {+ let lane = lane();+ let kernel = PrintLane::kernel_python();+ let marker_cell = "open(\"gate-marker\", \"w\").write(\"done\")\nprint(\"MARKED\")".to_string();+ let script = serde_json::json!({+ // Turn 1 spawns and ends ("WAITING"); the reply drains as turn 2;+ // the held continuation runs as the post-reply turn, writes the+ // gate marker, and the now-passing gate stops the run.+ "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": "kid = await rlm.spawn(\"run the kid task\", name=\"kid\")\nprint(\"KID\", kid.rlm_child_id)" } },+ ] },+ "WAITING",+ "READ THE REPLY",+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": marker_cell } },+ ] },+ "AUTONOMOUS CONTINUES",+ ],+ "repeatLastResponse": true,+ "children": {+ "kid": { "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": reply_cell("KID") } },+ ], "delayMs": 3000 },+ "kid done",+ ] },+ },+ });+ let (stdout, stderr, code) = lane.run(+ &[+ "--autonomous",+ "--autonomous-gate",+ "test -f gate-marker",+ "-p",+ "delegate then keep going",+ ],+ &script,+ &kernel,+ &[],+ );+ assert_eq!(code, 0, "stderr: {stderr}\nstdout: {stdout}");+ assert_eq!(+ stdout.trim_end(),+ "AUTONOMOUS CONTINUES",+ "the terminal answer is the post-reply autonomous continuation turn"+ );++ // The hold proof: the autonomous continuation's user row lands AFTER+ // the child's reply row — no continuation turn interleaved before it.+ let parent_file = lane.parent_session_file();+ let entries = PrintLane::entries(&parent_file);+ let reply_at = custom_row_at(&entries, "agent_message", Some("KID-RESULT"))+ .expect("the child reply row landed in the parent transcript");+ let continuation_at = autonomous_continuation_row_at(&entries)+ .expect("the autonomous continuation row landed in the parent transcript");+ assert!(+ continuation_at > reply_at,+ "the held autonomous continuation (row {continuation_at}) landed after the child reply (row {reply_at})"+ );+}++/// The R1 regression (via the goal token budget, no compaction needed):+/// the reply turn crosses the budget, the accounting arms the budget+/// steer, and the drive loop must run it AFTER the reply drained —+/// before the fix the post-prompt loop broke with the armed steer+/// unrun. The budget self-calibrates: pass 1 runs the same script with+/// a huge budget and reads the persisted faux usage of the spawn turn+/// and the reply turn; the real run uses spawn + half the reply turn+/// (thousands of tokens of margin, so the crossing lands mid-reply-turn+/// and nowhere else).+#[test]+fn print_inline_budget_steer_from_a_drained_reply_runs_after_it() {+ let warm_lane = lane();+ let kernel = PrintLane::kernel_python();+ let complete_cell = "done = await goal.complete()\nprint(\"GOAL COMPLETED\")".to_string();+ let script = serde_json::json!({+ // Turn 1 spawns and ends; the reply drains as turn 2 (crossing+ // the budget); the wrap-up steer runs as turn 3 and completes the+ // goal, so the run ends deterministically.+ "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": "kid = await rlm.spawn(\"run the kid task\", name=\"kid\")\nprint(\"KID\", kid.rlm_child_id)" } },+ ] },+ "WAITING",+ "READ THE REPLY",+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": complete_cell } },+ ] },+ "GOAL WRAPPED UP",+ ],+ "repeatLastResponse": true,+ "children": {+ "kid": { "responses": [+ { "content": [+ { "type": "toolCall", "name": "ipython",+ "arguments": { "code": reply_cell("KID") } },+ ], "delayMs": 3000 },+ "kid done",+ ] },+ },+ });++ // Pass 1: the same script with a budget no turn can cross; the goal+ // completes at the same slot, so the usage rows of the first three+ // assistant messages match the real run's.+ let (_, _, warm) = warm_lane.run(+ &[+ "--goal",+ "finish the delegated work",+ "--goal-token-budget",+ "4000000000",+ "-p",+ "delegate then finish",+ ],+ &script,+ &kernel,+ &[],+ );+ assert_eq!(warm, 0);+ let warm_file = warm_lane.parent_session_file();+ let warm_entries = PrintLane::entries(&warm_file);+ let usage: Vec<u64> = warm_entries+ .iter()+ .filter(|entry| entry.get("type").and_then(|t| t.as_str()) == Some("message"))+ .filter(|entry| {+ entry.pointer("/message/role").and_then(|r| r.as_str()) == Some("assistant")+ })+ .map(|entry| {+ let usage = entry+ .pointer("/message/usage")+ .expect("the faux row carries usage");+ let input = usage+ .get("input")+ .and_then(serde_json::Value::as_u64)+ .unwrap_or(0);+ let output = usage+ .get("output")+ .and_then(serde_json::Value::as_u64)+ .unwrap_or(0);+ input + output+ })+ .collect();+ // The two spawn-turn assistant rows, then the reply-turn row.+ assert!(usage.len() >= 3, "the warm run's assistant rows: {usage:?}");+ let spawn_turn: u64 = usage[0] + usage[1];+ let reply_turn: u64 = usage[2];+ assert!(+ reply_turn > 0,+ "the reply turn's usage is positive: {usage:?}"+ );+ let budget = spawn_turn + reply_turn / 2;++ // The real run: the crossing lands mid-reply-turn (the spawn turn+ // stays under budget).+ let lane = lane();+ let (stdout, stderr, code) = lane.run(+ &[+ "--goal",+ "finish the delegated work",+ "--goal-token-budget",+ &budget.to_string(),+ "-p",+ "delegate then finish",+ ],+ &script,+ &kernel,+ &[],+ );+ assert_eq!(code, 0, "stderr: {stderr}\nstdout: {stdout}");+ assert_eq!(+ stdout.trim_end(),+ "GOAL WRAPPED UP",+ "the budget steer's wrap-up turn ran after the reply drained"+ );++ // The steer's budget-limit row lands AFTER the child's reply row.+ let parent_file = lane.parent_session_file();+ let entries = PrintLane::entries(&parent_file);+ let reply_at = custom_row_at(&entries, "agent_message", Some("KID-RESULT"))+ .expect("the child reply row landed in the parent transcript");+ let steer_at = entries+ .iter()+ .position(|entry| {+ entry.get("type").and_then(|t| t.as_str()) == Some("custom_message")+ && entry.get("customType").and_then(|t| t.as_str()) == Some("goal_context")+ && entry+ .pointer("/content")+ .and_then(|c| c.as_str())+ .is_some_and(|text| text.starts_with("[goal: budget-limit]"))+ })+ .expect("the budget steer row landed in the parent transcript");+ assert!(+ steer_at > reply_at,+ "the budget steer (row {steer_at}) landed after the child reply (row {reply_at})"+ );+}++#[test]+fn print_inline_rename_rejects_sibling_collisions_and_preserves_routing() {+ let lane = lane();+ let kernel = PrintLane::kernel_python();+ let parent_cell = r#"+alpha = await rlm.spawn("answer alpha", name="alpha")+beta = await rlm.spawn("check self rename", name="beta")+first = await rlm.collect([beta], timeout_ms=60000)+assert first[0].settled and first[0].answer_text == "beta checked"+try:+ await rlm.rename("alpha", session_id=beta)+except Exception as error:+ assert "unavailable" in str(error), str(error)+else:+ raise AssertionError("parent rename accepted a duplicate sibling name")+rows = await rlm.list_subagents()+assert {row.rlm_child_id: row.session_name for row in rows} == {alpha.rlm_child_id: "alpha", beta.rlm_child_id: "beta"}+results = await rlm.collect(["alpha", "beta"], timeout_ms=60000)+assert [(result.session_name, result.answer_text) for result in results] == [("alpha", "alpha answered"), ("beta", "beta checked")]+assert await rlm.rename("beta", session_id=beta) == "beta"+assert await rlm.rename("gamma", session_id=beta) == "gamma"+renamed = await rlm.collect(["gamma"], timeout_ms=60000)+assert renamed[0].rlm_child_id == beta.rlm_child_id+print("RENAME ROUTING VERIFIED")+"#;+ let child_cell = r#"+try:+ await rlm.rename("alpha")+except Exception as error:+ assert "unavailable" in str(error), str(error)+else:+ raise AssertionError("self rename accepted a duplicate sibling name")+print("SELF RENAME REJECTED")+"#;+ let script = serde_json::json!({+ "responses": [+ { "content": [{ "type": "toolCall", "name": "ipython",+ "arguments": { "code": parent_cell } }] },+ "RENAMES CHECKED",+ ],+ "repeatLastResponse": true,+ "children": {+ "alpha": { "responses": ["alpha answered"] },+ "beta": { "responses": [+ { "content": [{ "type": "toolCall", "name": "ipython",+ "arguments": { "code": child_cell } }] },+ "beta checked",+ ] },+ },+ });+ let (stdout, stderr, code) = lane.run(&["-p", "check rename routing"], &script, &kernel, &[]);+ assert_eq!(code, 0, "stderr: {stderr}\nstdout: {stdout}");+ let entries = PrintLane::entries(&lane.parent_session_file());+ let tool_output: String = entries+ .iter()+ .filter(|entry| {+ entry+ .pointer("/message/role")+ .and_then(|role| role.as_str())+ == Some("toolResult")+ })+ .map(serde_json::Value::to_string)+ .collect();+ assert!(+ tool_output.contains("RENAME ROUTING VERIFIED"),+ "rename checks completed without a tool error: {tool_output}"+ );+}++#[test]+fn print_inline_delete_cancels_an_executing_child_and_removes_it() {+ let lane = lane();+ let kernel = PrintLane::kernel_python();+ let parent_cell = r#"+import asyncio+from pathlib import Path+ready = asyncio.get_running_loop().create_future()+async def accept_ready(reader, writer):+ try:+ assert await reader.readline() == b"ready\n"+ ready.set_result(None)+ finally:+ writer.close()+ await writer.wait_closed()+server = await asyncio.start_server(accept_ready, "127.0.0.1", 0)+try:+ Path("cancel-port").write_text(str(server.sockets[0].getsockname()[1]))+ child = await rlm.spawn("wait until cancelled", name="waiting")+ await asyncio.wait_for(ready, timeout=30)+ deleted = await rlm.delete_subagent(child)+ assert deleted.status == "cancelled", deleted+ assert await rlm.list_subagents() == []+ try:+ await rlm.collect([child], timeout_ms=0)+ except Exception as error:+ assert "No direct RLM child matches" in str(error), str(error)+ else:+ raise AssertionError("deleted child remained collectable")+ Path("cancel-verified").write_text("done")+finally:+ server.close()+ await server.wait_closed()+"#;+ let child_cell = r#"+import asyncio, os+from pathlib import Path+Path("cancel-child-pid").write_text(str(os.getpid()))+reader, writer = await asyncio.open_connection("127.0.0.1", int(Path("cancel-port").read_text()))+writer.write(b"ready\n")+await writer.drain()+writer.close()+await writer.wait_closed()+await asyncio.Event().wait()+Path("cancel-child-finished").write_text("unexpected")+"#;+ let script = serde_json::json!({+ "responses": [+ { "content": [{ "type": "toolCall", "name": "ipython",+ "arguments": { "code": parent_cell } }] },+ "CHILD CANCELLED",+ ],+ "repeatLastResponse": true,+ "children": {+ "waiting": { "responses": [+ { "content": [{ "type": "toolCall", "name": "ipython",+ "arguments": { "code": child_cell } }] },+ "unexpected completion",+ ] },+ },+ });+ let (stdout, stderr, code) = lane.run(&["-p", "cancel the child"], &script, &kernel, &[]);+ assert_eq!(code, 0, "stderr: {stderr}\nstdout: {stdout}");+ assert!(+ lane.home.path().join("cancel-verified").exists(),+ "deletion and routing checks completed; stderr: {stderr}\nstdout: {stdout}"+ );+ assert!(!lane.home.path().join("cancel-child-finished").exists());+ let child_pid = std::fs::read_to_string(lane.home.path().join("cancel-child-pid"))+ .unwrap()+ .parse::<u32>()+ .unwrap();+ assert!(+ !pa_core::platform::pid_exists(child_pid),+ "cancelled child's Python process {child_pid} outlived the print run"+ );+}diff --git a/crates/pa-core/README.md b/crates/pa-core/README.mdindex 9c437c2c38..18f208d4fc 100644--- a/crates/pa-core/README.md+++ b/crates/pa-core/README.md@@ -74,7 +74,7 @@ only: nothing wires it to a user-facing cloud toggle yet.No provider HTTP (pa-ai), no loop policy (pa-agent), no daemon supervision (pa-daemon), no TUI (pa-tui). No update coordination (the pa-cli coordinator owns the FSM; the update-flow seam here is the daemon-free support layer: `update::version` (semver/channel policy), `update::install` (the managed install-root layout), `update::release` (the channel manifest fetch), `update::download` (sha256-verified archive download + staging)). The package manager installs sources and resolves resource paths only. No workspace snapshot upload, transport, or remote materialization (staging and verification live here; the cloud attach surface owns the transport when it ships).## Public API-`SessionEngine` (message in -> events out), `export_html` (the HTML exporter plus its renderer seam: `tools_section`, `pre_render_custom_tools` + `ToolHtmlRenderer`/`RenderedToolHtml`/`RenderedToolResult`, and `ansi_to_html::ansi_lines_to_html`/`tool_render::trim_rendered_result_lines` for renderer implementers), `ToolRegistry`, kernel manager, settings (`SettingsManager`), packages (`packages::PackageManager` + source types), `platform` (process control, file locking, permissions, shell selection - usable by higher crates, e.g. pa-cli's detached spawn), `session_engine::rlm_host::RlmSubagentHost` (implemented by pa-daemon for supervisor-backed children; the default is no children), `session_engine::semantic_edges` (the TS `semantic-edges.ts` WRITER: `SemanticEdgeRecorder`/`SemanticEdgeIdentity`, `semantic_edge_ledger_path` + `last_committed_request_id`, and the `X-ACP-Model-Request-ID`/`Idempotency-Key` constants — one durable per-session ledger of model-request events, byte-compatible with the TS lines; the fold and any publishing stay downstream), `mcp::McpManager` (the session's host-side MCP manager, exposed as `SessionEngine.mcp_manager`: auth gating for built-in integrations, the `mcpServers` setting seam, and the `mcp.*` host-request handlers - `mcp.config`/`mcp.refresh`/optional `mcp.begin_login` - the kernel's generic MCP client resolves through), `mcp::McpManager::connection_roster` + `mcp::McpConnectionEntry` (the `/mcp` view's roster: every resolved integration with its connected state, display kind, transport, and generic-listable flag), `mcp::McpManager::service_catalog_views` + `service_catalog_diagnostics` (the `/mcp` view's resolved service-catalog cards and their diagnostics, answered from local state - the TS `buildServiceCatalogViews` parity; the picker never round-trips the kernel), `mcp::McpManager::api_key_credential_views` + `mcp::API_KEY_CREDENTIALS`/`McpCredentialView` (the `/mcp` view's api-key credential rows - the stored keys the surface manages alongside the connections, e.g. the web-search key - configured from the shared auth store), `models` (the registry and resolver, plus `models::order_for_picker`: the picker-catalog order the composition root applies to its snapshot), `session_engine::provider_adapter` (`switchable_stream_fn`/`ProviderTarget`: the live provider-target slot a host swaps on `set_model`; the adapter bridges the loop's abort into pa-ai's `StreamOptions::signal` cancellation token, so a turn abort cancels the in-flight HTTP fetch at the transport — closed by `ModelStream::close` and the stream's drop), `session_engine::ipython_state` (the post-compaction `ipython_state` kernel-persistence notice: the `CompactionKernelProbe` view of the kernel provisioner the engine wiring binds via `AgentSession::set_kernel_state_probe`, and the notice row that rides `CompactRun` for the surfaces to broadcast). `session_engine::decision_api::DECISION_API_SKILL_NAME` (the bundled gated skill name consumed by CLI prompt inspection) and `SessionEngine::{system_prompt, sync_decision_api_from_session}` (the prompt/status facade; shared switch and policy internals stay crate-internal). `session_engine::session_commands` (the `/compact`/`/refine`/`/goal`/`/autonomous`/`/decision-api` executor: the durable echo/result rows with their persistence order - the echo ahead of the command so its own work sees it - the compaction/refinement/goal/autonomous arms, and the post-execution live-context rebuild that keeps the rows in the agent state; hosts own the wire surface), `session_engine::auto_refine_trigger` (the compact-trigger auto-refine machine on `AgentSession`: the arm/discard/increment accessors and `consume_compact_auto_refine`, the shared gate/review/stamp sequence every scheduling surface applies - TS `_compactAutoRefinePending`/`_lastAutoRefineReviewAt`/`_assistantTurnsSinceAutoRefine` plus `_maybeAutoRefine`'s compact arm, the serialized checkpoint's compact step, and dispose's serialized drain, with the surface parameter carrying the one behavioral difference between a boundary and a disposal). `session_engine::goal_boundary` (the goal arms of the natural turn end on `SessionEngine`: the `--goal` construction seed with its next-turn context row - TS `_pendingNextTurnMessages` on `AgentSession` - the usage accounting, the budget-limit steer mint, the natural continuation mint with its slot rollback, and the terminal-error finish; the transports - the print driver's in-loop hook, the ACP settle loop, the daemon worker's queue - drive the one goal driver through these methods). `SessionEngine::expand_skill_submission` + `AgentSession`'s prompt-path expansion (the `/skill:<name>` submission seam, TS `_expandSkillCommand`: `skills::expand_skill_command` builds the `<skill ...>` block over the shared `pa_types::skill_blocks` parse, the accepted-turn row and the admitted user message agree on the expanded text, and the `skill_use_count` session counter counts at the admission). `workspace_snapshot` (`create_workspace_snapshot`: bounded, secret/nested-repo/submodule/symlink-ancestor-excluding capture of a git worktree into an owner-private staging directory, with the caller-chosen `BaselineMode` (HEAD-tree content verified against HEAD's object ids, or explicit external) and a `ConcurrentMutation` error when the worktree changes under the capture; `verify_workspace_snapshot`: offline manifest/blob/baseline integrity check; the `SnapshotManifest`/`WorkspaceSnapshot`/`SnapshotLimits`/`BaselineMode`/`SnapshotError` types). All subsystem internals `pub(crate)`; the engine is the only facade - subsystems must not import each other directly (the package manager consumes the public settings API only).+`SessionEngine` (message in -> events out), `export_html` (the HTML exporter plus its renderer seam: `tools_section`, `pre_render_custom_tools` + `ToolHtmlRenderer`/`RenderedToolHtml`/`RenderedToolResult`, and `ansi_to_html::ansi_lines_to_html`/`tool_render::trim_rendered_result_lines` for renderer implementers), `ToolRegistry`, kernel manager, settings (`SettingsManager`), packages (`packages::PackageManager` + source types), `platform` (process control, file locking, permissions, shell selection - usable by higher crates, e.g. pa-cli's detached spawn), `session_engine::rlm_host::RlmSubagentHost` (implemented by pa-daemon for supervisor-backed children and by pa-cli's print mode for in-process children; the default is no children; the trait crate also owns the shared spawn/depth facts — `DEFAULT_RLM_MAX_DEPTH`, the depth-limit and name errors, the daemonless `create_session` refusal, `rlm_child_session_dir`, and the `persisted_rlm_max_depth`/`resolve_rlm_max_depth` precedence chain), `session_engine::semantic_edges` (the TS `semantic-edges.ts` WRITER: `SemanticEdgeRecorder`/`SemanticEdgeIdentity`, `semantic_edge_ledger_path` + `last_committed_request_id`, and the `X-ACP-Model-Request-ID`/`Idempotency-Key` constants — one durable per-session ledger of model-request events, byte-compatible with the TS lines; the fold and any publishing stay downstream), `mcp::McpManager` (the session's host-side MCP manager, exposed as `SessionEngine.mcp_manager`: auth gating for built-in integrations, the `mcpServers` setting seam, and the `mcp.*` host-request handlers - `mcp.config`/`mcp.refresh`/optional `mcp.begin_login` - the kernel's generic MCP client resolves through), `mcp::McpManager::connection_roster` + `mcp::McpConnectionEntry` (the `/mcp` view's roster: every resolved integration with its connected state, display kind, transport, and generic-listable flag), `mcp::McpManager::service_catalog_views` + `service_catalog_diagnostics` (the `/mcp` view's resolved service-catalog cards and their diagnostics, answered from local state - the TS `buildServiceCatalogViews` parity; the picker never round-trips the kernel), `mcp::McpManager::api_key_credential_views` + `mcp::API_KEY_CREDENTIALS`/`McpCredentialView` (the `/mcp` view's api-key credential rows - the stored keys the surface manages alongside the connections, e.g. the web-search key - configured from the shared auth store), `models` (the registry and resolver, plus `models::order_for_picker`: the picker-catalog order the composition root applies to its snapshot), `session_engine::provider_adapter` (`switchable_stream_fn`/`ProviderTarget`: the live provider-target slot a host swaps on `set_model`; the adapter bridges the loop's abort into pa-ai's `StreamOptions::signal` cancellation token, so a turn abort cancels the in-flight HTTP fetch at the transport — closed by `ModelStream::close` and the stream's drop), `session_engine::ipython_state` (the post-compaction `ipython_state` kernel-persistence notice: the `CompactionKernelProbe` view of the kernel provisioner the engine wiring binds via `AgentSession::set_kernel_state_probe`, and the notice row that rides `CompactRun` for the surfaces to broadcast). `session_engine::decision_api::DECISION_API_SKILL_NAME` (the bundled gated skill name consumed by CLI prompt inspection) and `SessionEngine::{system_prompt, sync_decision_api_from_session}` (the prompt/status facade; shared switch and policy internals stay crate-internal). `session_engine::session_commands` (the `/compact`/`/refine`/`/goal`/`/autonomous`/`/decision-api` executor: the durable echo/result rows with their persistence order - the echo ahead of the command so its own work sees it - the compaction/refinement/goal/autonomous arms, and the post-execution live-context rebuild that keeps the rows in the agent state; hosts own the wire surface), `session_engine::auto_refine_trigger` (the compact-trigger auto-refine machine on `AgentSession`: the arm/discard/increment accessors and `consume_compact_auto_refine`, the shared gate/review/stamp sequence every scheduling surface applies - TS `_compactAutoRefinePending`/`_lastAutoRefineReviewAt`/`_assistantTurnsSinceAutoRefine` plus `_maybeAutoRefine`'s compact arm, the serialized checkpoint's compact step, and dispose's serialized drain, with the surface parameter carrying the one behavioral difference between a boundary and a disposal). `session_engine::goal_boundary` (the goal arms of the natural turn end on `SessionEngine`: the `--goal` construction seed with its next-turn context row - TS `_pendingNextTurnMessages` on `AgentSession` - the usage accounting, the budget-limit steer mint, the natural continuation mint with its slot rollback, the RLM deferral behind unsettled descendant work (mark/drop/take owed, the wake-up ownership probe, and the latest settled turn the post-settle deliveries decide from), and the terminal-error finish; the transports - the print driver's in-loop hook, the ACP settle loop, the daemon worker's queue - drive the one goal driver through these methods). `SessionEngine::expand_skill_submission` + `AgentSession`'s prompt-path expansion (the `/skill:<name>` submission seam, TS `_expandSkillCommand`: `skills::expand_skill_command` builds the `<skill ...>` block over the shared `pa_types::skill_blocks` parse, the accepted-turn row and the admitted user message agree on the expanded text, and the `skill_use_count` session counter counts at the admission). `workspace_snapshot` (`create_workspace_snapshot`: bounded, secret/nested-repo/submodule/symlink-ancestor-excluding capture of a git worktree into an owner-private staging directory, with the caller-chosen `BaselineMode` (HEAD-tree content verified against HEAD's object ids, or explicit external) and a `ConcurrentMutation` error when the worktree changes under the capture; `verify_workspace_snapshot`: offline manifest/blob/baseline integrity check; the `SnapshotManifest`/`WorkspaceSnapshot`/`SnapshotLimits`/`BaselineMode`/`SnapshotError` types). All subsystem internals `pub(crate)`; the engine is the only facade - subsystems must not import each other directly (the package manager consumes the public settings API only).## Decision API ownership and public seamsdiff --git a/crates/pa-core/src/prompts/system_prompt.rs b/crates/pa-core/src/prompts/system_prompt.rsindex 9af9e8cd6f..ff4e49f176 100644--- a/crates/pa-core/src/prompts/system_prompt.rs+++ b/crates/pa-core/src/prompts/system_prompt.rs@@ -88,8 +88,14 @@ pub struct BuildSystemPromptOptions<'a> {pub rlm_depth: Option<u32>,/// Human-readable parent name or id for child communication doctrine.pub rlm_parent_agent: Option<&'a str>,- /// Whether the session has no RLM child runtime (no daemon to spawn through).+ /// Whether the session runs without a daemon (no scheduler, no+ /// bash-completion wake-ups). The wake-up facts the daemonless line+ /// states must match the embedding's wiring.pub daemonless: bool,+ /// Whether `rlm.spawn` can create children in this session (the+ /// daemonless print host or a daemon worker); a daemonless session+ /// without one cannot spawn at all.+ pub can_spawn: bool,/// Enabled user-configured generic MCP servers.pub generic_mcp_servers: Vec<String>,}@@ -305,10 +311,13 @@ fn session_role_section(options: &BuildSystemPromptOptions, has_ipython: bool) -if depth == 0 { " (root)" } else { " (not root)" })];if options.daemonless {- lines.push(- "Subagents and completion notifications are unavailable in this session (no daemon): rlm.spawn will error, and nothing wakes you after your turn ends, so await background commands before ending it. Plan to do all work yourself."- .to_string(),- );+ lines.push(if options.can_spawn {+ "This session has no daemon: heartbeats never fire, and background `bash()` completions do not wake you, so await them before ending your turn. Subagent replies and exit notices still wake you, and the run waits for your subagents before it exits."+ .to_string()+ } else {+ "This session has no daemon: `rlm.spawn` is unavailable, heartbeats never fire, and background `bash()` completions do not wake you, so await them before ending your turn."+ .to_string()+ });}if !has_ipython {lines.push(diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rsindex 515d51bb89..513b9c3c47 100644--- a/crates/pa-core/src/session_engine/engine.rs+++ b/crates/pa-core/src/session_engine/engine.rs@@ -49,6 +49,12 @@ pub struct SessionEngineConfig {/// The session's depth in the RLM recursion tree (0 for top-level/// sessions); gates the `refine.*` host requests.pub rlm_depth: Option<u32>,+ /// Whether the session runs without a daemon: nothing outside the+ /// session itself (no scheduler, no bash-completion wake) starts a+ /// turn. Set explicitly by the embedding; print sessions are+ /// daemonless with or without an inline-subagent host, daemon+ /// workers are not.+ pub daemonless: bool,/// The full registry model (input modalities for `model.info`); the/// engine derives minimal facts from `model` when absent.pub model_info: Option<pa_types::ai::Model>,@@ -518,7 +524,8 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S// A spawned child's prompt must read "depth: N (not root)" with// the child-agent reply doctrine, never the root identity.rlm_depth: config.rlm_depth,- daemonless: config.rlm_subagent_host.is_none(),+ daemonless: config.daemonless,+ can_spawn: config.rlm_subagent_host.is_some(),generic_mcp_servers,prompt_guidelines: Some(prompt_guidelines),..Default::default()diff --git a/crates/pa-core/src/session_engine/engine/tests.rs b/crates/pa-core/src/session_engine/engine/tests.rsindex 93e5a4787c..79e41d3bb5 100644--- a/crates/pa-core/src/session_engine/engine/tests.rs+++ b/crates/pa-core/src/session_engine/engine/tests.rs@@ -81,6 +81,7 @@ async fn engine_runs_tool_loop_and_persists() {extra_builtin_skill_overrides: vec![],rlm_subagent_host: None,rlm_depth: None,+ daemonless: true,telemetry: None,model_info: None,on_background_work_settled: None,@@ -180,6 +181,7 @@ async fn spawned_child_prompt_stamps_its_depth() {extra_builtin_skill_overrides: vec![],rlm_subagent_host: None,rlm_depth: Some(2),+ daemonless: true,telemetry: None,model_info: None,on_background_work_settled: None,@@ -247,6 +249,7 @@ async fn oauth_creds_unlock_generic_mcp_gating_in_new_sessions() {extra_builtin_skill_overrides: vec![],rlm_subagent_host: None,rlm_depth: None,+ daemonless: true,telemetry: None,model_info: None,on_background_work_settled: None,diff --git a/crates/pa-core/src/session_engine/goal_boundary.rs b/crates/pa-core/src/session_engine/goal_boundary.rsindex d93f9ac367..6d9b771f6a 100644--- a/crates/pa-core/src/session_engine/goal_boundary.rs+++ b/crates/pa-core/src/session_engine/goal_boundary.rs@@ -83,13 +83,10 @@ impl SessionEngine {.ok()}- /// Mint one goal continuation: an active goal consumes one slot and returns- /// its context row; a failed persist fails the goal and mints nothing.- pub async fn mint_goal_continuation(&self) -> Option<CustomMessage> {- // The just-settled turn gates the mint (read before the driver lock),- // and a trailing failed continuation pair stops riding the context.- let last_turn: Option<pa_agent::types::AssistantMessage> = self- .session+ /// The latest settled assistant turn in its loop form: the natural mint+ /// gates on it and the RLM settle site's delivery decides from it.+ pub async fn latest_settled_assistant(&self) -> Option<pa_agent::types::AssistantMessage> {+ self.session.last_assistant_message().await.and_then(|wire| match wire {@@ -97,7 +94,14 @@ impl SessionEngine {super::provider_adapter::json_round_trip(&assistant)}_ => None,- });+ })+ }++ /// The just-settled turn that gates a goal mint, with a trailing failed+ /// continuation pair dropped so the corpse stops riding the context (the+ /// daemon's consult and settle sites perform the same read-and-drop).+ async fn last_turn_for_goal_mint(&self) -> Option<pa_agent::types::AssistantMessage> {+ let last_turn = self.latest_settled_assistant().await;if last_turn.as_ref().is_some_and(|turn: &pa_agent::types::AssistantMessage| {@@ -107,13 +111,28 @@ impl SessionEngine {{self.session.drop_failed_goal_continuation().await;}+ last_turn+ }++ /// Mint one goal continuation: an active goal consumes one slot and+ /// returns its context row — the armed RLM deferral delivers first+ /// (whichever consult runs after the blockers clear consumes it) — and+ /// a failed persist fails the goal and mints nothing.+ pub async fn mint_goal_continuation(&self) -> Option<CustomMessage> {+ let last_turn = self.last_turn_for_goal_mint().await;let persistence = self.session.shared_persistence();let mut driver = self.goal_driver.lock().await;if !driver.owns_continuation_wakeup() {return None;}let mut session = persistence.lock().await;- match driver.next_continuation_message(&mut session, last_turn.as_ref()) {+ let was_owed = driver.owes_continuation();+ let minted = if was_owed {+ driver.take_owed_continuation(&mut session, last_turn.as_ref())+ } else {+ driver.next_continuation_message(&mut session, last_turn.as_ref())+ };+ match minted {Ok(message) => message,Err(error) => {let message = format!("{error:#}");@@ -171,4 +190,52 @@ impl SessionEngine {pub async fn clear_pending_goal_continuation(&self) {self.goal_driver.lock().await.continuation_consumed();}++ /// Defer the goal continuation while descendant RLM work is unsettled+ /// (TS quiescence): the natural turn end arms the deferral, a later+ /// mint or the drive loop's settle site delivers it.+ pub async fn mark_goal_continuation_owed(&self) {+ self.goal_driver.lock().await.mark_continuation_owed();+ }++ /// Whether an active goal owns the wake-up discipline (an autonomous+ /// hold defers behind it and drops its own continuation).+ pub async fn goal_owns_continuation_wakeup(&self) -> bool {+ self.goal_driver.lock().await.owns_continuation_wakeup()+ }++ /// A goal that does not own the wake-up drops an armed RLM deferral+ /// (the daemon's consult order): the deferral dies with the goal's+ /// loop. No deferral, no locks.+ pub async fn drop_owed_goal_continuation(&self) {+ {+ let driver = self.goal_driver.lock().await;+ if !driver.owes_continuation() {+ return;+ }+ }+ let persistence = self.session.shared_persistence();+ let mut driver = self.goal_driver.lock().await;+ let mut session = persistence.lock().await;+ let _ = driver.take_owed_continuation(&mut session, /*last_turn*/ None);+ }++ /// Deliver the RLM-deferred goal continuation once descendant work+ /// settled: an inactive goal drops the deferral; a live one mints; a+ /// refusal keeps the deferral armed (a no-progress backoff window+ /// retries through the boundary's wake).+ pub async fn take_owed_goal_continuation(&self) -> Option<CustomMessage> {+ let last_turn = self.last_turn_for_goal_mint().await;+ let persistence = self.session.shared_persistence();+ let mut driver = self.goal_driver.lock().await;+ let mut session = persistence.lock().await;+ match driver.take_owed_continuation(&mut session, last_turn.as_ref()) {+ Ok(message) => message,+ Err(error) => {+ tracing::warn!("owed goal continuation mint failed: {error:#}");+ // The driver restored the deferral on its failed mint.+ None+ }+ }+ }}diff --git a/crates/pa-core/src/session_engine/rlm_host.rs b/crates/pa-core/src/session_engine/rlm_host.rsindex 2fc3582d1a..130cd90f1e 100644--- a/crates/pa-core/src/session_engine/rlm_host.rs+++ b/crates/pa-core/src/session_engine/rlm_host.rs@@ -215,9 +215,7 @@ impl RlmSubagentHost for NoRlmChildren {&self,_request: RlmCreateSessionRequest,) -> RlmHostFuture<RlmCreateSessionHandle> {- Box::pin(async {- anyhow::bail!("rlm.create_session requires a daemon-backed depth-0 session");- })+ Box::pin(async { Err(rlm_create_session_daemonless_error()) })}fn list_subagents(&self) -> RlmHostFuture<Vec<RlmSubagentEntry>> {Box::pin(async { Ok(Vec::new()) })@@ -266,6 +264,130 @@ pub fn no_children_collect(targets: &[String]) -> anyhow::Result<Vec<RlmChildResOk(Vec::new())}+// Shared spawn-site extractions (the daemon's supervisor host and the+// daemonless inline host answer with the same text and the same layout).++/// The workspace's default recursion bound (TS `DEFAULT_RLM_MAX_DEPTH`).+pub const DEFAULT_RLM_MAX_DEPTH: u32 = 2;++/// The spawn refusal at the recursion bound.+#[must_use]+pub fn rlm_depth_limit_error(depth: u32, max_depth: u32) -> anyhow::Error {+ anyhow::anyhow!(+ "RLM recursion depth limit reached (RLM_DEPTH={depth}, RLM_MAX_DEPTH={max_depth})"+ )+}++/// The spawn-name refusal: one source keeps the reservation check and the+/// availability check byte-identical across hosts.+#[must_use]+pub fn spawn_name_unavailable_error(name: &str, depth: u32) -> anyhow::Error {+ anyhow::anyhow!(+ "Agent name \"{name}\" is unavailable: an agent of that name already exists at depth {depth} under this parent"+ )+}++/// The `rlm.create_session` refusal for daemonless sessions (the+/// [`NoRlmChildren`] text, shared by every host that cannot create+/// resident sessions).+#[must_use]+pub fn rlm_create_session_daemonless_error() -> anyhow::Error {+ anyhow::anyhow!("rlm.create_session requires a daemon-backed depth-0 session")+}++/// The per-child session directory under the parent's artifacts tree (an+/// ephemeral temp dir when the parent has no durable session id).+///+/// # Errors+///+/// Error when the directory cannot be created.+pub fn rlm_child_session_dir(+ agent_dir: &std::path::Path,+ parent_session_id: Option<&str>,+ child_id: &str,+) -> anyhow::Result<std::path::PathBuf> {+ let base = match parent_session_id {+ Some(session_id) => agent_dir+ .join("session-artifacts")+ .join(session_id)+ .join(child_id),+ None => std::env::temp_dir().join(format!("prime-agent-rlm-{child_id}")),+ };+ std::fs::create_dir_all(&base).map_err(|error| {+ anyhow::anyhow!("create RLM child session dir {}: {error}", base.display())+ })?;+ Ok(base)+}++/// The last persisted `rlm_max_depth_state` custom entry in a session+/// file (TS `_loadPersistedRlmMaxDepthState`): the chat override a+/// resumed session re-seeds its depth bound from. `None` when absent or+/// unreadable.+pub fn persisted_rlm_max_depth(path: Option<&str>) -> Option<u64> {+ let path = std::path::Path::new(path?);+ let mut bytes = Vec::new();+ std::io::Read::read_to_end(+ &mut std::io::BufReader::new(std::fs::File::open(path).ok()?),+ &mut bytes,+ )+ .ok()?;+ let content = std::str::from_utf8(&bytes).ok()?;+ content+ .lines()+ .rev()+ // The exact union gate: a matching row's raw text carries either the+ // `customType` literal or a `\u`-escape (serde never letter-escapes),+ // so the union admits every line the reference could match;+ // `rlm_max_depth_row` judges the candidates by the decoded fields.+ .filter(|line| line.contains("rlm_max_depth_state") || line.contains("\\u"))+ .find_map(rlm_max_depth_row)+}++/// One candidate line's depth bound: `Some(depth)` for a matching custom+/// row with a parseable `data.maxDepth`, `None` otherwise.+fn rlm_max_depth_row(line: &str) -> Option<u64> {+ let value: serde_json::Value = serde_json::from_str(line.trim()).ok()?;+ if value.get("type").and_then(serde_json::Value::as_str) != Some("custom") {+ return None;+ }+ if value.get("customType").and_then(serde_json::Value::as_str) != Some("rlm_max_depth_state") {+ return None;+ }+ value+ .get("data")+ .and_then(|data| data.get("maxDepth"))+ .and_then(serde_json::Value::as_u64)+}++/// The depth-bound resolution and its precedence: chat override >+/// inherited > global setting > env > default. Returns the bound with its+/// source label (the daemon surfaces the label as `rlm_max_depth_source`).+#[must_use]+pub fn resolve_rlm_max_depth(+ session_file: Option<&str>,+ inherited: Option<u32>,+ cwd: &std::path::Path,+ agent_dir: &std::path::Path,+) -> (u64, &'static str) {+ persisted_rlm_max_depth(session_file)+ .map(|depth| (depth, "chat"))+ .or_else(|| inherited.map(|depth| (u64::from(depth), "inherited")))+ .or_else(|| {+ crate::settings::SettingsManager::create(cwd, agent_dir)+ .get_rlm_max_depth()+ .map(|depth| (depth, "global"))+ })+ .or_else(|| {+ std::env::var("RLM_MAX_DEPTH")+ .ok()+ .filter(|value| !value.is_empty())+ .and_then(|value| value.parse::<u64>().ok())+ .filter(|value| *value >= 1)+ .map(|depth| (depth, "env"))+ })+ .unwrap_or((u64::from(DEFAULT_RLM_MAX_DEPTH), "default"))+}+// Progress notes/// Outcome of one `rlm.progress.note`.diff --git a/crates/pa-core/tests/abort_kernel_cell.rs b/crates/pa-core/tests/abort_kernel_cell.rsindex bc88e4d95e..b55c84ea35 100644--- a/crates/pa-core/tests/abort_kernel_cell.rs+++ b/crates/pa-core/tests/abort_kernel_cell.rs@@ -165,6 +165,7 @@ async fn abort_during_a_kernel_cell_settles_the_turn_immediately() {extra_builtin_skill_overrides: Vec::new(),rlm_subagent_host: None,rlm_depth: None,+ daemonless: true,telemetry: None,model_info: None,mcp_manager: None,diff --git a/crates/pa-core/tests/turn_boundary_kernel.rs b/crates/pa-core/tests/turn_boundary_kernel.rsindex 46d8a2d5a9..ff2b198d04 100644--- a/crates/pa-core/tests/turn_boundary_kernel.rs+++ b/crates/pa-core/tests/turn_boundary_kernel.rs@@ -200,6 +200,7 @@ async fn turn_boundary_host_requests_round_trip_through_a_real_kernel() {extra_builtin_skill_overrides: Vec::new(),rlm_subagent_host: None,rlm_depth: None,+ daemonless: true,telemetry: None,model_info: Some(registry_model()),mcp_manager: None,diff --git a/crates/pa-daemon/src/agent_engine.rs b/crates/pa-daemon/src/agent_engine.rsindex 0626bbc383..8e2c0ab181 100644--- a/crates/pa-daemon/src/agent_engine.rs+++ b/crates/pa-daemon/src/agent_engine.rs@@ -57,7 +57,6 @@ use turn_types::{mod model;-use model::persisted_rlm_max_depth;pub(crate) use model::saved_session_context_from_parts;mod config;diff --git a/crates/pa-daemon/src/agent_engine/lifecycle.rs b/crates/pa-daemon/src/agent_engine/lifecycle.rsindex 60012575cc..490989dec8 100644--- a/crates/pa-daemon/src/agent_engine/lifecycle.rs+++ b/crates/pa-daemon/src/agent_engine/lifecycle.rs@@ -991,6 +991,8 @@ impl AgentSessionEngine {children as Arc<dyn pa_core::session_engine::rlm_host::RlmSubagentHost>}),rlm_depth: Some(self.rlm_depth.load(std::sync::atomic::Ordering::Relaxed)),+ // The worker session runs under the daemon scheduler and its wake-ups.+ daemonless: false,model_info: Some(model.clone()),// Prewarm; the depth gate keeps subagent workers lazy.prewarm_ipython_kernel: Some(true),diff --git a/crates/pa-daemon/src/agent_engine/model.rs b/crates/pa-daemon/src/agent_engine/model.rsindex c65bf4b6e2..2977f5fc2b 100644--- a/crates/pa-daemon/src/agent_engine/model.rs+++ b/crates/pa-daemon/src/agent_engine/model.rs@@ -1,11 +1,9 @@//! The agent-session engine's model concern: the startup/restore//! model-resolution cluster (the TS `createAgentSession` chain), the-//! session's live-model and thinking-level surfaces, the request API-key-//! seam, and the persisted max-depth read.+//! session's live-model and thinking-level surfaces, and the request+//! API-key seam.-use super::{- AgentSessionEngine, EngineModelSelection, Model, RestoredSessionModel, SessionEngine, Value,-};+use super::{AgentSessionEngine, EngineModelSelection, Model, RestoredSessionModel, SessionEngine};impl AgentSessionEngine {/// The startup chain: the saved settings default, then the featured@@ -400,47 +398,6 @@ impl AgentSessionEngine {}}-/// The last persisted `rlm_max_depth_state` custom entry in a session-/// file (TS `_loadPersistedRlmMaxDepthState`): the chat override a resumed-/// session re-seeds its depth bound from. `None` when absent or unreadable.-/// Same contract as the reference oracle (`agent_engine/tests.rs`): whole-/// file valid UTF-8, newest-first, malformed lines skip.-pub(crate) fn persisted_rlm_max_depth(path: Option<&str>) -> Option<u64> {- let path = std::path::Path::new(path?);- let mut bytes = Vec::new();- std::io::Read::read_to_end(- &mut std::io::BufReader::new(std::fs::File::open(path).ok()?),- &mut bytes,- )- .ok()?;- let content = std::str::from_utf8(&bytes).ok()?;- content- .lines()- .rev()- // The exact union gate: a matching row's raw text carries either the- // `customType` literal or a `\u`-escape (serde never letter-escapes),- // so the union admits every line the reference could match;- // `rlm_max_depth_row` judges the candidates by the decoded fields.- .filter(|line| line.contains("rlm_max_depth_state") || line.contains("\\u"))- .find_map(rlm_max_depth_row)-}--/// One candidate line's depth bound: `Some(depth)` for a matching custom-/// row with a parseable `data.maxDepth`, `None` otherwise.-fn rlm_max_depth_row(line: &str) -> Option<u64> {- let value: Value = serde_json::from_str(line.trim()).ok()?;- if value.get("type").and_then(Value::as_str) != Some("custom") {- return None;- }- if value.get("customType").and_then(Value::as_str) != Some("rlm_max_depth_state") {- return None;- }- value- .get("data")- .and_then(|data| data.get("maxDepth"))- .and_then(Value::as_u64)-}-/// The saved model context of a session file: the pinned `(provider,/// model)` and the saved thinking level, present only when the file carries/// a `thinking_level_change` row. `None` when the file cannot be read (thediff --git a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs b/crates/pa-daemon/src/agent_engine/session_engine_impl.rsindex f5d51ffa2b..b112bda605 100644--- a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs+++ b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs@@ -3,11 +3,11 @@//! turn state machine, and the export/telemetry reads.use super::{- artifact_reference, json, map_thinking_level, now_millis, persisted_rlm_max_depth,- AgentSessionEngine, Arc, BranchSummaryOutcome, BranchSummaryRequest, BranchSummaryRun,- CompactionOutcome, CompactionRequest, CompactionRun, EngineEvent, EngineModelSelection,- ParentIdentity, PromptRequest, ProviderTarget, SessionEngine, SideQuestionOutcome,- SideQuestionRequest, StartupScope, TurnPrompt, Value, DEFAULT_RLM_MAX_DEPTH,+ artifact_reference, json, map_thinking_level, now_millis, AgentSessionEngine, Arc,+ BranchSummaryOutcome, BranchSummaryRequest, BranchSummaryRun, CompactionOutcome,+ CompactionRequest, CompactionRun, EngineEvent, EngineModelSelection, ParentIdentity,+ PromptRequest, ProviderTarget, SessionEngine, SideQuestionOutcome, SideQuestionRequest,+ StartupScope, TurnPrompt, Value, DEFAULT_RLM_MAX_DEPTH,};use pa_core::session_engine::agent_messaging::AgentFamilyRelationship;@@ -837,28 +837,13 @@ impl SessionEngine for AgentSessionEngine {.ok_or_else(|| anyhow::anyhow!("unknown thinking level \"{thinking}\""))?;}// The depth bound's precedence: chat override > inherited > global- // setting > env > default.- let (max_depth, source) = persisted_rlm_max_depth(identity.session_file.as_deref())- .map(|depth| (depth, "chat"))- .or_else(|| {- identity- .rlm_max_depth- .map(|depth| (u64::from(depth), "inherited"))- })- .or_else(|| {- let settings =- pa_core::settings::SettingsManager::create(self.cwd(), &self.config.agent_dir);- settings.get_rlm_max_depth().map(|depth| (depth, "global"))- })- .or_else(|| {- std::env::var("RLM_MAX_DEPTH")- .ok()- .filter(|value| !value.is_empty())- .and_then(|value| value.parse::<u64>().ok())- .filter(|value| *value >= 1)- .map(|depth| (depth, "env"))- })- .unwrap_or((u64::from(DEFAULT_RLM_MAX_DEPTH), "default"));+ // setting > env > default (the shared resolver).+ let (max_depth, source) = pa_core::session_engine::rlm_host::resolve_rlm_max_depth(+ identity.session_file.as_deref(),+ identity.rlm_max_depth,+ &self.cwd(),+ &self.config.agent_dir,+ );*self.rlm_max_depth_source.lock().expect("depth source lock") = source;// The semantic-edge identity (TS `semanticEdgeLedgerPath` +// provenance): a spawned child's ledger lives in its rlm sessiondiff --git a/crates/pa-daemon/src/agent_engine/tests/rlm_children.rs b/crates/pa-daemon/src/agent_engine/tests/rlm_children.rsindex 3c9fdea561..3bb3f59870 100644--- a/crates/pa-daemon/src/agent_engine/tests/rlm_children.rs+++ b/crates/pa-daemon/src/agent_engine/tests/rlm_children.rs@@ -1,9 +1,10 @@//! The rlm-children tests (the persisted max-depth scan, the settled-child release probe).use super::*;+use pa_core::session_engine::rlm_host::persisted_rlm_max_depth;/// The reference reader the depth scan replaced, verbatim: the whole-file/// read plus a full `parse_session_entries` walk. The scan-/// (`model::persisted_rlm_max_depth`) must match it on every class.+/// (`rlm_host::persisted_rlm_max_depth`) must match it on every class.fn persisted_rlm_max_depth_reference(path: Option<&str>) -> Option<u64> {let path = std::path::Path::new(path?);let content = std::fs::read_to_string(path).ok()?;@@ -199,7 +200,7 @@ fn persisted_rlm_max_depth_scan_matches_reference_across_classes() {std::fs::write(&path, bytes).unwrap();let path_str = path.display().to_string();assert_eq!(- model::persisted_rlm_max_depth(Some(&path_str)),+ persisted_rlm_max_depth(Some(&path_str)),persisted_rlm_max_depth_reference(Some(&path_str)),"depth class {name}");@@ -220,24 +221,24 @@ fn persisted_rlm_max_depth_scan_matches_reference_across_classes() {std::fs::write(&path, bytes).unwrap();let path_str = path.display().to_string();assert_eq!(- model::persisted_rlm_max_depth(Some(&path_str)),+ persisted_rlm_max_depth(Some(&path_str)),persisted_rlm_max_depth_reference(Some(&path_str)),"depth class invalid_utf8");assert!(- model::persisted_rlm_max_depth(Some(&path_str)).is_none(),+ persisted_rlm_max_depth(Some(&path_str)).is_none(),"invalid utf8 voids the override");}// Missing file and absent path: both readers keep the create-carried bound.- assert_eq!(model::persisted_rlm_max_depth(None), None);+ assert_eq!(persisted_rlm_max_depth(None), None);assert_eq!(- model::persisted_rlm_max_depth(None),+ persisted_rlm_max_depth(None),persisted_rlm_max_depth_reference(None));let missing = "/nonexistent-cold-open-residual/session.jsonl";assert_eq!(- model::persisted_rlm_max_depth(Some(missing)),+ persisted_rlm_max_depth(Some(missing)),persisted_rlm_max_depth_reference(Some(missing)));}diff --git a/crates/pa-daemon/src/rlm_child_model.rs b/crates/pa-daemon/src/rlm_child_model.rsindex 99f3aea9ff..f37258e4fd 100644--- a/crates/pa-daemon/src/rlm_child_model.rs+++ b/crates/pa-daemon/src/rlm_child_model.rs@@ -62,7 +62,12 @@ pub fn resolve_child_model(/// The resolution before the allowlist gate: `None` inherits the parent model; a reference resolves/// parent equality first, then an exact catalog selector, then a unique short-form match.-fn resolve_child_model_unchecked(+/// Public for the daemonless print host: print sessions do not enforce+/// `allowedModels`, so its children do not either.+///+/// # Errors+/// Returns an error when the reference cannot be resolved against the catalog.+pub fn resolve_child_model_unchecked(agent_dir: &Path,reference: Option<&str>,parent_model: Option<&str>,diff --git a/crates/pa-daemon/src/rlm_children.rs b/crates/pa-daemon/src/rlm_children.rsindex 89c99f8f70..b2f3687e27 100644--- a/crates/pa-daemon/src/rlm_children.rs+++ b/crates/pa-daemon/src/rlm_children.rs@@ -24,6 +24,10 @@ use pa_types::session::CustomMessage;use serde_json::{json, Value};use tokio::sync::Mutex;+use pa_core::session_engine::rlm_host::{+ rlm_child_session_dir, rlm_depth_limit_error, spawn_name_unavailable_error,+};+use crate::rlm_child_model::{assert_thinking_supported, cap_text, compact_rlm_text, resolve_child_model, rlm_child_label,ANSWER_TEXT_MAX_CHARS,@@ -31,7 +35,7 @@ use crate::rlm_child_model::{use crate::supervisor_link::SupervisorLink;use crate::util::now_ms;-pub const DEFAULT_RLM_MAX_DEPTH: u32 = 2;+pub use pa_core::session_engine::rlm_host::DEFAULT_RLM_MAX_DEPTH;/// Close reasons: `Killed` — jobs cancel, the session file archives;/// `Shutdown` — the resume entry survives, so a later scheduled wake can@@ -890,7 +894,7 @@ impl SupervisorChildSessionsInner {let children = self.children.lock().await;for record in children.iter() {if record.lock().await.session_name == name {- return Err(spawn_name_unavailable(name, depth));+ return Err(spawn_name_unavailable_error(name, depth));}}Ok(())@@ -915,28 +919,11 @@ impl SupervisorChildSessionsInner {/// The per-child session directory under the parent's artifacts tree.fn child_session_dir(&self, child_id: &str, identity: &ParentIdentity) -> Result<PathBuf> {- let base = match &identity.session_id {- Some(session_id) => self- .agent_dir- .join("session-artifacts")- .join(session_id)- .join(child_id),- // No persistent parent artifacts dir: an ephemeral temp dir.- None => std::env::temp_dir().join(format!("prime-agent-rlm-{child_id}")),- };- std::fs::create_dir_all(&base)- .with_context(|| format!("create RLM child session dir {}", base.display()))?;- Ok(base)+ rlm_child_session_dir(&self.agent_dir, identity.session_id.as_deref(), child_id)+ .with_context(|| format!("spawn RLM child session dir {child_id}"))}}-/// One source so the reservation refusal and the availability check stay byte-identical.-fn spawn_name_unavailable(name: &str, depth: u32) -> anyhow::Error {- anyhow!(- "Agent name \"{name}\" is unavailable: an agent of that name already exists at depth {depth} under this parent"- )-}-mod host;mod lifecycle;mod registry;diff --git a/crates/pa-daemon/src/rlm_children/host.rs b/crates/pa-daemon/src/rlm_children/host.rsindex 54679db076..31bcc5326f 100644--- a/crates/pa-daemon/src/rlm_children/host.rs+++ b/crates/pa-daemon/src/rlm_children/host.rs@@ -5,12 +5,12 @@use super::{assert_thinking_supported, bail, create_default_rlm_subagent_session_name,create_rlm_child_terminal_notice, json, now_ms, resolve_child_model, rlm_child_label,- spawn_name_unavailable, Arc, ChildCloseReason, ChildRecord, Context, DaemonCommand, Duration,- Instant, Mutex, Path, PathBuf, Result, RlmChildResult, RlmChildTerminalNotice,- RlmCreateSessionHandle, RlmCreateSessionRequest, RlmDeleteSubagentResult, RlmHostFuture,- RlmSpawnHandle, RlmSpawnRequest, RlmSubagentEntry, RlmSubagentHost, SpawnNameReservationGuard,- SupervisorChildSessions, SupervisorChildSessionsInner, Value, KILL_TIMEOUT_MS,- RENAME_TIMEOUT_MS,+ rlm_depth_limit_error, spawn_name_unavailable_error, Arc, ChildCloseReason, ChildRecord,+ Context, DaemonCommand, Duration, Instant, Mutex, Path, PathBuf, Result, RlmChildResult,+ RlmChildTerminalNotice, RlmCreateSessionHandle, RlmCreateSessionRequest,+ RlmDeleteSubagentResult, RlmHostFuture, RlmSpawnHandle, RlmSpawnRequest, RlmSubagentEntry,+ RlmSubagentHost, SpawnNameReservationGuard, SupervisorChildSessions,+ SupervisorChildSessionsInner, Value, KILL_TIMEOUT_MS, RENAME_TIMEOUT_MS,};/// Resolve the child model with the daemon `allowedModels` allowlist enforced, refusing loudly with@@ -57,11 +57,10 @@ impl RlmSubagentHost for SupervisorChildSessions {Box::pin(async move {let identity = this.identity.lock().expect("identity lock").clone();if identity.rlm_depth >= identity.rlm_max_depth {- bail!(- "RLM recursion depth limit reached (RLM_DEPTH={}, RLM_MAX_DEPTH={})",+ bail!(rlm_depth_limit_error(identity.rlm_depth,identity.rlm_max_depth- );+ ));}let child_id = format!("sub-{}", &uuid::Uuid::new_v4().simple().to_string()[..8]);let name = request.name.clone().unwrap_or_else(|| {@@ -75,7 +74,7 @@ impl RlmSubagentHost for SupervisorChildSessions {.is_some().then(|| {if !this.reserve_spawn_name(&name) {- return Err(spawn_name_unavailable(&name, identity.rlm_depth + 1));+ return Err(spawn_name_unavailable_error(&name, identity.rlm_depth + 1));}Ok(SpawnNameReservationGuard {inner: Arc::clone(&this),