Skip to content

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

Rust

feat(coding-agent): per-sibling-set names and family roster (#595)

Sebastian Müller7f207361ffa8
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 1690e81ae5..7cb6200580 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -8,6 +8,7 @@
- Fixed SIGINT in print mode leaving the session active until liveness reclaim.
- Fixed daemon startup failing permanently when an interrupted supervisor owner directory contained only stray files.
- Fixed agents-view fallback notices and scoped live sessions surviving transient refresh failures across chat returns.
+- Fixed stopping completed subagents deleting their retained sessions.
## [0.5.1] - 2026-08-04
diff --git a/packages/coding-agent/skills/agent-message/SKILL.md b/packages/coding-agent/skills/agent-message/SKILL.md
index 0b2f8ddac9..1115ad0f74 100644
--- a/packages/coding-agent/skills/agent-message/SKILL.md
+++ b/packages/coding-agent/skills/agent-message/SKILL.md
@@ -25,6 +25,10 @@ if child is not None:
## API
+- `await agent_message.roster()` — returns `current` (`name`, `id`, `depth`) and
+ relationship-scoped `entries` (`relationship`, `name`, `id`, `depth`, `status`)
+ for the current agent's parent, siblings, and children. It includes inactive
+ family members and sorts parent, siblings by name, then children by name.
- `await agent_message.list_agents()` — returns `current` and `agents`, where
each agent includes active session id, session id, optional name, runtime
kind, cwd, streaming state, and pending message count. This includes live
diff --git a/packages/coding-agent/skills/agent-message/src/agent_message/__init__.py b/packages/coding-agent/skills/agent-message/src/agent_message/__init__.py
index 5e5ee6de52..aa7a928100 100644
--- a/packages/coding-agent/skills/agent-message/src/agent_message/__init__.py
+++ b/packages/coding-agent/skills/agent-message/src/agent_message/__init__.py
@@ -20,6 +20,11 @@ async def list_agents() -> dict[str, Any]:
return await host_request("agent_message.list")
+async def roster() -> dict[str, Any]:
+ """List this agent's parent, siblings, and children, including inactive family."""
+ return await host_request("agent_message.roster")
+
+
async def send(target: str, message: str, mode: MessageMode = "auto") -> dict[str, Any]:
"""Send one direct text message to another active Prime Agent session.
diff --git a/packages/coding-agent/src/cli/daemon-command.ts b/packages/coding-agent/src/cli/daemon-command.ts
index 0c5085ff60..1969549829 100644
--- a/packages/coding-agent/src/cli/daemon-command.ts
+++ b/packages/coding-agent/src/cli/daemon-command.ts
@@ -272,15 +272,24 @@ async function runOpen(parsed: ParsedDaemonClientCommand): Promise<void> {
const client = new DaemonClient(parsed.socketPath);
await client.connect();
try {
- const sessions = await getLiveSessions(client);
- const sessionName = sessionArgs.name ?? nextDefaultSessionName(sessions);
- const response = await client.request({
- type: "create",
- name: sessionName,
- config: sessionArgs.config,
- sessionPath: sessionArgs.sessionPath,
- continueRecent: sessionArgs.continueRecent,
- });
+ const autoName = sessionArgs.name === undefined;
+ const sessions = await getLiveSessions(client, autoName);
+ let sessionName = sessionArgs.name ?? nextDefaultSessionName(sessions);
+ let response: DaemonResponse;
+ while (true) {
+ response = await client.request({
+ type: "create",
+ name: sessionName,
+ config: sessionArgs.config,
+ sessionPath: sessionArgs.sessionPath,
+ continueRecent: sessionArgs.continueRecent,
+ });
+ if (response.success || !autoName || !response.error.includes(`Agent name "${sessionName}" is unavailable`)) {
+ break;
+ }
+ sessions.push({ sessionName } as SessionSummary);
+ sessionName = nextDefaultSessionName(sessions);
+ }
const data = requireSuccess(response);
if (!isLiveSessionSummary(data)) {
throw new Error("Daemon returned an invalid create response");
@@ -629,8 +638,8 @@ function resolvePathOption(value: string, cwd: string): string {
return isLocalPath(expanded) ? resolve(cwd, expanded) : expanded;
}
-async function getLiveSessions(client: DaemonClient): Promise<SessionSummary[]> {
- const response = await client.request({ type: "list" });
+async function getLiveSessions(client: DaemonClient, all = false): Promise<SessionSummary[]> {
+ const response = await client.request({ type: "list", ...(all ? { all: true } : {}) });
const data = requireSuccess(response);
const sessions = getSessionSummaries(data);
if (!sessions) {
@@ -645,12 +654,20 @@ function nextDefaultSessionName(sessions: SessionSummary[]): string {
);
const numericNames = [...existingNames]
.map((name) => Number.parseInt(name, 10))
- .filter((value) => Number.isInteger(value) && value > 0);
+ .filter((value) => Number.isSafeInteger(value) && value > 0);
let next = numericNames.length > 0 ? Math.max(...numericNames) + 1 : 1;
- while (existingNames.has(String(next))) {
+ while (Number.isSafeInteger(next)) {
+ if (!existingNames.has(String(next))) {
+ return String(next);
+ }
next++;
}
- return String(next);
+
+ let fallback = "session";
+ while (existingNames.has(fallback)) {
+ fallback += "-";
+ }
+ return fallback;
}
async function runStart(parsed: ParsedDaemonClientCommand): Promise<void> {
diff --git a/packages/coding-agent/src/core/agent-messages.ts b/packages/coding-agent/src/core/agent-messages.ts
index 57ab32edc1..239be588a8 100644
--- a/packages/coding-agent/src/core/agent-messages.ts
+++ b/packages/coding-agent/src/core/agent-messages.ts
@@ -16,6 +16,8 @@ export const DEFAULT_AGENT_MESSAGE_RATE_LIMIT_REFILL_MS = 1000;
export type AgentSessionMessageDeliveryMode = "auto" | "steer" | "follow_up";
export type AgentSessionMessageDeliveryStatus = "delivered" | "queued";
export type AgentSessionMessageRuntimeKind = "top-level" | "subagent";
+export type AgentFamilyStatus = "running" | "idle" | "inactive";
+export type AgentFamilyRelationship = "parent" | "sibling" | "child";
export interface AgentSessionMessageEndpoint {
activeSessionId: string;
@@ -35,6 +37,11 @@ export interface AgentSessionMessageAgentSummary extends AgentSessionMessageEndp
parentActiveSessionId?: string;
rlmChildId?: string;
sessionDir?: string;
+ sessionPath?: string;
+ parentSessionId?: string;
+ parentSessionPath?: string;
+ rlmDepth?: number;
+ status?: AgentFamilyStatus;
}
export interface AgentSessionMessageListResult {
@@ -42,6 +49,40 @@ export interface AgentSessionMessageListResult {
agents: AgentSessionMessageAgentSummary[];
}
+export interface AgentFamilyCatalogEntry {
+ id: string;
+ name?: string;
+ depth: number;
+ status: AgentFamilyStatus;
+ parentSessionId?: string;
+ parentSessionPath?: string;
+ sessionPath?: string;
+}
+
+export interface AgentFamilyRosterEntry {
+ relationship: AgentFamilyRelationship;
+ name: string;
+ id: string;
+ depth: number;
+ status: AgentFamilyStatus;
+}
+
+export interface AgentFamilyRosterResult {
+ current: { name: string; id: string; depth: number };
+ entries: AgentFamilyRosterEntry[];
+}
+
+export interface AgentSessionNameScope {
+ parentSessionId?: string;
+ parentSessionPath?: string;
+ depth: number;
+}
+
+export interface AgentSessionNameAvailabilityInput extends AgentSessionNameScope {
+ name: string;
+ ignoreSessionId?: string;
+}
+
export interface AgentSessionMessagePayload {
id: string;
source: typeof AGENT_MESSAGE_SOURCE;
@@ -87,6 +128,9 @@ export interface AgentSessionMessageSendInput {
export interface AgentSessionMessageController {
listAgents(): AgentSessionMessageListResult | Promise<AgentSessionMessageListResult>;
+ roster?(): AgentFamilyRosterResult | Promise<AgentFamilyRosterResult>;
+ assertSessionNameAvailable?(input: AgentSessionNameAvailabilityInput): void | Promise<void>;
+ setSessionName?(name: string): void | Promise<void>;
sendAgentMessage(input: AgentSessionMessageSendInput): Promise<AgentSessionMessageReceipt>;
}
@@ -98,6 +142,112 @@ export interface AgentSessionMessageSafetyStatus {
rateLimitRefillMs: number;
}
+export function formatAgentSessionNameUnavailable(name: string, depth: number): string {
+ return `Agent name "${name}" is unavailable: an agent of that name already exists at depth ${depth} under this parent`;
+}
+
+export function assertAgentSessionNameAvailable(
+ catalog: readonly AgentFamilyCatalogEntry[],
+ input: AgentSessionNameAvailabilityInput,
+): void {
+ const conflict = catalog.some(
+ (entry) =>
+ entry.id !== input.ignoreSessionId &&
+ entry.name === input.name &&
+ entry.depth === input.depth &&
+ sameAgentSessionNameParent(entry, input, catalog),
+ );
+ if (conflict) {
+ throw new Error(formatAgentSessionNameUnavailable(input.name, input.depth));
+ }
+}
+
+export function buildAgentFamilyRoster(
+ current: AgentFamilyCatalogEntry,
+ catalog: readonly AgentFamilyCatalogEntry[],
+): AgentFamilyRosterResult {
+ const parent = catalog.find((entry) => isAgentFamilyParent(entry, current));
+ const siblings = catalog.filter(
+ (entry) =>
+ entry.id !== current.id && entry.depth === current.depth && sameAgentFamilyParent(entry, current, catalog),
+ );
+ const children = catalog.filter((entry) => entry.depth === current.depth + 1 && isAgentFamilyParent(current, entry));
+ const row = (relationship: AgentFamilyRelationship, entry: AgentFamilyCatalogEntry): AgentFamilyRosterEntry => ({
+ relationship,
+ name: entry.name ?? entry.id,
+ id: entry.id,
+ depth: entry.depth,
+ status: entry.status,
+ });
+ return {
+ current: { name: current.name ?? current.id, id: current.id, depth: current.depth },
+ entries: [
+ ...(parent ? [row("parent", parent)] : []),
+ ...siblings
+ .sort((a, b) => (a.name ?? a.id).localeCompare(b.name ?? b.id))
+ .map((entry) => row("sibling", entry)),
+ ...children.sort((a, b) => (a.name ?? a.id).localeCompare(b.name ?? b.id)).map((entry) => row("child", entry)),
+ ],
+ };
+}
+
+function sameAgentSessionNameParent(
+ left: AgentSessionNameScope,
+ right: AgentSessionNameScope,
+ catalog: readonly AgentFamilyCatalogEntry[],
+): boolean {
+ if (left.depth === 0 && right.depth === 0) {
+ return true;
+ }
+ return sameAgentFamilyParent(left, right, catalog);
+}
+
+function sameAgentFamilyParent(
+ left: AgentSessionNameScope,
+ right: AgentSessionNameScope,
+ catalog: readonly AgentFamilyCatalogEntry[],
+): boolean {
+ if (left.parentSessionPath !== undefined && left.parentSessionPath === right.parentSessionPath) {
+ return true;
+ }
+ if (left.parentSessionId !== undefined && left.parentSessionId === right.parentSessionId) {
+ return true;
+ }
+ const hasCatalogParentPair = (parentSessionId: string | undefined, parentSessionPath: string | undefined) =>
+ parentSessionId !== undefined &&
+ parentSessionPath !== undefined &&
+ catalog.some(
+ (entry) =>
+ (entry.id === parentSessionId && entry.sessionPath === parentSessionPath) ||
+ (entry.parentSessionId === parentSessionId && entry.parentSessionPath === parentSessionPath),
+ );
+ if (
+ hasCatalogParentPair(left.parentSessionId, right.parentSessionPath) ||
+ hasCatalogParentPair(right.parentSessionId, left.parentSessionPath)
+ ) {
+ return true;
+ }
+ if (
+ left.depth === 0 &&
+ right.depth === 0 &&
+ left.parentSessionPath === undefined &&
+ right.parentSessionPath === undefined &&
+ left.parentSessionId === undefined &&
+ right.parentSessionId === undefined
+ ) {
+ return true;
+ }
+ // Unresolved mixed identifiers stay unrelated to avoid false name conflicts across families.
+ return false;
+}
+
+function isAgentFamilyParent(parent: AgentFamilyCatalogEntry, child: AgentFamilyCatalogEntry): boolean {
+ return (
+ (child.parentSessionPath !== undefined && child.parentSessionPath === parent.sessionPath) ||
+ (child.parentSessionId !== undefined && child.parentSessionId === parent.id)
+ );
+}
+
export function createAgentSessionMessageId(): string {
return `agentmsg_${randomUUID()}`;
}
@@ -307,6 +457,10 @@ export function createAgentMessageHostHandlers(
): Record<string, HostRequestHandler> {
return {
"agent_message.list": async () => (await controller.listAgents()) as unknown as Record<string, unknown>,
+ "agent_message.roster": async () => {
+ if (!controller.roster) throw new Error("agent family roster is not available in this session");
+ return (await controller.roster()) as unknown as Record<string, unknown>;
+ },
"agent_message.send": async (payload) => {
if (typeof payload.target !== "string") {
throw new Error("agent_message.send target must be a string");
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index 3be6f0e67c..b8ea3b6b0b 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -54,13 +54,17 @@ import { sleep } from "../utils/sleep.js";
import {
AGENT_MESSAGE_RECEIVED_PREVIEW_LABEL,
AGENT_MESSAGE_SKILL_NAME,
+ type AgentFamilyCatalogEntry,
+ type AgentFamilyRosterResult,
type AgentSessionMessage,
type AgentSessionMessageAgentSummary,
type AgentSessionMessageController,
type AgentSessionMessageListResult,
type AgentSessionMessageReceipt,
+ assertAgentSessionNameAvailable,
assertDirectAgentMessageTarget,
createAgentMessageHostHandlers,
+ formatAgentSessionNameUnavailable,
isAgentSessionMessage,
normalizeAgentSessionMessage,
normalizeAgentSessionMessageDeliveryMode,
@@ -2973,13 +2977,20 @@ export class AgentSession {
handleAgentMessageHostRequest(
type: string,
payload: Record<string, unknown> = {},
- ): Promise<AgentSessionMessageListResult | AgentSessionMessageReceipt> | AgentSessionMessageListResult {
+ ):
+ | Promise<AgentSessionMessageListResult | AgentSessionMessageReceipt | AgentFamilyRosterResult>
+ | AgentSessionMessageListResult
+ | AgentFamilyRosterResult {
if (!this._agentMessageController) {
throw new Error("agent messaging is not available in this session");
}
switch (type) {
case "agent_message.list":
return this._agentMessageController.listAgents();
+ case "agent_message.roster":
+ if (!this._agentMessageController.roster)
+ throw new Error("agent family roster is not available in this session");
+ return this._agentMessageController.roster();
case "agent_message.send": {
if (typeof payload.target !== "string") {
throw new Error("agent_message.send target must be a string");
@@ -4187,6 +4198,7 @@ export class AgentSession {
toolSnippets,
promptGuidelines,
allowRecursion: this._rlmDepth < this._rlmMaxDepth,
+ rlmDepth: this._rlmDepth,
harnessState: this._loadMergedHarnessState(),
};
return buildSystemPrompt(this._baseSystemPromptOptions);
@@ -8126,7 +8138,11 @@ export class AgentSession {
appendEntry: (customType, data) => {
this.sessionManager.appendCustomEntry(customType, data);
},
- setSessionName: (name) => {
+ setSessionName: async (name) => {
+ if (this._agentMessageController?.setSessionName) {
+ await this._agentMessageController.setSessionName(name);
+ return;
+ }
this.setSessionName(name);
},
getSessionName: () => {
@@ -8455,6 +8471,8 @@ export class AgentSession {
createAgentMessageHostHandlers({
listAgents: async () =>
(await this.handleAgentMessageHostRequest("agent_message.list")) as AgentSessionMessageListResult,
+ roster: async () =>
+ (await this.handleAgentMessageHostRequest("agent_message.roster")) as AgentFamilyRosterResult,
sendAgentMessage: async (input) =>
(await this.handleAgentMessageHostRequest("agent_message.send", {
target: input.target,
@@ -8925,6 +8943,46 @@ export class AgentSession {
return matches[0]!;
}
+ /** Delete an inactive direct or nested child by its registry child id without affecting active runs. */
+ async deleteInactiveRlmSubagent(
+ childId: string,
+ isExternallyRunning: () => boolean = () => false,
+ ): Promise<"deleted" | "not_found" | "running"> {
+ const isRunning = (): boolean => this._activeRlmChildRuns.has(childId) || isExternallyRunning();
+ if (isRunning()) {
+ return "running";
+ }
+ const subagent = [
+ ...(await this.listRlmSubagents()).subagents,
+ ...this._retryableRlmSubagentDeletions.values(),
+ ].find((entry) => entry.rlm_child_id === childId);
+ if (!subagent) {
+ for (const run of this._activeRlmChildRuns.values()) {
+ const result = await run.session?.deleteInactiveRlmSubagent(childId, isExternallyRunning);
+ if (result && result !== "not_found") {
+ return result;
+ }
+ }
+ for (const retained of this._retainedRlmChildSessions.values()) {
+ const result = await retained.deleteInactiveRlmSubagent(childId, isExternallyRunning);
+ if (result !== "not_found") {
+ return result;
+ }
+ }
+ return "not_found";
+ }
+ if (isRunning()) {
+ return "running";
+ }
+ const result = await this._trackRlmSubagentDeletion(subagent, () => {
+ if (isRunning()) {
+ return Promise.resolve({ subagent, outcome: "skipped_running" });
+ }
+ return this._deleteResolvedRlmSubagent(subagent);
+ });
+ return result.outcome === "skipped_running" ? "running" : "deleted";
+ }
+
/** Delete a running, retained, or passive direct child selected from this parent session's registry. */
async deleteRlmSubagent(target: string): Promise<RlmDeleteSubagentResult> {
const inFlight = [...this._deletingRlmChildren.values()].filter(({ subagent }) =>
@@ -9221,47 +9279,44 @@ export class AgentSession {
}
private async _assertRlmSubagentSessionNameAvailable(name: string, ignorePendingReservation = false): Promise<void> {
+ const depth = this._rlmDepth + 1;
if (!ignorePendingReservation && this._pendingRlmSubagentSessionNames.has(name)) {
- throw new Error(`RLM subagent session name "${name}" is already in use`);
- }
- 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 = await 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`);
+ throw new Error(formatAgentSessionNameUnavailable(name, depth));
+ }
+ const localConflict =
+ [...this._activeRlmChildRuns.values()].some(
+ (run) => run.session?.sessionName === name || (!run.session && run.sessionName === name),
+ ) ||
+ [...this._retainedRlmChildSessions.values()].some((session) => session.sessionName === name) ||
+ [...this._retryableRlmSubagentDeletions.values()].some((entry) => entry.session_name === name);
+ if (localConflict) {
+ throw new Error(formatAgentSessionNameUnavailable(name, depth));
+ }
+ const controller = this._agentMessageController;
+ if (!controller) return;
+ const input = {
+ name,
+ depth,
+ parentSessionId: this.sessionId,
+ parentSessionPath: this.sessionFile,
+ };
+ if (controller.assertSessionNameAvailable) {
+ await controller.assertSessionNameAvailable(input);
+ return;
}
+ const listed = await controller.listAgents();
+ const catalog = listed.agents.map(
+ (agent): AgentFamilyCatalogEntry => ({
+ id: agent.sessionId,
+ ...(agent.sessionName ? { name: agent.sessionName } : {}),
+ depth: agent.rlmDepth ?? 0,
+ status: agent.status ?? "idle",
+ ...(agent.parentSessionId ? { parentSessionId: agent.parentSessionId } : {}),
+ ...(agent.parentSessionPath ? { parentSessionPath: agent.parentSessionPath } : {}),
+ ...(agent.sessionPath ? { sessionPath: agent.sessionPath } : {}),
+ }),
+ );
+ assertAgentSessionNameAvailable(catalog, input);
}
private async _authenticatedRlmModels(): Promise<Model<Api>[]> {
@@ -9332,7 +9387,7 @@ export class AgentSession {
}
if (requestedSessionName) {
if (this._pendingRlmSubagentSessionNames.has(requestedSessionName)) {
- throw new Error(`RLM subagent session name "${requestedSessionName}" is already in use`);
+ throw new Error(formatAgentSessionNameUnavailable(requestedSessionName, this._rlmDepth + 1));
}
this._pendingRlmSubagentSessionNames.add(requestedSessionName);
}
diff --git a/packages/coding-agent/src/core/extensions/types.ts b/packages/coding-agent/src/core/extensions/types.ts
index 99b86a5b78..89ff11dcf3 100644
--- a/packages/coding-agent/src/core/extensions/types.ts
+++ b/packages/coding-agent/src/core/extensions/types.ts
@@ -1145,7 +1145,7 @@ export interface ExtensionAPI {
// =========================================================================
/** Set the session display name (shown in session selector). */
- setSessionName(name: string): void;
+ setSessionName(name: string): void | Promise<void>;
/** Get the current session name, if set. */
getSessionName(): string | undefined;
@@ -1364,7 +1364,7 @@ export type SendUserMessageHandler = (
export type AppendEntryHandler = <T = unknown>(customType: string, data?: T) => void;
-export type SetSessionNameHandler = (name: string) => void;
+export type SetSessionNameHandler = (name: string) => void | Promise<void>;
export type GetSessionNameHandler = () => string | undefined;
diff --git a/packages/coding-agent/src/core/prompts/rlm.ts b/packages/coding-agent/src/core/prompts/rlm.ts
index db4d259c5c..36cf38979b 100644
--- a/packages/coding-agent/src/core/prompts/rlm.ts
+++ b/packages/coding-agent/src/core/prompts/rlm.ts
@@ -6,6 +6,7 @@ export interface RlmPromptOptions {
installedSkills?: string[];
messagesPath: string;
allowRecursion?: boolean;
+ depth?: number;
activeTools?: string[];
}
@@ -35,6 +36,7 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {
const { cwd, skillsDir, messagesPath } = options;
const installedSkills = options.installedSkills ?? [];
const allowRecursion = options.allowRecursion ?? true;
+ const depth = options.depth ?? 0;
const activeTools = options.activeTools ?? [];
const hasIpython = options.activeTools === undefined ? true : activeTools.includes("ipython");
const canRunShellSkills = hasIpython || activeTools.includes("bash");
@@ -45,6 +47,7 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {
"",
`Working directory: ${cwd}`,
`Conversation log: ${messagesPath}`,
+ `Recursive agent depth: ${depth}`,
`Pre-installed Python packages: ${DEFAULT_RLM_EXTRA_IMPORT_LABELS.join(", ")}.`,
"Install additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).",
];
@@ -82,10 +85,11 @@ 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`, `.session_dir`, `.model`, and optional `.warning`. 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.",
+ "Choose a stable child name with `await rlm('sub-task', name='api-reviewer')`; names must be non-empty and unique among siblings (children of the same parent). If omitted, the host generates a readable unique name.",
"A child inherits your current model by default. When the user or an applicable skill requests a different model, search the bounded authenticated catalog with `matches = await rlm.find_models('requested model')`, choose from each match's `provider`, `id`, `name`, and `selector`, then pass the exact `provider/model` selector with `model=matches[0].selector`. Do not choose a different model on your own.",
"If an `RLMResult.warning` is set, the requested model could not be used and the child fell back to `.model`; follow the warning and tell the user which model actually ran.",
"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.",
+ "Use `await agent_message.roster()` when available to discover your parent, siblings, and children, including inactive family members, with their fixed depths and current statuses.",
"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.",
diff --git a/packages/coding-agent/src/core/rlm-runtime.ts b/packages/coding-agent/src/core/rlm-runtime.ts
index 08f39aed0d..3a10b730af 100644
--- a/packages/coding-agent/src/core/rlm-runtime.ts
+++ b/packages/coding-agent/src/core/rlm-runtime.ts
@@ -46,6 +46,7 @@ export interface RlmListSubagentsResult {
export interface RlmDeleteSubagentResult {
subagent: RlmSubagentRegistryEntry;
+ outcome?: "deleted" | "skipped_running";
}
export interface RlmModelMatch {
@@ -199,8 +200,8 @@ export function createRlmDeleteSubagentHostHandler(handler: RlmDeleteSubagentHan
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 };
+ const { subagent, outcome } = await handler(payload.target.trim());
+ return outcome === undefined ? { subagent } : { subagent, outcome };
};
}
diff --git a/packages/coding-agent/src/core/system-prompt.ts b/packages/coding-agent/src/core/system-prompt.ts
index 5f84502995..a2b263de6c 100644
--- a/packages/coding-agent/src/core/system-prompt.ts
+++ b/packages/coding-agent/src/core/system-prompt.ts
@@ -27,6 +27,8 @@ export interface BuildSystemPromptOptions {
skills?: Skill[];
/** Whether to include the model-facing rlm recursion guidance. */
allowRecursion?: boolean;
+ /** Fixed recursive-agent depth for this session. */
+ rlmDepth?: number;
/** Global harness state to inject as compact persistent context. */
harnessState?: HarnessState;
}
@@ -104,6 +106,7 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions): string {
installedSkills: getPythonSkillRuntimeInfo(visibleSkills).map((skill) => skill.importName),
activeTools: tools.filter((name) => name === "ipython" || name === "bash" || name === "edit"),
allowRecursion,
+ depth: options.rlmDepth,
});
// Appended AFTER the trained buildRlmPrompt prefix, and before the harness-state
diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
index a15c30bd39..47fee3ad6a 100644
--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
@@ -1923,16 +1923,12 @@ export class AgentsViewMode implements Component, Focusable {
await this.stopAgentForDeletion(row);
}
- // Subagent rows only stay visible while the daemon hosts their session, and
- // the daemon releases a child session as soon as its run settles, so any
- // visible subagent is part of an active run regardless of its idle/streaming
- // status. A kill that races completion reports "already finished".
private async handleKillSubagentSelected(row: AgentsViewRow): Promise<void> {
const identity = getSummaryIdentity(row.summary);
if (this.pendingKillSubagent?.identity === identity && this.isDeleteConfirmationVisible()) {
const pending = this.pendingKillSubagent;
this.clearDeleteConfirmation({ render: false });
- await this.killSubagent(pending);
+ await this.killSubagent(pending, row);
return;
}
const childId = row.summary.rlmChildId;
@@ -1945,23 +1941,54 @@ export class AgentsViewMode implements Component, Focusable {
this.showDeleteConfirmation();
}
- private async killSubagent(pending: PendingKillSubagent): Promise<void> {
- this.setStatusMessage("Stopping subagent...");
+ private async killSubagent(pending: PendingKillSubagent, currentRow: AgentsViewRow): Promise<void> {
+ const running = currentRow.section === "running";
+ const client = this.requireClient();
+ this.setStatusMessage(running ? "Stopping subagent..." : "Deleting subagent...");
try {
- const response = await this.requireClient().request({
- type: "cancel_rlm_child",
- activeSessionId: pending.rootActiveSessionId,
- childId: pending.childId,
- });
- const data = requireDaemonData(response);
- const cancelled = isRecord(data) && data.cancelled === true;
- this.setStatusMessage(cancelled ? "Subagent stopped" : "Subagent already finished", { render: false });
+ if (!running && client.supportsServerCapability("delete_rlm_subagent")) {
+ const data = requireDaemonData(
+ await client.request({
+ type: "delete_rlm_subagent",
+ activeSessionId: pending.rootActiveSessionId,
+ childId: pending.childId,
+ }),
+ );
+ const deleted = isRecord(data) && data.deleted === true;
+ const stillRunning = isRecord(data) && data.reason === "running";
+ this.setStatusMessage(
+ deleted
+ ? "Subagent deleted"
+ : stillRunning
+ ? "Subagent is running; stop it first"
+ : "Subagent already removed",
+ { render: false },
+ );
+ } else {
+ const data = requireDaemonData(
+ await client.request({
+ type: "cancel_rlm_child",
+ activeSessionId: pending.rootActiveSessionId,
+ childId: pending.childId,
+ }),
+ );
+ const cancelled = isRecord(data) && data.cancelled === true;
+ this.setStatusMessage(
+ running
+ ? cancelled
+ ? "Subagent stopped"
+ : "Subagent already finished"
+ : "The daemon cannot delete subagents; it was left unchanged",
+ { render: false, ...(running ? {} : { tone: "warning" as const }) },
+ );
+ }
await this.refreshSessions();
} catch (error) {
+ const command = running ? "cancel_rlm_child" : "delete_rlm_subagent";
this.setStatusMessage(
- isUnknownDaemonCommandError(error, "cancel_rlm_child")
- ? "Failed to stop subagent: the daemon is running an older build; restart the daemon and try again"
- : formatError("Failed to stop subagent", error),
+ isUnknownDaemonCommandError(error, command)
+ ? "Failed to update subagent: the daemon is running an older build; restart the daemon and try again"
+ : formatError("Failed to update subagent", error),
);
}
}
@@ -2537,7 +2564,7 @@ export class AgentsViewMode implements Component, Focusable {
const title = pendingDelete
? this.getPendingDeleteTitle()
: pendingKill
- ? `${keyText("app.agents.delete")} again to stop`
+ ? `${keyText("app.agents.delete")} again to ${row.section === "running" ? "stop" : "delete"}`
: styleRowTitle(row);
// Append the background summary as a dim suffix on the same line, e.g.
// "fix auth · Refactoring token validation". Hidden during delete/stop
@@ -2634,7 +2661,7 @@ export class AgentsViewMode implements Component, Focusable {
if (this.replyTarget) {
return truncateToWidth(theme.fg("muted", this.renderReplyComposerHints()), width);
}
- // Replying is reserved for top-level agents; subagents can be stopped.
+ // Replying is reserved for top-level agents; subagents can be stopped or deleted.
const selectedRow = this.rows[this.selectedIndex];
const selectedAgent = selectedRow?.kind === "agent";
const selectedSubagent = selectedRow?.kind === "subagent";
@@ -2650,7 +2677,9 @@ export class AgentsViewMode implements Component, Focusable {
selectedAgent
? `${keyText("app.agents.delete")} ${selectedRow?.section === "inactive" ? "delete" : "stop/deactivate"}`
: undefined,
- selectedSubagent ? `${keyText("app.agents.delete")} stop` : undefined,
+ selectedSubagent
+ ? `${keyText("app.agents.delete")} ${selectedRow.section === "running" ? "stop" : "delete"}`
+ : undefined,
this.selectedRowCanShowProgram() ? `${keyText("app.agents.program")} program` : undefined,
]
.filter((hint): hint is string => hint !== undefined)
diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-state.ts b/packages/coding-agent/src/modes/agents-view/agents-view-state.ts
index cfce771dcb..b0a7e7d36a 100644
--- a/packages/coding-agent/src/modes/agents-view/agents-view-state.ts
+++ b/packages/coding-agent/src/modes/agents-view/agents-view-state.ts
@@ -1,7 +1,7 @@
import { basename, resolve } from "node:path";
import { canonicalizePath } from "../../utils/paths.js";
import type { AgentConnectionHeartbeat, AgentConnectionSavedSessionInfo } from "../agent-connection/index.js";
-import type { SessionSummary } from "../daemon/daemon-session-list.js";
+import { classifySessionRosterStatus, type SessionSummary } from "../daemon/daemon-session-list.js";
export type AgentsViewSection = "running" | "idle" | "inactive";
@@ -88,14 +88,7 @@ export interface AgentsViewRow {
}
export function classifyAgentsViewSession(summary: SessionSummary): AgentsViewSection {
- if (summary.hasActiveHeartbeat || summary.activity === "working" || isAgentsViewSessionBusy(summary)) {
- return "running";
- }
- return "idle";
-}
-
-function isAgentsViewSessionBusy(summary: SessionSummary): boolean {
- return summary.isSessionActive || summary.hasRunningRlmChildren === true;
+ return classifySessionRosterStatus(summary);
}
export function classifyUnifiedSession(record: Pick<UnifiedSessionRecord, "daemon" | "heartbeat">): AgentsViewSection {
diff --git a/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts b/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts
index aabe580008..c841b5b79c 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts
@@ -1,5 +1,7 @@
import { type ChildProcess, spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
+import { readFile } from "node:fs/promises";
+import { dirname, join, resolve } from "node:path";
import { createCliSubprocessEnv, createCliSubprocessLaunchSpec } from "../../cli/subprocess-launch.js";
import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";
import { deleteSessionFile } from "../../core/session-file-actions.js";
@@ -15,6 +17,7 @@ interface SessionInfoWire extends Omit<SessionInfo, "created" | "modified"> {
type CatalogRequest =
| { type: "request"; id: string; command: "list"; cwd?: string; sessionDir?: string }
| { type: "request"; id: string; command: "resolve"; selector: string; cwd: string; sessionDir?: string }
+ | { type: "request"; id: string; command: "siblings"; sessionPath: string }
| { type: "request"; id: string; command: "rename"; sessionPath: string; name: string }
| { type: "request"; id: string; command: "delete"; sessionPath: string }
| { type: "request"; id: string; command: "archive"; sessionPath: string; sessionId: string }
@@ -56,6 +59,52 @@ function deserializeSessionInfo(session: SessionInfoWire): SessionInfo {
};
}
+interface SavedRlmSubagentRegistryEntry {
+ type?: unknown;
+ childId?: unknown;
+ sessionFile?: unknown;
+ status?: unknown;
+}
+
+export async function listSavedSessionSiblings(sessionPath: string): Promise<SessionInfo[]> {
+ const target = await readSessionInfo(sessionPath);
+ if (!target) throw new Error(`Session not found: ${sessionPath}`);
+ if (!target.parentSessionPath) return [target];
+ const parentPath = resolve(dirname(target.path), target.parentSessionPath);
+ const parent = await readSessionInfo(parentPath);
+ if (!parent) return [target];
+ const registryPath = join(dirname(dirname(parent.path)), "session-artifacts", parent.id, "rlm-subagents.jsonl");
+ let contents: string;
+ try {
+ contents = await readFile(registryPath, "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [target];
+ throw error;
+ }
+ const latest = new Map<string, SavedRlmSubagentRegistryEntry>();
+ for (const line of contents.split(/\r?\n/)) {
+ if (!line.trim()) continue;
+ try {
+ const entry = JSON.parse(line) as SavedRlmSubagentRegistryEntry;
+ if (entry.type === "rlm_subagent" && typeof entry.childId === "string") latest.set(entry.childId, entry);
+ } catch {
+ // Ignore malformed registry history just like the owning worker does.
+ }
+ }
+ const siblingPaths = new Set<string>([resolve(target.path)]);
+ for (const entry of latest.values()) {
+ if (entry.status !== "deleted" && typeof entry.sessionFile === "string")
+ siblingPaths.add(resolve(entry.sessionFile));
+ }
+ const siblings = await Promise.all([...siblingPaths].map((path) => readSessionInfo(path)));
+ return siblings.filter(
+ (info): info is SessionInfo =>
+ info !== null &&
+ info.parentSessionPath !== undefined &&
+ resolve(dirname(info.path), info.parentSessionPath) === parentPath,
+ );
+}
+
/** @internal Exported to pin catalog selector semantics without spawning a catalog process. */
export function resolveCatalogSessionMatch(
sessions: readonly SessionInfo[],
@@ -93,6 +142,7 @@ function isCatalogRequest(value: unknown): value is CatalogRequest {
typeof candidate.id === "string" &&
(candidate.command === "list" ||
candidate.command === "resolve" ||
+ candidate.command === "siblings" ||
candidate.command === "rename" ||
candidate.command === "delete" ||
candidate.command === "archive" ||
@@ -173,6 +223,14 @@ async function handleCatalogRequest(request: CatalogRequest): Promise<void> {
}
throw new Error(`No session found matching '${request.selector}'`);
}
+ case "siblings":
+ sendCatalogMessage({
+ type: "response",
+ id: request.id,
+ success: true,
+ data: { sessions: (await listSavedSessionSiblings(request.sessionPath)).map(serializeSessionInfo) },
+ });
+ return;
case "rename":
SessionManager.open(request.sessionPath).appendSessionInfo(request.name.trim());
sendCatalogMessage({ type: "response", id: request.id, success: true });
@@ -270,6 +328,16 @@ export class DaemonCatalogClient {
return data.sessions.map(deserializeSessionInfo);
}
+ async siblings(sessionPath: string): Promise<SessionInfo[]> {
+ const data = await this.request<{ sessions: SessionInfoWire[] }>({
+ type: "request",
+ id: randomUUID(),
+ command: "siblings",
+ sessionPath,
+ });
+ return data.sessions.map(deserializeSessionInfo);
+ }
+
async rename(sessionPath: string, name: string): Promise<void> {
await this.request({ type: "request", id: randomUUID(), command: "rename", sessionPath, name });
}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index f3c1c8187b..6dea574d8b 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -34,6 +34,8 @@ import {
} from "../../config.js";
import {
AGENT_MESSAGE_SOURCE,
+ type AgentFamilyCatalogEntry,
+ type AgentFamilyRosterResult,
type AgentSessionMessageAgentSummary,
type AgentSessionMessageController,
type AgentSessionMessageDeliveryStatus,
@@ -44,7 +46,9 @@ import {
type AgentSessionMessageReceipt,
type AgentSessionMessageSender,
assertAgentMessageQueueCapacity,
+ assertAgentSessionNameAvailable,
assertDirectAgentMessageTarget,
+ buildAgentFamilyRoster,
createAgentSessionMessage,
createAgentSessionMessageId,
createAgentSessionMessageReceipt,
@@ -168,6 +172,7 @@ import { getDaemonRuntimeIdentity } from "./daemon-runtime-identity.js";
import {
buildRlmChildSnapshots,
buildSessionList,
+ classifySessionRosterStatus,
inactiveLifecycleForSession,
isActiveSessionBusy,
type SessionSummary,
@@ -253,6 +258,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"execute_bash_and_wait",
"abort_bash",
"cancel_rlm_child",
+ "delete_rlm_subagent",
"wait_for_idle",
"wait_for_headless_completion",
"get_session_header",
@@ -1187,7 +1193,7 @@ export class AgentDaemon {
clientEnv,
};
if (name) {
- state.runtime.session.setSessionName(name);
+ await this.setStateSessionName(state, name);
}
this.sessions.set(state.activeSessionId, state);
this.bindingSessions.add(state.activeSessionId);
@@ -1317,7 +1323,7 @@ export class AgentDaemon {
throw new RuntimeOpenCancelledError();
}
if (command.name) {
- state.runtime.session.setSessionName(command.name);
+ await this.setStateSessionName(state, command.name);
}
this.adoptClientEnv(state, clientEnv);
this.rebindCronJobsToState(state);
@@ -1329,12 +1335,29 @@ export class AgentDaemon {
if (runtimeOpenGuard && !(await runtimeOpenGuard())) {
throw new RuntimeOpenCancelledError();
}
+ if (command.name) {
+ const normalizedName = command.name.trim();
+ if (!normalizedName) {
+ throw new Error("Session name cannot be empty");
+ }
+ await this.assertFamilySessionNameAvailable({
+ name: normalizedName,
+ depth: passiveSubagent.info.rlmDepth ?? passiveSubagent.entry.rlmDepth ?? 1,
+ parentSessionId: passiveSubagent.entry.parentSessionId,
+ parentSessionPath:
+ passiveSubagent.entry.parentSessionFile ??
+ passiveSubagent.chain.at(-2)?.sessionFile ??
+ passiveSubagent.rootParentState?.runtime.session.sessionFile ??
+ passiveSubagent.rootInfo?.path,
+ ignoreSessionId: passiveSubagent.info.id,
+ });
+ }
const state = await this.hydratePassiveRlmSubagent(passiveSubagent, clientEnv);
if (runtimeOpenGuard && !(await runtimeOpenGuard())) {
throw new RuntimeOpenCancelledError();
}
if (command.name) {
- state.runtime.session.setSessionName(command.name);
+ await this.setStateSessionName(state, command.name);
}
if (passiveSubagent.rootParentState) this.adoptClientEnv(passiveSubagent.rootParentState, clientEnv);
this.adoptClientEnv(state, clientEnv);
@@ -1378,7 +1401,7 @@ export class AgentDaemon {
throw new RuntimeOpenCancelledError();
}
if (command.name) {
- existing.runtime.session.setSessionName(command.name);
+ await this.setStateSessionName(existing, command.name);
}
this.adoptClientEnv(existing, clientEnv);
this.rebindCronJobsToState(existing);
@@ -1417,7 +1440,7 @@ export class AgentDaemon {
// the creator's identity at load, and swapping it would only make
// pi.exec disagree with those captures.
if (command.name) {
- existing.runtime.session.setSessionName(command.name);
+ await this.setStateSessionName(existing, command.name);
}
this.adoptClientEnv(existing, clientEnv);
this.rebindCronJobsToState(existing);
@@ -2784,6 +2807,9 @@ export class AgentDaemon {
};
return {
listAgents: () => this.createAgentMessageListResult(requireCurrentState()),
+ roster: () => this.createAgentFamilyRoster(requireCurrentState()),
+ assertSessionNameAvailable: (input) => this.assertFamilySessionNameAvailable(input),
+ setSessionName: (name) => this.setStateSessionName(requireCurrentState(), name),
sendAgentMessage: (input) =>
this.sendAgentSessionMessage({
targetSelector: input.target,
@@ -3571,6 +3597,7 @@ export class AgentDaemon {
if (!name) {
throw new Error("Session name cannot be empty");
}
+ await this.assertStateSessionNameAvailable(state, name);
state.runtime.session.setSessionName(name);
return success(command.id, "rename", summaryForActiveSession(state));
}
@@ -3585,8 +3612,18 @@ export class AgentDaemon {
throw new Error("Session name cannot be empty");
}
if (state) {
+ await this.assertStateSessionNameAvailable(state, name);
state.runtime.session.setSessionName(name);
} else {
+ const info = await readSessionInfo(command.sessionPath);
+ if (!info) throw new Error(`Session not found: ${command.sessionPath}`);
+ const depth = info.rlmDepth ?? 0;
+ await this.assertFamilySessionNameAvailable({
+ name,
+ depth,
+ ...(depth > 0 && info.parentSessionPath ? { parentSessionPath: info.parentSessionPath } : {}),
+ ignoreSessionId: info.id,
+ });
SessionManager.open(command.sessionPath).appendSessionInfo(name);
}
return success(command.id, "rename_saved_session");
@@ -3936,6 +3973,28 @@ export class AgentDaemon {
return success(command.id, "cancel_rlm_child", { cancelled });
}
+ case "delete_rlm_subagent": {
+ const state = this.getSessionState(command.activeSessionId);
+ const isResidentChildRunning = () => {
+ const childState = [...this.sessions.values()].find(
+ (candidate) =>
+ candidate.runtime.metadata.kind === "subagent" &&
+ candidate.runtime.metadata.rlmChildId === command.childId,
+ );
+ return (
+ childState !== undefined &&
+ (childState.runtime.session.isStreaming || childState.runtime.session.unfinishedActionCount > 0)
+ );
+ };
+ const result = isResidentChildRunning()
+ ? "running"
+ : await state.runtime.session.deleteInactiveRlmSubagent(command.childId, isResidentChildRunning);
+ return success(command.id, "delete_rlm_subagent", {
+ deleted: result === "deleted",
+ ...(result === "running" ? { reason: "running" } : {}),
+ });
+ }
+
case "wait_for_idle": {
const state = this.getSessionState(command.activeSessionId);
await state.runtime.session.waitForIdle();
@@ -4279,6 +4338,7 @@ export class AgentDaemon {
if (!name) {
throw new Error("Session name cannot be empty");
}
+ await this.assertStateSessionNameAvailable(state, name);
state.runtime.session.setSessionName(name);
return success(command.id, "set_session_name");
}
@@ -4712,14 +4772,28 @@ export class AgentDaemon {
private createAgentMessageAgentSummary(state: ActiveSessionState): AgentSessionMessageAgentSummary {
const metadata = state.runtime.metadata;
+ const session = state.runtime.session;
return {
...this.createAgentSessionMessageEndpoint(state),
cwd: state.runtime.cwd,
- isStreaming: state.runtime.session.isStreaming,
- unfinishedActionCount: state.runtime.session.unfinishedActionCount,
+ isStreaming: session.isStreaming,
+ unfinishedActionCount: session.unfinishedActionCount,
...(metadata.parentActiveSessionId ? { parentActiveSessionId: metadata.parentActiveSessionId } : {}),
+ ...(metadata.parentSessionId ? { parentSessionId: metadata.parentSessionId } : {}),
+ ...(metadata.parentSessionFile ? { parentSessionPath: metadata.parentSessionFile } : {}),
+ rlmDepth: session.rlmDepth,
+ status: classifySessionRosterStatus({
+ activeSessionId: state.activeSessionId,
+ runtimeKind: metadata.kind,
+ activity: session.isSessionActive ? "working" : "idle",
+ isSessionActive: session.isSessionActive,
+ hasRunningRlmChildren: session.hasRunningRlmChildren?.() ?? false,
+ hasActiveHeartbeat: this.cronStore.getHeartbeat(state.activeSessionId)?.status === "active",
+ isStreaming: session.isStreaming,
+ } as SessionSummary),
...(metadata.rlmChildId ? { rlmChildId: metadata.rlmChildId } : {}),
...(metadata.sessionDir ? { sessionDir: metadata.sessionDir } : {}),
+ ...(session.sessionFile ? { sessionPath: session.sessionFile } : {}),
};
}
@@ -4741,8 +4815,17 @@ export class AgentDaemon {
...(passive.chain.length === 1 && passive.rootParentState
? { parentActiveSessionId: passive.rootParentState.activeSessionId }
: {}),
+ parentSessionId: entry.parentSessionId,
+ parentSessionPath:
+ entry.parentSessionFile ??
+ passive.chain.at(-2)?.sessionFile ??
+ passive.rootParentState?.runtime.session.sessionFile ??
+ passive.rootInfo?.path,
+ rlmDepth: info.rlmDepth ?? entry.rlmDepth,
+ status: "inactive",
rlmChildId: entry.childId,
sessionDir: entry.sessionDir,
+ sessionPath: entry.sessionFile,
});
}
const localIds = new Set(localAgents.map((agent) => agent.activeSessionId));
@@ -4751,12 +4834,106 @@ export class AgentDaemon {
agents: [
...localAgents,
...[...this.remoteAgentPeers.values()].filter(
- (peer) => !localIds.has(peer.activeSessionId) && !this.closingSessions.has(peer.activeSessionId),
+ (peer) =>
+ peer.status !== "inactive" &&
+ !localIds.has(peer.activeSessionId) &&
+ !this.closingSessions.has(peer.activeSessionId),
),
],
};
}
+ private async createAgentFamilyCatalog(): Promise<AgentFamilyCatalogEntry[]> {
+ const current = [...this.sessions.values()].find((state) => !this.bindingSessions.has(state.activeSessionId));
+ const listed = current ? await this.createAgentMessageListResult(current) : { agents: [] };
+ const remotePeers = new Set(this.remoteAgentPeers.values());
+ const localAgents = current
+ ? [this.createAgentMessageAgentSummary(current), ...listed.agents.filter((agent) => !remotePeers.has(agent))]
+ : listed.agents.filter((agent) => !remotePeers.has(agent));
+ const activePaths = new Set(
+ localAgents.flatMap((agent) => (agent.sessionPath ? [resolve(agent.sessionPath)] : [])),
+ );
+ const savedRoots = (await SessionManager.listAll(undefined, this.options.defaultSessionConfig.sessionDir))
+ .filter(
+ (info) =>
+ (info.rlmDepth ?? (info.parentSessionPath ? -1 : 0)) === 0 && !activePaths.has(resolve(info.path)),
+ )
+ .map(
+ (info): AgentFamilyCatalogEntry => ({
+ id: info.id,
+ ...(info.name ? { name: info.name } : {}),
+ depth: info.rlmDepth ?? 0,
+ status: "inactive",
+ sessionPath: resolve(info.path),
+ }),
+ );
+ const byId = new Map<string, AgentFamilyCatalogEntry>(savedRoots.map((entry) => [entry.id, entry]));
+ const addAgent = (agent: AgentSessionMessageAgentSummary) => {
+ byId.set(agent.sessionId, {
+ id: agent.sessionId,
+ ...(agent.sessionName ? { name: agent.sessionName } : {}),
+ depth: agent.rlmDepth ?? 0,
+ status: agent.status ?? "idle",
+ ...(agent.parentSessionId ? { parentSessionId: agent.parentSessionId } : {}),
+ ...(agent.parentSessionPath ? { parentSessionPath: resolve(agent.parentSessionPath) } : {}),
+ ...(agent.sessionPath ? { sessionPath: resolve(agent.sessionPath) } : {}),
+ });
+ };
+ for (const peer of this.remoteAgentPeers.values()) addAgent(peer);
+ for (const agent of localAgents) addAgent(agent);
+ for (const state of this.sessions.values()) {
+ const entry = byId.get(state.runtime.session.sessionId);
+ if (entry && state.runtime.session.sessionFile) entry.sessionPath = resolve(state.runtime.session.sessionFile);
+ }
+ for (const passive of await this.listPassiveRlmSubagents()) {
+ const entry = byId.get(passive.info.id);
+ if (entry) entry.sessionPath = resolve(passive.entry.sessionFile);
+ }
+ return [...byId.values()];
+ }
+
+ private async createAgentFamilyRoster(currentState: ActiveSessionState): Promise<AgentFamilyRosterResult> {
+ const catalog = await this.createAgentFamilyCatalog();
+ const current = catalog.find((entry) => entry.id === currentState.runtime.session.sessionId);
+ if (!current) throw new Error("Current agent is missing from the family catalog");
+ return buildAgentFamilyRoster(current, catalog);
+ }
+
+ private async assertFamilySessionNameAvailable(input: {
+ name: string;
+ depth: number;
+ parentSessionId?: string;
+ parentSessionPath?: string;
+ ignoreSessionId?: string;
+ }): Promise<void> {
+ assertAgentSessionNameAvailable(await this.createAgentFamilyCatalog(), {
+ ...input,
+ ...(input.parentSessionPath ? { parentSessionPath: resolve(input.parentSessionPath) } : {}),
+ });
+ }
+
+ private async assertStateSessionNameAvailable(state: ActiveSessionState, name: string): Promise<void> {
+ const session = state.runtime.session;
+ const metadata = state.runtime.metadata;
+ const depth = session.rlmDepth ?? 0;
+ await this.assertFamilySessionNameAvailable({
+ name,
+ depth,
+ ...(depth > 0 && metadata.parentSessionId ? { parentSessionId: metadata.parentSessionId } : {}),
+ ...(depth > 0 && metadata.parentSessionFile ? { parentSessionPath: metadata.parentSessionFile } : {}),
+ ignoreSessionId: session.sessionId,
+ });
+ }
+
+ private async setStateSessionName(state: ActiveSessionState, name: string): Promise<void> {
+ const normalizedName = name.trim();
+ if (!normalizedName) {
+ throw new Error("Session name cannot be empty");
+ }
+ await this.assertStateSessionNameAvailable(state, normalizedName);
+ state.runtime.session.setSessionName(normalizedName);
+ }
+
// 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[] {
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index 27a4f68c1e..1786b1f32d 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -56,7 +56,7 @@ export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 7;
// Revision 11 adds immediate get/set commands for active-session RLM max depth.
// Revision 12 publishes idle-residency metadata on session summary rows.
export const DAEMON_SCHEMA_REVISION = 12;
-export const DAEMON_SCHEMA_ID = "protocol-7-schema-12-5bd6b0b12204";
+export const DAEMON_SCHEMA_ID = "protocol-7-schema-12-670d88ac98dd";
export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;
export type DaemonProtocolVersion = number;
@@ -81,6 +81,7 @@ export interface DaemonPromptAdmissionCancellationResult {
}
export type DaemonServerCapability =
| DaemonClientCapability
+ | "delete_rlm_subagent"
| "heartbeat_catalog"
| "heartbeat_management"
| "model_catalog"
@@ -123,6 +124,7 @@ export const DAEMON_SUPPORTED_CLIENT_CAPABILITIES: readonly DaemonClientCapabili
export const DAEMON_DEFAULT_SERVER_CAPABILITIES: readonly DaemonServerCapability[] = [
...DAEMON_SUPPORTED_CLIENT_CAPABILITIES,
+ "delete_rlm_subagent",
"heartbeat_catalog",
"heartbeat_management",
"model_catalog",
@@ -486,6 +488,7 @@ export type DaemonCommand =
}
| { id?: string; type: "abort_bash"; activeSessionId: string }
| { id?: string; type: "cancel_rlm_child"; activeSessionId: string; childId: string }
+ | { id?: string; type: "delete_rlm_subagent"; activeSessionId: string; childId: string }
| { id?: string; type: "wait_for_idle"; activeSessionId: string }
| { id?: string; type: "wait_for_headless_completion"; activeSessionId: string }
| { id?: string; type: "get_session_header"; activeSessionId: string }
@@ -620,6 +623,10 @@ const CLIENT_OWNED_DAEMON_COMMAND = {
minProtocol: 7,
capability: "client_owned_sessions",
} as const;
+const DELETE_RLM_SUBAGENT_COMMAND = {
+ minProtocol: 7,
+ capability: "delete_rlm_subagent",
+} as const;
const FLAT_SESSION_TREE_COMMAND = { minProtocol: 7 } as const;
export const DAEMON_COMMAND_COMPATIBILITY = {
@@ -654,6 +661,7 @@ export const DAEMON_COMMAND_COMPATIBILITY = {
execute_bash: LEGACY_DAEMON_COMMAND,
abort_bash: LEGACY_DAEMON_COMMAND,
cancel_rlm_child: LEGACY_DAEMON_COMMAND,
+ delete_rlm_subagent: DELETE_RLM_SUBAGENT_COMMAND,
wait_for_idle: LEGACY_DAEMON_COMMAND,
wait_for_headless_completion: CURRENT_DAEMON_COMMAND,
get_session_header: CURRENT_DAEMON_COMMAND,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
index 533684db30..2b69aea9f9 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
@@ -19,6 +19,7 @@ export type SessionLifecycle = "draft" | "live" | "archived";
// Heuristic activity of a live session. Classification-in-flight counts as
// "working" so the view never sees an unlabeled idle session.
export type SessionActivity = "working" | "idle";
+export type SessionRosterStatus = "running" | "idle" | "inactive";
// Upper bound on the spawn-code source carried in a session summary. Generous
// enough for real spawn cells while keeping the daemon wire payload bounded.
@@ -99,6 +100,12 @@ export function resolveAttachModelFallbackMessage(
return summary.model ? undefined : startupModelFallbackMessage;
}
+export function classifySessionRosterStatus(summary: SessionSummary): SessionRosterStatus {
+ if (!summary.activeSessionId) return "inactive";
+ if (summary.hasActiveHeartbeat || summary.activity === "working" || isSessionSummaryBusy(summary)) return "running";
+ return "idle";
+}
+
export function isSessionSummaryBusy(summary: SessionSummary): boolean {
return summary.isSessionActive || summary.hasRunningRlmChildren === true;
}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index 6f284f5158..2b861e72fa 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -13,7 +13,12 @@ import {
getDaemonUpdateRestartManifestPath,
VERSION,
} from "../../config.js";
-import type { AgentSessionMessageAgentSummary } from "../../core/agent-messages.js";
+import {
+ type AgentFamilyCatalogEntry,
+ type AgentSessionMessageAgentSummary,
+ assertAgentSessionNameAvailable,
+ formatAgentSessionNameUnavailable,
+} from "../../core/agent-messages.js";
import { type AgentSessionRuntimeConfig, mergeAgentSessionRuntimeConfig } from "../../core/agent-session-config.js";
import {
type AgentCronJob,
@@ -72,7 +77,12 @@ import {
} from "./daemon-protocol.js";
import { getDaemonRuntimeIdentity } from "./daemon-runtime-identity.js";
import { matchesSessionIdSuffix } from "./daemon-session-id.js";
-import { isSessionSummaryBusy, type SessionSummary, summaryForInactiveSession } from "./daemon-session-list.js";
+import {
+ classifySessionRosterStatus,
+ isSessionSummaryBusy,
+ type SessionSummary,
+ summaryForInactiveSession,
+} from "./daemon-session-list.js";
import {
acquireDaemonSocketPathLease,
cleanupDaemonSocketPath,
@@ -164,6 +174,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"execute_bash_and_wait",
"abort_bash",
"cancel_rlm_child",
+ "delete_rlm_subagent",
"wait_for_idle",
"wait_for_headless_completion",
"get_session_header",
@@ -592,6 +603,7 @@ export class DaemonSupervisor {
private readonly streamReconstructor = new CompactAssistantStreamReconstructor();
private readonly compactCatchupInProgress = new Set<string>();
private agentPeerSyncQueue: Promise<void> = Promise.resolve();
+ private readonly pendingRootSessionNames = new Set<string>();
private readonly catalog: DaemonCatalogClient;
private readonly settingsManager: SettingsManager;
private idleEvictionTimer?: ReturnType<typeof setTimeout>;
@@ -1736,6 +1748,7 @@ export class DaemonSupervisor {
return this.forwardToWorker(match.worker, command);
}
case "rename_saved_session":
+ await this.assertSupervisorSavedSessionNameAvailable(command.sessionPath, command.name.trim());
if (!command.activeSessionId) {
await this.catalog.rename(command.sessionPath, command.name);
return success(command.id, command.type);
@@ -1845,6 +1858,9 @@ export class DaemonSupervisor {
command.type === "kill" &&
(match.summary.activeSessionId ?? match.summary.id) === match.worker.descriptor.rootActiveSessionId;
if (!isRootKill) {
+ if (command.type === "rename" || command.type === "set_session_name") {
+ await this.assertSupervisorSessionNameAvailable(match.summary, command.name.trim());
+ }
const response = await this.forwardToWorker(match.worker, resolvedCommand);
if (admission && response.success) admission.status = "owned";
return response;
@@ -1936,6 +1952,13 @@ export class DaemonSupervisor {
private async createOrReuseWorker(clientId: string, command: DaemonCreateCommand): Promise<ResidentWorker> {
let createCommand = command;
+ if (command.name !== undefined) {
+ const normalizedName = command.name.trim();
+ if (!normalizedName) {
+ throw new Error("Session name cannot be empty");
+ }
+ createCommand = { ...command, name: normalizedName };
+ }
const ownerClientId = command.lifecycle === "client_owned" ? clientId : undefined;
if (command.sessionPath) {
const activeMatches = this.matchWorkers(command.sessionPath);
@@ -1949,7 +1972,7 @@ export class DaemonSupervisor {
const sessionPath = looksLikeSessionPath(command.sessionPath)
? resolve(command.sessionPath)
: await this.catalog.resolve(command.sessionPath, config.cwd ?? process.cwd(), config.sessionDir);
- createCommand = { ...command, sessionPath };
+ createCommand = { ...createCommand, sessionPath };
const existing = this.findWorkerBySessionFile(sessionPath);
if (existing) {
return this.reuseWorkerForCreate(existing.worker, ownerClientId, sessionPath);
@@ -1964,11 +1987,32 @@ export class DaemonSupervisor {
if (pending) {
return pending;
}
+ let reservedRootName: string | undefined;
+ if (createCommand.name) {
+ const savedSiblings = createCommand.sessionPath ? await this.catalog.siblings(createCommand.sessionPath) : [];
+ const target = savedSiblings.find(
+ (session) => canonicalSessionPath(session.path) === canonicalSessionPath(createCommand.sessionPath!),
+ );
+ const targetSummary = target ? summaryForInactiveSession(target) : { sessionId: "new-root", rlmDepth: 0 };
+ if (target?.parentSessionPath && (target.rlmDepth ?? 0) > 0) {
+ this.assertSavedSiblingNameAvailable(savedSiblings, target, createCommand.name);
+ } else {
+ await this.assertSupervisorSessionNameAvailable(targetSummary, createCommand.name);
+ }
+ if ((targetSummary.rlmDepth ?? 0) === 0) {
+ if (this.pendingRootSessionNames.has(createCommand.name)) {
+ throw new Error(formatAgentSessionNameUnavailable(createCommand.name, 0));
+ }
+ reservedRootName = createCommand.name;
+ this.pendingRootSessionNames.add(reservedRootName);
+ }
+ }
const opening = this.launchWorker(createCommand, undefined, ownerClientId);
this.openingWorkers.set(key, opening);
try {
return await opening;
} finally {
+ if (reservedRootName) this.pendingRootSessionNames.delete(reservedRootName);
if (this.openingWorkers.get(key) === opening) {
this.openingWorkers.delete(key);
}
@@ -2181,7 +2225,7 @@ export class DaemonSupervisor {
worker.descriptor.consecutiveFailures = 0;
worker.descriptor.lastError = undefined;
this.persistWorker(worker);
- await this.syncAgentPeers();
+ await this.syncAgentPeers().catch((error) => this.log(`Could not synchronize agent peers: ${String(error)}`));
this.broadcastHeartbeatsChanged();
return worker;
} catch (error) {
@@ -2860,6 +2904,79 @@ export class DaemonSupervisor {
}
}
+ private async familyCatalogEntries(): Promise<AgentFamilyCatalogEntry[]> {
+ const active = [...this.workers.values()].flatMap((worker) => [...worker.summaries.values()]);
+ const activePaths = new Set(
+ active.flatMap((summary) => (summary.sessionFile ? [canonicalSessionPath(summary.sessionFile)] : [])),
+ );
+ const savedRoots = (await this.catalog.list()).filter(
+ (info) =>
+ (info.rlmDepth ?? (info.parentSessionPath ? -1 : 0)) === 0 &&
+ !activePaths.has(canonicalSessionPath(info.path)),
+ );
+ return [...active, ...savedRoots.map((info) => summaryForInactiveSession(info))].map((summary) => ({
+ id: summary.sessionId,
+ ...(summary.sessionName ? { name: summary.sessionName } : {}),
+ depth: summary.rlmDepth ?? 0,
+ status: classifySessionRosterStatus(summary),
+ ...(summary.parentSessionId ? { parentSessionId: summary.parentSessionId } : {}),
+ ...(summary.parentSessionPath ? { parentSessionPath: canonicalSessionPath(summary.parentSessionPath) } : {}),
+ ...(summary.sessionFile ? { sessionPath: canonicalSessionPath(summary.sessionFile) } : {}),
+ }));
+ }
+
+ private async assertSupervisorSessionNameAvailable(
+ target: Pick<SessionSummary, "sessionId" | "rlmDepth" | "parentSessionId" | "parentSessionPath">,
+ name: string,
+ ): Promise<void> {
+ assertAgentSessionNameAvailable(await this.familyCatalogEntries(), {
+ name,
+ depth: target.rlmDepth ?? 0,
+ parentSessionId: target.parentSessionId,
+ parentSessionPath: target.parentSessionPath ? canonicalSessionPath(target.parentSessionPath) : undefined,
+ ignoreSessionId: target.sessionId,
+ });
+ }
+
+ private async assertSupervisorSavedSessionNameAvailable(sessionPath: string, name: string): Promise<void> {
+ const targetPath = canonicalSessionPath(sessionPath);
+ const active = [...this.workers.values()]
+ .flatMap((worker) => [...worker.summaries.values()])
+ .find((summary) => summary.sessionFile && canonicalSessionPath(summary.sessionFile) === targetPath);
+ if (active) return this.assertSupervisorSessionNameAvailable(active, name);
+ const siblings = await this.catalog.siblings(sessionPath);
+ const saved = siblings.find((info) => canonicalSessionPath(info.path) === targetPath);
+ if (!saved) throw new Error(`Session not found: ${sessionPath}`);
+ if (saved.parentSessionPath && (saved.rlmDepth ?? 0) > 0) {
+ this.assertSavedSiblingNameAvailable(siblings, saved, name);
+ } else {
+ await this.assertSupervisorSessionNameAvailable(summaryForInactiveSession(saved), name);
+ }
+ }
+
+ private assertSavedSiblingNameAvailable(siblings: SessionInfo[], target: SessionInfo, name: string): void {
+ assertAgentSessionNameAvailable(
+ siblings.map((info) => {
+ const summary = summaryForInactiveSession(info);
+ return {
+ id: summary.sessionId,
+ ...(summary.sessionName ? { name: summary.sessionName } : {}),
+ depth: summary.rlmDepth ?? 0,
+ status: classifySessionRosterStatus(summary),
+ ...(summary.parentSessionPath
+ ? { parentSessionPath: canonicalSessionPath(summary.parentSessionPath) }
+ : {}),
+ };
+ }),
+ {
+ name,
+ depth: target.rlmDepth ?? 0,
+ parentSessionPath: target.parentSessionPath ? canonicalSessionPath(target.parentSessionPath) : undefined,
+ ignoreSessionId: target.id,
+ },
+ );
+ }
+
private syncAgentPeers(): Promise<void> {
const sync = this.agentPeerSyncQueue
.catch(() => undefined)
@@ -2872,11 +2989,13 @@ export class DaemonSupervisor {
);
await Promise.all(
readyWorkers.map(async (worker) => {
- const peers = readyWorkers
- .filter((candidate) => candidate !== worker)
- .flatMap((candidate) =>
- [...candidate.summaries.values()].map((summary) => this.agentPeerSummary(summary)),
- );
+ const peers = [
+ ...readyWorkers
+ .filter((candidate) => candidate !== worker)
+ .flatMap((candidate) =>
+ [...candidate.summaries.values()].map((summary) => this.agentPeerSummary(summary)),
+ ),
+ ];
const response = await worker.client.requestWorker({ type: "worker_sync_agent_peers", peers }, 5000);
if (!response.success) {
throw new Error(response.error);
@@ -2906,6 +3025,11 @@ export class DaemonSupervisor {
? 1 + summary.sessionActions.queuedCount
: summary.sessionActions.queuedCount),
...(summary.parentActiveSessionId ? { parentActiveSessionId: summary.parentActiveSessionId } : {}),
+ ...(summary.parentSessionId ? { parentSessionId: summary.parentSessionId } : {}),
+ ...(summary.parentSessionPath ? { parentSessionPath: summary.parentSessionPath } : {}),
+ ...(summary.sessionFile ? { sessionPath: summary.sessionFile } : {}),
+ ...(summary.rlmDepth !== undefined ? { rlmDepth: summary.rlmDepth } : {}),
+ status: classifySessionRosterStatus(summary),
...(summary.rlmChildId ? { rlmChildId: summary.rlmChildId } : {}),
};
}
diff --git a/packages/coding-agent/test/agent-session-bus.test.ts b/packages/coding-agent/test/agent-session-bus.test.ts
index e2b9cf5ff4..a54fc6af5b 100644
--- a/packages/coding-agent/test/agent-session-bus.test.ts
+++ b/packages/coding-agent/test/agent-session-bus.test.ts
@@ -3,7 +3,9 @@ import {
AGENT_MESSAGE_SOURCE,
AgentSessionMessageRateLimiter,
assertAgentMessageQueueCapacity,
+ assertAgentSessionNameAvailable,
assertDirectAgentMessageTarget,
+ buildAgentFamilyRoster,
createAgentSessionMessagePrompt,
createAgentSessionMessageReceipt,
normalizeAgentSessionMessage,
@@ -168,6 +170,103 @@ describe("agent session bus", () => {
expect(() => assertAgentMessageQueueCapacity(19, 20)).not.toThrow();
});
+ it("enforces names per sibling set across active and inactive catalog rows", () => {
+ const catalog = [
+ { id: "root-a", name: "alpha", depth: 0, status: "running" as const, sessionPath: "/root-a" },
+ { id: "root-b", name: "beta", depth: 0, status: "inactive" as const, sessionPath: "/root-b" },
+ { id: "child-a", name: "reviewer", depth: 1, status: "idle" as const, parentSessionPath: "/root-a" },
+ { id: "child-b", name: "reviewer", depth: 1, status: "inactive" as const, parentSessionPath: "/root-b" },
+ ];
+
+ expect(() => assertAgentSessionNameAvailable(catalog, { name: "beta", depth: 0 })).toThrow(
+ "an agent of that name already exists at depth 0 under this parent",
+ );
+ expect(() =>
+ assertAgentSessionNameAvailable(
+ [...catalog, { id: "fork", name: "forked", depth: 0, status: "idle", parentSessionPath: "/root-a" }],
+ { name: "beta", depth: 0, parentSessionPath: "/root-a", ignoreSessionId: "fork" },
+ ),
+ ).toThrow("an agent of that name already exists at depth 0 under this parent");
+ expect(() =>
+ assertAgentSessionNameAvailable(catalog, { name: "reviewer", depth: 1, parentSessionPath: "/root-a" }),
+ ).toThrow("an agent of that name already exists at depth 1 under this parent");
+ expect(() =>
+ assertAgentSessionNameAvailable(catalog, { name: "reviewer", depth: 2, parentSessionPath: "/child-a" }),
+ ).not.toThrow();
+ expect(() =>
+ assertAgentSessionNameAvailable(catalog, {
+ name: "reviewer",
+ depth: 1,
+ parentSessionPath: "/root-a",
+ ignoreSessionId: "child-a",
+ }),
+ ).not.toThrow();
+ });
+
+ it("resolves sibling parents canonically without grouping parentless non-roots", () => {
+ const catalog = [
+ { id: "root", name: "orchestrator", depth: 0, status: "running" as const, sessionPath: "/root" },
+ { id: "id-child", name: "reviewer", depth: 1, status: "idle" as const, parentSessionId: "root" },
+ {
+ id: "path-child",
+ name: "builder",
+ depth: 1,
+ status: "inactive" as const,
+ parentSessionPath: "/root",
+ },
+ { id: "orphan", name: "reviewer", depth: 1, status: "inactive" as const },
+ ];
+
+ expect(() =>
+ assertAgentSessionNameAvailable(catalog, { name: "reviewer", depth: 1, parentSessionPath: "/root" }),
+ ).toThrow("an agent of that name already exists at depth 1 under this parent");
+ expect(() =>
+ assertAgentSessionNameAvailable(catalog, { name: "builder", depth: 1, parentSessionId: "root" }),
+ ).toThrow("an agent of that name already exists at depth 1 under this parent");
+ expect(() => assertAgentSessionNameAvailable(catalog, { name: "reviewer", depth: 1 })).not.toThrow();
+ expect(() =>
+ assertAgentSessionNameAvailable(catalog, {
+ name: "reviewer",
+ depth: 1,
+ parentSessionPath: "/unknown-root",
+ }),
+ ).not.toThrow();
+ expect(buildAgentFamilyRoster(catalog[1]!, catalog).entries).toEqual([
+ { relationship: "parent", name: "orchestrator", id: "root", depth: 0, status: "running" },
+ { relationship: "sibling", name: "builder", id: "path-child", depth: 1, status: "inactive" },
+ ]);
+ });
+
+ it("builds a sorted nuclear-family roster with inactive members", () => {
+ const catalog = [
+ { id: "root", name: "orchestrator", depth: 0, status: "running" as const, sessionPath: "/root" },
+ {
+ id: "current",
+ name: "builder",
+ depth: 1,
+ status: "idle" as const,
+ parentSessionPath: "/root",
+ sessionPath: "/builder",
+ },
+ { id: "sibling-z", name: "zeta", depth: 1, status: "running" as const, parentSessionPath: "/root" },
+ { id: "sibling-a", name: "alpha", depth: 1, status: "inactive" as const, parentSessionPath: "/root" },
+ { id: "child-z", name: "tester", depth: 2, status: "inactive" as const, parentSessionPath: "/builder" },
+ { id: "child-a", name: "reviewer", depth: 2, status: "idle" as const, parentSessionPath: "/builder" },
+ { id: "cousin", name: "ignored", depth: 2, status: "idle" as const, parentSessionPath: "/other" },
+ ];
+
+ expect(buildAgentFamilyRoster(catalog[1]!, catalog)).toEqual({
+ current: { name: "builder", id: "current", depth: 1 },
+ entries: [
+ { relationship: "parent", name: "orchestrator", id: "root", depth: 0, status: "running" },
+ { relationship: "sibling", name: "alpha", id: "sibling-a", depth: 1, status: "inactive" },
+ { relationship: "sibling", name: "zeta", id: "sibling-z", depth: 1, status: "running" },
+ { relationship: "child", name: "reviewer", id: "child-a", depth: 2, status: "idle" },
+ { relationship: "child", name: "tester", id: "child-z", depth: 2, status: "inactive" },
+ ],
+ });
+ });
+
it("rate limits senders with a token bucket", () => {
let now = 0;
const limiter = new AgentSessionMessageRateLimiter({
diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.ts
index 53bfa57e29..03657382a1 100644
--- a/packages/coding-agent/test/agent-session-recursion.test.ts
+++ b/packages/coding-agent/test/agent-session-recursion.test.ts
@@ -21,6 +21,7 @@ import { convertToLlm } from "../src/core/messages.js";
import { ModelRegistry } from "../src/core/model-registry.js";
import {
createDefaultRlmSubagentSessionName,
+ createRlmDeleteSubagentHostHandler,
createRlmRunHostHandler,
type SubagentRuntimeHost,
} from "../src/core/rlm-runtime.js";
@@ -28,6 +29,7 @@ import { SessionManager } from "../src/core/session-manager.js";
import { SettingsManager, type SettingsStorage } from "../src/core/settings-manager.js";
import type { Skill } from "../src/core/skills.js";
import { createSyntheticSourceInfo } from "../src/core/source-info.js";
+import { type ActiveSessionState, resolveActiveSessionState } from "../src/modes/daemon/active-session-state.js";
import { createTestResourceLoader } from "./utilities.js";
const model = getModel("anthropic", "claude-sonnet-4-5")!;
@@ -269,6 +271,26 @@ describe("AgentSession rlm recursion", () => {
return session;
}
+ it("propagates skipped-running deletion outcomes through the host handler", async () => {
+ const subagent = {
+ rlm_child_id: "running-child",
+ active_session_id: "running-session",
+ session_id: "running-session",
+ session_name: "running-worker",
+ session_dir: join(tempDir, "running-child"),
+ status: "running" as const,
+ };
+ const deleteHandler = createRlmDeleteSubagentHostHandler(async () => ({
+ subagent,
+ outcome: "skipped_running",
+ }));
+
+ await expect(deleteHandler({ target: subagent.rlm_child_id })).resolves.toEqual({
+ subagent,
+ outcome: "skipped_running",
+ });
+ });
+
it("persists RLM_DEPTH for a fresh session and reports the seeded depth", () => {
vi.stubEnv("RLM_DEPTH", "1");
try {
@@ -370,21 +392,96 @@ describe("AgentSession rlm recursion", () => {
expect(childSession.sessionName).toBe("api-reviewer");
expect((await 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',
+ 'Agent name "api-reviewer" is unavailable: an agent of that name already exists at depth 1 under this parent',
);
- 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("falls back to listed family metadata when a controller lacks name validation", async () => {
+ const listAgents = vi.fn(() => ({
+ current: { activeSessionId: "parent-active", sessionId: "unrelated-current" },
+ agents: [
+ {
+ activeSessionId: "passive-active",
+ sessionId: "passive-session",
+ sessionName: "passive-worker",
+ runtimeKind: "subagent" as const,
+ cwd: tempDir,
+ isStreaming: false,
+ unfinishedActionCount: 0,
+ parentSessionId: "parent-session",
+ parentSessionPath: parentPath,
+ rlmDepth: 1,
+ status: "idle" as const,
+ },
+ {
+ activeSessionId: "other-active",
+ sessionId: "other-session",
+ sessionName: "other-family-worker",
+ runtimeKind: "subagent" as const,
+ cwd: tempDir,
+ isStreaming: false,
+ unfinishedActionCount: 0,
+ parentSessionId: "other-parent",
+ rlmDepth: 1,
+ },
+ ],
+ }));
+ const manager = SessionManager.create(tempDir, join(tempDir, "sessions"));
+ manager.newSession({ id: "parent-session" });
+ const parentPath = manager.getSessionFile();
+ if (!parentPath) throw new Error("Missing parent session path");
+ const root = createSession({
+ sessionManager: manager,
+ agentMessageController: {
+ listAgents,
+ sendAgentMessage: async () => {
+ throw new Error("unexpected send");
+ },
+ },
+ });
+
+ await expect(root.runRlmChild("duplicate passive", { name: "passive-worker" })).rejects.toThrow(
+ 'Agent name "passive-worker" is unavailable',
+ );
+ await expect(root.runRlmChild("different family", { name: "other-family-worker" })).resolves.toMatchObject({
+ answer: "child answer: different family",
+ });
+ expect(listAgents).toHaveBeenCalled();
+ });
+
+ it("throws loud ambiguity when a child name equals a sibling session id for send and delete", async () => {
+ const first = createSession({ rlmSessionDir: join(tempDir, "first") });
+ const second = createSession({ rlmSessionDir: join(tempDir, "second") });
+ second.setSessionName(first.sessionId);
+ const root = createSession();
+ expect(root.retainFinishedRlmChildSession("first-child", first)).toBe(true);
+ expect(root.retainFinishedRlmChildSession("second-child", second)).toBe(true);
+ const states = new Map<string, ActiveSessionState>([
+ [
+ "first-active",
+ {
+ activeSessionId: "first-active",
+ runtime: { session: first },
+ } as ActiveSessionState,
+ ],
+ [
+ "second-active",
+ {
+ activeSessionId: "second-active",
+ runtime: { session: second },
+ } as ActiveSessionState,
+ ],
+ ]);
+
+ expect(() => resolveActiveSessionState(states, first.sessionId)).toThrow("Ambiguous active session");
+ await expect(root.deleteRlmSubagent(first.sessionId)).rejects.toThrow("is ambiguous");
+ });
+
it("reserves a running child's current name after it is renamed", async () => {
let releaseChild: () => void = () => {};
const release = new Promise<void>((resolve) => {
@@ -418,10 +515,7 @@ describe("AgentSession rlm recursion", () => {
expect((await 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`,
+ 'Agent name "renamed-running-worker" is unavailable: an agent of that name already exists at depth 1 under this parent',
);
releaseChild();
await runPromise;
@@ -490,10 +584,7 @@ describe("AgentSession rlm recursion", () => {
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`,
+ 'Agent name "retained-retry-worker" is unavailable: an agent of that name already exists at depth 1 under this parent',
);
await expect(root.deleteRlmSubagent("retained-retry-worker")).resolves.toMatchObject({
@@ -1397,6 +1488,90 @@ describe("AgentSession rlm recursion", () => {
expect(root.cancelRlmChildRun(childId)).toBe(false);
});
+ it("reports a shared running outcome to concurrent inactive-delete callers", async () => {
+ let runningChecks = 0;
+ const isExternallyRunning = () => ++runningChecks >= 5;
+ const deleteRuntime = vi.fn(async () => {});
+ const root = createSession({
+ agentMessageController: {
+ listAgents: () => ({
+ current: { activeSessionId: "parent-active", sessionId: "parent-session" },
+ agents: [
+ {
+ activeSessionId: "child-active",
+ sessionId: "child-session",
+ sessionName: "worker",
+ runtimeKind: "subagent",
+ cwd: tempDir,
+ isStreaming: false,
+ unfinishedActionCount: 0,
+ parentActiveSessionId: "parent-active",
+ rlmChildId: "child",
+ sessionDir: join(tempDir, "child"),
+ },
+ ],
+ }),
+ sendAgentMessage: async () => {
+ throw new Error("unexpected send");
+ },
+ },
+ subagentRuntimeHost: {
+ createRlmSubagentRuntime: async () => {
+ throw new Error("unexpected hydration");
+ },
+ deleteRlmSubagentRuntime: deleteRuntime,
+ },
+ });
+
+ const first = root.deleteInactiveRlmSubagent("child", isExternallyRunning);
+ const second = root.deleteInactiveRlmSubagent("child", isExternallyRunning);
+
+ await expect(Promise.all([first, second])).resolves.toEqual(["running", "running"]);
+ expect(deleteRuntime).not.toHaveBeenCalled();
+ });
+
+ it("deletes only inactive RLM children through the explicit inactive path", async () => {
+ let releaseChild: () => void = () => {};
+ const release = new Promise<void>((resolve) => {
+ releaseChild = resolve;
+ });
+ let childStarted = false;
+ const retainedChild = createSession({
+ rlmSessionDir: join(tempDir, "retained-child"),
+ streamFn: () => {
+ const stream = createAssistantMessageEventStream();
+ childStarted = true;
+ void release.then(() => {
+ stream.push({ type: "done", reason: "stop", message: assistantMessage("done") });
+ });
+ return stream;
+ },
+ });
+ const deleteRuntime = vi.fn(async () => {});
+ const root = createSession({
+ subagentRuntimeHost: {
+ createRlmSubagentRuntime: async () => ({ session: retainedChild }),
+ deleteRlmSubagentRuntime: deleteRuntime,
+ releaseRlmSubagentRuntime: async (runtime, options) => {
+ options.parentSession.retainFinishedRlmChildSession(options.id, runtime.session);
+ },
+ },
+ });
+
+ const runPromise = root.runRlmChild("slow child", { name: "retained-worker" });
+ await waitFor(() => childStarted);
+ const childId = [...(root as unknown as InspectableRlmSession)._activeRlmChildRuns.keys()][0]!;
+ await expect(root.deleteInactiveRlmSubagent(childId)).resolves.toBe("running");
+ expect(deleteRuntime).not.toHaveBeenCalled();
+
+ releaseChild();
+ await expect(runPromise).resolves.toMatchObject({ answer: "done" });
+ await waitFor(() => (root as unknown as InspectableRlmSession)._activeRlmChildRuns.size === 0);
+ await expect(root.deleteInactiveRlmSubagent(childId)).resolves.toBe("deleted");
+ expect(deleteRuntime).toHaveBeenCalledWith(childId, retainedChild);
+ await expect(root.deleteInactiveRlmSubagent("unknown-child")).resolves.toBe("not_found");
+ });
+
it("does not let completion retention resurrect a child being deleted", async () => {
let releaseRetention: () => void = () => {};
const retentionGate = new Promise<void>((resolve) => {
@@ -1656,7 +1831,9 @@ describe("AgentSession rlm recursion", () => {
await runFailure;
expect((root as unknown as InspectableRlmSession)._activeRlmChildRuns.size).toBe(1);
expect(await root.listRlmSubagents()).toEqual({ subagents: [] });
- await expect(root.runRlmChild("replacement", { name: "queued-worker" })).rejects.toThrow("already in use");
+ await expect(root.runRlmChild("replacement", { name: "queued-worker" })).rejects.toThrow(
+ "an agent of that name already exists at depth 1 under this parent",
+ );
releaseRuntimeCreation();
await waitFor(() => releaseRuntime.mock.calls.length === 1);
@@ -1754,6 +1931,55 @@ describe("AgentSession rlm recursion", () => {
expect(await root.listRlmSubagents()).toEqual({ subagents: [] });
});
+ it("deletes an inactive nested RLM child through the root session", async () => {
+ let releaseParent: () => void = () => {};
+ const parentRelease = new Promise<void>((resolve) => {
+ releaseParent = resolve;
+ });
+ let parentStarted = false;
+ const root = createSession({
+ maxDepth: 2,
+ streamFn: (_model, context) => {
+ const text = userText(context);
+ if (text !== "slow parent") {
+ return streamAnswer(`child answer: ${text}`);
+ }
+ const stream = createAssistantMessageEventStream();
+ parentStarted = true;
+ void parentRelease.then(() => {
+ stream.push({ type: "done", reason: "stop", message: assistantMessage("parent done") });
+ });
+ return stream;
+ },
+ });
+
+ const parentPromise = root.runRlmChild("slow parent");
+ await waitFor(() => parentStarted);
+ const parentRun = [...(root as unknown as InspectableRlmSession)._activeRlmChildRuns.values()][0];
+ if (!parentRun?.session) {
+ throw new Error("Missing parent child session");
+ }
+ const parentSession = parentRun.session;
+ const nestedResult = await parentSession.runRlmChild("nested child");
+ if (!nestedResult.session_dir) {
+ throw new Error("Missing nested child session directory");
+ }
+ const nestedId = basename(nestedResult.session_dir);
+ const nestedSession = parentSession.getRlmChildSession(nestedId);
+ if (!nestedSession) {
+ throw new Error("Missing retained nested child session");
+ }
+ const disposeNested = vi.spyOn(nestedSession, "disposeAsync");
+
+ await expect(root.deleteInactiveRlmSubagent(nestedId)).resolves.toBe("deleted");
+ expect(await parentSession.listRlmSubagents()).toEqual({ subagents: [] });
+ expect(disposeNested).toHaveBeenCalledOnce();
+ expect(parentRun.status).toBe("running");
+
+ releaseParent();
+ await expect(parentPromise).resolves.toMatchObject({ answer: "parent done" });
+ });
+
it("cancels nested rlm child runs through the root session", async () => {
let releaseChild: () => void = () => {};
const release = new Promise<void>((resolve) => {
diff --git a/packages/coding-agent/test/agents-view-mode.test.ts b/packages/coding-agent/test/agents-view-mode.test.ts
index aa2c65a7b9..cbe3fc2356 100644
--- a/packages/coding-agent/test/agents-view-mode.test.ts
+++ b/packages/coding-agent/test/agents-view-mode.test.ts
@@ -108,6 +108,127 @@ describe("AgentsViewMode", () => {
expect(self.selectedIndex).toBe(4);
});
+ it("re-resolves subagent state before choosing stop or delete intent", async () => {
+ const child = summary({
+ id: "passive-child-session",
+ activeSessionId: undefined,
+ sessionId: "passive-child-session",
+ runtimeKind: "subagent",
+ rlmChildId: "passive-child",
+ });
+ const request = vi.fn(async (command: { type: string }) => ({
+ success: true as const,
+ data: command.type === "cancel_rlm_child" ? { cancelled: false } : { deleted: true },
+ }));
+ const client = { request, supportsServerCapability: vi.fn(() => true) };
+ const self = {
+ rows: [
+ {
+ kind: "subagent",
+ section: "running",
+ summary: child,
+ selectable: true,
+ identity: "child-row",
+ parentIdentity: "root-row",
+ },
+ {
+ kind: "agent",
+ section: "idle",
+ summary: summary({ id: "root-active", activeSessionId: "root-active", sessionId: "root-session" }),
+ selectable: true,
+ identity: "root-row",
+ },
+ ],
+ selectedIndex: 0,
+ pendingDeleteAgent: undefined,
+ pendingKillSubagent: undefined,
+ deleteConfirmExpiresAt: 0,
+ deleteConfirmTimer: undefined,
+ ui: { requestRender: vi.fn() },
+ requireClient: () => client,
+ setStatusMessage: vi.fn(),
+ refreshSessions: vi.fn(async () => true),
+ handleKillSubagentSelected(row: unknown) {
+ return invoke("handleKillSubagentSelected", self, row);
+ },
+ findSubagentRootRow(row: unknown) {
+ return invoke("findSubagentRootRow", self, row);
+ },
+ isDeleteConfirmationVisible() {
+ return invoke("isDeleteConfirmationVisible", self);
+ },
+ showDeleteConfirmation() {
+ return invoke("showDeleteConfirmation", self);
+ },
+ clearDeleteConfirmation(options: unknown) {
+ return invoke("clearDeleteConfirmation", self, options);
+ },
+ killSubagent(pending: unknown, row: unknown) {
+ return invoke("killSubagent", self, pending, row);
+ },
+ };
+
+ await invoke("handleDeleteSelected", self);
+ expect(request).not.toHaveBeenCalled();
+
+ // The child finishes during confirmation. The second keypress must use the
+ // current row state rather than the original running state.
+ self.rows[0]!.section = "inactive";
+ await invoke("handleDeleteSelected", self);
+ expect(request).toHaveBeenCalledWith({
+ type: "delete_rlm_subagent",
+ activeSessionId: "root-active",
+ childId: "passive-child",
+ });
+ expect(request).not.toHaveBeenCalledWith(expect.objectContaining({ type: "cancel_rlm_child" }));
+ expect(self.setStatusMessage).toHaveBeenCalledWith("Subagent deleted", { render: false });
+ });
+
+ it("uses cancel when an inactive subagent starts running during confirmation", async () => {
+ const request = vi.fn(async () => ({ success: true as const, data: { cancelled: true } }));
+ const self = {
+ requireClient: () => ({ request, supportsServerCapability: () => true }),
+ setStatusMessage: vi.fn(),
+ refreshSessions: vi.fn(async () => true),
+ };
+ await invoke(
+ "killSubagent",
+ self,
+ { identity: "child-row", rootActiveSessionId: "root-active", childId: "passive-child" },
+ { section: "running" },
+ );
+ expect(request).toHaveBeenCalledWith({
+ type: "cancel_rlm_child",
+ activeSessionId: "root-active",
+ childId: "passive-child",
+ });
+ expect(request).not.toHaveBeenCalledWith(expect.objectContaining({ type: "delete_rlm_subagent" }));
+ });
+
+ it("falls back to cancel-only when subagent deletion is unsupported", async () => {
+ const request = vi.fn(async () => ({ success: true as const, data: { cancelled: false } }));
+ const self = {
+ requireClient: () => ({ request, supportsServerCapability: () => false }),
+ setStatusMessage: vi.fn(),
+ refreshSessions: vi.fn(async () => true),
+ };
+ await invoke(
+ "killSubagent",
+ self,
+ { identity: "child-row", rootActiveSessionId: "root-active", childId: "passive-child" },
+ { section: "inactive" },
+ );
+ expect(request).toHaveBeenCalledWith({
+ type: "cancel_rlm_child",
+ activeSessionId: "root-active",
+ childId: "passive-child",
+ });
+ expect(self.setStatusMessage).toHaveBeenCalledWith("The daemon cannot delete subagents; it was left unchanged", {
+ render: false,
+ tone: "warning",
+ });
+ });
+
it("uses the opened session as the crash-path back target", async () => {
const opened = summary({ sessionName: "opened" });
const previous = summary({ id: "previous", activeSessionId: "previous", sessionId: "previous" });
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index 26003edce5..6149d13214 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -69,7 +69,7 @@ function heartbeat(id: string, nextRunAt?: string, activeSessionId = "child") {
}
describe("agents view state", () => {
- test("classifies active daemon sessions into coarse fleet sections", () => {
+ test("classifies sessions by live runtime status at any depth", () => {
expect(classifyAgentsViewSession(makeSummary({ isStreaming: true, activity: "working" }))).toBe("running");
expect(
classifyAgentsViewSession(
@@ -77,9 +77,25 @@ describe("agents view state", () => {
),
).toBe("running");
expect(classifyAgentsViewSession(makeSummary({ activity: "working" }))).toBe("running");
+ expect(
+ classifyAgentsViewSession(
+ makeSummary({ runtimeKind: "subagent", rlmDepth: 3, activity: "working", isSessionActive: true }),
+ ),
+ ).toBe("running");
expect(classifyAgentsViewSession(makeSummary({ activity: "idle", messageCount: 2 }))).toBe("idle");
- expect(classifyAgentsViewSession(makeSummary({ activity: "idle", messageCount: 0 }))).toBe("idle");
- expect(classifyAgentsViewSession(makeSummary({ activity: "idle", messageCount: 4 }))).toBe("idle");
+ expect(classifyAgentsViewSession(makeSummary({ runtimeKind: "subagent", activity: "idle" }))).toBe("idle");
+ expect(
+ classifyAgentsViewSession(
+ makeSummary({
+ activeSessionId: undefined,
+ runtimeKind: "subagent",
+ rlmDepth: 3,
+ activity: "working",
+ isSessionActive: true,
+ hasActiveHeartbeat: true,
+ }),
+ ),
+ ).toBe("inactive");
});
test("places all non-busy resident sessions in Idle", () => {
@@ -1418,7 +1434,7 @@ describe("agents view state", () => {
"saved-child",
]);
expect(rows).toHaveLength(2);
- expect(rows.every((row) => row.kind === "agent" && row.depth === 0)).toBe(true);
+ expect(rows.every((row) => row.kind === "agent" && row.depth === 0 && row.section === "inactive")).toBe(true);
expect(rows.find((row) => row.summary.sessionId === "registry-child")?.summary).toMatchObject({
parentSessionId: "root-session",
rlmDepth: 1,
diff --git a/packages/coding-agent/test/daemon-catalog-process.test.ts b/packages/coding-agent/test/daemon-catalog-process.test.ts
index 98282f4e43..53bc162f1d 100644
--- a/packages/coding-agent/test/daemon-catalog-process.test.ts
+++ b/packages/coding-agent/test/daemon-catalog-process.test.ts
@@ -1,6 +1,9 @@
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, relative } from "node:path";
import { describe, expect, it } from "vitest";
-import type { SessionInfo } from "../src/core/session-manager.js";
-import { resolveCatalogSessionMatch } from "../src/modes/daemon/daemon-catalog-process.js";
+import { type SessionInfo, SessionManager } from "../src/core/session-manager.js";
+import { listSavedSessionSiblings, resolveCatalogSessionMatch } from "../src/modes/daemon/daemon-catalog-process.js";
function session(id: string, name: string | undefined, path: string): SessionInfo {
return {
@@ -18,6 +21,69 @@ function session(id: string, name: string | undefined, path: string): SessionInf
}
describe("daemon catalog selector resolution", () => {
+ it("reads only a saved child's persisted sibling set", async () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-catalog-siblings-"));
+ const sessionDir = join(root, "sessions");
+ const parent = SessionManager.create(root, sessionDir);
+ parent.newSession();
+ parent.appendSessionInfo("parent");
+ const first = SessionManager.create(root, join(root, "first"));
+ first.newSession({ parentSession: parent.getSessionFile(), rlmDepth: 1 });
+ first.appendSessionInfo("first");
+ const second = SessionManager.create(root, join(root, "second"));
+ second.newSession({ parentSession: parent.getSessionFile(), rlmDepth: 1 });
+ second.appendSessionInfo("second");
+ const registry = join(dirname(sessionDir), "session-artifacts", parent.getSessionId(), "rlm-subagents.jsonl");
+ mkdirSync(dirname(registry), { recursive: true });
+ writeFileSync(
+ registry,
+ [
+ { type: "rlm_subagent", childId: "first", sessionFile: first.getSessionFile(), status: "completed" },
+ { type: "rlm_subagent", childId: "second", sessionFile: second.getSessionFile(), status: "completed" },
+ ]
+ .map((entry) => JSON.stringify(entry))
+ .join("\n"),
+ );
+
+ await expect(listSavedSessionSiblings(first.getSessionFile()!)).resolves.toEqual([
+ expect.objectContaining({ id: first.getSessionId(), name: "first" }),
+ expect.objectContaining({ id: second.getSessionId(), name: "second" }),
+ ]);
+ });
+
+ it("resolves relative parent headers from each child session directory", async () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-catalog-relative-siblings-"));
+ const sessionDir = join(root, "sessions");
+ const parent = SessionManager.create(root, sessionDir);
+ parent.newSession();
+ parent.appendSessionInfo("parent");
+ const parentFile = parent.getSessionFile()!;
+ const firstDir = join(root, "first");
+ const first = SessionManager.create(root, firstDir);
+ first.newSession({ parentSession: relative(firstDir, parentFile), rlmDepth: 1 });
+ first.appendSessionInfo("first");
+ const secondDir = join(root, "second");
+ const second = SessionManager.create(root, secondDir);
+ second.newSession({ parentSession: relative(secondDir, parentFile), rlmDepth: 1 });
+ second.appendSessionInfo("second");
+ const registry = join(dirname(sessionDir), "session-artifacts", parent.getSessionId(), "rlm-subagents.jsonl");
+ mkdirSync(dirname(registry), { recursive: true });
+ writeFileSync(
+ registry,
+ [
+ { type: "rlm_subagent", childId: "first", sessionFile: first.getSessionFile(), status: "completed" },
+ { type: "rlm_subagent", childId: "second", sessionFile: second.getSessionFile(), status: "completed" },
+ ]
+ .map((entry) => JSON.stringify(entry))
+ .join("\n"),
+ );
+
+ await expect(listSavedSessionSiblings(first.getSessionFile()!)).resolves.toEqual([
+ expect.objectContaining({ id: first.getSessionId(), name: "first" }),
+ expect.objectContaining({ id: second.getSessionId(), name: "second" }),
+ ]);
+ });
+
it("treats an exact name colliding with another session id prefix as ambiguous", () => {
const sessions = [
session("named-session-id", "target", "/tmp/by-name.jsonl"),
diff --git a/packages/coding-agent/test/daemon-client.test.ts b/packages/coding-agent/test/daemon-client.test.ts
index 8520b90e11..2a28c47da3 100644
--- a/packages/coding-agent/test/daemon-client.test.ts
+++ b/packages/coding-agent/test/daemon-client.test.ts
@@ -215,6 +215,39 @@ describe("DaemonClient", () => {
client.close();
});
+ it("does not send subagent deletion to an old daemon without the capability", async () => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ const connect = client.connect();
+ const socket = netMock.sockets[0]!;
+ socket.emit("connect");
+ await connect;
+ emitHello(socket, DAEMON_PROTOCOL_VERSION, []);
+
+ await expect(
+ client.request({ type: "delete_rlm_subagent", activeSessionId: "active-1", childId: "child-1" }),
+ ).rejects.toThrow("does not support delete_rlm_subagent");
+ expect(socket.writes).toEqual([]);
+ client.close();
+ });
+
+ it("sends subagent deletion to a capable daemon without requiring a schema bump", async () => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ const connect = client.connect();
+ const socket = netMock.sockets[0]!;
+ socket.emit("connect");
+ await connect;
+ emitHello(socket, DAEMON_PROTOCOL_VERSION, ["delete_rlm_subagent"], DAEMON_SCHEMA_REVISION - 1);
+
+ const request = client.request({
+ type: "delete_rlm_subagent",
+ activeSessionId: "active-1",
+ childId: "child-1",
+ });
+ await vi.waitFor(() => expect(socket.writes).toHaveLength(1));
+ client.close();
+ await expect(request).rejects.toThrow("closed before the operation completed");
+ });
+
it("rejects an old daemon before requesting session state", async () => {
const client = new DaemonClient("/tmp/prime-agent.sock");
const connect = client.connect();
diff --git a/packages/coding-agent/test/daemon-command.test.ts b/packages/coding-agent/test/daemon-command.test.ts
index 9769f30163..56af52f616 100644
--- a/packages/coding-agent/test/daemon-command.test.ts
+++ b/packages/coding-agent/test/daemon-command.test.ts
@@ -14,6 +14,7 @@ const daemonClientMock = vi.hoisted(() => {
schedule?: string;
prompt?: string;
includeInactive?: boolean;
+ all?: boolean;
sessionPath?: string;
config?: {
extensionFlagValues?: Record<string, boolean | string>;
@@ -219,6 +220,18 @@ describe("daemon command", () => {
expect(client?.closeListenerCountAtClose).toBe(0);
});
+ it("chooses a terminating non-colliding default name past the safe-integer range", async () => {
+ const unsafeIntegerName = "9007199254740992";
+ daemonClientMock.behavior.sessions = [makeSessionSummary("active-1", "session-1", unsafeIntegerName)];
+
+ await expect(handleDaemonCommand(["daemon", "--socket", "/tmp/prime-agent.sock"])).resolves.toBe(true);
+
+ const client = daemonClientMock.instances[1];
+ expect(client?.requests[0]).toEqual({ type: "list", all: true });
+ expect(client?.requests[1]).toMatchObject({ type: "create", name: "1" });
+ expect(client?.requests[1]?.name).not.toBe(unsafeIntegerName);
+ });
+
it("keeps create session name after an unknown boolean extension flag", async () => {
await expect(
handleDaemonCommand(["daemon", "--socket", "/tmp/prime-agent.sock", "create", "--unknown-typo", "my-session"]),
diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.ts
index 179a5fb282..400eff95a1 100644
--- a/packages/coding-agent/test/daemon-mode.test.ts
+++ b/packages/coding-agent/test/daemon-mode.test.ts
@@ -55,6 +55,33 @@ describe("daemon mode helpers", () => {
expect(client.id).toBe("public-client");
});
+ it("normalizes daemon session names before validation and persistence", async () => {
+ const daemon = new AgentDaemon("/tmp/unused-daemon.sock", {
+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },
+ createRuntime: vi.fn(),
+ });
+ const setSessionName = vi.fn();
+ const state = makeState("active");
+ state.runtime = {
+ ...state.runtime,
+ metadata: { kind: "top-level", createdAt: 1 },
+ session: { setSessionName },
+ } as never;
+ const assertStateSessionNameAvailable = vi.fn(async () => {});
+ const internals = daemon as unknown as {
+ assertStateSessionNameAvailable: typeof assertStateSessionNameAvailable;
+ setStateSessionName(state: ActiveSessionState, name: string): Promise<void>;
+ };
+ internals.assertStateSessionNameAvailable = assertStateSessionNameAvailable;
+
+ await internals.setStateSessionName(state, " normalized ");
+
+ expect(assertStateSessionNameAvailable).toHaveBeenCalledWith(state, "normalized");
+ expect(setSessionName).toHaveBeenCalledWith("normalized");
+ await expect(internals.setStateSessionName(state, " ")).rejects.toThrow("Session name cannot be empty");
+ expect(setSessionName).toHaveBeenCalledOnce();
+ });
+
it("finds only direct child active sessions", () => {
const parent = makeState("parent");
const child = makeState("child", "parent");
@@ -184,6 +211,86 @@ describe("daemon mode helpers", () => {
});
});
+ it("classifies local roster status with heartbeat and running-child activity", () => {
+ const daemon = new AgentDaemon("/tmp/prime-agent-status-test.sock", {
+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },
+ createRuntime: vi.fn(),
+ });
+ const state = makeState("local-active");
+ let hasRunningChildren = true;
+ state.runtime = {
+ ...state.runtime,
+ cwd: "/tmp",
+ metadata: { kind: "top-level", createdAt: 1 },
+ session: {
+ sessionId: "local-session",
+ isSessionActive: false,
+ isStreaming: false,
+ unfinishedActionCount: 0,
+ hasRunningRlmChildren: () => hasRunningChildren,
+ },
+ } as never;
+ const internals = daemon as unknown as {
+ cronStore: { getHeartbeat(activeSessionId: string): AgentCronJob | undefined };
+ createAgentMessageAgentSummary(state: ActiveSessionState): { status?: string };
+ };
+ const getHeartbeat = vi.spyOn(internals.cronStore, "getHeartbeat").mockReturnValue(undefined);
+
+ expect(internals.createAgentMessageAgentSummary(state).status).toBe("running");
+ hasRunningChildren = false;
+ state.runtime = {
+ ...state.runtime,
+ metadata: { kind: "subagent", createdAt: 1 },
+ } as ActiveSessionState["runtime"];
+ expect(internals.createAgentMessageAgentSummary(state).status).toBe("idle");
+ getHeartbeat.mockReturnValue({ status: "active" } as AgentCronJob);
+ expect(internals.createAgentMessageAgentSummary(state).status).toBe("running");
+ });
+
+ it("keeps fresh local rows over stale synced peers in the family catalog", async () => {
+ const daemon = new AgentDaemon("/tmp/prime-agent-local-precedence.sock", {
+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },
+ createRuntime: vi.fn(),
+ });
+ const state = makeState("local-active");
+ state.runtime = {
+ ...state.runtime,
+ cwd: "/tmp",
+ metadata: { kind: "top-level", createdAt: 1 },
+ session: {
+ sessionId: "shared-session",
+ sessionName: "fresh-local",
+ isSessionActive: false,
+ isStreaming: false,
+ unfinishedActionCount: 0,
+ hasRunningRlmChildren: () => false,
+ },
+ } as never;
+ const internals = daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ remoteAgentPeers: Map<string, Record<string, unknown>>;
+ createAgentFamilyCatalog(): Promise<Array<{ id: string; name?: string }>>;
+ };
+ internals.sessions.set(state.activeSessionId, state);
+ internals.remoteAgentPeers.set("stale-active", {
+ activeSessionId: "stale-active",
+ sessionId: "shared-session",
+ sessionName: "stale-peer",
+ runtimeKind: "top-level",
+ cwd: "/tmp",
+ isStreaming: false,
+ unfinishedActionCount: 0,
+ });
+ const listAll = vi.spyOn(SessionManager, "listAll").mockResolvedValue([]);
+ try {
+ expect(await internals.createAgentFamilyCatalog()).toContainEqual(
+ expect.objectContaining({ id: "shared-session", name: "fresh-local" }),
+ );
+ } finally {
+ listAll.mockRestore();
+ }
+ });
+
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" },
@@ -4374,6 +4481,7 @@ describe("daemon mode helpers", () => {
sessionName: "renamed-worker",
runtimeKind: "subagent",
parentActiveSessionId: parentState.activeSessionId,
+ status: "inactive",
rlmChildId: fixture.childId,
}),
);
@@ -4381,9 +4489,25 @@ describe("daemon mode helpers", () => {
expect.objectContaining({
activeSessionId: expect.any(String),
sessionName: "nested-worker",
+ status: "inactive",
rlmChildId: fixture.grandchildId,
}),
);
+ const messageController = internals.createAgentMessageController(() => parentState);
+ await expect(messageController.roster?.()).resolves.toMatchObject({
+ current: { id: parentState.runtime.session.sessionId, depth: 0 },
+ entries: [
+ expect.objectContaining({ relationship: "child", name: "renamed-worker", depth: 1, status: "inactive" }),
+ ],
+ });
+ await expect(
+ messageController.assertSessionNameAvailable?.({
+ name: "renamed-worker",
+ depth: 1,
+ parentSessionId: parentState.runtime.session.sessionId,
+ parentSessionPath: fixture.parentSessionFile,
+ }),
+ ).rejects.toThrow("an agent of that name already exists at depth 1 under this parent");
const listResponse = (await internals.handleCommand(makeClient("client-1", parentState.activeSessionId), {
type: "list",
all: true,
@@ -4633,6 +4757,48 @@ describe("daemon mode helpers", () => {
}
});
+ it("validates a requested passive child name before hydration", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-passive-name-preflight-"));
+ try {
+ const fixture = makePersistedRlmDaemonFixture(tempDir);
+ const internals = fixture.daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;
+ assertFamilySessionNameAvailable: ReturnType<typeof vi.fn>;
+ hydratePassiveRlmSubagent: ReturnType<typeof vi.fn>;
+ };
+ const parentState = await internals.createRuntime({
+ type: "create",
+ sessionPath: fixture.parentSessionFile,
+ });
+ const nameError = new Error("sibling name collision");
+ internals.assertFamilySessionNameAvailable = vi.fn(async () => {
+ throw nameError;
+ });
+ internals.hydratePassiveRlmSubagent = vi.fn();
+
+ await expect(
+ internals.createRuntime({
+ type: "create",
+ sessionPath: fixture.childSessionFile,
+ name: " sibling ",
+ }),
+ ).rejects.toBe(nameError);
+ expect(internals.assertFamilySessionNameAvailable).toHaveBeenCalledWith({
+ name: "sibling",
+ depth: 1,
+ parentSessionId: parentState.runtime.session.sessionId,
+ parentSessionPath: fixture.parentSessionFile,
+ ignoreSessionId: expect.any(String),
+ });
+ expect(internals.hydratePassiveRlmSubagent).not.toHaveBeenCalled();
+ expect(fixture.createRuntime).toHaveBeenCalledOnce();
+ expect([...internals.sessions.values()]).toEqual([parentState]);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
it("hydrates a passive child on agent message and delivers to it", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-message-"));
try {
@@ -6149,21 +6315,169 @@ describe("daemon mode helpers", () => {
}
});
- it("deletes a passive child without hydrating it", async () => {
- const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-delete-"));
+ it("keeps cancel pure when a retained or unknown child has no active run", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-rlm-cancel-"));
try {
const fixture = makePersistedRlmDaemonFixture(tempDir);
const internals = fixture.daemon as unknown as {
createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;
- createSubagentRuntimeHost(parent: ActiveSessionState): SubagentRuntimeHost;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;
};
- const parentState = await internals.createRuntime({
- type: "create",
- sessionPath: fixture.parentSessionFile,
+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });
+ const parentSession = parentState.runtime.session as unknown as {
+ cancelRlmChildRun: ReturnType<typeof vi.fn>;
+ deleteRlmSubagent: ReturnType<typeof vi.fn>;
+ };
+ parentSession.cancelRlmChildRun = vi.fn(() => false);
+ parentSession.deleteRlmSubagent = vi.fn();
+
+ for (const childId of [fixture.childId, "unknown-child"]) {
+ const result = (await internals.handleCommand(makeClient("client-1", parentState.activeSessionId), {
+ type: "cancel_rlm_child",
+ activeSessionId: parentState.activeSessionId,
+ childId,
+ })) as { data: { cancelled: boolean } };
+ expect(result.data.cancelled).toBe(false);
+ }
+ expect(parentSession.deleteRlmSubagent).not.toHaveBeenCalled();
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("refuses to delete a busy hydrated child and deletes it after it becomes idle", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-hydrated-rlm-delete-"));
+ try {
+ const fixture = makePersistedRlmDaemonFixture(tempDir);
+ const internals = fixture.daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;
+ };
+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });
+ const childState = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });
+ let isStreaming = true;
+ Object.defineProperty(childState.runtime.session, "isStreaming", { get: () => isStreaming });
+ Object.defineProperty(childState.runtime.session, "unfinishedActionCount", { get: () => 0 });
+ const parentSession = parentState.runtime.session as unknown as {
+ deleteInactiveRlmSubagent: ReturnType<typeof vi.fn>;
+ };
+ const deleteSpy = vi.fn(async (childId: string, isExternallyRunning: () => boolean) => {
+ if (isExternallyRunning()) return "running" as const;
+ await (
+ fixture.daemon as unknown as {
+ createSubagentRuntimeHost(parent: ActiveSessionState): SubagentRuntimeHost;
+ }
+ )
+ .createSubagentRuntimeHost(parentState)
+ .deleteRlmSubagentRuntime(childId, childState.runtime.session);
+ return "deleted" as const;
});
+ parentSession.deleteInactiveRlmSubagent = deleteSpy;
+ const client = makeClient("client-1", parentState.activeSessionId);
- await internals.createSubagentRuntimeHost(parentState).deleteRlmSubagentRuntime(fixture.childId);
+ const busy = (await internals.handleCommand(client, {
+ type: "delete_rlm_subagent",
+ activeSessionId: parentState.activeSessionId,
+ childId: fixture.childId,
+ })) as { data: { deleted: boolean; reason?: string } };
+ expect(busy.data).toEqual({ deleted: false, reason: "running" });
+ expect(deleteSpy).not.toHaveBeenCalled();
+ expect(internals.sessions.get(childState.activeSessionId)).toBe(childState);
+ isStreaming = false;
+ const idle = (await internals.handleCommand(client, {
+ type: "delete_rlm_subagent",
+ activeSessionId: parentState.activeSessionId,
+ childId: fixture.childId,
+ })) as { data: { deleted: boolean } };
+ expect(idle.data).toEqual({ deleted: true });
+ expect(internals.sessions.has(childState.activeSessionId)).toBe(false);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("refuses to delete a busy nested resident child through the root session", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-nested-rlm-delete-"));
+ try {
+ const fixture = makePersistedRlmDaemonFixture(tempDir);
+ const internals = fixture.daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;
+ };
+ const rootState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });
+ const nestedState = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });
+ const nestedSession = nestedState.runtime.session;
+ nestedState.runtime = {
+ ...nestedState.runtime,
+ metadata: {
+ ...nestedState.runtime.metadata,
+ parentActiveSessionId: "intermediate-active",
+ },
+ session: nestedSession,
+ } as ActiveSessionState["runtime"];
+ Object.defineProperty(nestedState.runtime.session, "isStreaming", { get: () => true });
+ Object.defineProperty(nestedState.runtime.session, "unfinishedActionCount", { get: () => 0 });
+ const rootSession = rootState.runtime.session as unknown as {
+ deleteInactiveRlmSubagent: ReturnType<typeof vi.fn>;
+ };
+ const deleteSpy = vi.fn(async () => "deleted" as const);
+ rootSession.deleteInactiveRlmSubagent = deleteSpy;
+
+ const result = (await internals.handleCommand(makeClient("client-1", rootState.activeSessionId), {
+ type: "delete_rlm_subagent",
+ activeSessionId: rootState.activeSessionId,
+ childId: fixture.childId,
+ })) as { data: { deleted: boolean; reason?: string } };
+
+ expect(result.data).toEqual({ deleted: false, reason: "running" });
+ expect(deleteSpy).not.toHaveBeenCalled();
+ expect(internals.sessions.get(nestedState.activeSessionId)).toBe(nestedState);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("deletes a passive child without hydrating it and treats unknown children benignly", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-delete-"));
+ try {
+ const fixture = makePersistedRlmDaemonFixture(tempDir);
+ const internals = fixture.daemon as unknown as {
+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;
+ };
+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });
+ const parentSession = parentState.runtime.session as unknown as {
+ deleteInactiveRlmSubagent: (childId: string) => Promise<"deleted" | "not_found">;
+ };
+ parentSession.deleteInactiveRlmSubagent = async (childId) => {
+ if (childId !== fixture.childId) return "not_found";
+ await (
+ fixture.daemon as unknown as {
+ createSubagentRuntimeHost(parent: ActiveSessionState): SubagentRuntimeHost;
+ }
+ )
+ .createSubagentRuntimeHost(parentState)
+ .deleteRlmSubagentRuntime(childId);
+ return "deleted";
+ };
+ const client = makeClient("client-1", parentState.activeSessionId);
+
+ const unknown = (await internals.handleCommand(client, {
+ type: "delete_rlm_subagent",
+ activeSessionId: parentState.activeSessionId,
+ childId: "unknown-child",
+ })) as { data: { deleted: boolean } };
+ expect(unknown.data).toEqual({ deleted: false });
+
+ const result = (await internals.handleCommand(client, {
+ type: "delete_rlm_subagent",
+ activeSessionId: parentState.activeSessionId,
+ childId: fixture.childId,
+ })) as { data: { deleted: boolean } };
+ expect(result.data).toEqual({ deleted: true });
expect(fixture.createRuntime).toHaveBeenCalledOnce();
expect(existsSync(fixture.childSessionFile)).toBe(true);
const persisted = readFileSync(join(fixture.parentArtifactDir, "rlm-subagents.jsonl"), "utf8")
@@ -6175,7 +6489,6 @@ describe("daemon mode helpers", () => {
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 {
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index 870e226234..4843eb7ffd 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -67,6 +67,14 @@ describe("daemon protocol helpers", () => {
);
});
+ it("capability-gates explicit subagent deletion instead of schema-gating it", () => {
+ expect(DAEMON_COMMAND_COMPATIBILITY.delete_rlm_subagent).toEqual({
+ minProtocol: 7,
+ capability: "delete_rlm_subagent",
+ });
+ expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toContain("delete_rlm_subagent");
+ });
+
it("capability-gates the optional model catalog surface", () => {
expect(DAEMON_COMMAND_COMPATIBILITY.get_model_catalog).toEqual({
minProtocol: 7,
diff --git a/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts
index 2837da19a0..6e1f784025 100644
--- a/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts
@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { AgentSessionMessageAgentSummary } from "../src/core/agent-messages.js";
+import { readSessionInfo, SessionManager } from "../src/core/session-manager.js";
import { success } from "../src/modes/daemon/daemon-protocol.js";
import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";
@@ -12,6 +13,8 @@ interface SupervisorInternals {
refreshWorkerSummaries(worker: WorkerFixture): Promise<void>;
syncAgentPeers(): Promise<void>;
findSummaryInWorker(worker: WorkerFixture, selector: string): SessionSummary | undefined;
+ createOrReuseWorker(clientId: string, command: { type: "create"; name: string }): Promise<WorkerFixture>;
+ assertSupervisorSavedSessionNameAvailable(sessionPath: string, name: string): Promise<void>;
}
interface WorkerFixture {
@@ -85,6 +88,117 @@ describe("daemon supervisor passive subagent topology", () => {
expect(supervisor.findSummaryInWorker(resident, "88889999cccc")).toBe(child);
});
+ it("rejects an explicit root name that collides with a saved root", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-root-name-"));
+ tempDirs.push(directory);
+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: directory, cwd: directory },
+ descriptorDir: join(directory, "workers"),
+ }) as unknown as SupervisorInternals;
+ const launchWorker = vi.fn();
+ Object.assign(supervisor, {
+ catalog: {
+ list: vi.fn(async () => [
+ {
+ id: "saved-root",
+ name: "duplicate-root",
+ path: join(directory, "saved.jsonl"),
+ cwd: directory,
+ created: new Date(0),
+ modified: new Date(0),
+ messageCount: 0,
+ firstMessage: "",
+ allMessagesText: "",
+ },
+ ]),
+ },
+ launchWorker,
+ });
+
+ await expect(
+ supervisor.createOrReuseWorker("client", { type: "create", name: "duplicate-root" }),
+ ).rejects.toThrow("an agent of that name already exists at depth 0 under this parent");
+ expect(launchWorker).not.toHaveBeenCalled();
+ });
+
+ it("rejects a forked root name that collides with another saved root", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-forked-root-name-"));
+ tempDirs.push(directory);
+ const sourceManager = SessionManager.create(directory, join(directory, "sessions"));
+ sourceManager.newSession({ rlmDepth: 0 });
+ sourceManager.flushNow();
+ const sourcePath = sourceManager.getSessionFile();
+ if (!sourcePath) throw new Error("Missing source session path");
+ const forkedManager = SessionManager.forkFrom(sourcePath, directory, join(directory, "sessions"));
+ const forkedPath = forkedManager.getSessionFile();
+ if (!forkedPath) throw new Error("Missing forked session path");
+ const forkedInfo = await readSessionInfo(forkedPath);
+ if (!forkedInfo) throw new Error("Missing forked session info");
+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: directory, cwd: directory },
+ descriptorDir: join(directory, "workers"),
+ }) as unknown as SupervisorInternals;
+ Object.assign(supervisor, {
+ catalog: {
+ siblings: vi.fn(async () => [forkedInfo]),
+ list: vi.fn(async () => [
+ {
+ id: "other-root",
+ name: "duplicate-root",
+ path: join(directory, "other.jsonl"),
+ cwd: directory,
+ created: new Date(0),
+ modified: new Date(0),
+ messageCount: 0,
+ firstMessage: "",
+ allMessagesText: "",
+ rlmDepth: 0,
+ },
+ ]),
+ },
+ });
+
+ await expect(supervisor.assertSupervisorSavedSessionNameAvailable(forkedPath, "duplicate-root")).rejects.toThrow(
+ "an agent of that name already exists at depth 0 under this parent",
+ );
+ });
+
+ it("normalizes explicit root names before supervisor validation and launch", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-normalized-root-name-"));
+ tempDirs.push(directory);
+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: directory, cwd: directory },
+ descriptorDir: join(directory, "workers"),
+ }) as unknown as SupervisorInternals;
+ const launchWorker = vi.fn();
+ Object.assign(supervisor, {
+ catalog: {
+ list: vi.fn(async () => [
+ {
+ id: "saved-root",
+ name: "duplicate-root",
+ path: join(directory, "saved.jsonl"),
+ cwd: directory,
+ created: new Date(0),
+ modified: new Date(0),
+ messageCount: 0,
+ firstMessage: "",
+ allMessagesText: "",
+ },
+ ]),
+ },
+ launchWorker,
+ });
+
+ await expect(
+ supervisor.createOrReuseWorker("client", { type: "create", name: " duplicate-root " }),
+ ).rejects.toThrow('Agent name "duplicate-root" is unavailable');
+ await expect(supervisor.createOrReuseWorker("client", { type: "create", name: " " })).rejects.toThrow(
+ "Session name cannot be empty",
+ );
+ expect(launchWorker).not.toHaveBeenCalled();
+ });
+
it("retains passive worker summaries and sends them to cross-worker agent peer maps", async () => {
const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-passive-peers-"));
tempDirs.push(directory);
@@ -130,6 +244,7 @@ describe("daemon supervisor passive subagent topology", () => {
sessionId: "passive-session",
sessionName: "passive-worker",
runtimeKind: "subagent",
+ status: "inactive",
rlmChildId: "passive-child",
}),
);
diff --git a/packages/coding-agent/test/kernel-agent-message-skill.test.ts b/packages/coding-agent/test/kernel-agent-message-skill.test.ts
index 7b9ba11d5c..7d877b2508 100644
--- a/packages/coding-agent/test/kernel-agent-message-skill.test.ts
+++ b/packages/coding-agent/test/kernel-agent-message-skill.test.ts
@@ -68,6 +68,13 @@ describe("agent-message skill over the kernel host bridge", () => {
],
};
},
+ "agent_message.roster": async (payload) => {
+ requests.push({ type: "agent_message.roster", payload });
+ return {
+ current: { name: "alpha", id: "session-alpha", depth: 0 },
+ entries: [{ relationship: "sibling", name: "Beta", id: "session-beta", depth: 0, status: "idle" }],
+ };
+ },
"agent_message.send": async (payload) => {
requests.push({ type: "agent_message.send", payload });
return {
@@ -88,13 +95,18 @@ describe("agent-message skill over the kernel host bridge", () => {
const result = await manager.execute(`
import json
agents = await agent_message.list_agents()
+roster = await agent_message.roster()
receipt = await agent_message.send("beta", "hello beta", mode="follow_up")
-print(json.dumps({"agents": agents, "receipt": receipt}, sort_keys=True))
+print(json.dumps({"agents": agents, "roster": roster, "receipt": receipt}, sort_keys=True))
`);
expect(result.status).toBe("ok");
const output = JSON.parse(result.stdout.trim());
expect(output.agents.agents).toHaveLength(2);
+ expect(output.roster).toMatchObject({
+ current: { id: "session-alpha", depth: 0 },
+ entries: [{ relationship: "sibling", id: "session-beta", status: "idle" }],
+ });
expect(output.receipt).toMatchObject({
id: "agentmsg-test",
source: "agent_message",
@@ -111,7 +123,8 @@ print(json.dumps({"agents": agents, "receipt": receipt}, sort_keys=True))
},
]);
expect(requests[0]).toMatchObject({ type: "agent_message.list", payload: { type: "agent_message.list" } });
- expect(requests[1]).toMatchObject({
+ expect(requests[1]).toMatchObject({ type: "agent_message.roster", payload: { type: "agent_message.roster" } });
+ expect(requests[2]).toMatchObject({
type: "agent_message.send",
payload: {
type: "agent_message.send",
@@ -120,7 +133,7 @@ print(json.dumps({"agents": agents, "receipt": receipt}, sort_keys=True))
mode: "follow_up",
},
});
- expect(requests[1].payload).not.toHaveProperty("from");
+ expect(requests[2].payload).not.toHaveProperty("from");
});
it("validates mode before sending to the host", async () => {
diff --git a/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts b/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts
index 64fc4d7937..a40c7ee987 100644
--- a/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts
@@ -237,7 +237,7 @@ describe("ENG-4649 subagent model selection", () => {
const first = harness.session.runRlmChild("first task", { name: "shared-reviewer" });
await expect(harness.session.runRlmChild("second task", { name: "shared-reviewer" })).rejects.toThrow(
- 'RLM subagent session name "shared-reviewer" is already in use',
+ 'Agent name "shared-reviewer" is unavailable: an agent of that name already exists at depth 1 under this parent',
);
await expect(first).resolves.toMatchObject({ answer: "first child answer" });
} finally {
diff --git a/packages/coding-agent/test/system-prompt.test.ts b/packages/coding-agent/test/system-prompt.test.ts
index a0016c691f..e90ad8d677 100644
--- a/packages/coding-agent/test/system-prompt.test.ts
+++ b/packages/coding-agent/test/system-prompt.test.ts
@@ -54,6 +54,7 @@ describe("buildRlmPrompt", () => {
"",
"Working directory: /repo",
"Conversation log: /repo/.pi/sessions/session.jsonl",
+ "Recursive agent depth: 0",
`Pre-installed Python packages: ${DEFAULT_RLM_EXTRA_IMPORT_LABELS.join(", ")}.`,
"Install additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).",
"",