A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
make recursive subagent spawning an explicit rlm.spawn call (#2152)
Sebastian Müllerea7dbd1f103f
diff --git a/README.md b/README.mdindex e4b77ad79f..626a35c121 100644--- a/README.md+++ b/README.md@@ -44,7 +44,7 @@ Prime Agent is an open-source coding and research agent for general and long-runPrime Agent combines a persistent Python control environment with durable harness state, so useful working context and reusable operating patterns can outlive a single chat window.- **Everything is programmatic:** a persistent Python REPL is the built-in model tool; file operations, shell commands, tool use, subagents, and context management happen through code.-- **Subagents are built in:** `rlm(...)` spawns real child agents for parallel or background work and returns their results programmatically.+- **Subagents are built in:** `rlm.spawn(...)` spawns real child agents for parallel or background work and returns their results programmatically.- **The harness can improve:** `/refine` reviews the current trajectory and can apply small, evidence-backed updates to supplemental harness state. It never rewrites the immutable base system prompt, and recorded snapshots support rollback.- **Skills are executable:** skills are importable Python packages, and the built-in skill creator can turn recurring workflows into project or personal skills.- **Sessions run in the background:** daemon-backed agents keep running when the terminal disconnects and can be reattached later.diff --git a/packages/coding-agent/.changes/res-1334-rlm-spawn.md b/packages/coding-agent/.changes/res-1334-rlm-spawn.mdnew file mode 100644index 0000000000..a48b4a537c--- /dev/null+++ b/packages/coding-agent/.changes/res-1334-rlm-spawn.md@@ -0,0 +1,2 @@+- Changed recursive subagent spawning to the explicit `await rlm.spawn(...)` call; the `rlm` object is no longer callable and calling it raises an error naming `rlm.spawn`.+- Changed `rlm.spawn` to require an explicit `name` keyword argument for every spawned child.diff --git a/packages/coding-agent/docs/quickstart.md b/packages/coding-agent/docs/quickstart.mdindex e55a8375b5..5125a504f1 100644--- a/packages/coding-agent/docs/quickstart.md+++ b/packages/coding-agent/docs/quickstart.md@@ -77,7 +77,7 @@ Prime Agent runs in your current working directory and can modify files there. U## Recursive Subagents-Recursive subagents are a built-in Prime Agent capability. The model spawns independent work from the Python REPL with `await rlm("subtask")`; each call returns at admission with a child handle and never returns the answer. Children send requested results as explicit `agent_message` replies to the parent or write them to files. Child agents use the same TypeScript agent runtime, providers, tools, skills, and session machinery as the parent.+Recursive subagents are a built-in Prime Agent capability. The model spawns independent work from the Python REPL with `await rlm.spawn("subtask", name="worker")`; each call returns at admission with a child handle and never returns the answer. Children send requested results as explicit `agent_message` replies to the parent or write them to files. Child agents use the same TypeScript agent runtime, providers, tools, skills, and session machinery as the parent.You can prompt the model to use that capability directly:diff --git a/packages/coding-agent/docs/rlm-runtime.md b/packages/coding-agent/docs/rlm-runtime.mdindex 63625ccbc9..a9c1e56e4f 100644--- a/packages/coding-agent/docs/rlm-runtime.md+++ b/packages/coding-agent/docs/rlm-runtime.md@@ -23,7 +23,7 @@ flowchart TDWhen the model delegates work:```python-handle = await rlm("inspect the API", name="api-reviewer")+handle = await rlm.spawn("inspect the API", name="api-reviewer")print(handle.rlm_child_id, handle.name, handle.session_dir, handle.model)```@@ -42,7 +42,7 @@ sequenceDiagramparticipant P as Model providerM->>H: Python tool call- H->>K: execute await rlm("inspect the API")+ H->>K: execute await rlm.spawn("inspect the API", name="api-reviewer")K->>H: host_request · rlm.runH->>H: check depth and resolve modelH->>H: admit child task and update registry@@ -66,8 +66,8 @@ sequenceDiagram| `src/core/kernel/repl-manager.ts` | Runtime process, stdio protocol, execution, host-request dispatch, interrupt, and shutdown. || `src/core/tools/ipython.ts` | Agent tool wrapper, lazy kernel provisioning, namespace bootstrap, and output shaping. || `src/core/agent-session.ts` | RLM policy, child creation, registry, usage attribution, cancellation, and goal handlers. |-| `src/core/rlm-runtime.ts` | Typed request/spawn-handle validation for `rlm.run`, model discovery, list, and delete. |-| `prime-agent-runtime/src/rlm/` | Python shim, handle types, callable `rlm`, and session-backed harness state. |+| `src/core/rlm-runtime.ts` | Typed request/spawn-handle validation for `rlm.spawn`, model discovery, list, and delete. |+| `prime-agent-runtime/src/rlm/` | Python shim, handle types, the `rlm` namespace object, and session-backed harness state. |The Python side does not call providers or implement an agent loop.@@ -103,7 +103,7 @@ Calls to `ReplKernelManager.execute()` are serialized. One kernel has one sharedA running cell can await task admission:```python-handle = await rlm("subtask")+handle = await rlm.spawn("subtask", name="worker")```The runtime ships the call to the host as a `host_request` event and keeps its event loop free while awaiting the reply. The host dispatches the typed request and answers with a `host_reply` request carrying the same id, so a cell can block on admission without stalling other runtime work. Child answers do not use this response path; they arrive later through explicit `agent_message` replies or files.@@ -114,7 +114,7 @@ The runtime ships the call to the host as a `host_request` event and keeps its e```pythonrlm-run(prompt: str, **kwargs)+spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None)find_models(query: str = "", limit: int = 8)list_subagents()delete_subagent(selector)@@ -124,18 +124,12 @@ RLMModelRLMSubagent```-The kernel bootstrap places the callable `rlm` object in the user namespace, so these are equivalent:--```python-await rlm("subtask")-await rlm.run("subtask")-```+The kernel bootstrap places the `rlm` object in the user namespace, so a cell calls `await rlm.spawn("subtask", name="worker")`. The `rlm` object itself is not callable, and the old `rlm.run` attribute is gone; both raise an error naming `rlm.spawn`.`RLMSpawnHandle` contains `rlm_child_id`, `name`, `session_dir`, and `model`. It confirms admission only and never contains the child's answer.-Supported `rlm.run` options are:+`name` is required. The other `rlm.spawn` options are:-- `name`: a unique readable child session name;- `model`: an exact `provider/model` selector from `rlm.find_models()`; and- `thinking`: an explicit child reasoning level; must be valid for the resolved child model, defaults to the parent level (clamped to the child model).@@ -161,9 +155,9 @@ Children receive incremented `RLM_DEPTH`, the inherited maximum depth, and theirEach direct call admits an independent child and returns its handle immediately:```python-api_review = await rlm("review the API", name="api-reviewer")-test_review = await rlm("review the tests", name="test-reviewer")-audit = await rlm("slow independent audit", name="audit-reviewer")+api_review = await rlm.spawn("review the API", name="api-reviewer")+test_review = await rlm.spawn("review the tests", name="test-reviewer")+audit = await rlm.spawn("slow independent audit", name="audit-reviewer")```End the turn instead of waiting for completion. Children send requested answers with `await agent_message.send(message, receiver_role="parent")`, and replies arrive as ordinary agent messages over later turns. A child may instead write results to files for the parent to read. The host runs each admitted child as an independent `AgentSession`; daemon-backed children can be retained as independently addressable session workers.@@ -243,7 +237,7 @@ Provider credentials are resolved by the TypeScript host. The bounded model cata| Failure | Behavior ||---|---|| Managed runtime is missing | Kernel bootstrap rebuilds it; a custom `PRIME_AGENT_KERNEL_PYTHON` without a current `prime-agent-runtime` is rejected at kernel startup. |-| Depth limit reached | The host rejects the `rlm.run` request; the error reply raises in Python. |+| Depth limit reached | The host rejects the spawn request; the error reply raises in Python. || Unsupported options | Host rejects the request. || Requested model unavailable | Spawn fails instead of substituting another model. || Host connection closed | Pending `host_request` calls fail with `RuntimeError` so awaiting cells unblock. |diff --git a/packages/coding-agent/docs/rlm.md b/packages/coding-agent/docs/rlm.mdindex 27653930fd..12f4405945 100644--- a/packages/coding-agent/docs/rlm.md+++ b/packages/coding-agent/docs/rlm.md@@ -11,7 +11,7 @@ flowchart LRkernel["Persistent Python kernel"]data["Files · data · shell commands"]skills["Python-backed skills"]- children["rlm(...) child agents"]+ children["rlm.spawn(...) child agents"]answer["Answer or next turn"]task --> parent@@ -63,10 +63,10 @@ Each `bash()` call is its own process, while Python state, `os.chdir(...)`, and### 2. Subagents are native RLM calls-The callable `rlm` object is preloaded in the kernel. Spawn a child with a direct call:+The `rlm` object is preloaded in the kernel. Spawn a child with `rlm.spawn`, which requires a `name`:```python-handle = await rlm("Review the authentication flow for security issues", name="auth-reviewer")+handle = await rlm.spawn("Review the authentication flow for security issues", name="auth-reviewer")print(handle.rlm_child_id, handle.name, handle.session_dir, handle.model)```@@ -75,12 +75,12 @@ The call returns immediately after task admission with a child handle; it neverSpawn independent children in separate calls and end the turn instead of awaiting completion:```python-api_review = await rlm("Review the public API", name="api-reviewer")-test_review = await rlm("Review the test coverage", name="test-reviewer")-integration_audit = await rlm("Run the slow integration audit", name="integration-audit")+api_review = await rlm.spawn("Review the public API", name="api-reviewer")+test_review = await rlm.spawn("Review the test coverage", name="test-reviewer")+integration_audit = await rlm.spawn("Run the slow integration audit", name="integration-audit")```-Results arrive only through explicit `agent_message` replies or files, never as an `rlm()` return value. Children reply when an answer is needed:+Results arrive only through explicit `agent_message` replies or files, never as an `rlm.spawn()` return value. Children reply when an answer is needed:```pythonawait agent_message.send(message, receiver_role="parent")@@ -126,7 +126,7 @@ For a skill named `release-audit`, the model can call:report = await release_audit(repository=".", target_version="0.4.0")```-This makes Python-backed skills a superset of instruction-only skills: they can provide guidance, scripts, references, dependencies, typed callables, and optional shell commands. They may also call `rlm(...)` themselves when a capability needs recursive delegation.+This makes Python-backed skills a superset of instruction-only skills: they can provide guidance, scripts, references, dependencies, typed callables, and optional shell commands. They may also call `rlm.spawn(...)` themselves when a capability needs recursive delegation.Only skill metadata is placed in the startup prompt. The agent loads the full `SKILL.md` when the task matches, then inspects and calls the documented Python API. See [Skills](skills.md) for discovery, packaging, and the built-in skill-creation workflow.diff --git a/packages/coding-agent/docs/usage.md b/packages/coding-agent/docs/usage.mdindex 3d68af75bd..c8d3ad0e79 100644--- a/packages/coding-agent/docs/usage.md+++ b/packages/coding-agent/docs/usage.md@@ -104,17 +104,17 @@ See [Sessions](sessions.md) and [Compaction](compaction.md) for details.Normal interactive sessions are persistent agents backed by isolated worker processes. Closing the TUI detaches the client; use `prime-agent agents`, `prime-agent list`, or `prime-agent attach <agent>` to find and reattach to running work. `prime-agent stop <agent>` stops one root agent, while `prime-agent shutdown` stops all workers and the local supervisor.-Within a session, the model can delegate through the `rlm` callable already available in the Python REPL:+Within a session, the model can delegate through the `rlm` object already available in the Python REPL:```python# Spawn independent children. Each call returns at admission with a child handle,# never the child's answer.-review = await rlm(+review = await rlm.spawn("Review authentication and reply to the parent with findings.",name="auth-reviewer",)-tests = await rlm("Find missing regression tests and reply to the parent.", name="test-reviewer")-docs = await rlm("Find stale public documentation and reply to the parent.", name="docs-reviewer")+tests = await rlm.spawn("Find missing regression tests and reply to the parent.", name="test-reviewer")+docs = await rlm.spawn("Find stale public documentation and reply to the parent.", name="docs-reviewer")# Children reply from their own sessions with:# await agent_message.send(message, receiver_role="parent")diff --git a/packages/coding-agent/examples/extensions/subagent/README.md b/packages/coding-agent/examples/extensions/subagent/README.mdindex d6a79f83d6..f82f45b047 100644--- a/packages/coding-agent/examples/extensions/subagent/README.md+++ b/packages/coding-agent/examples/extensions/subagent/README.md@@ -2,8 +2,8 @@Delegate tasks to specialized subprocess agents with isolated context windows.-Prime Agent also provides native recursive delegation through `rlm.call()` and-`rlm.run_async()`. This extension is a separate example for users who want+Prime Agent also provides native recursive delegation through `rlm.spawn()`.+This extension is a separate example for users who wantfile-defined agent profiles and explicit single, parallel, or chained workflows.## Featuresdiff --git a/packages/coding-agent/skills/skill-creator/references/python-skills.md b/packages/coding-agent/skills/skill-creator/references/python-skills.mdindex fe0ce1b477..903c884eb4 100644--- a/packages/coding-agent/skills/skill-creator/references/python-skills.md+++ b/packages/coding-agent/skills/skill-creator/references/python-skills.md@@ -119,7 +119,7 @@ Omit `[project.scripts]` when a CLI is not needed.- The install is editable and keyed on a hash of `pyproject.toml`: editing Python source takes effect on the next kernel start with no reinstall; editing `pyproject.toml` triggers a reinstall automatically.- If the user sets `PRIME_AGENT_KERNEL_PYTHON`, Prime Agent installs nothing — skills whose imports are missing there are disabled with a warning.-A Python skill runs inside the agent's kernel, so it can itself spawn recursive sub-agents with `import rlm` and `await rlm.run("subtask")` — useful for skills that delegate open-ended work.+A Python skill runs inside the agent's kernel, so it can itself spawn recursive sub-agents with `import rlm` and `await rlm.spawn("subtask", name="worker")` — useful for skills that delegate open-ended work.## Verifying a Python Skilldiff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex eec21e2341..0071a9e167 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -10797,7 +10797,7 @@ export class AgentSession {const { name: rawName, model: rawModel, thinking: rawThinking, ...unsupported } = kwargs;const unsupportedKwargs = Object.keys(unsupported);if (unsupportedKwargs.length > 0) {- throw new Error(`Unsupported rlm.run kwargs: ${unsupportedKwargs.sort().join(", ")}`);+ throw new Error(`Unsupported rlm.spawn kwargs: ${unsupportedKwargs.sort().join(", ")}`);}const requestedSessionName = normalizeRequestedRlmSubagentSessionName(rawName);const requestedModel = normalizeRequestedRlmSubagentModel(rawModel);diff --git a/packages/coding-agent/src/core/kernel/bootstrap.ts b/packages/coding-agent/src/core/kernel/bootstrap.tsindex 5ab93cc64e..460512f5f6 100644--- a/packages/coding-agent/src/core/kernel/bootstrap.ts+++ b/packages/coding-agent/src/core/kernel/bootstrap.ts@@ -87,7 +87,7 @@ const REQUIRED_HARNESS_METHODS = ["delete_prompt_note","record_refinement",];-const RUNTIME_READY_CHECK = `import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ${JSON.stringify(REQUIRED_HARNESS_METHODS)}; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert hasattr(rlm, 'run'); assert callable(rlm); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm); 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 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 = `import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ${JSON.stringify(REQUIRED_HARNESS_METHODS)}; assert callable(mcp.list_tools); assert callable(mcp.call_tool); 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 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 BOOTSTRAP_VERSION_FILE = ".bootstrap-version";const BOOTSTRAP_LOCK_NAME = ".bootstrap.lock";const BOOTSTRAP_LOCK_RETRY_MS = 100;@@ -877,6 +877,7 @@ function formatBootstrapFailure(error: unknown): Error {return new Error(`Failed to set up the Python kernel runtime. ${errorMessage(error)}\n` +"First-time setup needs internet to install uv, Python, prime-agent-runtime, and default Python packages; once set up, prime-agent runs offline. " ++ "An interrupted runtime upgrade needs network once more, so re-run this while online. " +"Set PRIME_AGENT_KERNEL_PYTHON to a Python with a current prime-agent-runtime and default Python packages installed to skip auto-bootstrap.",);}@@ -896,7 +897,7 @@ async function ensureKernelPythonUncached(const missing: string[] = [];if (!(await hasPrimeAgentRuntime(python))) {missing.push(- "a current prime-agent-runtime with callable rlm.run, rlm.create_session, rlm.host_request, and explicit harness CRUD methods",+ "a current prime-agent-runtime with callable rlm.spawn, rlm.create_session, rlm.host_request, and explicit harness CRUD methods",);}if (missing.length === 0) {diff --git a/packages/coding-agent/src/core/prompts/rlm.ts b/packages/coding-agent/src/core/prompts/rlm.tsindex d7be88bd47..b3e599c721 100644--- a/packages/coding-agent/src/core/prompts/rlm.ts+++ b/packages/coding-agent/src/core/prompts/rlm.ts@@ -48,7 +48,7 @@ const REPL_CONTROL_PROMPT = ["","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.","",- "RLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm('sub-task')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.",+ "RLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.",].join("\n");export interface ChildAgentDoctrineOptions {@@ -149,15 +149,15 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {if (depth === 0 && hasIpython) {parts.push("",- "From a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm(...)` still creates a child.",+ "From a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.",);}if (allowRecursion && hasIpython) {parts.push("",- "A callable `rlm` is already in your global namespace. `await rlm('sub-task')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.",- "Choose a stable child name with `await rlm('sub-task', name='api-reviewer')`; names must be unique among siblings. If omitted, the host generates a readable unique name.",+ "An `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.",+ "`name` is required: choose a stable child name that is unique among siblings.","A child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.",);if (hasAgentMessage) {@@ -196,7 +196,7 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {/*** Supplemental sub-agent delegation guidance, appended after the base RLM* prompt (see system-prompt.ts). The recursion block covers the mechanics- * (`rlm(...)` admission and handle management); this block adds the+ * (`rlm.spawn(...)` admission and handle management); this block adds the* when and why in the same When -> Why -> menu order Claude Code's Agent tool* uses. The subagent-spec menu itself renders just after this, inside the* harness-state block.@@ -207,7 +207,7 @@ export function buildSubagentGuidance(const lines = ["# Delegating to sub-agents","",- "Spawn independent, self-contained work with `handle = await rlm('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.",+ "Spawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.",];if (options.hasAgentMessage) {lines.push(diff --git a/packages/coding-agent/src/core/refinement/refinement.ts b/packages/coding-agent/src/core/refinement/refinement.tsindex ce15ade8d8..1322952cf1 100644--- a/packages/coding-agent/src/core/refinement/refinement.ts+++ b/packages/coding-agent/src/core/refinement/refinement.ts@@ -129,7 +129,7 @@ Continual harness components:- prompt: supplemental prompt notes only. The base system prompt is immutable and MUST NOT be rewritten.- memory: durable facts, decisions, failures, preferences, and outcomes.- skill: installed Python REPL skill. Skill create/update edits MUST include a \`reference\` object with \`{"type":"python"}\`, a Python import, and a callable or call pattern; they also MUST include an \`arguments\` object describing accepted inputs, required fields, defaults, and constraints. Use \`{}\` for \`arguments\` only when the Python callable truly needs no external inputs. Include the RLM-native call form \`await <skill_import>(...)\`.-- subagent: reusable delegation specs, including purpose, instructions, and when to invoke. Include the RLM-native call form: compose a concise task prompt and spawn with \`handle = await rlm("sub-task")\`; admission returns immediately with \`rlm_child_id\`, \`name\`, \`session_dir\`, and \`model\`, never the child's answer. Results arrive only through explicit \`agent_message\` replies or files; children reply with \`await agent_message.send(message, receiver_role="parent")\`. Use \`await rlm.list_subagents()\` to recover direct child handles and \`await agent_message.send(..., receiver_role="child", receiver_name=handle.name)\` for follow-ups. Do not invent wrappers like \`run_subagent(...)\`.+- subagent: reusable delegation specs, including purpose, instructions, and when to invoke. Include the RLM-native call form: compose a concise task prompt and spawn with \`handle = await rlm.spawn("sub-task", name="worker")\`; admission returns immediately with \`rlm_child_id\`, \`name\`, \`session_dir\`, and \`model\`, never the child's answer. Results arrive only through explicit \`agent_message\` replies or files; children reply with \`await agent_message.send(message, receiver_role="parent")\`. Use \`await rlm.list_subagents()\` to recover direct child handles and \`await agent_message.send(..., receiver_role="child", receiver_name=handle.name)\` for follow-ups. Do not invent wrappers like \`run_subagent(...)\`.Scope and persistence policy:- The default editable continual harness store is local to the current Prime Agent session. Use it for session-specific progress, active task state, current-run coordination notes, temporary blockers, and project facts that should not affect other sessions.@@ -494,7 +494,7 @@ export function formatHarnessStateForPrompt(: "When to refine the continual harness: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep continual harness edits small and evidence-backed.","",includeIpythonExamples- ? "Call contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm('sub-task')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries."+ ? "Call contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.": options.includeShellExamples? "Call contract: use installed skills as shell commands when available (for example `<skill_import> ...`). Continual harness entries are routing/context hints only in sessions without the Python REPL; do not use Python `await`, `asyncio`, or `rlm` examples unless the prompt also documents a Python kernel.": "Call contract: continual harness entries are routing/context hints only in sessions without the Python REPL or shell access; do not use Python `await`, `asyncio`, `rlm`, or shell skill commands unless the prompt also documents those interfaces.",@@ -512,7 +512,7 @@ export function formatHarnessStateForPrompt(// REPL sessions, include the native `rlm` invocation hint.if (kind === "subagent" && entries.length > 0 && includeIpythonExamples) {lines.push(- `${kind}: ${entries.length} (invoke a spec by turning it into a concise task prompt and spawning with \`await rlm('<task>')\`; admission returns a child handle, never the answer)`,+ `${kind}: ${entries.length} (invoke a spec by turning it into a concise task prompt and spawning with \`await rlm.spawn('<task>', name='<worker>')\`; admission returns a child handle, never the answer)`,);} else {lines.push(`${kind}: ${entries.length}`);diff --git a/packages/coding-agent/src/core/rlm-runtime.ts b/packages/coding-agent/src/core/rlm-runtime.tsindex 837a6d77ad..b9f655be8e 100644--- a/packages/coding-agent/src/core/rlm-runtime.ts+++ b/packages/coding-agent/src/core/rlm-runtime.ts@@ -5,7 +5,7 @@ import type { ToolDefinition } from "./extensions/index.js";import type { HostRequestHandler } from "./kernel/index.js";import { THINKING_LEVELS } from "./thinking-levels.js";-/** Request emitted by `rlm.run`; cellSourceCode preserves the spawning cell for display. */+/** Request emitted by `rlm.spawn`; cellSourceCode preserves the spawning cell for display. */export interface RlmRunRequest {prompt: string;kwargs: Record<string, unknown>;@@ -81,7 +81,7 @@ const RLM_SUBAGENT_SESSION_NAME_MAX_LENGTH = 64;export const DEFAULT_RLM_MODEL_SEARCH_LIMIT = 8;export const MAX_RLM_MODEL_SEARCH_LIMIT = 20;-export function normalizeRequestedRlmSubagentSessionName(value: unknown, operation = "rlm.run"): string | undefined {+export function normalizeRequestedRlmSubagentSessionName(value: unknown, operation = "rlm.spawn"): string | undefined {if (value === undefined) {return undefined;}@@ -100,7 +100,7 @@ export function normalizeRequestedRlmSubagentSessionName(value: unknown, operatiexport function normalizeRequestedRlmSubagentThinkingLevel(value: unknown,- operation = "rlm.run",+ operation = "rlm.spawn",): ThinkingLevel | undefined {if (value === undefined) {return undefined;@@ -115,7 +115,7 @@ export function normalizeRequestedRlmSubagentThinkingLevel(return level as ThinkingLevel;}-export function normalizeRequestedRlmSubagentModel(value: unknown, operation = "rlm.run"): string | undefined {+export function normalizeRequestedRlmSubagentModel(value: unknown, operation = "rlm.spawn"): string | undefined {if (value === undefined) {return undefined;}@@ -201,7 +201,7 @@ export function createRlmCreateSessionHostHandler(handler: RlmCreateSessionHandlexport function createRlmRunHostHandler(handler: RlmRunHandler): HostRequestHandler {return async (payload) => {if (typeof payload.prompt !== "string") {- throw new Error("rlm.run prompt must be a string");+ throw new Error("rlm.spawn prompt must be a string");}const kwargs = isRecord(payload.kwargs) ? payload.kwargs : {};const cellSourceCode = typeof payload.cellSourceCode === "string" ? payload.cellSourceCode : undefined;diff --git a/packages/coding-agent/src/core/tools/ipython.ts b/packages/coding-agent/src/core/tools/ipython.tsindex bae3ba41c1..a9f696a2b8 100644--- a/packages/coding-agent/src/core/tools/ipython.ts+++ b/packages/coding-agent/src/core/tools/ipython.ts@@ -47,7 +47,7 @@ except Exception as _prime_agent_rlm_error:f"Import error: {_PRIME_AGENT_RLM_IMPORT_ERROR}")- async def run(self, prompt, **kwargs):+ async def spawn(self, prompt, **kwargs):self._raise_missing()async def find_models(self, query="", limit=8):@@ -62,9 +62,6 @@ except Exception as _prime_agent_rlm_error:async def delete_subagent(self, target):self._raise_missing()- async def __call__(self, prompt, **kwargs):- return await self.run(prompt, **kwargs)-rlm = _PrimeAgentMissingRlm()def bash(command):diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex c2b6e4f212..0e3d3f8f27 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -440,7 +440,9 @@ describe("AgentSession rlm recursion", () => {await expect(root.runRlmChild("inspect another API", { name: "api-reviewer" })).rejects.toThrow('Agent name "api-reviewer" is unavailable: an agent of that name already exists at depth 1 under this parent',);- await expect(root.runRlmChild("invalid name", { name: " " })).rejects.toThrow("rlm.run name must not be empty");+ await expect(root.runRlmChild("invalid name", { name: " " })).rejects.toThrow(+ "rlm.spawn name must not be empty",+ );await expect(root.runRlmChild("reserved name", { name: "all" })).rejects.toThrow("Broadcast agent messaging is not supported",);@@ -2925,7 +2927,7 @@ describe("AgentSession rlm recursion", () => {const promptPromise = root.prompt("start");await waitFor(() => seenSystemPrompts.length === 1);- expect(seenSystemPrompts[0]!).toContain("A callable `rlm`");+ expect(seenSystemPrompts[0]!).toContain("An `rlm` object");await root.setRlmMaxDepth(0);await root.steer("continue after max-depth update");@@ -2933,7 +2935,7 @@ describe("AgentSession rlm recursion", () => {await promptPromise;expect(seenSystemPrompts).toHaveLength(2);- expect(seenSystemPrompts[1]!).not.toContain("A callable `rlm`");+ expect(seenSystemPrompts[1]!).not.toContain("An `rlm` object");});it("rehydrates chat max depth ahead of reconstruction config", async () => {@@ -2958,10 +2960,10 @@ describe("AgentSession rlm recursion", () => {if (!baselineLeafId) throw new Error("Missing baseline branch leaf");await root.setRlmMaxDepth(2);- expect(root.systemPrompt).toContain("A callable `rlm`");+ expect(root.systemPrompt).toContain("An `rlm` object");await root.navigateTree(baselineLeafId, { summarize: false });expect(root.getRlmMaxDepthStatus()).toEqual({ maxDepth: 0, source: "env" });- expect(root.systemPrompt).not.toContain("A callable `rlm`");+ expect(root.systemPrompt).not.toContain("An `rlm` object");} finally {vi.unstubAllEnvs();}@@ -3091,7 +3093,7 @@ describe("AgentSession rlm recursion", () => {});expect(resumed.sessionManager.getLeafId()).toBe(baselineLeafId);expect(resumed.rlmMaxDepth).toBe(0);- expect(resumed.systemPrompt).not.toContain("A callable `rlm`");+ expect(resumed.systemPrompt).not.toContain("An `rlm` object");} finally {vi.unstubAllEnvs();}@@ -3137,7 +3139,7 @@ describe("AgentSession rlm recursion", () => {expect(grandchild?.rlmMaxDepth).toBe(3);await root.setRlmMaxDepth(0);- expect(root.systemPrompt).not.toContain("A callable `rlm`");+ expect(root.systemPrompt).not.toContain("An `rlm` object");await expect(root.runRlmChild("blocked at root")).rejects.toThrow("RLM recursion depth limit reached (RLM_DEPTH=0, RLM_MAX_DEPTH=0)",);@@ -3261,21 +3263,21 @@ describe("AgentSession rlm recursion", () => {await expect(root.runRlmChild("nested")).rejects.toThrow("RLM recursion depth limit reached");});- it("rejects unsupported rlm.run kwargs loudly", async () => {+ it("rejects unsupported rlm.spawn kwargs loudly", async () => {const root = createSession();await expect(root.runRlmChild("nested", { temperature: 0 })).rejects.toThrow(- "Unsupported rlm.run kwargs: temperature",+ "Unsupported rlm.spawn kwargs: temperature",);});- it("rejects a non-string rlm.run thinking kwarg", async () => {+ it("rejects a non-string rlm.spawn thinking kwarg", async () => {const root = createSession();- await expect(root.runRlmChild("nested", { thinking: 3 })).rejects.toThrow("rlm.run thinking must be a string");+ await expect(root.runRlmChild("nested", { thinking: 3 })).rejects.toThrow("rlm.spawn thinking must be a string");});- it("rejects an unknown rlm.run thinking level", async () => {+ it("rejects an unknown rlm.spawn thinking level", async () => {const root = createSession();await expect(root.runRlmChild("nested", { thinking: "ultra" })).rejects.toThrow("must be one of");});@@ -4672,7 +4674,7 @@ import rlmasync def _delayed_rlm():await asyncio.sleep(0.05)- return await rlm.run("detached child after idle")+ return await rlm.spawn("detached child after idle", name="detached-worker")_task = asyncio.create_task(_delayed_rlm())print("scheduled")diff --git a/packages/coding-agent/test/kernel-bootstrap.test.ts b/packages/coding-agent/test/kernel-bootstrap.test.tsindex f1cf37a88f..d81ccee49c 100644--- a/packages/coding-agent/test/kernel-bootstrap.test.ts+++ b/packages/coding-agent/test/kernel-bootstrap.test.ts@@ -519,7 +519,7 @@ dependencies = ["httpx"]writeFakePython(overridePython, ["dill"]);process.env.PRIME_AGENT_KERNEL_PYTHON = overridePython;- await expect(ensureKernelPython()).rejects.toThrow(/current prime-agent-runtime with callable rlm\.run/);+ await expect(ensureKernelPython()).rejects.toThrow(/current prime-agent-runtime with callable rlm\.spawn/);});it("rejects PRIME_AGENT_KERNEL_PYTHON with a legacy harness API", async () => {@@ -542,7 +542,7 @@ dependencies = ["httpx"]);process.env.PRIME_AGENT_KERNEL_PYTHON = overridePython;- await expect(ensureKernelPython()).rejects.toThrow(/current prime-agent-runtime with callable rlm\.run/);+ await expect(ensureKernelPython()).rejects.toThrow(/current prime-agent-runtime with callable rlm\.spawn/);});it("fails an invalid PRIME_AGENT_KERNEL_PYTHON without bootstrapping", async () => {diff --git a/packages/coding-agent/test/refinement.test.ts b/packages/coding-agent/test/refinement.test.tsindex d8e2731859..26495159ed 100644--- a/packages/coding-agent/test/refinement.test.ts+++ b/packages/coding-agent/test/refinement.test.ts@@ -1349,7 +1349,7 @@ describe("global refinement history", () => {const userPrompt = request.messages[0].content[0].text;expect(userPrompt).toContain("Requested refinement scope: local");expect(userPrompt).toContain("Global entries in the overview are read-only context");- expect(request.systemPrompt).toContain('handle = await rlm("sub-task")');+ expect(request.systemPrompt).toContain('handle = await rlm.spawn("sub-task", name="worker")');expect(request.systemPrompt).toContain("never the child's answer");expect(request.systemPrompt).toContain('receiver_role="parent"');expect(request.systemPrompt).toContain("await rlm.list_subagents()");diff --git a/packages/coding-agent/test/repl-kernel-execute.test.ts b/packages/coding-agent/test/repl-kernel-execute.test.tsindex c653bce98f..5365fcdd16 100644--- a/packages/coding-agent/test/repl-kernel-execute.test.ts+++ b/packages/coding-agent/test/repl-kernel-execute.test.ts@@ -122,6 +122,41 @@ describeIf("ReplKernelManager execute (real runtime)", () => {expect(unknown.error?.evalue).toContain('host request type "test.unknown" is not available');}, 30_000);+ it("spawns through rlm.spawn over the unchanged rlm.run wire type, requires a child name, and refuses a direct rlm call", async () => {+ const requestTypes: string[] = [];+ const hostHandlers: HostRequestHandlers = {+ "rlm.run": async (payload) => {+ requestTypes.push("rlm.run");+ expect(payload.prompt).toBe("child work");+ return {+ rlm_child_id: "sub-a1b2c3d4",+ name: "worker",+ session_dir: dir,+ model: "anthropic/claude-opus-4-7",+ };+ },+ };+ manager = new ReplKernelManager({ python: python as string, cwd: dir, hostHandlers });++ const spawned = await manager.execute(+ "import rlm\nhandle = await rlm.spawn('child work', name='worker')\nhandle.name",+ );+ expect(spawned.status).toBe("ok");+ expect(spawned.result).toBe("'worker'");+ expect(requestTypes).toEqual(["rlm.run"]);++ const nameless = await manager.execute("await rlm.spawn('child work')");+ expect(nameless.status).toBe("error");+ expect(nameless.error?.ename).toBe("TypeError");+ expect(nameless.error?.evalue).toContain("required keyword-only argument: 'name'");+ expect(requestTypes).toEqual(["rlm.run"]);++ const called = await manager.execute("await rlm('child work')");+ expect(called.status).toBe("error");+ expect(called.error?.ename).toBe("TypeError");+ expect(called.error?.evalue).toContain("await rlm.spawn(");+ }, 30_000);+it("dispose sends the protocol shutdown so live bash children die with the kernel", async () => {manager = new ReplKernelManager({ python: python as string, cwd: dir });const r = await manager.execute("from rlm import bash\nh = bash('sleep 600')\nh.pid");diff --git a/packages/coding-agent/test/suite/agent-session-prompt.test.ts b/packages/coding-agent/test/suite/agent-session-prompt.test.tsindex c06fb3035f..a88a0db1c6 100644--- a/packages/coding-agent/test/suite/agent-session-prompt.test.ts+++ b/packages/coding-agent/test/suite/agent-session-prompt.test.ts@@ -496,11 +496,11 @@ active extension doctrine`,const promptPromise = harness.session.prompt("start");await responseStarted.promise;expect(harness.session.agent.state.systemPrompt).toContain("active extension doctrine");- expect(harness.session.agent.state.systemPrompt).not.toContain("A callable `rlm`");+ expect(harness.session.agent.state.systemPrompt).not.toContain("An `rlm` object");await harness.session.setRlmMaxDepth(2);- expect(harness.session.agent.state.systemPrompt).toContain("A callable `rlm`");+ expect(harness.session.agent.state.systemPrompt).toContain("An `rlm` object");expect(harness.session.agent.state.systemPrompt).toContain("active extension doctrine");responseGate.resolve();await promptPromise;diff --git a/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts b/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.tsindex 64b5d630ee..78b2f5ec02 100644--- a/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts+++ b/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts@@ -427,7 +427,7 @@ describe("ENG-4649 subagent model selection", () => {});try {await expect(harness.session.runRlmChild("bad type", { model: 42 })).rejects.toThrow(- "rlm.run model must be a string",+ "rlm.spawn model must be a string",);await expect(harness.session.runRlmChild("unknown model", { model: `${provider}/missing-model` }),diff --git a/packages/coding-agent/test/system-prompt.test.ts b/packages/coding-agent/test/system-prompt.test.tsindex dde3273f62..d877e9a302 100644--- a/packages/coding-agent/test/system-prompt.test.ts+++ b/packages/coding-agent/test/system-prompt.test.ts@@ -44,7 +44,7 @@ describe("buildRlmPrompt", () => {});expect(prompt).toContain("Installed Python skill modules (pre-imported): `websearch`.");- expect(prompt).toContain("A callable `rlm` is already in your global namespace");+ expect(prompt).toContain("An `rlm` object is already in your global namespace");expect(prompt).toContain("persistent Python REPL");expect(prompt).toContain("Python is the orchestration language");});@@ -337,7 +337,7 @@ describe("buildSystemPrompt", () => {expect(prompt).toContain("Call contract: read each installed Python skill's SKILL.md");expect(prompt).toContain("Continual harness skill entries are Python REPL skills");expect(prompt).toContain("Spawn a continual harness subagent spec by composing a concise task prompt");- expect(prompt).toContain("handle = await rlm('sub-task')");+ expect(prompt).toContain("handle = await rlm.spawn('sub-task', name='worker')");expect(prompt).toContain("admission returns immediately");expect(prompt).toContain("never the child's answer");expect(prompt).toContain("receiver_role='parent'");@@ -430,7 +430,7 @@ describe("buildSystemPrompt", () => {expect(prompt).toContain("You are a general purpose agent that uses code to solve tasks.");expect(prompt).toContain("Working directory: /repo");expect(prompt).toContain("Conversation log: /repo/.pi/sessions/session.jsonl");- expect(prompt).toContain("await rlm('sub-task')");+ expect(prompt).toContain("await rlm.spawn('sub-task', name='api-reviewer')");expect(prompt).toContain("returns at admission, not completion");expect(prompt).toContain("Results arrive only through an available messaging capability or files");expect(prompt).toContain("recover direct child handles");diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.pyindex 53776789ba..8d416e0c14 100644--- a/prime-agent-runtime/src/rlm/__init__.py+++ b/prime-agent-runtime/src/rlm/__init__.py@@ -11,6 +11,10 @@ from typing import Anyfrom .bash import BashHandle, BashResult, bashfrom .harness import HarnessEntry, HarnessScope, HarnessState, RefinementEvent, get_harness_state+_NOT_CALLABLE_MESSAGE = "'rlm' is not callable; spawn a child with: handle = await rlm.spawn('sub-task', name='worker')"+_RENAMED_RUN_MESSAGE = "rlm.run was renamed; spawn a child with: handle = await rlm.spawn('sub-task', name='worker')"++@dataclass(frozen=True)class RLMSpawnHandle:rlm_child_id: str@@ -48,13 +52,13 @@ class RLMSubagent:def _spawn_handle_from_payload(payload: Any) -> RLMSpawnHandle:if not isinstance(payload, dict):- raise RuntimeError("rlm.run returned an invalid spawn handle")+ raise RuntimeError("rlm.spawn returned an invalid spawn handle")child_id = payload.get("rlm_child_id")name = payload.get("name")session_dir = payload.get("session_dir")model = payload.get("model")if not all(isinstance(value, str) and value for value in (child_id, name, session_dir, model)):- raise RuntimeError("rlm.run returned an invalid spawn handle")+ raise RuntimeError("rlm.spawn returned an invalid spawn handle")return RLMSpawnHandle(rlm_child_id=child_id,name=name,@@ -117,15 +121,28 @@ def emit(data: dict[str, Any]) -> None:repl.emit(data)-async def run(prompt: str, **kwargs: Any) -> RLMSpawnHandle:+async def spawn(+ prompt: str,+ *,+ name: str,+ model: str | None = None,+ thinking: str | None = None,+) -> RLMSpawnHandle:"""Spawn a recursive Prime Agent child and return once its task is admitted.+ ``name`` is required and must be unique among siblings.``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."""if not isinstance(prompt, str):raise TypeError(f"prompt must be str, got {type(prompt).__name__}")+ kwargs: dict[str, Any] = {"name": name}+ if model is not None:+ kwargs["model"] = model+ if thinking is not None:+ kwargs["thinking"] = thinking+ # Wire type stays "rlm.run" so kernels and hosts of different versions stay compatible.payload = await host_request("rlm.run", {"prompt": prompt, "kwargs": kwargs})return _spawn_handle_from_payload(payload)@@ -285,12 +302,19 @@ class _HarnessProxy:_harness_state = _HarnessProxy()-class _RLMCallable:+class _RLMNamespace:harness = _harness_stateget_harness_state = staticmethod(get_harness_state)- async def run(self, prompt: str, **kwargs: Any) -> RLMSpawnHandle:- return await run(prompt, **kwargs)+ async def spawn(+ self,+ prompt: str,+ *,+ name: str,+ model: str | None = None,+ thinking: str | None = None,+ ) -> RLMSpawnHandle:+ return await spawn(prompt, name=name, model=model, thinking=thinking)async def create_session(self,@@ -311,20 +335,26 @@ class _RLMCallable:async def delete_subagent(self, target: str | RLMSubagent) -> RLMSubagent:return await delete_subagent(target)- async def __call__(self, prompt: str, **kwargs: Any) -> RLMSpawnHandle:- return await run(prompt, **kwargs)+ def __call__(self, *args: Any, **kwargs: Any) -> Any:+ raise TypeError(_NOT_CALLABLE_MESSAGE)++ # AttributeError keeps hasattr() semantics intact while still naming the replacement.+ def __getattr__(self, name: str) -> Any:+ if name == "run":+ raise AttributeError(_RENAMED_RUN_MESSAGE)+ raise AttributeError(f"'rlm' object has no attribute {name!r}")-rlm = _RLMCallable()+rlm = _RLMNamespace()harness = _harness_state-class _CallableModule(types.ModuleType):- async def __call__(self, prompt: str, **kwargs: Any) -> RLMSpawnHandle:- return await run(prompt, **kwargs)+class _NotCallableModule(types.ModuleType):+ def __call__(self, *args: Any, **kwargs: Any) -> Any:+ raise TypeError(_NOT_CALLABLE_MESSAGE)-sys.modules[__name__].__class__ = _CallableModule+sys.modules[__name__].__class__ = _NotCallableModule__all__ = ["BashHandle",@@ -350,7 +380,7 @@ __all__ = ["host_request","list_subagents","rlm",- "run",+ "spawn",]# Lazily re-export the MCP base class. Kept lazy so `import rlm` never requires@@ -363,4 +393,6 @@ def __getattr__(name: str) -> Any: # noqa: D401 - module-level lazy attr hookfrom . import mcp_basereturn getattr(mcp_base, name)+ if name == "run":+ raise AttributeError(_RENAMED_RUN_MESSAGE)raise AttributeError(f"module {__name__!r} has no attribute {name!r}")diff --git a/prime-agent-runtime/src/rlm/harness.py b/prime-agent-runtime/src/rlm/harness.pyindex 3d2f0af8ef..71452e5908 100644--- a/prime-agent-runtime/src/rlm/harness.py+++ b/prime-agent-runtime/src/rlm/harness.py@@ -4,7 +4,7 @@ The state model is intentionally small: it records prompt notes, memory,skills, subagent specs, and refinement events in the session-local harnessstore by default; pass ``global_=True`` for the cross-session global store.Execution still belongs to Prime Agent's TypeScript host and the existing-``rlm.run`` recursion bridge.+``rlm.spawn`` recursion bridge."""from __future__ import annotations@@ -746,7 +746,7 @@ class HarnessState:"Call contract: installed Python skills use await <skill_import>(...) or a matching shell CLI; ""harness skill entries are Python REPL skills and must include a Python reference plus arguments. ""Spawn a subagent spec by composing a concise task prompt and calling "- "handle = await rlm('sub-task'); admission returns immediately with rlm_child_id, name, session_dir, "+ "handle = await rlm.spawn('sub-task', name='worker'); admission returns immediately with rlm_child_id, name, session_dir, ""and model, never the child's answer. Results arrive only through explicit agent_message replies or ""files; children reply with await agent_message.send(message, receiver_role='parent'). Use ""await rlm.list_subagents() to recover direct child handles and await agent_message.send(..., "diff --git a/prime-agent-runtime/test/test_harness.py b/prime-agent-runtime/test/test_harness.pyindex 8fc4afec4d..49cc7c06f1 100644--- a/prime-agent-runtime/test/test_harness.py+++ b/prime-agent-runtime/test/test_harness.py@@ -127,7 +127,7 @@ class HarnessStateTest(unittest.TestCase):reloaded.overview(),)overview = reloaded.overview()- self.assertIn("handle = await rlm('sub-task')", overview)+ self.assertIn("handle = await rlm.spawn('sub-task', name='worker')", overview)self.assertIn("never the child's answer", overview)self.assertIn("receiver_role='parent'", overview)self.assertIn("await rlm.list_subagents()", overview)diff --git a/prime-agent-runtime/test/test_subagent_registry.py b/prime-agent-runtime/test/test_subagent_registry.pyindex 99b86038c0..ad38ca77b4 100644--- a/prime-agent-runtime/test/test_subagent_registry.py+++ b/prime-agent-runtime/test/test_subagent_registry.py@@ -73,7 +73,7 @@ class RlmSubagentRegistryTest(unittest.TestCase):with patch.object(rlm_module, "host_request", host_request):result = asyncio.run(- rlm_module.rlm(+ rlm_module.rlm.spawn("check the API",name="api-reviewer",model="deepseek/deepseek-v4-flash",@@ -94,6 +94,22 @@ class RlmSubagentRegistryTest(unittest.TestCase):self.assertEqual(result.name, "api-reviewer")self.assertEqual(result.model, "deepseek/deepseek-v4-flash")+ def test_requires_an_explicit_child_name(self) -> None:+ host_request = AsyncMock()+ with patch.object(rlm_module, "host_request", host_request):+ with self.assertRaisesRegex(TypeError, r"missing 1 required keyword-only argument: 'name'"):+ asyncio.run(rlm_module.rlm.spawn("check the API"))+ host_request.assert_not_awaited()++ def test_rejects_calling_rlm_directly_with_spawn_guidance(self) -> None:+ for target in (rlm_module.rlm, rlm_module):+ with self.assertRaisesRegex(TypeError, r"not callable; spawn a child with: handle = await rlm\.spawn\("):+ target("check the API")+ for target in (rlm_module, rlm_module.rlm):+ with self.assertRaisesRegex(AttributeError, r"rlm\.run was renamed; spawn a child with: handle = await rlm\.spawn\("):+ target.run+ self.assertFalse(hasattr(target, "run"))+def test_finds_authenticated_models_through_host(self) -> None:host_request = AsyncMock(return_value={