A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
CRUD subagents and naming (#390)
Seth Karten990025d3535f
diff --git a/packages/ai/test/prime-inference-models.test.ts b/packages/ai/test/prime-inference-models.test.tsindex 9d373c2c55..331fe43252 100644--- a/packages/ai/test/prime-inference-models.test.ts+++ b/packages/ai/test/prime-inference-models.test.ts@@ -71,11 +71,13 @@ describe("Prime Inference models", () => {expect(gemini.reasoning).toBe(true);// The HF-style ultra id maps onto OpenRouter's short id via alias for- // pricing/modality, but the gateway enforces a 131k window (measured- // 2026-07-08), so the curated override wins for contextWindow.+ // modality/reasoning, but the gateway enforces a 131k window (measured+ // 2026-07-08), so the curated override wins for contextWindow. OpenRouter+ // may omit its live output cap, in which case the conservative fallback wins.const ultra = getModel("prime-inference", "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B");expect(ultra.contextWindow).toBe(131072);- expect(ultra.maxTokens).toBe(16384);+ expect(ultra.maxTokens).toBeGreaterThan(0);+ expect(ultra.maxTokens).toBeLessThanOrEqual(ultra.contextWindow);const maverick = getModel("prime-inference", "meta-llama/llama-4-maverick");expect(maverick.contextWindow).toBe(1048576);diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex add0243f2a..1e0fb2f701 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -2,6 +2,7 @@## [Unreleased]+- Added parent-scoped subagent lifecycle APIs: create children with readable default or orchestrator-chosen names, recover running or completed children through `rlm.list_subagents()`, continue them through agent messaging, and close/remove them with `rlm.delete_subagent()`.- Changed shell commands to use discoverable agent, schedule, package, model, session, update, doctor, and full-shutdown verbs without exposing the background daemon hierarchy ([ENG-4538](https://linear.app/primeintellect/issue/ENG-4538/standardize-bash-command-conventions-and-improve-command-discovery)).- Fixed unsupported Node versions crashing before startup by requiring Node 22.8.0 or newer and showing upgrade guidance before loading the CLI ([ENG-4260](https://linear.app/primeintellect/issue/ENG-4260/incorrect-node-version-breaks-first-launch)).- Added `@` file-path autocomplete to new-agent and reply prompts in the Agents View.diff --git a/packages/coding-agent/docs/kernel-and-rlm-recursion.md b/packages/coding-agent/docs/kernel-and-rlm-recursion.mdindex fb734fe2d5..de5e88497b 100644--- a/packages/coding-agent/docs/kernel-and-rlm-recursion.md+++ b/packages/coding-agent/docs/kernel-and-rlm-recursion.md@@ -69,13 +69,13 @@ packages/coding-agent/src/core/agent-session.tsParent session owns recursion settings and implements runRlmChild().packages/coding-agent/src/core/rlm-runtime.ts- TypeScript request/result types for rlm.run and the adapter that registers- it as a typed host request handler.+ TypeScript request/result types for rlm.run, rlm.list_subagents, and+ rlm.delete_subagent plus their typed host request handlers.prime-agent-runtime/src/rlm/__init__.pyPython shim installed into ~/.prime/agent/kernel-venv. Exposes rlm, rlm.run(),- host_request(), RLMResult, TokenUsage, and the session-backed harness state- helper.+ rlm.list_subagents(), rlm.delete_subagent(), host_request(), RLMResult,+ RLMSubagent, TokenUsage, and the session-backed harness state helper.prime-agent-runtime/src/rlm/harness.pySession-backed JSON store for reset-free harness refinement notes: prompt@@ -382,8 +382,10 @@ It exports:```pythonrlmrun(prompt: str, **kwargs)+list_subagents()host_request(request_type: str, payload: dict | None = None)RLMResult+RLMSubagentTokenUsage```@@ -440,7 +442,7 @@ awaits the FutureThe callback strips the reply's `status` field and converts the payload into `RLMResult`, or raises `RuntimeError` when the host reports an error. The comm-open/await machinery is the public `host_request()`; `run()` is a typed wrapper around it, and other kernel-side skills reuse `host_request()` for their own request types.-The shim accepts `**kwargs` for API compatibility with `rlm-harness` and includes them in the comm payload. V1 does not apply any kwargs on the TypeScript side. Unsupported kwargs are rejected with a clear error instead of being ignored.+The shim accepts `**kwargs` and includes them in the comm payload. The TypeScript host supports `name="..."` for an orchestrator-chosen child session name; all other kwargs are rejected with a clear error instead of being ignored.### Why Control-Channel Comm Replies Exist@@ -508,6 +510,9 @@ options.hostHandlers[data.type](data)sendCommMessage(comm_id, { status: "ok", ...result })```+The RLM handlers include `rlm.run` for child creation and+`rlm.list_subagents` for the current parent session's automatic child registry.+Unknown types fail with `host request type "<type>" is not available in this session`.Errors are returned as:@@ -601,6 +606,83 @@ Turns are counted as assistant messages in the child transcript.The answer is the child's final assistant text. This matches the RLM-1 training surface: the model stops calling tools and the final assistant text is the answer.+### Parent-Scoped Subagent Registry++The host exposes the current parent session's direct children without relying on+Python task handles or a model-maintained file:++```python+children = await rlm.list_subagents()+for child in children:+ print(+ child.rlm_child_id,+ child.active_session_id,+ child.session_id,+ child.session_name,+ child.session_dir,+ child.status,+ )+```++Entries have status `running` while the initial `rlm()` call is active and+`completed` after a successful call returns. Every child also gets a readable,+collision-resistant default `session_name` derived from its task and child ID,+for example `subagent-check-the-http-api-a1b2c3d4`. The orchestrator can choose+an exact name at spawn time with `await rlm("Check the API", name="api-reviewer")`;+empty, overlong, or already-addressable names are rejected. Users and+orchestrators can rename it later without changing the child ID. Failed or+cancelled children are+removed. Because the registry is owned by the TypeScript parent session, it+remains available after kernel restart, state restore, or compaction even if the+original Python `asyncio.Task` handle was lost.++In daemon mode `active_session_id` identifies the retained child session. The+same parent/orchestrator can continue it directly:++```python+children = await rlm.list_subagents()+child = next((item for item in children if item.active_session_id), None)+if child is not None:+ await agent_message.send(child.session_name, "Check the latest change.")+```++That message starts an ordinary follow-up turn in the existing child context; it+does not reopen or alter the completed `rlm()` result. Inline and in-process+children have `active_session_id=None`, so they remain inspectable but are not+addressable through daemon agent messaging.++Delete a direct child by passing its registry entry or any exact registry+identifier (`session_name`, `rlm_child_id`, `session_id`, or+`active_session_id`):++```python+child = (await rlm.list_subagents())[0]+deleted = await rlm.delete_subagent(child)+# Equivalent when the child has a chosen name:+# deleted = await rlm.delete_subagent("api-reviewer")+```++Deletion cancels a running child and waits for its runtime to close. A completed+retained child closes immediately. In both cases it is removed from+`rlm.list_subagents()` and, in daemon mode, from agent messaging and observation.+Deletion does not erase the child's session transcript or artifacts on disk.+Only direct children in the current parent registry can be selected; unknown or+ambiguous selectors raise an error. The returned `RLMSubagent` is the deleted+entry's final registry snapshot.++Together these APIs provide the parent-scoped lifecycle operations: create with+`rlm(...)`, read with `rlm.list_subagents()` and `agent_observe`, continue/update+with `agent_message.send(...)`, and delete with `rlm.delete_subagent(...)`.++The registry is scoped to the parent session transcript. Closing or replacing a+daemon runtime cascades cleanup to its resident children; reopening that same+parent session rehydrates its successfully completed children from the+parent's artifact registry so they remain listable, messageable, and deletable.+An unrelated new parent session inherits nothing, and inline children are not+rehydrated. Deletion writes a durable tombstone before it reports success, so a+deleted child stays removed while its transcript and artifacts remain on disk.+There is no task/result migration or general cross-session reopen API.+### Cost Accounting`RLMResult.usage` reports the child session's token usage. The parent session's displayed usage and cost do not currently fold child usage into the parent assistant-message totals. Child cost is independent in v1 and should be read from the child result or child session until parent aggregation is added.diff --git a/packages/coding-agent/skills/agent-message/SKILL.md b/packages/coding-agent/skills/agent-message/SKILL.mdindex e14d9c4119..0b2f8ddac9 100644--- a/packages/coding-agent/skills/agent-message/SKILL.md+++ b/packages/coding-agent/skills/agent-message/SKILL.md@@ -1,6 +1,6 @@---name: agent-message-description: Message other active Prime Agent sessions through the daemon. Use to discover active agents and send a direct text message without spoofing sender identity.+description: Message other active Prime Agent sessions, including completed retained subagents, through the daemon. Use to discover active agents and send a direct text message without spoofing sender identity.---# Agent Message@@ -12,8 +12,15 @@ not try to include a `from` field.Call directly from the kernel:```python-agents = await agent_message.list_agents()-receipt = await agent_message.send("worker", "Please inspect the latest result.", mode="auto")+children = await rlm.list_subagents()+child = next((item for item in children if item.active_session_id), None)+if child is not None:+ receipt = await agent_message.send(+ child.session_name,+ "Please inspect the latest result.",+ mode="auto",+ )+ # Keep the child until this follow-up finishes so its result remains observable.```## API@@ -21,12 +28,17 @@ receipt = await agent_message.send("worker", "Please inspect the latest result."- `await agent_message.list_agents()` — returns `current` and `agents`, whereeach agent includes active session id, session id, optional name, runtimekind, cwd, streaming state, and pending message count. This includes live- subagents; filter by `runtimeKind == "subagent"`, `parentActiveSessionId`,- or `rlmChildId` before messaging a specific subagent.+ subagents and successful completed subagents retained by an open parent.+ For the current parent session's direct children, prefer+ `await rlm.list_subagents()` over filtering this global list. Every RLM child+ gets a readable unique `session_name`, or the orchestrator can choose one with+ `rlm("task", name="api-reviewer")`; use that name directly as a target.- `await agent_message.send(target, message, mode="auto")` — sends one direct- text message to an active session. `target` is resolved by the daemon like- other live-session selectors. `mode` is `"auto"`, `"follow_up"`, or- `"steer"`. In `auto` mode, messages to busy sessions are queued as steering+ text message to an active session. Sending to an idle completed subagent+ starts an ordinary follow-up turn in that same child session and context.+ The child remains available only until its parent session closes. `target`+ is resolved by the daemon like other live-session selectors. `mode` is+ `"auto"`, `"follow_up"`, or `"steer"`. In `auto` mode, messages to busy sessions are queued as steeringmessages so the target sees them during the active run; use `"follow_up"` forintentionally delayed delivery. Returns a receipt with a `deliveryStatus`field: `"delivered"` means the message reached an idle target's context;@@ -36,6 +48,10 @@ receipt = await agent_message.send("worker", "Please inspect the latest result."## Safety+- Do not delete a child immediately after `send`: delivered follow-ups may still+ be running and queued receipts have not run yet. Wait until observation shows+ the child is idle and its context is no longer needed before calling+ `await rlm.delete_subagent(child)`.- Broadcast sends are not supported.- Sender identity is daemon-derived and cannot be spoofed from Python.- The daemon enforces message size, rate, and pending-queue limits beforediff --git a/packages/coding-agent/skills/agent-observe/SKILL.md b/packages/coding-agent/skills/agent-observe/SKILL.mdindex d213cf54fd..a8116f326a 100644--- a/packages/coding-agent/skills/agent-observe/SKILL.md+++ b/packages/coding-agent/skills/agent-observe/SKILL.md@@ -13,9 +13,13 @@ mutate another session.Call directly from the kernel:```python-agents = await agent_observe.list_agents()-worker = await agent_observe.get_agent("worker")-recent = await agent_observe.recent_messages("worker", limit=6)+children = await rlm.list_subagents()+child = next((item for item in children if item.active_session_id), None)+if child is not None:+ worker = await agent_observe.get_agent(child.session_name)+ recent = await agent_observe.recent_messages(child.session_name, limit=6)+ # Deletion is a parent-owned RLM operation, not an observe mutation:+ await rlm.delete_subagent(child)```## API@@ -23,9 +27,12 @@ recent = await agent_observe.recent_messages("worker", limit=6)- `await agent_observe.list_agents()` returns `current` and `agents`. Eachagent includes active session id, session id, optional name, runtime kind,cwd, status, streaming state, message count, pending count, and a latest- message preview. This includes subagents shown in the agents view; filter- by `runtimeKind == "subagent"` and `parentSessionId` or- `parentActiveSessionId` to inspect subagents that belong to your session.+ message preview. This includes live subagents and successful completed+ subagents retained by an open parent. For the current parent session's direct+ children, prefer `await rlm.list_subagents()` over filtering this global+ list. Every RLM child gets a readable unique `session_name`, or the+ orchestrator can choose one with `rlm("task", name="api-reviewer")`; use that+ name directly as an observation target.- `await agent_observe.get_agent(target)` returns `agent`, where `agent`contains one agent summary. `target` is resolved like other live-sessionselectors: active id, session id/name, or unambiguous suffix.diff --git a/packages/coding-agent/src/core/agent-session-runtime.ts b/packages/coding-agent/src/core/agent-session-runtime.tsindex 8eda0a5b05..dbbb929335 100644--- a/packages/coding-agent/src/core/agent-session-runtime.ts+++ b/packages/coding-agent/src/core/agent-session-runtime.ts@@ -384,6 +384,13 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {this.subagentRuntimes.set(options.id, runtime);try {await runtime.session.bindExtensions({});+ if (options.parentSession.getRlmChildRunStatus(options.id) === "cancelled") {+ throw new Error("RLM subagent startup was cancelled");+ }+ if (runtime.session.sessionName !== options.sessionName) {+ runtime.session.setSessionName(options.sessionName);+ }+ options.onSessionPublished?.(runtime.session);} catch (error) {this.subagentRuntimes.delete(options.id);await runtime.dispose();@@ -392,6 +399,23 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {return runtime;}+ async deleteRlmSubagentRuntime(childId: string, session: AgentSession): Promise<void> {+ const runtime = this.subagentRuntimes.get(childId);+ if (!runtime) {+ await session.disposeAsync();+ return;+ }+ this.subagentRuntimes.delete(childId);+ const shouldDisposeStaleSession = runtime.session !== session;+ try {+ await runtime.dispose();+ } finally {+ if (shouldDisposeStaleSession) {+ await session.disposeAsync();+ }+ }+ }+async releaseRlmSubagentRuntime(runtime: RlmSubagentRuntime,options: CreateRlmSubagentRuntimeOptions,diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 677de8f02c..0961cb2c98 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -54,6 +54,7 @@ import {AGENT_MESSAGE_RECEIVED_PREVIEW_LABEL,AGENT_MESSAGE_SKILL_NAME,type AgentSessionMessage,+ type AgentSessionMessageAgentSummary,type AgentSessionMessageController,type AgentSessionMessageListResult,type AgentSessionMessageReceipt,@@ -198,9 +199,16 @@ import { resolveConfigValue } from "./resolve-config-value.js";import type { ResourceExtensionPaths, ResourceLoader } from "./resource-loader.js";import {type CreateRlmSubagentRuntimeOptions,+ createDefaultRlmSubagentSessionName,+ createRlmDeleteSubagentHostHandler,+ createRlmListSubagentsHostHandler,createRlmRunHostHandler,+ normalizeRequestedRlmSubagentSessionName,+ type RlmDeleteSubagentResult,type RlmInternalRunResult,+ type RlmListSubagentsResult,type RlmRunResult,+ type RlmSubagentRegistryEntry,type RlmSubagentReleaseStatus,type RlmSubagentRuntime,type RlmUsage,@@ -241,6 +249,8 @@ export interface RlmChildAgentSnapshot {id: string;parentId?: string;activeSessionId?: string;+ /** Stable daemon-visible session name for addressing/displaying the child. */+ sessionName?: string;label: string;status: RlmChildAgentStatus;durationMs?: number;@@ -657,16 +667,24 @@ type AutonomousRuntimeSnapshot = Pick<interface RlmChildRun {id: string;prompt: string;+ sessionName: string;sessionDir: string;status: RlmChildAgentStatus;result?: RlmRunResult;error?: string;+ releaseError?: unknown;task?: Promise<RlmInternalRunResult>;abort: () => void;/** Child session, once its runtime exists. Used to cancel nested child runs. */session?: AgentSession;/** Re-emits the run's rlm_child_update snapshot with its current status. */emitUpdate?: () => void;+ /** Idempotent child-event forwarder cleanup, once the child runtime exists. */+ unsubscribe?: () => void;+ /** Rejects the public rlm.run promise when deletion detaches stuck underlying work. */+ rejectTask?: (error: Error) => void;+ /** Snapshot retained until an in-flight runtime creation is released after early deletion. */+ detachedDeletion?: RlmSubagentRegistryEntry;}// ============================================================================@@ -870,6 +888,12 @@ export class AgentSession {// Inline mode keeps finished child sessions so the inspector can still read them;// the daemon does the same by leaving the child session resident in its registry.private _retainedRlmChildSessions = new Map<string, AgentSession>();+ private _deletedRlmChildIds = new Set<string>();+ private _retryableRlmSubagentDeletions = new Map<string, RlmSubagentRegistryEntry>();+ private _deletingRlmChildren = new Map<+ string,+ { subagent: RlmSubagentRegistryEntry; promise: Promise<RlmDeleteSubagentResult> }+ >();// Kept alive for retained children so nested updates (e.g. a grandchild cancel)// still forward to root; torn down when the retained child is disposed.private _retainedRlmChildUnsubscribes = new Map<string, () => void>();@@ -2540,6 +2564,8 @@ export class AgentSession {await session.disposeAsync().catch(() => undefined);}this._retainedRlmChildSessions.clear();+ this._deletedRlmChildIds.clear();+ this._retryableRlmSubagentDeletions.clear();try {await this._ipythonKernelProvisioner?.dispose();} catch {@@ -2569,6 +2595,8 @@ export class AgentSession {session.dispose();}this._retainedRlmChildSessions.clear();+ this._deletedRlmChildIds.clear();+ this._retryableRlmSubagentDeletions.clear();this._pendingNextTurnMessages = [];this._rejectQueuedAgentMessageDeliveries(new Error("Queued agent message was cleared before delivery."));this._steeringMessages = [];@@ -5853,6 +5881,8 @@ export class AgentSession {"rlm.run": createRlmRunHostHandler(({ prompt, kwargs, cellSourceCode }) =>this.runRlmChild(prompt, kwargs, cellSourceCode),),+ "rlm.list_subagents": createRlmListSubagentsHostHandler(() => this.listRlmSubagents()),+ "rlm.delete_subagent": createRlmDeleteSubagentHostHandler((target) => this.deleteRlmSubagent(target)),"model.info": async () => ({id: this.model?.id ?? null,provider: this.model?.provider ?? null,@@ -6096,6 +6126,7 @@ export class AgentSession {private _createRlmSubagentRuntimeOptions(options: {id: string;prompt: string;+ sessionName: string;spawnCode?: string;sessionDir: string;model: Model<any>;@@ -6104,6 +6135,7 @@ export class AgentSession {parentSession: this,id: options.id,prompt: options.prompt,+ sessionName: options.sessionName,spawnCode: options.spawnCode,sessionDir: options.sessionDir,model: options.model,@@ -6206,6 +6238,15 @@ export class AgentSession {rlmParentNodeId: options.rlmParentNodeId,sessionStartEvent: { type: "session_start", reason: "startup" },});+ if (child.sessionName !== options.sessionName) {+ try {+ child.setSessionName(options.sessionName);+ } catch (error) {+ child.dispose();+ throw error;+ }+ }+ options.onSessionPublished?.(child);return { session: child };}@@ -6235,10 +6276,221 @@ export class AgentSession {return this._activeRlmChildRuns.get(childId)?.status;}+ /** Current direct-child registry for the model-facing rlm.list_subagents API. */+ listRlmSubagents(): RlmListSubagentsResult {+ const daemonChildren = new Map<string, AgentSessionMessageAgentSummary>();+ const listedAgents = this._agentMessageController?.listAgents();+ const parentActiveSessionId = listedAgents?.current?.activeSessionId;+ if (parentActiveSessionId) {+ for (const agent of listedAgents.agents) {+ if (+ agent.runtimeKind === "subagent" &&+ agent.parentActiveSessionId === parentActiveSessionId &&+ agent.rlmChildId+ ) {+ daemonChildren.set(agent.rlmChildId, agent);+ }+ }+ }++ const subagents: RlmListSubagentsResult["subagents"] = [];+ const recorded = new Set<string>();+ for (const run of this._activeRlmChildRuns.values()) {+ if (this._deletingRlmChildren.has(run.id) || run.status === "error" || run.status === "cancelled") {+ continue;+ }+ const daemonChild = daemonChildren.get(run.id);+ subagents.push({+ rlm_child_id: run.id,+ active_session_id: daemonChild?.activeSessionId ?? null,+ session_id: daemonChild?.sessionId ?? run.session?.sessionId ?? null,+ session_name: daemonChild?.sessionName ?? run.session?.sessionName ?? run.sessionName,+ session_dir: run.sessionDir,+ status: run.status === "done" ? "completed" : "running",+ });+ recorded.add(run.id);+ }+ for (const [childId, childSession] of this._retainedRlmChildSessions) {+ if (+ this._deletingRlmChildren.has(childId) ||+ recorded.has(childId) ||+ this._retryableRlmSubagentDeletions.has(childId)+ ) {+ continue;+ }+ const daemonChild = daemonChildren.get(childId);+ const sessionDir = childSession._rlmSessionDir;+ if (!sessionDir) {+ continue;+ }+ subagents.push({+ rlm_child_id: childId,+ active_session_id: daemonChild?.activeSessionId ?? null,+ session_id: daemonChild?.sessionId ?? childSession.sessionId,+ session_name:+ daemonChild?.sessionName ?? childSession.sessionName ?? createDefaultRlmSubagentSessionName("", childId),+ session_dir: sessionDir,+ status: "completed",+ });+ }+ return { subagents };+ }++ private _rlmSubagentMatchesTarget(entry: RlmSubagentRegistryEntry, target: string): boolean {+ return (+ entry.rlm_child_id === target ||+ entry.active_session_id === target ||+ entry.session_id === target ||+ entry.session_name === target+ );+ }++ private _resolveDirectRlmSubagent(target: string): RlmSubagentRegistryEntry {+ const candidates = [...this.listRlmSubagents().subagents, ...this._retryableRlmSubagentDeletions.values()];+ const matches = candidates.filter((entry) => this._rlmSubagentMatchesTarget(entry, target));+ if (matches.length === 0) {+ throw new Error(`No direct RLM subagent matches "${target}" in the current parent session`);+ }+ if (matches.length > 1) {+ throw new Error(`RLM subagent selector "${target}" is ambiguous in the current parent session`);+ }+ return matches[0]!;+ }++ /** Delete a running or retained direct child selected from this parent session's registry. */+ async deleteRlmSubagent(target: string): Promise<RlmDeleteSubagentResult> {+ const inFlight = [...this._deletingRlmChildren.values()].filter(({ subagent }) =>+ this._rlmSubagentMatchesTarget(subagent, target),+ );+ const directMatches = [+ ...this.listRlmSubagents().subagents,+ ...this._retryableRlmSubagentDeletions.values(),+ ].filter((entry) => this._rlmSubagentMatchesTarget(entry, target));+ const matchingChildIds = new Set([+ ...inFlight.map(({ subagent }) => subagent.rlm_child_id),+ ...directMatches.map((subagent) => subagent.rlm_child_id),+ ]);+ if (matchingChildIds.size > 1) {+ throw new Error(`RLM subagent selector "${target}" is ambiguous in the current parent session`);+ }+ if (inFlight[0]) {+ return inFlight[0].promise;+ }++ const subagent = directMatches[0] ?? this._resolveDirectRlmSubagent(target);+ const deletion = this._deleteResolvedRlmSubagent(subagent);+ this._deletingRlmChildren.set(subagent.rlm_child_id, { subagent, promise: deletion });+ try {+ return await deletion;+ } finally {+ if (this._deletingRlmChildren.get(subagent.rlm_child_id)?.promise === deletion) {+ this._deletingRlmChildren.delete(subagent.rlm_child_id);+ }+ }+ }++ private _deleteRlmSubagentSession(childId: string, session: AgentSession): Promise<void> {+ if (this._subagentRuntimeHost) {+ return this._subagentRuntimeHost.deleteRlmSubagentRuntime(childId, session);+ }+ return session.disposeAsync();+ }++ private _removeRlmSubagentTracking(childId: string, run?: RlmChildRun): void {+ run?.unsubscribe?.();+ this._retainedRlmChildUnsubscribes.get(childId)?.();+ this._retainedRlmChildUnsubscribes.delete(childId);+ this._retainedRlmChildSessions.delete(childId);+ this._retryableRlmSubagentDeletions.delete(childId);+ if (!run || this._activeRlmChildRuns.get(childId) === run) {+ this._activeRlmChildRuns.delete(childId);+ }+ if (run) {+ run.abort = noopRlmChildAbort;+ run.unsubscribe = undefined;+ run.rejectTask = undefined;+ run.session = undefined;+ }+ }++ private async _deleteResolvedRlmSubagent(subagent: RlmSubagentRegistryEntry): Promise<RlmDeleteSubagentResult> {+ const childId = subagent.rlm_child_id;+ const run = this._activeRlmChildRuns.get(childId);+ if (run) {+ this._cancelRlmChildRun(run, "Deleted by parent orchestrator");+ const liveSession = run.session;+ if (liveSession) {+ try {+ await this._deleteRlmSubagentSession(childId, liveSession);+ } catch (error) {+ // The initial run was cancelled even though host closure failed. Reject its+ // public promise now. Parent teardown owns cleanup once it starts, so do not+ // repopulate maps that dispose() has already cleared.+ run.rejectTask?.(new Error("Deleted by parent orchestrator"));+ if (this._disposed || this._disposing) {+ this._removeRlmSubagentTracking(childId, run);+ void liveSession.disposeAsync().catch(() => undefined);+ throw error;+ }+ this._retainedRlmChildSessions.set(childId, liveSession);+ this._retryableRlmSubagentDeletions.set(childId, subagent);+ if (run.unsubscribe) {+ this._retainedRlmChildUnsubscribes.set(childId, run.unsubscribe);+ }+ this._activeRlmChildRuns.delete(childId);+ run.abort = noopRlmChildAbort;+ run.unsubscribe = undefined;+ run.rejectTask = undefined;+ run.session = undefined;+ throw error;+ }+ // Runtime closure is the deletion boundary. Reject the public call and do+ // not wait for provider/tool work that ignored abort; the tombstone blocks+ // any late retention by the detached work task.+ run.rejectTask?.(new Error("Deleted by parent orchestrator"));+ this._deletedRlmChildIds.add(childId);+ this._removeRlmSubagentTracking(childId, run);+ return { subagent };+ }++ // Runtime creation has not published a session. Detach immediately rather+ // than blocking on tool/runtime startup; keep the selector snapshot until+ // the eventual release succeeds or becomes hidden/retryable on failure.+ run.detachedDeletion = subagent;+ run.rejectTask?.(new Error("Deleted by parent orchestrator"));+ this._deletedRlmChildIds.add(childId);+ // Keep the cancelled run tracked until startup settles. It stays hidden from+ // list/delete, reserves its selectors against reuse, and lets daemon startup's+ // open guard tear the half-bound runtime down before it becomes addressable.+ return { subagent };+ }++ const retained = this._retainedRlmChildSessions.get(childId);+ if (retained) {+ try {+ await this._deleteRlmSubagentSession(childId, retained);+ } catch (error) {+ if (this._disposed || this._disposing) {+ this._removeRlmSubagentTracking(childId);+ void retained.disposeAsync().catch(() => undefined);+ } else {+ // Hide failed cleanup from the public registry while preserving the+ // original selector and session for an explicit retry.+ this._retryableRlmSubagentDeletions.set(childId, subagent);+ }+ throw error;+ }+ }+ this._deletedRlmChildIds.add(childId);+ this._removeRlmSubagentTracking(childId);+ return { subagent };+ }+/**- * Retain a finished child session so the inspector can still read it; disposed with- * the parent. Returns false (and disposes the child) when the parent is already- * tearing down, so the caller can drop the matching event forwarder too.+ * Retain a finished child session for the parent lifetime so inspectors and+ * daemon-hosted agent messaging can keep addressing it. Returns false (and disposes+ * the child) when the parent is already tearing down, so the caller can drop the+ * matching event forwarder too.*/retainFinishedRlmChildSession(childId: string, session: AgentSession): boolean {// A child can finish concurrently while the parent is (or has) torn down; don't@@ -6247,6 +6499,9 @@ export class AgentSession {void session.disposeAsync().catch(() => undefined);return false;}+ if (this._deletingRlmChildren.has(childId) || this._deletedRlmChildIds.has(childId)) {+ return false;+ }this._retainedRlmChildSessions.set(childId, session);return true;}@@ -6316,11 +6571,58 @@ export class AgentSession {return false;}+ private _assertRlmSubagentSessionNameAvailable(name: string): void {+ const conflictsWithSelector = (endpoint: {+ activeSessionId: string;+ sessionId: string;+ sessionName?: string;+ rlmChildId?: string;+ }) =>+ endpoint.activeSessionId === name ||+ endpoint.sessionId === name ||+ endpoint.sessionName === name ||+ endpoint.rlmChildId === name;+ for (const [childId, run] of this._activeRlmChildRuns) {+ if (+ childId === name ||+ run.sessionName === name ||+ run.session?.sessionId === name ||+ run.session?.sessionName === name+ ) {+ throw new Error(`RLM subagent session name "${name}" is already in use`);+ }+ }+ for (const [childId, session] of this._retainedRlmChildSessions) {+ if (childId === name || session.sessionId === name || session.sessionName === name) {+ throw new Error(`RLM subagent session name "${name}" is already in use`);+ }+ }+ for (const subagent of this._retryableRlmSubagentDeletions.values()) {+ if (this._rlmSubagentMatchesTarget(subagent, name)) {+ throw new Error(`RLM subagent session name "${name}" is already in use`);+ }+ }+ const listedAgents = this._agentMessageController?.listAgents();+ if (+ listedAgents &&+ ((listedAgents.current ? conflictsWithSelector(listedAgents.current) : false) ||+ listedAgents.agents.some(conflictsWithSelector))+ ) {+ throw new Error(`RLM subagent session name "${name}" is already in use`);+ }+ }+private _startRlmChildRun(prompt: string, kwargs: Record<string, unknown> = {}, spawnCode?: string): RlmChildRun {- const unsupportedKwargs = Object.keys(kwargs);+ const { name: rawName, ...unsupported } = kwargs;+ const unsupportedKwargs = Object.keys(unsupported);if (unsupportedKwargs.length > 0) {throw new Error(`Unsupported rlm.run kwargs: ${unsupportedKwargs.sort().join(", ")}`);}+ const requestedSessionName = normalizeRequestedRlmSubagentSessionName(rawName);+ if (requestedSessionName) {+ assertDirectAgentMessageTarget(requestedSessionName);+ this._assertRlmSubagentSessionNameAvailable(requestedSessionName);+ }if (this._rlmDepth >= this._rlmMaxDepth) {throw new Error(`RLM recursion depth limit reached (RLM_DEPTH=${this._rlmDepth}, RLM_MAX_DEPTH=${this._rlmMaxDepth})`,@@ -6333,6 +6635,10 @@ export class AgentSession {const childSessionDir = this._createChildRlmSessionDir();const childNodeId = basename(childSessionDir);+ const sessionName = requestedSessionName ?? createDefaultRlmSubagentSessionName(prompt, childNodeId);+ if (!requestedSessionName) {+ this._assertRlmSubagentSessionNameAvailable(sessionName);+ }const startedAt = Date.now();const parentAssistantForUsage = this._findLastAssistantMessage();const label = rlmChildLabel(prompt);@@ -6347,6 +6653,7 @@ export class AgentSession {const run: RlmChildRun = {id: childNodeId,prompt,+ sessionName,sessionDir: childSessionDir,status: "running",abort: noopRlmChildAbort,@@ -6359,6 +6666,7 @@ export class AgentSession {child: {id: childNodeId,parentId: this._rlmParentNodeId,+ sessionName: childSession?.sessionName ?? sessionName,label,status: run.status,durationMs,@@ -6375,34 +6683,53 @@ export class AgentSession {run.emitUpdate = emitChildUpdate;emitChildUpdate();- const subagentOptions = this._createRlmSubagentRuntimeOptions({- id: childNodeId,- prompt,- spawnCode,- sessionDir: childSessionDir,- model,- });+ const publishChildSession = (child: AgentSession) => {+ childSession = child;+ // A host can publish before its create promise resolves. Do not restore the+ // live-session pointer if deletion already removed this run in the meantime.+ if (this._activeRlmChildRuns.get(run.id) !== run) {+ return;+ }+ run.session = child;+ run.abort = () => {+ void child.abort();+ };+ };+ const subagentOptions: CreateRlmSubagentRuntimeOptions = {+ ...this._createRlmSubagentRuntimeOptions({+ id: childNodeId,+ prompt,+ sessionName,+ spawnCode,+ sessionDir: childSessionDir,+ model,+ }),+ onSessionPublished: publishChildSession,+ };let childRuntime: RlmSubagentRuntime | undefined;let unsubscribeChild: (() => void) | undefined;+ const deletedTask = new Promise<never>((_resolve, reject) => {+ run.rejectTask = reject;+ });- const task = (async (): Promise<RlmInternalRunResult> => {+ const workTask = (async (): Promise<RlmInternalRunResult> => {try {if (isRlmChildRunCancelled(run)) {throw new Error(run.error ?? "RLM child cancelled");}childRuntime = await this._createRlmSubagentRuntime(subagentOptions);const child = childRuntime.session;- childSession = child;- run.session = child;- run.abort = () => {- void child.abort();- };- unsubscribeChild = child.subscribe((event) => {+ if (child.sessionName !== subagentOptions.sessionName) {+ child.setSessionName(subagentOptions.sessionName);+ }+ publishChildSession(child);+ const unsubscribeChildEvents = child.subscribe((event) => {if (event.type === "rlm_child_update") {this._emit(event);return;}switch (event.type) {+ case "session_info_changed":case "recap_update":emitChildUpdate();break;@@ -6437,6 +6764,15 @@ export class AgentSession {}}});+ let childEventsSubscribed = true;+ unsubscribeChild = () => {+ if (!childEventsSubscribed) {+ return;+ }+ childEventsSubscribed = false;+ unsubscribeChildEvents();+ };+ run.unsubscribe = unsubscribeChild;if (isRlmChildRunCancelled(run)) {await child.abort();throw new Error(run.error ?? "RLM child cancelled");@@ -6478,24 +6814,74 @@ export class AgentSession {} finally {const releaseStatus: RlmSubagentReleaseStatus =run.status === "cancelled" || run.status === "error" ? run.status : "done";- if (childRuntime) {- await this._releaseRlmSubagentRuntime(childRuntime, subagentOptions, releaseStatus);- }- // Keep the forwarder only if the child was actually retained (retention can- // decline when the parent is disposing); otherwise drop it.- if (unsubscribeChild) {- if (this._retainedRlmChildSessions.has(run.id)) {- this._retainedRlmChildUnsubscribes.set(run.id, unsubscribeChild);- } else {- unsubscribeChild();+ try {+ if (childRuntime) {+ await this._releaseRlmSubagentRuntime(childRuntime, subagentOptions, releaseStatus).catch((error) => {+ run.releaseError = error;+ return Promise.reject(error);+ });+ }+ } finally {+ // A later successful cancelled/error release supersedes an earlier failed+ // delete attempt; drop its hidden retry entry and selector reservation.+ if (!run.releaseError && releaseStatus !== "done" && this._retryableRlmSubagentDeletions.has(run.id)) {+ this._removeRlmSubagentTracking(run.id, run);+ }+ if (run.releaseError && releaseStatus !== "done" && childSession && run.detachedDeletion) {+ try {+ // Early deletion returned before runtime creation completed. If normal+ // release fails, use the host's delete path as a second cleanup attempt.+ await this._deleteRlmSubagentSession(run.id, childSession);+ } catch {+ // Keep a hidden selector-addressable cleanup entry rather than orphaning+ // a host runtime after delete already returned successfully.+ if (!this._disposed && !this._disposing) {+ this._retainedRlmChildSessions.set(run.id, childSession);+ this._retryableRlmSubagentDeletions.set(run.id, run.detachedDeletion);+ }+ } finally {+ run.detachedDeletion = undefined;+ }+ }+ // A host release failure after successful work leaves a retryable parent+ // entry. Failed/cancelled runs remain omitted from the public registry.+ if (+ run.releaseError &&+ releaseStatus === "done" &&+ childSession &&+ !this._disposed &&+ !this._disposing &&+ !this._deletedRlmChildIds.has(run.id)+ ) {+ this._retainedRlmChildSessions.set(run.id, childSession);+ } else if (+ run.releaseError &&+ releaseStatus !== "done" &&+ childSession &&+ !this._retryableRlmSubagentDeletions.has(run.id)+ ) {+ // Failed/cancelled runs are not registry entries, so make a best-effort+ // local cleanup unless the session is deliberately retained for retry.+ await childSession.disposeAsync().catch(() => undefined);+ }+ // Keep the forwarder only if the child was actually retained (retention can+ // decline when the parent is disposing or deleting it); otherwise drop it.+ if (unsubscribeChild) {+ if (this._retainedRlmChildSessions.has(run.id)) {+ this._retainedRlmChildUnsubscribes.set(run.id, unsubscribeChild);+ } else {+ unsubscribeChild();+ }}+ run.abort = noopRlmChildAbort;+ run.unsubscribe = undefined;+ run.rejectTask = undefined;+ run.session = undefined;+ this._activeRlmChildRuns.delete(run.id);}- run.abort = noopRlmChildAbort;- run.session = undefined;- this._activeRlmChildRuns.delete(run.id);}})();- run.task = task;+ run.task = Promise.race([workTask, deletedTask]);return run;}diff --git a/packages/coding-agent/src/core/prompts/rlm.ts b/packages/coding-agent/src/core/prompts/rlm.tsindex 54566a50bb..d6d98087ff 100644--- a/packages/coding-agent/src/core/prompts/rlm.ts+++ b/packages/coding-agent/src/core/prompts/rlm.ts@@ -40,7 +40,6 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {const activeTools = options.activeTools ?? [];const hasIpython = options.activeTools === undefined ? true : activeTools.includes("ipython");const canRunShellSkills = hasIpython || activeTools.includes("bash");- const hasAgentObserveSkill = installedSkills.includes("agent_observe");const parts = ["You are a general purpose agent that uses code to solve tasks.","You solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.",@@ -85,10 +84,10 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {parts.push("","A callable `rlm` is already in your global namespace. It returns an `RLMResult` with `.answer` (string), `.usage`, `.turns`, and `.session_dir`. A direct `await rlm('sub-task')` is valid only when the result is immediately required.",+ "Choose a stable child name with `await rlm('sub-task', name='api-reviewer')`; names must be non-empty and unique among addressable sessions. If omitted, the host generates a readable unique name.","Sub-agents should not block Prime Agent by default: start them with `task = asyncio.create_task(rlm('sub-task'))`, keep the task handle, continue any independent work, and await the task only when you need its result.",- hasAgentObserveSkill- ? "For long-running fan-out, do not rely only on in-memory `asyncio.Task` handles: they can be lost if the kernel restarts or state is restored. Write a small disk registry under `os.environ.get('RLM_SESSION_DIR')` when set, or another explicit project path otherwise, with each subtask prompt/label and observed active session or child ids; recover status later with `agent_observe`."- : "For long-running fan-out, do not rely only on in-memory `asyncio.Task` handles: they can be lost if the kernel restarts or state is restored. Write a small disk registry under `os.environ.get('RLM_SESSION_DIR')` when set, or another explicit project path otherwise, with each subtask prompt/label and observed active session or child ids so work can be reconciled after restore.",+ "For long-running fan-out, do not rely only on in-memory `asyncio.Task` handles: they can be lost if the kernel restarts or state is restored. Recover the current parent session's automatic child registry with `children = await rlm.list_subagents()`; each entry exposes `rlm_child_id`, `active_session_id`, `session_id`, `session_name`, `session_dir`, and `status`.",+ "Delete a running or retained direct child with `await rlm.delete_subagent(child)` (or pass its name/ID); deletion cancels running work, closes the child runtime, and removes it from the registry and daemon addressability.","For parallel sub-agents, launch them together and collect them with normal Python async patterns such as `await asyncio.gather(rlm('task1'), rlm('task2'))`; `asyncio` is already imported.","For sub-agent work that can run in the background, keep the task handle from `asyncio.create_task(rlm('sub-task'))` so you do not block the main execution path; use normal task callbacks, `task.done()`, or `await task` later to observe completion and read the returned `RLMResult.answer`.",);@@ -116,9 +115,11 @@ export function buildSubagentGuidance(): string {"You already have `rlm` in scope. This is about *when* to spawn one — which matters as much as how.","","Default to non-blocking subagents: create an `asyncio` task, keep the handle, continue independent work, and await only at the collection point where the result is needed.",- "For subagent work that must survive kernel restarts, state restore, or compaction, persist a disk-backed registry before or immediately after spawning: after importing `os` and `Path`, store the subtask label, prompt, start time, and any observed `activeSessionId`, `rlmChildId`, or `session_dir` under `Path(os.environ['RLM_SESSION_DIR'])` when that variable is set, or another explicit project path otherwise. Treat in-memory `asyncio.Task` objects as convenience handles only; after restore, reload the registry and recover status from live subagent sessions instead of assuming those task objects still exist.",- 'If the `agent_observe` skill is installed, use it like the agents view to inspect live subagents without awaiting them: list agents with `await agent_observe.list_agents()`, filter `runtimeKind == "subagent"` and `parentSessionId` or `parentActiveSessionId`, and read bounded previews with `await agent_observe.recent_messages(target, limit=...)`.',- "If the `agent_message` skill is installed, live subagents are addressable like other active agents: list targets with `await agent_message.list_agents()` and send concise coordination or steering messages with `await agent_message.send(target, message, mode='auto')`; use `mode='steer'` only when you intend to interrupt current work.",+ "The host automatically keeps a parent-scoped subagent registry across kernel restarts, state restore, and compaction. Recover it with `children = await rlm.list_subagents()` instead of maintaining a separate registry file or relying on lost `asyncio.Task` handles.",+ "Successful subagent sessions remain in that registry after their initial `rlm()` call finishes, but only while the current parent session remains open. Failed or cancelled children are removed, and retained children close when their parent session closes.",+ "Choose a child name at spawn time with `rlm('task', name='api-reviewer')`, or let the host generate a readable, unique default `session_name`. If the `agent_observe` skill is installed and a registry entry has `active_session_id`, inspect it by name with `await agent_observe.get_agent(child.session_name)` or read bounded previews with `await agent_observe.recent_messages(child.session_name, limit=...)`.",+ "If the `agent_message` skill is installed and a registry entry has `active_session_id`, continue that same child by name with `await agent_message.send(child.session_name, message, mode='auto')`; use `mode='steer'` only when you intend to interrupt current work.",+ "Delete a direct child by registry entry or selector with `await rlm.delete_subagent(child)` or `await rlm.delete_subagent('api-reviewer')`. Deleting a running child cancels it first; deleting any child closes its runtime, removes it from the parent registry, and makes it unavailable to messaging and observation.","","Reach for sub-agents when:","- you have independent sub-tasks that can run in parallel — fan them out with `asyncio.create_task(rlm('task'))` or collect a batch with `await asyncio.gather(rlm('task1'), rlm('task2'))` rather than working them one after another;",@@ -129,9 +130,6 @@ export function buildSubagentGuidance(): string {"","For example:","```python",- "from pathlib import Path",- "import os",- "","# Independent sub-tasks in parallel — each returns just its conclusion, not the files it read","auth, api = await asyncio.gather("," rlm('Summarize how authentication works in this repo: entrypoints, token flow, and key files.'),",@@ -143,12 +141,10 @@ export function buildSubagentGuidance(): string {"print(res.answer)","","# Background — kick off a slow sub-task, keep working, collect it later",- "task = asyncio.create_task(rlm('Run the full test suite and report any failures with root causes.'))",- "# For long-running fan-out, also persist a label/prompt/id registry.",- "# Use RLM_SESSION_DIR when set; otherwise choose an explicit project path.",- "# Example: registry_root = Path(os.environ['RLM_SESSION_DIR']) if os.environ.get('RLM_SESSION_DIR') else Path('subagent-registry')",- "# registry_root.joinpath('subagents.jsonl').write_text(...)",- "# ... continue with other work while it runs ...",+ "task = asyncio.create_task(rlm('Run the full test suite and report any failures with root causes.', name='test-runner'))",+ "# The host registry remains available even if the Python task handle is later lost",+ "children = await rlm.list_subagents()",+ "# ... continue independent work ...","failures = (await task).answer","```","",diff --git a/packages/coding-agent/src/core/rlm-runtime.ts b/packages/coding-agent/src/core/rlm-runtime.tsindex 8cdabdf291..5f00f818b2 100644--- a/packages/coding-agent/src/core/rlm-runtime.ts+++ b/packages/coding-agent/src/core/rlm-runtime.ts@@ -27,7 +27,68 @@ export interface RlmInternalRunResult extends RlmRunResult {assistantUsage: Usage;}+export type RlmSubagentRegistryStatus = "running" | "completed";++export interface RlmSubagentRegistryEntry {+ rlm_child_id: string;+ active_session_id: string | null;+ session_id: string | null;+ session_name: string;+ session_dir: string;+ status: RlmSubagentRegistryStatus;+}++export interface RlmListSubagentsResult {+ subagents: RlmSubagentRegistryEntry[];+}++export interface RlmDeleteSubagentResult {+ subagent: RlmSubagentRegistryEntry;+}+export type RlmRunHandler = (request: RlmRunRequest) => Promise<RlmRunResult>;+export type RlmListSubagentsHandler = () => RlmListSubagentsResult;+export type RlmDeleteSubagentHandler = (target: string) => Promise<RlmDeleteSubagentResult>;++const RLM_SUBAGENT_SESSION_NAME_MAX_LENGTH = 64;++/** Validate and normalize an orchestrator-supplied subagent session name. */+export function normalizeRequestedRlmSubagentSessionName(value: unknown): string | undefined {+ if (value === undefined) {+ return undefined;+ }+ if (typeof value !== "string") {+ throw new Error("rlm.run name must be a string");+ }+ const name = value.trim();+ if (!name) {+ throw new Error("rlm.run name must not be empty");+ }+ if (name.length > RLM_SUBAGENT_SESSION_NAME_MAX_LENGTH) {+ throw new Error(`rlm.run name must be at most ${RLM_SUBAGENT_SESSION_NAME_MAX_LENGTH} characters`);+ }+ return name;+}++/** Create a readable, collision-resistant default name usable as an agent-message selector. */+export function createDefaultRlmSubagentSessionName(prompt: string, childId: string): string {+ const promptSlug = prompt+ .normalize("NFKD")+ .replace(/[\u0300-\u036f]/g, "")+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "");+ const idSuffix =+ childId+ .replace(/^sub-/, "")+ .replace(/[^A-Za-z0-9]+/g, "")+ .slice(-8) || "child";+ const fixedLength = "subagent--".length + idSuffix.length;+ const promptPart = (promptSlug || "worker")+ .slice(0, Math.max(1, RLM_SUBAGENT_SESSION_NAME_MAX_LENGTH - fixedLength))+ .replace(/-+$/g, "");+ return `subagent-${promptPart || "worker"}-${idSuffix}`;+}function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === "object" && value !== null && !Array.isArray(value);@@ -46,6 +107,25 @@ export function createRlmRunHostHandler(handler: RlmRunHandler): HostRequestHand};}+/** Expose the current parent session's RLM child registry to its kernel. */+export function createRlmListSubagentsHostHandler(handler: RlmListSubagentsHandler): HostRequestHandler {+ return async () => {+ const { subagents } = handler();+ return { subagents };+ };+}++/** Delete one direct child selected from the current parent session's registry. */+export function createRlmDeleteSubagentHostHandler(handler: RlmDeleteSubagentHandler): HostRequestHandler {+ return async (payload) => {+ if (typeof payload.target !== "string" || !payload.target.trim()) {+ throw new Error("rlm.delete_subagent target must be a non-empty string");+ }+ const { subagent } = await handler(payload.target.trim());+ return { subagent };+ };+}+export interface RlmSubagentRuntime {session: AgentSession;}@@ -54,6 +134,7 @@ export interface CreateRlmSubagentRuntimeOptions {parentSession: AgentSession;id: string;prompt: string;+ sessionName: string;sessionDir: string;model: Model<any>;thinkingLevel: ThinkingLevel;@@ -69,6 +150,8 @@ export interface CreateRlmSubagentRuntimeOptions {rlmParentNodeId: string;/** Source of the IPython cell that spawned this subagent, for display. */spawnCode?: string;+ /** Publish the session to the parent before a host makes the runtime addressable. */+ onSessionPublished?: (session: AgentSession) => void;}/** Terminal status of an RLM child run, passed to the host when releasing its runtime. */@@ -76,6 +159,8 @@ export type RlmSubagentReleaseStatus = "done" | "error" | "cancelled";export interface SubagentRuntimeHost {createRlmSubagentRuntime(options: CreateRlmSubagentRuntimeOptions): Promise<RlmSubagentRuntime>;+ /** Close the host-owned child identified by childId; session may predate an in-child session replacement. */+ deleteRlmSubagentRuntime(childId: string, session: AgentSession): Promise<void>;releaseRlmSubagentRuntime?(runtime: RlmSubagentRuntime,options: CreateRlmSubagentRuntimeOptions,diff --git a/packages/coding-agent/src/core/tools/ipython.ts b/packages/coding-agent/src/core/tools/ipython.tsindex 44b751fa13..3fc7a6cefe 100644--- a/packages/coding-agent/src/core/tools/ipython.ts+++ b/packages/coding-agent/src/core/tools/ipython.ts@@ -40,7 +40,7 @@ except Exception as _prime_agent_rlm_error:_PRIME_AGENT_RLM_IMPORT_ERROR = str(_prime_agent_rlm_error)class _PrimeAgentMissingRlm:- async def run(self, prompt, **kwargs):+ def _raise_missing(self):raise RuntimeError("prime-agent-runtime is not installed in this IPython kernel. ""Remove ~/.prime/agent/kernel-venv so prime-agent can rebuild it, or set "@@ -48,6 +48,15 @@ except Exception as _prime_agent_rlm_error:f"Import error: {_PRIME_AGENT_RLM_IMPORT_ERROR}")+ async def run(self, prompt, **kwargs):+ self._raise_missing()++ async def list_subagents(self):+ self._raise_missing()++ async def delete_subagent(self, target):+ self._raise_missing()+async def __call__(self, prompt, **kwargs):return await self.run(prompt, **kwargs)diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.tsindex 5e225f7987..f67b0d14df 100644--- a/packages/coding-agent/src/modes/agent-connection/types.ts+++ b/packages/coding-agent/src/modes/agent-connection/types.ts@@ -477,6 +477,8 @@ export interface AgentConnectionRlmChildAgentSnapshot {parentId?: string;/** The child's own daemon active-session id, for attaching to it directly. */activeSessionId?: string;+ /** Stable daemon-visible session name for addressing/displaying the child. */+ sessionName?: string;label: string;status: AgentConnectionRlmChildAgentStatus;durationMs?: number;diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 8d262ffa41..b11c60321e 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -8,7 +8,18 @@import { spawn } from "node:child_process";import { createHash, randomUUID } from "node:crypto";-import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";+import {+ closeSync,+ existsSync,+ fsyncSync,+ mkdirSync,+ openSync,+ readFileSync,+ renameSync,+ rmSync,+ writeFileSync,+ writeSync,+} from "node:fs";import { createConnection, createServer, type Server, type Socket } from "node:net";import { dirname, join, resolve } from "node:path";import { getLogger } from "@earendil-works/pi-ai";@@ -23,6 +34,7 @@ import {import {AGENT_MESSAGE_SOURCE,type AgentSessionMessageAgentSummary,+ type AgentSessionMessageController,type AgentSessionMessageDeliveryStatus,type AgentSessionMessageEndpoint,type AgentSessionMessageListResult,@@ -313,7 +325,28 @@ interface BoundSupervisorGenerationClaim {ownerFingerprint: string;}+const RLM_SUBAGENT_REGISTRY_FILE = "rlm-subagents.jsonl";++interface PersistedRlmSubagentRegistryEntry {+ type: "rlm_subagent";+ childId: string;+ sessionName: string;+ sessionDir: string;+ sessionFile: string;+ parentSessionId: string;+ parentSessionFile?: string;+ rlmDepth?: number;+ rlmMaxDepth?: number;+ rlmParentNodeId?: string;+ prompt?: string;+ spawnCode?: string;+ status: "running" | "completed" | "deleted";+ createdAt: number;+ updatedAt: string;+}+class RuntimeOpenCancelledError extends Error {}+class BoundSessionUnavailableError extends Error {}export async function runDaemonMode(options: DaemonModeOptions): Promise<never> {const socketPath = options.socketPath ?? defaultDaemonSocketPath();@@ -332,6 +365,10 @@ export class AgentDaemon {private readonly clients = new Set<DaemonSocketClient>();private readonly sessions = new Map<string, ActiveSessionState>();private readonly openingSessions = new Map<string, Promise<ActiveSessionState>>();+ private readonly rlmRehydrationClaims = new Map<+ string,+ { parentState: ActiveSessionState; entry: PersistedRlmSubagentRegistryEntry }+ >();private readonly closingSessions = new Map<string, Promise<void>>();private readonly sideQuestionRuns = new Map<string,@@ -711,12 +748,149 @@ export class AgentDaemon {}}+ private rlmSubagentRegistryPath(parentSession: AgentSession): string | undefined {+ const artifactDir = parentSession.sessionManager.getSessionArtifactDir();+ if (!artifactDir) {+ return undefined;+ }+ return join(artifactDir, RLM_SUBAGENT_REGISTRY_FILE);+ }++ private appendRlmSubagentRegistryEntry(+ parentState: ActiveSessionState,+ entry: PersistedRlmSubagentRegistryEntry,+ ): boolean {+ const path = this.rlmSubagentRegistryPath(parentState.runtime.session);+ if (!path) {+ return true;+ }+ try {+ mkdirSync(dirname(path), { recursive: true });+ const existing = existsSync(path) ? readFileSync(path, "utf8") : "";+ const separator = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";+ const handle = openSync(path, "a");+ try {+ writeSync(handle, `${separator}${JSON.stringify(entry)}\n`);+ fsyncSync(handle);+ } finally {+ closeSync(handle);+ }+ return true;+ } catch (error) {+ this.log(+ `failed to persist RLM subagent registry entry: ${error instanceof Error ? error.message : String(error)}`,+ );+ return false;+ }+ }++ private recordRlmSubagentRegistryEntry(+ parentState: ActiveSessionState,+ input: {+ childId: string;+ sessionName: string;+ sessionDir: string;+ sessionFile: string;+ rlmDepth: number;+ rlmMaxDepth: number;+ rlmParentNodeId?: string;+ prompt?: string;+ spawnCode?: string;+ status: PersistedRlmSubagentRegistryEntry["status"];+ createdAt?: number;+ },+ ): void {+ const parentSession = parentState.runtime.session;+ this.appendRlmSubagentRegistryEntry(parentState, {+ type: "rlm_subagent",+ childId: input.childId,+ sessionName: input.sessionName,+ sessionDir: input.sessionDir,+ sessionFile: input.sessionFile,+ parentSessionId: parentSession.sessionId,+ ...(parentSession.sessionFile ? { parentSessionFile: parentSession.sessionFile } : {}),+ rlmDepth: input.rlmDepth,+ rlmMaxDepth: input.rlmMaxDepth,+ ...(input.rlmParentNodeId ? { rlmParentNodeId: input.rlmParentNodeId } : {}),+ ...(input.prompt ? { prompt: input.prompt } : {}),+ ...(input.spawnCode ? { spawnCode: input.spawnCode } : {}),+ status: input.status,+ createdAt: input.createdAt ?? Date.now(),+ updatedAt: new Date().toISOString(),+ });+ }++ private recordRlmSubagentDeletion(parentState: ActiveSessionState, childId: string): void {+ const latest = this.readLatestRlmSubagentRegistry(parentState, true).find((entry) => entry.childId === childId);+ if (!latest || latest.status === "deleted") {+ return;+ }+ if (+ !this.appendRlmSubagentRegistryEntry(parentState, {+ ...latest,+ status: "deleted",+ updatedAt: new Date().toISOString(),+ })+ ) {+ throw new Error(`Failed to persist deletion for RLM subagent ${childId}`);+ }+ }++ private readLatestRlmSubagentRegistry(+ parentState: ActiveSessionState,+ throwOnReadError = false,+ ): PersistedRlmSubagentRegistryEntry[] {+ const path = this.rlmSubagentRegistryPath(parentState.runtime.session);+ if (!path || !existsSync(path)) {+ return [];+ }+ const latest = new Map<string, PersistedRlmSubagentRegistryEntry>();+ let lines: string[];+ try {+ lines = readFileSync(path, "utf8").split(/\r?\n/);+ } catch (error) {+ this.log(`failed to read RLM subagent registry: ${error instanceof Error ? error.message : String(error)}`);+ if (throwOnReadError) {+ throw error;+ }+ return [];+ }+ for (const line of lines) {+ const trimmed = line.trim();+ if (!trimmed) {+ continue;+ }+ try {+ const entry = JSON.parse(trimmed) as Partial<PersistedRlmSubagentRegistryEntry>;+ if (+ entry.type !== "rlm_subagent" ||+ typeof entry.childId !== "string" ||+ typeof entry.sessionName !== "string" ||+ typeof entry.sessionDir !== "string" ||+ typeof entry.sessionFile !== "string" ||+ (entry.status !== "running" && entry.status !== "completed" && entry.status !== "deleted") ||+ (entry.rlmDepth !== undefined && (!Number.isSafeInteger(entry.rlmDepth) || entry.rlmDepth < 0)) ||+ (entry.rlmMaxDepth !== undefined && (!Number.isSafeInteger(entry.rlmMaxDepth) || entry.rlmMaxDepth < 0))+ ) {+ continue;+ }+ latest.set(entry.childId, entry as PersistedRlmSubagentRegistryEntry);+ } catch (error) {+ this.log(+ `ignored malformed RLM subagent registry entry: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ }+ return [...latest.values()];+ }+private async addRuntime(runtime: AgentSessionRuntime,name?: string,clientEnv?: Record<string, string>,onStateCreated?: (state: ActiveSessionState) => void,runtimeOpenGuard?: RuntimeOpenGuard,+ onStateBound?: (state: ActiveSessionState) => void,): Promise<ActiveSessionState> {const restoredActiveSessionId = runtime.metadata.kind === "top-level" ? this.restoreActiveSessionId : undefined;if (restoredActiveSessionId) {@@ -750,9 +924,13 @@ export class AgentDaemon {},subagentRuntimeHost: this.createSubagentRuntimeHost(state),});- if (runtimeOpenGuard && !(await runtimeOpenGuard())) {- throw new RuntimeOpenCancelledError();+ if (runtimeOpenGuard) {+ const guardResult = runtimeOpenGuard();+ if (!(typeof guardResult === "boolean" ? guardResult : await guardResult)) {+ throw new RuntimeOpenCancelledError();+ }}+ onStateBound?.(state);} catch (error) {state.unsubscribe?.();this.sessions.delete(state.activeSessionId);@@ -901,26 +1079,7 @@ export class AgentDaemon {return this.deleteRlmHeartbeatForState(stateRef, id);},},- agentMessageController: {- listAgents: () => {- if (!stateRef) {- throw new Error("Agent message state is not ready for this session yet");- }- return this.createAgentMessageListResult(stateRef);- },- sendAgentMessage: (input) => {- if (!stateRef) {- throw new Error("Agent message state is not ready for this session yet");- }- return this.sendAgentSessionMessage({- targetSelector: input.target,- message: input.message,- fromState: stateRef,- deliveryMode: input.deliveryMode,- origin: "agent",- });- },- },+ agentMessageController: this.createAgentMessageController(() => stateRef),agentObserveController: this.createAgentObserveController(() => stateRef),},}),@@ -929,7 +1088,7 @@ export class AgentDaemon {await runtime.dispose().catch(() => undefined);throw new RuntimeOpenCancelledError();}- return this.addRuntime(+ const state = await this.addRuntime(runtime,command.name,clientEnv,@@ -938,6 +1097,20 @@ export class AgentDaemon {},runtimeOpenGuard,);+ const openedSessionFile = state.runtime.session.sessionFile;+ const rehydrationKey = openedSessionFile ? resolve(openedSessionFile) : undefined;+ const rehydrationClaim = rehydrationKey ? this.rlmRehydrationClaims.get(rehydrationKey) : undefined;+ if (rehydrationKey && rehydrationClaim) {+ if (this.rlmRehydrationClaims.get(rehydrationKey) === rehydrationClaim) {+ this.rlmRehydrationClaims.delete(rehydrationKey);+ }+ await this.closeSession(state, "replaced");+ return this.rehydrateCompletedRlmSubagent(rehydrationClaim.parentState, rehydrationClaim.entry);+ }+ if (state.runtime.metadata.kind === "top-level") {+ await this.rehydrateCompletedRlmSubagents(state);+ }+ return state;};const sessionFile = sessionManager.getSessionFile();@@ -1151,6 +1324,9 @@ export class AgentDaemon {};try {await this.agentMessageTargetLocks.get(activeSessionId)?.catch(() => undefined);+ if (this.sessions.get(activeSessionId) !== state || this.closingSessions.has(activeSessionId)) {+ throw new Error("Target session is closing before prompt delivery");+ }if (canRun && !canRun()) {return false;}@@ -1514,7 +1690,10 @@ export class AgentDaemon {private getBoundSessionState(id: string): ActiveSessionState {const state = this.getSessionState(id);if (this.bindingSessions.has(state.activeSessionId)) {- throw new Error(`Active session ${state.activeSessionId} is still initializing`);+ throw new BoundSessionUnavailableError(`Active session ${state.activeSessionId} is still initializing`);+ }+ if (this.closingSessions.has(state.activeSessionId)) {+ throw new BoundSessionUnavailableError(`Active session ${state.activeSessionId} is closing`);}return state;}@@ -1534,6 +1713,30 @@ export class AgentDaemon {private createSubagentRuntimeHost(parentState: ActiveSessionState): SubagentRuntimeHost {return {createRlmSubagentRuntime: async (options) => this.createRlmSubagentRuntime(parentState, options),+ deleteRlmSubagentRuntime: async (childId, session) => {+ const state = [...this.sessions.values()].find(+ (candidate) =>+ candidate.runtime.metadata.kind === "subagent" &&+ candidate.runtime.metadata.parentActiveSessionId === parentState.activeSessionId &&+ candidate.runtime.metadata.rlmChildId === childId,+ );+ // Persist the deletion boundary before tearing down the runtime. If the write+ // fails, the live child remains available for the parent to retry instead of+ // becoming a disposed session that can still rehydrate after a crash.+ this.recordRlmSubagentDeletion(parentState, childId);+ if (!state) {+ await session.disposeAsync();+ return;+ }+ const shouldDisposeStaleSession = state.runtime.session !== session;+ try {+ await this.closeSession(state, "killed", false);+ } finally {+ if (shouldDisposeStaleSession) {+ await session.disposeAsync();+ }+ }+ },disposeRlmSubagentRuntimes: async () => {const cascadeError = await this.closeChildSessions(parentState, "replaced");if (cascadeError) {@@ -1542,15 +1745,32 @@ export class AgentDaemon {},releaseRlmSubagentRuntime: async (runtime, options, status) => {const state = this.findRuntimeState(runtime);- // A successful subagent stays resident so it's still viewable (torn down with the- // parent via closeChildSessions); errored/cancelled would re-seed as "done", so close them.+ // A successful subagent stays resident so it's still viewable and messageable;+ // closeChildSessions tears it down with the parent. Errored or cancelled children+ // would re-seed as "done", so close them immediately.if (state && status === "done") {// Run shutdown side effects without disposing the still-readable session.this.cancelSubagentRlmHeartbeats(state);await flushAgentTraceUpload(state.runtime.session.sessionManager).catch(() => undefined);- // Retention can decline if the parent is already tearing down; if so, close- // the session here so it doesn't linger in the registry.+ // Retention can decline if deletion or parent teardown won while the trace+ // flush was in flight. Persist completion only after retention succeeds, so+ // a late completion cannot overwrite a durable deletion tombstone.if (options.parentSession.retainFinishedRlmChildSession(options.id, runtime.session)) {+ if (runtime.session.sessionFile) {+ this.recordRlmSubagentRegistryEntry(parentState, {+ childId: options.id,+ sessionName: runtime.session.sessionName ?? options.sessionName,+ sessionDir: options.sessionDir,+ sessionFile: runtime.session.sessionFile,+ rlmDepth: options.rlmDepth,+ rlmMaxDepth: options.rlmMaxDepth,+ rlmParentNodeId: options.rlmParentNodeId,+ prompt: options.prompt.length <= 4096 ? options.prompt : undefined,+ spawnCode: options.spawnCode,+ status: "completed",+ createdAt: state.runtime.metadata.createdAt,+ });+ }return;}}@@ -1594,6 +1814,8 @@ export class AgentDaemon {customTools: options.customTools,includeGoals: options.includeGoals,includeCompactSkill: options.includeCompactSkill,+ agentMessageController: this.createAgentMessageController(() => stateRef),+ agentObserveController: this.createAgentObserveController(() => stateRef),rlmHeartbeatController: {listRlmHeartbeats: (listOptions) => {if (!stateRef) {@@ -1639,12 +1861,255 @@ export class AgentDaemon {},}),);- await this.addRuntime(runtime, undefined, parentState.clientEnv, (state) => {- stateRef = state;- });+ await this.addRuntime(+ runtime,+ undefined,+ parentState.clientEnv,+ (state) => {+ stateRef = state;+ },+ () => options.parentSession.getRlmChildRunStatus(options.id) !== "cancelled",+ () => {+ if (runtime.session.sessionName !== options.sessionName) {+ runtime.session.setSessionName(options.sessionName);+ }+ if (runtime.session.sessionFile) {+ this.recordRlmSubagentRegistryEntry(parentState, {+ childId: options.id,+ sessionName: options.sessionName,+ sessionDir: options.sessionDir,+ sessionFile: runtime.session.sessionFile,+ rlmDepth: options.rlmDepth,+ rlmMaxDepth: options.rlmMaxDepth,+ rlmParentNodeId: options.rlmParentNodeId,+ prompt: options.prompt.length <= 4096 ? options.prompt : undefined,+ spawnCode: options.spawnCode,+ status: "running",+ createdAt: runtime.metadata.createdAt,+ });+ }+ options.onSessionPublished?.(runtime.session);+ },+ );return runtime;}+ private isRlmAncestorState(state: ActiveSessionState, candidate: ActiveSessionState): boolean {+ const visited = new Set<string>();+ let current: ActiveSessionState | undefined = state;+ while (current && !visited.has(current.activeSessionId)) {+ if (current.activeSessionId === candidate.activeSessionId) {+ return true;+ }+ visited.add(current.activeSessionId);+ const parentId: string | undefined = current.runtime.metadata.parentActiveSessionId;+ current = parentId ? this.sessions.get(parentId) : undefined;+ }+ return false;+ }++ private hasRlmSubagentState(parentState: ActiveSessionState, childId: string, sessionFile?: string): boolean {+ const targetSessionFile = sessionFile ? resolve(sessionFile) : undefined;+ return [...this.sessions.values()].some((state) => {+ const existingFile = state.runtime.session.sessionFile;+ if (targetSessionFile && existingFile && resolve(existingFile) === targetSessionFile) {+ return true;+ }+ const metadata = state.runtime.metadata;+ return (+ metadata.kind === "subagent" &&+ metadata.parentActiveSessionId === parentState.activeSessionId &&+ metadata.rlmChildId === childId+ );+ });+ }++ private async rehydrateCompletedRlmSubagent(+ parentState: ActiveSessionState,+ entry: PersistedRlmSubagentRegistryEntry,+ ): Promise<ActiveSessionState> {+ let stateRef: ActiveSessionState | undefined;+ let runtime: AgentSessionRuntime | undefined;+ try {+ const sessionManager = await SessionManager.openAsync(entry.sessionFile, entry.sessionDir);+ runtime = await withClientEnv(parentState.clientEnv, () =>+ createAgentSessionRuntime(this.options.createRuntime, {+ cwd: sessionManager.getCwd(),+ agentDir: parentState.runtime.services.agentDir,+ sessionManager,+ sessionStartEvent: { type: "session_start", reason: "startup" },+ sessionConfig: parentState.runtime.runtimeConfig,+ sessionOptions: {+ agentMessageController: this.createAgentMessageController(() => stateRef),+ agentObserveController: this.createAgentObserveController(() => stateRef),+ rlmHeartbeatController: {+ listRlmHeartbeats: (listOptions) => {+ if (!stateRef) {+ throw new Error("RLM heartbeat state is not ready for this session yet");+ }+ return this.cronStore.listRlmHeartbeats(stateRef.activeSessionId, listOptions);+ },+ createRlmHeartbeat: (input) => {+ if (!stateRef) {+ throw new Error("RLM heartbeat state is not ready for this session yet");+ }+ return this.createRlmHeartbeatForState(stateRef, input);+ },+ updateRlmHeartbeat: (input) => {+ if (!stateRef) {+ throw new Error("RLM heartbeat state is not ready for this session yet");+ }+ return this.updateRlmHeartbeatForState(stateRef, input);+ },+ deleteRlmHeartbeat: (id) => {+ if (!stateRef) {+ throw new Error("RLM heartbeat state is not ready for this session yet");+ }+ return this.deleteRlmHeartbeatForState(stateRef, id);+ },+ },+ rlmSessionDir: entry.sessionDir,+ rlmDepth: entry.rlmDepth ?? 1,+ rlmMaxDepth: entry.rlmMaxDepth ?? 1,+ rlmParentNodeId: entry.rlmParentNodeId ?? entry.childId,+ },+ runtimeMetadata: {+ kind: "subagent",+ createdAt: entry.createdAt,+ parentActiveSessionId: parentState.activeSessionId,+ parentSessionId: parentState.runtime.session.sessionId,+ ...(parentState.runtime.session.sessionFile+ ? { parentSessionFile: parentState.runtime.session.sessionFile }+ : {}),+ rlmChildId: entry.childId,+ rlmParentNodeId: entry.rlmParentNodeId ?? entry.childId,+ ...(entry.prompt ? { prompt: entry.prompt } : {}),+ ...(entry.spawnCode ? { spawnCode: entry.spawnCode } : {}),+ sessionDir: entry.sessionDir,+ },+ }),+ );+ const state = await this.addRuntime(runtime, undefined, parentState.clientEnv, (createdState) => {+ stateRef = createdState;+ });+ // The session transcript is authoritative for mutable metadata such as a+ // later user-assigned name; the registry value is only the spawn snapshot.+ if (!parentState.runtime.session.retainFinishedRlmChildSession(entry.childId, runtime.session)) {+ await this.closeSession(state, "replaced");+ throw new RuntimeOpenCancelledError();+ }+ await this.rehydrateCompletedRlmSubagents(state);+ return state;+ } catch (error) {+ if (stateRef && this.sessions.get(stateRef.activeSessionId) === stateRef) {+ await this.closeSession(stateRef, "completed").catch(() => undefined);+ } else {+ await runtime?.dispose().catch(() => undefined);+ }+ throw error;+ }+ }++ private async rehydrateCompletedRlmSubagents(parentState: ActiveSessionState): Promise<void> {+ for (const entry of this.readLatestRlmSubagentRegistry(parentState)) {+ if (entry.status !== "completed" || !existsSync(entry.sessionFile)) {+ continue;+ }+ const sessionKey = resolve(entry.sessionFile);+ const existing = this.findSessionBySessionFile(entry.sessionFile);+ if (existing && this.isRlmAncestorState(parentState, existing)) {+ continue;+ }+ if (existing && !this.bindingSessions.has(existing.activeSessionId)) {+ if (existing.runtime.metadata.kind !== "top-level") {+ continue;+ }+ // A stable explicit open has already returned a valid active ID. Notify+ // its clients before replacing it with the correctly configured child.+ await this.closeSession(existing, "replaced").catch((error) => {+ this.log(+ `failed to replace top-level RLM subagent ${entry.sessionName}: ${+ error instanceof Error ? error.message : String(error)+ }`,+ );+ });+ }+ const pending = this.openingSessions.get(sessionKey);+ if (pending) {+ const claim = { parentState, entry };+ const installedClaim = !this.rlmRehydrationClaims.has(sessionKey);+ if (installedClaim) {+ // createRuntime consumes this after binding but before top-level recursive+ // recovery or promise resolution, so callers receive the child state.+ this.rlmRehydrationClaims.set(sessionKey, claim);+ }+ try {+ await pending;+ continue;+ } catch (error) {+ this.log(+ `failed to await completed RLM subagent ${entry.sessionName}: ${+ error instanceof Error ? error.message : String(error)+ }`,+ );+ // The failed owner completed all runtime cleanup before rejecting. Clear+ // only that stale claim, then let rehydration retry the persisted child.+ if (this.openingSessions.get(sessionKey) === pending) {+ this.openingSessions.delete(sessionKey);+ }+ if (this.hasRlmSubagentState(parentState, entry.childId, entry.sessionFile)) {+ continue;+ }+ } finally {+ if (installedClaim && this.rlmRehydrationClaims.get(sessionKey) === claim) {+ this.rlmRehydrationClaims.delete(sessionKey);+ }+ }+ }+ if (this.hasRlmSubagentState(parentState, entry.childId, entry.sessionFile)) {+ continue;+ }+ const opening = this.rehydrateCompletedRlmSubagent(parentState, entry);+ this.openingSessions.set(sessionKey, opening);+ try {+ await opening;+ } catch (error) {+ this.log(+ `failed to rehydrate completed RLM subagent ${entry.sessionName}: ${+ error instanceof Error ? error.message : String(error)+ }`,+ );+ } finally {+ if (this.openingSessions.get(sessionKey) === opening) {+ this.openingSessions.delete(sessionKey);+ }+ }+ }+ }++ private createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController {+ const requireCurrentState = () => {+ const current = getCurrentState();+ if (!current) {+ throw new Error("Agent message state is not ready for this session yet");+ }+ return current;+ };+ return {+ listAgents: () => this.createAgentMessageListResult(requireCurrentState()),+ sendAgentMessage: (input) =>+ this.sendAgentSessionMessage({+ targetSelector: input.target,+ message: input.message,+ fromState: requireCurrentState(),+ deliveryMode: input.deliveryMode,+ origin: "agent",+ }),+ };+ }+private createAgentObserveController(getCurrentState: () => ActiveSessionState | undefined): AgentObserveController {const requireCurrentState = () => {const current = getCurrentState();@@ -2291,7 +2756,7 @@ export class AgentDaemon {}case "prompt": {- const state = this.getSessionState(command.activeSessionId);+ const state = this.getBoundSessionState(command.activeSessionId);let responseSent = false;const sendSuccessResponse = () => {if (responseSent) {@@ -2330,7 +2795,7 @@ export class AgentDaemon {}case "steer": {- const state = this.getSessionState(command.activeSessionId);+ const state = this.getBoundSessionState(command.activeSessionId);if (command.expandPromptTemplates === false) {await state.runtime.session.restoreSteeringMessage(command.message, command.images, {queueKey: command.queueKey,@@ -2350,7 +2815,7 @@ export class AgentDaemon {}case "follow_up": {- const state = this.getSessionState(command.activeSessionId);+ const state = this.getBoundSessionState(command.activeSessionId);let queued: boolean;if (command.expandPromptTemplates === false) {queued = await state.runtime.session.restoreFollowUpMessage(command.message, command.images, {@@ -3255,17 +3720,29 @@ export class AgentDaemon {current: this.createAgentSessionMessageEndpoint(current),agents: [...localAgents,- ...[...this.remoteAgentPeers.values()].filter((peer) => !localIds.has(peer.activeSessionId)),+ ...[...this.remoteAgentPeers.values()].filter(+ (peer) => !localIds.has(peer.activeSessionId) && !this.closingSessions.has(peer.activeSessionId),+ ),],};}+ private findRemoteAgentPeer(selector: string): AgentSessionMessageAgentSummary | undefined {+ for (const peer of this.remoteAgentPeers.values()) {+ if (peer.activeSessionId === selector || peer.sessionId === selector || peer.sessionName === selector) {+ return peer;+ }+ }+ return undefined;+ }+// Half-bound sessions are hidden from other sessions' listings; the current// session stays visible to itself (controllers run during its own bind).private listTargetableSessionStates(current: ActiveSessionState): ActiveSessionState[] {return [...this.sessions.values()].filter((state) =>- state.activeSessionId === current.activeSessionId || !this.bindingSessions.has(state.activeSessionId),+ state.activeSessionId === current.activeSessionId ||+ (!this.bindingSessions.has(state.activeSessionId) && !this.closingSessions.has(state.activeSessionId)),);}@@ -3357,7 +3834,10 @@ export class AgentDaemon {try {targetState = this.getBoundSessionState(targetSelector);} catch (error) {- if (this.options.worker && options.fromState) {+ if (error instanceof BoundSessionUnavailableError) {+ throw error;+ }+ if (this.options.worker && options.fromState && this.findRemoteAgentPeer(targetSelector)) {return this.sendRemoteAgentSessionMessage(options.fromState,targetSelector,@@ -3452,6 +3932,9 @@ export class AgentDaemon {return response.data as AgentSessionMessageReceipt;} catch (error) {lastError = error;+ if (error instanceof Error && error.message.startsWith("Unknown active session:")) {+ throw error;+ }} finally {client.close();}@@ -3816,7 +4299,11 @@ export class AgentDaemon {return undefined;}- private async closeSession(state: ActiveSessionState, reason: DaemonSessionClosedReason): Promise<void> {+ private async closeSession(+ state: ActiveSessionState,+ reason: DaemonSessionClosedReason,+ waitForAbort = true,+ ): Promise<void> {for (const client of state.clients) {this.abortSideQuestionsFor(client, state.activeSessionId);}@@ -3825,7 +4312,7 @@ export class AgentDaemon {await existingClose;return;}- const closePromise = Promise.resolve().then(() => this.closeSessionOnce(state, reason));+ const closePromise = Promise.resolve().then(() => this.closeSessionOnce(state, reason, waitForAbort));this.closingSessions.set(state.activeSessionId, closePromise);try {await closePromise;@@ -3845,7 +4332,11 @@ export class AgentDaemon {}}- private async closeSessionOnce(state: ActiveSessionState, reason: DaemonSessionClosedReason): Promise<void> {+ private async closeSessionOnce(+ state: ActiveSessionState,+ reason: DaemonSessionClosedReason,+ waitForAbort: boolean,+ ): Promise<void> {if (!this.sessions.has(state.activeSessionId)) {return;}@@ -3857,7 +4348,7 @@ export class AgentDaemon {// Abort in-flight status work before any await/dispose so it can't write// agent_status to a session being torn down.this.summarizer.forget(state.activeSessionId);- const cascadeError = await this.closeChildSessions(state, reason);+ const cascadeError = await this.closeChildSessions(state, reason, waitForAbort);// Empty draft (no messages, config, or jobs): discard rather than persist an// empty session file. Mirrors the detach-time discard so a config-bearing// draft closed via kill/completed is never wiped.@@ -3879,12 +4370,22 @@ export class AgentDaemon {if (reason === "update") {state.runtime.session.abortForUpdateRestart();}- if (reason === "killed" || reason === "shutdown" || reason === "replaced") {+ if (reason === "killed") {+ const abort = state.runtime.session.abort().catch(() => undefined);+ if (waitForAbort) {+ await abort;+ }+ } else if (reason === "shutdown" || reason === "replaced") {await state.runtime.session.abort().catch(() => undefined);}this.recordWorkerRecoveryState(state, `closed:${reason}`, false);state.unsubscribe?.();- await state.runtime.dispose();+ let disposeError: unknown;+ try {+ await state.runtime.dispose();+ } catch (error) {+ disposeError = error;+ }this.broadcastToSession(state, { type: "session_closed", activeSessionId: state.activeSessionId, reason });for (const client of state.clients) {client.attachedActiveSessionIds.delete(state.activeSessionId);@@ -3898,6 +4399,9 @@ export class AgentDaemon {await deleteSessionFile(sessionFile).catch(() => undefined);}}+ if (disposeError) {+ throw disposeError;+ }if (persistError && !keepsResumeEntry && reason !== "completed") {throw persistError;}@@ -3909,11 +4413,12 @@ export class AgentDaemon {private async closeChildSessions(parentState: ActiveSessionState,reason: DaemonSessionClosedReason,+ waitForAbort = true,): Promise<unknown> {let cascadeError: unknown;for (const childState of getChildActiveSessionStates(this.sessions, parentState)) {try {- await this.closeSession(childState, reason);+ await this.closeSession(childState, reason, waitForAbort);} catch (error) {cascadeError ??= error;}diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.tsindex 063bccc8d2..946e4bb6e5 100644--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts@@ -309,6 +309,7 @@ function rlmChildSnapshotForActiveSession(id: metadata.rlmChildId ?? activeSession.activeSessionId,parentId: parentNodeId,activeSessionId: activeSession.activeSessionId,+ sessionName: session.sessionName,label: rlmChildLabel(metadata.prompt ?? ""),status,answerPreview,diff --git a/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts b/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.tsindex 528cadd1f7..c4b89e7c91 100644--- a/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts+++ b/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts@@ -24,6 +24,8 @@ export interface ChildAgentInspectorNode {id: string;/** The child's own daemon active-session id, for attaching directly to its stream. */activeSessionId?: string;+ /** Stable daemon-visible session name for addressing/displaying the child. */+ sessionName?: string;label: string;status: ChildAgentStatus;durationMs?: number;@@ -387,7 +389,7 @@ export class ChildAgentSummaryComponent implements Component, Focusable {if (flat.length < 2) {return "";}- const labels = flat.map((entry) => entry.node.label);+ const labels = flat.map((entry) => this.entryLabel(entry));let prefix = labels[0] ?? "";for (const label of labels) {let i = 0;@@ -409,7 +411,7 @@ export class ChildAgentSummaryComponent implements Component, Focusable {if (flat.length < 2 || !prefix) {return "";}- const labels = flat.map((entry) => entry.node.label);+ const labels = flat.map((entry) => this.entryLabel(entry));let suffix = labels[0] ?? "";for (const label of labels) {let i = 0;@@ -445,7 +447,7 @@ export class ChildAgentSummaryComponent implements Component, Focusable {const icon = formatChildAgentStatusIcon(entry.node.status, rawIcon);const agentLabel = `S${number}`;const agentCell = theme.fg("muted", padTableCell(agentLabel, agentWidth));- const promptCell = this.elidePrompt(entry.node.label, sharedPrefix, sharedSuffix, promptWidth);+ const promptCell = this.elidePrompt(this.entryLabel(entry), sharedPrefix, sharedSuffix, promptWidth);const recapCell = theme.fg("muted", padTableCell(childAgentRecap(entry.node), recapWidth, "…"));const tools =entry.node.toolUseCount === undefined@@ -461,6 +463,10 @@ export class ChildAgentSummaryComponent implements Component, Focusable {return `${indent}${icon} ${agentCell}${gap}${promptCell}${gap}${recapCell}${gap}${theme.fg("muted", metrics)}`;}+ private entryLabel(entry: FlatChildAgentNode): string {+ return entry.node.sessionName?.trim() || entry.node.label;+ }+private elidePrompt(label: string, sharedPrefix: string, sharedSuffix: string, width: number): string {const text = this.elideAroundDiff(label, sharedPrefix, sharedSuffix);const safeWidth = Math.max(0, width);diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 99d1c532d9..10569ff8d0 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -303,6 +303,7 @@ export function mergeChildAgentSnapshots(...incoming,parentId: incoming.parentId ?? previous.parentId,activeSessionId: incoming.activeSessionId ?? previous.activeSessionId,+ sessionName: incoming.sessionName ?? previous.sessionName,durationMs: incoming.durationMs ?? previous.durationMs,answerPreview: incoming.answerPreview ?? previous.answerPreview,toolUseCount:@@ -324,6 +325,7 @@ function childAgentSummaryChanged(const nextTokens = next.tokenCount === undefined ? undefined : formatTokenCount(next.tokenCount);return (previous.parentId !== next.parentId ||+ previous.sessionName !== next.sessionName ||previous.label !== next.label ||previous.status !== next.status ||previous.durationMs !== next.durationMs ||@@ -5494,6 +5496,7 @@ export class InteractiveMode {const build = (child: AgentConnectionRlmChildAgentSnapshot): ChildAgentInspectorNode => ({id: child.id,activeSessionId: child.activeSessionId,+ sessionName: child.sessionName,label: child.label,status: child.status,durationMs: child.durationMs,diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex bf8a5eac2d..0e2657160a 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -12,12 +12,17 @@ import {type Usage,} from "@earendil-works/pi-ai";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { AgentSessionMessageController } from "../src/core/agent-messages.js";import { AgentSession } from "../src/core/agent-session.js";import { AuthStorage } from "../src/core/auth-storage.js";-import { KernelManager } from "../src/core/kernel/index.js";+import { type HostRequestHandlers, KernelManager } from "../src/core/kernel/index.js";import { convertToLlm } from "../src/core/messages.js";import { ModelRegistry } from "../src/core/model-registry.js";-import { createRlmRunHostHandler } from "../src/core/rlm-runtime.js";+import {+ createDefaultRlmSubagentSessionName,+ createRlmRunHostHandler,+ type SubagentRuntimeHost,+} from "../src/core/rlm-runtime.js";import { SessionManager } from "../src/core/session-manager.js";import { SettingsManager } from "../src/core/settings-manager.js";import type { Skill } from "../src/core/skills.js";@@ -91,6 +96,8 @@ interface CapturedCommReply {}interface InspectableRlmRun {+ id: string;+ sessionDir: string;abort: () => void;status: string;error?: string;@@ -99,6 +106,14 @@ interface InspectableRlmRun {interface InspectableRlmSession {_activeRlmChildRuns: Map<string, InspectableRlmRun>;+ _deletingRlmChildren: Map<+ string,+ { subagent: ReturnType<AgentSession["listRlmSubagents"]>["subagents"][number]; promise: Promise<unknown> }+ >;+ _retryableRlmSubagentDeletions: Map<string, ReturnType<AgentSession["listRlmSubagents"]>["subagents"][number]>;+ _retainedRlmChildSessions: Map<string, AgentSession>;+ _retainedRlmChildUnsubscribes: Map<string, () => void>;+ _createKernelHostHandlers(): HostRequestHandlers;}interface KernelPumpTestApi {@@ -201,7 +216,16 @@ describe("AgentSession rlm recursion", () => {rmSync(tempDir, { recursive: true, force: true });});- function createSession(options: { depth?: number; maxDepth?: number; streamFn?: StreamFn } = {}): AgentSession {+ function createSession(+ options: {+ depth?: number;+ maxDepth?: number;+ streamFn?: StreamFn;+ agentMessageController?: AgentSessionMessageController;+ subagentRuntimeHost?: SubagentRuntimeHost;+ rlmSessionDir?: string;+ } = {},+ ): AgentSession {const authStorage = AuthStorage.create(join(tempDir, "auth.json"));authStorage.setRuntimeApiKey("anthropic", "test-key");const sessionManager = SessionManager.create(tempDir, join(tempDir, "sessions"));@@ -226,12 +250,183 @@ describe("AgentSession rlm recursion", () => {cwd: tempDir,modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models.json")),resourceLoader: createTestResourceLoader(),+ agentMessageController: options.agentMessageController,+ subagentRuntimeHost: options.subagentRuntimeHost,rlmDepth: options.depth,rlmMaxDepth: options.maxDepth,+ rlmSessionDir: options.rlmSessionDir,});return session;}+ it("creates readable collision-resistant default subagent session names", () => {+ expect(createDefaultRlmSubagentSessionName("Summarize the HTTP API!", "sub-a1b2c3d4")).toBe(+ "subagent-summarize-the-http-api-a1b2c3d4",+ );+ expect(createDefaultRlmSubagentSessionName("Summarize the HTTP API!", "sub-eeeeffff")).not.toBe(+ createDefaultRlmSubagentSessionName("Summarize the HTTP API!", "sub-a1b2c3d4"),+ );+ expect(createDefaultRlmSubagentSessionName("same task", "sub-aBcDeFgH")).not.toBe(+ createDefaultRlmSubagentSessionName("same task", "sub-AbCdEfGh"),+ );+ expect(createDefaultRlmSubagentSessionName("x".repeat(200), "sub-a1b2c3d4")).toHaveLength(64);+ });++ it("lets the orchestrator choose a unique subagent session name", async () => {+ const root = createSession();+ const result = await root.runRlmChild("inspect the API", { name: " api-reviewer " });+ if (!result.session_dir) {+ throw new Error("Missing child session directory");+ }+ const childId = basename(result.session_dir);+ const childSession = root.getRlmChildSession(childId);+ if (!childSession) {+ throw new Error("Missing retained child session");+ }+ expect(childSession.sessionName).toBe("api-reviewer");+ expect(root.listRlmSubagents().subagents[0]?.session_name).toBe("api-reviewer");++ await expect(root.runRlmChild("collide with child id", { name: childId })).rejects.toThrow(+ `RLM subagent session name "${childId}" is already in use`,+ );+ await expect(root.runRlmChild("inspect another API", { name: "api-reviewer" })).rejects.toThrow(+ 'RLM subagent session name "api-reviewer" is already in use',+ );+ await expect(+ root.runRlmChild("collide with retained session id", { name: childSession.sessionId }),+ ).rejects.toThrow(`RLM subagent session name "${childSession.sessionId}" is already in use`);+ await expect(root.runRlmChild("invalid name", { name: " " })).rejects.toThrow("rlm.run name must not be empty");+ await expect(root.runRlmChild("reserved name", { name: "all" })).rejects.toThrow(+ "Broadcast agent messaging is not supported",+ );+ });++ it("reserves a running child's current name after it is renamed", async () => {+ let releaseChild: () => void = () => {};+ const release = new Promise<void>((resolve) => {+ releaseChild = resolve;+ });+ let childStarted = false;+ const root = createSession({+ streamFn: (_model, context) => {+ const stream = createAssistantMessageEventStream();+ childStarted = true;+ void release.then(() => {+ stream.push({+ type: "done",+ reason: "stop",+ message: assistantMessage(`child answer: ${userText(context)}`),+ });+ });+ return stream;+ },+ });+ const runPromise = root.runRlmChild("rename while running", { name: "spawn-worker" });+ await waitFor(() => childStarted);+ const running = root.listRlmSubagents().subagents[0];+ if (!running) {+ throw new Error("Missing running child");+ }+ if (!running.session_id) {+ throw new Error("Missing running child session ID");+ }+ root.getRlmChildSession(running.rlm_child_id)?.setSessionName("renamed-running-worker");+ expect(root.listRlmSubagents().subagents[0]?.session_name).toBe("renamed-running-worker");++ await expect(root.runRlmChild("reuse renamed selector", { name: "renamed-running-worker" })).rejects.toThrow(+ 'RLM subagent session name "renamed-running-worker" is already in use',+ );+ await expect(root.runRlmChild("reuse running session id", { name: running.session_id })).rejects.toThrow(+ `RLM subagent session name "${running.session_id}" is already in use`,+ );+ releaseChild();+ await runPromise;+ });++ it("makes an externally restored retained child listable and deletable", async () => {+ const childId = "restored-child";+ const childDir = join(tempDir, childId);+ mkdirSync(childDir, { recursive: true });+ const child = createSession({ rlmSessionDir: childDir });+ child.setSessionName("restored-worker");+ const disposeChild = vi.spyOn(child, "disposeAsync");+ const root = createSession();++ expect(root.retainFinishedRlmChildSession(childId, child)).toBe(true);+ expect(root.listRlmSubagents().subagents).toEqual([+ expect.objectContaining({+ rlm_child_id: childId,+ session_name: "restored-worker",+ status: "completed",+ }),+ ]);++ await expect(root.deleteRlmSubagent("restored-worker")).resolves.toMatchObject({+ subagent: { rlm_child_id: childId, session_name: "restored-worker" },+ });+ expect(disposeChild).toHaveBeenCalledOnce();+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ });++ it("hides a retained child after failed deletion and keeps it selector-retryable", async () => {+ const childId = "retained-retry-child";+ const childDir = join(tempDir, childId);+ mkdirSync(childDir, { recursive: true });+ const child = createSession({ rlmSessionDir: childDir });+ child.setSessionName("retained-retry-worker");+ let deleteAttempts = 0;+ const deleteRuntime = vi.fn(async (_childId: string, session: AgentSession) => {+ deleteAttempts++;+ if (deleteAttempts === 1) {+ throw new Error("retained close failed");+ }+ await session.disposeAsync();+ });+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: child }),+ deleteRlmSubagentRuntime: deleteRuntime,+ },+ });+ expect(root.retainFinishedRlmChildSession(childId, child)).toBe(true);+ const retainedSnapshot = root.listRlmSubagents().subagents[0];+ if (!retainedSnapshot?.session_id) {+ throw new Error("Missing retained child session ID");+ }++ await expect(root.deleteRlmSubagent("retained-retry-worker")).rejects.toThrow("retained close failed");+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect((root as unknown as InspectableRlmSession)._retryableRlmSubagentDeletions.size).toBe(1);+ child.setSessionName("renamed-retry-worker");+ await expect(root.runRlmChild("reuse retry selector", { name: "retained-retry-worker" })).rejects.toThrow(+ 'RLM subagent session name "retained-retry-worker" is already in use',+ );+ await expect(root.runRlmChild("reuse retry session ID", { name: retainedSnapshot.session_id })).rejects.toThrow(+ `RLM subagent session name "${retainedSnapshot.session_id}" is already in use`,+ );++ await expect(root.deleteRlmSubagent("retained-retry-worker")).resolves.toMatchObject({+ subagent: { rlm_child_id: childId, session_name: "retained-retry-worker" },+ });+ expect(deleteRuntime).toHaveBeenCalledTimes(2);+ expect((root as unknown as InspectableRlmSession)._retryableRlmSubagentDeletions.size).toBe(0);+ });++ it("makes an orchestrator-chosen name override a custom runtime's preexisting name", async () => {+ const hostedChild = createSession();+ hostedChild.setSessionName("factory-assigned-name");+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: hostedChild }),+ deleteRlmSubagentRuntime: async () => {},+ },+ });++ await root.runRlmChild("inspect custom runtime", { name: "orchestrator-name" });++ expect(hostedChild.sessionName).toBe("orchestrator-name");+ });+it("runs a child session under a sub directory and returns an RLM-shaped result", async () => {const root = createSession();const childUpdates: Array<{@@ -266,6 +461,137 @@ describe("AgentSession rlm recursion", () => {expect(doneUpdate?.toolUseCount).toBeUndefined();});+ it("lists a completed child with its parent-scoped messaging identity until disposal", async () => {+ let daemonChildId = "";+ const root = createSession({+ agentMessageController: {+ listAgents: () => ({+ current: { activeSessionId: "parent-active", sessionId: "parent-session" },+ agents: [+ {+ activeSessionId: "other-child-active",+ sessionId: "other-child-session",+ runtimeKind: "subagent",+ cwd: tempDir,+ isStreaming: false,+ pendingMessageCount: 0,+ parentActiveSessionId: "other-parent",+ rlmChildId: daemonChildId,+ },+ {+ activeSessionId: "child-active",+ sessionId: "child-session",+ runtimeKind: "subagent",+ cwd: tempDir,+ isStreaming: false,+ pendingMessageCount: 0,+ parentActiveSessionId: "parent-active",+ rlmChildId: daemonChildId,+ },+ ],+ }),+ sendAgentMessage: async () => {+ throw new Error("unexpected send");+ },+ },+ });++ const result = await root.runRlmChild("retained worker");+ if (!result.session_dir) {+ throw new Error("Missing child session directory");+ }+ daemonChildId = basename(result.session_dir);++ expect(root.getRlmChildSession(daemonChildId)?.getLastAssistantText()).toBe("child answer: retained worker");+ const expectedSessionName = createDefaultRlmSubagentSessionName("retained worker", daemonChildId);+ expect(root.getRlmChildSession(daemonChildId)?.sessionName).toBe(expectedSessionName);+ const expectedRegistry = {+ subagents: [+ {+ rlm_child_id: daemonChildId,+ active_session_id: "child-active",+ session_id: "child-session",+ session_name: expectedSessionName,+ session_dir: result.session_dir,+ status: "completed",+ },+ ],+ };+ expect(root.listRlmSubagents()).toEqual(expectedRegistry);+ const inspectable = root as unknown as InspectableRlmSession;+ const conflictingDeletion = {+ ...expectedRegistry.subagents[0],+ rlm_child_id: "deleting-child",+ session_name: daemonChildId,+ status: "completed" as const,+ };+ inspectable._deletingRlmChildren.set("deleting-child", {+ subagent: conflictingDeletion,+ promise: Promise.resolve({ subagent: conflictingDeletion }),+ });+ await expect(root.deleteRlmSubagent(daemonChildId)).rejects.toThrow("is ambiguous");+ inspectable._deletingRlmChildren.delete("deleting-child");++ const handlers = inspectable._createKernelHostHandlers();+ const listHandler = handlers["rlm.list_subagents"];+ const deleteHandler = handlers["rlm.delete_subagent"];+ if (!listHandler || !deleteHandler) {+ throw new Error("Missing RLM subagent registry host handlers");+ }+ await expect(listHandler({})).resolves.toEqual(expectedRegistry);+ await expect(deleteHandler({ target: expectedSessionName })).resolves.toEqual({+ subagent: expectedRegistry.subagents[0],+ });+ expect(root.getRlmChildSession(daemonChildId)).toBeUndefined();+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ await expect(deleteHandler({ target: expectedSessionName })).rejects.toThrow("No direct RLM subagent matches");++ root.dispose();++ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ });++ it("disposes an inline child when setting its session name fails", async () => {+ const root = createSession();+ const appendSessionInfo = vi.spyOn(SessionManager.prototype, "appendSessionInfo").mockImplementation(() => {+ throw new Error("session info failed");+ });+ const dispose = vi.spyOn(AgentSession.prototype, "dispose");+ try {+ await expect(root.runRlmChild("inline naming failure", { name: "bad-name" })).rejects.toThrow(+ "session info failed",+ );+ expect(dispose).toHaveBeenCalled();+ } finally {+ appendSessionInfo.mockRestore();+ dispose.mockRestore();+ }+ });++ it("emits updated child session names after a retained child is renamed", async () => {+ const root = createSession();+ const events: unknown[] = [];+ root.subscribe((event) => events.push(event));++ const result = await root.runRlmChild("rename after completion", { name: "original-worker" });+ if (!result.session_dir) {+ throw new Error("Missing child session directory");+ }+ const childId = basename(result.session_dir);+ const child = root.getRlmChildSession(childId);+ if (!child) {+ throw new Error("Missing retained child session");+ }++ child.setSessionName("renamed-worker");++ const childUpdates = events.filter(+ (event): event is { type: "rlm_child_update"; child: { sessionName?: string } } =>+ typeof event === "object" && event !== null && (event as { type?: string }).type === "rlm_child_update",+ );+ expect(childUpdates.at(-1)?.child.sessionName).toBe("renamed-worker");+ });+it("surfaces a child's recap on its snapshot once the summarizer sets it", async () => {let releaseChild: () => void = () => {};const release = new Promise<void>((resolve) => {@@ -297,6 +623,18 @@ describe("AgentSession rlm recursion", () => {if (!rootRun?.session) {throw new Error("Missing child session on root run");}+ expect(root.listRlmSubagents()).toEqual({+ subagents: [+ {+ rlm_child_id: rootRun.id,+ active_session_id: null,+ session_id: rootRun.session.sessionId,+ session_name: createDefaultRlmSubagentSessionName("slow shard", rootRun.id),+ session_dir: rootRun.sessionDir,+ status: "running",+ },+ ],+ });// What the daemon summarizer does for subagents: stash the recap on the session,// which emits recap_update and re-emits the parent's enriched child snapshot.@@ -540,11 +878,368 @@ describe("AgentSession rlm recursion", () => {releaseChild();await expect(runPromise).rejects.toThrow("Cancelled by user");expect(childStatuses[childStatuses.length - 1]).toBe("cancelled");+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });// The run has finished; a second cancel finds nothing to stop.expect(root.cancelRlmChildRun(childId)).toBe(false);});+ it("does not let completion retention resurrect a child being deleted", async () => {+ let releaseRetention: () => void = () => {};+ const retentionGate = new Promise<void>((resolve) => {+ releaseRetention = resolve;+ });+ let releaseStarted = false;+ const hostedChild = createSession();+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: hostedChild }),+ deleteRlmSubagentRuntime: async (_childId, child) => {+ await child.disposeAsync();+ },+ releaseRlmSubagentRuntime: async (runtime, options, status) => {+ if (status !== "done") {+ await runtime.session.disposeAsync();+ return;+ }+ releaseStarted = true;+ await retentionGate;+ if (!options.parentSession.retainFinishedRlmChildSession(options.id, runtime.session)) {+ await runtime.session.disposeAsync();+ }+ },+ },+ });++ const runPromise = root.runRlmChild("fast child", { name: "fast-worker" });+ const runFailure = expect(runPromise).rejects.toThrow("Deleted by parent orchestrator");+ await waitFor(() => releaseStarted);+ const completed = root.listRlmSubagents().subagents[0];+ if (!completed) {+ throw new Error("Missing completed child during release");+ }+ const deletion = root.deleteRlmSubagent("fast-worker");+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ await expect(deletion).resolves.toEqual({ subagent: completed });+ await runFailure;+ releaseRetention();+ await Promise.resolve();++ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ });++ it("keeps failed closure retryable without hanging or late resurrection", async () => {+ let releaseChild: () => void = () => {};+ const release = new Promise<void>((resolve) => {+ releaseChild = resolve;+ });+ let childStarted = false;+ const childDir = join(tempDir, "release-failure-child");+ const hostedChild = createSession({+ rlmSessionDir: childDir,+ streamFn: (_model, context) => {+ const text = userText(context);+ const stream = createAssistantMessageEventStream();+ childStarted = true;+ void release.then(() => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage(`child answer: ${text}`) });+ });+ return stream;+ },+ });+ let deleteAttempts = 0;+ const deleteRuntime = vi.fn(async (_childId: string, child: AgentSession) => {+ deleteAttempts++;+ if (deleteAttempts === 1) {+ throw new Error("close failed");+ }+ await child.disposeAsync();+ });+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: hostedChild }),+ deleteRlmSubagentRuntime: deleteRuntime,+ releaseRlmSubagentRuntime: async () => {+ throw new Error("release failed");+ },+ },+ });++ const runPromise = root.runRlmChild("slow release", { name: "release-worker" });+ await waitFor(() => childStarted);+ const runFailure = expect(runPromise).rejects.toThrow("Deleted by parent orchestrator");+ const deletion = root.deleteRlmSubagent("release-worker");+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ await expect(deletion).rejects.toThrow("close failed");+ await runFailure;+ expect((root as unknown as InspectableRlmSession)._activeRlmChildRuns.size).toBe(0);+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });++ // The failed close remains directly retryable by the original selector even+ // though the cancelled child is hidden from the public registry.+ await expect(root.deleteRlmSubagent("release-worker")).resolves.toMatchObject({+ subagent: { session_name: "release-worker" },+ });+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ releaseChild();+ await Promise.resolve();+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ });++ it("does not restore failed delete retry state after parent teardown", async () => {+ let rejectDelete: (error: Error) => void = () => {};+ const deleteGate = new Promise<void>((_resolve, reject) => {+ rejectDelete = reject;+ });+ let childStarted = false;+ const hostedChild = createSession({+ streamFn: () => {+ const stream = createAssistantMessageEventStream();+ childStarted = true;+ return stream;+ },+ });+ const deleteRuntime = vi.fn(async () => {+ await deleteGate;+ });+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: hostedChild }),+ deleteRlmSubagentRuntime: deleteRuntime,+ },+ });++ const runPromise = root.runRlmChild("delete during parent teardown", { name: "teardown-worker" });+ const runFailure = expect(runPromise).rejects.toThrow("Deleted by parent orchestrator");+ await waitFor(() => childStarted);+ const deletion = root.deleteRlmSubagent("teardown-worker");+ const deletionFailure = expect(deletion).rejects.toThrow("close failed during teardown");+ await waitFor(() => deleteRuntime.mock.calls.length === 1);++ await root.disposeAsync();+ rejectDelete(new Error("close failed during teardown"));+ await deletionFailure;+ await runFailure;++ const internals = root as unknown as InspectableRlmSession;+ expect(internals._activeRlmChildRuns.size).toBe(0);+ expect(internals._retainedRlmChildSessions.size).toBe(0);+ expect(internals._retainedRlmChildUnsubscribes.size).toBe(0);+ expect(internals._retryableRlmSubagentDeletions.size).toBe(0);+ });++ it("drops a hidden delete retry after detached runtime release succeeds", async () => {+ let releaseChild: () => void = () => {};+ const release = new Promise<void>((resolve) => {+ releaseChild = resolve;+ });+ let childStarted = false;+ const hostedChild = createSession({+ streamFn: (_model, context) => {+ const stream = createAssistantMessageEventStream();+ childStarted = true;+ void release.then(() => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage(userText(context)) });+ });+ return stream;+ },+ });+ const releaseRuntime = vi.fn(async () => {+ await hostedChild.disposeAsync();+ });+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: hostedChild }),+ deleteRlmSubagentRuntime: async () => {+ throw new Error("close failed");+ },+ releaseRlmSubagentRuntime: releaseRuntime,+ },+ });++ const runPromise = root.runRlmChild("release after failed close", { name: "eventual-release-worker" });+ const runFailure = expect(runPromise).rejects.toThrow("Deleted by parent orchestrator");+ await waitFor(() => childStarted);+ await expect(root.deleteRlmSubagent("eventual-release-worker")).rejects.toThrow("close failed");+ await runFailure;+ const internals = root as unknown as InspectableRlmSession;+ expect(internals._retryableRlmSubagentDeletions.size).toBe(1);++ releaseChild();+ await waitFor(() => releaseRuntime.mock.calls.length === 1);+ await waitFor(() => internals._retryableRlmSubagentDeletions.size === 0);+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ await expect(root.deleteRlmSubagent("eventual-release-worker")).rejects.toThrow("No direct RLM subagent matches");+ });++ it("does not expose a cancelled child when release cleanup fails", async () => {+ let releaseChild: () => void = () => {};+ const release = new Promise<void>((resolve) => {+ releaseChild = resolve;+ });+ let childStarted = false;+ const hostedChild = createSession({+ streamFn: (_model, context) => {+ const stream = createAssistantMessageEventStream();+ childStarted = true;+ void release.then(() => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage(userText(context)) });+ });+ return stream;+ },+ });+ const disposeHostedChild = vi.spyOn(hostedChild, "disposeAsync");+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: hostedChild }),+ deleteRlmSubagentRuntime: async () => {},+ releaseRlmSubagentRuntime: async () => {+ throw new Error("release failed");+ },+ },+ });++ const runPromise = root.runRlmChild("cancel before failed release", { name: "cancelled-worker" });+ await waitFor(() => childStarted);+ const childId = root.listRlmSubagents().subagents[0]?.rlm_child_id;+ expect(childId).toBeTruthy();+ expect(root.cancelRlmChildRun(childId as string)).toBe(true);+ releaseChild();++ await expect(runPromise).rejects.toThrow();+ expect(disposeHostedChild).toHaveBeenCalledOnce();+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ });++ it("deletes a queued child without waiting for blocked startup", async () => {+ let releaseRuntimeCreation: () => void = () => {};+ const runtimeCreationGate = new Promise<void>((resolve) => {+ releaseRuntimeCreation = resolve;+ });+ let runtimeCreationStarted = false;+ const hostedChild = createSession();+ const releaseRuntime = vi.fn(async () => {+ await hostedChild.disposeAsync();+ });+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => {+ runtimeCreationStarted = true;+ await runtimeCreationGate;+ return { session: hostedChild };+ },+ deleteRlmSubagentRuntime: async () => {},+ releaseRlmSubagentRuntime: releaseRuntime,+ },+ });+ const runPromise = root.runRlmChild("blocked before runtime creation", { name: "queued-worker" });+ const runFailure = expect(runPromise).rejects.toThrow("Deleted by parent orchestrator");+ await waitFor(() => runtimeCreationStarted);+ const queued = root.listRlmSubagents().subagents[0];+ expect(queued).toBeDefined();++ await expect(root.deleteRlmSubagent("queued-worker")).resolves.toEqual({ subagent: queued });+ await runFailure;+ expect((root as unknown as InspectableRlmSession)._activeRlmChildRuns.size).toBe(1);+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ await expect(root.runRlmChild("replacement", { name: "queued-worker" })).rejects.toThrow("already in use");++ releaseRuntimeCreation();+ await waitFor(() => releaseRuntime.mock.calls.length === 1);+ await waitFor(() => (root as unknown as InspectableRlmSession)._activeRlmChildRuns.size === 0);+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ });++ it("keeps late startup cleanup retryable when release and fallback delete fail", async () => {+ let releaseRuntimeCreation: () => void = () => {};+ const runtimeCreationGate = new Promise<void>((resolve) => {+ releaseRuntimeCreation = resolve;+ });+ let runtimeCreationStarted = false;+ const hostedChild = createSession();+ const disposeHostedChild = vi.spyOn(hostedChild, "disposeAsync");+ let deleteAttempts = 0;+ const deleteRuntime = vi.fn(async () => {+ deleteAttempts++;+ if (deleteAttempts === 1) {+ throw new Error("fallback delete failed");+ }+ await hostedChild.disposeAsync();+ });+ const releaseRuntime = vi.fn(async () => {+ throw new Error("cancelled release failed");+ });+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => {+ runtimeCreationStarted = true;+ await runtimeCreationGate;+ return { session: hostedChild };+ },+ deleteRlmSubagentRuntime: deleteRuntime,+ releaseRlmSubagentRuntime: releaseRuntime,+ },+ });++ const runPromise = root.runRlmChild("delete during runtime creation", { name: "starting-worker" });+ const runFailure = expect(runPromise).rejects.toThrow("Deleted by parent orchestrator");+ await waitFor(() => runtimeCreationStarted);+ const starting = root.listRlmSubagents().subagents[0];+ expect(starting).toBeDefined();++ await expect(root.deleteRlmSubagent("starting-worker")).resolves.toEqual({ subagent: starting });+ await runFailure;+ expect(deleteRuntime).not.toHaveBeenCalled();+ releaseRuntimeCreation();++ const internals = root as unknown as InspectableRlmSession;+ await waitFor(() => releaseRuntime.mock.calls.length === 1);+ await waitFor(() => internals._retryableRlmSubagentDeletions.size === 1);+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(deleteRuntime).toHaveBeenCalledTimes(1);+ expect(disposeHostedChild).not.toHaveBeenCalled();++ await expect(root.deleteRlmSubagent("starting-worker")).resolves.toEqual({ subagent: starting });+ expect(deleteRuntime).toHaveBeenCalledTimes(2);+ expect(disposeHostedChild).toHaveBeenCalledOnce();+ expect(internals._retryableRlmSubagentDeletions.size).toBe(0);+ });++ it("deletes a running direct child by name and waits for runtime cleanup", async () => {+ let releaseChild: () => void = () => {};+ const release = new Promise<void>((resolve) => {+ releaseChild = resolve;+ });+ let childStarted = false;+ const root = createSession({+ streamFn: (_model, context) => {+ const text = userText(context);+ const stream = createAssistantMessageEventStream();+ childStarted = true;+ void release.then(() => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage(`child answer: ${text}`) });+ });+ return stream;+ },+ });++ const runPromise = root.runRlmChild("slow named shard", { name: "slow-worker" });+ await waitFor(() => childStarted);+ const running = root.listRlmSubagents().subagents[0];+ if (!running) {+ throw new Error("Missing running child registry entry");+ }+ const runFailure = expect(runPromise).rejects.toThrow("Deleted by parent orchestrator");+ const deletion = root.deleteRlmSubagent("slow-worker");+ const duplicateDeletion = root.deleteRlmSubagent(running.rlm_child_id);+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ await expect(deletion).resolves.toEqual({ subagent: running });+ await expect(duplicateDeletion).resolves.toEqual({ subagent: running });+ await runFailure;+ releaseChild();+ expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ });+it("cancels nested rlm child runs through the root session", async () => {let releaseChild: () => void = () => {};const release = new Promise<void>((resolve) => {@@ -594,6 +1289,7 @@ describe("AgentSession rlm recursion", () => {throw new Error("Missing nested run id");}+ await expect(root.deleteRlmSubagent(nestedId)).rejects.toThrow("No direct RLM subagent matches");expect(root.cancelRlmChildRun(nestedId)).toBe(true);releaseNested();await expect(nestedPromise).rejects.toThrow("Cancelled by user");diff --git a/packages/coding-agent/test/child-agent-summary-list.test.ts b/packages/coding-agent/test/child-agent-summary-list.test.tsindex e1f4859536..ee8bb3cbae 100644--- a/packages/coding-agent/test/child-agent-summary-list.test.ts+++ b/packages/coding-agent/test/child-agent-summary-list.test.ts@@ -139,6 +139,22 @@ describe("ChildAgentSummaryComponent inline list", () => {expect(out[ellipsisIndex - 1]).not.toBe(" ");});+ it("prefers stable session names over spawn prompts in the summary row", () => {+ const summary = new ChildAgentSummaryComponent();+ summary.setNodes([+ {+ ...node("a"),+ sessionName: "anticheat-review",+ label: "You are doing a manual trajectory review for anti-cheat evidence",+ recap: "Extracting and analyzing test results",+ },+ ]);+ const out = stripAnsi(summary.render(120).join("\n"));+ expect(out).toContain("anticheat-review");+ expect(out).not.toContain("manual trajectory");+ expect(out).toContain("Extracting and analyzing test results");+ });+it("keeps the selected background active across the entire row", () => {const summary = new ChildAgentSummaryComponent();summary.focused = true;diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex de0cd3f53e..8c75ce51b4 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -1,11 +1,13 @@-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import type { Socket } from "node:net";import { tmpdir } from "node:os";-import { join } from "node:path";+import { join, resolve } from "node:path";import type { Api, Model } from "@earendil-works/pi-ai";import { describe, expect, it, vi } from "vitest";+import type { AgentSessionMessageController } from "../src/core/agent-messages.js";import type { CreateAgentSessionRuntimeFactory } from "../src/core/agent-session-runtime.js";import type { AgentCronJob, AgentCronJobStore } from "../src/core/cron-jobs.js";+import { type CreateRlmSubagentRuntimeOptions, createDefaultRlmSubagentSessionName } from "../src/core/rlm-runtime.js";import { SessionManager } from "../src/core/session-manager.js";import type { ActiveSessionState, DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";import {@@ -150,7 +152,7 @@ describe("daemon mode helpers", () => {});});- it("lists and sends agent messages to live subagents", async () => {+ it("lists and sends agent messages to completed retained subagents", async () => {const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },createRuntime: async () => {@@ -169,6 +171,7 @@ describe("daemon mode helpers", () => {pendingMessageCount: 0,},} as never;+ const defaultSubagentName = createDefaultRlmSubagentSessionName("retained worker", "child-1");const subagentState = makeState("child", "parent") as ActiveSessionState & {runtime: ActiveSessionState["runtime"] & {session: {@@ -195,7 +198,7 @@ describe("daemon mode helpers", () => {},session: {sessionId: "session-child",- sessionName: "Subagent",+ sessionName: defaultSubagentName,isStreaming: false,pendingMessageCount: 0,acceptAgentMessagePrompt,@@ -203,49 +206,282 @@ describe("daemon mode helpers", () => {} as never;const internals = daemon as unknown as {sessions: Map<string, ActiveSessionState>;- createAgentMessageListResult(current: ActiveSessionState): {- agents: Array<{- activeSessionId: string;- runtimeKind?: string;- parentActiveSessionId?: string;- rlmChildId?: string;- }>;- };- sendAgentSessionMessage(options: {- targetSelector: string;- message: string;- fromState?: ActiveSessionState;- origin: "agent" | "cli";- }): Promise<unknown>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;};internals.sessions.set(parentState.activeSessionId, parentState);+ // A successfully completed RLM child remains idle in this daemon registry.internals.sessions.set(subagentState.activeSessionId, subagentState);- const subagentSummary = internals- .createAgentMessageListResult(parentState)+ const controller = internals.createAgentMessageController(() => parentState);+ const subagentSummary = controller+ .listAgents().agents.find((agent) => agent.activeSessionId === subagentState.activeSessionId);expect(subagentSummary).toMatchObject({+ sessionName: defaultSubagentName,runtimeKind: "subagent",parentActiveSessionId: parentState.activeSessionId,rlmChildId: "child-1",});+ if (!subagentSummary?.sessionName) {+ throw new Error("Missing default subagent session name");+ }await expect(- internals.sendAgentSessionMessage({- targetSelector: subagentState.activeSessionId,+ controller.sendAgentMessage({+ target: subagentSummary.sessionName,message: "report current progress",- fromState: parentState,- origin: "agent",}),).resolves.toMatchObject({deliveryStatus: "delivered",target: { activeSessionId: subagentState.activeSessionId, runtimeKind: "subagent" },});expect(acceptAgentMessagePrompt).toHaveBeenCalledOnce();- expect(acceptAgentMessagePrompt.mock.calls[0]?.[0]).toContain("To: Subagent, active child");+ expect(acceptAgentMessagePrompt.mock.calls[0]?.[0]).toContain(`To: ${defaultSubagentName}, active child`);expect(acceptAgentMessagePrompt.mock.calls[0]?.[0]).toContain("report current progress");});+ it("closes the exact parent-scoped daemon runtime when a retained subagent is deleted", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const parentState = makeState("parent");+ parentState.runtime = {+ ...parentState.runtime,+ session: {+ sessionManager: { getSessionArtifactDir: () => undefined },+ },+ } as ActiveSessionState["runtime"];+ const childState = makeState("child", parentState.activeSessionId);+ const foreignChildState = makeState("foreign-child", "other-parent");+ const childSession = {+ disposeAsync: vi.fn(async () => {}),+ } as unknown as ActiveSessionState["runtime"]["session"];+ const foreignSession = {+ disposeAsync: vi.fn(async () => {}),+ } as unknown as ActiveSessionState["runtime"]["session"];+ childState.runtime = {+ ...childState.runtime,+ metadata: { ...childState.runtime.metadata, rlmChildId: "child-1" },+ session: childSession,+ } as ActiveSessionState["runtime"];+ foreignChildState.runtime = {+ ...foreignChildState.runtime,+ metadata: { ...foreignChildState.runtime.metadata, rlmChildId: "child-1" },+ session: foreignSession,+ } as ActiveSessionState["runtime"];+ const closeSession = vi.fn(async () => {});+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ closeSession: typeof closeSession;+ createSubagentRuntimeHost(parent: ActiveSessionState): {+ deleteRlmSubagentRuntime(childId: string, session: ActiveSessionState["runtime"]["session"]): Promise<void>;+ };+ };+ internals.sessions.set(childState.activeSessionId, childState);+ internals.sessions.set(foreignChildState.activeSessionId, foreignChildState);+ internals.closeSession = closeSession;++ const staleParentReference = {+ disposeAsync: vi.fn(async () => {}),+ } as unknown as ActiveSessionState["runtime"]["session"];+ const host = internals.createSubagentRuntimeHost(parentState);+ await host.deleteRlmSubagentRuntime("child-1", staleParentReference);++ expect(closeSession).toHaveBeenCalledOnce();+ expect(closeSession).toHaveBeenCalledWith(childState, "killed", false);+ expect(closeSession).not.toHaveBeenCalledWith(foreignChildState, expect.anything());+ expect(childSession.disposeAsync).not.toHaveBeenCalled();+ expect(staleParentReference.disposeAsync).toHaveBeenCalledOnce();++ const missingSession = {+ disposeAsync: vi.fn(async () => {}),+ } as unknown as ActiveSessionState["runtime"]["session"];+ await host.deleteRlmSubagentRuntime("missing-child", missingSession);+ expect(missingSession.disposeAsync).toHaveBeenCalledOnce();+ });++ it("keeps a child live when its durable deletion boundary cannot be read", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-delete-registry-failure-"));+ try {+ const sessionDir = join(tempDir, "sessions");+ const parentManager = SessionManager.create(tempDir, sessionDir);+ parentManager.newSession();+ const parentArtifactDir = parentManager.getSessionArtifactDir();+ if (!parentArtifactDir) {+ throw new Error("Missing parent artifact directory");+ }+ mkdirSync(join(parentArtifactDir, "rlm-subagents.jsonl"), { recursive: true });++ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const parentState = makeState("parent");+ parentState.runtime = {+ ...parentState.runtime,+ session: makeRuntimeSession(parentManager),+ } as ActiveSessionState["runtime"];+ const childState = makeState("child", parentState.activeSessionId);+ childState.runtime = {+ ...childState.runtime,+ metadata: { ...childState.runtime.metadata, rlmChildId: "child-1" },+ session: { disposeAsync: vi.fn(async () => {}) },+ } as unknown as ActiveSessionState["runtime"];+ const closeSession = vi.fn(async () => {});+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ closeSession: typeof closeSession;+ createSubagentRuntimeHost(parent: ActiveSessionState): {+ deleteRlmSubagentRuntime(+ childId: string,+ session: ActiveSessionState["runtime"]["session"],+ ): Promise<void>;+ };+ };+ internals.sessions.set(childState.activeSessionId, childState);+ internals.closeSession = closeSession;++ await expect(+ internals+ .createSubagentRuntimeHost(parentState)+ .deleteRlmSubagentRuntime("child-1", childState.runtime.session),+ ).rejects.toThrow();+ expect(closeSession).not.toHaveBeenCalled();+ expect(internals.sessions.get(childState.activeSessionId)).toBe(childState);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("hides daemon sessions from messaging and observation while they are closing", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ worker: { authenticationToken: "worker-token" },+ });+ const parentState = makeState("parent");+ const childState = makeState("child", parentState.activeSessionId);+ const sessionPrompt = vi.fn(async () => {});+ for (const [state, sessionId] of [+ [parentState, "session-parent"],+ [childState, "session-child"],+ ] as const) {+ state.runtime = {+ ...state.runtime,+ cwd: "/tmp",+ session: {+ sessionId,+ sessionName: sessionId,+ prompt: sessionPrompt,+ isStreaming: false,+ pendingMessageCount: 0,+ },+ } as unknown as ActiveSessionState["runtime"];+ }+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ closingSessions: Map<string, Promise<void>>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;+ getBoundSessionState(id: string): ActiveSessionState;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;+ agentMessageTargetLocks: Map<string, Promise<void>>;+ promptWithAgentMessagePreparingGuard(state: ActiveSessionState, message: string): Promise<boolean>;+ };+ internals.sessions.set(parentState.activeSessionId, parentState);+ internals.sessions.set(childState.activeSessionId, childState);+ internals.closingSessions.set(childState.activeSessionId, Promise.resolve());++ const controller = internals.createAgentMessageController(() => parentState);+ const listed = controller.listAgents();+ expect(listed.agents).not.toContainEqual(+ expect.objectContaining({ activeSessionId: childState.activeSessionId }),+ );+ expect(() => internals.getBoundSessionState(childState.activeSessionId)).toThrow("is closing");+ await expect(+ controller.sendAgentMessage({ target: childState.activeSessionId, message: "continue" }),+ ).rejects.toThrow("is closing");+ const client = makeClient("client-1", childState.activeSessionId);+ for (const command of [+ { id: "prompt", type: "prompt", activeSessionId: childState.activeSessionId, message: "continue" },+ { id: "steer", type: "steer", activeSessionId: childState.activeSessionId, message: "continue" },+ { id: "follow-up", type: "follow_up", activeSessionId: childState.activeSessionId, message: "continue" },+ ] as const) {+ await expect(internals.handleCommand(client, command)).rejects.toThrow("is closing");+ }++ internals.closingSessions.delete(childState.activeSessionId);+ let releaseTargetLock: () => void = () => {};+ const targetLock = new Promise<void>((resolve) => {+ releaseTargetLock = resolve;+ });+ internals.agentMessageTargetLocks.set(childState.activeSessionId, targetLock);+ const guardedPrompt = internals.promptWithAgentMessagePreparingGuard(childState, "continue");+ await Promise.resolve();+ internals.closingSessions.set(childState.activeSessionId, Promise.resolve());+ releaseTargetLock();+ await expect(guardedPrompt).rejects.toThrow("closing before prompt delivery");+ expect(sessionPrompt).not.toHaveBeenCalled();+ });++ it("removes a closing daemon session even when runtime disposal fails", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const state = makeState("child");+ const dispose = vi.fn(async () => {+ throw new Error("dispose failed");+ });+ state.runtime = {+ ...state.runtime,+ dispose,+ session: {+ sessionId: "session-child",+ sessionFile: undefined,+ abort: vi.fn(() => new Promise<void>(() => {})),+ },+ } as unknown as ActiveSessionState["runtime"];+ state.extensionUiRequests = new Map();+ state.unsubscribe = vi.fn();+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ closingSessions: Map<string, Promise<void>>;+ closeSession(state: ActiveSessionState, reason: "killed", waitForAbort?: boolean): Promise<void>;+ closeChildSessions: ReturnType<typeof vi.fn>;+ isEmptyDraftContent: ReturnType<typeof vi.fn>;+ abortBashForClose: ReturnType<typeof vi.fn>;+ recordWorkerRecoveryState: ReturnType<typeof vi.fn>;+ broadcastToSession: ReturnType<typeof vi.fn>;+ cancelScheduledJobsForSession: ReturnType<typeof vi.fn>;+ };+ internals.sessions.set(state.activeSessionId, state);+ internals.closeChildSessions = vi.fn(async () => undefined);+ internals.isEmptyDraftContent = vi.fn(() => true);+ internals.abortBashForClose = vi.fn(async () => {});+ internals.recordWorkerRecoveryState = vi.fn();+ internals.broadcastToSession = vi.fn();+ internals.cancelScheduledJobsForSession = vi.fn();++ await expect(internals.closeSession(state, "killed", false)).rejects.toThrow("dispose failed");++ expect(dispose).toHaveBeenCalledOnce();+ expect(internals.sessions.has(state.activeSessionId)).toBe(false);+ expect(internals.closingSessions.has(state.activeSessionId)).toBe(false);+ });+it("lists and routes agent messages to peers hosted by another worker", async () => {const daemon = new AgentDaemon("/tmp/prime-agent-worker-test.sock", {defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },@@ -265,10 +501,11 @@ describe("daemon mode helpers", () => {pendingMessageCount: 0,},} as never;+ const remoteSelector = "remote is closing";const receipt = {id: "agentmsg-remote",source: "agent_message",- target: { activeSessionId: "remote", sessionId: "session-remote" },+ target: { activeSessionId: remoteSelector, sessionId: "session-remote" },message: "continue remotely",deliveryStatus: "delivered",deliveredAt: "2026-01-01T00:00:00.000Z",@@ -288,8 +525,8 @@ describe("daemon mode helpers", () => {}): Promise<unknown>;};internals.sessions.set(source.activeSessionId, source);- internals.remoteAgentPeers.set("remote", {- activeSessionId: "remote",+ internals.remoteAgentPeers.set(remoteSelector, {+ activeSessionId: remoteSelector,sessionId: "session-remote",sessionName: "Remote",runtimeKind: "top-level",@@ -300,17 +537,66 @@ describe("daemon mode helpers", () => {internals.sendRemoteAgentSessionMessage = sendRemoteAgentSessionMessage;expect(internals.createAgentMessageListResult(source).agents).toContainEqual(- expect.objectContaining({ activeSessionId: "remote" }),+ expect.objectContaining({ activeSessionId: remoteSelector }),);await expect(internals.sendAgentSessionMessage({- targetSelector: "remote",+ targetSelector: remoteSelector,message: "continue remotely",fromState: source,origin: "agent",}),).resolves.toEqual(receipt);- expect(sendRemoteAgentSessionMessage).toHaveBeenCalledWith(source, "remote", "continue remotely", undefined);+ expect(sendRemoteAgentSessionMessage).toHaveBeenCalledWith(+ source,+ remoteSelector,+ "continue remotely",+ undefined,+ );+ });++ it("fails unknown local agent-message targets without worker remote retries", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-worker-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ worker: { authenticationToken: "worker-token" },+ });+ const source = makeState("source");+ source.runtime = {+ ...source.runtime,+ cwd: "/tmp",+ session: {+ sessionId: "session-source",+ sessionName: "Source",+ isStreaming: false,+ pendingMessageCount: 0,+ },+ } as never;+ const sendRemoteAgentSessionMessage = vi.fn();+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ sendRemoteAgentSessionMessage: typeof sendRemoteAgentSessionMessage;+ sendAgentSessionMessage(options: {+ targetSelector: string;+ message: string;+ fromState: ActiveSessionState;+ origin: "agent";+ }): Promise<unknown>;+ };+ internals.sessions.set(source.activeSessionId, source);+ internals.sendRemoteAgentSessionMessage = sendRemoteAgentSessionMessage;++ await expect(+ internals.sendAgentSessionMessage({+ targetSelector: "deleted-child",+ message: "continue",+ fromState: source,+ origin: "agent",+ }),+ ).rejects.toThrow("Unknown active session: deleted-child");+ expect(sendRemoteAgentSessionMessage).not.toHaveBeenCalled();});it("reports queued status when a direct accept races into the queue", async () => {@@ -2591,6 +2877,662 @@ describe("daemon mode helpers", () => {}});+ it("rehydrates completed RLM subagents into the parent registry and durably deletes them", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-rlm-rehydrate-"));+ try {+ const sessionDir = join(tempDir, "sessions");+ const parentManager = SessionManager.create(tempDir, sessionDir);+ parentManager.newSession();+ parentManager.appendSessionInfo("Parent");+ const parentSessionFile = parentManager.getSessionFile();+ const parentArtifactDir = parentManager.getSessionArtifactDir();+ if (!parentSessionFile || !parentArtifactDir) {+ throw new Error("Missing parent session paths");+ }++ const childId = "child-1";+ const childSessionDir = join(parentArtifactDir, childId);+ const childManager = SessionManager.create(tempDir, childSessionDir);+ childManager.newSession({ parentSession: parentSessionFile });+ childManager.appendSessionInfo("spawn-worker");+ childManager.appendSessionInfo("renamed-worker");+ const childSessionFile = childManager.getSessionFile();+ const childArtifactDir = childManager.getSessionArtifactDir();+ if (!childSessionFile || !childArtifactDir) {+ throw new Error("Missing child session paths");+ }+ const grandchildId = "grandchild-1";+ const grandchildSessionDir = join(childArtifactDir, grandchildId);+ const grandchildManager = SessionManager.create(tempDir, grandchildSessionDir);+ grandchildManager.newSession({ parentSession: childSessionFile });+ grandchildManager.appendSessionInfo("nested-worker");+ const grandchildSessionFile = grandchildManager.getSessionFile();+ if (!grandchildSessionFile) {+ throw new Error("Missing grandchild session file");+ }+ writeFileSync(+ join(childArtifactDir, "rlm-subagents.jsonl"),+ `${JSON.stringify({+ type: "rlm_subagent",+ childId: grandchildId,+ sessionName: "nested-worker",+ sessionDir: grandchildSessionDir,+ sessionFile: grandchildSessionFile,+ parentSessionId: childManager.getSessionId(),+ parentSessionFile: childSessionFile,+ rlmDepth: 2,+ rlmMaxDepth: 4,+ rlmParentNodeId: grandchildId,+ status: "completed",+ createdAt: 2,+ updatedAt: "2026-01-01T00:00:00.000Z",+ })}\n${JSON.stringify({+ type: "rlm_subagent",+ childId: "cycle-to-root",+ sessionName: "cycle-to-root",+ sessionDir: parentArtifactDir,+ sessionFile: parentSessionFile,+ parentSessionId: childManager.getSessionId(),+ parentSessionFile: childSessionFile,+ rlmDepth: 2,+ rlmMaxDepth: 4,+ rlmParentNodeId: "cycle-to-root",+ status: "completed",+ createdAt: 3,+ updatedAt: "2026-01-01T00:00:00.000Z",+ })}\n`,+ );+ writeFileSync(+ join(parentArtifactDir, "rlm-subagents.jsonl"),+ `${JSON.stringify({+ type: "rlm_subagent",+ childId,+ sessionName: "spawn-worker",+ sessionDir: childSessionDir,+ sessionFile: childSessionFile,+ parentSessionId: parentManager.getSessionId(),+ parentSessionFile,+ rlmDepth: 1,+ rlmMaxDepth: 4,+ rlmParentNodeId: childId,+ status: "completed",+ createdAt: 1,+ updatedAt: "2026-01-01T00:00:00.000Z",+ })}\n`,+ );++ const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {+ return {+ session: makeRuntimeSession(options.sessionManager),+ extensionsResult: { extensions: [], errors: [], runtime: {} } as unknown as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["extensionsResult"],+ services: { cwd: options.cwd, agentDir: options.agentDir } as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["services"],+ diagnostics: [],+ };+ });+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir },+ createRuntime,+ });+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createSubagentRuntimeHost(parent: ActiveSessionState): {+ deleteRlmSubagentRuntime(+ childId: string,+ session: ActiveSessionState["runtime"]["session"],+ ): Promise<void>;+ };+ rehydrateCompletedRlmSubagents(parent: ActiveSessionState): Promise<void>;+ closeSession(state: ActiveSessionState, reason: "killed", waitForAbort?: boolean): Promise<void>;+ };++ const parentState = await internals.createRuntime({ type: "create", sessionPath: parentSessionFile });+ const childState = [...internals.sessions.values()].find(+ (state) => state.runtime.metadata.rlmChildId === childId,+ );+ const grandchildState = [...internals.sessions.values()].find(+ (state) => state.runtime.metadata.rlmChildId === grandchildId,+ );++ expect(createRuntime).toHaveBeenCalledTimes(3);+ expect(createRuntime.mock.calls[1]?.[0].sessionOptions).toMatchObject({+ rlmDepth: 1,+ rlmMaxDepth: 4,+ });+ expect(createRuntime.mock.calls[2]?.[0].sessionOptions).toMatchObject({+ rlmDepth: 2,+ rlmMaxDepth: 4,+ });+ expect(childState?.runtime.session.sessionName).toBe("renamed-worker");+ expect(childState?.runtime.metadata).toMatchObject({+ kind: "subagent",+ parentActiveSessionId: parentState.activeSessionId,+ parentSessionId: parentState.runtime.session.sessionId,+ rlmChildId: childId,+ rlmParentNodeId: childId,+ sessionDir: childSessionDir,+ });+ expect(parentState.runtime.session.retainFinishedRlmChildSession).toHaveBeenCalledWith(+ childId,+ childState?.runtime.session,+ );+ expect(grandchildState?.runtime.metadata).toMatchObject({+ kind: "subagent",+ parentActiveSessionId: childState?.activeSessionId,+ parentSessionId: childState?.runtime.session.sessionId,+ rlmChildId: grandchildId,+ });+ expect(childState?.runtime.session.retainFinishedRlmChildSession).toHaveBeenCalledWith(+ grandchildId,+ grandchildState?.runtime.session,+ );+ expect(+ [...internals.sessions.values()].some((state) => state.runtime.metadata.rlmChildId === "cycle-to-root"),+ ).toBe(false);++ if (!childState) {+ throw new Error("Missing rehydrated child state");+ }+ appendFileSync(join(parentArtifactDir, "rlm-subagents.jsonl"), "{unterminated malformed registry line");+ internals.closeSession = vi.fn(async (state: ActiveSessionState) => {+ internals.sessions.delete(state.activeSessionId);+ });+ await internals+ .createSubagentRuntimeHost(parentState)+ .deleteRlmSubagentRuntime(childId, childState.runtime.session);+ expect(internals.sessions.has(childState.activeSessionId)).toBe(false);+ const persistedLines = readFileSync(join(parentArtifactDir, "rlm-subagents.jsonl"), "utf8")+ .trim()+ .split(/\r?\n/);+ const persistedDeletion = JSON.parse(persistedLines.at(-1) ?? "") as { childId: string; status: string };+ expect(persistedDeletion).toMatchObject({ childId, status: "deleted" });++ await internals.rehydrateCompletedRlmSubagents(parentState);+ expect(createRuntime).toHaveBeenCalledTimes(3);+ expect([...internals.sessions.values()].some((state) => state.runtime.metadata.rlmChildId === childId)).toBe(+ false,+ );+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("coalesces retained rehydration with successful and failed explicit session opens", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-rehydrate-open-race-"));+ try {+ const sessionDir = join(tempDir, "sessions");+ const parentManager = SessionManager.create(tempDir, sessionDir);+ parentManager.newSession();+ const parentArtifactDir = parentManager.getSessionArtifactDir();+ const parentSessionFile = parentManager.getSessionFile();+ if (!parentArtifactDir || !parentSessionFile) {+ throw new Error("Missing parent session paths");+ }+ const childId = "racing-child";+ const childSessionDir = join(parentArtifactDir, childId);+ const childManager = SessionManager.create(tempDir, childSessionDir);+ childManager.newSession({ parentSession: parentSessionFile });+ childManager.appendSessionInfo("racing-worker");+ const childSessionFile = childManager.getSessionFile();+ if (!childSessionFile) {+ throw new Error("Missing child session file");+ }+ mkdirSync(parentArtifactDir, { recursive: true });+ writeFileSync(+ join(parentArtifactDir, "rlm-subagents.jsonl"),+ `${JSON.stringify({+ type: "rlm_subagent",+ childId,+ sessionName: "racing-worker",+ sessionDir: childSessionDir,+ sessionFile: childSessionFile,+ parentSessionId: parentManager.getSessionId(),+ parentSessionFile,+ rlmDepth: 1,+ rlmMaxDepth: 4,+ rlmParentNodeId: childId,+ status: "completed",+ createdAt: 1,+ updatedAt: "2026-01-01T00:00:00.000Z",+ })}\n`,+ );++ let bindStarted = false;+ let releaseBind: () => void = () => {};+ const bindGate = new Promise<void>((resolve) => {+ releaseBind = resolve;+ });+ let successfulBindStarted = false;+ let releaseSuccessfulBind: () => void = () => {};+ const successfulBindGate = new Promise<void>((resolve) => {+ releaseSuccessfulBind = resolve;+ });+ const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {+ const session = makeRuntimeSession(options.sessionManager);+ const runtimeNumber = createRuntime.mock.calls.length;+ session.bindExtensions = vi.fn(async () => {+ if (runtimeNumber === 1) {+ bindStarted = true;+ await bindGate;+ throw new Error("explicit bind failed");+ }+ if (runtimeNumber === 3) {+ successfulBindStarted = true;+ await successfulBindGate;+ }+ });+ return {+ session,+ extensionsResult: { extensions: [], errors: [], runtime: {} } as unknown as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["extensionsResult"],+ services: { cwd: options.cwd, agentDir: options.agentDir } as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["services"],+ diagnostics: [],+ };+ });+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir },+ createRuntime,+ });+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ rehydrateCompletedRlmSubagents(parent: ActiveSessionState): Promise<void>;+ };+ const parentState = makeState("parent");+ parentState.runtime = {+ ...parentState.runtime,+ metadata: { kind: "top-level", createdAt: 1 },+ runtimeConfig: {},+ services: { cwd: tempDir, agentDir: tempDir },+ session: makeRuntimeSession(parentManager),+ } as unknown as ActiveSessionState["runtime"];+ internals.sessions.set(parentState.activeSessionId, parentState);++ const explicitOpen = internals.createRuntime({ type: "create", sessionPath: childSessionFile });+ const explicitFailure = explicitOpen.catch((error: unknown) => error);+ for (let attempt = 0; attempt < 50 && !bindStarted; attempt++) {+ await new Promise((resolve) => setTimeout(resolve, 1));+ }+ expect(bindStarted).toBe(true);+ const rehydrate = internals.rehydrateCompletedRlmSubagents(parentState);+ releaseBind();+ const [explicitError] = await Promise.all([explicitFailure, rehydrate]);++ expect(explicitError).toEqual(expect.objectContaining({ message: "explicit bind failed" }));+ expect(createRuntime).toHaveBeenCalledTimes(2);+ expect(+ [...internals.sessions.values()].filter(+ (state) =>+ state.runtime.session.sessionFile &&+ resolve(state.runtime.session.sessionFile) === resolve(childSessionFile),+ ),+ ).toHaveLength(1);+ const rehydrated = [...internals.sessions.values()].find(+ (state) => state.runtime.metadata.rlmChildId === childId,+ );+ expect(rehydrated).toBeDefined();+ expect(parentState.runtime.session.retainFinishedRlmChildSession).toHaveBeenCalledWith(+ childId,+ rehydrated?.runtime.session,+ );++ const siblingId = "successful-racing-child";+ const siblingSessionDir = join(parentArtifactDir, siblingId);+ const siblingManager = SessionManager.create(tempDir, siblingSessionDir);+ siblingManager.newSession({ parentSession: parentSessionFile });+ siblingManager.appendSessionInfo("successful-racing-worker");+ const siblingSessionFile = siblingManager.getSessionFile();+ if (!siblingSessionFile) {+ throw new Error("Missing sibling session file");+ }+ const siblingArtifactDir = siblingManager.getSessionArtifactDir();+ if (!siblingArtifactDir) {+ throw new Error("Missing sibling artifact directory");+ }+ mkdirSync(siblingArtifactDir, { recursive: true });+ writeFileSync(+ join(siblingArtifactDir, "rlm-subagents.jsonl"),+ `${JSON.stringify({+ type: "rlm_subagent",+ childId: "cycle-to-root",+ sessionName: "cycle-to-root",+ sessionDir,+ sessionFile: parentSessionFile,+ parentSessionId: siblingManager.getSessionId(),+ parentSessionFile: siblingSessionFile,+ rlmDepth: 0,+ rlmMaxDepth: 4,+ rlmParentNodeId: "cycle-to-root",+ status: "completed",+ createdAt: 2,+ updatedAt: "2026-01-01T00:00:01.000Z",+ })}\n`,+ );+ appendFileSync(+ join(parentArtifactDir, "rlm-subagents.jsonl"),+ `${JSON.stringify({+ type: "rlm_subagent",+ childId: siblingId,+ sessionName: "successful-racing-worker",+ sessionDir: siblingSessionDir,+ sessionFile: siblingSessionFile,+ parentSessionId: parentManager.getSessionId(),+ parentSessionFile,+ rlmDepth: 1,+ rlmMaxDepth: 4,+ rlmParentNodeId: siblingId,+ status: "completed",+ createdAt: 2,+ updatedAt: "2026-01-01T00:00:01.000Z",+ })}\n`,+ );+ const successfulExplicitOpen = internals.createRuntime({+ type: "create",+ sessionPath: siblingSessionFile,+ });+ for (let attempt = 0; attempt < 50 && !successfulBindStarted; attempt++) {+ await new Promise((resolve) => setTimeout(resolve, 1));+ }+ expect(successfulBindStarted).toBe(true);+ const successfulRehydrate = internals.rehydrateCompletedRlmSubagents(parentState);+ releaseSuccessfulBind();+ const [successfulState] = await Promise.all([successfulExplicitOpen, successfulRehydrate]);++ expect(createRuntime).toHaveBeenCalledTimes(4);+ expect(createRuntime.mock.calls[3]?.[0].sessionOptions).toEqual(+ expect.objectContaining({+ rlmSessionDir: siblingSessionDir,+ rlmDepth: 1,+ rlmMaxDepth: 4,+ rlmParentNodeId: siblingId,+ }),+ );+ expect(successfulState.runtime.metadata).toEqual(+ expect.objectContaining({+ kind: "subagent",+ parentActiveSessionId: parentState.activeSessionId,+ rlmChildId: siblingId,+ }),+ );+ expect(internals.sessions.has(successfulState.activeSessionId)).toBe(true);+ expect(parentState.runtime.session.retainFinishedRlmChildSession).toHaveBeenCalledWith(+ siblingId,+ successfulState.runtime.session,+ );+ expect(successfulState.runtime.session.retainFinishedRlmChildSession).not.toHaveBeenCalledWith(+ "cycle-to-root",+ expect.anything(),+ );+ expect(internals.sessions.get(parentState.activeSessionId)).toBe(parentState);+ expect(+ [...internals.sessions.values()].filter(+ (state) =>+ state.runtime.session.sessionFile &&+ resolve(state.runtime.session.sessionFile) === resolve(siblingSessionFile),+ ),+ ).toHaveLength(1);++ const stableId = "stable-explicit-child";+ const stableSessionDir = join(parentArtifactDir, stableId);+ const stableManager = SessionManager.create(tempDir, stableSessionDir);+ stableManager.newSession({ parentSession: parentSessionFile });+ stableManager.appendSessionInfo("stable-explicit-worker");+ const stableSessionFile = stableManager.getSessionFile();+ if (!stableSessionFile) {+ throw new Error("Missing stable explicit session file");+ }+ appendFileSync(+ join(parentArtifactDir, "rlm-subagents.jsonl"),+ `${JSON.stringify({+ type: "rlm_subagent",+ childId: stableId,+ sessionName: "stable-explicit-worker",+ sessionDir: stableSessionDir,+ sessionFile: stableSessionFile,+ parentSessionId: parentManager.getSessionId(),+ parentSessionFile,+ rlmDepth: 2,+ rlmMaxDepth: 5,+ rlmParentNodeId: stableId,+ status: "completed",+ createdAt: 3,+ updatedAt: "2026-01-01T00:00:02.000Z",+ })}\n`,+ );+ const stableState = await internals.createRuntime({ type: "create", sessionPath: stableSessionFile });+ expect(stableState.runtime.metadata.kind).toBe("top-level");+ await internals.rehydrateCompletedRlmSubagents(parentState);++ expect(createRuntime).toHaveBeenCalledTimes(6);+ expect(createRuntime.mock.calls[5]?.[0].sessionOptions).toEqual(+ expect.objectContaining({+ rlmSessionDir: stableSessionDir,+ rlmDepth: 2,+ rlmMaxDepth: 5,+ rlmParentNodeId: stableId,+ }),+ );+ expect(stableState.runtime.metadata.kind).toBe("top-level");+ expect(internals.sessions.has(stableState.activeSessionId)).toBe(false);+ const restoredStableState = [...internals.sessions.values()].find(+ (state) => state.runtime.metadata.rlmChildId === stableId,+ );+ expect(restoredStableState?.runtime.metadata).toEqual(+ expect.objectContaining({+ kind: "subagent",+ parentActiveSessionId: parentState.activeSessionId,+ rlmChildId: stableId,+ }),+ );+ expect(parentState.runtime.session.retainFinishedRlmChildSession).toHaveBeenCalledWith(+ stableId,+ restoredStableState?.runtime.session,+ );+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("gives RLM subagents messaging controllers for their own nested children", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-nested-controller-"));+ try {+ const sessionNamesDuringBind: Array<string | undefined> = [];+ const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {+ const session = makeRuntimeSession(options.sessionManager);+ session.bindExtensions = vi.fn(async () => {+ sessionNamesDuringBind.push(options.sessionManager.getSessionName());+ });+ return {+ session,+ extensionsResult: { extensions: [], errors: [], runtime: {} } as unknown as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["extensionsResult"],+ services: { cwd: options.cwd, agentDir: options.agentDir } as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["services"],+ diagnostics: [],+ };+ });+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir: tempDir },+ createRuntime,+ });+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ bindingSessions: Set<string>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createRlmSubagentRuntime(+ parentState: ActiveSessionState,+ options: CreateRlmSubagentRuntimeOptions,+ ): Promise<unknown>;+ };+ const parentState = await internals.createRuntime({+ type: "create",+ sessionPath: join(tempDir, "parent.jsonl"),+ });+ const childSessionName = createDefaultRlmSubagentSessionName("spawn a nested worker", "child-1");+ let publishedWhileBinding = false;+ await internals.createRlmSubagentRuntime(parentState, {+ parentSession: parentState.runtime.session,+ id: "child-1",+ prompt: "spawn a nested worker",+ sessionName: childSessionName,+ sessionDir: join(tempDir, "child"),+ model: {} as Model<Api>,+ thinkingLevel: "off",+ serviceTier: null,+ scopedModels: [],+ activeToolNames: [],+ customTools: [],+ includeGoals: false,+ includeCompactSkill: false,+ rlmDepth: 1,+ rlmMaxDepth: 2,+ rlmParentNodeId: "child-1",+ onSessionPublished: (session) => {+ expect(session.sessionName).toBe(childSessionName);+ const state = [...internals.sessions.values()].find(+ (candidate) => candidate.runtime.session === session,+ );+ publishedWhileBinding = !!state && internals.bindingSessions.has(state.activeSessionId);+ },+ });+ expect(publishedWhileBinding).toBe(true);++ const childOptions = createRuntime.mock.calls[1]?.[0];+ const childController = childOptions?.sessionOptions?.agentMessageController;+ expect(childController).toBeDefined();+ const currentChild = childController?.listAgents().current;+ const childActiveSessionId = currentChild?.activeSessionId;+ expect(childActiveSessionId).toBeTruthy();+ expect(currentChild?.sessionName).toBe(childSessionName);+ expect(sessionNamesDuringBind[1]).toBeUndefined();++ const grandchildState = makeState("grandchild", childActiveSessionId);+ grandchildState.runtime = {+ ...grandchildState.runtime,+ cwd: tempDir,+ metadata: { ...grandchildState.runtime.metadata, rlmChildId: "grandchild-1" },+ session: {+ sessionId: "session-grandchild",+ sessionName: "Grandchild",+ isStreaming: false,+ pendingMessageCount: 0,+ },+ } as never;+ internals.sessions.set(grandchildState.activeSessionId, grandchildState);+ expect(childController?.listAgents().agents).toContainEqual(+ expect.objectContaining({+ activeSessionId: grandchildState.activeSessionId,+ parentActiveSessionId: childActiveSessionId,+ rlmChildId: "grandchild-1",+ }),+ );++ const sessionsBeforeCancelledStartup = internals.sessions.size;+ vi.mocked(parentState.runtime.session.getRlmChildRunStatus).mockReturnValue("cancelled");+ await expect(+ internals.createRlmSubagentRuntime(parentState, {+ parentSession: parentState.runtime.session,+ id: "cancelled-child",+ prompt: "delete during daemon startup",+ sessionName: "cancelled-worker",+ sessionDir: join(tempDir, "cancelled-child"),+ model: {} as Model<Api>,+ thinkingLevel: "off",+ serviceTier: null,+ scopedModels: [],+ activeToolNames: [],+ customTools: [],+ includeGoals: false,+ includeCompactSkill: false,+ rlmDepth: 1,+ rlmMaxDepth: 2,+ rlmParentNodeId: "cancelled-child",+ }),+ ).rejects.toThrow();+ expect(parentState.runtime.session.getRlmChildRunStatus).toHaveBeenCalledWith("cancelled-child");+ expect(internals.sessions.size).toBe(sessionsBeforeCancelledStartup);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("closes a registered RLM runtime when its requested session name cannot be persisted", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-child-name-failure-"));+ try {+ let failingChildSession: ReturnType<typeof makeRuntimeSession> | undefined;+ const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {+ const session = makeRuntimeSession(options.sessionManager);+ if (createRuntime.mock.calls.length > 1) {+ failingChildSession = session;+ session.setSessionName = vi.fn(() => {+ throw new Error("name persistence failed");+ });+ }+ return {+ session,+ extensionsResult: { extensions: [], errors: [], runtime: {} } as unknown as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["extensionsResult"],+ services: { cwd: options.cwd, agentDir: options.agentDir } as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["services"],+ diagnostics: [],+ };+ });+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir: tempDir },+ createRuntime,+ });+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createRlmSubagentRuntime(+ parentState: ActiveSessionState,+ options: CreateRlmSubagentRuntimeOptions,+ ): Promise<unknown>;+ };+ const parentState = await internals.createRuntime({+ type: "create",+ sessionPath: join(tempDir, "parent.jsonl"),+ });+ await expect(+ internals.createRlmSubagentRuntime(parentState, {+ parentSession: parentState.runtime.session,+ id: "child-name-failure",+ prompt: "fail while naming",+ sessionName: "requested-name",+ sessionDir: join(tempDir, "child"),+ model: {} as Model<Api>,+ thinkingLevel: "off",+ serviceTier: null,+ scopedModels: [],+ activeToolNames: [],+ customTools: [],+ includeGoals: false,+ includeCompactSkill: false,+ rlmDepth: 1,+ rlmMaxDepth: 2,+ rlmParentNodeId: "child-name-failure",+ }),+ ).rejects.toThrow("name persistence failed");++ expect(failingChildSession).toBeDefined();+ expect(failingChildSession?.disposeAsync).toHaveBeenCalledOnce();+ expect(internals.sessions.size).toBe(1);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("excludes half-bound sessions from targeting until extension binding completes", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-binding-gate-"));try {@@ -4194,14 +5136,25 @@ function makeRuntimeSession(): Awaited<ReturnType<CreateAgentSessionRuntimeFactory>>["session"] {return {sessionManager,+ messages: [],+ extensionRunner: {+ hasHandlers: vi.fn(() => false),+ emit: vi.fn(async () => {}),+ },sessionFile: sessionManager.getSessionFile(),sessionId: sessionManager.getSessionId(),+ get sessionName() {+ return sessionManager.getSessionName();+ },setSubagentRuntimeHost: vi.fn(),+ getRlmChildRunStatus: vi.fn(() => "running"),+ retainFinishedRlmChildSession: vi.fn(() => true),subscribe: vi.fn(() => vi.fn()),bindExtensions: vi.fn(async () => {}),setExecEnvProvider: vi.fn(),- setSessionName: vi.fn(),+ setSessionName: vi.fn((name: string) => sessionManager.appendSessionInfo(name)),dispose: vi.fn(),+ disposeAsync: vi.fn(async () => {}),abort: vi.fn(async () => {}),} as unknown as Awaited<ReturnType<CreateAgentSessionRuntimeFactory>>["session"];}diff --git a/packages/coding-agent/test/ipython-bootstrap.test.ts b/packages/coding-agent/test/ipython-bootstrap.test.tsindex caa5c3d18c..cad537f639 100644--- a/packages/coding-agent/test/ipython-bootstrap.test.ts+++ b/packages/coding-agent/test/ipython-bootstrap.test.ts@@ -11,6 +11,13 @@ describe("IPython RLM bootstrap", () => {expect(buildRlmBootstrapCode()).toMatch(/^import asyncio$/m);});+ it("gives subagent registry operations the actionable missing-runtime fallback", () => {+ const code = buildRlmBootstrapCode();+ expect(code).toContain("async def list_subagents(self)");+ expect(code).toContain("async def delete_subagent(self, target)");+ expect(code).toContain("self._raise_missing()");+ });+it("disables colored output for subprocesses launched by the kernel", () => {expect(buildRlmBootstrapCode()).toContain('_prime_agent_os.environ["NO_COLOR"] = "1"');});diff --git a/packages/coding-agent/test/suite/agent-session-runtime.test.ts b/packages/coding-agent/test/suite/agent-session-runtime.test.tsindex 86ff21d767..5b54d98426 100644--- a/packages/coding-agent/test/suite/agent-session-runtime.test.ts+++ b/packages/coding-agent/test/suite/agent-session-runtime.test.ts@@ -233,12 +233,97 @@ describe("AgentSessionRuntime characterization", () => {expect(secondDispose).toHaveBeenCalledTimes(1);});+ it("deletes exact and replaced in-process RLM child runtimes and retained sessions", async () => {+ const { runtime } = await createRuntimeForTest(() => {});+ const childSession = {} as AgentSession;+ const disposeRuntime = vi.fn(async () => {});+ const childRuntime = { session: childSession, dispose: disposeRuntime } as unknown as AgentSessionRuntime;+ const runtimeWithSubagents = runtime as unknown as RuntimeSubagentMapAccess;+ runtimeWithSubagents.subagentRuntimes.set("child-1", childRuntime);++ await runtime.deleteRlmSubagentRuntime("child-1", childSession);++ expect(disposeRuntime).toHaveBeenCalledOnce();+ expect(runtimeWithSubagents.subagentRuntimes.has("child-1")).toBe(false);++ const currentSession = {} as AgentSession;+ const disposeReplacedRuntime = vi.fn(async () => {});+ const replacedRuntime = {+ session: currentSession,+ dispose: disposeReplacedRuntime,+ } as unknown as AgentSessionRuntime;+ const disposeStaleSession = vi.fn(async () => {});+ const staleSession = { disposeAsync: disposeStaleSession } as unknown as AgentSession;+ runtimeWithSubagents.subagentRuntimes.set("replaced-child", replacedRuntime);++ await runtime.deleteRlmSubagentRuntime("replaced-child", staleSession);++ expect(disposeReplacedRuntime).toHaveBeenCalledOnce();+ expect(disposeStaleSession).toHaveBeenCalledOnce();+ expect(runtimeWithSubagents.subagentRuntimes.has("replaced-child")).toBe(false);++ const disposeRetained = vi.fn(async () => {});+ const retainedSession = { disposeAsync: disposeRetained } as unknown as AgentSession;+ await runtime.deleteRlmSubagentRuntime("retained-child", retainedSession);+ expect(disposeRetained).toHaveBeenCalledOnce();+ });++ it("publishes in-process RLM sessions before create resolves and rejects cancelled startup", async () => {+ const { runtime, faux, tempDir } = await createRuntimeForTest(() => {});+ const parentSession = runtime.session;+ const getRunStatus = vi.spyOn(parentSession, "getRlmChildRunStatus").mockReturnValue("running");+ let createResolved = false;+ const onSessionPublished = vi.fn((session: AgentSession) => {+ expect(createResolved).toBe(false);+ expect(session.sessionName).toBe("in-process-worker");+ });+ const baseOptions = {+ parentSession,+ prompt: "run in process",+ model: faux.getModel(),+ thinkingLevel: "off" as const,+ serviceTier: null,+ scopedModels: [],+ activeToolNames: [],+ customTools: [],+ includeGoals: false,+ includeCompactSkill: false,+ rlmDepth: 1,+ rlmMaxDepth: 2,+ };++ const childRuntime = await runtime.createRlmSubagentRuntime({+ ...baseOptions,+ id: "in-process-child",+ sessionName: "in-process-worker",+ sessionDir: join(tempDir, "in-process-child"),+ rlmParentNodeId: "in-process-child",+ onSessionPublished,+ });+ createResolved = true;+ expect(onSessionPublished).toHaveBeenCalledOnce();+ await runtime.deleteRlmSubagentRuntime("in-process-child", childRuntime.session);++ getRunStatus.mockReturnValue("cancelled");+ await expect(+ runtime.createRlmSubagentRuntime({+ ...baseOptions,+ id: "cancelled-child",+ sessionName: "cancelled-worker",+ sessionDir: join(tempDir, "cancelled-child"),+ rlmParentNodeId: "cancelled-child",+ }),+ ).rejects.toThrow("startup was cancelled");+ expect((runtime as unknown as RuntimeSubagentMapAccess).subagentRuntimes.has("cancelled-child")).toBe(false);+ });+it("disposes hosted RLM children during session replacement", async () => {const disposeRlmSubagentRuntimes = vi.fn(async () => {});const host: SubagentRuntimeHost = {createRlmSubagentRuntime: async () => {throw new Error("unexpected child creation");},+ deleteRlmSubagentRuntime: async () => {},disposeRlmSubagentRuntimes,};const { runtime } = await createRuntimeForTest(() => {});diff --git a/packages/coding-agent/test/suite/regressions/4519-heartbeat-rebirth.test.ts b/packages/coding-agent/test/suite/regressions/4519-heartbeat-rebirth.test.tsindex a6f5e25e24..a6ffff9b17 100644--- a/packages/coding-agent/test/suite/regressions/4519-heartbeat-rebirth.test.ts+++ b/packages/coding-agent/test/suite/regressions/4519-heartbeat-rebirth.test.ts@@ -263,6 +263,7 @@ describe("ENG-4519 heartbeat rebirth", () => {const activeSessionId = "active-session";const runtime = { session: original.session };const state = { activeSessionId, runtime } as unknown as ActiveSessionState;+ internals.sessions.set(activeSessionId, state);let releaseLock: () => void = () => {};const lock = new Promise<void>((resolve) => {releaseLock = resolve;diff --git a/packages/coding-agent/test/system-prompt.test.ts b/packages/coding-agent/test/system-prompt.test.tsindex 651c2343dd..6ecc2d9470 100644--- a/packages/coding-agent/test/system-prompt.test.ts+++ b/packages/coding-agent/test/system-prompt.test.ts@@ -126,7 +126,7 @@ describe("buildRlmPrompt", () => {expect(prompt).not.toContain("Read each skill's SKILL.md for its API");});- test("mentions agent observation recovery only when the skill is installed", () => {+ test("exposes the automatic child registry independently of observation skills", () => {const withoutObserve = buildRlmPrompt({cwd: "/repo",messagesPath: "/repo/.pi/sessions/session.jsonl",@@ -139,11 +139,12 @@ describe("buildRlmPrompt", () => {activeTools: ["ipython"],});- expect(withoutObserve).toContain(- "Write a small disk registry under `os.environ.get('RLM_SESSION_DIR')` when set",- );- expect(withoutObserve).not.toContain("recover status later with `agent_observe`");- expect(withObserve).toContain("recover status later with `agent_observe`");+ for (const prompt of [withoutObserve, withObserve]) {+ expect(prompt).toContain("await rlm.list_subagents()");+ expect(prompt).toContain("await rlm.delete_subagent(child)");+ expect(prompt).toContain("automatic child registry");+ expect(prompt).not.toContain("Write a small disk registry");+ }});test("documents the %%bash first-line rule when ipython is active", () => {@@ -379,18 +380,28 @@ describe("buildSystemPrompt", () => {expect(prompt).toContain("asyncio.create_task");expect(prompt).toContain("Sub-agents should not block Prime Agent by default");expect(prompt).toContain("Default to non-blocking subagents");- expect(prompt).toContain("disk-backed registry");- expect(prompt).toContain("RLM_SESSION_DIR");- expect(prompt).toContain("from pathlib import Path");- expect(prompt).toContain("import os");- expect(prompt).toContain("kernel restarts, state restore, or compaction");- expect(prompt).toContain("agent_observe.list_agents");- expect(prompt).toContain('runtimeKind == "subagent"');- expect(prompt).toContain("parentSessionId");- expect(prompt).toContain("parentActiveSessionId");+ expect(prompt).toContain("automatic child registry");+ expect(prompt).toContain("parent-scoped subagent registry");+ expect(prompt).toContain("kernel restarts, state restore, and compaction");+ expect(prompt).toContain("rlm.list_subagents");+ expect(prompt).toContain("rlm.delete_subagent");+ expect(prompt).toContain("rlm_child_id");+ expect(prompt).toContain("active_session_id");+ expect(prompt).toContain("session_name");+ expect(prompt).toContain("name='api-reviewer'");+ expect(prompt).toContain("names must be non-empty and unique");+ expect(prompt).toContain("session_dir");+ expect(prompt).toContain("`agent_observe` skill is installed and a registry entry has `active_session_id`");+ expect(prompt).toContain("agent_observe.get_agent");expect(prompt).toContain("agent_observe.recent_messages");- expect(prompt).toContain("agent_message.list_agents");+ expect(prompt).toContain("Successful subagent sessions remain in that registry");+ expect(prompt).toContain("current parent session remains open");+ expect(prompt).toContain("retained children close when their parent session closes");expect(prompt).toContain("agent_message.send");+ expect(prompt).toContain("agent_message.send(child.session_name");+ expect(prompt).toContain("readable, unique default `session_name`");+ expect(prompt).toContain("same child");+ expect(prompt).not.toContain("disk-backed registry");expect(prompt).toContain("mode='steer'");expect(prompt).toContain("sub-agent work that can run in the background");expect(prompt).toContain("do not block the main execution path");diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.pyindex e2ef222263..b3f2a8fe6d 100644--- a/prime-agent-runtime/src/rlm/__init__.py+++ b/prime-agent-runtime/src/rlm/__init__.py@@ -43,6 +43,16 @@ class RLMResult:turns: int = 0+@dataclass(frozen=True)+class RLMSubagent:+ rlm_child_id: str+ active_session_id: str | None+ session_id: str | None+ session_name: str+ session_dir: Path+ status: str++def _env_int(name: str, default: int) -> int:raw = os.environ.get(name)if raw is None or raw == "":@@ -164,6 +174,60 @@ async def run(prompt: str, **kwargs: Any) -> RLMResult:return _result_from_payload(payload)+def _subagent_from_payload(payload: Any, operation: str = "rlm.list_subagents") -> RLMSubagent:+ if not isinstance(payload, dict):+ raise RuntimeError(f"{operation} returned an invalid subagent entry")+ child_id = payload.get("rlm_child_id")+ active_session_id = payload.get("active_session_id")+ session_id = payload.get("session_id")+ session_name = payload.get("session_name")+ session_dir = payload.get("session_dir")+ status = payload.get("status")+ if not isinstance(child_id, str) or not child_id:+ raise RuntimeError(f"{operation} entry is missing rlm_child_id")+ if active_session_id is not None and not isinstance(active_session_id, str):+ raise RuntimeError(f"{operation} entry has invalid active_session_id")+ if session_id is not None and not isinstance(session_id, str):+ raise RuntimeError(f"{operation} entry has invalid session_id")+ if not isinstance(session_name, str) or not session_name:+ raise RuntimeError(f"{operation} entry is missing session_name")+ if not isinstance(session_dir, str) or not session_dir:+ raise RuntimeError(f"{operation} entry is missing session_dir")+ if status not in {"running", "completed"}:+ raise RuntimeError(f"{operation} entry has invalid status")+ return RLMSubagent(+ rlm_child_id=child_id,+ active_session_id=active_session_id,+ session_id=session_id,+ session_name=session_name,+ session_dir=Path(session_dir),+ status=status,+ )+++async def list_subagents() -> list[RLMSubagent]:+ """List direct RLM children retained by the current parent session."""+ payload = await host_request("rlm.list_subagents")+ entries = payload.get("subagents")+ if not isinstance(entries, list):+ raise RuntimeError("rlm.list_subagents returned an invalid subagents registry")+ return [_subagent_from_payload(entry) for entry in entries]+++async def delete_subagent(target: str | RLMSubagent) -> RLMSubagent:+ """Delete one running or retained direct child from the current parent session."""+ if isinstance(target, RLMSubagent):+ selector = target.rlm_child_id+ elif isinstance(target, str):+ selector = target.strip()+ if not selector:+ raise ValueError("target must not be empty")+ else:+ raise TypeError(f"target must be str or RLMSubagent, got {type(target).__name__}")+ payload = await host_request("rlm.delete_subagent", {"target": selector})+ return _subagent_from_payload(payload.get("subagent"), "rlm.delete_subagent")++class _HarnessProxy:"""Resolve the harness state against the current environment on every access.@@ -222,6 +286,12 @@ class _RLMCallable:async def run(self, prompt: str, **kwargs: Any) -> RLMResult:return await run(prompt, **kwargs)+ async def list_subagents(self) -> list[RLMSubagent]:+ return await list_subagents()++ async def delete_subagent(self, target: str | RLMSubagent) -> RLMSubagent:+ return await delete_subagent(target)+async def __call__(self, prompt: str, **kwargs: Any) -> RLMResult:return await run(prompt, **kwargs)@@ -245,11 +315,14 @@ __all__ = ["McpToolError","NotEnabled","RLMResult",+ "RLMSubagent","RefinementEvent","TokenUsage",+ "delete_subagent","get_harness_state","harness","host_request",+ "list_subagents","rlm","run",]diff --git a/prime-agent-runtime/test/test_subagent_registry.py b/prime-agent-runtime/test/test_subagent_registry.pynew file mode 100644index 0000000000..dff6eadc9b--- /dev/null+++ b/prime-agent-runtime/test/test_subagent_registry.py@@ -0,0 +1,151 @@+from __future__ import annotations++import asyncio+import importlib+import unittest+from pathlib import Path+from unittest.mock import AsyncMock, patch+++rlm_module = importlib.import_module("rlm")+++class RlmSubagentRegistryTest(unittest.TestCase):+ def test_lists_parent_scoped_subagents_from_host(self) -> None:+ host_request = AsyncMock(+ return_value={+ "subagents": [+ {+ "rlm_child_id": "sub-a1b2c3d4",+ "active_session_id": "active-child",+ "session_id": "session-child",+ "session_name": "subagent-check-api-a1b2c3d4",+ "session_dir": "/tmp/parent/sub-a1b2c3d4",+ "status": "completed",+ }+ ]+ }+ )++ with patch.object(rlm_module, "host_request", host_request):+ subagents = asyncio.run(rlm_module.rlm.list_subagents())++ self.assertEqual(len(subagents), 1)+ self.assertEqual(subagents[0].rlm_child_id, "sub-a1b2c3d4")+ self.assertEqual(subagents[0].active_session_id, "active-child")+ self.assertEqual(subagents[0].session_id, "session-child")+ self.assertEqual(subagents[0].session_name, "subagent-check-api-a1b2c3d4")+ self.assertEqual(subagents[0].session_dir, Path("/tmp/parent/sub-a1b2c3d4"))+ self.assertEqual(subagents[0].status, "completed")+ host_request.assert_awaited_once_with("rlm.list_subagents")++ def test_forwards_orchestrator_chosen_name_to_host(self) -> None:+ host_request = AsyncMock(+ return_value={+ "answer": "done",+ "usage": {"prompt_tokens": 1, "completion_tokens": 1},+ "turns": 1,+ "session_dir": "/tmp/parent/sub-a1b2c3d4",+ }+ )++ with patch.object(rlm_module, "host_request", host_request):+ asyncio.run(rlm_module.rlm("check the API", name="api-reviewer"))++ host_request.assert_awaited_once_with(+ "rlm.run",+ {"prompt": "check the API", "kwargs": {"name": "api-reviewer"}},+ )++ def test_deletes_subagent_by_name_through_host(self) -> None:+ deleted_payload = {+ "rlm_child_id": "sub-a1b2c3d4",+ "active_session_id": "active-child",+ "session_id": "session-child",+ "session_name": "api-reviewer",+ "session_dir": "/tmp/parent/sub-a1b2c3d4",+ "status": "completed",+ }+ host_request = AsyncMock(return_value={"subagent": deleted_payload})++ with patch.object(rlm_module, "host_request", host_request):+ deleted = asyncio.run(rlm_module.rlm.delete_subagent(" api-reviewer "))++ self.assertEqual(deleted.rlm_child_id, "sub-a1b2c3d4")+ self.assertEqual(deleted.session_name, "api-reviewer")+ host_request.assert_awaited_once_with(+ "rlm.delete_subagent",+ {"target": "api-reviewer"},+ )++ def test_deletes_subagent_object_by_child_id(self) -> None:+ subagent = rlm_module.RLMSubagent(+ rlm_child_id="sub-a1b2c3d4",+ active_session_id=None,+ session_id="session-child",+ session_name="api-reviewer",+ session_dir=Path("/tmp/parent/sub-a1b2c3d4"),+ status="running",+ )+ host_request = AsyncMock(+ return_value={+ "subagent": {+ "rlm_child_id": subagent.rlm_child_id,+ "active_session_id": subagent.active_session_id,+ "session_id": subagent.session_id,+ "session_name": subagent.session_name,+ "session_dir": str(subagent.session_dir),+ "status": subagent.status,+ }+ }+ )++ with patch.object(rlm_module, "host_request", host_request):+ asyncio.run(rlm_module.delete_subagent(subagent))++ host_request.assert_awaited_once_with(+ "rlm.delete_subagent",+ {"target": "sub-a1b2c3d4"},+ )++ def test_rejects_invalid_delete_response_and_target(self) -> None:+ host_request = AsyncMock(return_value={"subagent": {"status": "completed"}})++ with patch.object(rlm_module, "host_request", host_request):+ with self.assertRaisesRegex(RuntimeError, "rlm.delete_subagent entry is missing rlm_child_id"):+ asyncio.run(rlm_module.delete_subagent("api-reviewer"))++ with self.assertRaisesRegex(ValueError, "target must not be empty"):+ asyncio.run(rlm_module.delete_subagent(" "))+ with self.assertRaisesRegex(TypeError, "target must be str or RLMSubagent"):+ asyncio.run(rlm_module.delete_subagent(123))++ def test_rejects_invalid_registry_payload(self) -> None:+ host_request = AsyncMock(return_value={"subagents": [{"status": "completed"}]})++ with patch.object(rlm_module, "host_request", host_request):+ with self.assertRaisesRegex(RuntimeError, "missing rlm_child_id"):+ asyncio.run(rlm_module.list_subagents())++ def test_requires_a_default_session_name(self) -> None:+ host_request = AsyncMock(+ return_value={+ "subagents": [+ {+ "rlm_child_id": "sub-a1b2c3d4",+ "active_session_id": None,+ "session_id": "session-child",+ "session_dir": "/tmp/parent/sub-a1b2c3d4",+ "status": "running",+ }+ ]+ }+ )++ with patch.object(rlm_module, "host_request", host_request):+ with self.assertRaisesRegex(RuntimeError, "missing session_name"):+ asyncio.run(rlm_module.list_subagents())+++if __name__ == "__main__":+ unittest.main()