Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

pa-daemon/pa-core: add rlm.rename for sessions and direct children (port of TS #2529) (#3344)

Sebastian Müller022c90b9f2d7
diff --git a/.changes/rlm-rename.md b/.changes/rlm-rename.md
new file mode 100644
index 0000000000..c7d7c948c5
--- /dev/null
+++ b/.changes/rlm-rename.md
@@ -0,0 +1,2 @@
+- Added the `rlm.rename(new_name, session_id=...)` kernel function: renames the calling session (no `session_id`) or a direct child selected by spawn handle, `list_subagents()` row, or session id — never by child name — reusing spawn-name validation and daemon-owned sibling uniqueness; the renamed session gets a `Session renamed `old` -> `new`` transcript notice (suffixed ` by parent` when a parent renamed it), and the kernel readiness check now requires a runtime with `rlm.rename`.
+- Agents view: the rename affordance (ctrl+r / `/name`) now also applies to subagent rows, which carry the same renameable session identity as top-level agent rows.
diff --git a/Cargo.lock b/Cargo.lock
index a86a1dbde4..5ec6ea6641 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1336,6 +1336,7 @@ dependencies = [
"pa-models",
"pa-telemetry",
"pa-types",
+ "proptest",
"serde",
"serde_json",
"sha2",
diff --git a/crates/pa-cli/src/daemon_command.rs b/crates/pa-cli/src/daemon_command.rs
index 4a60b7824a..9f7426c3f9 100644
--- a/crates/pa-cli/src/daemon_command.rs
+++ b/crates/pa-cli/src/daemon_command.rs
@@ -341,6 +341,7 @@ fn run_rename(client: &mut DaemonClient, args: &[String], json: bool) -> Result<
id: None,
active_session_id,
name: name.clone(),
+ renamed_by: None,
rest: serde_json::Map::new(),
})?;
let data = require_success(response)?.unwrap_or(Value::Null);
diff --git a/crates/pa-cli/tests/interactive_daemon_e2e.rs b/crates/pa-cli/tests/interactive_daemon_e2e.rs
index b9991d743c..727ce6ded9 100644
--- a/crates/pa-cli/tests/interactive_daemon_e2e.rs
+++ b/crates/pa-cli/tests/interactive_daemon_e2e.rs
@@ -5337,6 +5337,7 @@ async fn tui_idle_session_event_repaints_without_input() {
id: None,
active_session_id: session.clone(),
name: "renamed-while-attached".to_string(),
+ renamed_by: None,
rest: serde_json::Map::default(),
})
.await
diff --git a/crates/pa-core/src/kernel/bootstrap/mod.rs b/crates/pa-core/src/kernel/bootstrap/mod.rs
index 9df740ba33..898b1c0fdd 100644
--- a/crates/pa-core/src/kernel/bootstrap/mod.rs
+++ b/crates/pa-core/src/kernel/bootstrap/mod.rs
@@ -196,7 +196,7 @@ async fn ensure_kernel_python_uncached(
let mut missing = Vec::new();
if !has_prime_agent_runtime(&python_str) {
missing.push(
- "a current prime-agent-runtime with callable rlm.spawn, rlm.create_session, rlm.host_request, rlm.progress_note, and explicit harness CRUD methods".to_string(),
+ "a current prime-agent-runtime with callable rlm.spawn, rlm.create_session, rlm.host_request, rlm.progress_note, rlm.rename, and explicit harness CRUD methods".to_string(),
);
}
if missing.is_empty() {
diff --git a/crates/pa-core/src/kernel/bootstrap/venv/probe.rs b/crates/pa-core/src/kernel/bootstrap/venv/probe.rs
index 8809b3e9dc..9a31e0fd50 100644
--- a/crates/pa-core/src/kernel/bootstrap/venv/probe.rs
+++ b/crates/pa-core/src/kernel/bootstrap/venv/probe.rs
@@ -27,7 +27,7 @@ fn run_quiet(command: &str, args: &[&str]) -> bool {
/// The runtime-ready assertion from the TS product: a current
/// prime-agent-runtime with the callable RLM surface, harness CRUD, bash
/// handles, and protocol version 3.
-const RUNTIME_READY_CHECK: &str = "import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ['create_memory', 'update_memory', 'delete_memory', 'create_skill', 'update_skill', 'delete_skill', 'create_subagent', 'update_subagent', 'delete_subagent', 'create_prompt_note', 'update_prompt_note', 'delete_prompt_note', 'record_refinement']; _mcp_discovery_methods = ['list_plugins', 'search_plugins', 'list_connections', 'search_tools', 'describe_tool']; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert all(callable(getattr(mcp, _m, None)) for _m in _mcp_discovery_methods), \"rlm.mcp is missing MCP discovery methods (list_plugins, search_plugins, list_connections, search_tools, describe_tool); the kernel venv needs a current prime-agent-runtime\"; assert callable(rlm.spawn); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm.spawn); assert inspect.signature(rlm.spawn).parameters['name'].default is inspect.Parameter.empty; assert not hasattr(rlm, 'run'); assert not hasattr(rlm.rlm, 'run'); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert callable(rlm.create_session); assert callable(rlm.rlm.create_session); assert callable(rlm.progress_note); assert callable(rlm.rlm.progress_note); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background'); from rlm.bash import BashHandle, BashResult; assert callable(rlm.bash); assert all(callable(getattr(BashHandle, _m, None)) for _m in ('tail', 'output', 'poll', 'kill')); assert {'exit_code', 'output', 'duration'} <= set(BashResult.__dataclass_fields__); import rlm.repl as _repl; assert callable(_repl.main); assert callable(_repl.emit); assert callable(_repl.host_request); assert callable(_repl.is_active); assert _repl.PROTOCOL_VERSION == 3; assert callable(rlm.emit); assert not hasattr(rlm, 'HOST_COMM_TARGET'); assert not hasattr(mcp, 'install_shutdown_hook')";
+const RUNTIME_READY_CHECK: &str = "import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ['create_memory', 'update_memory', 'delete_memory', 'create_skill', 'update_skill', 'delete_skill', 'create_subagent', 'update_subagent', 'delete_subagent', 'create_prompt_note', 'update_prompt_note', 'delete_prompt_note', 'record_refinement']; _mcp_discovery_methods = ['list_plugins', 'search_plugins', 'list_connections', 'search_tools', 'describe_tool']; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert all(callable(getattr(mcp, _m, None)) for _m in _mcp_discovery_methods), \"rlm.mcp is missing MCP discovery methods (list_plugins, search_plugins, list_connections, search_tools, describe_tool); the kernel venv needs a current prime-agent-runtime\"; assert callable(rlm.spawn); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm.spawn); assert inspect.signature(rlm.spawn).parameters['name'].default is inspect.Parameter.empty; assert not hasattr(rlm, 'run'); assert not hasattr(rlm.rlm, 'run'); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert callable(rlm.create_session); assert callable(rlm.rlm.create_session); assert callable(rlm.progress_note); assert callable(rlm.rlm.progress_note); assert callable(rlm.rename); assert callable(rlm.rlm.rename); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background'); from rlm.bash import BashHandle, BashResult; assert callable(rlm.bash); assert all(callable(getattr(BashHandle, _m, None)) for _m in ('tail', 'output', 'poll', 'kill')); assert {'exit_code', 'output', 'duration'} <= set(BashResult.__dataclass_fields__); import rlm.repl as _repl; assert callable(_repl.main); assert callable(_repl.emit); assert callable(_repl.host_request); assert callable(_repl.is_active); assert _repl.PROTOCOL_VERSION == 3; assert callable(rlm.emit); assert not hasattr(rlm, 'HOST_COMM_TARGET'); assert not hasattr(mcp, 'install_shutdown_hook')";
pub(crate) fn has_prime_agent_runtime(python: &str) -> bool {
run_quiet(python, &["-c", RUNTIME_READY_CHECK])
diff --git a/crates/pa-core/src/prompts/layers/core.md b/crates/pa-core/src/prompts/layers/core.md
index 8f3629f864..89069808be 100644
--- a/crates/pa-core/src/prompts/layers/core.md
+++ b/crates/pa-core/src/prompts/layers/core.md
@@ -35,6 +35,7 @@ The following programmatic tools are available in the REPL for subagent manageme
- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`
- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handles
- `rlm.delete_subagent(target: str | RLMSubagent) -> RLMSubagent`
+- `rlm.rename(new_name: str, *, session_id=None) -> str`: rename the calling session (omit `session_id`) or a direct child (spawn handle, `list_subagents()` row, or session id; never the child's name); names must be unique among siblings, and the renamed session sees a transcript line for the change
- `rlm.collect(targets=None, *, timeout_ms: int = 0) -> list[RLMChildResult]`: typed snapshots of direct children (status, settled flag, answer preview, error) without steering anyone; `timeout_ms=0` returns a non-blocking snapshot; a positive timeout blocks only this call until the children settle or the deadline passes
- `rlm.progress_note(message: str) -> dict`: report brief in-flight progress to the parent orchestrator (at most 512 characters, throttled to about one note per 10 seconds); the parent sees notes without needing a reply
- `RLMSpawnHandle`
diff --git a/crates/pa-core/src/session_engine/messages.rs b/crates/pa-core/src/session_engine/messages.rs
index bf2e92484c..a17cae5f3b 100644
--- a/crates/pa-core/src/session_engine/messages.rs
+++ b/crates/pa-core/src/session_engine/messages.rs
@@ -35,6 +35,10 @@ pub const HEARTBEAT_PROMPT_CUSTOM_TYPE: &str = "heartbeat_prompt";
/// TS `ASYNC_BASH_COMPLETION_CUSTOM_TYPE`: the durable row a detached
/// kernel bash completion admits as the woken turn's injected prompt.
pub const ASYNC_BASH_COMPLETION_CUSTOM_TYPE: &str = "async_bash_completion";
+/// TS `SESSION_RENAMED_CUSTOM_TYPE` (#2529): the displayed notice a
+/// rename that changed an existing name leaves in the renamed session's
+/// transcript.
+pub const SESSION_RENAMED_CUSTOM_TYPE: &str = "session_renamed";
/// TS `ASYNC_BASH_COMPLETION_PREVIEW_LABEL`: the queue-strip label the
/// notice's queued row carries (the TUI renders it with its own label,
/// no lane prefix).
diff --git a/crates/pa-core/src/session_engine/rlm_host.rs b/crates/pa-core/src/session_engine/rlm_host.rs
index 968b13655c..b4242800f1 100644
--- a/crates/pa-core/src/session_engine/rlm_host.rs
+++ b/crates/pa-core/src/session_engine/rlm_host.rs
@@ -1,7 +1,8 @@
//! The `rlm.*` kernel host-request bridge: wire validation, the child-session
//! host seam, and handler registration for `rlm.spawn` (`rlm.run`),
//! `rlm.create_session`, `rlm.find_models`, `rlm.list_subagents`,
-//! `rlm.collect`, `rlm.progress.note`, and `rlm.delete_subagent`.
+//! `rlm.collect`, `rlm.progress.note`, `rlm.delete_subagent`, and
+//! `rlm.rename`.
//!
//! Wire contract: the Python side (`rlm/__init__.py`) sends typed requests and
//! parses strict `snake_case` replies. Pure normalization lives in
@@ -177,11 +178,27 @@ pub trait RlmSubagentHost: Send + Sync {
fn delete_subagent(&self, target: String) -> RlmHostFuture<RlmDeleteSubagentResult>;
/// Typed fan-in of child results; a timeout returns snapshots, never errors.
fn collect(&self, targets: Vec<String>, timeout_ms: u64) -> RlmHostFuture<Vec<RlmChildResult>>;
+ /// Rename the current session (`session_id` absent) or one direct
+ /// child (TS `rlm.rename`); answers the applied name.
+ fn rename(&self, name: String, session_id: Option<String>) -> RlmHostFuture<String>;
}
/// Host behavior for sessions with no child runtime: truthful empties and the
/// TS selector errors, so the kernel surface never silently invents children.
-pub struct NoRlmChildren;
+/// A self-rename still lands locally (TS `setSessionName`): the session's own
+/// `session_info` name row.
+pub struct NoRlmChildren {
+ /// The session whose name a self-rename appends.
+ session: Arc<tokio::sync::Mutex<crate::session::manager::SessionManager>>,
+}
+
+impl NoRlmChildren {
+ /// The no-children host over one session's persistence.
+ #[must_use]
+ pub fn new(session: Arc<tokio::sync::Mutex<crate::session::manager::SessionManager>>) -> Self {
+ Self { session }
+ }
+}
impl RlmSubagentHost for NoRlmChildren {
fn spawn(&self, _request: RlmSpawnRequest) -> RlmHostFuture<RlmSpawnHandle> {
@@ -216,6 +233,21 @@ impl RlmSubagentHost for NoRlmChildren {
) -> RlmHostFuture<Vec<RlmChildResult>> {
Box::pin(async move { no_children_collect(&targets) })
}
+ fn rename(&self, name: String, session_id: Option<String>) -> RlmHostFuture<String> {
+ // The alias boxes a `'static` future, so the session handle moves
+ // in by value — nothing here borrows `self`.
+ let session = Arc::clone(&self.session);
+ Box::pin(async move {
+ if session_id.is_some() {
+ anyhow::bail!("rlm.rename with session_id requires a daemon-backed session");
+ }
+ let mut session = session.lock().await;
+ session
+ .append_session_info(&name)
+ .map_err(anyhow::Error::from)?;
+ Ok(name)
+ })
+ }
}
/// `collect` against an empty roster: every target is a miss.
@@ -315,16 +347,18 @@ pub struct RlmHostBridge {
}
impl RlmHostBridge {
- /// Build the bridge: an explicit host, or the no-children behavior.
+ /// Build the bridge over one child-session host: the daemon supplies
+ /// [`SupervisorChildSessions`]; session embeddings without one pass
+ /// [`NoRlmChildren`] (built against the session's own persistence).
pub fn new(
registry: Arc<ModelRegistry>,
- host: Option<Arc<dyn RlmSubagentHost>>,
+ host: Arc<dyn RlmSubagentHost>,
usage: Arc<super::rlm_usage::RlmChildUsageAttributions>,
) -> Self {
Self {
registry,
notes: Arc::new(RlmProgressNotes::default()),
- host: host.unwrap_or_else(|| Arc::new(NoRlmChildren)),
+ host,
usage,
semantic_spawn: std::sync::OnceLock::new(),
}
@@ -340,6 +374,7 @@ pub fn register_rlm_host_handlers(handlers: &mut HostRequestHandlers, bridge: &A
register_list_subagents(handlers, bridge);
register_delete_subagent(handlers, bridge);
register_collect(handlers, bridge);
+ register_rename(handlers, bridge);
}
fn register_find_models(handlers: &mut HostRequestHandlers, bridge: &Arc<RlmHostBridge>) {
@@ -629,6 +664,45 @@ fn register_collect(handlers: &mut HostRequestHandlers, bridge: &Arc<RlmHostBrid
);
}
+fn register_rename(handlers: &mut HostRequestHandlers, bridge: &Arc<RlmHostBridge>) {
+ let host = Arc::clone(&bridge.host);
+ handlers.register(
+ "rlm.rename",
+ host_handler(move |payload| {
+ let host = Arc::clone(&host);
+ Box::pin(async move {
+ const OPERATION: &str = "rlm.rename";
+ let data = &payload.data;
+ // The name follows the spawn rules exactly (TS
+ // `createRlmRenameHostHandler` reuses the spawn
+ // normalizer); absent or non-string names read as the
+ // TS "must be a string" error.
+ let Some(name) = normalize_requested_rlm_subagent_session_name(
+ data.get("name").and_then(Value::as_str),
+ OPERATION,
+ )?
+ else {
+ anyhow::bail!("rlm.rename name must be a string");
+ };
+ assert_direct_agent_message_target(&name)?;
+ let session_id = match data.get("session_id") {
+ None | Some(Value::Null) => None,
+ Some(Value::String(raw)) => {
+ let trimmed = raw.trim();
+ if trimmed.is_empty() {
+ anyhow::bail!("rlm.rename session_id must be a non-empty string");
+ }
+ Some(trimmed.to_string())
+ }
+ Some(_) => anyhow::bail!("rlm.rename session_id must be a non-empty string"),
+ };
+ let name = host.rename(name, session_id).await?;
+ Ok(json!({ "name": name }))
+ })
+ }),
+ );
+}
+
/// Present-but-non-string kwargs fail like the TS normalizers do.
fn optional_string_kwarg<'a>(
kwargs: &'a Map<String, Value>,
@@ -669,12 +743,15 @@ mod tests {
/// A host recording every call, answering with fixed handles.
/// One recorded collect call: its targets and timeout.
type CollectCall = (Vec<String>, u64);
+ /// One recorded rename: the normalized name and the optional child id.
+ type RecordedRename = (String, Option<String>);
struct RecordingHost {
spawn_requests: Arc<Mutex<Vec<RlmSpawnRequest>>>,
create_requests: Arc<Mutex<Vec<RlmCreateSessionRequest>>>,
targets: Arc<Mutex<Vec<String>>>,
collects: Arc<Mutex<Vec<CollectCall>>>,
+ renames: Arc<Mutex<Vec<RecordedRename>>>,
}
impl RecordingHost {
@@ -684,6 +761,7 @@ mod tests {
create_requests: Arc::new(Mutex::new(Vec::new())),
targets: Arc::new(Mutex::new(Vec::new())),
collects: Arc::new(Mutex::new(Vec::new())),
+ renames: Arc::new(Mutex::new(Vec::new())),
})
}
}
@@ -789,6 +867,13 @@ mod tests {
}])
})
}
+ fn rename(&self, name: String, session_id: Option<String>) -> RlmHostFuture<String> {
+ let renames = Arc::clone(&self.renames);
+ Box::pin(async move {
+ renames.lock().await.push((name.clone(), session_id));
+ Ok(name)
+ })
+ }
}
fn persisted_session(dir: &std::path::Path) -> SessionManager {
@@ -1273,6 +1358,108 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn rename_round_trip_and_validation() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let host = RecordingHost::new();
+ let renames = Arc::clone(&host.renames);
+ let wiring = wired(dir.path(), Some(host));
+
+ // A child rename forwards the normalized name and the trimmed
+ // session id (the Python side already resolved handles to child
+ // ids).
+ let reply = call(
+ &wiring,
+ "rlm.rename",
+ json!({ "name": " bench-runner ", "session_id": " sub-1 " }),
+ )
+ .await
+ .unwrap();
+ assert_eq!(reply, json!({ "name": "bench-runner" }));
+ assert_eq!(
+ *renames.lock().await,
+ vec![("bench-runner".to_string(), Some("sub-1".to_string()))]
+ );
+
+ // A self rename carries no session id.
+ call(&wiring, "rlm.rename", json!({ "name": "solo" }))
+ .await
+ .unwrap();
+ assert_eq!(
+ renames.lock().await.last(),
+ Some(&("solo".to_string(), None))
+ );
+
+ // Validation: the shared spawn normalizer (the length rule) plus
+ // the rename-local broadcast guard, then the session id shape.
+ let error = call(&wiring, "rlm.rename", json!({})).await.unwrap_err();
+ assert_eq!(error.to_string(), "rlm.rename name must be a string");
+ let error = call(&wiring, "rlm.rename", json!({ "name": "x".repeat(65) }))
+ .await
+ .unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "rlm.rename name must be at most 64 characters"
+ );
+ let error = call(&wiring, "rlm.rename", json!({ "name": "all" }))
+ .await
+ .unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "Broadcast agent messaging is not supported"
+ );
+ let error = call(
+ &wiring,
+ "rlm.rename",
+ json!({ "name": "x", "session_id": " " }),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "rlm.rename session_id must be a non-empty string"
+ );
+ let error = call(
+ &wiring,
+ "rlm.rename",
+ json!({ "name": "x", "session_id": 7 }),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "rlm.rename session_id must be a non-empty string"
+ );
+ }
+
+ #[tokio::test]
+ async fn no_host_rename_appends_locally_and_rejects_child_targets() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let wiring = wired(dir.path(), None);
+ // A self rename appends the session's `session_info` name row
+ // (TS `setSessionName`).
+ let renamed = call(&wiring, "rlm.rename", json!({ "name": "solo-lane" }))
+ .await
+ .unwrap();
+ assert_eq!(renamed, json!({ "name": "solo-lane" }));
+ assert_eq!(
+ wiring.session.lock().await.get_session_name(),
+ Some("solo-lane".to_string())
+ );
+ // A child target requires the daemon-backed host.
+ let error = call(
+ &wiring,
+ "rlm.rename",
+ json!({ "name": "x", "session_id": "sub-1" }),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "rlm.rename with session_id requires a daemon-backed session"
+ );
+ }
+
#[tokio::test]
async fn no_host_session_reports_empty_roster_and_selector_misses() {
let dir = tempfile::TempDir::new().unwrap();
diff --git a/crates/pa-core/src/session_engine/runtime_wiring.rs b/crates/pa-core/src/session_engine/runtime_wiring.rs
index 3cb6319ddb..8eaca9b1a2 100644
--- a/crates/pa-core/src/session_engine/runtime_wiring.rs
+++ b/crates/pa-core/src/session_engine/runtime_wiring.rs
@@ -182,9 +182,15 @@ pub fn wire_session_runtime(
let rlm_usage = Arc::new(super::rlm_usage::RlmChildUsageAttributions::new(
session.clone(),
));
+ // The daemon supplies the child-session host; an embedding without
+ // one keeps the no-children behavior, whose self-rename appends the
+ // session's own `session_info` name row.
+ let subagent_host = rlm
+ .subagent_host
+ .unwrap_or_else(|| Arc::new(super::rlm_host::NoRlmChildren::new(session.clone())));
let rlm_bridge = Arc::new(RlmHostBridge::new(
model_registry,
- rlm.subagent_host,
+ subagent_host,
rlm_usage.clone(),
));
register_rlm_host_handlers(&mut handlers, &rlm_bridge);
diff --git a/crates/pa-core/tests/golden/corpus/system-prompt.json b/crates/pa-core/tests/golden/corpus/system-prompt.json
index 8735af7adb..04ef629974 100644
--- a/crates/pa-core/tests/golden/corpus/system-prompt.json
+++ b/crates/pa-core/tests/golden/corpus/system-prompt.json
@@ -8,5 +8,5 @@
"skillsSource": "bundled skills directory (<skills-dir>)"
},
"skill_count": 12,
- "systemPrompt": "# prime-agent harness\n\nThe prime-agent harness has one tool: `ipython`, a persistent CPython REPL. All other tools are \"programmatic tools\", functions inside the Python REPL called via \"programmatic tool calling\" (PTC). All programmatic tools are async unless described otherwise and can be run in the background. `await` works directly and globally in the REPL.\n\nThe harness often sends messages to the agent. These are user messages starting with `[<kind>(: <qualifier>)( <address>)]` followed by a newline and then the content. They are not user-generated.\n\n## Core tools\n\n- `bash(command: str) -> BashHandle`: synchronous, returns immediately and runs the command in the background; when a command is finished outside the calling `ipython` block, a notification is sent to the agent; each `bash()` call is its own process, so shell state does not persist between calls\n - `BashHandle`:\n - `.pid: int`\n - `.running: bool`\n - `.command: str`\n - `.tail(n: int = 50) -> str`\n - `.output() -> str`\n - `.poll() -> BashResult | None`\n - `.kill(sig: int = SIGTERM, grace: float = 5.0) -> None`: SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive\n - `await handle -> BashResult`: the handle is awaitable even after command completion, so agents can run commands non-blocking and await them after being notified of them finishing\n - `BashResult`\n - `.exit_code: int`\n - `.output: str`\n - `.duration: float`\n- `edit.run(path: str, old_str: str, new_str: str) -> str`: the primary method for editing files. async, exact-unique-match; the `edit` module is callable with the same arguments (`await edit(path=..., old_str=..., new_str=...)`)\n- `websearch.run(query: str, *, max_output: int = 8192, timeout: int | None, num_results: int | None) -> str`: search the web; the `websearch` module is callable with the same arguments\n- `attach_image(*paths: str) -> str`: loads images directly into context if the agent's model is vision-capable, errors otherwise\n\n## Subagents\n\nprime-agent is a recursive harness. Each session builds a tree of agents, starting at depth 0. Each agent up to a user-configured limit can launch subagents. These subagents are persistent, just like the root session. Each agent can communicate with its nuclear family: its singular parent (except for depth 0 sessions which have no parent), its siblings (other subagents under the same parent), and its children (its own subagents).\n\nThe following programmatic tools are available in the REPL for subagent management:\n\n- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None) -> RLMSpawnHandle`: spawns a new subagent one level deeper than the caller; returns immediately; errors when the caller cannot create subagents; if not given, `model` and `thinking` are inherited from the parent; results never arrive as `rlm.spawn()` return values, they arrive only via agent_message; `name` must be unique among the spawned agent's siblings, and be meaningful and descriptive but short\n- `rlm.create_session(prompt: str, name: str | None = None, model: str | None = None, thinking: str | None = None, cwd: str | None = None) -> RLMCreateSessionHandle`: creates another depth-0 session; only available to agents at depth 0 backed by a daemon; returns after the session is successfully created and the first prompt sent\n- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`\n- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handles\n- `rlm.delete_subagent(target: str | RLMSubagent) -> RLMSubagent`\n- `rlm.collect(targets=None, *, timeout_ms: int = 0) -> list[RLMChildResult]`: typed snapshots of direct children (status, settled flag, answer preview, error) without steering anyone; `timeout_ms=0` returns a non-blocking snapshot; a positive timeout blocks only this call until the children settle or the deadline passes\n- `rlm.progress_note(message: str) -> dict`: report brief in-flight progress to the parent orchestrator (at most 512 characters, throttled to about one note per 10 seconds); the parent sees notes without needing a reply\n- `RLMSpawnHandle`\n - `rlm_child_id: str`\n - `name: str`\n - `session_dir: Path`\n - `model: str`: provider/model, full resolved model name\n- `RLMCreateSessionHandle`\n - `active_session_id: str`: live daemon-instance id\n - `session_id: str`: durable on-disk session identity\n - `name: str`\n - `session_file: Path`: path to persisted session log\n - `model: str`: provider/model, full resolved model name\n- `RLMSubagent`\n - `rlm_child_id: str`\n - `active_session_id: str | None`\n - `session_id: str | None`\n - `session_name: str`\n - `session_dir: Path`\n - `status: Literal[\"running\", \"completed\", \"error\"]`\n - rows also carry live activity detail (current activity, tool use count, duration, answer preview, latest progress note)\n- `RLMModel`\n - `provider: str`\n - `id: str`\n - `name: str`\n - `selector: str`: the exact string to spawn the model\n\nThe following programmatic tools are available in the REPL for a2a communication:\n\n- `agent_message.send(message: str, *, receiver_role: Literal[\"parent\", \"sibling\", \"child\"], receiver_name: str | None) -> dict`: send a message to the receiver; returns a receipt with the message id and a delivery status (delivered or queued); all root sessions are siblings; `send(\"all\", broadcast_message)` broadcasts to the family roster and returns `{receipts: [...]}`\n- `agent_observe.list_agents() -> dict`: list nuclear family\n- `agent_observe.get_agent(target: str) -> dict`: one agent's status detail\n- `agent_observe.recent_messages(target: str, limit: int = 8, max_chars: int = 800) -> dict`: transcript preview; `limit` errors outside [1-50], `max_chars` outside [80-2000]\n\n## Continual Harness\n\nprime-agent is a continual harness. During a session, persistent memories can be written and read. These stay available even after multiple compactions.\n\nMemories are created by two mechanisms:\n\n- Refinement\n - Mechanism:\n - Another model suggests a refinement based on the transcript\n - The suggested edits are applied to the harness state\n - The main agent is notified by a structured harness message and the applied edits are saved\n - Triggered by:\n - Calling the programmatic tool `refine.run()`\n - By the user command `/refine`\n - Effect:\n - The refinement event is always saved in the harness state's refinement history\n - A harness message is sent to the agent with the refinement result\n- Active memory management by the agent\n - `refine.run(instructions: str | None = None, global_: bool = False) -> dict`: agent-triggered refinement (see above); returns immediately and runs when the current turn ends\n- `refine.status() -> dict`: whether a refinement is already pending for this turn or currently in flight\n - `rlm.harness.create_memory(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: creates a memory; use `global_=True` for cross-session entries (Python reserves `global`, so the parameter is spelled `global_`)\n - `rlm.harness.update_memory(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_memory(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_prompt_note(title: str, content: str, *, id: str | None = None, path: str = \"policy\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_prompt_note(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_prompt_note(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_skill(title: str, content: str, *, id: str | None = None, path: str = \"general\", reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: `reference`/`arguments` describe the Python callable (`reference` requires `{\"type\": \"python\"}`, a Python import, and a callable or call pattern)\n - `rlm.harness.update_skill(id: str, title: str, content: str, *, path: str | None = None, reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_skill(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_subagent(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_subagent(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_subagent(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.record_refinement(trigger: str, changes: list[str], *, evidence: str = \"\", outcome: str = \"\", id: str | None = None, global_: bool = False) -> RefinementEvent`\n - `rlm.harness.plan_refinement(observation: str, *, failing_component: str = \"\", next_step: str = \"\") -> list[str]`: a suggested diagnose -> update -> validate plan\n - `rlm.harness.overview(*, max_entries_per_kind: int = 20, global_: bool = False) -> str`: memory overview\n - `rlm.harness.search(query: str, kind: str | None = None, limit: int = 10, *, global_: bool = False) -> list[HarnessEntry]`: ranked term search over entries\n - `rlm.get_harness_state(state_dir: str | Path | None = None, *, global_: bool = False) -> HarnessState`: full memory details for the selected scope. Can read another agent's `HarnessState` by passing the path to it in `state_dir`\n - `HarnessEntry`\n - `id: str`\n - `kind: Literal[\"prompt\", \"memory\", \"skill\", \"subagent\"]`\n - `title: str`\n - `content: str`\n - `path: str`: category path (\"general\" for memories, \"policy\" for prompt notes)\n - `scope: Literal[\"local\", \"global\"]`\n - `reference: dict[str, Any]`: for skills\n - `arguments: dict[str, Any]`: for skills\n - `metadata: dict`\n - `source: Literal[\"agent\", \"refine\"]`\n - `created_at: str`: ISO timestamp of creation\n - `updated_at: str`: ISO timestamp of latest update\n - `version: int`: increments with every update, starting at 1\n - `HarnessState`\n - `scope: Literal[\"global\", \"local\"]`\n - `file_path: Path`\n - `entries: dict[kind, dict[id, HarnessEntry]]`\n - `refinements: list[RefinementEvent]`\n - `RefinementEvent`\n - `id: str`\n - `trigger: str`: what caused the refinement\n - `changes: list[str]`: applied edits; empty if never edited\n - `evidence: str`\n - `outcome: str`\n - `created_at: str`\n\n## Compaction\n\nprime-agent compacts automatically when there is only a given number of tokens left in the context window (default: 16384), when the user triggers compaction, or when the agent triggers compaction. REPL state persists across compactions, but compaction removes individual variables whose serialized form exceeds 16 MiB.\n\n- `compact.run(instructions: str | None = None) -> dict`: schedule a compaction at the next assistant turn boundary\n- `compact.status() -> dict`: context usage & threshold before auto-compaction\n\n## Goal\n\nIn goal mode prime-agent helps an agent stay on track until a task is fully finished, and handles interruptions and other issues. Goals can be user- or agent-created.\n\n- `goal.create(objective: str, token_budget: int | None = None) -> dict`: create goal and return goal state\n- `goal.get() -> dict`: get goal status (only one goal can be active at a time)\n- `goal.complete() -> dict`: mark goal as completed and get final goal status\n\n## Heartbeat\n\nIn prime-agent, agents can create heartbeats to wake themselves up after a given period of time with remembered instructions, recurrently on a given schedule.\n\n- `rlm_heartbeat.create(instruction: str, interval: str | None = None, label: str | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`: new recurring heartbeat for this session; `interval` is a schedule string (default: every 5 minutes); `delivery_mode`: steer (default) interrupts a busy session's current turn, follow_up waits for it to finish\n- `rlm_heartbeat.list(include_inactive: bool = False) -> dict`\n- `rlm_heartbeat.update(id: str, instruction: str | None = None, interval: str | None = None, label: str | None = None, status: Literal[\"pause\", \"resume\"] | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`\n- `rlm_heartbeat.delete(id: str) -> dict`\n\n## MCP\n\nprime-agent has support for programmatic tools that are defined in the MCP format. Their schema is discovered at runtime.\n\n- `mcp.list_tools(server: str) -> list[dict]`: returns tool schemas\n- `mcp.call_tool(server: str, tool: str, arguments: dict | None = None) -> Any`\n- `mcp.list_plugins(connection_status: str | None = None, limit: int = 50, cursor: str | None = None) -> dict`: one bounded page of the supported-service catalog\n- `mcp.search_plugins(query: str, limit: int = 10) -> dict`: bounded catalog search\n- `mcp.list_connections() -> list[dict]`: the user's current connections (the dispatch ids)\n- `mcp.search_tools(query: str, connection_id: str | None = None, limit: int = 20) -> dict`: search live tool names/descriptions and report the search scope\n- `mcp.describe_tool(connection_id: str, tool: str) -> dict`: one live tool's name, description, and inputSchema\n\n## Skills\n\nprime-agent provides multiple executable skills, described by their SKILL.md and executable code. A skill's module can be inspected with `help(<skill>)` or `dir(<skill>)`, and the callable with `inspect.signature(<skill>.<function>)`, if information is missing. The executable code is always pre-imported in the REPL as a programmatic tool, and a callable skill module can be called directly (`await <skill>(...)`).\n\nAll programmatic tools described above except for `bash`, `rlm.*`, and `mcp.*` are implemented as executable skills and will be listed again in the dynamic tail of this prompt. Additional executable and non-executable skills may exist as well; non-executable (markdown) skills are documentation read from disk, and each skill is also available as a shell command by the same name.\n\nThe following are mandatory rules, only to be overridden by clear user intent.\n\n- Memories must be kept lean and up-to-date.\n- `goal.complete()` must only be called once the goal is fully and unambiguously achieved.\n- Goals must only be created at a user's request.\n- Agents run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n- `bash(\"\"\"...\"\"\")` should be used over `bash(\"...\")` because it makes using quotation marks inside bash easy.\n- Bash commands must be run in the background; if they are quick, or the agent is doing other heavy work in the same `ipython` call, they should be awaited or polled in the same `ipython` call interleaved with other work, or a subsequent one; otherwise, the agent should wait for the notification; blocking calls reduce user responsiveness.\n- Shell state does not persist between calls, but agents can use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables — both persist in the REPL and apply to later `bash()` calls through POSIX process inheritance (since each bash call is a fresh process, Python does not inherit environment variables from bash).\n- Edits of existing files must be performed using `edit` with exact old/new strings; if the text contains triple double quotes (\"\"\"), the agent should use triple single-quoted variables or build `old`/`new` from inspected file slices.\n- Agents use Python for reading files and searching in them — it gives them reusable variables they can slice, filter, and act on without re-reading; using Python variables to find or produce, and to save the strings used in `edit` is also encouraged.\n- Agents always assign read/search results to named variables so they can revisit them later.\n- Agents must report assumptions they made and constants they changed to the user.\n- When an agent is done, they stop calling tools and state their final answer.\n- When delegation is available and useful, an agent assigns independent substantive tasks to separate workers. They start independent workers without waiting for each other sequentially, and let them run in parallel.\n- Agents do not keep the turn open by polling with `time.sleep()` or shell `sleep`, and they do not replace polling with a long blocking `await`. They await only the short operation needed to start work or inspect a result that is already available; otherwise they end the turn.\n- Agents use the Python REPL to keep intermediate variables, inspect and transform outputs, and write small helper functions.\n- Since compaction removes individual variables whose serialized form exceeds 16 MiB, agents can keep large source data on disk and reload it when needed.\n- Python is the orchestration language: agents use Python for loops, conditionals, parsing, and state. They use `bash()` to invoke programs, not to write shell programs, shell loops, or heredocs; those are done directly in Python.\n- Agents do not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Agents evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n- Agents do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, they run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Agents treat failures from that native environment as the relevant result.\n- Rules for root agents (depth 0):\n - Only message siblings if you are certain that it is necessary.\n - When work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n- Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n- Agents treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: they diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. They use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so agents continue working normally after calling it. Agents do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n- Instructions to agents for multi-agent work:\n - When spawning a subagent, keep the handle to stop or inspect the child later.\n - Ask for an explicit reply when needed; not every message needs a reply.\n - Use `await rlm.list_subagents()` after kernel restart or compaction.\n - Have children write files and read those files for fan-in.\n - Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\n\nThe following guidelines to agents have been shown to improve results on average. Agents should consider using them where appropriate. Clear user instructions always override these defaults.\n\n- Agents can use the following patterns to make better use of the REPL:\n - Write wrappers around `rlm.spawn` to have quick templates for subagents with arbitrary args: for text to programmatically pass and put into the prompt, for conditional behavior prompts, etc.\n - Use f-strings (`f\"\"\"...\"\"\"` or `f\"...\"`) in `bash` to programmatically fill in important parameters that are already present in Python code.\n- When writing or explaining something:\n - Agents use simplified technical English by default for user-facing prose: short sentences, common words, and concrete verbs; one main action or fact per sentence when practical; lists for steps or conditions. Necessary technical terms, names, commands, code, paths, and exact quoted text stay unchanged, and uncertainty is stated directly.\n - Agents use ordinary or established wording. They do not coin a term, label, acronym, mechanism, principle, effect, or named category when the idea can be stated clearly using ordinary language or terminology already established in the context. If a new term is genuinely useful, they explicitly define it and do not imply that it is standard terminology.\n - Agents keep names and terms consistent. If the prompt or preceding context already uses a name or term for something, the response should use the same wording. Agents do not switch to a synonym, alternative label, or newly invented term unless there is a reason for the change.\n- Agents take care and effort to avoid the following pitfalls while coding:\n - over-engineered solutions\n - overly defensive programming\n - hyper-fixation on rare/fictitious edge cases\n - overlapping subsystem responsibilities\n - solving problems at the wrong architectural layer\n - duplication of sources of truth, then inventing machinery to synchronize them\n - prematurely generalizing one-off flows\n - timeouts on everything\n - production code that exists purely to satisfy tests\n - patching bad premises additively instead of stepping back and deleting or adjusting them\n - tests for magic strings\n - excessive tests\n - comments that describe anything already described by the code\n - comments narrating the coding process instead of supporting the written code\n - fallbacks, legacy support, compatibility shims where not strictly needed; when in doubt, these should be discussed with the user\n - in UI, descriptions on everything\n\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent&apos;s parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location><skills-dir>/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent&apos;s parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location><skills-dir>/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model&apos;s context as a viewable attachment so the model can directly SEE it — for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image&apos;s visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location><skills-dir>/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location><skills-dir>/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location><skills-dir>/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location><skills-dir>/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>mcp</name>\n <type>markdown</type>\n <description>Use external MCP services generically from Python - search the supported-service catalog, inspect the user&apos;s connections, discover live tool schemas, and call tools on any connection (Notion, Linear, Slack, and the rest of the catalog) without per-service packages.</description>\n <location><skills-dir>/mcp/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location><skills-dir>/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location><skills-dir>/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user&apos;s /heartbeat.</description>\n <location><skills-dir>/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location><skills-dir>/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /mcp, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location><skills-dir>/websearch/SKILL.md</location>\n </skill>\n</available_skills>\n\nCurrent date: <date>\nWorking directory: /w\nConversation log: /w/sessions/fixture-session.jsonl\n\nRecursive agent depth: 0 (root)"
+ "systemPrompt": "# prime-agent harness\n\nThe prime-agent harness has one tool: `ipython`, a persistent CPython REPL. All other tools are \"programmatic tools\", functions inside the Python REPL called via \"programmatic tool calling\" (PTC). All programmatic tools are async unless described otherwise and can be run in the background. `await` works directly and globally in the REPL.\n\nThe harness often sends messages to the agent. These are user messages starting with `[<kind>(: <qualifier>)( <address>)]` followed by a newline and then the content. They are not user-generated.\n\n## Core tools\n\n- `bash(command: str) -> BashHandle`: synchronous, returns immediately and runs the command in the background; when a command is finished outside the calling `ipython` block, a notification is sent to the agent; each `bash()` call is its own process, so shell state does not persist between calls\n - `BashHandle`:\n - `.pid: int`\n - `.running: bool`\n - `.command: str`\n - `.tail(n: int = 50) -> str`\n - `.output() -> str`\n - `.poll() -> BashResult | None`\n - `.kill(sig: int = SIGTERM, grace: float = 5.0) -> None`: SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive\n - `await handle -> BashResult`: the handle is awaitable even after command completion, so agents can run commands non-blocking and await them after being notified of them finishing\n - `BashResult`\n - `.exit_code: int`\n - `.output: str`\n - `.duration: float`\n- `edit.run(path: str, old_str: str, new_str: str) -> str`: the primary method for editing files. async, exact-unique-match; the `edit` module is callable with the same arguments (`await edit(path=..., old_str=..., new_str=...)`)\n- `websearch.run(query: str, *, max_output: int = 8192, timeout: int | None, num_results: int | None) -> str`: search the web; the `websearch` module is callable with the same arguments\n- `attach_image(*paths: str) -> str`: loads images directly into context if the agent's model is vision-capable, errors otherwise\n\n## Subagents\n\nprime-agent is a recursive harness. Each session builds a tree of agents, starting at depth 0. Each agent up to a user-configured limit can launch subagents. These subagents are persistent, just like the root session. Each agent can communicate with its nuclear family: its singular parent (except for depth 0 sessions which have no parent), its siblings (other subagents under the same parent), and its children (its own subagents).\n\nThe following programmatic tools are available in the REPL for subagent management:\n\n- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None) -> RLMSpawnHandle`: spawns a new subagent one level deeper than the caller; returns immediately; errors when the caller cannot create subagents; if not given, `model` and `thinking` are inherited from the parent; results never arrive as `rlm.spawn()` return values, they arrive only via agent_message; `name` must be unique among the spawned agent's siblings, and be meaningful and descriptive but short\n- `rlm.create_session(prompt: str, name: str | None = None, model: str | None = None, thinking: str | None = None, cwd: str | None = None) -> RLMCreateSessionHandle`: creates another depth-0 session; only available to agents at depth 0 backed by a daemon; returns after the session is successfully created and the first prompt sent\n- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`\n- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handles\n- `rlm.delete_subagent(target: str | RLMSubagent) -> RLMSubagent`\n- `rlm.rename(new_name: str, *, session_id=None) -> str`: rename the calling session (omit `session_id`) or a direct child (spawn handle, `list_subagents()` row, or session id; never the child's name); names must be unique among siblings, and the renamed session sees a transcript line for the change\n- `rlm.collect(targets=None, *, timeout_ms: int = 0) -> list[RLMChildResult]`: typed snapshots of direct children (status, settled flag, answer preview, error) without steering anyone; `timeout_ms=0` returns a non-blocking snapshot; a positive timeout blocks only this call until the children settle or the deadline passes\n- `rlm.progress_note(message: str) -> dict`: report brief in-flight progress to the parent orchestrator (at most 512 characters, throttled to about one note per 10 seconds); the parent sees notes without needing a reply\n- `RLMSpawnHandle`\n - `rlm_child_id: str`\n - `name: str`\n - `session_dir: Path`\n - `model: str`: provider/model, full resolved model name\n- `RLMCreateSessionHandle`\n - `active_session_id: str`: live daemon-instance id\n - `session_id: str`: durable on-disk session identity\n - `name: str`\n - `session_file: Path`: path to persisted session log\n - `model: str`: provider/model, full resolved model name\n- `RLMSubagent`\n - `rlm_child_id: str`\n - `active_session_id: str | None`\n - `session_id: str | None`\n - `session_name: str`\n - `session_dir: Path`\n - `status: Literal[\"running\", \"completed\", \"error\"]`\n - rows also carry live activity detail (current activity, tool use count, duration, answer preview, latest progress note)\n- `RLMModel`\n - `provider: str`\n - `id: str`\n - `name: str`\n - `selector: str`: the exact string to spawn the model\n\nThe following programmatic tools are available in the REPL for a2a communication:\n\n- `agent_message.send(message: str, *, receiver_role: Literal[\"parent\", \"sibling\", \"child\"], receiver_name: str | None) -> dict`: send a message to the receiver; returns a receipt with the message id and a delivery status (delivered or queued); all root sessions are siblings; `send(\"all\", broadcast_message)` broadcasts to the family roster and returns `{receipts: [...]}`\n- `agent_observe.list_agents() -> dict`: list nuclear family\n- `agent_observe.get_agent(target: str) -> dict`: one agent's status detail\n- `agent_observe.recent_messages(target: str, limit: int = 8, max_chars: int = 800) -> dict`: transcript preview; `limit` errors outside [1-50], `max_chars` outside [80-2000]\n\n## Continual Harness\n\nprime-agent is a continual harness. During a session, persistent memories can be written and read. These stay available even after multiple compactions.\n\nMemories are created by two mechanisms:\n\n- Refinement\n - Mechanism:\n - Another model suggests a refinement based on the transcript\n - The suggested edits are applied to the harness state\n - The main agent is notified by a structured harness message and the applied edits are saved\n - Triggered by:\n - Calling the programmatic tool `refine.run()`\n - By the user command `/refine`\n - Effect:\n - The refinement event is always saved in the harness state's refinement history\n - A harness message is sent to the agent with the refinement result\n- Active memory management by the agent\n - `refine.run(instructions: str | None = None, global_: bool = False) -> dict`: agent-triggered refinement (see above); returns immediately and runs when the current turn ends\n- `refine.status() -> dict`: whether a refinement is already pending for this turn or currently in flight\n - `rlm.harness.create_memory(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: creates a memory; use `global_=True` for cross-session entries (Python reserves `global`, so the parameter is spelled `global_`)\n - `rlm.harness.update_memory(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_memory(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_prompt_note(title: str, content: str, *, id: str | None = None, path: str = \"policy\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_prompt_note(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_prompt_note(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_skill(title: str, content: str, *, id: str | None = None, path: str = \"general\", reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: `reference`/`arguments` describe the Python callable (`reference` requires `{\"type\": \"python\"}`, a Python import, and a callable or call pattern)\n - `rlm.harness.update_skill(id: str, title: str, content: str, *, path: str | None = None, reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_skill(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_subagent(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_subagent(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_subagent(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.record_refinement(trigger: str, changes: list[str], *, evidence: str = \"\", outcome: str = \"\", id: str | None = None, global_: bool = False) -> RefinementEvent`\n - `rlm.harness.plan_refinement(observation: str, *, failing_component: str = \"\", next_step: str = \"\") -> list[str]`: a suggested diagnose -> update -> validate plan\n - `rlm.harness.overview(*, max_entries_per_kind: int = 20, global_: bool = False) -> str`: memory overview\n - `rlm.harness.search(query: str, kind: str | None = None, limit: int = 10, *, global_: bool = False) -> list[HarnessEntry]`: ranked term search over entries\n - `rlm.get_harness_state(state_dir: str | Path | None = None, *, global_: bool = False) -> HarnessState`: full memory details for the selected scope. Can read another agent's `HarnessState` by passing the path to it in `state_dir`\n - `HarnessEntry`\n - `id: str`\n - `kind: Literal[\"prompt\", \"memory\", \"skill\", \"subagent\"]`\n - `title: str`\n - `content: str`\n - `path: str`: category path (\"general\" for memories, \"policy\" for prompt notes)\n - `scope: Literal[\"local\", \"global\"]`\n - `reference: dict[str, Any]`: for skills\n - `arguments: dict[str, Any]`: for skills\n - `metadata: dict`\n - `source: Literal[\"agent\", \"refine\"]`\n - `created_at: str`: ISO timestamp of creation\n - `updated_at: str`: ISO timestamp of latest update\n - `version: int`: increments with every update, starting at 1\n - `HarnessState`\n - `scope: Literal[\"global\", \"local\"]`\n - `file_path: Path`\n - `entries: dict[kind, dict[id, HarnessEntry]]`\n - `refinements: list[RefinementEvent]`\n - `RefinementEvent`\n - `id: str`\n - `trigger: str`: what caused the refinement\n - `changes: list[str]`: applied edits; empty if never edited\n - `evidence: str`\n - `outcome: str`\n - `created_at: str`\n\n## Compaction\n\nprime-agent compacts automatically when there is only a given number of tokens left in the context window (default: 16384), when the user triggers compaction, or when the agent triggers compaction. REPL state persists across compactions, but compaction removes individual variables whose serialized form exceeds 16 MiB.\n\n- `compact.run(instructions: str | None = None) -> dict`: schedule a compaction at the next assistant turn boundary\n- `compact.status() -> dict`: context usage & threshold before auto-compaction\n\n## Goal\n\nIn goal mode prime-agent helps an agent stay on track until a task is fully finished, and handles interruptions and other issues. Goals can be user- or agent-created.\n\n- `goal.create(objective: str, token_budget: int | None = None) -> dict`: create goal and return goal state\n- `goal.get() -> dict`: get goal status (only one goal can be active at a time)\n- `goal.complete() -> dict`: mark goal as completed and get final goal status\n\n## Heartbeat\n\nIn prime-agent, agents can create heartbeats to wake themselves up after a given period of time with remembered instructions, recurrently on a given schedule.\n\n- `rlm_heartbeat.create(instruction: str, interval: str | None = None, label: str | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`: new recurring heartbeat for this session; `interval` is a schedule string (default: every 5 minutes); `delivery_mode`: steer (default) interrupts a busy session's current turn, follow_up waits for it to finish\n- `rlm_heartbeat.list(include_inactive: bool = False) -> dict`\n- `rlm_heartbeat.update(id: str, instruction: str | None = None, interval: str | None = None, label: str | None = None, status: Literal[\"pause\", \"resume\"] | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`\n- `rlm_heartbeat.delete(id: str) -> dict`\n\n## MCP\n\nprime-agent has support for programmatic tools that are defined in the MCP format. Their schema is discovered at runtime.\n\n- `mcp.list_tools(server: str) -> list[dict]`: returns tool schemas\n- `mcp.call_tool(server: str, tool: str, arguments: dict | None = None) -> Any`\n- `mcp.list_plugins(connection_status: str | None = None, limit: int = 50, cursor: str | None = None) -> dict`: one bounded page of the supported-service catalog\n- `mcp.search_plugins(query: str, limit: int = 10) -> dict`: bounded catalog search\n- `mcp.list_connections() -> list[dict]`: the user's current connections (the dispatch ids)\n- `mcp.search_tools(query: str, connection_id: str | None = None, limit: int = 20) -> dict`: search live tool names/descriptions and report the search scope\n- `mcp.describe_tool(connection_id: str, tool: str) -> dict`: one live tool's name, description, and inputSchema\n\n## Skills\n\nprime-agent provides multiple executable skills, described by their SKILL.md and executable code. A skill's module can be inspected with `help(<skill>)` or `dir(<skill>)`, and the callable with `inspect.signature(<skill>.<function>)`, if information is missing. The executable code is always pre-imported in the REPL as a programmatic tool, and a callable skill module can be called directly (`await <skill>(...)`).\n\nAll programmatic tools described above except for `bash`, `rlm.*`, and `mcp.*` are implemented as executable skills and will be listed again in the dynamic tail of this prompt. Additional executable and non-executable skills may exist as well; non-executable (markdown) skills are documentation read from disk, and each skill is also available as a shell command by the same name.\n\nThe following are mandatory rules, only to be overridden by clear user intent.\n\n- Memories must be kept lean and up-to-date.\n- `goal.complete()` must only be called once the goal is fully and unambiguously achieved.\n- Goals must only be created at a user's request.\n- Agents run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n- `bash(\"\"\"...\"\"\")` should be used over `bash(\"...\")` because it makes using quotation marks inside bash easy.\n- Bash commands must be run in the background; if they are quick, or the agent is doing other heavy work in the same `ipython` call, they should be awaited or polled in the same `ipython` call interleaved with other work, or a subsequent one; otherwise, the agent should wait for the notification; blocking calls reduce user responsiveness.\n- Shell state does not persist between calls, but agents can use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables — both persist in the REPL and apply to later `bash()` calls through POSIX process inheritance (since each bash call is a fresh process, Python does not inherit environment variables from bash).\n- Edits of existing files must be performed using `edit` with exact old/new strings; if the text contains triple double quotes (\"\"\"), the agent should use triple single-quoted variables or build `old`/`new` from inspected file slices.\n- Agents use Python for reading files and searching in them — it gives them reusable variables they can slice, filter, and act on without re-reading; using Python variables to find or produce, and to save the strings used in `edit` is also encouraged.\n- Agents always assign read/search results to named variables so they can revisit them later.\n- Agents must report assumptions they made and constants they changed to the user.\n- When an agent is done, they stop calling tools and state their final answer.\n- When delegation is available and useful, an agent assigns independent substantive tasks to separate workers. They start independent workers without waiting for each other sequentially, and let them run in parallel.\n- Agents do not keep the turn open by polling with `time.sleep()` or shell `sleep`, and they do not replace polling with a long blocking `await`. They await only the short operation needed to start work or inspect a result that is already available; otherwise they end the turn.\n- Agents use the Python REPL to keep intermediate variables, inspect and transform outputs, and write small helper functions.\n- Since compaction removes individual variables whose serialized form exceeds 16 MiB, agents can keep large source data on disk and reload it when needed.\n- Python is the orchestration language: agents use Python for loops, conditionals, parsing, and state. They use `bash()` to invoke programs, not to write shell programs, shell loops, or heredocs; those are done directly in Python.\n- Agents do not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Agents evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n- Agents do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, they run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Agents treat failures from that native environment as the relevant result.\n- Rules for root agents (depth 0):\n - Only message siblings if you are certain that it is necessary.\n - When work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n- Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n- Agents treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: they diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. They use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so agents continue working normally after calling it. Agents do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n- Instructions to agents for multi-agent work:\n - When spawning a subagent, keep the handle to stop or inspect the child later.\n - Ask for an explicit reply when needed; not every message needs a reply.\n - Use `await rlm.list_subagents()` after kernel restart or compaction.\n - Have children write files and read those files for fan-in.\n - Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\n\nThe following guidelines to agents have been shown to improve results on average. Agents should consider using them where appropriate. Clear user instructions always override these defaults.\n\n- Agents can use the following patterns to make better use of the REPL:\n - Write wrappers around `rlm.spawn` to have quick templates for subagents with arbitrary args: for text to programmatically pass and put into the prompt, for conditional behavior prompts, etc.\n - Use f-strings (`f\"\"\"...\"\"\"` or `f\"...\"`) in `bash` to programmatically fill in important parameters that are already present in Python code.\n- When writing or explaining something:\n - Agents use simplified technical English by default for user-facing prose: short sentences, common words, and concrete verbs; one main action or fact per sentence when practical; lists for steps or conditions. Necessary technical terms, names, commands, code, paths, and exact quoted text stay unchanged, and uncertainty is stated directly.\n - Agents use ordinary or established wording. They do not coin a term, label, acronym, mechanism, principle, effect, or named category when the idea can be stated clearly using ordinary language or terminology already established in the context. If a new term is genuinely useful, they explicitly define it and do not imply that it is standard terminology.\n - Agents keep names and terms consistent. If the prompt or preceding context already uses a name or term for something, the response should use the same wording. Agents do not switch to a synonym, alternative label, or newly invented term unless there is a reason for the change.\n- Agents take care and effort to avoid the following pitfalls while coding:\n - over-engineered solutions\n - overly defensive programming\n - hyper-fixation on rare/fictitious edge cases\n - overlapping subsystem responsibilities\n - solving problems at the wrong architectural layer\n - duplication of sources of truth, then inventing machinery to synchronize them\n - prematurely generalizing one-off flows\n - timeouts on everything\n - production code that exists purely to satisfy tests\n - patching bad premises additively instead of stepping back and deleting or adjusting them\n - tests for magic strings\n - excessive tests\n - comments that describe anything already described by the code\n - comments narrating the coding process instead of supporting the written code\n - fallbacks, legacy support, compatibility shims where not strictly needed; when in doubt, these should be discussed with the user\n - in UI, descriptions on everything\n\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent&apos;s parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location><skills-dir>/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent&apos;s parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location><skills-dir>/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model&apos;s context as a viewable attachment so the model can directly SEE it — for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image&apos;s visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location><skills-dir>/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location><skills-dir>/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location><skills-dir>/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location><skills-dir>/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>mcp</name>\n <type>markdown</type>\n <description>Use external MCP services generically from Python - search the supported-service catalog, inspect the user&apos;s connections, discover live tool schemas, and call tools on any connection (Notion, Linear, Slack, and the rest of the catalog) without per-service packages.</description>\n <location><skills-dir>/mcp/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location><skills-dir>/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location><skills-dir>/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user&apos;s /heartbeat.</description>\n <location><skills-dir>/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location><skills-dir>/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /mcp, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location><skills-dir>/websearch/SKILL.md</location>\n </skill>\n</available_skills>\n\nCurrent date: <date>\nWorking directory: /w\nConversation log: /w/sessions/fixture-session.jsonl\n\nRecursive agent depth: 0 (root)"
}
diff --git a/crates/pa-daemon/Cargo.toml b/crates/pa-daemon/Cargo.toml
index 784e38a872..d0b67631c4 100644
--- a/crates/pa-daemon/Cargo.toml
+++ b/crates/pa-daemon/Cargo.toml
@@ -24,6 +24,9 @@ uuid = { version = "1", features = ["v4", "v7"] }
[dev-dependencies]
filetime = "0.2"
tempfile = "3"
+# The supervisor property suite draws sibling rosters for the live
+# rename ladder; the plain std features are enough (no fork/timeout).
+proptest = { workspace = true }
# Test-only: `ModelCatalog::with_urls` + the compiled offline Prime
# Inference entries build the loopback catalog the session-model restore
# tests script (the pa-core tests/common pattern, in-crate), and the
diff --git a/crates/pa-daemon/src/rlm_children.rs b/crates/pa-daemon/src/rlm_children.rs
index dd854798d6..901ad40568 100644
--- a/crates/pa-daemon/src/rlm_children.rs
+++ b/crates/pa-daemon/src/rlm_children.rs
@@ -86,6 +86,8 @@ const CREATE_TIMEOUT_MS: u64 = 120_000;
const PROMPT_TIMEOUT_MS: u64 = 30_000;
const STATE_TIMEOUT_MS: u64 = 30_000;
const KILL_TIMEOUT_MS: u64 = 30_000;
+/// Budget for one session rename over the supervisor route (TS uses 30s).
+const RENAME_TIMEOUT_MS: u64 = 30_000;
/// Grace over a collect budget passed to the worker `wait_for_idle`.
const IDLE_WAIT_GRACE_MS: u64 = 5_000;
/// Budget for one terminal-notice delivery over the supervisor route.
@@ -219,6 +221,8 @@ struct ChildRecord {
/// Serializes usage emissions for this child (read, cursor advance,
/// and sink delivery) without holding the record lock across them.
emit_lock: std::sync::Arc<tokio::sync::Mutex<()>>,
+ /// Serializes parent-directed rename and delete for this child.
+ rename_lock: std::sync::Arc<tokio::sync::Mutex<()>>,
}
impl ChildRecord {
@@ -240,9 +244,14 @@ impl ChildRecord {
}
fn matches(&self, target: &str) -> bool {
+ self.matches_id(target) || self.session_name == target
+ }
+
+ /// The id selectors (the rename target resolution): every field a
+ /// child handle or full session id can carry — never the name.
+ fn matches_id(&self, target: &str) -> bool {
self.rlm_child_id == target
|| self.active_session_id == target
- || self.session_name == target
|| self.session_id.as_deref() == Some(target)
}
}
@@ -741,6 +750,7 @@ impl SupervisorChildSessions {
usage_watch_live: false,
usage_rearm: false,
emit_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
+ rename_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
})));
}
diff --git a/crates/pa-daemon/src/rlm_children/host.rs b/crates/pa-daemon/src/rlm_children/host.rs
index 548b94fa64..e37561adb0 100644
--- a/crates/pa-daemon/src/rlm_children/host.rs
+++ b/crates/pa-daemon/src/rlm_children/host.rs
@@ -1,7 +1,7 @@
//! The host adapter concern: the `RlmSubagentHost` wire surface
//! (`spawn`, `create_session`, `list_subagents`, `delete_subagent`,
-//! `collect`) over the supervisor's child-sessions registry, with the
-//! spawn-admission helpers only this surface uses.
+//! `collect`, `rename`) over the supervisor's child-sessions registry,
+//! with the spawn-admission helpers only this surface uses.
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,
@@ -10,6 +10,7 @@ use super::{
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
@@ -150,6 +151,7 @@ impl RlmSubagentHost for SupervisorChildSessions {
usage_watch_live: false,
usage_rearm: false,
emit_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
+ rename_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
};
let record = Arc::new(Mutex::new(record));
this.children.lock().await.push(Arc::clone(&record));
@@ -325,6 +327,15 @@ impl RlmSubagentHost for SupervisorChildSessions {
// `No direct RLM subagent matches ...` message is the product
// surface); only the kill below gets a delete context.
let record = this.resolve_record(&target, "subagent").await?;
+ let rename_lock = record.lock().await.rename_lock.clone();
+ let _rename_guard = rename_lock.lock().await;
+ let no_longer_matches = {
+ let record = record.lock().await;
+ record.closed_by_parent || !record.matches(&target)
+ };
+ if no_longer_matches {
+ bail!("No direct RLM subagent matches \"{target}\" in the current parent session");
+ }
let active_session_id = record.lock().await.active_session_id.clone();
// Kill first: a failed kill keeps the child tracked so the caller
// can retry; a successful kill removes it from the registry.
@@ -512,6 +523,111 @@ impl RlmSubagentHost for SupervisorChildSessions {
Ok(results)
})
}
+
+ fn rename(&self, name: String, session_id: Option<String>) -> RlmHostFuture<String> {
+ let this = Arc::clone(&self.inner);
+ Box::pin(async move {
+ // Resolve the target: the caller's own session (an absent
+ // session id, its live active id, or its durable session id),
+ // or one direct child by rlm child id, active id, or durable
+ // session id ONLY — a child NAME never selects a rename
+ // target (TS `renameAgentFamilySession`).
+ let identity = this.identity.lock().expect("identity lock").clone();
+ let self_target = match &session_id {
+ None => true,
+ Some(target) => {
+ target == &this.parent_active_session_id
+ || identity.session_id.as_deref() == Some(target.as_str())
+ }
+ };
+ let (active_session_id, record) = if self_target {
+ (this.parent_active_session_id.clone(), None)
+ } else {
+ let target = session_id.clone().unwrap_or_default();
+ let mut by_ids = None;
+ let mut by_name = false;
+ {
+ let children = this.children.lock().await;
+ for candidate in children.iter() {
+ let record = candidate.lock().await;
+ if record.matches_id(&target) {
+ by_ids = Some(Arc::clone(candidate));
+ break;
+ }
+ if record.session_name == target {
+ by_name = true;
+ }
+ }
+ }
+ match by_ids {
+ Some(record) => {
+ let active_session_id = record.lock().await.active_session_id.clone();
+ (active_session_id, Some(record))
+ }
+ None if by_name => bail!(
+ "rlm.rename session_id \"{target}\" must be the full session id or a child handle, not a session name or id suffix"
+ ),
+ None => bail!(
+ "rlm.rename can only rename the current session or one of its direct children"
+ ),
+ }
+ };
+ // Serialize the daemon command and parent-side record update
+ // against another rename or delete of this child.
+ let rename_lock = if let Some(record) = &record {
+ Some(record.lock().await.rename_lock.clone())
+ } else {
+ None
+ };
+ let _rename_guard = if let Some(lock) = &rename_lock {
+ Some(lock.lock().await)
+ } else {
+ None
+ };
+ if let Some(record) = &record {
+ if record.lock().await.closed_by_parent {
+ bail!("rlm.rename can only rename the current session or one of its direct children");
+ }
+ }
+ // The rename itself is daemon-owned: the supervisor's live
+ // rename route reserves the name, asserts sibling uniqueness
+ // across the family, and appends the child's RLM ledger
+ // rename. `renamedBy: parent` marks the parent-directed
+ // rename so the renamed session's transcript notice names it.
+ // The child may be passivated — or a prior wake may have
+ // re-keyed its roster row past the record's spawn-time id —
+ // so the rename rides the same durable-selector wake retry
+ // the child prompts use (the record keeps the spawn-time
+ // routing id; only its durable session id still names a
+ // passivated child).
+ let renamed_by = record.as_ref().map(|_| {
+ pa_core::session_engine::agent_messaging::AgentFamilyRelationship::Parent
+ .as_str()
+ .to_string()
+ });
+ let make_command = |selector: &str| DaemonCommand::Rename {
+ id: None,
+ active_session_id: selector.to_string(),
+ name: name.clone(),
+ renamed_by: renamed_by.clone(),
+ rest: serde_json::Map::default(),
+ };
+ this.command_with_durable_wake(
+ make_command,
+ &active_session_id,
+ RENAME_TIMEOUT_MS,
+ &format!("rename session \"{active_session_id}\""),
+ )
+ .await?;
+ // A parent-directed rename updates the parent-side record so
+ // the roster row, collect/delete selectors, and the parent's
+ // name-availability check all stop matching the old name.
+ if let Some(record) = record {
+ record.lock().await.session_name = name.clone();
+ }
+ Ok(name)
+ })
+ }
}
/// Whether the child's durable session file already carries the task prompt
diff --git a/crates/pa-daemon/src/rlm_children/lifecycle.rs b/crates/pa-daemon/src/rlm_children/lifecycle.rs
index 1ae2ecc28d..a1639aab16 100644
--- a/crates/pa-daemon/src/rlm_children/lifecycle.rs
+++ b/crates/pa-daemon/src/rlm_children/lifecycle.rs
@@ -217,6 +217,66 @@ impl SupervisorChildSessionsInner {
})
}
+ /// Send one child-addressed daemon command and retry it ONCE by the
+ /// child's durable selector when its routing id no longer resolves
+ /// (the passivation-aware wake, TS's tier-2 revival — shared by the
+ /// prompt and the parent-directed rename): the child's worker was
+ /// idle-evicted, or a prior wake re-keyed the supervisor roster's
+ /// child row to a fresh worker id, so the routing id the caller
+ /// holds (the record's spawn-time active id) resolves nowhere. The
+ /// retry addresses the child by its DURABLE selector (its session id
+ /// — the session-file stem the supervisor's wake resolves through
+ /// the spawn ledger, then the child id) — the daemon's wake arm
+ /// launches a fresh worker over the child's session file and the
+ /// command lands on the replay. `subject` renders the failure
+ /// contexts; the retry's context appends the wake provenance. A
+ /// non-miss failure and a child with no record keep the original
+ /// error.
+ pub(super) async fn command_with_durable_wake(
+ &self,
+ make_command: impl Fn(&str) -> DaemonCommand,
+ active_session_id: &str,
+ timeout_ms: u64,
+ subject: &str,
+ ) -> Result<()> {
+ let command = make_command(active_session_id);
+ match self.command(&command, timeout_ms).await {
+ Ok(_) => Ok(()),
+ Err(error) => {
+ let rendered = format!("{error:#}");
+ if !rendered.starts_with("Unknown active session:") {
+ return Err(error).with_context(|| subject.to_string());
+ }
+ let durable = self.durable_child_selector_for(active_session_id).await;
+ let Some(durable) = durable else {
+ return Err(error).with_context(|| subject.to_string());
+ };
+ let retry = make_command(&durable);
+ self.command(&retry, timeout_ms)
+ .await
+ .with_context(|| format!("{subject} (woken by {durable})"))?;
+ Ok(())
+ }
+ }
+ }
+
+ /// The durable selector of the child whose routing id is
+ /// `active_session_id`: the address that reaches a passivated child
+ /// through the supervisor's ledger wake.
+ async fn durable_child_selector_for(&self, active_session_id: &str) -> Option<String> {
+ let children = self.children.lock().await;
+ for record in children.iter() {
+ let record = record.lock().await;
+ if record.active_session_id == active_session_id {
+ return Some(crate::rlm_children::durable_child_selector(
+ record.session_id.as_deref(),
+ &record.rlm_child_id,
+ ));
+ }
+ }
+ None
+ }
+
pub(super) async fn prompt_child(&self, active_session_id: &str, prompt: &str) -> Result<()> {
let make_command = |selector: &str| DaemonCommand::Prompt {
id: None,
@@ -238,49 +298,13 @@ impl SupervisorChildSessionsInner {
},
rest: Map::default(),
};
- let command = make_command(active_session_id);
- match self.command(&command, PROMPT_TIMEOUT_MS).await {
- Ok(_) => Ok(()),
- // The passivation-aware wake (TS's tier-2 revival): the
- // child's worker was idle-evicted, so its ROUTING id no
- // longer resolves. Retry once by the child's DURABLE selector
- // (its session id — the session-file stem the supervisor's
- // wake resolves through the spawn ledger, then the child id)
- // — the daemon's wake arm launches a fresh worker over the
- // child's session file and the prompt lands on the replay.
- Err(error) => {
- let rendered = format!("{error:#}");
- if !rendered.starts_with("Unknown active session:") {
- return Err(error)
- .with_context(|| format!("prompt RLM child session {active_session_id}"));
- }
- let mut durable: Option<String> = None;
- {
- let children = self.children.lock().await;
- for record in children.iter() {
- let record = record.lock().await;
- if record.active_session_id == active_session_id {
- durable = Some(crate::rlm_children::durable_child_selector(
- record.session_id.as_deref(),
- &record.rlm_child_id,
- ));
- break;
- }
- }
- }
- let Some(durable) = durable else {
- return Err(error)
- .with_context(|| format!("prompt RLM child session {active_session_id}"));
- };
- let retry = make_command(&durable);
- self.command(&retry, PROMPT_TIMEOUT_MS)
- .await
- .with_context(|| {
- format!("prompt RLM child session {active_session_id} (woken by {durable})")
- })?;
- Ok(())
- }
- }
+ self.command_with_durable_wake(
+ make_command,
+ active_session_id,
+ PROMPT_TIMEOUT_MS,
+ &format!("prompt RLM child session {active_session_id}"),
+ )
+ .await
}
pub(super) async fn kill_child(
diff --git a/crates/pa-daemon/src/rlm_children/registry.rs b/crates/pa-daemon/src/rlm_children/registry.rs
index 2dfe595133..cac72e1bbb 100644
--- a/crates/pa-daemon/src/rlm_children/registry.rs
+++ b/crates/pa-daemon/src/rlm_children/registry.rs
@@ -408,6 +408,7 @@ fn ledger_child_records(
usage_watch_live: false,
usage_rearm: false,
emit_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
+ rename_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
});
}
records
diff --git a/crates/pa-daemon/src/rlm_children/spawn_name_reservation_tests.rs b/crates/pa-daemon/src/rlm_children/spawn_name_reservation_tests.rs
index d02ac25529..68712024eb 100644
--- a/crates/pa-daemon/src/rlm_children/spawn_name_reservation_tests.rs
+++ b/crates/pa-daemon/src/rlm_children/spawn_name_reservation_tests.rs
@@ -16,8 +16,11 @@ async fn spawn_gated_supervisor(
socket: std::path::PathBuf,
create_seen_tx: mpsc::UnboundedSender<Value>,
verdict_rx: mpsc::UnboundedReceiver<bool>,
+ rename_seen_tx: mpsc::UnboundedSender<Value>,
+ rename_verdict_rx: Option<mpsc::UnboundedReceiver<()>>,
) {
let verdict_rx = std::sync::Arc::new(tokio::sync::Mutex::new(verdict_rx));
+ let rename_verdict_rx = rename_verdict_rx.map(|rx| Arc::new(tokio::sync::Mutex::new(rx)));
let listener = bind_transport(&socket).await.unwrap();
tokio::spawn(async move {
loop {
@@ -25,7 +28,9 @@ async fn spawn_gated_supervisor(
return;
};
let create_seen_tx = create_seen_tx.clone();
+ let rename_seen_tx = rename_seen_tx.clone();
let verdict_rx = std::sync::Arc::clone(&verdict_rx);
+ let rename_verdict_rx = rename_verdict_rx.clone();
tokio::spawn(async move {
let (reader, mut writer) = stream.split();
let mut reader = BufReader::new(reader);
@@ -94,6 +99,13 @@ async fn spawn_gated_supervisor(
Some(json!({ "text": "the child final answer" })),
),
"kill" => response_success(Some(&id), command_type, None),
+ "rename" => {
+ let _ = rename_seen_tx.send(command.clone());
+ if let Some(gate) = &rename_verdict_rx {
+ let _ = gate.lock().await.recv().await;
+ }
+ response_success(Some(&id), command_type, None)
+ }
"follow_up" => response_success(
Some(&id),
command_type,
@@ -116,12 +128,21 @@ async fn spawn_gated_supervisor(
async fn sessions_with_gated_supervisor(
create_seen_tx: mpsc::UnboundedSender<Value>,
verdict_rx: mpsc::UnboundedReceiver<bool>,
+ rename_seen_tx: mpsc::UnboundedSender<Value>,
+ rename_verdict_rx: Option<mpsc::UnboundedReceiver<()>>,
) -> SupervisorChildSessions {
let socket = std::env::temp_dir().join(format!(
"pa-rlm-gate-{}.sock",
uuid::Uuid::new_v4().simple()
));
- spawn_gated_supervisor(socket.clone(), create_seen_tx, verdict_rx).await;
+ spawn_gated_supervisor(
+ socket.clone(),
+ create_seen_tx,
+ verdict_rx,
+ rename_seen_tx,
+ rename_verdict_rx,
+ )
+ .await;
let link = Arc::new(crate::supervisor_link::SupervisorLink::new(socket));
let sessions = SupervisorChildSessions::new(
link,
@@ -160,7 +181,9 @@ fn spawn_request(name: &str, prompt: &str) -> RlmSpawnRequest {
async fn holds_a_spawn_name_reservation_until_admission_settles_then_frees_it() {
let (create_seen_tx, mut create_seen_rx) = mpsc::unbounded_channel();
let (verdict_tx, verdict_rx) = mpsc::unbounded_channel();
- let sessions = sessions_with_gated_supervisor(create_seen_tx, verdict_rx).await;
+ let (rename_seen_tx, _rename_seen_rx) = mpsc::unbounded_channel();
+ let sessions =
+ sessions_with_gated_supervisor(create_seen_tx, verdict_rx, rename_seen_tx, None).await;
let unavailable = "Agent name \"slow-worker\" is unavailable: an agent of that name already exists at depth 1 under this parent";
// The first spawn parks inside its create admission.
@@ -204,7 +227,9 @@ async fn holds_a_spawn_name_reservation_until_admission_settles_then_frees_it()
async fn a_cancelled_spawn_admission_frees_the_reserved_name() {
let (create_seen_tx, mut create_seen_rx) = mpsc::unbounded_channel();
let (verdict_tx, verdict_rx) = mpsc::unbounded_channel();
- let sessions = sessions_with_gated_supervisor(create_seen_tx, verdict_rx).await;
+ let (rename_seen_tx, _rename_seen_rx) = mpsc::unbounded_channel();
+ let sessions =
+ sessions_with_gated_supervisor(create_seen_tx, verdict_rx, rename_seen_tx, None).await;
// The spawn parks inside its create admission.
let parked = tokio::spawn(sessions.spawn(spawn_request("abandoned", "a parked admission")));
@@ -240,7 +265,9 @@ async fn a_cancelled_spawn_admission_frees_the_reserved_name() {
async fn a_failed_admission_frees_the_reserved_name() {
let (create_seen_tx, mut create_seen_rx) = mpsc::unbounded_channel();
let (verdict_tx, verdict_rx) = mpsc::unbounded_channel();
- let sessions = sessions_with_gated_supervisor(create_seen_tx, verdict_rx).await;
+ let (rename_seen_tx, _rename_seen_rx) = mpsc::unbounded_channel();
+ let sessions =
+ sessions_with_gated_supervisor(create_seen_tx, verdict_rx, rename_seen_tx, None).await;
let spawned = tokio::spawn(sessions.spawn(spawn_request("doomed", "kernel startup failed")));
create_seen_rx
@@ -264,3 +291,192 @@ async fn a_failed_admission_frees_the_reserved_name() {
assert_eq!(handle.name, "doomed");
assert!(!sessions.spawn_name_reserved("doomed"));
}
+
+/// The rename target resolution (TS `renameAgentFamilySession`): a child
+/// renames only by rlm child id, active id, or durable session id — a
+/// name never selects — and a miss outside the caller's own session and
+/// its direct children fails closed.
+#[tokio::test]
+async fn rename_resolves_child_targets_by_id_only() {
+ let (create_seen_tx, mut create_seen_rx) = mpsc::unbounded_channel();
+ let (verdict_tx, verdict_rx) = mpsc::unbounded_channel();
+ let (rename_seen_tx, _rename_seen_rx) = mpsc::unbounded_channel();
+ let sessions =
+ sessions_with_gated_supervisor(create_seen_tx, verdict_rx, rename_seen_tx, None).await;
+ let spawned = tokio::spawn(sessions.spawn(spawn_request("worker-a", "a named child")));
+ create_seen_rx
+ .recv()
+ .await
+ .expect("the create must reach the gated supervisor");
+ verdict_tx.send(true).expect("admit the create");
+ let _handle = spawned.await.expect("spawn task").expect("spawn the child");
+
+ // The child's NAME never selects a rename target.
+ let error = sessions
+ .rename("bench-runner".to_string(), Some("worker-a".to_string()))
+ .await
+ .expect_err("a child name never renames");
+ assert_eq!(
+ error.to_string(),
+ "rlm.rename session_id \"worker-a\" must be the full session id or a child handle, not a session name or id suffix"
+ );
+ // A selector outside the caller and its children fails closed.
+ let error = sessions
+ .rename("bench-runner".to_string(), Some("ghost".to_string()))
+ .await
+ .expect_err("an unknown target never renames");
+ assert_eq!(
+ error.to_string(),
+ "rlm.rename can only rename the current session or one of its direct children"
+ );
+}
+
+/// A parent-directed child rename rides the supervisor's live rename
+/// route (`renamedBy: parent`), and on success the parent-side record
+/// takes the new name — the old name stops matching, the new one hits.
+#[tokio::test]
+async fn parent_rename_forwards_and_reseeds_the_record_name() {
+ let (create_seen_tx, mut create_seen_rx) = mpsc::unbounded_channel();
+ let (verdict_tx, verdict_rx) = mpsc::unbounded_channel();
+ let (rename_seen_tx, mut rename_seen_rx) = mpsc::unbounded_channel();
+ let sessions =
+ sessions_with_gated_supervisor(create_seen_tx, verdict_rx, rename_seen_tx, None).await;
+ let spawned = tokio::spawn(sessions.spawn(spawn_request("worker-a", "a named child")));
+ create_seen_rx
+ .recv()
+ .await
+ .expect("the create must reach the gated supervisor");
+ verdict_tx.send(true).expect("admit the create");
+ let handle = spawned.await.expect("spawn task").expect("spawn the child");
+
+ let renamed = sessions
+ .rename(
+ "bench-runner".to_string(),
+ Some(handle.rlm_child_id.clone()),
+ )
+ .await
+ .expect("rename the child by its handle id");
+ assert_eq!(renamed, "bench-runner");
+ let seen = rename_seen_rx
+ .recv()
+ .await
+ .expect("the rename reached the supervisor");
+ assert_eq!(seen["type"], "rename");
+ assert_eq!(seen["activeSessionId"], "child-live");
+ assert_eq!(seen["name"], "bench-runner");
+ assert_eq!(
+ seen["renamedBy"], "parent",
+ "a child rename is parent-directed"
+ );
+
+ // The record took the new name: the old selector misses, the new one
+ // hits (the collect-by-name and delete selectors read it).
+ let error = sessions
+ .collect(vec!["worker-a".to_string()], 0)
+ .await
+ .expect_err("the old name no longer selects");
+ assert_eq!(
+ error.to_string(),
+ "No direct RLM child matches \"worker-a\" in the current parent session"
+ );
+ let rows = sessions
+ .collect(vec!["bench-runner".to_string()], 0)
+ .await
+ .expect("the new name selects");
+ assert_eq!(rows[0].rlm_child_id, handle.rlm_child_id);
+}
+
+/// A self rename (an absent session id, the caller's own active id, or
+/// its durable session id) routes to the caller's own worker through the
+/// supervisor with no `renamedBy` marker.
+#[tokio::test]
+async fn self_rename_targets_the_caller_without_the_parent_marker() {
+ let (create_seen_tx, _create_seen_rx) = mpsc::unbounded_channel();
+ let (_verdict_tx, verdict_rx) = mpsc::unbounded_channel();
+ let (rename_seen_tx, mut rename_seen_rx) = mpsc::unbounded_channel();
+ let sessions =
+ sessions_with_gated_supervisor(create_seen_tx, verdict_rx, rename_seen_tx, None).await;
+ sessions.set_identity(ParentIdentity {
+ model: Some("mock/mock-1".to_string()),
+ cwd: Some(std::env::temp_dir().to_string_lossy().to_string()),
+ session_id: Some("parent-file".to_string()),
+ ..ParentIdentity::with_default_depth()
+ });
+
+ for selector in [None, Some("parent-live"), Some("parent-file")] {
+ let renamed = sessions
+ .rename("solo".to_string(), selector.map(str::to_string))
+ .await
+ .expect("the self rename routes");
+ assert_eq!(renamed, "solo");
+ let seen = rename_seen_rx
+ .recv()
+ .await
+ .expect("the rename reached the supervisor");
+ assert_eq!(seen["type"], "rename");
+ assert_eq!(seen["activeSessionId"], "parent-live");
+ assert_eq!(seen["name"], "solo");
+ assert!(
+ seen.get("renamedBy").is_none(),
+ "a self rename carries no parent marker: {seen}"
+ );
+ }
+}
+
+/// A second rename must not overtake the first command and then let its
+/// earlier parent-side record write replace the final worker name.
+#[tokio::test]
+async fn concurrent_parent_renames_keep_the_last_applied_name() {
+ let (create_seen_tx, mut create_seen_rx) = mpsc::unbounded_channel();
+ let (verdict_tx, verdict_rx) = mpsc::unbounded_channel();
+ let (rename_seen_tx, mut rename_seen_rx) = mpsc::unbounded_channel();
+ let (rename_verdict_tx, rename_verdict_rx) = mpsc::unbounded_channel();
+ let sessions = sessions_with_gated_supervisor(
+ create_seen_tx,
+ verdict_rx,
+ rename_seen_tx,
+ Some(rename_verdict_rx),
+ )
+ .await;
+ let spawned = tokio::spawn(sessions.spawn(spawn_request("worker-a", "a named child")));
+ create_seen_rx
+ .recv()
+ .await
+ .expect("create reached the supervisor");
+ verdict_tx.send(true).expect("admit create");
+ let handle = spawned.await.expect("spawn task").expect("spawn child");
+
+ let first =
+ tokio::spawn(sessions.rename("first".to_string(), Some(handle.rlm_child_id.clone())));
+ let seen = rename_seen_rx
+ .recv()
+ .await
+ .expect("first rename reached supervisor");
+ assert_eq!(seen["name"], "first");
+ let second =
+ tokio::spawn(sessions.rename("second".to_string(), Some(handle.rlm_child_id.clone())));
+ // The second parent rename must wait before forwarding; the fake
+ // supervisor deliberately parks the first reply.
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_millis(100), rename_seen_rx.recv())
+ .await
+ .is_err()
+ );
+ rename_verdict_tx.send(()).expect("finish first rename");
+ assert_eq!(
+ first.await.expect("first task").expect("first rename"),
+ "first"
+ );
+ let seen = rename_seen_rx
+ .recv()
+ .await
+ .expect("second rename reached supervisor");
+ assert_eq!(seen["name"], "second");
+ rename_verdict_tx.send(()).expect("finish second rename");
+ assert_eq!(
+ second.await.expect("second task").expect("second rename"),
+ "second"
+ );
+ let rows = sessions.list_subagents().await.expect("roster");
+ assert_eq!(rows[0].session_name, "second");
+}
diff --git a/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs b/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs
index ded2795638..d49c62ac3f 100644
--- a/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs
+++ b/crates/pa-daemon/src/rlm_children/usage_emit_tests.rs
@@ -49,6 +49,7 @@ fn record_with_file(child_id: &str, session_file: &Path) -> Arc<Mutex<ChildRecor
usage_watch_live: false,
usage_rearm: false,
emit_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
+ rename_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
}))
}
diff --git a/crates/pa-daemon/src/rlm_children/watch_tests.rs b/crates/pa-daemon/src/rlm_children/watch_tests.rs
index 7bea6b1412..7083bf9cc3 100644
--- a/crates/pa-daemon/src/rlm_children/watch_tests.rs
+++ b/crates/pa-daemon/src/rlm_children/watch_tests.rs
@@ -1020,6 +1020,7 @@ fn an_already_settled_child_never_re_scores_as_an_unreachable_error() {
usage_watch_live: false,
usage_rearm: false,
emit_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
+ rename_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
};
// A running child that goes unreachable is the error class.
assert!(super::lifecycle::should_mark_unreachable_error(&base()));
diff --git a/crates/pa-daemon/src/saved_session_commands.rs b/crates/pa-daemon/src/saved_session_commands.rs
index f3a8a73897..4831a94db9 100644
--- a/crates/pa-daemon/src/saved_session_commands.rs
+++ b/crates/pa-daemon/src/saved_session_commands.rs
@@ -72,6 +72,28 @@ pub(crate) struct NameScope {
pub(crate) parent_session_path: Option<String>,
}
+/// The roster summary's name-reservation fields, the one projection both
+/// rename scopes read (a saved row by file, a live row by active id).
+fn name_scope_from_summary(summary: &Value, name: String) -> NameScope {
+ NameScope {
+ id: summary
+ .get("sessionId")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string(),
+ name,
+ depth: summary.get("rlmDepth").and_then(Value::as_u64).unwrap_or(0) as u32,
+ parent_session_id: summary
+ .get("parentSessionId")
+ .and_then(Value::as_str)
+ .map(str::to_string),
+ parent_session_path: summary
+ .get("parentSessionPath")
+ .and_then(Value::as_str)
+ .map(str::to_string),
+ }
+}
+
/// One family-catalog row (TS `AgentFamilyCatalogEntry`): the fields the
/// name-availability assertion reads.
struct FamilyRow {
@@ -357,26 +379,9 @@ impl Supervisor {
.roster
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
- roster.by_session_file(&canonical).map(|entry| {
- let summary = &entry.summary;
- NameScope {
- id: summary
- .get("sessionId")
- .and_then(Value::as_str)
- .unwrap_or_default()
- .to_string(),
- name: name.clone(),
- depth: summary.get("rlmDepth").and_then(Value::as_u64).unwrap_or(0) as u32,
- parent_session_id: summary
- .get("parentSessionId")
- .and_then(Value::as_str)
- .map(str::to_string),
- parent_session_path: summary
- .get("parentSessionPath")
- .and_then(Value::as_str)
- .map(str::to_string),
- }
- })
+ roster
+ .by_session_file(&canonical)
+ .map(|entry| name_scope_from_summary(&entry.summary, name.clone()))
};
if let Some(scope) = roster_row {
return Ok(scope);
@@ -434,10 +439,92 @@ impl Supervisor {
)
}
};
- // The pending-name reservation (TS `withSessionNameReservation`):
- // a concurrent rename of the same name in the same scope fails
- // with the unavailability error.
- let key = reservation_key(&scope);
+ // The reservation ladder wraps the whole arm — the offline catalog
+ // rename and the live forward alike (TS `withSessionNameReservation`
+ // holds the key across both).
+ match self
+ .with_session_name_reservation(&scope, async {
+ if active_session_id.is_none() {
+ // The offline catalog rename (TS `catalog.rename`):
+ // append the session_info entry, the ledger rename,
+ // and the roster row rewrite.
+ let path = Path::new(session_path);
+ if let Err(error) = append_saved_session_name(path, &scope.name) {
+ return (
+ vec![response_line(&response_failure(
+ Some(command_id),
+ type_name,
+ &error.to_string(),
+ None,
+ ))],
+ false,
+ );
+ }
+ if let Some(sessions_dir) = self.sessions_dir_path() {
+ ledger_rename_by_child_path(
+ &self.options.agent_dir,
+ &sessions_dir,
+ session_path,
+ &scope.name,
+ );
+ }
+ self.rewrite_roster_session_name(session_path, &scope.name);
+ // The renamed session file can carry passive scheduled
+ // rows: the catalog snapshot's rows key off the session
+ // file (TS #2487 invalidates the shared snapshot on the
+ // saved-session rename).
+ self.invalidate_passive_catalog();
+ return (
+ vec![response_line(&response_success(
+ Some(command_id),
+ type_name,
+ None,
+ ))],
+ false,
+ );
+ }
+ // The live form forwards to the owning worker (TS rewrites
+ // the selector onto the resolved summary's ids).
+ self.route_client_command(
+ command,
+ client_id,
+ attached,
+ command_id.to_string(),
+ type_name.to_string(),
+ None,
+ )
+ .await
+ })
+ .await
+ {
+ Ok(outcome) => outcome,
+ Err(error) => (
+ vec![response_line(&response_failure(
+ Some(command_id),
+ type_name,
+ &error,
+ None,
+ ))],
+ false,
+ ),
+ }
+ }
+
+ /// The rename reservation ladder (TS `withSessionNameReservation` +
+ /// `assertSupervisorSessionNameAvailable`, the supervisor's
+ /// daemon-owned name uniqueness): reserve the scope's
+ /// `[depth, parent, name]` key, assert family name availability, run
+ /// `action` under the reservation, and release the key on every exit —
+ /// a same-key concurrent rename fails with the unavailability error,
+ /// and a family conflict fails before the action runs. The live
+ /// `rename`/`set_session_name` forwards and the saved-session arm
+ /// share this one ladder.
+ pub(crate) async fn with_session_name_reservation<T>(
+ &self,
+ scope: &NameScope,
+ action: impl std::future::Future<Output = T>,
+ ) -> Result<T, String> {
+ let key = reservation_key(scope);
let reserved = {
let mut pending = self
.pending_session_names
@@ -446,81 +533,38 @@ impl Supervisor {
pending.insert(key.clone())
};
if !reserved {
- return (
- vec![response_line(&response_failure(
- Some(command_id),
- type_name,
- &name_unavailable_error(&scope.name, scope.depth),
- None,
- ))],
- false,
- );
+ return Err(name_unavailable_error(&scope.name, scope.depth));
}
- let availability = self.assert_family_name_available(&scope);
+ let output = match self.assert_family_name_available(scope) {
+ Ok(()) => Ok(action.await),
+ Err(error) => Err(error),
+ };
self.pending_session_names
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.remove(&key);
- if let Err(error) = availability {
- return (
- vec![response_line(&response_failure(
- Some(command_id),
- type_name,
- &error,
- None,
- ))],
- false,
- );
- }
- if active_session_id.is_none() {
- // The offline catalog rename (TS `catalog.rename`): append the
- // session_info entry, the ledger rename, and the roster row
- // rewrite.
- let path = Path::new(session_path);
- if let Err(error) = append_saved_session_name(path, &scope.name) {
- return (
- vec![response_line(&response_failure(
- Some(command_id),
- type_name,
- &error.to_string(),
- None,
- ))],
- false,
- );
- }
- if let Some(sessions_dir) = self.sessions_dir_path() {
- ledger_rename_by_child_path(
- &self.options.agent_dir,
- &sessions_dir,
- session_path,
- &scope.name,
- );
- }
- self.rewrite_roster_session_name(session_path, &scope.name);
- // The renamed session file can carry passive scheduled rows: the
- // catalog snapshot's rows key off the session file (TS #2487
- // invalidates the shared snapshot on the saved-session rename).
- self.invalidate_passive_catalog();
- return (
- vec![response_line(&response_success(
- Some(command_id),
- type_name,
- None,
- ))],
- false,
- );
- }
- // The live form forwards to the owning worker (TS rewrites the
- // selector onto the resolved summary's ids).
- self.route_client_command(
- command,
- client_id,
- attached,
- command_id.to_string(),
- type_name.to_string(),
- None,
- )
- .await
+ output
+ }
+
+ /// The name-reservation scope for a LIVE session's rename forward
+ /// (TS `summaryNameReservationInput` over the routed worker's matched
+ /// summary): the target's roster row, the same fields
+ /// [`Self::saved_session_name_scope`] reads for a saved row.
+ pub(crate) fn live_session_name_scope(
+ &self,
+ active_session_id: &str,
+ name: String,
+ ) -> Result<NameScope, String> {
+ let scope = {
+ let roster = self
+ .roster
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ roster
+ .by_active_session_id(active_session_id)
+ .map(|entry| name_scope_from_summary(&entry.summary, name))
+ };
+ scope.ok_or_else(|| format!("Unknown active session: {active_session_id}"))
}
/// The roster row rewrite of an offline rename (TS `writeRosterEntry`
diff --git a/crates/pa-daemon/src/session_custom.rs b/crates/pa-daemon/src/session_custom.rs
index 01885b4d7f..b587898b2b 100644
--- a/crates/pa-daemon/src/session_custom.rs
+++ b/crates/pa-daemon/src/session_custom.rs
@@ -381,6 +381,12 @@ mod tests {
use std::sync::Arc;
async fn created_worker() -> Arc<Worker> {
+ created_worker_named(Some("custom")).await
+ }
+
+ /// The worker fixture over an optional create name: a `None` create
+ /// leaves the session without a `session_info` name row.
+ async fn created_worker_named(name: Option<&str>) -> Arc<Worker> {
let dir = std::env::temp_dir().join(format!("pa-worker-sc-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let config = crate::worker::WorkerConfig {
@@ -395,12 +401,11 @@ mod tests {
script: Some(json!({ "responses": ["ack"] })),
};
let worker = Arc::new(Worker::new(config, None));
- let created = worker
- .dispatch(
- "create",
- &json!({ "noSession": true, "cwd": "/tmp", "name": "custom" }),
- )
- .await;
+ let mut create = json!({ "noSession": true, "cwd": "/tmp" });
+ if let Some(name) = name {
+ create["name"] = json!(name);
+ }
+ let created = worker.dispatch("create", &create).await;
assert!(created.success, "create failed: {created:?}");
worker
}
@@ -465,6 +470,57 @@ mod tests {
}
}
+ /// TS #2529 `applyStateSessionName`: a rename that changed an existing
+ /// name leaves the displayed `session_renamed` notice (with the
+ /// ` by parent` suffix when the rename is parent-directed); a first
+ /// name, or a rename that keeps the name, leaves none.
+ #[tokio::test]
+ async fn rename_leaves_a_displayed_notice_only_when_a_name_changed() {
+ let worker = created_worker_named(None).await;
+ // A first name leaves no notice (there was no previous name).
+ let response = worker.handle_rename("rename", &json!({ "name": "first" }));
+ assert!(response.success, "rename failed: {response:?}");
+ assert!(
+ custom_entries(&worker).is_empty(),
+ "a first name leaves no notice"
+ );
+
+ // A parent-directed rename of the existing name leaves the
+ // displayed notice with the parent suffix.
+ let response = worker.handle_rename(
+ "rename",
+ &json!({ "name": "bench-runner", "renamedBy": "parent" }),
+ );
+ assert!(response.success, "rename failed: {response:?}");
+ let rows = custom_entries(&worker);
+ assert_eq!(rows.len(), 1, "one notice row: {rows:?}");
+ assert_eq!(rows[0].0, "session_renamed");
+ assert_eq!(
+ rows[0].1,
+ json!("Session renamed `first` -> `bench-runner` by parent")
+ );
+ let display = {
+ let core = worker.core.lock().unwrap();
+ core.store.as_ref().and_then(|store| {
+ store
+ .entries()
+ .iter()
+ .find(|entry| entry.type_ == "custom_message")
+ .and_then(|entry| entry.fields.get("display").cloned())
+ })
+ };
+ assert_eq!(display, Some(json!(true)), "the notice is displayed");
+
+ // A rename that does not change the name leaves nothing new.
+ let response = worker.handle_rename("rename", &json!({ "name": "bench-runner" }));
+ assert!(response.success, "rename failed: {response:?}");
+ assert_eq!(
+ custom_entries(&worker).len(),
+ 1,
+ "an unchanged name leaves no second notice"
+ );
+ }
+
/// `restore_next_turn` parks the rows and the next delivered turn
/// replays them first (TS `prefixMessages` order).
#[tokio::test]
diff --git a/crates/pa-daemon/src/supervisor/routing.rs b/crates/pa-daemon/src/supervisor/routing.rs
index 8da3f72886..8da2b5c339 100644
--- a/crates/pa-daemon/src/supervisor/routing.rs
+++ b/crates/pa-daemon/src/supervisor/routing.rs
@@ -448,7 +448,10 @@ impl Supervisor {
// wakes it (reuse a resident host, otherwise launch
// a fresh worker over the file — TS's tier-2
// relaunch); a delete's kill marker resolves the
- // ledger edge and tombstones without a worker.
+ // ledger edge and tombstones without a worker. A
+ // parent-directed rename must hydrate its target
+ // the same way (TS `renameAgentFamilySession`
+ // resolves through the hydrated target).
if matches!(
command,
DaemonCommand::Prompt { .. }
@@ -457,6 +460,7 @@ impl Supervisor {
| DaemonCommand::FollowUp { .. }
| DaemonCommand::Attach { .. }
| DaemonCommand::Reattach { .. }
+ | DaemonCommand::Rename { .. }
| DaemonCommand::WaitForIdle { .. }
) {
match self.wake_saved_session(&selector).await {
@@ -708,9 +712,34 @@ impl Supervisor {
DaemonCommand::Kill { .. } => RouteAdmission::SupervisorInternal,
_ => RouteAdmission::ClientRequest,
};
- let response = self
- .route_command_ready(&resident, worker_command, payload, timeout, admission)
- .await;
+ // TS daemon-supervisor's `routeClientCommand` wraps the live
+ // `rename`/`set_session_name` forward in the name-reservation
+ // ladder: name uniqueness is daemon-owned, so a session worker's
+ // own rename can never mint a duplicate sibling name.
+ let response = match command {
+ DaemonCommand::Rename { name, .. } | DaemonCommand::SetSessionName { name, .. } => {
+ match self.live_session_name_scope(&resident.worker_id, name.trim().to_string()) {
+ Ok(scope) => self
+ .with_session_name_reservation(
+ &scope,
+ self.route_command_ready(
+ &resident,
+ worker_command,
+ payload,
+ timeout,
+ admission,
+ ),
+ )
+ .await
+ .unwrap_or_else(|error| Err(anyhow!(error))),
+ Err(error) => Err(anyhow!(error)),
+ }
+ }
+ _ => {
+ self.route_command_ready(&resident, worker_command, payload, timeout, admission)
+ .await
+ }
+ };
// The byte relay: a routed response the supervisor neither edits nor
// inspects goes to the client as the worker's own payload bytes with
// the client's command id spliced in front. The worker serializes
@@ -721,9 +750,10 @@ impl Supervisor {
// The typed path stays for every response this arm edits or reads
// beyond the frame header's hints: the chunked-snapshot attach
// clients, a rebound reattach (command echo rewrite), and the
- // small-payload bookkeeping commands (detach, kill, rename, the
- // promote-owned catalog forms). An attach-family relay also needs
- // the frame header's success/activeSessionId hints for the
+ // small-payload bookkeeping commands (detach, kill, rename,
+ // set_session_name, the promote-owned catalog forms). An
+ // attach-family relay also needs the frame header's
+ // success/activeSessionId hints for the
// supervisor's own bookkeeping; a hint-less one falls back to the
// typed parse so the bookkeeping never silently changes shape.
let client_wants_chunked = match command {
@@ -744,6 +774,7 @@ impl Supervisor {
DaemonCommand::Detach { .. }
| DaemonCommand::Kill { .. }
| DaemonCommand::Rename { .. }
+ | DaemonCommand::SetSessionName { .. }
| DaemonCommand::CronAdd {
promote_owned_session: Some(true),
..
@@ -924,9 +955,14 @@ impl Supervisor {
}
}
}
- if let DaemonCommand::Rename { name, .. } = command {
+ if let DaemonCommand::Rename { name, .. }
+ | DaemonCommand::SetSessionName { name, .. } = command
+ {
// A subagent rename is durable in the ledger, so the
// passive roster keeps the new name after passivation.
+ // The TS worker appends it in `applyStateSessionName`
+ // for both commands; the Rust port keeps the one
+ // supervisor-side block.
if response.success {
let descriptor = resident.descriptor.lock().await;
let is_child = descriptor
diff --git a/crates/pa-daemon/src/supervisor/tests.rs b/crates/pa-daemon/src/supervisor/tests.rs
index ba81ea5543..f64bd0010d 100644
--- a/crates/pa-daemon/src/supervisor/tests.rs
+++ b/crates/pa-daemon/src/supervisor/tests.rs
@@ -1,5 +1,8 @@
use super::*;
+use proptest::prelude::*;
+use proptest::test_runner::RngSeed;
+
/// The cargo test config sets `DO_NOT_TRACK=1`; the daemon's live
/// recording gate reads it (env before settings). Tests that exercise
/// gated daemon-event paths hold this guard while the three override
@@ -1984,3 +1987,97 @@ async fn off_window_daemon_events_never_count_into_the_summary() {
"the off-window attach never counts"
);
}
+
+proptest! {
+ #![proptest_config(ProptestConfig {
+ cases: 64,
+ rng_seed: RngSeed::Fixed(0x1145_2f6a),
+ ..ProptestConfig::default()
+ })]
+
+ // The live rename ladder: TS `routeClientCommand` wraps the forward in the name reservation.
+ #[test]
+ fn live_renames_reserve_family_names(
+ rows in prop::collection::vec(
+ (prop::sample::select(vec!["delta", "kilo"]), 0u32..=2, 0u8..=1),
+ 1..=4,
+ ),
+ (requested, pad) in (prop::sample::select(vec!["delta", "kilo"]), any::<bool>()),
+ kind in prop::sample::select(vec!["rename", "set_session_name"]),
+ pre_reserved in prop::bool::weighted(0.25),
+ ) {
+ let requested = if pad { format!(" {requested} ") } else { requested.to_string() };
+ let trimmed = requested.trim();
+ let (_, target_depth, target_parent) = *rows.last().expect("the last row");
+ // TS sameAgentSessionNameParent: depth-0 rows share one scope.
+ let conflict = rows[..rows.len() - 1].iter().any(|(name, depth, parent)| {
+ *name == trimmed
+ && *depth == target_depth
+ && (target_depth == 0 || *parent == target_parent)
+ });
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("the per-case runtime");
+ runtime.block_on(async {
+ let dir = tempfile::TempDir::new().expect("case dir");
+ let agent_dir = dir.path().join("agent");
+ let sessions_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&sessions_dir).expect("sessions dir");
+ let parents = [sessions_dir.join("pa.jsonl"), sessions_dir.join("pb.jsonl")];
+ let options = SupervisorOptions { socket_path: dir.path().join("d.sock"), agent_dir };
+ let supervisor = Arc::new(Supervisor::new(options).expect("supervisor"));
+ let active = format!("r{}-live", rows.len() - 1);
+ for (index, (name, depth, parent)) in rows.iter().enumerate() {
+ let summary = json!({
+ "sessionId": format!("r{index}"), "activeSessionId": format!("r{index}-live"),
+ "runtimeKind": "subagent", "rlmDepth": depth, "sessionName": name,
+ "parentSessionPath": parents[*parent as usize].to_string_lossy(),
+ });
+ supervisor.write_roster_summary(&summary, Some(format!("r{index}-live").as_str()));
+ }
+ let descriptor = serde_json::from_value::<DaemonWorkerDescriptor>(json!({
+ "version": 2, "workerId": &active, "pid": 4242, "socketPath": "/tmp/none.sock",
+ "recoveryJournalPath": "/tmp/none.jsonl", "supervisorSocketPath": "/tmp/none.sock",
+ "authenticationToken": "token", "rootActiveSessionId": &active, "createdAt": "t",
+ "updatedAt": "t", "lifecycle": "ready", "createCommand": {},
+ "consecutiveFailures": 0,
+ }))
+ .expect("descriptor");
+ let resident = ResidentWorker::new(active.clone(), descriptor, PathBuf::from("none"));
+ supervisor.registry.insert(resident.clone()).await;
+ // Retired: a forward past the ladder fails fast with WORKER_NOT_CONNECTED.
+ resident.note_retired();
+ let pre_key = pre_reserved.then(|| {
+ let scope = supervisor
+ .live_session_name_scope(&active, trimmed.into())
+ .expect("the target's own roster row");
+ let key = reservation_key(&scope);
+ supervisor.pending_session_names.lock().unwrap().insert(key.clone());
+ key
+ });
+ let command: DaemonCommand = serde_json::from_value(
+ json!({"type": kind, "activeSessionId": &active, "name": &requested}),
+ )
+ .expect("command");
+ let (queue_tx, _queue_rx) = tokio::sync::mpsc::channel(4);
+ let attached = subscribers::ClientSubscriptions::new("conn".to_string(), queue_tx);
+ let type_name = command_type_name(&command).to_string();
+ let (lines, stop) = supervisor
+ .route_client_command(&command, "client", &attached, "c1".into(), type_name, None)
+ .await;
+ prop_assert!(!stop);
+ prop_assert_eq!(&lines[0]["success"], &json!(false));
+ let expected = if conflict || pre_key.is_some() {
+ format!("Agent name \"{trimmed}\" is unavailable: an agent of that name already exists at depth {target_depth} under this parent")
+ } else {
+ WORKER_NOT_CONNECTED.to_string()
+ };
+ prop_assert_eq!(lines[0]["error"].as_str(), Some(expected.as_str()));
+ let pending = supervisor.pending_session_names.lock().unwrap().clone();
+ let expected_pending: std::collections::HashSet<String> = pre_key.into_iter().collect();
+ prop_assert_eq!(pending, expected_pending);
+ Ok(())
+ })?;
+ }
+}
diff --git a/crates/pa-daemon/src/worker.rs b/crates/pa-daemon/src/worker.rs
index 0f807d1a52..15fdb2e294 100644
--- a/crates/pa-daemon/src/worker.rs
+++ b/crates/pa-daemon/src/worker.rs
@@ -44,8 +44,8 @@ use create::{active_session_id_of, worker_server_capabilities};
// does not use it), so the unused-import lint is allowed deliberately here.
#[allow(unused_imports)]
pub(crate) use summary::{
- compact_action_label, emit_worker_event_with, push_roster_delta, session_snapshot,
- session_summary, RosterPushContext,
+ compact_action_label, emit_worker_event_with, persist_custom_row, push_roster_delta,
+ session_snapshot, session_summary, RosterPushContext,
};
use turn::TurnRunner;
diff --git a/crates/pa-daemon/src/worker/commands.rs b/crates/pa-daemon/src/worker/commands.rs
index ac0cbc9fbd..ef81d35460 100644
--- a/crates/pa-daemon/src/worker/commands.rs
+++ b/crates/pa-daemon/src/worker/commands.rs
@@ -1,9 +1,9 @@
//! The dispatch surface: command routing, the command handlers,
//! and the abort family.
use super::{
- json, response_failure, response_success, KillCloseReason, Lane, QueueCheckpoint, QueuedItem,
- Result, SessionFile, TurnSettle, VecDeque, Worker, PROMPT_ABORTED_BEFORE_DELIVERY,
- SIDE_QUESTION_SETTLE_TIMEOUT,
+ json, persist_custom_row, response_failure, response_success, KillCloseReason, Lane,
+ QueueCheckpoint, QueuedItem, Result, SessionFile, TurnSettle, VecDeque, Worker,
+ PROMPT_ABORTED_BEFORE_DELIVERY, SIDE_QUESTION_SETTLE_TIMEOUT,
};
use serde_json::Value;
@@ -802,12 +802,48 @@ impl Worker {
return response_failure(None, command, "Session name cannot be empty", None);
}
let mut core = self.core.lock().unwrap();
+ let previous = core
+ .store
+ .as_ref()
+ .and_then(|store| store.session_name().map(str::to_string));
if let Some(store) = core.store.as_mut() {
if let Err(error) = store.persist_entry("session_info", json!({ "name": name })) {
return response_failure(None, command, &error.to_string(), None);
}
}
let summary = self.summary_locked(&core);
+ // TS #2529 `applyStateSessionName`: a rename that changed an
+ // existing name leaves the renamed session a displayed transcript
+ // notice (" by parent" when the rename arrived from the parent
+ // session); a first name leaves none. The notice's durable row
+ // lands under the SAME core lock as the name write — worker
+ // commands run concurrently, so a second lock scope here could
+ // interleave another command's writes between the name and its
+ // notice, ordering the notice against a contradicted name history.
+ // The broadcast (the client frames) runs after the lock drops, in
+ // the `session_info_changed` order TS emits.
+ let renamed_notice = previous
+ .as_deref()
+ .filter(|previous| *previous != name)
+ .map(|previous| {
+ let content = if payload.get("renamedBy").and_then(Value::as_str)
+ == Some(
+ pa_core::session_engine::agent_messaging::AgentFamilyRelationship::Parent
+ .as_str(),
+ ) {
+ format!("Session renamed `{previous}` -> `{name}` by parent")
+ } else {
+ format!("Session renamed `{previous}` -> `{name}`")
+ };
+ json!({
+ "customType": pa_core::session_engine::messages::SESSION_RENAMED_CUSTOM_TYPE,
+ "content": content,
+ "display": true,
+ })
+ });
+ if let Some(notice) = renamed_notice.as_ref() {
+ persist_custom_row(&mut core, notice);
+ }
drop(core);
// TS `session.setSessionName` emits `session_info_changed` so every
// attached client re-reads the name (the interactive mode patches
@@ -820,6 +856,9 @@ impl Worker {
if let Ok(summary_value) = serde_json::to_value(&summary) {
self.engine.set_session_summary(summary_value);
}
+ if let Some(notice) = renamed_notice.as_ref() {
+ self.broadcast_custom_row(notice);
+ }
response_success(
None,
command,
diff --git a/crates/pa-daemon/src/worker/summary.rs b/crates/pa-daemon/src/worker/summary.rs
index 5731b332a0..99d807b563 100644
--- a/crates/pa-daemon/src/worker/summary.rs
+++ b/crates/pa-daemon/src/worker/summary.rs
@@ -170,18 +170,16 @@ impl Worker {
pub(crate) fn emit_custom_row(&self, message: &Value) {
{
let mut core = self.core.lock().unwrap();
- if let Some(store) = core.store.as_mut() {
- let _ = store.persist_entry(
- "custom_message",
- json!({
- "customType": message.get("customType").cloned().unwrap_or(Value::Null),
- "content": message.get("content").cloned().unwrap_or(Value::Null),
- "display": message.get("display").cloned().unwrap_or(Value::Bool(true)),
- "details": message.get("details").cloned().unwrap_or(Value::Null),
- }),
- );
- }
+ persist_custom_row(&mut core, message);
}
+ self.broadcast_custom_row(message);
+ }
+
+ /// Broadcast one recorded custom row's `message_start`/`message_end`
+ /// pair (the frames attached clients render for it). Runs OUTSIDE
+ /// the `core` lock: a caller that persisted the row under its own
+ /// lock scope broadcasts after releasing it.
+ pub(crate) fn broadcast_custom_row(&self, message: &Value) {
self.emit_worker_event(json!({ "type": "message_start", "message": message }));
self.emit_worker_event(json!({ "type": "message_end", "message": message }));
}
@@ -242,6 +240,30 @@ impl Worker {
}
}
+/// The durable half of [`Worker::emit_custom_row`]: append one custom
+/// row's `custom_message` entry while the CALLER holds the `core` lock,
+/// so a row tied to another locked write (the rename's notice, whose
+/// `session_info` name write it must not interleave with under
+/// concurrent worker commands) lands inside the caller's own lock scope.
+/// The persist error is display-row policy shared by every caller: the
+/// row is advisory, so the failure is swallowed, never the caller's.
+pub(crate) fn persist_custom_row(
+ core: &mut std::sync::MutexGuard<'_, SessionCore>,
+ message: &Value,
+) {
+ if let Some(store) = core.store.as_mut() {
+ let _ = store.persist_entry(
+ "custom_message",
+ json!({
+ "customType": message.get("customType").cloned().unwrap_or(Value::Null),
+ "content": message.get("content").cloned().unwrap_or(Value::Null),
+ "display": message.get("display").cloned().unwrap_or(Value::Bool(true)),
+ "details": message.get("details").cloned().unwrap_or(Value::Null),
+ }),
+ );
+ }
+}
+
pub(crate) fn emit_worker_event_with(
core: &Arc<Mutex<SessionCore>>,
events: &Arc<EventPump>,
diff --git a/crates/pa-daemon/tests/agent_family_e2e.rs b/crates/pa-daemon/tests/agent_family_e2e.rs
index 82d74d3596..651dd23722 100644
--- a/crates/pa-daemon/tests/agent_family_e2e.rs
+++ b/crates/pa-daemon/tests/agent_family_e2e.rs
@@ -1268,3 +1268,170 @@ async fn family_edges_never_cross_families_end_to_end() {
"a subagent of ANOTHER parent never renders as this session's child: {parent_messages}"
);
}
+
+/// Verifier (TS #2529): a parent renames one of its direct children
+/// through the real kernel host handler (`rlm.rename` with the spawn
+/// handle's child id) — the same handler map the parent's kernel
+/// dispatches into. The supervisor's reservation ladder admits the
+/// unique name, the child worker persists it and leaves the
+/// ` by parent` transcript notice, the child's RLM ledger edge carries
+/// the new name, and the parent-side selectors stop matching the old
+/// name (`rlm.collect` by the old name fails, the new name hits).
+#[tokio::test]
+async fn parent_renames_a_child_end_to_end() {
+ let Some(kernel_python) = kernel_python() else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("daemon.sock");
+ let agent_dir = dir.path().join("agent");
+ let sessions_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&sessions_dir).expect("sessions dir");
+
+ // The parent absorbs turns; the child only runs its spawn turn.
+ let parent_script = write_faux_script(
+ dir.path(),
+ "parent",
+ &json!([{ "text": "parent turn done" }]),
+ );
+ let child_script = write_faux_script(dir.path(), "child", &json!([{ "text": "kid spawned" }]));
+
+ let _daemon = spawn_supervisor(&socket, &agent_dir, &kernel_python);
+ wait_socket_ready(&socket);
+ let (mut client, hello) = Client::connect(&socket);
+ assert_eq!(hello["type"], "daemon_hello");
+
+ client.send_command(
+ "create-parent",
+ &json!({
+ "type": "create",
+ "name": "parent",
+ "config": {
+ "cwd": dir.path().to_string_lossy(),
+ "sessionDir": sessions_dir.to_string_lossy(),
+ "script": parent_script.to_string_lossy(),
+ },
+ }),
+ );
+ let created = client.read_response("create-parent");
+ assert_eq!(created["success"], true, "create parent failed: {created}");
+ let parent = &created["data"];
+ let parent_active_session_id = parent["activeSessionId"]
+ .as_str()
+ .or_else(|| parent["id"].as_str())
+ .expect("parent active session id")
+ .to_string();
+ let parent_session_id = parent["sessionId"].as_str().expect("parent session id");
+ let parent_session_file = parent["sessionFile"]
+ .as_str()
+ .expect("parent session file")
+ .to_string();
+
+ let children = SupervisorChildSessions::new(
+ Arc::new(SupervisorLink::new(socket.clone())),
+ agent_dir.clone(),
+ parent_active_session_id.clone(),
+ std::sync::Arc::new(pa_daemon::model_allowlist::ModelRefusalTelemetry::new(
+ agent_dir.clone(),
+ /*telemetry_disabled*/ true,
+ )),
+ );
+ children.set_identity(ParentIdentity {
+ rlm_depth: 0,
+ rlm_max_depth: 2,
+ model: Some("faux/faux-1".to_string()),
+ cwd: Some(dir.path().to_string_lossy().to_string()),
+ session_id: Some(parent_session_id.to_string()),
+ session_file: Some(parent_session_file.clone()),
+ thinking: None,
+ child_script: Some(child_script.to_string_lossy().to_string()),
+ });
+ let handle = children
+ .spawn(RlmSpawnRequest {
+ prompt: "work on the lane".to_string(),
+ name: Some("kid".to_string()),
+ model: None,
+ thinking: None,
+ spawned_by_request_id: None,
+ cell_source_code: None,
+ })
+ .await
+ .expect("spawn the child");
+ assert_eq!(handle.name, "kid");
+ children.notify_turn_done();
+ // Wait for the spawn turn to settle (bounded), then read the roster's
+ // live/persisted child ids.
+ let settle_deadline = Instant::now() + Duration::from_secs(60);
+ loop {
+ let roster = children.list_subagents().await.expect("child roster");
+ let row = roster.first().expect("one child row");
+ if row.status == "completed" || row.status == "error" {
+ assert_eq!(row.status, "completed", "spawn turn: {row:?}");
+ break;
+ }
+ assert!(
+ Instant::now() < settle_deadline,
+ "kid spawn turn never settled: {row:?}; daemon log tail: {}",
+ daemon_log_tail(&dir.path().join("receipts"))
+ );
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ let roster = children.list_subagents().await.expect("child roster");
+ let child_row = roster.first().expect("one child row");
+ let child_active_session_id = child_row
+ .active_session_id
+ .clone()
+ .expect("child active session id");
+
+ // The parent-side kernel host surface over the same registry (the
+ // wiring the parent worker's engine performs): the rename dispatches
+ // through the REAL `rlm.rename` handler, with the spawn handle's
+ // child id as the selector.
+ let children = Arc::new(children);
+ let wiring = pa_core::session_engine::runtime_wiring::wire_session_runtime(
+ pa_core::session::manager::SessionManager::in_memory(dir.path()),
+ dir.path(),
+ pa_core::session_engine::runtime_wiring::RlmWiring {
+ model_registry: None,
+ subagent_host: Some(Arc::clone(&children) as Arc<dyn RlmSubagentHost>),
+ },
+ None,
+ None,
+ );
+ let rename = wiring
+ .handlers
+ .get("rlm.rename")
+ .expect("rlm.rename handler registered")
+ .clone();
+ let reply = rename(HostRequestPayload {
+ data: json!({
+ "name": " bench-runner ",
+ "session_id": handle.rlm_child_id,
+ }),
+ cell_source_code: None,
+ })
+ .await
+ .expect("the rename dispatch");
+ assert_eq!(reply, json!({ "name": "bench-runner" }));
+
+ // The child's transcript carries the parent-directed notice.
+ client.wait_idle("w-child-rename", &child_active_session_id);
+ let child_messages = client.messages("gm-child-rename", &child_active_session_id);
+ assert!(
+ child_messages
+ .matches("Session renamed `kid` -> `bench-runner` by parent")
+ .count()
+ >= 1,
+ "the renamed session sees the notice: {child_messages}"
+ );
+
+ // The child's RLM ledger edge carries the new name (the passive roster
+ // keeps it after passivation).
+ let ledger = pa_daemon::rlm_ledger::RlmSpawnLedger::new(&agent_dir, &sessions_dir, |_| {});
+ let edges = ledger.edges(true).expect("ledger edges");
+ let edge = edges
+ .iter()
+ .find(|edge| edge.child_id == handle.rlm_child_id)
+ .expect("the child's ledger edge");
+ assert_eq!(edge.name, "bench-runner", "the ledger rename landed");
+}
diff --git a/crates/pa-daemon/tests/idle_passivation_e2e.rs b/crates/pa-daemon/tests/idle_passivation_e2e.rs
index 770a56ec63..b354c5863a 100644
--- a/crates/pa-daemon/tests/idle_passivation_e2e.rs
+++ b/crates/pa-daemon/tests/idle_passivation_e2e.rs
@@ -487,6 +487,302 @@ async fn a_settled_child_passivates_stays_listable_and_revives_by_agent_message(
}
}
+/// The root active ids of the persisted worker descriptors (the
+/// descriptor file's stem is the worker's active session id).
+fn root_worker_ids(agent_dir: &Path) -> Vec<String> {
+ let mut ids = Vec::new();
+ let Ok(instances) = std::fs::read_dir(agent_dir.join("daemon-workers")) else {
+ return ids;
+ };
+ for instance in instances.flatten() {
+ let Ok(entries) = std::fs::read_dir(instance.path()) else {
+ continue;
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
+ continue;
+ }
+ let Ok(content) = std::fs::read_to_string(&path) else {
+ continue;
+ };
+ let Ok(descriptor) = serde_json::from_str::<Value>(&content) else {
+ continue;
+ };
+ if let Some(id) = descriptor
+ .get("rootActiveSessionId")
+ .and_then(Value::as_str)
+ .filter(|id| !id.is_empty())
+ {
+ ids.push(id.to_string());
+ }
+ }
+ }
+ ids.sort();
+ ids
+}
+
+/// The rename arm of the passivation-aware wake (TS
+/// `renameAgentFamilySession` resolving through the hydrated target):
+/// the parent record keeps the child's SPAWN-time active id, a revival
+/// re-keys the supervisor roster's child row to the revived worker's
+/// fresh id (the registration's roster write drops the old id's index),
+/// and the revived worker's own idle passivation stops it again — after
+/// which the parent's rename, addressed by the record's stale id,
+/// resolves NOWHERE (no live resident for the binding, no roster row,
+/// no ledger edge: only the child's DURABLE id still names the session).
+/// The rename must reach the child through the same durable-selector
+/// wake retry `prompt_child` carries: the retry's wake launches a fresh
+/// worker over the child's session file and the rename lands there.
+#[tokio::test]
+async fn a_parent_rename_after_a_revival_and_second_passivation_reaches_the_child() {
+ let Some(kernel_python) = kernel_python() else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("daemon.sock");
+ let agent_dir = dir.path().join("agent");
+ let sessions_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&sessions_dir).expect("sessions dir");
+ std::fs::write(
+ agent_dir.join("settings.json"),
+ json!({ "idleEvictionMinutes": 1 }).to_string(),
+ )
+ .expect("write settings");
+ let parent_script = write_faux_script(
+ dir.path(),
+ "rename-parent",
+ &json!([{ "text": "parent turn done" }]),
+ );
+ let child_script = write_faux_script(
+ dir.path(),
+ "rename-child",
+ &json!([{ "text": "child done" }]),
+ );
+
+ let _daemon = spawn_supervisor(&socket, &agent_dir, &kernel_python);
+ wait_socket_ready(&socket);
+ let (mut client, hello) = Client::connect(&socket);
+ assert_eq!(hello["type"], "daemon_hello");
+ client.send_command(
+ "create-parent",
+ &json!({
+ "type": "create",
+ "name": "parent",
+ "config": {
+ "cwd": dir.path().to_string_lossy(),
+ "sessionDir": sessions_dir.to_string_lossy(),
+ "script": parent_script.to_string_lossy(),
+ },
+ }),
+ );
+ let created = client.read_response("create-parent");
+ assert_eq!(created["success"], true, "create parent failed: {created}");
+ let parent = &created["data"];
+ let parent_active_session_id = parent["activeSessionId"]
+ .as_str()
+ .or_else(|| parent["id"].as_str())
+ .expect("parent active session id")
+ .to_string();
+ let parent_session_id = parent["sessionId"].as_str().expect("parent session id");
+ let parent_session_file = parent["sessionFile"]
+ .as_str()
+ .expect("parent session file")
+ .to_string();
+
+ let link = Arc::new(SupervisorLink::new(socket.clone()));
+ let children = SupervisorChildSessions::new(
+ Arc::clone(&link),
+ agent_dir.clone(),
+ parent_active_session_id.clone(),
+ std::sync::Arc::new(pa_daemon::model_allowlist::ModelRefusalTelemetry::new(
+ agent_dir.clone(),
+ /*telemetry_disabled*/ true,
+ )),
+ );
+ children.set_identity(ParentIdentity {
+ rlm_depth: 0,
+ rlm_max_depth: 2,
+ model: Some("faux/faux-1".to_string()),
+ cwd: Some(dir.path().to_string_lossy().to_string()),
+ session_id: Some(parent_session_id.to_string()),
+ session_file: Some(parent_session_file),
+ thinking: None,
+ child_script: Some(child_script.to_string_lossy().to_string()),
+ });
+ let handle = children
+ .spawn(RlmSpawnRequest {
+ prompt: "work on the lane".to_string(),
+ name: Some("parked-kid".to_string()),
+ model: None,
+ thinking: None,
+ cell_source_code: None,
+ spawned_by_request_id: None,
+ })
+ .await
+ .expect("spawn the child");
+ children.notify_turn_done();
+
+ // The child settles done with a resident worker.
+ let deadline = Instant::now() + Duration::from_secs(30);
+ let child_active_session_id = loop {
+ let roster = children.list_subagents().await.expect("child roster");
+ if let Some(row) = roster.first() {
+ if row.status == "done" || row.status == "completed" {
+ break row
+ .active_session_id
+ .clone()
+ .expect("the settled child's live id");
+ }
+ }
+ assert!(Instant::now() < deadline, "the child never settled done");
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ };
+ let (child_session_id, child_session_dir) = {
+ let row = children
+ .list_subagents()
+ .await
+ .expect("roster for the file")
+ .pop()
+ .expect("the child row");
+ (
+ row.session_id.expect("the child's durable session id"),
+ row.session_dir,
+ )
+ };
+ let child_file =
+ std::path::Path::new(&child_session_dir).join(format!("{child_session_id}.jsonl"));
+
+ // THE FIRST PASSIVATION (same ask as the settled-child test).
+ let child_token =
+ worker_token(&agent_dir, &child_active_session_id).expect("the child worker's token");
+ client.send_command(
+ "passivate-1",
+ &json!({
+ "type": "worker_idle_passivation",
+ "workerToken": child_token,
+ "idleMinutes": 1,
+ }),
+ );
+ let passivated = client.read_response("passivate-1");
+ assert_eq!(
+ passivated["success"], true,
+ "the first idle passivation must succeed: {passivated}"
+ );
+
+ // THE REVIVAL: a fresh client attaches by the child's DURABLE session
+ // id (the TUI resume selector): the route's wake arm resolves the
+ // ledger edge and launches a fresh worker over the child's file, and
+ // the fresh worker's registration re-keys the roster's child row to
+ // its fresh active id — the spawn-time id the parent record keeps
+ // stops resolving from here on.
+ let (mut fresh, _hello) = Client::connect(&socket);
+ fresh.send_command(
+ "revive-attach",
+ &json!({ "type": "attach", "activeSessionId": child_session_id }),
+ );
+ let revived = fresh.read_response("revive-attach");
+ assert_eq!(
+ revived["success"], true,
+ "the attach by the durable id must wake the passivated child: {revived}"
+ );
+
+ // The fresh worker's identity (its descriptor's root active id is the
+ // new routing id the roster row now carries).
+ let deadline = Instant::now() + Duration::from_secs(30);
+ let revived_active_session_id = loop {
+ let ids = root_worker_ids(&agent_dir)
+ .into_iter()
+ .filter(|id| id != &child_active_session_id && id != &parent_active_session_id)
+ .collect::<Vec<_>>();
+ if let Some(id) = ids.first() {
+ break id.clone();
+ }
+ assert!(
+ Instant::now() < deadline,
+ "the revival never wrote a fresh worker descriptor (ids so far: {:?})",
+ root_worker_ids(&agent_dir)
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ };
+ let revived_token =
+ worker_token(&agent_dir, &revived_active_session_id).expect("the fresh worker's token");
+ let revived_pid =
+ worker_pid(&agent_dir, &revived_active_session_id).expect("the fresh worker's pid");
+
+ // THE SECOND PASSIVATION: the revived worker stops the same way, so
+ // the child is passive again — but its roster row is keyed by the
+ // REVIVED id, and the parent record still holds the spawn-time id.
+ client.send_command(
+ "passivate-2",
+ &json!({
+ "type": "worker_idle_passivation",
+ "workerToken": revived_token,
+ "idleMinutes": 1,
+ }),
+ );
+ let passivated = client.read_response("passivate-2");
+ assert_eq!(
+ passivated["success"], true,
+ "the second idle passivation must succeed: {passivated}"
+ );
+ let deadline = Instant::now() + Duration::from_secs(60);
+ while std::path::Path::new(&format!("/proc/{revived_pid}")).exists() {
+ assert!(
+ Instant::now() < deadline,
+ "the revived worker survived the second passivation"
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+
+ // THE RENAME: the parent's rename by the child handle resolves the
+ // record's spawn-time active id — the stale id that no longer
+ // routes. The durable-selector wake retry must land the rename on a
+ // fresh worker over the child's session file.
+ let renamed = children
+ .rename(
+ "renamed-lane".to_string(),
+ Some(handle.rlm_child_id.clone()),
+ )
+ .await;
+ let applied = renamed.unwrap_or_else(|error| {
+ panic!(
+ "the parent rename of the twice-passivated child must reach it through the durable wake: {error:#}"
+ )
+ });
+ assert_eq!(applied, "renamed-lane");
+
+ // The durable oracle: the child's session file carries the new name's
+ // `session_info` row (only a woken worker writes it), and the
+ // parent's registry row follows the applied name.
+ let entries = std::fs::read_to_string(&child_file).unwrap_or_default();
+ let named = entries
+ .lines()
+ .filter_map(|line| serde_json::from_str::<Value>(line).ok())
+ .any(|entry| {
+ entry.get("type").and_then(Value::as_str) == Some("session_info")
+ && entry.get("name").and_then(Value::as_str) == Some("renamed-lane")
+ });
+ assert!(
+ named,
+ "the woken child must carry the renamed session_info row (tail: {:?})",
+ entries
+ .lines()
+ .rev()
+ .take(3)
+ .collect::<Vec<_>>()
+ .join(" | ")
+ );
+ let row = children
+ .list_subagents()
+ .await
+ .expect("roster after the rename")
+ .into_iter()
+ .find(|row| row.rlm_child_id == handle.rlm_child_id)
+ .expect("the child row after the rename");
+ assert_eq!(row.session_name, "renamed-lane");
+}
+
/// An idle unowned ROOT passivates through the same worker-driven ask
/// (TS `canEvictWorker` reaches roots and children alike) and resumes
/// by its durable session id: the attach wakes a fresh worker over the
diff --git a/crates/pa-tui/src/agents_view/rename.rs b/crates/pa-tui/src/agents_view/rename.rs
index 03f84bb647..acf871d1c8 100644
--- a/crates/pa-tui/src/agents_view/rename.rs
+++ b/crates/pa-tui/src/agents_view/rename.rs
@@ -38,14 +38,14 @@ pub(super) enum RenameTarget {
impl AgentsViewMode {
/// The selected row's rename target and name prefill (TS
- /// `enterRenameMode`'s gate, :1868-1888): a top-level agent row with
- /// a live session or a saved file. One definition of "renameable" —
- /// the enter arm and the hint slot both read it.
+ /// `enterRenameMode`'s gate, :1868-1888): an agent or subagent row
+ /// with a live session or a saved file. One definition of
+ /// "renameable" — the enter arm and the hint slot both read it.
pub(super) fn rename_target(&self) -> Option<(RenameTarget, String)> {
let row = self
.rows
.get(self.selected)
- .filter(|row| row.kind == RowKind::Agent)?;
+ .filter(|row| matches!(row.kind, RowKind::Agent | RowKind::Subagent))?;
let active = row
.summary
.get("activeSessionId")
@@ -82,12 +82,12 @@ impl AgentsViewMode {
/// preamble took it before the rename arm ran.
pub(super) fn enter_rename_mode(&mut self) {
let Some((target, name)) = self.rename_target() else {
- // An agent row with neither target reports (TS :1876-1878);
- // any other selection stays silent (:1871).
+ // An agent or subagent row with neither target reports (TS
+ // :1876-1878); any other selection stays silent (:1871).
if self
.rows
.get(self.selected)
- .is_some_and(|row| row.kind == RowKind::Agent)
+ .is_some_and(|row| matches!(row.kind, RowKind::Agent | RowKind::Subagent))
{
self.set_status("This session cannot be renamed");
}
@@ -208,6 +208,7 @@ pub(super) fn spawn_rename_dispatch(
id: None,
active_session_id: active_session_id.clone(),
name: rename.name.clone(),
+ renamed_by: None,
rest: serde_json::Map::default(),
},
// TS `renameDaemonSavedSession` in the view context sends
diff --git a/crates/pa-tui/src/agents_view/tests/key_bindings.rs b/crates/pa-tui/src/agents_view/tests/key_bindings.rs
index 5b7896344f..691b3b9314 100644
--- a/crates/pa-tui/src/agents_view/tests/key_bindings.rs
+++ b/crates/pa-tui/src/agents_view/tests/key_bindings.rs
@@ -171,8 +171,8 @@ fn program_key_shows_and_hides_the_spawn_program() {
/// the header and the save/cancel hint render, the prefill is the
/// session's name, the editing grammar matches the search field, Enter
/// submits the trimmed name with the live target, a large paste saves
-/// expanded, Esc exits with the query untouched, and a child row never
-/// enters.
+/// expanded, Esc exits with the query untouched, and a child row enters
+/// with its own live target.
#[test]
fn rename_key_composes_edits_and_dispatches() {
let mut mode = mode_with_parent_and_child();
@@ -261,15 +261,25 @@ fn rename_key_composes_edits_and_dispatches() {
mode.pending_rename.take().map(|rename| rename.name),
Some(pasted)
);
- // A subagent row never enters rename mode (TS :1871: only
- // top-level agents rename). Expand the list so the child row is
- // the selection's landing.
+ // A subagent row enters rename mode too (TS #2529: agent and
+ // subagent rows both carry a renameable session). Expand the list
+ // so the child row is the selection's landing.
mode.handle_key("down");
mode.handle_key("enter");
mode.handle_key("down");
assert_eq!(mode.rows[mode.selected].kind, RowKind::Subagent);
mode.handle_key("ctrl+r");
- assert!(matches!(mode.composer, Composer::Search));
+ let Composer::Rename(rename) = &mode.composer else {
+ panic!("the subagent row entered rename mode")
+ };
+ assert_eq!(
+ rename.target,
+ RenameTarget::Live {
+ active_session_id: "c-live".to_string()
+ },
+ "the child's live session is the rename target"
+ );
+ assert_eq!(rename.editor.get_text(), "worker one");
}
#[test]
diff --git a/crates/pa-types/src/daemon/command.rs b/crates/pa-types/src/daemon/command.rs
index b456ad540e..66f5f98131 100644
--- a/crates/pa-types/src/daemon/command.rs
+++ b/crates/pa-types/src/daemon/command.rs
@@ -329,6 +329,12 @@ pub enum DaemonCommand {
id: Option<String>,
active_session_id: String,
name: String,
+ /// Who directed the rename (`renamedBy` on the wire, TS
+ /// `AgentFamilyRelationship` — only `"parent"` is sent): set when a
+ /// parent session renames one of its direct children, so the
+ /// renamed session's transcript notice can name it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ renamed_by: Option<String>,
#[serde(flatten)]
rest: JsonMap,
},
diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.py
index 5181c950eb..a90756641d 100644
--- a/prime-agent-runtime/src/rlm/__init__.py
+++ b/prime-agent-runtime/src/rlm/__init__.py
@@ -336,8 +336,8 @@ async def list_subagents() -> list[RLMSubagent]:
return [_subagent_from_payload(entry) for entry in entries]
-def _collect_target_selector(target: Any) -> str:
- """Normalize a collect target: spawn handle, subagent row, or a name/id string."""
+def _collect_target_selector(target: Any, what: str = "collect target") -> str:
+ """Normalize a child selector: spawn handle, subagent row, or a name/id string."""
if isinstance(target, RLMSpawnHandle):
return target.rlm_child_id
if isinstance(target, RLMSubagent):
@@ -345,7 +345,7 @@ def _collect_target_selector(target: Any) -> str:
if isinstance(target, str) and target.strip():
return target.strip()
raise TypeError(
- f"collect target must be RLMSpawnHandle, RLMSubagent, or non-empty str, got {type(target).__name__}"
+ f"{what} must be RLMSpawnHandle, RLMSubagent, or non-empty str, got {type(target).__name__}"
)
@@ -487,6 +487,26 @@ async def delete_subagent(target: str | RLMSubagent | RLMSpawnHandle) -> RLMSuba
return _subagent_from_payload(payload.get("subagent"), "rlm.delete_subagent")
+async def rename(new_name: str, *, session_id: str | RLMSpawnHandle | RLMSubagent | None = None) -> str:
+ """Rename this session or one of its direct children.
+
+ Omitting ``session_id`` renames the current session. A spawn handle, a
+ ``list_subagents()`` row, or a session id string renames a direct child;
+ child names are rejected. Names follow spawn rules, must be unique among
+ siblings, and the renamed session sees a transcript notice.
+ """
+ if not isinstance(new_name, str):
+ raise TypeError(f"new_name must be str, got {type(new_name).__name__}")
+ payload: dict[str, Any] = {"name": new_name}
+ if session_id is not None:
+ payload["session_id"] = _collect_target_selector(session_id, "session_id")
+ reply = await host_request("rlm.rename", payload)
+ name = reply.get("name")
+ if not isinstance(name, str):
+ raise RuntimeError("rlm.rename returned an invalid name")
+ return name
+
+
class _HarnessProxy:
"""Resolve the harness state against the current environment on every access.
@@ -634,6 +654,14 @@ class _RLMNamespace:
async def delete_subagent(self, target: str | RLMSubagent | RLMSpawnHandle) -> RLMSubagent:
return await delete_subagent(target)
+ async def rename(
+ self,
+ new_name: str,
+ *,
+ session_id: str | RLMSpawnHandle | RLMSubagent | None = None,
+ ) -> str:
+ return await rename(new_name, session_id=session_id)
+
async def collect(self, targets: Any = None, *, timeout_ms: int = 0) -> list[RLMChildResult]:
return await collect(targets, timeout_ms=timeout_ms)
@@ -686,6 +714,7 @@ __all__ = [
"host_request",
"list_subagents",
"progress_note",
+ "rename",
"rlm",
"spawn",
]
diff --git a/prime-agent-runtime/test/test_subagent_registry.py b/prime-agent-runtime/test/test_subagent_registry.py
index e1553d794e..cd399a0d97 100644
--- a/prime-agent-runtime/test/test_subagent_registry.py
+++ b/prime-agent-runtime/test/test_subagent_registry.py
@@ -237,6 +237,27 @@ class RlmSubagentRegistryTest(unittest.TestCase):
with self.assertRaisesRegex(TypeError, "target must be RLMSpawnHandle, RLMSubagent, or str"):
asyncio.run(rlm_module.delete_subagent(123))
+ def test_rename_dispatches_self_and_child_selectors(self) -> None:
+ handle = rlm_module.RLMSpawnHandle(
+ rlm_child_id="sub-a1b2c3d4",
+ name="api-reviewer",
+ session_dir=Path("/tmp/parent/sub-a1b2c3d4"),
+ model="deepseek/deepseek-v4-flash",
+ )
+ for target, expected_selector in ((None, None), (handle, handle.rlm_child_id), (" session-child ", "session-child")):
+ host_request = AsyncMock(return_value={"name": "bench-runner"})
+ with patch.object(rlm_module, "host_request", host_request):
+ self.assertEqual(asyncio.run(rlm_module.rlm.rename("bench-runner", session_id=target)), "bench-runner")
+ expected = {"name": "bench-runner"}
+ if expected_selector is not None:
+ expected["session_id"] = expected_selector
+ host_request.assert_awaited_once_with("rlm.rename", expected)
+
+ with self.assertRaisesRegex(TypeError, "session_id must be"):
+ asyncio.run(rlm_module.rename("bench-runner", session_id=123))
+ with self.assertRaisesRegex(TypeError, "new_name must be str"):
+ asyncio.run(rlm_module.rename(5))
+
def test_rejects_invalid_registry_payload(self) -> None:
host_request = AsyncMock(return_value={"subagents": [{"status": "completed"}]})