Skip to content

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

Rust

rlm.spawn: start a child in a given cwd (#3849)

Sebastian Müllerc6d4da9421e6
diff --git a/.changes/spawn-cwd.md b/.changes/spawn-cwd.md
new file mode 100644
index 0000000000..3230a92700
--- /dev/null
+++ b/.changes/spawn-cwd.md
@@ -0,0 +1 @@
+- `rlm.spawn(..., cwd=...)` starts a subagent in another directory and loads that directory's `AGENTS.md` project context.
diff --git a/crates/pa-cli/src/print_rlm.rs b/crates/pa-cli/src/print_rlm.rs
index 4b71307fae..bdf4790ad6 100644
--- a/crates/pa-cli/src/print_rlm.rs
+++ b/crates/pa-cli/src/print_rlm.rs
@@ -39,7 +39,8 @@ use crate::print_runtime::{ChildEngineOverrides, ChildLane, FauxChildQueue, Head
/// Everything a spawned child inherits from the print invocation: the
/// invocation's own config (cwd, agent dir, prompt/skill paths) and the
-/// parsed faux script when the run is scripted.
+/// parsed faux script when the run is scripted. A child spawned with a
+/// `cwd` gets a copy carrying that cwd.
pub(crate) struct PrintRecipe {
pub options: crate::mode::RunOptions,
pub faux: Option<Value>,
@@ -638,7 +639,21 @@ impl RlmSubagentHost for InlineHost {
if node.depth >= node.max_depth {
return Err(rlm_depth_limit_error(node.depth, node.max_depth));
}
- let recipe = Arc::clone(&node.recipe);
+ let recipe = match request.cwd.as_deref() {
+ None => Arc::clone(&node.recipe),
+ Some(requested) => {
+ let mut options = node.recipe.options.clone();
+ options.config.cwd = pa_daemon::rlm_child_model::resolve_child_cwd(
+ &options.config.cwd,
+ Some(requested),
+ "rlm.spawn",
+ )?;
+ Arc::new(PrintRecipe {
+ options,
+ faux: node.recipe.faux.clone(),
+ })
+ }
+ };
let config = &recipe.options.config;
let child_id = format!("sub-{}", &uuid::Uuid::new_v4().simple().to_string()[..8]);
let name = request.name.clone().unwrap_or_else(|| {
@@ -1281,6 +1296,7 @@ mod tests {
name: Some("late".to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
});
diff --git a/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs b/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs
index a5e8295a87..9706c4295e 100644
--- a/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs
+++ b/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs
@@ -225,6 +225,7 @@ fn spawn_request(name: &str, prompt: &str) -> RlmSpawnRequest {
name: Some(name.to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
}
diff --git a/crates/pa-core/src/prompts/layers/core.md b/crates/pa-core/src/prompts/layers/core.md
index 68ac9d2a6a..c51a1628ae 100644
--- a/crates/pa-core/src/prompts/layers/core.md
+++ b/crates/pa-core/src/prompts/layers/core.md
@@ -30,7 +30,7 @@ prime-agent is a recursive harness. Each session builds a tree of agents, starti
The following programmatic tools are available in the REPL for subagent management:
-- `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
+- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None, cwd: 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; `cwd` starts the child in that directory (relative paths resolve against the session cwd; it must exist) and loads its project context; 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
- `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
- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`
- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handles
diff --git a/crates/pa-core/src/session_engine/rlm_host.rs b/crates/pa-core/src/session_engine/rlm_host.rs
index 0feedff1fb..ae64b06d88 100644
--- a/crates/pa-core/src/session_engine/rlm_host.rs
+++ b/crates/pa-core/src/session_engine/rlm_host.rs
@@ -143,6 +143,8 @@ pub struct RlmSpawnRequest {
pub model: Option<String>,
/// Validated thinking level; the host checks model support.
pub thinking: Option<String>,
+ /// Working directory; the host resolves relative paths against the session cwd.
+ pub cwd: Option<String>,
/// The parent's in-flight turn request the spawn anchors to (TS
/// `spawnedByRequestId`): `None` for a spawn outside an active run.
pub spawned_by_request_id: Option<String>,
@@ -660,7 +662,7 @@ fn spawn_request_from_payload(prompt: &str, data: &Value) -> anyhow::Result<RlmS
reject_unsupported_kwargs(
&kwargs,
OPERATION,
- &["name", "model", "thinking", "factory"],
+ &["name", "model", "thinking", "cwd", "factory"],
)?;
let name = optional_string_kwarg(&kwargs, "name", OPERATION)?;
let name = normalize_requested_rlm_subagent_session_name(name, OPERATION)?;
@@ -672,6 +674,7 @@ fn spawn_request_from_payload(prompt: &str, data: &Value) -> anyhow::Result<RlmS
let thinking = optional_string_kwarg(&kwargs, "thinking", OPERATION)?;
let thinking =
normalize_requested_rlm_subagent_thinking_level(thinking, OPERATION)?.map(String::from);
+ let cwd = cwd_kwarg(&kwargs, OPERATION)?;
let factory = match kwargs.get("factory") {
None | Some(Value::Null) => None,
Some(tag) => Some(serde_json::from_value(tag.clone()).map_err(|_| {
@@ -685,6 +688,7 @@ fn spawn_request_from_payload(prompt: &str, data: &Value) -> anyhow::Result<RlmS
name,
model,
thinking,
+ cwd,
spawned_by_request_id: None,
factory,
})
@@ -722,17 +726,7 @@ fn register_create_session(handlers: &mut HostRequestHandlers, bridge: &Arc<RlmH
let thinking =
normalize_requested_rlm_subagent_thinking_level(thinking, OPERATION)?
.map(String::from);
- let cwd = match kwargs.get("cwd") {
- None => None,
- Some(Value::String(cwd)) => {
- let cwd = cwd.trim();
- if cwd.is_empty() {
- anyhow::bail!("rlm.create_session cwd must be a non-empty string");
- }
- Some(cwd.to_string())
- }
- Some(_) => anyhow::bail!("rlm.create_session cwd must be a non-empty string"),
- };
+ let cwd = cwd_kwarg(&kwargs, OPERATION)?;
let handle = host
.create_session(RlmCreateSessionRequest {
prompt: prompt.to_string(),
@@ -882,6 +876,14 @@ fn optional_string_kwarg<'a>(
}
}
+fn cwd_kwarg(kwargs: &Map<String, Value>, operation: &str) -> anyhow::Result<Option<String>> {
+ match kwargs.get("cwd") {
+ None => Ok(None),
+ Some(Value::String(cwd)) if !cwd.trim().is_empty() => Ok(Some(cwd.trim().to_string())),
+ Some(_) => anyhow::bail!("{operation} cwd must be a non-empty string"),
+ }
+}
+
fn reject_unsupported_kwargs(
kwargs: &Map<String, Value>,
operation: &str,
@@ -1331,7 +1333,7 @@ mod tests {
"type": "rlm.run",
"prompt": "ship the lane",
"kwargs": {
- "name": "worker", "model": "p/m", "thinking": "High",
+ "name": "worker", "model": "p/m", "thinking": "High", "cwd": "lanes/a",
"factory": { "runId": "r1", "specId": "sw", "stateId": "build" },
}
}),
@@ -1353,6 +1355,7 @@ mod tests {
assert_eq!(requests[0].name.as_deref(), Some("worker"));
assert_eq!(requests[0].model.as_deref(), Some("p/m"));
assert_eq!(requests[0].thinking.as_deref(), Some("high"));
+ assert_eq!(requests[0].cwd.as_deref(), Some("lanes/a"));
assert_eq!(
requests[0].factory,
Some(RlmFactoryTag {
diff --git a/crates/pa-daemon/src/rlm_child_model.rs b/crates/pa-daemon/src/rlm_child_model.rs
index 4a3ebc8d7c..fa8a09ad46 100644
--- a/crates/pa-daemon/src/rlm_child_model.rs
+++ b/crates/pa-daemon/src/rlm_child_model.rs
@@ -1,7 +1,8 @@
//! RLM child model resolution and roster text helpers: reference resolution against the
-//! credential-backed catalog, the spawn-time thinking-support check, plus the roster text caps.
+//! credential-backed catalog, the spawn-time thinking-support check, the requested child cwd,
+//! plus the roster text caps.
-use std::path::Path;
+use std::path::{Path, PathBuf};
use anyhow::{anyhow, bail, Result};
use pa_ai::models::{get_supported_thinking_levels, thinking_level_from_str};
@@ -158,6 +159,27 @@ pub fn assert_thinking_supported(
);
}
+/// The directory a child starts in: a requested `cwd` resolves against the
+/// session cwd and is canonicalized (project-context discovery walks its
+/// ancestors), otherwise the child shares the session cwd.
+///
+/// # Errors
+/// Returns an error naming `operation` when the requested directory does not exist.
+pub fn resolve_child_cwd(
+ session_cwd: &Path,
+ requested: Option<&str>,
+ operation: &str,
+) -> Result<PathBuf> {
+ let Some(requested) = requested else {
+ return Ok(session_cwd.to_path_buf());
+ };
+ let joined = session_cwd.join(requested);
+ match joined.canonicalize() {
+ Ok(cwd) if cwd.is_dir() => Ok(cwd),
+ _ => bail!("{operation} cwd {} is not a directory", joined.display()),
+ }
+}
+
/// Rejection message for an unresolved model reference: the
/// unavailability, the selector form, and close matches for retry.
fn model_unavailable_error(
diff --git a/crates/pa-daemon/src/rlm_children.rs b/crates/pa-daemon/src/rlm_children.rs
index fb9585c962..ca566dba17 100644
--- a/crates/pa-daemon/src/rlm_children.rs
+++ b/crates/pa-daemon/src/rlm_children.rs
@@ -29,8 +29,8 @@ use pa_core::session_engine::rlm_host::{
};
use crate::rlm_child_model::{
- assert_thinking_supported, cap_text, compact_rlm_text, resolve_child_model, rlm_child_label,
- ANSWER_TEXT_MAX_CHARS,
+ assert_thinking_supported, cap_text, compact_rlm_text, resolve_child_cwd, resolve_child_model,
+ rlm_child_label, ANSWER_TEXT_MAX_CHARS,
};
use crate::supervisor_link::SupervisorLink;
use crate::util::now_ms;
diff --git a/crates/pa-daemon/src/rlm_children/host.rs b/crates/pa-daemon/src/rlm_children/host.rs
index e3e97c2980..c8ae1ebd6a 100644
--- a/crates/pa-daemon/src/rlm_children/host.rs
+++ b/crates/pa-daemon/src/rlm_children/host.rs
@@ -4,11 +4,11 @@
//! with the spawn-admission helpers only this surface uses.
use super::{
assert_thinking_supported, bail, create_default_rlm_subagent_session_name, json, now_ms,
- resolve_child_model, rlm_child_label, rlm_depth_limit_error, spawn_name_unavailable_error, Arc,
- ChildCloseReason, ChildObservationSource, ChildRecord, Context, DaemonCommand, Duration,
- Instant, Mutex, Path, PathBuf, Result, RlmChildResult, RlmCreateSessionHandle,
- RlmCreateSessionRequest, RlmDeleteSubagentResult, RlmHostFuture, RlmSpawnHandle,
- RlmSpawnRequest, RlmSubagentEntry, RlmSubagentHost, SpawnNameReservationGuard,
+ resolve_child_cwd, resolve_child_model, rlm_child_label, rlm_depth_limit_error,
+ spawn_name_unavailable_error, Arc, ChildCloseReason, ChildObservationSource, ChildRecord,
+ Context, DaemonCommand, Duration, Instant, Mutex, Path, Result, RlmChildResult,
+ RlmCreateSessionHandle, RlmCreateSessionRequest, RlmDeleteSubagentResult, RlmHostFuture,
+ RlmSpawnHandle, RlmSpawnRequest, RlmSubagentEntry, RlmSubagentHost, SpawnNameReservationGuard,
SupervisorChildSessions, SupervisorChildSessionsInner, Value, KILL_TIMEOUT_MS,
RENAME_TIMEOUT_MS,
};
@@ -121,7 +121,11 @@ impl RlmSubagentHost for SupervisorChildSessions {
assert_thinking_supported(&this.agent_dir, request.thinking.as_deref(), &model)?;
let thinking = request.thinking.as_deref().or(identity.thinking.as_deref());
let child_dir = this.child_session_dir(&child_id, &identity)?;
- let cwd = identity.cwd.clone().unwrap_or_else(|| "/".to_string());
+ let cwd = resolve_child_cwd(
+ Path::new(identity.cwd.as_deref().unwrap_or("/")),
+ request.cwd.as_deref(),
+ "rlm.spawn",
+ )?;
let mut runtime_metadata = json!({
"kind": "subagent",
"rlmChildId": child_id,
@@ -141,7 +145,7 @@ impl RlmSubagentHost for SupervisorChildSessions {
identity.rlm_depth + 1,
&model,
thinking,
- &cwd,
+ &cwd.to_string_lossy(),
&child_dir,
request.spawned_by_request_id.as_deref(),
Some(runtime_metadata),
@@ -338,11 +342,11 @@ impl RlmSubagentHost for SupervisorChildSessions {
assert_thinking_supported(&this.agent_dir, request.thinking.as_deref(), &model)?;
// A depth-0 resident session is created exactly like a client
// `create`: the shared sessions dir and the requested cwd.
- let cwd = match &request.cwd {
- Some(cwd) if Path::new(cwd).is_absolute() => PathBuf::from(cwd),
- Some(cwd) => Path::new(identity.cwd.as_deref().unwrap_or("/")).join(cwd),
- None => PathBuf::from(identity.cwd.clone().unwrap_or_else(|| "/".to_string())),
- };
+ let cwd = resolve_child_cwd(
+ Path::new(identity.cwd.as_deref().unwrap_or("/")),
+ request.cwd.as_deref(),
+ "rlm.create_session",
+ )?;
let sessions_dir = crate::paths::sessions_dir(&this.agent_dir)?;
std::fs::create_dir_all(&sessions_dir)
.with_context(|| format!("create sessions dir {}", sessions_dir.display()))?;
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 1961849b6a..804873e9b8 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
@@ -160,6 +160,7 @@ fn spawn_request(name: &str, prompt: &str) -> RlmSpawnRequest {
name: Some(name.to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
}
diff --git a/crates/pa-daemon/src/rlm_children/watch_tests.rs b/crates/pa-daemon/src/rlm_children/watch_tests.rs
index 52c8969865..0ce4665bf5 100644
--- a/crates/pa-daemon/src/rlm_children/watch_tests.rs
+++ b/crates/pa-daemon/src/rlm_children/watch_tests.rs
@@ -428,6 +428,7 @@ async fn spawn_child(sessions: &SupervisorChildSessions) -> RlmSpawnHandle {
name: Some("f20-worker".to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
})
diff --git a/crates/pa-daemon/tests/agent_family_e2e.rs b/crates/pa-daemon/tests/agent_family_e2e.rs
index 1ad6558529..f5da974b08 100644
--- a/crates/pa-daemon/tests/agent_family_e2e.rs
+++ b/crates/pa-daemon/tests/agent_family_e2e.rs
@@ -423,6 +423,7 @@ async fn parent_child_agent_message_round_trip_end_to_end() {
name: Some("kid".to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
})
@@ -753,6 +754,7 @@ async fn family_edges_never_cross_families_end_to_end() {
name: Some(kid_name.to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
})
@@ -894,6 +896,7 @@ async fn family_edges_never_cross_families_end_to_end() {
name: Some("grandkid".to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
})
@@ -1213,6 +1216,7 @@ async fn parent_renames_a_child_end_to_end() {
name: Some("kid".to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
})
@@ -1427,6 +1431,7 @@ async fn passivated_child_recent_messages_reads_its_file_end_to_end() {
name: Some("kid-a".to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
})
diff --git a/crates/pa-daemon/tests/agents_view_roster_e2e.rs b/crates/pa-daemon/tests/agents_view_roster_e2e.rs
index 0e10c0d089..86bc19ed71 100644
--- a/crates/pa-daemon/tests/agents_view_roster_e2e.rs
+++ b/crates/pa-daemon/tests/agents_view_roster_e2e.rs
@@ -424,6 +424,7 @@ async fn rlm_children_key_the_roster_by_parent_path_and_child_id() {
name: Some("child-a".to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
})
diff --git a/crates/pa-daemon/tests/idle_passivation_e2e.rs b/crates/pa-daemon/tests/idle_passivation_e2e.rs
index 9f2c90353c..ac0f5004dc 100644
--- a/crates/pa-daemon/tests/idle_passivation_e2e.rs
+++ b/crates/pa-daemon/tests/idle_passivation_e2e.rs
@@ -294,6 +294,7 @@ async fn a_settled_child_passivates_stays_listable_and_revives_by_agent_message(
name: Some("parked-kid".to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
})
@@ -612,6 +613,7 @@ async fn a_parent_rename_after_a_revival_and_second_passivation_reaches_the_chil
name: Some("parked-kid".to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
})
diff --git a/crates/pa-daemon/tests/launch_env_e2e.rs b/crates/pa-daemon/tests/launch_env_e2e.rs
index 39c56e5481..51056518a7 100644
--- a/crates/pa-daemon/tests/launch_env_e2e.rs
+++ b/crates/pa-daemon/tests/launch_env_e2e.rs
@@ -545,6 +545,7 @@ async fn an_rlm_spawn_child_inherits_the_parent_worker_env() {
name: Some("worker-a".to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
})
diff --git a/crates/pa-daemon/tests/rlm_children_e2e.rs b/crates/pa-daemon/tests/rlm_children_e2e.rs
index 56cd134a30..a032099435 100644
--- a/crates/pa-daemon/tests/rlm_children_e2e.rs
+++ b/crates/pa-daemon/tests/rlm_children_e2e.rs
@@ -232,11 +232,95 @@ fn spawn_request(name: &str, prompt: &str) -> RlmSpawnRequest {
name: Some(name.to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
}
}
+/// A child spawned with a relative `cwd` runs in that directory and loads only
+/// its project context; a missing directory refuses the spawn.
+#[tokio::test]
+async fn rlm_spawn_cwd_starts_the_child_in_that_directory() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("daemon.sock");
+ let agent_dir = dir.path().join("agent");
+ let main = dir.path().join("main");
+ let project = dir.path().join("project");
+ let marker = format!("SPAWN_CWD_CONTEXT_{}", uuid::Uuid::new_v4().simple());
+ let main_marker = format!("SPAWN_CWD_PARENT_CONTEXT_{}", uuid::Uuid::new_v4().simple());
+ for (path, content) in [(&main, &main_marker), (&project, &marker)] {
+ std::fs::create_dir_all(path).expect("project dir");
+ std::fs::write(path.join("AGENTS.md"), content).expect("write AGENTS.md");
+ }
+ std::fs::create_dir_all(&agent_dir).expect("agent dir");
+ let _daemon = spawn_daemon(&socket, &agent_dir);
+ let (mut client, _) = Client::connect(&socket);
+ // The faux engine (and its faux model) runs the real agent engine, so the
+ // child builds its system prompt.
+ let script = dir.path().join("faux.json");
+ std::fs::write(
+ &script,
+ json!({ "engine": "faux", "responses": [ { "text": "child answer" } ] }).to_string(),
+ )
+ .expect("write script");
+ let children = children(&socket, &agent_dir, &script, 0);
+ children.set_identity(ParentIdentity {
+ rlm_depth: 0,
+ rlm_max_depth: 2,
+ model: Some("faux/faux-1".to_string()),
+ cwd: Some(main.to_string_lossy().to_string()),
+ session_id: Some("parent-session-uuid".to_string()),
+ session_file: Some(agent_dir.join("parent.jsonl").to_string_lossy().to_string()),
+ thinking: None,
+ child_script: Some(script.to_string_lossy().to_string()),
+ });
+
+ let handle = children
+ .spawn(RlmSpawnRequest {
+ cwd: Some("../project".to_string()),
+ ..spawn_request("worker-cwd", "ship the lane")
+ })
+ .await
+ .expect("spawn");
+ let summary = wait_until(Duration::from_secs(10), || {
+ client.send_command("l1", &json!({ "type": "list" }));
+ let list = client.read_response("l1");
+ list["data"]["sessions"].as_array().and_then(|sessions| {
+ sessions
+ .iter()
+ .find(|summary| summary["sessionName"] == "worker-cwd")
+ .cloned()
+ })
+ });
+ assert_eq!(
+ summary["cwd"],
+ json!(project.canonicalize().expect("project"))
+ );
+ client.send_command(
+ "prompt",
+ &json!({ "type": "get_system_prompt", "activeSessionId": summary["id"] }),
+ );
+ let context = client.read_response("prompt");
+ let system_prompt = context["data"]["systemPrompt"].as_str().unwrap_or_default();
+ assert!(system_prompt.contains(&marker), "{context}");
+ assert!(!system_prompt.contains(&main_marker), "{context}");
+
+ let missing = project.join("missing");
+ let error = children
+ .spawn(RlmSpawnRequest {
+ cwd: Some(missing.to_string_lossy().to_string()),
+ ..spawn_request("worker-missing", "ship the lane")
+ })
+ .await
+ .expect_err("missing cwd");
+ assert_eq!(
+ error.to_string(),
+ format!("rlm.spawn cwd {} is not a directory", missing.display())
+ );
+ let _ = children.delete_subagent(handle.rlm_child_id).await;
+}
+
/// Spawn a child through the supervisor, observe it in both rosters, collect its answer,
/// then delete it (both rosters drop it).
#[tokio::test]
diff --git a/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs b/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs
index b70a0d5347..b4f82e4bd3 100644
--- a/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs
+++ b/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs
@@ -498,6 +498,7 @@ async fn subscribe_after_spawn_then_shutdown_seeds_the_passive_child() {
name: Some("worker-a".to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
})
diff --git a/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs b/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs
index 785c45e2b0..5736c10c4b 100644
--- a/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs
+++ b/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs
@@ -231,6 +231,7 @@ fn spawn_request(name: &str, prompt: &str) -> RlmSpawnRequest {
name: Some(name.to_string()),
model: None,
thinking: None,
+ cwd: None,
spawned_by_request_id: None,
factory: None,
}
diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.py
index 2239f8d2f2..ebda25e987 100644
--- a/prime-agent-runtime/src/rlm/__init__.py
+++ b/prime-agent-runtime/src/rlm/__init__.py
@@ -182,6 +182,7 @@ async def spawn(
name: str,
model: str | None = None,
thinking: str | None = None,
+ cwd: str | None = None,
) -> RLMSpawnHandle:
"""Spawn a recursive Prime Agent child and return once its task is admitted.
@@ -189,8 +190,10 @@ async def spawn(
``model`` selects a child with an exact ``provider/model`` selector.
``thinking`` sets the child reasoning level (e.g. 'off', 'low', 'medium', 'high');
defaults to the parent level; levels invalid for the resolved model fail the spawn.
+ ``cwd`` starts the child in that directory (relative to the session cwd); defaults
+ to the session cwd.
"""
- return await _spawn(prompt, name=name, model=model, thinking=thinking)
+ return await _spawn(prompt, name=name, model=model, thinking=thinking, cwd=cwd)
async def _spawn(
@@ -199,6 +202,7 @@ async def _spawn(
name: str,
model: str | None = None,
thinking: str | None = None,
+ cwd: str | None = None,
factory: dict[str, str] | None = None,
) -> RLMSpawnHandle:
"""``spawn`` plus the factory executor's run tag (``{runId, specId,
@@ -210,6 +214,8 @@ async def _spawn(
kwargs["model"] = model
if thinking is not None:
kwargs["thinking"] = thinking
+ if cwd is not None:
+ kwargs["cwd"] = cwd
if factory is not None:
kwargs["factory"] = factory
# Wire type stays "rlm.run" so kernels and hosts of different versions stay compatible.
@@ -657,8 +663,9 @@ class _RLMNamespace:
name: str,
model: str | None = None,
thinking: str | None = None,
+ cwd: str | None = None,
) -> RLMSpawnHandle:
- return await spawn(prompt, name=name, model=model, thinking=thinking)
+ return await spawn(prompt, name=name, model=model, thinking=thinking, cwd=cwd)
async def create_session(
self,
diff --git a/prime-agent-runtime/test/test_subagent_registry.py b/prime-agent-runtime/test/test_subagent_registry.py
index 01561c6a4e..f687859a47 100644
--- a/prime-agent-runtime/test/test_subagent_registry.py
+++ b/prime-agent-runtime/test/test_subagent_registry.py
@@ -62,7 +62,7 @@ class RlmSubagentRegistryTest(unittest.TestCase):
self.assertEqual(subagents[0].status, "error")
- def test_forwards_orchestrator_chosen_name_and_model_to_host(self) -> None:
+ def test_forwards_orchestrator_chosen_name_model_and_cwd_to_host(self) -> None:
host_request = AsyncMock(
return_value={
"rlm_child_id": "sub-a1b2c3d4",
@@ -78,6 +78,7 @@ class RlmSubagentRegistryTest(unittest.TestCase):
"check the API",
name="api-reviewer",
model="deepseek/deepseek-v4-flash",
+ cwd="../api",
)
)
@@ -88,6 +89,7 @@ class RlmSubagentRegistryTest(unittest.TestCase):
"kwargs": {
"name": "api-reviewer",
"model": "deepseek/deepseek-v4-flash",
+ "cwd": "../api",
},
},
)