A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(rlm): show the spawn kickoff as an agent message from the parent (#3369)
Sebastian Müller419777a893e8
diff --git a/.changes/spawn-kickoff-agent-message.md b/.changes/spawn-kickoff-agent-message.mdnew file mode 100644index 0000000000..33b9423460--- /dev/null+++ b/.changes/spawn-kickoff-agent-message.md@@ -0,0 +1 @@+- A spawned subagent's kickoff task now renders as an agent message from the parent (labeled `[task from parent]`) instead of an unlabeled user message, and spawn prompts are no longer expanded as slash commands or prompt templates, matching the TypeScript version.diff --git a/crates/pa-core/src/session_engine/agent_messaging.rs b/crates/pa-core/src/session_engine/agent_messaging.rsindex 1a73dd30e0..e1eb003c7c 100644--- a/crates/pa-core/src/session_engine/agent_messaging.rs+++ b/crates/pa-core/src/session_engine/agent_messaging.rs@@ -276,7 +276,7 @@ pub struct AgentSessionMessageRowPayload<'a> {pub message: &'a str,pub from: &'a Value,pub from_relationship: Option<AgentFamilyRelationship>,- pub target: &'a Value,+ pub target: Option<&'a Value>,/// Unix timestamp in milliseconds.pub timestamp: u64,}@@ -293,7 +293,9 @@ pub fn create_agent_session_message_row(payload: &AgentSessionMessageRowPayload<if let Some(relationship) = payload.from_relationship {details.insert("fromRelationship".to_string(), json!(relationship.as_str()));}- details.insert("target".to_string(), payload.target.clone());+ if let Some(target) = payload.target {+ details.insert("target".to_string(), target.clone());+ }json!({"role": "custom","customType": AGENT_MESSAGE_CUSTOM_TYPE,diff --git a/crates/pa-core/src/session_engine/agent_messaging/tests.rs b/crates/pa-core/src/session_engine/agent_messaging/tests.rsindex 3139893ed6..2d20527581 100644--- a/crates/pa-core/src/session_engine/agent_messaging/tests.rs+++ b/crates/pa-core/src/session_engine/agent_messaging/tests.rs@@ -130,7 +130,7 @@ fn the_custom_row_carries_the_ts_agent_message_shape() {message: "finished the research",from: &from,from_relationship: Some(AgentFamilyRelationship::Child),- target: &target,+ target: Some(&target),timestamp: 123,});// TS `createAgentSessionMessage`: custom role, agent_message type, prompt as content, and the@@ -153,10 +153,13 @@ fn the_custom_row_carries_the_ts_agent_message_shape() {message: "finished the research",from: &Value::Null,from_relationship: None,- target: &target,+ // An absent target omits the key too (TS `spawnMessage` carries+ // none), not a null.+ target: None,timestamp: 124,});assert!(plain["details"].get("fromRelationship").is_none());+ assert!(plain["details"].get("target").is_none());assert_eq!(plain["details"]["from"], Value::Null);}diff --git a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs b/crates/pa-daemon/src/agent_engine/session_engine_impl.rsindex b56744d5fa..31565bb287 100644--- a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs+++ b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs@@ -302,7 +302,16 @@ impl SessionEngine for AgentSessionEngine {*self.own_summary.lock()- .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(summary);+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(summary.clone());+ if let Some(children) = &self.children {+ children.set_parent_session_name(+ summary+ .get("sessionName")+ .and_then(Value::as_str)+ .filter(|name| !name.is_empty())+ .map(str::to_string),+ );+ }}fn configure_service_tier(&self, tier: Option<pa_types::ai::ServiceTier>) {diff --git a/crates/pa-daemon/src/rlm_child_usage.rs b/crates/pa-daemon/src/rlm_child_usage.rsindex 7488c889d5..c5f889d377 100644--- a/crates/pa-daemon/src/rlm_child_usage.rs+++ b/crates/pa-daemon/src/rlm_child_usage.rs@@ -1,7 +1,7 @@//! The child-side half of RLM usage attribution: splitting one child's//! session rows into per-origin batches (the engine-side producer owns the rest).//!-//! Origin labels: the task prompt is the first user row (`spawn_task`); later+//! Origin labels: the task prompt is the spawn kickoff row (`spawn_task`);//! user rows are `direct_user`; `error`/`aborted` fold nowhere.use pa_types::ai::Usage;@@ -20,26 +20,13 @@ fn message_role(entry: &SessionEntry, role: &str) -> bool {== Some(role)}-/// The index of the child file's first user row (the task prompt).-fn first_user_row(entries: &[SessionEntry]) -> Option<usize> {- entries.iter().position(|entry| message_role(entry, "user"))-}-/// The nearest preceding user or agent-session message row labels a completion's origin; non-agent-/// custom rows and plain user rows (after the task prompt) label `direct_user`.-fn child_usage_origin(- entries: &[SessionEntry],- task_prompt_row: Option<usize>,- assistant_index: usize,-) -> ChildUsageOrigin {+/// custom rows and plain user rows label `direct_user`.+fn child_usage_origin(entries: &[SessionEntry], assistant_index: usize) -> ChildUsageOrigin {for index in (0..assistant_index).rev() {let entry = &entries[index];if message_role(entry, "user") {- return if Some(index) == task_prompt_row {- ChildUsageOrigin::SpawnTask- } else {- ChildUsageOrigin::DirectUser- };+ return ChildUsageOrigin::DirectUser;}if entry.type_ != "custom_message" {continue;@@ -96,13 +83,12 @@ pub(crate) fn child_usage_batches(entries: &[SessionEntry],from: usize,) -> (Vec<(ChildUsageOrigin, Usage)>, usize) {- let task_prompt_row = first_user_row(entries);let mut batches: Vec<(ChildUsageOrigin, Usage)> = Vec::new();for (index, entry) in entries.iter().enumerate().skip(from) {let Some(usage) = assistant_usage(entry) else {continue;};- let origin = child_usage_origin(entries, task_prompt_row, index);+ let origin = child_usage_origin(entries, index);match batches.iter_mut().find(|(origin_, _)| *origin_ == origin) {Some((_, total)) => {pa_core::session_engine::rlm_usage::add_assistant_usage(total, &usage);@@ -154,6 +140,16 @@ mod tests {)}+ /// The spawn kickoff row (TS `spawnMessage`: the `agent_message` custom+ /// row with `details.id "spawn:<id>"`).+ fn spawn_kickoff_row(id: &str, message: &str) -> SessionEntry {+ custom_message_row(+ id,+ "agent_message",+ &json!({"id": "spawn:sub-1", "message": message}),+ )+ }+fn captured_usage(input: u64, output: u64, total_tokens: u64, cost_total: f64) -> Value {json!({"input": input, "output": output, "cacheRead": 0, "cacheWrite": 0,@@ -166,15 +162,15 @@ mod tests {serde_json::from_value(entry.fields["message"]["usage"].clone()).unwrap()}- /// The origin walk over a real child-file shape: the first user row is- /// the task prompt, an agent-message custom row relabels the origin,+ /// The origin walk over a real child-file shape: the spawn kickoff row+ /// is the task prompt, an agent-message custom row relabels the origin,/// a later user row is a direct user prompt, and an aborted/// completion folds nowhere. The captured numbers verify the/// `spawn_task` batch: 50,208 input + 2,929 output, $0.0089957.#[test]fn origin_walk_and_cursor_over_a_child_file() {let entries = vec![- user_row("u1"),+ spawn_kickoff_row("c0", "ship the lane"),assistant_row("a1",&captured_usage(50_208, 2_929, 53_137, 0.008_995_7),@@ -237,7 +233,7 @@ mod tests {#[test]fn batches_sum_across_completions_of_one_origin() {let entries = vec![- user_row("u1"),+ spawn_kickoff_row("c0", "ship the lane"),assistant_row("a1", &captured_usage(10, 5, 0, 0.01), "toolUse"),assistant_row("a2", &captured_usage(20, 8, 0, 0.02), "stop"),];diff --git a/crates/pa-daemon/src/rlm_children.rs b/crates/pa-daemon/src/rlm_children.rsindex de0ca7e8e2..8bb9d11b26 100644--- a/crates/pa-daemon/src/rlm_children.rs+++ b/crates/pa-daemon/src/rlm_children.rs@@ -302,6 +302,10 @@ struct SupervisorChildSessionsInner {link: Arc<SupervisorLink>,agent_dir: PathBuf,parent_active_session_id: String,+ /// The parent session's live name (the worker's summary, the TS+ /// `sessionName` of every spawn row's `from` endpoint): `None` until+ /// the worker publishes a summary, and refreshed by every rename.+ parent_session_name: std::sync::Mutex<Option<String>>,// Std mutex: the identity lock is only a data swap, never held across// an await, so sync engine paths can set it without a runtime `block_on`.identity: std::sync::Mutex<ParentIdentity>,@@ -368,6 +372,7 @@ impl SupervisorChildSessions {link,agent_dir,parent_active_session_id,+ parent_session_name: std::sync::Mutex::new(None),identity: std::sync::Mutex::new(ParentIdentity::with_default_depth()),children: Mutex::new(Vec::new()),pending_spawn_names: std::sync::Mutex::new(std::collections::HashSet::new()),@@ -507,6 +512,22 @@ impl SupervisorChildSessions {*self.inner.identity.lock().expect("identity lock") = identity;}+ /// Replace the parent session's live name (the worker's summary — the+ /// `sessionName` of the spawn kickoff's `from` endpoint); `None` when+ /// the summary carries none.+ ///+ /// # Panics+ ///+ /// Panics when the name mutex is poisoned (a holder panicked while+ /// holding the lock).+ pub fn set_parent_session_name(&self, name: Option<String>) {+ *self+ .inner+ .parent_session_name+ .lock()+ .expect("parent session name lock") = name;+ }+/// Rebuild the children registry from the spawn ledger (a restarted/// parent lists its ledger children again).pub async fn reseed_from_ledger(&self) {diff --git a/crates/pa-daemon/src/rlm_children/host.rs b/crates/pa-daemon/src/rlm_children/host.rsindex 8d47603d81..35c1b0113e 100644--- a/crates/pa-daemon/src/rlm_children/host.rs+++ b/crates/pa-daemon/src/rlm_children/host.rs@@ -158,7 +158,42 @@ impl RlmSubagentHost for SupervisorChildSessions {// starts after the parent's continuation request is in flight.let watcher_this = Arc::clone(&this);let watcher_record = Arc::clone(&record);- let prompt = request.prompt.clone();+ // TS `spawnMessage`: the kickoff rides prompt admission as+ // the parent's `agent_message` row, so the child renders a+ // parent message and the model reads the+ // "[task from parent]" label.+ let prompt = request.prompt.as_str();+ let kickoff_content = format!("[task from parent]\n\n{prompt}");+ let kickoff_row_id = format!("spawn:{child_id}");+ let mut parent_endpoint = json!({+ "activeSessionId": this.parent_active_session_id,+ });+ if let Some(session_id) = &identity.session_id {+ parent_endpoint["sessionId"] = json!(session_id);+ }+ if let Some(name) = this+ .parent_session_name+ .lock()+ .expect("parent session name lock")+ .clone()+ {+ parent_endpoint["sessionName"] = json!(name);+ }+ let kickoff_row =+ pa_core::session_engine::agent_messaging::create_agent_session_message_row(+ &pa_core::session_engine::agent_messaging::AgentSessionMessageRowPayload {+ id: &kickoff_row_id,+ prompt: &kickoff_content,+ message: prompt,+ from: &parent_endpoint,+ from_relationship: Some(+ pa_core::session_engine::agent_messaging::AgentFamilyRelationship::Parent,+ ),+ // TS `spawnMessage` carries no `target`.+ target: None,+ timestamp: now_ms(),+ },+ );let child_active_session_id = created.active_session_id.clone();let child_session_file = created.session_file.clone();let child_log_id = child_id.clone();@@ -176,20 +211,30 @@ impl RlmSubagentHost for SupervisorChildSessions {}watcher_record.lock().await.prompt_admitted = true;if let Err(error) = watcher_this- .prompt_child(&child_active_session_id, &prompt)+ .prompt_child(+ &child_active_session_id,+ &kickoff_content,+ Some(&kickoff_row),+ ).await{// The route can fail ambiguously around a worker// replacement. The durable session file arbitrates: a- // prompt in the file landed (re-sending would duplicate- // the first turn); one retry is safe.- let landed =- session_file_carries_prompt(child_session_file.as_deref(), &prompt);+ // kickoff row in the file landed (re-sending would+ // duplicate the first turn); one retry is safe.+ let landed = session_file_carries_spawn_kickoff(+ child_session_file.as_deref(),+ &kickoff_row_id,+ );let retried = if landed {Ok(())} else {watcher_this- .prompt_child(&child_active_session_id, &prompt)+ .prompt_child(+ &child_active_session_id,+ &kickoff_content,+ Some(&kickoff_row),+ ).await};if let Err(retry_error) = retried {@@ -597,9 +642,14 @@ impl RlmSubagentHost for SupervisorChildSessions {}}-/// Whether the child's durable session file already carries the task-/// prompt (the record a worker replacement replays from arbitrates).-fn session_file_carries_prompt(session_file: Option<&str>, prompt: &str) -> bool {+/// Whether the child's durable session file already carries the spawn+/// kickoff row (`agent_message` custom row with `details.id` =+/// `spawn:<child id>`). The session file is the record a worker+/// replacement replays from, so it arbitrates an ambiguous prompt-route+/// failure: a row in the file was durably processed by the dead worker (a+/// re-send would duplicate the first turn), a missing row provably never+/// landed.+fn session_file_carries_spawn_kickoff(session_file: Option<&str>, spawn_row_id: &str) -> bool {let Some(path) = session_file.filter(|path| !path.is_empty()) else {return false;};@@ -609,18 +659,10 @@ fn session_file_carries_prompt(session_file: Option<&str>, prompt: &str) -> boolcontent.lines().filter_map(|line| serde_json::from_str::<Value>(line).ok())- .filter(|entry| {- entry.get("type").and_then(Value::as_str) == Some("message")- && entry.pointer("/message/role").and_then(Value::as_str) == Some("user")- })- .any(|entry| match entry.pointer("/message/content") {- Some(Value::String(text)) => text.contains(prompt),- Some(Value::Array(blocks)) => blocks.iter().any(|block| {- block- .get("text")- .and_then(Value::as_str)- .is_some_and(|text| text.contains(prompt))- }),- _ => false,+ .any(|entry| {+ entry.get("type").and_then(Value::as_str) == Some("custom_message")+ && entry.get("customType").and_then(Value::as_str)+ == Some(pa_core::session_engine::agent_messaging::AGENT_MESSAGE_CUSTOM_TYPE)+ && entry.pointer("/details/id").and_then(Value::as_str) == Some(spawn_row_id)})}diff --git a/crates/pa-daemon/src/rlm_children/lifecycle.rs b/crates/pa-daemon/src/rlm_children/lifecycle.rsindex 820b39d0e9..f3572a0dc2 100644--- a/crates/pa-daemon/src/rlm_children/lifecycle.rs+++ b/crates/pa-daemon/src/rlm_children/lifecycle.rs@@ -179,7 +179,10 @@ impl SupervisorChildSessionsInner {.await?;// A failed prompt tears the just-created session down (TS kills the// created session in the create-path catch block).- if let Err(error) = self.prompt_child(&created.active_session_id, prompt).await {+ if let Err(error) = self+ .prompt_child(&created.active_session_id, prompt, None)+ .await+ {let _ = self.kill_child(&created.active_session_id, ChildCloseReason::Killed).await;@@ -273,7 +276,15 @@ impl SupervisorChildSessionsInner {None}- pub(super) async fn prompt_child(&self, active_session_id: &str, prompt: &str) -> Result<()> {+ /// Prompt one child over the supervisor link (TS `promptAndWait`):+ /// `custom_message` replaces the persisted user row (TS+ /// `customMessage`).+ pub(super) async fn prompt_child(+ &self,+ active_session_id: &str,+ prompt: &str,+ custom_message: Option<&Value>,+ ) -> Result<()> {let make_command = |selector: &str| DaemonCommand::Prompt {id: None,active_session_id: selector.to_string(),@@ -286,7 +297,7 @@ impl SupervisorChildSessionsInner {expand_prompt_templates: None,source: Some(json!("rpc")),agent_message_id: None,- custom_message: None,+ custom_message: custom_message.cloned(),queue_key: None,prefix_messages: None,admission_id: None,diff --git a/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs b/crates/pa-daemon/src/rlm_children/usage_emit_tests.rsindex a0402c6436..b718fb5db9 100644--- a/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs+++ b/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs@@ -78,8 +78,8 @@ fn child_file(dir: &Path) -> PathBuf {&path,concat!(r#"{"type":"session","id":"child-1","timestamp":"2026-09-23T00:00:00.000Z","cwd":"/tmp","version":3}"#, "\n",- r#"{"type":"message","id":"u1","parentId":null,"timestamp":"2026-09-23T00:00:01.000Z","message":{"role":"user","content":[{"type":"text","text":"the task"}],"timestamp":0}}"#, "\n",- r#"{"type":"message","id":"a1","parentId":"u1","timestamp":"2026-09-23T00:00:02.000Z","message":{"role":"assistant","content":[],"stopReason":"toolUse","usage":{"input":50208,"output":2929,"cacheRead":0,"cacheWrite":0,"totalTokens":53137,"cost":{"input":0.0075312,"output":0.0014645,"cacheRead":0,"cacheWrite":0,"total":0.0089957}}}}"#, "\n",+ r#"{"type":"custom_message","id":"c0","parentId":null,"timestamp":"2026-09-23T00:00:01.000Z","customType":"agent_message","content":"[task from parent]\n\nthe task","display":true,"details":{"id":"spawn:child-1","message":"the task"}}"#, "\n",+ r#"{"type":"message","id":"a1","parentId":"c0","timestamp":"2026-09-23T00:00:02.000Z","message":{"role":"assistant","content":[],"stopReason":"toolUse","usage":{"input":50208,"output":2929,"cacheRead":0,"cacheWrite":0,"totalTokens":53137,"cost":{"input":0.0075312,"output":0.0014645,"cacheRead":0,"cacheWrite":0,"total":0.0089957}}}}"#, "\n",),).unwrap();diff --git a/crates/pa-daemon/src/session_store/tests.rs b/crates/pa-daemon/src/session_store/tests.rsindex eba967d548..e719f3d53b 100644--- a/crates/pa-daemon/src/session_store/tests.rs+++ b/crates/pa-daemon/src/session_store/tests.rs@@ -187,12 +187,23 @@ fn the_depth_two_chain_reports_the_folded_aggregate() {"totalTokens": 1_040,"cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0.10 },});+ let kickoff = |id: &str, parent: Option<&str>| {+ json!({+ "type": "custom_message", "id": id, "parentId": parent,+ "timestamp": "2026-09-24T00:00:00.000Z",+ "customType": "agent_message",+ "content": "[task from parent]\n\ntask",+ "display": true,+ "details": { "id": "spawn:sub-1", "message": "task" },+ })+ .to_string()+ };let lines = [json!({"type": "session", "version": 3, "id": "child-s1", "timestamp": "2026-09-24T00:00:00.000Z", "cwd": "/tmp"}).to_string(),- row("u1", None, json!({"role": "user", "content": "task"})),+ kickoff("c0", None),row("a1",- Some("u1"),+ Some("c0"),json!({"role": "assistant","provider": "prime-inference", "model": "internal/glm-5.3-fast",diff --git a/crates/pa-daemon/src/worker/input.rs b/crates/pa-daemon/src/worker/input.rsindex 926db0718c..5cc20dc44a 100644--- a/crates/pa-daemon/src/worker/input.rs+++ b/crates/pa-daemon/src/worker/input.rs@@ -355,7 +355,7 @@ impl Worker {message,from: &sender,from_relationship,- target: &target,+ target: Some(&target),timestamp: crate::util::now_ms(),},);diff --git a/crates/pa-daemon/tests/rlm_children_e2e.rs b/crates/pa-daemon/tests/rlm_children_e2e.rsindex bd9b06d21c..d35b3e3e96 100644--- a/crates/pa-daemon/tests/rlm_children_e2e.rs+++ b/crates/pa-daemon/tests/rlm_children_e2e.rs@@ -209,6 +209,7 @@ fn children(socket: &Path, agent_dir: &Path, script: &Path, depth: u32) -> Superthinking: None,child_script: Some(script.to_string_lossy().to_string()),});+ sessions.set_parent_session_name(Some("parent-name".to_string()));sessions}@@ -347,6 +348,45 @@ async fn rlm_children_spawn_roster_collect_delete_end_to_end() {assert_eq!(entry.label.as_deref(), Some("ship the lane"));assert!(entry.session_dir.ends_with(&handle.rlm_child_id));+ // The kickoff row (TS `spawnMessage`): the task prompt lands as the+ // parent-attributed `agent_message` custom row — never a user row —+ // carrying the promised `[task from parent]` label, the raw prompt as+ // `details.message`, `details.id "spawn:<child id>"`, and the+ // delivery's parent/child endpoints.+ let rows: Vec<Value> = std::fs::read_to_string(child_files[0].path())+ .expect("read child session file")+ .lines()+ .filter_map(|line| serde_json::from_str::<Value>(line).ok())+ .collect();+ let Some(kickoff) = rows+ .iter()+ .find(|row| row.get("type").and_then(Value::as_str) == Some("custom_message"))+ else {+ panic!("no custom_message row in the child file: {rows:?}");+ };+ assert_eq!(kickoff["customType"], "agent_message");+ assert_eq!(kickoff["content"], "[task from parent]\n\nship the lane");+ assert_eq!(+ kickoff["details"],+ json!({+ "id": format!("spawn:{}", handle.rlm_child_id),+ "message": "ship the lane",+ "from": {+ "activeSessionId": "parent-active-id",+ "sessionId": "parent-session-uuid",+ "sessionName": "parent-name",+ },+ "fromRelationship": "parent",+ }),+ );+ // The kickoff is the child's only prompt: no user row exists.+ assert!(+ rows.iter()+ .filter(|row| row.get("type").and_then(Value::as_str) == Some("message"))+ .all(|row| row.pointer("/message/role").and_then(Value::as_str) != Some("user")),+ "the kickoff left a user row: {rows:?}"+ );+// Collect: settled snapshot of the child, and the selector errors.let results = children.collect(vec![handle.rlm_child_id.clone()], 5_000)diff --git a/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs b/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rsindex 92a4184406..58dd98ff16 100644--- a/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs+++ b/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs@@ -358,7 +358,18 @@ async fn concurrent_spawns_prompt_exactly_once_across_a_worker_replacement() {let deadline = Instant::now() + Duration::from_secs(150);let content = loop {let content = std::fs::read_to_string(&session_file).unwrap_or_default();- if content.matches(&marker).count() == 1 {+ let kickoff_rows = content+ .lines()+ .filter_map(|line| serde_json::from_str::<Value>(line).ok())+ .filter(|entry| {+ entry.get("type").and_then(Value::as_str) == Some("custom_message")+ && entry+ .get("content")+ .and_then(Value::as_str)+ .is_some_and(|text| text.contains(&marker))+ })+ .count();+ if kickoff_rows == 1 {break content;}if Instant::now() >= deadline {