A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(coding-agent): narrow agent reach to the nuclear family (#597)
Sebastian Müllercba2a919a7a9
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex 7cb6200580..382e1e1379 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -9,6 +9,7 @@- 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.+- Fixed silent or cancelled RLM children leaving parents without a terminal status notice.## [0.5.1] - 2026-08-04diff --git a/packages/coding-agent/docs/long-running-agents.md b/packages/coding-agent/docs/long-running-agents.mdindex 617a1294ed..2ec0a36e9e 100644--- a/packages/coding-agent/docs/long-running-agents.md+++ b/packages/coding-agent/docs/long-running-agents.md@@ -81,8 +81,9 @@ From the IPython kernel, use the preloaded `agent_message` Python skill:```pythonroster = await agent_message.list_agents()receipt = await agent_message.send(- "api-reviewer","Recheck the endpoint after the latest edit",+ receiver_role="sibling",+ receiver_name="api-reviewer",mode="auto",)print(receipt["deliveryStatus"])@@ -93,7 +94,11 @@ For the current parent's direct RLM children, prefer the parent-scoped registry:```pythonchildren = await rlm.list_subagents()child = next(item for item in children if item.session_name == "api-reviewer")-await agent_message.send(child.session_name, "Continue with the updated diff")+await agent_message.send(+ "Continue with the updated diff",+ receiver_role="child",+ receiver_name=child.session_name,+)```Delivery modes are:@@ -102,7 +107,7 @@ Delivery modes are:- `steer`: intentionally inject the message into active work; and- `follow_up`: wait until the target's current work finishes.-A receipt is `delivered` when it reached an idle target's context or `queued` when accepted for later delivery. Messaging is direct only; broadcasts are not supported. The daemon derives sender identity and enforces message-size, rate, and pending-queue limits.+A receipt is `delivered` when it reached an idle target's context or `queued` when accepted for later delivery. `agent_message.send("all", message)` broadcasts only within the family roster. The daemon derives sender identity and enforces message-size, rate, and pending-queue limits.## Heartbeats and Scheduled Promptsdiff --git a/packages/coding-agent/skills/agent-message/SKILL.md b/packages/coding-agent/skills/agent-message/SKILL.mdindex 72ea2efe85..4aa99ef90f 100644--- a/packages/coding-agent/skills/agent-message/SKILL.md+++ b/packages/coding-agent/skills/agent-message/SKILL.md@@ -1,13 +1,14 @@---name: agent-message-description: Message other active Prime Agent sessions, including completed retained subagents, through the daemon. Use to discover active agents and send a direct text message without spoofing sender identity.+description: Message an agent's parent, siblings, or direct children through the daemon. Use the family roster to discover reachable agents and send direct text without spoofing sender identity.---# Agent Message-Send direct messages to other active Prime Agent sessions through the local-daemon. The daemon derives your sender identity from the current session; do-not try to include a `from` field.+Send direct messages within the current agent's nuclear family through the+local daemon: parent, siblings, and direct children only. Roots are siblings.+The daemon derives your sender identity from the current session; do not try+to include a `from` field.Call directly from the kernel:@@ -26,26 +27,21 @@ if child is not None:## API-- `await agent_message.roster()` — returns `current` (`name`, `id`, `depth`) and- relationship-scoped `entries` (`relationship`, `name`, `id`, `depth`, `status`)+- `await agent_message.list_agents()` — returns `current` (`name`, `id`, `depth`)+ and family-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- subagents and successful completed subagents retained by an open parent.- For the current parent session's direct children, prefer- `await rlm.list_subagents()` over filtering this global list. Every RLM child- gets a readable unique `session_name`, or the orchestrator can choose one with- `rlm("task", name="api-reviewer")`; use that name directly as a target.+ family members and sorts parent, siblings by name, then children by name; it+ does not expose a global daemon session list.- `await agent_message.send(message, receiver_role="parent" | "sibling" | "child", receiver_name=None, mode="auto")` — sends one directtext message to an active session. Sending to an idle completed subagentstarts an ordinary follow-up turn in that same child session and context.The child remains available only until its parent session closes. The daemonresolves `receiver_role` within the current agent family; `receiver_name` is- required for siblings and children and omitted for the unique parent. The- legacy positional `send(target, message)` form remains available during- migration. `mode` is+ required for siblings and children and omitted for the unique parent.+ `send("all", message)` broadcasts only to the+ family roster and returns `{receipts: [...]}` in roster order; successful entries+ are ordinary receipts and failed entries contain the target id and a short `error`.+ One failed delivery does not reject successful deliveries. `mode` is`"auto"`, `"follow_up"`, or `"steer"`. In `auto` mode, messages to busy sessions are queued as steeringmessages so the target sees them during the active run; use `"follow_up"` forintentionally delayed delivery. Returns a receipt with a `deliveryStatus`@@ -60,7 +56,8 @@ if child is not None:be running and queued receipts have not run yet. Wait until observation showsthe child is idle and its context is no longer needed before calling`await rlm.delete_subagent(child)`.-- Broadcast sends are not supported.+- Reach is limited to parent, siblings, and direct children; relay through an+ intermediate child instead of messaging grandchildren or cousins directly.- Sender identity is daemon-derived and cannot be spoofed from Python.- The daemon enforces message size, rate, and pending-queue limits beforeaccepting delivery.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__.pyindex d5b4df4e32..0bd4815109 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@@ -17,48 +17,33 @@ _MESSAGE_DISPLAY_MIME = "application/vnd.prime-agent.agent-message+json"async def list_agents() -> dict[str, Any]:- """List active daemon sessions addressable by agent_message.send()."""- 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")+ return await host_request("agent_message.list_agents")async def send(message: str,- *legacy_args: str,+ broadcast_message: str | None = None,+ *,receiver_role: ReceiverRole | str | None = None,receiver_name: str | None = None,mode: MessageMode = "auto",) -> dict[str, Any]:- """Send one direct message, preferably using a nuclear-family role.-- New form: ``send(message, receiver_role="parent" | "sibling" | "child",- receiver_name=...)``. A name or id is required for siblings and children and- must be omitted for the unique parent. The legacy positional- ``send(target, message, mode)`` form remains available during migration.- """+ """Send one direct role-addressed message or broadcast to ``"all"``."""roles = ("parent", "sibling", "child")- payload: dict[str, Any]- if legacy_args:- if receiver_role is not None or receiver_name is not None:+ if broadcast_message is not None:+ if message != "all":raise TypeError(- "legacy agent_message.send cannot combine positional target/message "- "with receiver_role or receiver_name"+ "positional agent_message.send targets are not supported; "+ "use receiver_role and receiver_name")- if len(legacy_args) > 2:- raise TypeError("legacy agent_message.send accepts target, message, and optional mode")- target = message- legacy_message = legacy_args[0]- if len(legacy_args) == 2:- mode = legacy_args[1] # type: ignore[assignment]- if not isinstance(target, str):- raise TypeError(f"target must be str, got {type(target).__name__}")- if not isinstance(legacy_message, str):- raise TypeError("legacy agent_message.send requires target and message strings")- payload = {"target": target, "message": legacy_message, "mode": mode}+ if receiver_role is not None or receiver_name is not None:+ raise TypeError("broadcast cannot be combined with receiver_role/receiver_name")+ payload: dict[str, Any] = {+ "target": "all",+ "message": broadcast_message,+ "mode": mode,+ }else:if receiver_role not in roles:raise ValueError('receiver_role must be "parent", "sibling", or "child"')@@ -78,7 +63,13 @@ async def send(if mode not in ("auto", "follow_up", "steer"):raise ValueError('mode must be "auto", "follow_up", or "steer"')receipt = await host_request("agent_message.send", payload)- _emit_sent_message(receipt, receiver_role)+ receipts = receipt.get("receipts") if isinstance(receipt, dict) else None+ if isinstance(receipts, list):+ for item in receipts:+ if isinstance(item, dict) and "deliveryStatus" in item:+ _emit_sent_message(item)+ else:+ _emit_sent_message(receipt, receiver_role)return receiptdiff --git a/packages/coding-agent/skills/agent-observe/SKILL.md b/packages/coding-agent/skills/agent-observe/SKILL.mdindex a8116f326a..b68386c3cb 100644--- a/packages/coding-agent/skills/agent-observe/SKILL.md+++ b/packages/coding-agent/skills/agent-observe/SKILL.md@@ -1,14 +1,16 @@---name: agent-observe-description: Read-only observation of active Prime Agent sessions through the local daemon. Use to list agents, inspect session status, and read bounded recent-message previews without mutating other sessions.+description: Read-only observation of an agent's parent, siblings, and direct children. Use to inspect family status and bounded recent-message previews without mutating sessions.---# Agent Observe-Observe active Prime Agent sessions through the local daemon. This skill is-read-only: it can list sessions, inspect one session, and fetch bounded recent-message previews. It cannot prompt, steer, clear, kill, rename, or otherwise-mutate another session.+Observe the current agent's nuclear family through the local daemon: parent,+siblings, direct children, and self. Observation is currently limited to family+members in the same worker; root siblings in other workers are not observable yet.+This skill is read-only: it can list family sessions, inspect one session, and fetch+bounded recent message previews. It cannot prompt, steer, clear, kill, rename, or+otherwise mutate another session.Call directly from the kernel:@@ -27,12 +29,9 @@ if child is not None:- `await agent_observe.list_agents()` returns `current` and `agents`. Eachagent includes active session id, session id, optional name, runtime kind,cwd, status, streaming state, message count, pending count, and a latest- message preview. This includes live subagents and successful completed- subagents retained by an open parent. For the current parent session's direct- children, prefer `await rlm.list_subagents()` over filtering this global- list. Every RLM child gets a readable unique `session_name`, or the- orchestrator can choose one with `rlm("task", name="api-reviewer")`; use that- name directly as an observation target.+ message preview. The list is restricted to self, parent, siblings, and direct+ children. For direct children, `await rlm.list_subagents()` also exposes+ parent-owned lifecycle handles.- `await agent_observe.get_agent(target)` returns `agent`, where `agent`contains one agent summary. `target` is resolved like other live-sessionselectors: active id, session id/name, or unambiguous suffix.@@ -43,6 +42,8 @@ if child is not None:## Safety- This skill is read-only and exposes no mutation commands.+- Targets outside the nuclear family are rejected; transcript reads follow the+ same family rule as messaging.- Message access is bounded by count and per-message character limit.- Prefer status and recent previews for orchestration. Ask the user beforeusing observed context to steer or message another session.diff --git a/packages/coding-agent/src/core/agent-messages.ts b/packages/coding-agent/src/core/agent-messages.tsindex 25c5746261..fd64802176 100644--- a/packages/coding-agent/src/core/agent-messages.ts+++ b/packages/coding-agent/src/core/agent-messages.ts@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";import type { AgentMessage } from "@earendil-works/pi-agent-core";import type { HostRequestHandler } from "./kernel/index.js";import type { CustomMessage } from "./messages.js";+import { canonicalSessionPath } from "./session-lease.js";export const AGENT_MESSAGE_CUSTOM_TYPE = "agent_message";export const AGENT_MESSAGE_SKILL_NAME = "agent-message";@@ -19,6 +20,8 @@ export type AgentSessionMessageRuntimeKind = "top-level" | "subagent";export type AgentFamilyStatus = "running" | "idle" | "inactive";export type AgentFamilyRelationship = "parent" | "sibling" | "child";+export const AGENT_FAMILY_REACH_ERROR = "Agent reach is limited to parent, siblings, and children";+export interface AgentSessionMessageEndpoint {activeSessionId: string;sessionId: string;@@ -61,6 +64,7 @@ export interface AgentSessionMessageAgentSummary extends AgentSessionMessageEndpparentSessionPath?: string;rlmDepth?: number;status?: AgentFamilyStatus;+ rlmChildRegistryStatus?: "running" | "completed" | "deleted";}export interface AgentSessionMessageListResult {@@ -168,6 +172,28 @@ export interface AgentSessionMessageSafetyStatus {rateLimitRefillMs: number;}+/**+ * Structural reservation key for sibling-scoped session names. JSON encoding keeps+ * parent paths and names containing delimiter characters from colliding into one key;+ * the worker- and supervisor-side reservation maps must never diverge in encoding.+ */+export function sessionNameReservationKey(input: {+ name: string;+ depth: number;+ parentSessionId?: string;+ parentSessionPath?: string;+}): string {+ const [parentType, parentValue] =+ input.depth === 0+ ? ["root", ""]+ : input.parentSessionPath+ ? ["path", canonicalSessionPath(input.parentSessionPath)]+ : input.parentSessionId+ ? ["id", input.parentSessionId]+ : ["root", ""];+ return JSON.stringify([input.depth, parentType, parentValue, input.name]);+}+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`;}@@ -281,6 +307,27 @@ function isAgentFamilyParent(parent: AgentFamilyCatalogEntry, child: AgentFamily);}+/** Pure nuclear-family policy over persisted parent-edge snapshots. */+export function agentFamilyRelationship(+ current: AgentFamilyCatalogEntry,+ target: AgentFamilyCatalogEntry,+): AgentFamilyRelationship | undefined {+ if (current.id === target.id) return undefined;+ if (isAgentFamilyParent(target, current)) return "parent";+ if (isAgentFamilyParent(current, target)) return "child";+ if (current.depth === target.depth && sameAgentFamilyParent(current, target, [current, target])) return "sibling";+ return undefined;+}++export function assertAgentFamilyReach(+ current: AgentFamilyCatalogEntry,+ target: AgentFamilyCatalogEntry,+): AgentFamilyRelationship {+ const relationship = agentFamilyRelationship(current, target);+ if (!relationship) throw new Error(AGENT_FAMILY_REACH_ERROR);+ return relationship;+}+export function createAgentSessionMessageId(): string {return `agentmsg_${randomUUID()}`;}@@ -504,11 +551,10 @@ export class AgentSessionMessageRateLimiter {}export function createAgentMessageHostHandlers(- controller: AgentSessionMessageController,+ controller: Pick<AgentSessionMessageController, "roster" | "sendAgentMessage" | "awaitPendingChildPublication">,): Record<string, HostRequestHandler> {return {- "agent_message.list": async () => (await controller.listAgents()) as unknown as Record<string, unknown>,- "agent_message.roster": async () => {+ "agent_message.list_agents": 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>;},@@ -518,30 +564,35 @@ export function createAgentMessageHostHandlers(}let target: string;if (typeof payload.target === "string") {- target = payload.target;- if (target.trim().toLowerCase() === "all") {- if (!controller.roster) throw new Error("agent family roster is not available in this session");- const roster = await controller.roster();- const results = await Promise.allSettled(- roster.entries.map((entry) =>- controller.sendAgentMessage({- target: entry.id,- message: payload.message as string,- deliveryMode: normalizeAgentSessionMessageDeliveryMode(payload.mode),- receiverRole: entry.relationship,- }),- ),- );- const receipts = results.map((result, index) =>- result.status === "fulfilled"- ? result.value- : {- target: roster.entries[index]!.id,- error: result.reason instanceof Error ? result.reason.message : String(result.reason),- },+ if (payload.target !== "all") {+ throw new Error(+ "positional agent_message.send targets are not supported; use receiver_role and receiver_name",);- return { receipts } as unknown as Record<string, unknown>;}+ if (payload.receiver_role !== undefined || payload.receiver_name !== undefined) {+ throw new Error("agent_message.send broadcast cannot be combined with receiver_role/receiver_name");+ }+ if (!controller.roster) throw new Error("agent family roster is not available in this session");+ const roster = await controller.roster();+ const results = await Promise.allSettled(+ roster.entries.map((entry) =>+ controller.sendAgentMessage({+ target: entry.id,+ message: payload.message as string,+ deliveryMode: normalizeAgentSessionMessageDeliveryMode(payload.mode),+ receiverRole: entry.relationship,+ }),+ ),+ );+ const receipts = results.map((result, index) =>+ result.status === "fulfilled"+ ? result.value+ : {+ target: roster.entries[index]!.id,+ error: result.reason instanceof Error ? result.reason.message : String(result.reason),+ },+ );+ return { receipts } as unknown as Record<string, unknown>;} else {const role = payload.receiver_role;if (role !== "parent" && role !== "sibling" && role !== "child") {@@ -579,9 +630,7 @@ export function createAgentMessageHostHandlers(target,message: payload.message,deliveryMode: normalizeAgentSessionMessageDeliveryMode(payload.mode),- ...(typeof payload.target === "string"- ? {}- : { receiverRole: payload.receiver_role as AgentFamilyRelationship }),+ receiverRole: payload.receiver_role as AgentFamilyRelationship,})) as unknown as Record<string, unknown>;},};diff --git a/packages/coding-agent/src/core/agent-observe.ts b/packages/coding-agent/src/core/agent-observe.tsindex e68a08b45a..045be77572 100644--- a/packages/coding-agent/src/core/agent-observe.ts+++ b/packages/coding-agent/src/core/agent-observe.ts@@ -60,7 +60,7 @@ export interface AgentObserveMessagePreview {}export interface AgentObserveController {- listAgents(): AgentObserveListResult;+ listAgents(): AgentObserveListResult | Promise<AgentObserveListResult>;getAgent(target: string): AgentObserveAgentSnapshot | Promise<AgentObserveAgentSnapshot>;recentMessages(input: AgentObserveRecentMessagesInput,diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 22c49a775b..fedef724ff 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -180,6 +180,8 @@ import {type CustomMessage,createCompactionOutcomeMessage,createHeartbeatPromptMessage,+ createRlmChildFailureMessage,+ createRlmChildTerminalNoticeMessage,createSessionSlashCommandMessage,createSessionSlashCommandResultMessage,HEARTBEAT_PROMPT_CUSTOM_TYPE,@@ -939,6 +941,8 @@ interface RlmChildRun {publication: AgentMessageDeferred;/** Child session, once its runtime exists. Used to cancel nested child runs. */session?: AgentSession;+ /** True once the detached run task has finished its catch and cleanup paths. */+ settled: boolean;/** Selector snapshot for a delete admitted while runtime startup was still pending. */detachedDeletion?: RlmSubagentRegistryEntry;/** Re-emits the run's rlm_child_update snapshot with its current status. */@@ -1205,6 +1209,7 @@ export class AgentSession {private _rlmParentNodeId?: string;private _rlmParentAgent?: string;private _repliedToParentSinceTask: boolean | undefined;+ private _parentReplyCount = 0;private _subagentRuntimeHost?: SubagentRuntimeHost;private _activeRlmChildRuns = new Map<string, RlmChildRun>();private _pendingRlmSubagentSessionNames = new Set<string>();@@ -3059,9 +3064,7 @@ export class AgentSession {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":+ case "agent_message.list_agents":if (!this._agentMessageController.roster)throw new Error("agent family roster is not available in this session");return this._agentMessageController.roster();@@ -3091,7 +3094,7 @@ export class AgentSession {| AgentObserveListResult| AgentObserveAgentSnapshot| AgentObserveRecentMessagesResult- | Promise<AgentObserveAgentSnapshot | AgentObserveRecentMessagesResult> {+ | Promise<AgentObserveListResult | AgentObserveAgentSnapshot | AgentObserveRecentMessagesResult> {const controller = this._agentObserveController;if (!controller) {throw new Error("agent observation is not available in this session");@@ -4455,7 +4458,7 @@ export class AgentSession {async acceptAgentMessagePrompt(text: string, options?: PromptOptions): Promise<void> {const customMessage =options?.customMessage && isAgentSessionMessage(options.customMessage) ? options.customMessage : undefined;- return this._prompt(text, {+ await this._prompt(text, {...options,expandPromptTemplates: false,skipInputHandlers: true,@@ -4464,6 +4467,7 @@ export class AgentSession {agentMessageId: options?.agentMessageId ?? customMessage?.details.id ?? parseAgentSessionMessagePromptId(text),customMessage,});+ if (customMessage?.details.fromRelationship === "parent") this._repliedToParentSinceTask = false;}async queueAgentMessagePrompt(@@ -4477,12 +4481,15 @@ export class AgentSession {agentMessageId,message: customMessage,});+ if (customMessage?.details.fromRelationship === "parent") this._repliedToParentSinceTask = false;return true;}- return this._queuePreparedPrompt("followUp", text, undefined, {+ const queued = await this._queuePreparedPrompt("followUp", text, undefined, {agentMessageId,message: customMessage,});+ if (queued && customMessage?.details.fromRelationship === "parent") this._repliedToParentSinceTask = false;+ return queued;}async promptHeartbeat(job: AgentCronJob, options?: PromptOptions): Promise<void> {@@ -8702,10 +8709,8 @@ export class AgentSession {Object.assign(handlers,createAgentMessageHostHandlers({- listAgents: async () =>- (await this.handleAgentMessageHostRequest("agent_message.list")) as AgentSessionMessageListResult,roster: async () =>- (await this.handleAgentMessageHostRequest("agent_message.roster")) as AgentFamilyRosterResult,+ (await this.handleAgentMessageHostRequest("agent_message.list_agents")) as AgentFamilyRosterResult,awaitPendingChildPublication: (selector) => this._awaitPendingRlmChildPublication(selector),sendAgentMessage: async (input) => {const receipt = (await this.handleAgentMessageHostRequest("agent_message.send", {@@ -8716,14 +8721,21 @@ export class AgentSession {if (this._rlmDepth > 0) {let addressedParent = input.receiverRole === "parent";if (input.receiverRole === undefined && this._agentMessageController?.roster) {- const roster = await this._agentMessageController.roster();- addressedParent = roster.entries.some(- (entry) =>- entry.relationship === "parent" &&- (entry.id === input.target || entry.name === input.target),- );+ try {+ const roster = await this._agentMessageController.roster();+ addressedParent = roster.entries.some(+ (entry) =>+ entry.relationship === "parent" &&+ (entry.id === input.target || entry.name === input.target),+ );+ } catch {+ addressedParent = false;+ }+ }+ if (addressedParent) {+ this._repliedToParentSinceTask = true;+ this._parentReplyCount += 1;}- if (addressedParent) this._repliedToParentSinceTask = true;}return receipt;},@@ -9042,7 +9054,10 @@ export class AgentSession {private async _awaitPendingRlmChildPublication(selector: string): Promise<string | undefined> {const run = [...this._activeRlmChildRuns.values()].find(- (candidate) => candidate.id === selector || candidate.sessionName === selector,+ (candidate) =>+ (candidate.status === "queued" || candidate.status === "running" || candidate.status === "done") &&+ !candidate.detachedDeletion &&+ (candidate.id === selector || candidate.sessionName === selector),);if (!run) return undefined;await run.publication.promise;@@ -9072,7 +9087,7 @@ export class AgentSession {const subagents: RlmListSubagentsResult["subagents"] = [];const recorded = new Set<string>();for (const run of this._activeRlmChildRuns.values()) {- if (this._deletingRlmChildren.has(run.id) || run.status === "error" || run.status === "cancelled") {+ if (this._deletingRlmChildren.has(run.id) || run.detachedDeletion || run.status === "cancelled") {continue;}const daemonChild = daemonChildren.get(run.id);@@ -9082,7 +9097,7 @@ export class AgentSession {session_id: daemonChild?.sessionId ?? run.session?.sessionId ?? null,session_name: daemonChild?.sessionName ?? run.session?.sessionName ?? run.sessionName,session_dir: run.sessionDir,- status: run.status === "done" ? "completed" : "running",+ status: run.status === "done" ? "completed" : run.status === "error" ? "error" : "running",});recorded.add(run.id);}@@ -9126,7 +9141,7 @@ export class AgentSession {session_id: daemonChild.sessionId,session_name: daemonChild.sessionName ?? createDefaultRlmSubagentSessionName("", childId),session_dir: daemonChild.sessionDir,- status: "completed",+ status: daemonChild.rlmChildRegistryStatus === "completed" ? "completed" : "error",});}return { subagents };@@ -9328,6 +9343,11 @@ export class AgentSession {this._emitRlmSubagentRemoval(subagent);}const liveSession = run.session;+ if (run.status === "error" && !liveSession && run.settled) {+ this._deletedRlmChildIds.add(childId);+ this._removeRlmSubagentTracking(childId, run);+ return { subagent };+ }if (liveSession) {try {await this._deleteRlmSubagentSession(childId, liveSession);@@ -9617,6 +9637,7 @@ export class AgentSession {sessionName,sessionDir: childSessionDir,status: "queued",+ settled: false,abort: noopRlmChildAbort,publication: createAgentMessageDeferred(),};@@ -9669,6 +9690,15 @@ export class AgentSession {onSessionPublished: publishChildSession,};+ const injectTerminalMessage = async (message: CustomMessage): Promise<void> => {+ await this._promptInjectedMessage(message.content as string, message, {+ streamingBehavior: "followUp",+ queueIfBusy: true,+ returnAfterAccepted: true,+ suppressAutonomousContinuation: true,+ }).catch(() => undefined);+ };+// Runtime startup and the task run are deliberately detached. The public// spawn resolves at admission, while this task owns live tracking, usage,// retention, cancellation, and late-startup cleanup.@@ -9677,6 +9707,7 @@ export class AgentSession {try {childRuntime = await this._createRlmSubagentRuntime(subagentOptions);const child = childRuntime.session;+ if (run.status === "cancelled") throw new Error(run.error ?? "RLM child cancelled");if (child.sessionName !== sessionName) child.setSessionName(sessionName);publishChildSession(child);throwIfCancelled();@@ -9759,6 +9790,7 @@ export class AgentSession {timestamp: Date.now(),};throwIfCancelled();+ const parentReplyCountBeforeRun = child._parentReplyCount;await child.promptAndWait(content, {expandPromptTemplates: false,source: "extension",@@ -9769,6 +9801,17 @@ export class AgentSession {durationMs = Date.now() - startedAt;activity = undefined;emitChildUpdate();+ if (!run.detachedDeletion && child._parentReplyCount === parentReplyCountBeforeRun) {+ const lastAssistantText = child.getLastAssistantText();+ await injectTerminalMessage(+ createRlmChildTerminalNoticeMessage({+ kind: "completed_without_reply",+ childId: run.id,+ sessionName,+ lastAssistantTextPreview: lastAssistantText ? compactRlmText(lastAssistantText) : undefined,+ }),+ );+ }if (!this.registerRlmChildSession(run.id, child)) {if (childRuntime && this._subagentRuntimeHost?.releaseRlmSubagentRuntime) {await this._subagentRuntimeHost@@ -9789,15 +9832,47 @@ export class AgentSession {activity = undefined;emitChildUpdate();if (!run.detachedDeletion) {+ if (run.status === "error") {+ await injectTerminalMessage(+ createRlmChildFailureMessage({+ childId: run.id,+ sessionName,+ error: run.error ?? "unknown error",+ }),+ );+ } else if (run.status === "cancelled") {+ await injectTerminalMessage(+ createRlmChildTerminalNoticeMessage({+ kind: "cancelled",+ childId: run.id,+ sessionName,+ reason: run.error,+ }),+ );+ }+ }+ if (!run.detachedDeletion && childSession && this._subagentRuntimeHost?.releaseRlmSubagentRuntime) {+ try {+ await this._subagentRuntimeHost.releaseRlmSubagentRuntime(+ childRuntime ?? { session: childSession },+ subagentOptions,+ run.status === "cancelled" ? "cancelled" : "error",+ );+ if (run.status === "cancelled" && !this._disposed && !this._disposing) {+ this._deletedRlmChildIds.add(run.id);+ this._removeRlmSubagentTracking(run.id);+ }+ } catch {+ await childSession?.disposeAsync().catch(() => undefined);+ }+ } else if (!run.detachedDeletion) {try {if (childRuntime && this._subagentRuntimeHost) {await this._subagentRuntimeHost.deleteRlmSubagentRuntime(run.id, childRuntime.session);} else if (childSession) {await childSession.disposeAsync();- } else {- return;}- if (!this._disposed && !this._disposing) {+ if (run.status === "cancelled" && !this._disposed && !this._disposing) {this._deletedRlmChildIds.add(run.id);this._removeRlmSubagentTracking(run.id);}@@ -9823,12 +9898,16 @@ export class AgentSession {run.abort = noopRlmChildAbort;run.unsubscribe = undefined;run.session = undefined;- } else {+ } else if (run.status !== "error" || run.detachedDeletion) {this._removeRlmSubagentTracking(run.id, run);+ } else {+ run.unsubscribe?.();+ run.abort = noopRlmChildAbort;+ run.unsubscribe = undefined;}}+ run.settled = true;}- // Follow-up: deliver post-admission startup failures to the parent over a2a.})().catch(() => undefined);return {diff --git a/packages/coding-agent/src/core/extensions/loader.ts b/packages/coding-agent/src/core/extensions/loader.tsindex d974d5c79d..c22dc49628 100644--- a/packages/coding-agent/src/core/extensions/loader.ts+++ b/packages/coding-agent/src/core/extensions/loader.ts@@ -248,9 +248,9 @@ function createExtensionAPI(runtime.appendEntry(customType, data);},- setSessionName(name: string): void {+ setSessionName(name: string): void | Promise<void> {runtime.assertActive();- runtime.setSessionName(name);+ return runtime.setSessionName(name);},getSessionName(): string | undefined {diff --git a/packages/coding-agent/src/core/messages.ts b/packages/coding-agent/src/core/messages.tsindex 0a4535e73d..1174bdb97a 100644--- a/packages/coding-agent/src/core/messages.ts+++ b/packages/coding-agent/src/core/messages.ts@@ -31,6 +31,8 @@ export const IPYTHON_STATE_RESTORED_CUSTOM_TYPE = "ipython_state_restored";export const SESSION_SLASH_COMMAND_CUSTOM_TYPE = "session_slash_command";export const SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE = "session_slash_command_result";export const COMPACTION_OUTCOME_CUSTOM_TYPE = "compaction_outcome";+export const RLM_CHILD_FAILURE_CUSTOM_TYPE = "rlm_child_failure";+export const RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE = "rlm_child_terminal_notice";export interface SessionSlashCommandDetails {command: SessionSlashCommand;@@ -71,6 +73,58 @@ export interface CompactionOutcomeMessage extends CustomMessage<CompactionOutcomdetails: CompactionOutcomeDetails;}+export interface RlmChildFailureDetails {+ childId: string;+ sessionName: string;+ error: string;+}++export type RlmChildTerminalNoticeDetails =+ | {+ kind: "cancelled";+ childId: string;+ sessionName: string;+ reason?: string;+ }+ | {+ kind: "completed_without_reply";+ childId: string;+ sessionName: string;+ lastAssistantTextPreview?: string;+ };++export function createRlmChildFailureMessage(+ details: RlmChildFailureDetails,+ timestamp = Date.now(),+): CustomMessage<RlmChildFailureDetails> {+ return {+ role: "custom",+ customType: RLM_CHILD_FAILURE_CUSTOM_TYPE,+ content: `RLM child ${details.sessionName} (${details.childId}) failed: ${details.error}`,+ display: true,+ details,+ timestamp,+ };+}++export function createRlmChildTerminalNoticeMessage(+ details: RlmChildTerminalNoticeDetails,+ timestamp = Date.now(),+): CustomMessage<RlmChildTerminalNoticeDetails> {+ const content =+ details.kind === "cancelled"+ ? `RLM child ${details.sessionName} (${details.childId}) was cancelled${details.reason ? `: ${details.reason}` : ""}`+ : `RLM child ${details.sessionName} (${details.childId}) completed without sending a reply${details.lastAssistantTextPreview ? `. Last assistant text: ${details.lastAssistantTextPreview}` : ""}`;+ return {+ role: "custom",+ customType: RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,+ content,+ display: true,+ details,+ timestamp,+ };+}+/*** Message type for bash executions via the ! command.*/diff --git a/packages/coding-agent/src/core/prompts/rlm.ts b/packages/coding-agent/src/core/prompts/rlm.tsindex 3746c51473..7e023d5278 100644--- a/packages/coding-agent/src/core/prompts/rlm.ts+++ b/packages/coding-agent/src/core/prompts/rlm.ts@@ -30,7 +30,7 @@ const IPYTHON_CONTROL_PROMPT = ["","Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, IPython kernel, and native call interface exposed to the model.","",- "RLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm('sub-task')`; admission returns a child handle immediately. Results arrive only through explicit `agent_message` replies or files, never as an `rlm()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.",+ "RLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm('sub-task')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.",].join("\n");export interface ChildAgentDoctrineOptions {@@ -60,6 +60,8 @@ export function buildChildAgentDoctrine(options: ChildAgentDoctrineOptions): strexport function buildRlmPrompt(options: RlmPromptOptions): string {const { cwd, skillsDir, messagesPath } = options;const installedSkills = options.installedSkills ?? [];+ const hasAgentMessage = installedSkills.includes("agent_message");+ const hasAgentObserve = installedSkills.includes("agent_observe");const allowRecursion = options.allowRecursion ?? true;const depth = options.depth ?? 0;const activeTools = options.activeTools ?? [];@@ -110,6 +112,16 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {if (skillLines.length > 0) {parts.push("", ...skillLines);}+ if (hasAgentMessage) {+ parts.push(+ "Agent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.",+ );+ }+ if (hasAgentObserve) {+ parts.push(+ "Agent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.",+ );+ }if (allowRecursion && hasIpython) {parts.push(@@ -117,8 +129,23 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {"A callable `rlm` is already in your global namespace. `await rlm('sub-task')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.","Choose a stable child name with `await rlm('sub-task', name='api-reviewer')`; names must be unique among siblings. If omitted, the host generates a readable unique name.","A child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`.",- "Children reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.",- "Use `await agent_message.roster()` to discover family and `await rlm.list_subagents()` to recover direct child handles. Inspect a child's rollout with `agent_observe` or read files it wrote; use `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.",+ );+ if (hasAgentMessage) {+ parts.push(+ "Children reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.",+ "Use `await agent_message.list_agents()` to discover family and `await rlm.list_subagents()` to recover direct child handles. Use `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.",+ );+ } else {+ parts.push("Use `await rlm.list_subagents()` to recover direct child handles after admission.");+ }+ if (hasAgentObserve) {+ parts.push(+ "Use `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.",+ );+ } else {+ parts.push("Inspect files a child wrote when you need to collect its work without an observation capability.");+ }+ parts.push("Spawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.",);}@@ -144,15 +171,27 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {* uses. The subagent-spec menu itself renders just after this, inside the* harness-state block.*/-export function buildSubagentGuidance(options: { includeRefineExamples?: boolean } = {}): string {+export function buildSubagentGuidance(+ options: { includeRefineExamples?: boolean; hasAgentMessage?: boolean; hasAgentObserve?: boolean } = {},+): string {const lines = ["# Delegating to sub-agents","",- "Spawn independent, self-contained work with `handle = await rlm('task', name='worker')`. This returns at admission, not completion; keep the handle to observe, message, stop, or inspect the child later.",- "Ask for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.",- "Use `await rlm.list_subagents()` after kernel restart or compaction. Use `agent_observe` for bounded transcript inspection, or have children write files and read those files for fan-in.",- "Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.",+ "Spawn independent, self-contained work with `handle = await rlm('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.",];+ if (options.hasAgentMessage) {+ lines.push(+ "Ask for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.",+ );+ }+ lines.push("Use `await rlm.list_subagents()` after kernel restart or compaction.");+ if (options.hasAgentObserve) {+ lines.push("Use `agent_observe` for bounded transcript inspection.");+ }+ lines.push(+ "Have children write files and read those files for fan-in.",+ "Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.",+ );if (options.includeRefineExamples ?? true) {lines.push("Persist genuinely reusable delegation patterns with `await refine.run()`.");}diff --git a/packages/coding-agent/src/core/rlm-runtime.ts b/packages/coding-agent/src/core/rlm-runtime.tsindex 1ee8aa8fc1..e89472fce0 100644--- a/packages/coding-agent/src/core/rlm-runtime.ts+++ b/packages/coding-agent/src/core/rlm-runtime.ts@@ -18,7 +18,7 @@ export interface RlmSpawnHandle {model: string;}-export type RlmSubagentRegistryStatus = "running" | "completed";+export type RlmSubagentRegistryStatus = "running" | "completed" | "error";export interface RlmSubagentRegistryEntry {rlm_child_id: string;diff --git a/packages/coding-agent/src/core/system-prompt.ts b/packages/coding-agent/src/core/system-prompt.tsindex 32bf1631e5..23b78de367 100644--- a/packages/coding-agent/src/core/system-prompt.ts+++ b/packages/coding-agent/src/core/system-prompt.ts@@ -127,7 +127,14 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions): string {// menu, so the model reads when/why to delegate and then sees the concrete subagent// specs it can match against — the same ordering as Claude Code's Agent tool.if ((allowRecursion ?? true) && hasIpython) {- prompt += `\n\n${buildSubagentGuidance({ includeRefineExamples: hasRefineSkill })}`;+ const visiblePythonSkillNames = new Set(+ getPythonSkillRuntimeInfo(visibleSkills).map((skill) => skill.importName),+ );+ prompt += `\n\n${buildSubagentGuidance({+ includeRefineExamples: hasRefineSkill,+ hasAgentMessage: visiblePythonSkillNames.has("agent_message"),+ hasAgentObserve: visiblePythonSkillNames.has("agent_observe"),+ })}`;}if (harnessState) {diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 6f13e4d84e..e9fdb7c348 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -22,7 +22,7 @@ import {} from "node:fs";import { readFile } from "node:fs/promises";import { createConnection, createServer, type Server, type Socket } from "node:net";-import { dirname, join, resolve } from "node:path";+import { dirname, isAbsolute, join, resolve } from "node:path";import { type Api, getLogger, type Model } from "@earendil-works/pi-ai";import { createCliSubprocessEnv, createCliSubprocessLaunchSpec } from "../../cli/subprocess-launch.js";import {@@ -33,6 +33,7 @@ import {VERSION,} from "../../config.js";import {+ AGENT_FAMILY_REACH_ERROR,AGENT_MESSAGE_SOURCE,type AgentFamilyCatalogEntry,type AgentFamilyRelationship,@@ -46,6 +47,8 @@ import {AgentSessionMessageRateLimiter,type AgentSessionMessageReceipt,type AgentSessionMessageSender,+ agentFamilyRelationship,+ assertAgentFamilyReach,assertAgentMessageQueueCapacity,assertAgentSessionNameAvailable,assertDirectAgentMessageTarget,@@ -57,9 +60,11 @@ import {DEFAULT_AGENT_MESSAGE_MAX_PENDING_PER_SESSION,DEFAULT_AGENT_MESSAGE_RATE_LIMIT_CAPACITY,DEFAULT_AGENT_MESSAGE_RATE_LIMIT_REFILL_MS,+ formatAgentSessionNameUnavailable,isAgentSessionMessagePrompt,normalizeAgentSessionMessage,resolveAgentSessionMessageStreamingBehavior,+ sessionNameReservationKey,} from "../../core/agent-messages.js";import {type AgentObserveAgentSnapshot,@@ -103,7 +108,7 @@ import {type SessionPassivationSnapshot,} from "../../core/session-action-store.js";import { deleteSessionFile } from "../../core/session-file-actions.js";-import { acquireSessionLease, type SessionLease } from "../../core/session-lease.js";+import { acquireSessionLease, canonicalSessionPath, type SessionLease } from "../../core/session-lease.js";import {readSessionInfo,resolveSessionRlmDepth,@@ -409,6 +414,15 @@ export async function runDaemonMode(options: DaemonModeOptions): Promise<never>return new Promise(() => {});}+export function isTerminalRemoteAgentMessageError(error: unknown): error is Error {+ return (+ error instanceof Error &&+ (error.message.startsWith("Unknown active session:") ||+ error.message.startsWith("Ambiguous") ||+ error.message === AGENT_FAMILY_REACH_ERROR)+ );+}+export class AgentDaemon {private server?: Server;private shuttingDown = false;@@ -484,6 +498,7 @@ export class AgentDaemon {// Sessions inserted into `sessions` but still awaiting extension binding;// visible to host controllers during bind, excluded from targeting.private readonly bindingSessions = new Set<string>();+ private readonly pendingSessionNames = new Set<string>();private restoreActiveSessionId: string | undefined;private supervisorMonitorTimer?: ReturnType<typeof setTimeout>;private supervisorFenceTimer?: ReturnType<typeof setTimeout>;@@ -1037,7 +1052,7 @@ export class AgentDaemon {): Promise<void> => {for (const entry of entries) {const sessionKey = resolve(entry.sessionFile);- if (entry.status !== "completed" || visited.has(sessionKey)) continue;+ if (entry.status === "deleted" || visited.has(sessionKey)) continue;visited.add(sessionKey);const info = await readSessionInfo(entry.sessionFile);if (!info) continue;@@ -1116,7 +1131,7 @@ export class AgentDaemon {sessionName: passive.info.name ?? passive.entry.sessionName,model: passive.entry.model ? `${passive.entry.model.provider}/${passive.entry.model.modelId}` : undefined,label: rlmChildLabel(passive.entry.prompt ?? ""),- status: "done",+ status: passive.entry.status === "completed" ? "done" : "error",sessionDir: passive.entry.sessionDir,});seenChildIds.add(passive.entry.childId);@@ -1202,9 +1217,6 @@ export class AgentDaemon {lastEventSequence: 0,clientEnv,};- if (name) {- await this.setStateSessionName(state, name);- }this.sessions.set(state.activeSessionId, state);this.bindingSessions.add(state.activeSessionId);let completeBinding!: () => void;@@ -1214,6 +1226,9 @@ export class AgentDaemon {this.bindingCompletions.set(state.activeSessionId, bindingCompletion);onStateCreated?.(state);try {+ if (name) {+ await this.setStateSessionName(state, name);+ }await bindActiveSessionState(state, {broadcast: (targetSessionState, message) => this.broadcastToSession(targetSessionState, message),createConnectionState: (targetSessionState) => this.createConnectionState(targetSessionState),@@ -2224,6 +2239,16 @@ export class AgentDaemon {});},releaseRlmSubagentRuntime: async (runtime, options, status) => {+ // Persist the deletion boundary first, but never let a registry failure+ // strand the cancelled child as a stale resident session.+ let deletionError: unknown;+ if (status === "cancelled") {+ try {+ await this.recordRlmSubagentDeletion(parentState, options.id);+ } catch (error) {+ deletionError = error;+ }+ }const state = [...this.sessions.values()].find((candidate) =>candidate.runtime.metadata.kind === "subagent" &&@@ -2236,6 +2261,7 @@ export class AgentDaemon {} else {await runtime.session.disposeAsync();}+ if (deletionError !== undefined) throw deletionError;},deleteRlmSubagentRuntime: async (childId, session) => {const state = [...this.sessions.values()].find(@@ -2807,7 +2833,7 @@ export class AgentDaemon {listAgents: () => this.createAgentMessageListResult(requireCurrentState()),roster: () => this.createAgentFamilyRoster(requireCurrentState()),assertSessionNameAvailable: (input) => this.assertFamilySessionNameAvailable(input),- setSessionName: (name) => this.setStateSessionName(requireCurrentState(), name),+ setSessionName: (name) => this.setStateSessionNameViaSupervisor(requireCurrentState(), name),sendAgentMessage: (input) =>this.sendAgentSessionMessage({targetSelector: input.target,@@ -2834,12 +2860,50 @@ export class AgentDaemon {};}- private createAgentObserveListResult(currentState: ActiveSessionState): AgentObserveListResult {+ private async createAgentObserveListResult(currentState: ActiveSessionState): Promise<AgentObserveListResult> {+ const agents = this.listTargetableSessionStates(currentState)+ .filter(+ (state) =>+ state.activeSessionId === currentState.activeSessionId ||+ this.isAgentFamilyReachable(currentState, state),+ )+ .map((state) => this.createAgentObserveSummary(state, currentState));+ const residentIds = new Set(agents.map((agent) => agent.activeSessionId));+ for (const passive of await this.listPassiveRlmSubagents()) {+ if (residentIds.has(passive.info.id)) continue;+ try {+ assertAgentFamilyReach(this.agentFamilyEntry(currentState), this.passiveAgentFamilyEntry(passive));+ } catch (error) {+ if (error instanceof Error && error.message === AGENT_FAMILY_REACH_ERROR) continue;+ throw error;+ }+ agents.push({+ activeSessionId: passive.info.id,+ sessionId: passive.info.id,+ sessionName: passive.info.name ?? passive.entry.sessionName,+ runtimeKind: "subagent",+ cwd: passive.info.cwd,+ status: "idle",+ isCurrent: false,+ isStreaming: false,+ isCompacting: false,+ attachedClients: 0,+ messageCount: passive.info.messageCount,+ queuedCount: 0,+ isSessionActive: false,+ ...(passive.chain.length === 1 && passive.rootParentState+ ? { parentActiveSessionId: passive.rootParentState.activeSessionId }+ : {}),+ parentSessionId: passive.entry.parentSessionId,+ rlmChildId: passive.entry.childId,+ ...(passive.entry.rlmParentNodeId ? { rlmParentNodeId: passive.entry.rlmParentNodeId } : {}),+ ...(passive.info.firstMessage ? { firstMessage: passive.info.firstMessage } : {}),+ });+ residentIds.add(passive.info.id);+ }return {current: this.createAgentObserveSummary(currentState, currentState),- agents: this.listTargetableSessionStates(currentState).map((state) =>- this.createAgentObserveSummary(state, currentState),- ),+ agents,};}@@ -2847,8 +2911,10 @@ export class AgentDaemon {currentState: ActiveSessionState,target: string,): Promise<AgentObserveAgentSnapshot> {+ const targetState = await this.getOrHydrateAuthorizedAgentFamilyTarget(currentState, target);+ this.assertAgentFamilyReachable(currentState, targetState);return {- agent: this.createAgentObserveSummary(await this.getOrHydrateBoundSessionState(target), currentState),+ agent: this.createAgentObserveSummary(targetState, currentState),};}@@ -2856,7 +2922,8 @@ export class AgentDaemon {currentState: ActiveSessionState,input: AgentObserveRecentMessagesInput,): Promise<AgentObserveRecentMessagesResult> {- const targetState = await this.getOrHydrateBoundSessionState(input.target);+ const targetState = await this.getOrHydrateAuthorizedAgentFamilyTarget(currentState, input.target);+ this.assertAgentFamilyReachable(currentState, targetState);const limit = normalizeObserveLimit(input.limit);const maxChars = normalizeObserveMaxChars(input.maxChars);const messages = targetState.runtime.session.messages;@@ -3608,8 +3675,7 @@ export class AgentDaemon {if (!name) {throw new Error("Session name cannot be empty");}- await this.assertStateSessionNameAvailable(state, name);- state.runtime.session.setSessionName(name);+ await this.setStateSessionName(state, name);return success(command.id, "rename", summaryForActiveSession(state));}@@ -3623,19 +3689,33 @@ export class AgentDaemon {throw new Error("Session name cannot be empty");}if (state) {- await this.assertStateSessionNameAvailable(state, name);- state.runtime.session.setSessionName(name);+ await this.setStateSessionName(state, 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);+ await this.withSessionNameReservation(+ {+ name,+ depth,+ ...(depth > 0 && info.parentSessionPath ? { parentSessionPath: info.parentSessionPath } : {}),+ },+ async () => {+ await this.assertFamilySessionNameAvailable(+ {+ name,+ depth,+ ...(depth > 0 && info.parentSessionPath+ ? { parentSessionPath: info.parentSessionPath }+ : {}),+ ignoreSessionId: info.id,+ },+ undefined,+ true,+ );+ SessionManager.open(command.sessionPath).appendSessionInfo(name);+ },+ );}return success(command.id, "rename_saved_session");}@@ -3866,7 +3946,7 @@ export class AgentDaemon {clientId: client.id,senderKey: this.createCliAgentMessageSenderKey(),deliveryMode: command.deliveryMode,- origin: "cli",+ origin: command.agentOrigin === true ? "agent" : "cli",});return success(command.id, "send_message", receipt);}@@ -4368,8 +4448,7 @@ export class AgentDaemon {if (!name) {throw new Error("Session name cannot be empty");}- await this.assertStateSessionNameAvailable(state, name);- state.runtime.session.setSessionName(name);+ await this.setStateSessionName(state, name);return success(command.id, "set_session_name");}@@ -4827,7 +4906,9 @@ export class AgentDaemon {activity: session.isSessionActive ? "working" : "idle",isSessionActive: session.isSessionActive,hasRunningRlmChildren: session.hasRunningRlmChildren?.() ?? false,- hasActiveHeartbeat: this.cronStore.getHeartbeat(state.activeSessionId)?.status === "active",+ hasActiveHeartbeat:+ this.cronStore.getHeartbeat(state.activeSessionId)?.status === "active" ||+ this.cronStore.listRlmHeartbeats(state.activeSessionId).some((job) => job.status === "active"),isStreaming: session.isStreaming,} as SessionSummary),...(metadata.rlmChildId ? { rlmChildId: metadata.rlmChildId } : {}),@@ -4863,6 +4944,7 @@ export class AgentDaemon {rlmDepth: info.rlmDepth ?? entry.rlmDepth,status: "inactive",rlmChildId: entry.childId,+ rlmChildRegistryStatus: entry.status,sessionDir: entry.sessionDir,sessionPath: entry.sessionFile,});@@ -4882,20 +4964,22 @@ export class AgentDaemon {};}- private async createAgentFamilyCatalog(): Promise<AgentFamilyCatalogEntry[]> {- const current = [...this.sessions.values()].find((state) => !this.bindingSessions.has(state.activeSessionId));+ private async createAgentFamilyCatalog(currentState?: ActiveSessionState): Promise<AgentFamilyCatalogEntry[]> {+ const current =+ currentState ?? [...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)] : [])),+ localAgents.flatMap((agent) => (agent.sessionPath ? [canonicalSessionPath(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)),+ (info.rlmDepth ?? (info.parentSessionPath ? -1 : 0)) === 0 &&+ !activePaths.has(canonicalSessionPath(info.path)),).map((info): AgentFamilyCatalogEntry => ({@@ -4903,15 +4987,16 @@ export class AgentDaemon {...(info.name ? { name: info.name } : {}),depth: info.rlmDepth ?? 0,status: "inactive",- sessionPath: resolve(info.path),+ sessionPath: canonicalSessionPath(info.path),}),);const byId = new Map<string, AgentFamilyCatalogEntry>(savedRoots.map((entry) => [entry.id, entry]));const addAgent = (agent: AgentSessionMessageAgentSummary) => {+ const depth = agent.rlmDepth ?? 0;byId.set(agent.sessionId, {id: agent.sessionId,...(agent.sessionName ? { name: agent.sessionName } : {}),- depth: agent.rlmDepth ?? 0,+ depth,status: agent.status ?? "idle",...(agent.runtimeKind === "subagent"? (() => {@@ -4920,55 +5005,121 @@ export class AgentDaemon {return repliedSinceTask === undefined ? {} : { repliedSinceTask };})(): {}),- ...(agent.parentSessionId ? { parentSessionId: agent.parentSessionId } : {}),- ...(agent.parentSessionPath ? { parentSessionPath: resolve(agent.parentSessionPath) } : {}),- ...(agent.sessionPath ? { sessionPath: resolve(agent.sessionPath) } : {}),+ ...(depth > 0 && agent.parentSessionId ? { parentSessionId: agent.parentSessionId } : {}),+ ...(depth > 0 && agent.parentSessionPath+ ? { parentSessionPath: canonicalSessionPath(agent.parentSessionPath) }+ : {}),+ ...(agent.sessionPath ? { sessionPath: canonicalSessionPath(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);+ if (entry && state.runtime.session.sessionFile)+ entry.sessionPath = canonicalSessionPath(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);+ if (entry) entry.sessionPath = canonicalSessionPath(passive.entry.sessionFile);}return [...byId.values()];}private async createAgentFamilyRoster(currentState: ActiveSessionState): Promise<AgentFamilyRosterResult> {- const catalog = await this.createAgentFamilyCatalog();+ const catalog = await this.createAgentFamilyCatalog(currentState);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(), {+ private async assertFamilySessionNameAvailable(+ input: {+ name: string;+ depth: number;+ parentSessionId?: string;+ parentSessionPath?: string;+ ignoreSessionId?: string;+ },+ currentState?: ActiveSessionState,+ ignorePendingReservation = false,+ ): Promise<void> {+ if (!ignorePendingReservation && this.pendingSessionNames.has(sessionNameReservationKey(input))) {+ throw new Error(formatAgentSessionNameUnavailable(input.name, input.depth));+ }+ assertAgentSessionNameAvailable(await this.createAgentFamilyCatalog(currentState), {...input,- ...(input.parentSessionPath ? { parentSessionPath: resolve(input.parentSessionPath) } : {}),+ ...(input.parentSessionPath ? { parentSessionPath: canonicalSessionPath(input.parentSessionPath) } : {}),});}+ private resolveHeaderParentSessionPath(state: ActiveSessionState): string | undefined {+ const session = state.runtime.session;+ const headerParent = session.sessionManager?.getHeader?.()?.parentSession;+ if (!headerParent || isAbsolute(headerParent)) return headerParent;+ return session.sessionFile ? resolve(dirname(session.sessionFile), headerParent) : undefined;+ }+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,- });+ const headerParent = depth > 0 ? this.resolveHeaderParentSessionPath(state) : undefined;+ await this.assertFamilySessionNameAvailable(+ {+ name,+ depth,+ ...(depth > 0 && !headerParent && metadata.parentSessionId+ ? { parentSessionId: metadata.parentSessionId }+ : {}),+ ...(depth > 0 && (headerParent ?? metadata.parentSessionFile)+ ? { parentSessionPath: headerParent ?? metadata.parentSessionFile }+ : {}),+ ignoreSessionId: session.sessionId,+ },+ state,+ true,+ );+ }++ private async withSessionNameReservation<T>(+ input: { name: string; depth: number; parentSessionId?: string; parentSessionPath?: string },+ action: () => Promise<T>,+ ): Promise<T> {+ const key = sessionNameReservationKey(input);+ if (this.pendingSessionNames.has(key)) {+ throw new Error(formatAgentSessionNameUnavailable(input.name, input.depth));+ }+ this.pendingSessionNames.add(key);+ try {+ return await action();+ } finally {+ this.pendingSessionNames.delete(key);+ }+ }++ private async setStateSessionNameViaSupervisor(state: ActiveSessionState, name: string): Promise<void> {+ const supervisorSocketPath = process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];+ if (!this.options.worker || !supervisorSocketPath) {+ return this.setStateSessionName(state, name);+ }+ const client = new DaemonClient(supervisorSocketPath);+ try {+ await client.connect(1000);+ await client.waitForHello(1000);+ const response = await client.request(+ {+ type: "set_session_name",+ activeSessionId: state.activeSessionId,+ name,+ workerToken: this.options.worker.authenticationToken,+ },+ 30_000,+ );+ if (!response.success) throw deserializeDaemonError(response);+ } finally {+ client.close();+ }}private async setStateSessionName(state: ActiveSessionState, name: string): Promise<void> {@@ -4976,8 +5127,26 @@ export class AgentDaemon {if (!normalizedName) {throw new Error("Session name cannot be empty");}- await this.assertStateSessionNameAvailable(state, normalizedName);- state.runtime.session.setSessionName(normalizedName);+ const session = state.runtime.session;+ const metadata = state.runtime.metadata;+ const depth = session.rlmDepth ?? 0;+ const headerParent = depth > 0 ? this.resolveHeaderParentSessionPath(state) : undefined;+ return this.withSessionNameReservation(+ {+ name: normalizedName,+ depth,+ ...(depth > 0 && !headerParent && metadata.parentSessionId+ ? { parentSessionId: metadata.parentSessionId }+ : {}),+ ...(depth > 0 && (headerParent ?? metadata.parentSessionFile)+ ? { parentSessionPath: headerParent ?? metadata.parentSessionFile }+ : {}),+ },+ async () => {+ await this.assertStateSessionNameAvailable(state, normalizedName);+ state.runtime.session.setSessionName(normalizedName);+ },+ );}// Half-bound sessions are hidden from other sessions' listings; the current@@ -5058,19 +5227,113 @@ export class AgentDaemon {}}+ private agentFamilyEntry(state: ActiveSessionState): AgentFamilyCatalogEntry {+ const metadata = state.runtime.metadata;+ const depth = state.runtime.session.rlmDepth ?? 0;+ const headerParent = depth > 0 ? this.resolveHeaderParentSessionPath(state) : undefined;+ const parentSessionPath = depth > 0 ? (headerParent ?? metadata.parentSessionFile) : undefined;+ return {+ id: state.runtime.session.sessionId,+ ...(state.runtime.session.sessionName ? { name: state.runtime.session.sessionName } : {}),+ depth,+ status: "running",+ ...(depth > 0 && !headerParent && metadata.parentSessionId+ ? { parentSessionId: metadata.parentSessionId }+ : {}),+ ...(parentSessionPath ? { parentSessionPath: canonicalSessionPath(parentSessionPath) } : {}),+ ...(state.runtime.session.sessionFile+ ? { sessionPath: canonicalSessionPath(state.runtime.session.sessionFile) }+ : {}),+ };+ }++ private passiveAgentFamilyEntry(passive: PassiveRlmSubagent): AgentFamilyCatalogEntry {+ const entry = passive.entry;+ const depth = passive.info.rlmDepth ?? entry.rlmDepth ?? passive.chain.length;+ const parentSessionPath =+ depth > 0+ ? (entry.parentSessionFile ??+ passive.chain.at(-2)?.sessionFile ??+ passive.rootParentState?.runtime.session.sessionFile ??+ passive.rootInfo?.path)+ : undefined;+ return {+ id: passive.info.id,+ name: passive.info.name ?? entry.sessionName,+ depth,+ status: "idle",+ ...(depth > 0 && entry.parentSessionId ? { parentSessionId: entry.parentSessionId } : {}),+ ...(parentSessionPath ? { parentSessionPath: canonicalSessionPath(parentSessionPath) } : {}),+ sessionPath: canonicalSessionPath(entry.sessionFile),+ };+ }++ private async getOrHydrateAuthorizedAgentFamilyTarget(+ currentState: ActiveSessionState,+ target: string,+ ): Promise<ActiveSessionState> {+ try {+ return this.getBoundSessionState(target);+ } catch (error) {+ if (error instanceof BoundSessionUnavailableError) {+ const targetState = this.getSessionState(target);+ this.assertAgentFamilyReachable(currentState, targetState);+ return this.getOrHydrateBoundSessionState(target);+ }+ if (error instanceof AmbiguousActiveSessionError) {+ const targetState = this.resolveAgentFamilySessionName(currentState, target, error);+ return this.getOrHydrateBoundSessionState(targetState.activeSessionId);+ }+ }+ const passive = await this.findPassiveRlmSubagent(target);+ if (!passive) return this.getOrHydrateBoundSessionState(target);+ assertAgentFamilyReach(this.agentFamilyEntry(currentState), this.passiveAgentFamilyEntry(passive));+ return this.hydratePassiveRlmSubagent(passive);+ }++ private resolveAgentFamilySessionName(+ currentState: ActiveSessionState,+ target: string,+ ambiguity: AmbiguousActiveSessionError,+ ): ActiveSessionState {+ const reachableMatches = new Map(+ [...this.sessions.values()]+ .filter((state) => {+ const session = state.runtime.session;+ return (+ (session.sessionId === target || session.sessionName === target) &&+ (state.activeSessionId === currentState.activeSessionId ||+ this.isAgentFamilyReachable(currentState, state))+ );+ })+ .map((state) => [state.activeSessionId, state]),+ ).values();+ const matches = [...reachableMatches];+ if (matches.length !== 1) throw ambiguity;+ return matches[0]!;+ }++ private isAgentFamilyReachable(currentState: ActiveSessionState, targetState: ActiveSessionState): boolean {+ try {+ assertAgentFamilyReach(this.agentFamilyEntry(currentState), this.agentFamilyEntry(targetState));+ return true;+ } catch (error) {+ if (error instanceof Error && error.message === AGENT_FAMILY_REACH_ERROR) return false;+ throw error;+ }+ }++ private assertAgentFamilyReachable(currentState: ActiveSessionState, targetState: ActiveSessionState): void {+ if (currentState.activeSessionId === targetState.activeSessionId) return;+ assertAgentFamilyReach(this.agentFamilyEntry(currentState), this.agentFamilyEntry(targetState));+ }+private agentMessageRelationship(fromState: ActiveSessionState | undefined,targetState: ActiveSessionState,): AgentFamilyRelationship | undefined {if (!fromState) return undefined;- const from = fromState.runtime.metadata;- const target = targetState.runtime.metadata;- const fromSessionId = fromState.runtime.session.sessionId;- const targetSessionId = targetState.runtime.session.sessionId;- if (target.parentSessionId === fromSessionId) return "parent";- if (from.parentSessionId === targetSessionId) return "child";- if (from.parentSessionId === target.parentSessionId) return "sibling";- return undefined;+ return agentFamilyRelationship(this.agentFamilyEntry(targetState), this.agentFamilyEntry(fromState));}private async sendAgentSessionMessage(options: {@@ -5093,30 +5356,45 @@ export class AgentDaemon {targetState = this.getBoundSessionState(targetSelector);} catch (error) {if (error instanceof BoundSessionUnavailableError) {+ if (options.origin === "agent" && options.fromState) {+ this.assertAgentFamilyReachable(options.fromState, this.getSessionState(targetSelector));+ }targetState = await this.getOrHydrateBoundSessionState(targetSelector);} else {- if (error instanceof AmbiguousActiveSessionError) throw error;- const passiveSubagent = await this.findPassiveRlmSubagent(targetSelector);- if (passiveSubagent) {- targetState = await this.hydratePassiveRlmSubagent(passiveSubagent);+ if (error instanceof AmbiguousActiveSessionError) {+ if (options.origin !== "agent" || !options.fromState) throw error;+ const resolved = this.resolveAgentFamilySessionName(options.fromState, targetSelector, error);+ targetState = await this.getOrHydrateBoundSessionState(resolved.activeSessionId);} else {- const hydratingChild = [...this.sessions.values()].find(- (state) =>- state.runtime.metadata.kind === "subagent" && state.runtime.metadata.rlmChildId === targetSelector,- );- if (hydratingChild) {- targetState = await this.waitForHydratingChild(hydratingChild, targetSelector);- } else if (this.options.worker && options.fromState) {- // The supervisor can resolve and wake a saved worker even when it is no longer- // present in this worker's resident peer snapshot.- return this.sendRemoteAgentSessionMessage(- options.fromState,- targetSelector,- message,- options.deliveryMode,- );+ const passiveSubagent = await this.findPassiveRlmSubagent(targetSelector);+ if (passiveSubagent) {+ if (options.origin === "agent" && options.fromState) {+ assertAgentFamilyReach(+ this.agentFamilyEntry(options.fromState),+ this.passiveAgentFamilyEntry(passiveSubagent),+ );+ }+ targetState = await this.hydratePassiveRlmSubagent(passiveSubagent);} else {- throw error;+ const hydratingChild = [...this.sessions.values()].find(+ (state) =>+ state.runtime.metadata.kind === "subagent" &&+ state.runtime.metadata.rlmChildId === targetSelector,+ );+ if (hydratingChild) {+ targetState = await this.waitForHydratingChild(hydratingChild, targetSelector);+ } else if (this.options.worker && options.fromState) {+ // The supervisor can resolve and wake a saved worker even when it is no longer+ // present in this worker's resident peer snapshot.+ return this.sendRemoteAgentSessionMessage(+ options.fromState,+ targetSelector,+ message,+ options.deliveryMode,+ );+ } else {+ throw error;+ }}}}@@ -5124,6 +5402,9 @@ export class AgentDaemon {if (options.fromState?.activeSessionId === targetState.activeSessionId) {throw new Error("Agent messaging cannot target the sending session");}+ if (options.origin === "agent" && options.fromState) {+ this.assertAgentFamilyReachable(options.fromState, targetState);+ }const releaseQueueSlot = this.reserveAgentMessageQueueSlot(targetState);const senderKey =options.senderKey ?? options.fromState?.activeSessionId ?? `client:${options.clientId ?? "unknown"}`;@@ -5194,6 +5475,7 @@ export class AgentDaemon {targetActiveSessionId: targetSelector,message,fromActiveSessionId: fromState.activeSessionId,+ agentOrigin: true,deliveryMode,},30_000,diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.tsindex 1786b1f32d..f9f41d47aa 100644--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts@@ -55,8 +55,9 @@ export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 7;// Revision 10 publishes persisted RLM spawn depth on all session catalog rows.// 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-670d88ac98dd";+// Revision 13 narrows agent-origin reach and roster wire shapes to the nuclear family.+export const DAEMON_SCHEMA_REVISION = 13;+export const DAEMON_SCHEMA_ID = "protocol-7-schema-13-816309b1cd50";export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;export type DaemonProtocolVersion = number;@@ -461,6 +462,8 @@ export type DaemonCommand =targetActiveSessionId: string;message: string;fromActiveSessionId?: string;+ /** Internal worker-origin marker; public clients remain unrestricted. */+ agentOrigin?: boolean;deliveryMode?: AgentSessionMessageDeliveryMode;}| { id?: string; type: "agent_messages_status"; activeSessionId?: string }@@ -574,7 +577,7 @@ export type DaemonCommand =| { id?: string; type: "import_jsonl"; activeSessionId: string; inputPath: string; cwdOverride?: string }| { id?: string; type: "export_html"; activeSessionId: string; outputPath?: string }| { id?: string; type: "export_jsonl"; activeSessionId: string; outputPath?: string }- | { id?: string; type: "set_session_name"; activeSessionId: string; name: string }+ | { id?: string; type: "set_session_name"; activeSessionId: string; name: string; workerToken?: string }| { id?: string; type: "get_rlm_max_depth_status"; activeSessionId: string }| { id?: string; type: "set_rlm_max_depth"; activeSessionId: string; maxDepth: number; global?: boolean }| { id?: string; type: "rename_saved_session"; activeSessionId?: string; sessionPath: string; name: string }diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex 2b861e72fa..846d5d5193 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -16,8 +16,10 @@ import {import {type AgentFamilyCatalogEntry,type AgentSessionMessageAgentSummary,+ assertAgentFamilyReach,assertAgentSessionNameAvailable,formatAgentSessionNameUnavailable,+ sessionNameReservationKey,} from "../../core/agent-messages.js";import { type AgentSessionRuntimeConfig, mergeAgentSessionRuntimeConfig } from "../../core/agent-session-config.js";import {@@ -39,7 +41,7 @@ import {type WorkerEvictionSnapshot,} from "../../core/session-action-store.js";import { canonicalSessionPath, getProcessStartId, SessionAlreadyActiveError } from "../../core/session-lease.js";-import type { SessionInfo } from "../../core/session-manager.js";+import { readSessionInfo, type SessionInfo } from "../../core/session-manager.js";import { SettingsManager } from "../../core/settings-manager.js";import { signalProcessGroupOrProcess } from "../../utils/child-process.js";import type { AgentConnectionHeartbeat } from "../agent-connection/types.js";@@ -603,7 +605,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 pendingSessionNames = new Set<string>();private readonly catalog: DaemonCatalogClient;private readonly settingsManager: SettingsManager;private idleEvictionTimer?: ReturnType<typeof setTimeout>;@@ -1747,13 +1749,21 @@ export class DaemonSupervisor {const match = await this.findWorkerForClient(client, command.activeSessionId);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);- }- break;+ case "rename_saved_session": {+ const target = await this.savedSessionNameReservationInput(command.sessionPath, command.name.trim());+ return await this.withSessionNameReservation(target, async () => {+ await this.assertSupervisorSavedSessionNameAvailable(command.sessionPath, target.name);+ if (!command.activeSessionId) {+ await this.catalog.rename(command.sessionPath, command.name);+ return success(command.id, command.type);+ }+ const match = await this.findWorkerForClient(client, command.activeSessionId);+ return await this.forwardToWorker(match.worker, {+ ...command,+ activeSessionId: match.summary.activeSessionId ?? match.summary.id,+ });+ });+ }case "delete_saved_session":if (!command.activeSessionId) {const active = this.findWorkerBySessionFile(command.sessionPath);@@ -1767,6 +1777,7 @@ export class DaemonSupervisor {}if (command.type === "send_message") {+ // agentOrigin without fromActiveSessionId is trusted only at the direct socket-client boundary.const source = command.fromActiveSessionId? await this.findWorkerForClient(client, command.fromActiveSessionId): undefined;@@ -1791,6 +1802,14 @@ export class DaemonSupervisor {}throw error;}+ if (source && command.agentOrigin === true) {+ const targetInfo = await readSessionInfo(sessionPath);+ if (!targetInfo) throw new Error(`Unknown active session: ${command.targetActiveSessionId}`);+ assertAgentFamilyReach(+ this.familyCatalogEntry(source.summary),+ this.familyCatalogEntry(summaryForInactiveSession(targetInfo)),+ );+ }const worker = await this.createOrReuseWorker(this.protocolClientId(client), {type: "create",sessionPath,@@ -1803,6 +1822,9 @@ export class DaemonSupervisor {target = { worker, summary };}const targetActiveSessionId = target.summary.activeSessionId ?? target.summary.id;+ if (source && command.agentOrigin === true) {+ assertAgentFamilyReach(this.familyCatalogEntry(source.summary), this.familyCatalogEntry(target.summary));+ }if (source) {if ((source.summary.activeSessionId ?? source.summary.id) === targetActiveSessionId) {throw new Error("Agent messaging cannot target the sending session");@@ -1841,7 +1863,12 @@ export class DaemonSupervisor {try {throwIfAdmissionCancelled(admission);const match = await waitForPromptAdmission(- this.findWorkerForClient(client, command.activeSessionId),+ command.type === "set_session_name" && command.workerToken !== undefined+ ? this.findWorker(+ command.activeSessionId,+ (worker) => worker.descriptor.authenticationToken === command.workerToken,+ )+ : this.findWorkerForClient(client, command.activeSessionId),admission?.controller.signal,);throwIfAdmissionCancelled(admission);@@ -1858,12 +1885,19 @@ export class DaemonSupervisor {command.type === "kill" &&(match.summary.activeSessionId ?? match.summary.id) === match.worker.descriptor.rootActiveSessionId;if (!isRootKill) {+ const forward = async () => {+ const response = await this.forwardToWorker(match.worker, resolvedCommand);+ if (admission && response.success) admission.status = "owned";+ return response;+ };if (command.type === "rename" || command.type === "set_session_name") {- await this.assertSupervisorSessionNameAvailable(match.summary, command.name.trim());+ const reservation = this.summaryNameReservationInput(match.summary, command.name.trim());+ return await this.withSessionNameReservation(reservation, async () => {+ await this.assertSupervisorSessionNameAvailable(match.summary, reservation.name);+ return forward();+ });}- const response = await this.forwardToWorker(match.worker, resolvedCommand);- if (admission && response.success) admission.status = "owned";- return response;+ return await forward();}this.persistWorkerStopTombstone(match.worker, true);let response: DaemonResponse;@@ -1987,32 +2021,27 @@ export class DaemonSupervisor {if (pending) {return pending;}- let reservedRootName: string | undefined;- if (createCommand.name) {+ const opening = (async () => {+ if (!createCommand.name) return this.launchWorker(createCommand, undefined, ownerClientId);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));+ const reservation = this.summaryNameReservationInput(targetSummary, createCommand.name);+ return this.withSessionNameReservation(reservation, async () => {+ if (target?.parentSessionPath && (target.rlmDepth ?? 0) > 0) {+ this.assertSavedSiblingNameAvailable(savedSiblings, target, createCommand.name!);+ } else {+ await this.assertSupervisorSessionNameAvailable(targetSummary, createCommand.name!);}- reservedRootName = createCommand.name;- this.pendingRootSessionNames.add(reservedRootName);- }- }- const opening = this.launchWorker(createCommand, undefined, ownerClientId);+ return 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);}@@ -2914,15 +2943,25 @@ export class DaemonSupervisor {(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) } : {}),- }));+ return [...active, ...savedRoots.map((info) => summaryForInactiveSession(info))].map((summary) =>+ this.familyCatalogEntry(summary),+ );+ }++ private async withSessionNameReservation<T>(+ input: { name: string; depth: number; parentSessionId?: string; parentSessionPath?: string },+ action: () => Promise<T>,+ ): Promise<T> {+ const key = sessionNameReservationKey(input);+ if (this.pendingSessionNames.has(key)) {+ throw new Error(formatAgentSessionNameUnavailable(input.name, input.depth));+ }+ this.pendingSessionNames.add(key);+ try {+ return await action();+ } finally {+ this.pendingSessionNames.delete(key);+ }}private async assertSupervisorSessionNameAvailable(@@ -2938,6 +2977,38 @@ export class DaemonSupervisor {});}+ private async savedSessionNameReservationInput(+ sessionPath: string,+ name: string,+ ): Promise<{ name: string; depth: number; parentSessionId?: string; parentSessionPath?: string }> {+ 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.summaryNameReservationInput(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}`);+ return {+ name,+ depth: saved.rlmDepth ?? siblings.find((sibling) => sibling.rlmDepth !== undefined)?.rlmDepth ?? 0,+ parentSessionPath: saved.parentSessionPath,+ };+ }++ private summaryNameReservationInput(+ target: Pick<SessionSummary, "rlmDepth" | "parentSessionId" | "parentSessionPath">,+ name: string,+ ): { name: string; depth: number; parentSessionId?: string; parentSessionPath?: string } {+ const depth = target.rlmDepth ?? (target.parentSessionPath ? 1 : 0);+ return {+ name,+ depth,+ ...(depth > 0 && target.parentSessionId ? { parentSessionId: target.parentSessionId } : {}),+ ...(depth > 0 && target.parentSessionPath ? { parentSessionPath: target.parentSessionPath } : {}),+ };+ }+private async assertSupervisorSavedSessionNameAvailable(sessionPath: string, name: string): Promise<void> {const targetPath = canonicalSessionPath(sessionPath);const active = [...this.workers.values()]@@ -2955,13 +3026,14 @@ export class DaemonSupervisor {}private assertSavedSiblingNameAvailable(siblings: SessionInfo[], target: SessionInfo, name: string): void {+ const setDepth = target.rlmDepth ?? siblings.find((sibling) => sibling.rlmDepth !== undefined)?.rlmDepth ?? 0;assertAgentSessionNameAvailable(siblings.map((info) => {const summary = summaryForInactiveSession(info);return {id: summary.sessionId,...(summary.sessionName ? { name: summary.sessionName } : {}),- depth: summary.rlmDepth ?? 0,+ depth: setDepth,status: classifySessionRosterStatus(summary),...(summary.parentSessionPath? { parentSessionPath: canonicalSessionPath(summary.parentSessionPath) }@@ -2970,7 +3042,7 @@ export class DaemonSupervisor {}),{name,- depth: target.rlmDepth ?? 0,+ depth: setDepth,parentSessionPath: target.parentSessionPath ? canonicalSessionPath(target.parentSessionPath) : undefined,ignoreSessionId: target.id,},@@ -2992,9 +3064,10 @@ export class DaemonSupervisor {const peers = [...readyWorkers.filter((candidate) => candidate !== worker)- .flatMap((candidate) =>- [...candidate.summaries.values()].map((summary) => this.agentPeerSummary(summary)),- ),+ .flatMap((candidate) => {+ const root = candidate.summaries.get(candidate.descriptor.rootActiveSessionId);+ return root ? [this.agentPeerSummary(root)] : [];+ }),];const response = await worker.client.requestWorker({ type: "worker_sync_agent_peers", peers }, 5000);if (!response.success) {@@ -3011,6 +3084,21 @@ export class DaemonSupervisor {return worker.descriptor.ownerClientId === undefined;}+ private familyCatalogEntry(summary: SessionSummary): AgentFamilyCatalogEntry {+ const depth = summary.rlmDepth ?? (summary.parentSessionPath ? 1 : 0);+ return {+ id: summary.sessionId,+ ...(summary.sessionName ? { name: summary.sessionName } : {}),+ depth,+ status: classifySessionRosterStatus(summary),+ ...(depth > 0 && summary.parentSessionId ? { parentSessionId: summary.parentSessionId } : {}),+ ...(depth > 0 && summary.parentSessionPath+ ? { parentSessionPath: canonicalSessionPath(summary.parentSessionPath) }+ : {}),+ ...(summary.sessionFile ? { sessionPath: canonicalSessionPath(summary.sessionFile) } : {}),+ };+ }+private agentPeerSummary(summary: SessionSummary): AgentSessionMessageAgentSummary {return {activeSessionId: summary.activeSessionId ?? summary.id,diff --git a/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts b/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.tsindex d1bf0f784c..450b376383 100644--- a/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts@@ -15,11 +15,20 @@ import {type HeartbeatPromptDetails,IPYTHON_STATE_RESTORED_CUSTOM_TYPE,type IpythonStateRestoredDetails,+ RLM_CHILD_FAILURE_CUSTOM_TYPE,+ RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,+ type RlmChildFailureDetails,+ type RlmChildTerminalNoticeDetails,} from "../../../core/messages.js";import { getMarkdownTheme, theme } from "../theme/theme.js";import { keyText } from "./keybinding-hints.js";-type InjectedPromptDetails = GoalContextDetails | HeartbeatPromptDetails | IpythonStateRestoredDetails;+type InjectedPromptDetails =+ | GoalContextDetails+ | HeartbeatPromptDetails+ | IpythonStateRestoredDetails+ | RlmChildFailureDetails+ | RlmChildTerminalNoticeDetails;type InjectedPromptMessage = CustomMessage<InjectedPromptDetails>;export function isInjectedPromptMessage(message: AgentMessage): message is InjectedPromptMessage {@@ -27,7 +36,9 @@ export function isInjectedPromptMessage(message: AgentMessage): message is Injecmessage.role === "custom" &&(message.customType === HEARTBEAT_PROMPT_CUSTOM_TYPE ||message.customType === GOAL_CONTEXT_CUSTOM_TYPE ||- message.customType === IPYTHON_STATE_RESTORED_CUSTOM_TYPE)+ message.customType === IPYTHON_STATE_RESTORED_CUSTOM_TYPE ||+ message.customType === RLM_CHILD_FAILURE_CUSTOM_TYPE ||+ message.customType === RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE));}@@ -119,6 +130,13 @@ export class InjectedPromptMessageComponent extends Container {const label = details?.restored === false ? "Started fresh IPython kernel" : "Restored IPython kernel state";return `${theme.fg("accent", "◆")} ${theme.fg("muted", label)}`;}+ if (+ this.message.customType === RLM_CHILD_FAILURE_CUSTOM_TYPE ||+ this.message.customType === RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE+ ) {+ const hint = this.expanded ? "" : ` (${keyText("app.tools.expand")} to expand)`;+ return theme.fg("muted", "RLM child status") + theme.fg("dim", hint);+ }const details = this.message.details;const title = goalLabel(details as GoalContextDetails | undefined);diff --git a/packages/coding-agent/test/agent-session-bus.test.ts b/packages/coding-agent/test/agent-session-bus.test.tsindex a54fc6af5b..d068c1a840 100644--- a/packages/coding-agent/test/agent-session-bus.test.ts+++ b/packages/coding-agent/test/agent-session-bus.test.ts@@ -1,16 +1,19 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import {AGENT_MESSAGE_SOURCE,AgentSessionMessageRateLimiter,+ assertAgentFamilyReach,assertAgentMessageQueueCapacity,assertAgentSessionNameAvailable,assertDirectAgentMessageTarget,buildAgentFamilyRoster,+ createAgentMessageHostHandlers,createAgentSessionMessagePrompt,createAgentSessionMessageReceipt,normalizeAgentSessionMessage,parseAgentSessionMessagePromptId,resolveAgentSessionMessageStreamingBehavior,+ sessionNameReservationKey,} from "../src/core/agent-messages.js";describe("agent session bus", () => {@@ -170,6 +173,177 @@ describe("agent session bus", () => {expect(() => assertAgentMessageQueueCapacity(19, 20)).not.toThrow();});+ it("resolves role sends and scopes all broadcasts to the family roster", async () => {+ const sendAgentMessage = vi.fn(async (input: { target: string; message: string }) => ({+ id: input.target,+ source: AGENT_MESSAGE_SOURCE as typeof AGENT_MESSAGE_SOURCE,+ target: { activeSessionId: input.target, sessionId: input.target },+ message: input.message,+ deliveryStatus: "delivered" as const,+ deliveredAt: new Date(0).toISOString(),+ deliveryMode: "auto" as const,+ }));+ const handlers = createAgentMessageHostHandlers({+ roster: () => ({+ current: { name: "builder", id: "builder", depth: 1 },+ entries: [+ { relationship: "parent", name: "root", id: "root", depth: 0, status: "running" },+ { relationship: "sibling", name: "reviewer", id: "sibling", depth: 1, status: "idle" },+ { relationship: "child", name: "tester", id: "child", depth: 2, status: "inactive" },+ ],+ }),+ sendAgentMessage,+ });++ await handlers["agent_message.send"]!({+ message: "hello",+ receiver_role: "sibling",+ receiver_name: "reviewer",+ });+ expect(sendAgentMessage).toHaveBeenLastCalledWith({+ target: "sibling",+ message: "hello",+ deliveryMode: undefined,+ receiverRole: "sibling",+ });++ sendAgentMessage.mockClear();+ await expect(handlers["agent_message.send"]!({ target: "all", message: "status" })).resolves.toMatchObject({+ receipts: [+ { id: "root", deliveryStatus: "delivered" },+ { id: "sibling", deliveryStatus: "delivered" },+ { id: "child", deliveryStatus: "delivered" },+ ],+ });+ expect(sendAgentMessage.mock.calls.map(([input]) => input.target)).toEqual(["root", "sibling", "child"]);++ sendAgentMessage.mockClear();+ await expect(+ handlers["agent_message.send"]!({+ target: "all",+ message: "private",+ receiver_role: "sibling",+ receiver_name: "reviewer",+ }),+ ).rejects.toThrow("broadcast cannot be combined with receiver_role/receiver_name");+ expect(sendAgentMessage).not.toHaveBeenCalled();+ });++ it("rejects non-all string targets at the host boundary", async () => {+ const sendAgentMessage = vi.fn();+ const handlers = createAgentMessageHostHandlers({+ roster: () => ({+ current: { name: "builder", id: "builder", depth: 1 },+ entries: [],+ }),+ sendAgentMessage,+ });++ await expect(handlers["agent_message.send"]!({ target: "reviewer", message: "status" })).rejects.toThrow(+ "use receiver_role and receiver_name",+ );+ expect(sendAgentMessage).not.toHaveBeenCalled();+ });++ it("reports individual broadcast failures without rejecting successful receipts", async () => {+ const sendAgentMessage = vi.fn(async (input: { target: string; message: string }) => {+ if (input.target === "sibling") throw new Error("rate limited");+ return {+ id: input.target,+ source: AGENT_MESSAGE_SOURCE as typeof AGENT_MESSAGE_SOURCE,+ target: { activeSessionId: input.target, sessionId: input.target },+ message: input.message,+ deliveryStatus: "delivered" as const,+ deliveredAt: new Date(0).toISOString(),+ deliveryMode: "auto" as const,+ };+ });+ const handlers = createAgentMessageHostHandlers({+ roster: () => ({+ current: { name: "builder", id: "builder", depth: 1 },+ entries: [+ { relationship: "parent", name: "root", id: "root", depth: 0, status: "running" },+ { relationship: "sibling", name: "reviewer", id: "sibling", depth: 1, status: "idle" },+ ],+ }),+ sendAgentMessage,+ });++ await expect(handlers["agent_message.send"]!({ target: "all", message: "status" })).resolves.toMatchObject({+ receipts: [+ { id: "root", deliveryStatus: "delivered" },+ { target: "sibling", error: "rate limited" },+ ],+ });+ });++ it("authorizes exactly one persisted nuclear-family edge", () => {+ const root = { id: "root", depth: 0, status: "running" as const, sessionPath: "/root" };+ const otherRoot = { id: "other-root", depth: 0, status: "running" as const, sessionPath: "/other" };+ const child = {+ id: "child",+ depth: 1,+ status: "running" as const,+ parentSessionPath: "/root",+ sessionPath: "/child",+ };+ const sibling = {+ id: "sibling",+ depth: 1,+ status: "idle" as const,+ parentSessionId: "root",+ parentSessionPath: "/root",+ sessionPath: "/sibling",+ };+ const idOnlySibling = {+ id: "id-only-sibling",+ depth: 1,+ status: "idle" as const,+ parentSessionId: "root",+ sessionPath: "/id-only-sibling",+ };+ const grandchild = {+ id: "grandchild",+ depth: 2,+ status: "idle" as const,+ parentSessionPath: "/child",+ };++ expect(assertAgentFamilyReach(root, otherRoot)).toBe("sibling");+ expect(() => assertAgentFamilyReach(root, { id: "orphan", depth: 3, status: "inactive" })).toThrow(+ "Agent reach is limited to parent, siblings, and children",+ );+ expect(() =>+ assertAgentFamilyReach(+ { id: "orphan-a", depth: 3, status: "inactive" },+ { id: "orphan-b", depth: 3, status: "inactive" },+ ),+ ).toThrow("Agent reach is limited to parent, siblings, and children");+ expect(assertAgentFamilyReach(root, child)).toBe("child");+ expect(assertAgentFamilyReach(child, root)).toBe("parent");+ expect(assertAgentFamilyReach(child, sibling)).toBe("sibling");+ expect(assertAgentFamilyReach(sibling, idOnlySibling)).toBe("sibling");+ expect(() => assertAgentFamilyReach(root, grandchild)).toThrow(+ "Agent reach is limited to parent, siblings, and children",+ );+ expect(() => assertAgentFamilyReach(sibling, grandchild)).toThrow(+ "Agent reach is limited to parent, siblings, and children",+ );+ });++ it("collapses depth-zero name reservations to the root scope", () => {+ const rootKey = sessionNameReservationKey({ name: "worker", depth: 0 });++ expect(+ sessionNameReservationKey({+ name: "worker",+ depth: 0,+ parentSessionId: "fork-origin",+ parentSessionPath: "/sessions/fork-origin.jsonl",+ }),+ ).toBe(rootKey);+ });+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" },diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex 62beb81e9b..c98a957e55 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -14,7 +14,11 @@ import {} from "@earendil-works/pi-ai";import { Type } from "typebox";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { type AgentSessionMessageController, isAgentSessionMessage } from "../src/core/agent-messages.js";+import {+ type AgentSessionMessageController,+ createAgentSessionMessage,+ isAgentSessionMessage,+} from "../src/core/agent-messages.js";import { AgentSession } from "../src/core/agent-session.js";import { AuthStorage } from "../src/core/auth-storage.js";import type { LoadExtensionsResult } from "../src/core/extensions/index.js";@@ -32,6 +36,7 @@ import { SettingsManager, type SettingsStorage } from "../src/core/settings-manaimport 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 { AgentDaemon } from "../src/modes/daemon/daemon-mode.js";import { createTestExtensionsResult, createTestResourceLoader } from "./utilities.js";const model = getModel("anthropic", "claude-sonnet-4-5")!;@@ -108,7 +113,9 @@ interface InspectableRlmRun {sessionDir: string;abort: () => void;status: string;+ settled: boolean;error?: string;+ detachedDeletion?: Awaited<ReturnType<AgentSession["listRlmSubagents"]>>["subagents"][number];session?: AgentSession;}@@ -213,6 +220,17 @@ async function expectSettlesWithin(promise: Promise<void>, timeoutMs: number): Pexpect(result).toBe("settled");}+function findLastMessage(+ messages: readonly AgentMessage[],+ predicate: (message: AgentMessage) => boolean,+): AgentMessage | undefined {+ for (let i = messages.length - 1; i >= 0; i--) {+ const message = messages[i];+ if (message && predicate(message)) return message;+ }+ return undefined;+}+describe("AgentSession rlm recursion", () => {let tempDir: string;let session: AgentSession | undefined;@@ -803,6 +821,63 @@ describe("AgentSession rlm recursion", () => {);});+ it("delivers an id-addressed send while a completed child's terminal injection is pending", async () => {+ let releaseTerminalInjection: () => void = () => {};+ const terminalInjectionGate = new Promise<void>((resolve) => {+ releaseTerminalInjection = resolve;+ });+ const child = createSession({ rlmSessionDir: join(tempDir, "completed-child") });+ const sendAgentMessage = vi.fn(async (input: { target: string; message: string }) => ({+ id: "agentmsg-completed-child",+ source: "agent_message" as const,+ target: { activeSessionId: "child-active", sessionId: input.target },+ message: input.message,+ deliveryStatus: "delivered" as const,+ deliveryMode: "auto" as const,+ }));+ const root = createSession({+ agentMessageController: {+ listAgents: () => ({ agents: [] }),+ roster: () => ({+ current: { name: "root", id: root.sessionId, depth: 0 },+ entries: [+ {+ relationship: "child" as const,+ name: child.sessionName ?? child.sessionId,+ id: child.sessionId,+ depth: 1,+ status: "idle" as const,+ },+ ],+ }),+ sendAgentMessage,+ },+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: child }),+ deleteRlmSubagentRuntime: async (_id, session) => session?.disposeAsync(),+ },+ });+ const promptInjectedMessage = vi.fn(async () => terminalInjectionGate);+ (root as unknown as { _promptInjectedMessage: typeof promptInjectedMessage })._promptInjectedMessage =+ promptInjectedMessage;+ const spawned = await root.runRlmChild("completed task", { name: "completed-worker" });+ const internals = root as unknown as InspectableRlmSession;+ await waitFor(() => internals._activeRlmChildRuns.get(spawned.rlm_child_id)?.status === "done");+ await waitFor(() => promptInjectedMessage.mock.calls.length === 1);+ const send = internals._createKernelHostHandlers()["agent_message.send"];+ if (!send) throw new Error("Missing agent_message.send host handler");++ await expect(+ send({ message: "follow-up", receiver_role: "child", receiver_name: spawned.rlm_child_id }),+ ).resolves.toMatchObject({ message: "follow-up" });+ expect(sendAgentMessage).toHaveBeenCalledWith(+ expect.objectContaining({ target: child.sessionId, message: "follow-up" }),+ );++ releaseTerminalInjection();+ await waitFor(() => !internals._activeRlmChildRuns.has(spawned.rlm_child_id));+ });+it("propagates pending child startup failure to an immediate roled send", async () => {let rejectStartup: ((error: Error) => void) | undefined;const startupGate = new Promise<never>((_resolve, reject) => {@@ -835,6 +910,106 @@ describe("AgentSession rlm recursion", () => {await expect(pendingSend).rejects.toThrow("child startup failed");});+ it("falls through a retained failed child name to a healthy roster child", async () => {+ let releaseFailureInjection: () => void = () => {};+ const failureInjectionGate = new Promise<void>((resolve) => {+ releaseFailureInjection = resolve;+ });+ const sendAgentMessage = vi.fn(async (input: { target: string; message: string }) => ({+ id: "agentmsg-healthy-child",+ source: "agent_message" as const,+ target: { activeSessionId: "healthy-active", sessionId: input.target },+ message: input.message,+ deliveryStatus: "delivered" as const,+ deliveryMode: "auto" as const,+ }));+ const root = createSession({+ agentMessageController: {+ listAgents: () => ({ agents: [] }),+ roster: () => ({+ current: { name: "root", id: root.sessionId, depth: 0 },+ entries: [+ {+ relationship: "child" as const,+ name: "shared-child",+ id: "healthy-child-session",+ depth: 1,+ status: "idle" as const,+ },+ ],+ }),+ sendAgentMessage,+ },+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => {+ throw new Error("child startup failed");+ },+ deleteRlmSubagentRuntime: async () => {},+ },+ });+ const promptInjectedMessage = vi.fn(async () => failureInjectionGate);+ (root as unknown as { _promptInjectedMessage: typeof promptInjectedMessage })._promptInjectedMessage =+ promptInjectedMessage;+ await root.runRlmChild("failing task", { name: "shared-child" });+ await waitFor(() =>+ [...(root as unknown as InspectableRlmSession)._activeRlmChildRuns.values()].some(+ (run) => run.status === "error",+ ),+ );+ const handlers = (root as unknown as InspectableRlmSession)._createKernelHostHandlers();+ const send = handlers["agent_message.send"];+ if (!send) throw new Error("Missing agent_message.send host handler");++ await expect(+ send({ message: "hello", receiver_role: "child", receiver_name: "shared-child" }),+ ).resolves.toMatchObject({ message: "hello" });+ expect(sendAgentMessage).toHaveBeenCalledWith(+ expect.objectContaining({ target: "healthy-child-session", message: "hello" }),+ );+ releaseFailureInjection();+ });++ it("falls through a delete-before-startup tombstone during a roled send", async () => {+ let releaseRuntimeCreation: () => void = () => {};+ const runtimeCreationGate = new Promise<void>((resolve) => {+ releaseRuntimeCreation = resolve;+ });+ let runtimeCreationStarted = false;+ const hostedChild = createSession();+ const root = createSession({+ agentMessageController: {+ listAgents: () => ({ agents: [] }),+ roster: () => ({+ current: { name: "root", id: root.sessionId, depth: 0 },+ entries: [],+ }),+ sendAgentMessage: async () => {+ throw new Error("unexpected send");+ },+ },+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => {+ runtimeCreationStarted = true;+ await runtimeCreationGate;+ return { session: hostedChild };+ },+ deleteRlmSubagentRuntime: async (_id, child) => child?.disposeAsync(),+ },+ });+ await root.runRlmChild("blocked startup", { name: "deleted-child" });+ await waitFor(() => runtimeCreationStarted);+ await root.deleteRlmSubagent("deleted-child");+ const handlers = (root as unknown as InspectableRlmSession)._createKernelHostHandlers();+ const send = handlers["agent_message.send"];+ if (!send) throw new Error("Missing agent_message.send host handler");++ await expect(send({ message: "hello", receiver_role: "child", receiver_name: "deleted-child" })).rejects.toThrow(+ 'No child matches "deleted-child"',+ );+ releaseRuntimeCreation();+ await waitFor(() => (root as unknown as InspectableRlmSession)._activeRlmChildRuns.size === 0);+ });+it("marks a broadcast delivery to the parent as replied without reloading the roster", async () => {const roster = vi.fn(() => ({current: { name: "child", id: "child-session", depth: 1 },@@ -875,6 +1050,110 @@ describe("AgentSession rlm recursion", () => {expect(child.repliedToParentSinceTask).toBe(true);});+ it("routes family messages with sender-perspective labels and resets parent steer reply state", async () => {+ const parent = createSession();+ parent.setSessionName("parent");+ const child = createSession({ depth: 1 });+ child.setSessionName("worker");+ (child as unknown as { _repliedToParentSinceTask: boolean })._repliedToParentSinceTask = true;++ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir },+ createRuntime: vi.fn(),+ });+ const parentState = {+ activeSessionId: "parent-active",+ clients: new Set(),+ pendingAttaches: 0,+ lastEventSequence: 0,+ runtime: {+ metadata: { kind: "top-level", createdAt: 1 },+ session: parent,+ },+ } as unknown as ActiveSessionState;+ const childState = {+ activeSessionId: "child-active",+ clients: new Set(),+ pendingAttaches: 0,+ lastEventSequence: 0,+ runtime: {+ metadata: {+ kind: "subagent",+ createdAt: 1,+ parentActiveSessionId: "parent-active",+ parentSessionId: parent.sessionId,+ },+ session: child,+ },+ } as unknown as ActiveSessionState;+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ sendAgentSessionMessage(options: {+ targetSelector: string;+ message: string;+ fromState: ActiveSessionState;+ deliveryMode?: "auto" | "steer" | "follow_up";+ origin: "agent";+ }): Promise<unknown>;+ };+ internals.sessions.set(parentState.activeSessionId, parentState);+ internals.sessions.set(childState.activeSessionId, childState);++ await internals.sendAgentSessionMessage({+ targetSelector: parentState.activeSessionId,+ message: "done",+ fromState: childState,+ origin: "agent",+ });+ const reply = findLastMessage(parent.messages, isAgentSessionMessage);+ expect(reply && isAgentSessionMessage(reply) ? reply.content : undefined).toContain("[from child:worker]");++ await internals.sendAgentSessionMessage({+ targetSelector: childState.activeSessionId,+ message: "continue",+ fromState: parentState,+ deliveryMode: "steer",+ origin: "agent",+ });+ const steer = findLastMessage(child.messages, isAgentSessionMessage);+ expect(steer && isAgentSessionMessage(steer) ? steer.content : undefined).toContain("[from parent]");+ expect(child.repliedToParentSinceTask).toBe(false);+ });++ it("resets replied state when a parent message is accepted", async () => {+ const child = createSession({ depth: 1 });+ (child as unknown as { _repliedToParentSinceTask: boolean })._repliedToParentSinceTask = true;+ const message = createAgentSessionMessage({+ id: "agentmsg-parent-task",+ source: "agent_message",+ message: "new task",+ fromRelationship: "parent",+ target: { activeSessionId: "child-active", sessionId: child.sessionId },+ deliveryMode: "auto",+ });++ await child.acceptAgentMessagePrompt(message.content as string, { customMessage: message });++ expect(child.repliedToParentSinceTask).toBe(false);+ });++ it("resets replied state when a parent follow-up is queued", async () => {+ const child = createSession({ depth: 1 });+ (child as unknown as { _repliedToParentSinceTask: boolean })._repliedToParentSinceTask = true;+ const message = createAgentSessionMessage({+ id: "agentmsg-parent-follow-up",+ source: "agent_message",+ message: "continue",+ fromRelationship: "parent",+ target: { activeSessionId: "child-active", sessionId: child.sessionId },+ deliveryMode: "follow_up",+ });++ await child.queueAgentMessagePrompt(message.content as string, "followUp", message);++ expect(child.repliedToParentSinceTask).toBe(false);+ });+it("leaves replied state unknown when a child session is rehydrated", () => {const manager = SessionManager.create(tempDir, join(tempDir, "resumed-child"));manager.newSession({ rlmDepth: 1 });@@ -885,6 +1164,223 @@ describe("AgentSession rlm recursion", () => {expect(resumed.repliedToParentSinceTask).toBeUndefined();});+ it("surfaces post-admission startup failure in the parent transcript and subagent registry", async () => {+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => {+ throw new Error("kernel startup failed");+ },+ deleteRlmSubagentRuntime: async () => {},+ },+ });++ const spawned = await root.runRlmChild("start failing child", { name: "failing-worker" });+ await vi.waitFor(async () => {+ expect((await root.listRlmSubagents()).subagents).toContainEqual(+ expect.objectContaining({ rlm_child_id: spawned.rlm_child_id, status: "error" }),+ );+ });+ await vi.waitFor(() => {+ expect(root.messages).toContainEqual(+ expect.objectContaining({+ role: "custom",+ customType: "rlm_child_failure",+ content: expect.stringContaining("failing-worker"),+ }),+ );+ expect(root.messages).toContainEqual(+ expect.objectContaining({ content: expect.stringContaining("kernel startup failed") }),+ );+ });+ });++ it("injects exactly one cancellation notice when a child run is cancelled", async () => {+ let releaseChild: () => void = () => {};+ const release = new Promise<void>((resolve) => {+ releaseChild = resolve;+ });+ let childStarted = false;+ const root = createSession({+ streamFn: () => {+ const stream = createAssistantMessageEventStream();+ childStarted = true;+ void release.then(() => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage("late child answer") });+ });+ return stream;+ },+ });++ const spawned = await root.runRlmChild("slow child", { name: "cancel-worker" });+ await waitFor(() => childStarted);+ expect(root.cancelRlmChildRun(spawned.rlm_child_id)).toBe(true);+ releaseChild();+ await vi.waitFor(() => {+ const notices = root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ );+ expect(notices).toHaveLength(1);+ expect(notices[0]).toMatchObject({+ content: expect.stringContaining(+ `RLM child cancel-worker (${spawned.rlm_child_id}) was cancelled: Cancelled by user`,+ ),+ details: { kind: "cancelled", reason: "Cancelled by user" },+ });+ });+ });++ it("injects exactly one notice with a preview when a child completes without replying", async () => {+ const root = createSession();++ const spawned = await root.runRlmChild("silent child", { name: "silent-worker" });+ await vi.waitFor(() => {+ const notices = root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ );+ expect(notices).toHaveLength(1);+ expect(notices[0]).toMatchObject({+ content: expect.stringContaining(+ `RLM child silent-worker (${spawned.rlm_child_id}) completed without sending a reply`,+ ),+ details: {+ kind: "completed_without_reply",+ lastAssistantTextPreview: "child answer: silent child",+ },+ });+ });+ });++ it("does not inject a terminal notice when a parent follow-up resets reply state after a reply", async () => {+ const child = createSession({+ depth: 1,+ rlmSessionDir: join(tempDir, "replying-child"),+ agentMessageController: {+ listAgents: () => ({ agents: [] }),+ roster: () => ({+ current: { name: "reply-worker", id: child.sessionId, depth: 1 },+ entries: [{ relationship: "parent", name: "parent", id: "parent-session", depth: 0, status: "idle" }],+ }),+ sendAgentMessage: async () => ({+ id: "agentmsg-reply-before-follow-up",+ source: "agent_message",+ target: { activeSessionId: "parent-active", sessionId: "parent-session" },+ message: "done",+ deliveryStatus: "delivered",+ deliveryMode: "auto",+ }),+ },+ });+ vi.spyOn(child, "promptAndWait").mockImplementation(async () => {+ const send = (child as unknown as InspectableRlmSession)._createKernelHostHandlers()["agent_message.send"];+ if (!send) throw new Error("Missing agent_message.send host handler");+ await send({ message: "done", receiver_role: "parent" });+ const followUp = createAgentSessionMessage({+ id: "agentmsg-parent-follow-up-after-reply",+ source: "agent_message",+ message: "continue cleanup",+ fromRelationship: "parent",+ target: { activeSessionId: "child-active", sessionId: child.sessionId },+ deliveryMode: "follow_up",+ });+ await child.queueAgentMessagePrompt(followUp.content as string, "followUp", followUp);+ expect(child.repliedToParentSinceTask).toBe(false);+ });+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: child }),+ deleteRlmSubagentRuntime: async () => {},+ },+ });++ const spawned = await root.runRlmChild("reply first", { name: "reply-worker" });+ await vi.waitFor(async () => {+ expect((await root.listRlmSubagents()).subagents).toContainEqual(+ expect.objectContaining({ rlm_child_id: spawned.rlm_child_id, status: "completed" }),+ );+ });+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(0);+ });++ it("keeps detached deletion silent when child startup later settles", async () => {+ let releaseRuntimeCreation: () => void = () => {};+ const runtimeCreationGate = new Promise<void>((resolve) => {+ releaseRuntimeCreation = resolve;+ });+ let runtimeCreationStarted = false;+ const child = createSession({ rlmSessionDir: join(tempDir, "deleted-child") });+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => {+ runtimeCreationStarted = true;+ await runtimeCreationGate;+ return { session: child };+ },+ deleteRlmSubagentRuntime: async (_id, session) => session?.disposeAsync(),+ },+ });++ const spawned = await root.runRlmChild("delete before startup", { name: "deleted-worker" });+ await waitFor(() => runtimeCreationStarted);+ await root.deleteRlmSubagent(spawned.rlm_child_id);+ releaseRuntimeCreation();+ await waitFor(() => !(root as unknown as InspectableRlmSession)._activeRlmChildRuns.has(spawned.rlm_child_id));+ expect(+ root.messages.filter(+ (message) => message.role === "custom" && message.customType === "rlm_child_terminal_notice",+ ),+ ).toHaveLength(0);+ });++ it("fully deletes a settled startup failure and frees its session name", async () => {+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => {+ throw new Error("kernel startup failed");+ },+ deleteRlmSubagentRuntime: async () => {},+ },+ });+ const spawned = await root.runRlmChild("start failing child", { name: "reusable-worker" });+ const internals = root as unknown as InspectableRlmSession;+ await vi.waitFor(() => expect(internals._activeRlmChildRuns.get(spawned.rlm_child_id)?.settled).toBe(true));++ await expect(root.deleteRlmSubagent(spawned.rlm_child_id)).resolves.toMatchObject({+ subagent: { rlm_child_id: spawned.rlm_child_id, session_name: "reusable-worker" },+ });++ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(internals._activeRlmChildRuns.has(spawned.rlm_child_id)).toBe(false);+ await expect(root.runRlmChild("replacement child", { name: "reusable-worker" })).resolves.toMatchObject({+ name: "reusable-worker",+ });+ });++ it("releases a hosted child when its initial task fails", async () => {+ const child = createSession({ rlmSessionDir: join(tempDir, "host-error-child") });+ vi.spyOn(child, "promptAndWait").mockRejectedValue(new Error("child prompt failed"));+ const releaseRlmSubagentRuntime = vi.fn(async () => {});+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => ({ session: child }),+ releaseRlmSubagentRuntime,+ deleteRlmSubagentRuntime: async () => {},+ },+ });++ const spawned = await root.runRlmChild("fail hosted child");+ await vi.waitFor(() => {+ expect(releaseRlmSubagentRuntime).toHaveBeenCalledWith(+ expect.objectContaining({ session: child }),+ expect.objectContaining({ id: spawned.rlm_child_id }),+ "error",+ );+ });+ });+it("notifies the runtime host when the initial child task completes", async () => {const child = createSession({ rlmSessionDir: join(tempDir, "host-completion-child") });const completeRlmSubagentRuntime = vi.fn(() => true);@@ -996,26 +1492,30 @@ describe("AgentSession rlm recursion", () => {expect(await root.listRlmSubagents()).toEqual({ subagents: [] });});- it("lists and deletes a passive daemon child without a retained runtime", async () => {+ it("lists passive daemon children using their nonresident registry outcomes", async () => {const deleteRlmSubagentRuntime = vi.fn(async () => {});const root = createSession({agentMessageController: {listAgents: () => ({current: { activeSessionId: "parent-active", sessionId: "parent-session" },- agents: [- {- activeSessionId: "passive-session",- sessionId: "passive-session",- sessionName: "passive-worker",- runtimeKind: "subagent",- cwd: tempDir,- isStreaming: false,- unfinishedActionCount: 0,- parentActiveSessionId: "parent-active",- rlmChildId: "passive-child",- sessionDir: join(tempDir, "passive-child"),- },- ],+ agents: (+ [+ ["failed", "running"],+ ["finished", "completed"],+ ] as const+ ).map(([name, registryStatus]) => ({+ activeSessionId: `${name}-session`,+ sessionId: `${name}-session`,+ sessionName: `${name}-worker`,+ runtimeKind: "subagent",+ cwd: tempDir,+ isStreaming: false,+ unfinishedActionCount: 0,+ parentActiveSessionId: "parent-active",+ rlmChildId: `${name}-child`,+ rlmChildRegistryStatus: registryStatus,+ sessionDir: join(tempDir, `${name}-child`),+ })),}),sendAgentMessage: async () => {throw new Error("unexpected send");@@ -1028,19 +1528,29 @@ describe("AgentSession rlm recursion", () => {deleteRlmSubagentRuntime,},});- const expected = {- rlm_child_id: "passive-child",- active_session_id: "passive-session",- session_id: "passive-session",- session_name: "passive-worker",- session_dir: join(tempDir, "passive-child"),- status: "completed" as const,- };+ const expected = [+ {+ rlm_child_id: "failed-child",+ active_session_id: "failed-session",+ session_id: "failed-session",+ session_name: "failed-worker",+ session_dir: join(tempDir, "failed-child"),+ status: "error" as const,+ },+ {+ rlm_child_id: "finished-child",+ active_session_id: "finished-session",+ session_id: "finished-session",+ session_name: "finished-worker",+ session_dir: join(tempDir, "finished-child"),+ status: "completed" as const,+ },+ ];- expect(await root.listRlmSubagents()).toEqual({ subagents: [expected] });- await expect(root.deleteRlmSubagent("passive-worker")).resolves.toEqual({ subagent: expected });- expect(deleteRlmSubagentRuntime).toHaveBeenCalledWith("passive-child", undefined);- expect(await root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: expected });+ await expect(root.deleteRlmSubagent("finished-worker")).resolves.toEqual({ subagent: expected[1] });+ expect(deleteRlmSubagentRuntime).toHaveBeenCalledWith("finished-child", undefined);+ expect(await root.listRlmSubagents()).toEqual({ subagents: [expected[0]] });});it("coalesces concurrent deletion of the same passive daemon child", async () => {@@ -1217,7 +1727,7 @@ describe("AgentSession rlm recursion", () => {const result = await root.runRlmChild("summarize shard 1");expect(result.rlm_child_id).toMatch(/^sub-/);- await waitFor(() => streamFn.mock.calls.length === 1);+ await waitFor(() => streamFn.mock.calls.length >= 1);});it("adds child usage to the parent session aggregate", async () => {@@ -1228,13 +1738,13 @@ describe("AgentSession rlm recursion", () => {const before = root.getSessionStats();await root.runRlmChild("summarize shard 2");- await waitFor(() => root.getSessionStats().tokens.input === before.tokens.input + 7);+ await waitFor(() => root.sessionManager.getEntries().some((entry) => entry.type === "child_usage_attributed"));const after = root.getSessionStats();- expect(after.tokens.input).toBe(before.tokens.input + 7);- expect(after.tokens.output).toBe(before.tokens.output + 3);- expect(after.tokens.total).toBe(before.tokens.total + 10);- expect(after.cost).toBe(before.cost + 10);+ expect(after.tokens.input).toBeGreaterThanOrEqual(before.tokens.input + 7);+ expect(after.tokens.output).toBeGreaterThanOrEqual(before.tokens.output + 3);+ expect(after.tokens.total).toBeGreaterThanOrEqual(before.tokens.total + 10);+ expect(after.cost).toBeGreaterThanOrEqual(before.cost + 10);expect(parentAssistant.usage.totalTokens).toBe(0);const parentEntry = root.sessionManager@@ -2046,6 +2556,76 @@ describe("AgentSession rlm recursion", () => {expect(internals._rlmChildCleanupFailures.size).toBe(0);});+ it("reserves an errored startup name while its detached failure injection settles", async () => {+ let releaseFailureInjection: () => void = () => {};+ const failureInjectionGate = new Promise<void>((resolve) => {+ releaseFailureInjection = resolve;+ });+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => {+ throw new Error("startup failed");+ },+ deleteRlmSubagentRuntime: async () => undefined,+ },+ });+ const promptInjectedMessage = vi.fn(async () => failureInjectionGate);+ (root as unknown as { _promptInjectedMessage: typeof promptInjectedMessage })._promptInjectedMessage =+ promptInjectedMessage;++ await root.runRlmChild("failing startup", { name: "failed-worker" });+ await waitFor(() => promptInjectedMessage.mock.calls.length === 1);+ const failed = (await root.listRlmSubagents()).subagents[0];+ expect(failed).toMatchObject({ session_name: "failed-worker", status: "error" });+ await expect(root.deleteRlmSubagent("failed-worker")).resolves.toEqual({ subagent: failed });+ const internals = root as unknown as InspectableRlmSession;+ expect(internals._activeRlmChildRuns.size).toBe(1);+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });+ await expect(root.runRlmChild("replacement", { name: "failed-worker" })).rejects.toThrow(+ "an agent of that name already exists at depth 1 under this parent",+ );++ releaseFailureInjection();+ await waitFor(() => !internals._activeRlmChildRuns.has(failed?.rlm_child_id ?? ""));+ await expect(root.runRlmChild("replacement", { name: "failed-worker" })).resolves.toMatchObject({+ name: "failed-worker",+ });+ });++ it("reserves a deleted queued child's name until startup settles", async () => {+ let releaseRuntimeCreation: () => void = () => {};+ const runtimeCreationGate = new Promise<void>((resolve) => {+ releaseRuntimeCreation = resolve;+ });+ let runtimeCreationStarted = false;+ const hostedChild = createSession();+ const setSessionName = vi.spyOn(hostedChild, "setSessionName");+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => {+ runtimeCreationStarted = true;+ await runtimeCreationGate;+ return { session: hostedChild };+ },+ deleteRlmSubagentRuntime: async (_id, child) => child?.disposeAsync(),+ },+ });+ await root.runRlmChild("blocked before runtime creation", { name: "reserved-worker" });+ await waitFor(() => runtimeCreationStarted);++ await root.deleteRlmSubagent("reserved-worker");+ await expect(root.runRlmChild("replacement", { name: "reserved-worker" })).rejects.toThrow(+ "an agent of that name already exists at depth 1 under this parent",+ );++ releaseRuntimeCreation();+ await waitFor(() => (root as unknown as InspectableRlmSession)._activeRlmChildRuns.size === 0);+ expect(setSessionName).not.toHaveBeenCalled();+ await expect(root.runRlmChild("replacement", { name: "reserved-worker" })).resolves.toMatchObject({+ name: "reserved-worker",+ });+ });+it("deletes a queued child without waiting for blocked startup", async () => {let releaseRuntimeCreation: () => void = () => {};const runtimeCreationGate = new Promise<void>((resolve) => {@@ -2074,9 +2654,6 @@ describe("AgentSession rlm recursion", () => {await expect(root.deleteRlmSubagent("queued-worker")).resolves.toEqual({ subagent: queued });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(- "an agent of that name already exists at depth 1 under this parent",- );releaseRuntimeCreation();await waitFor(() => deleteRuntime.mock.calls.length === 1);diff --git a/packages/coding-agent/test/agent-session-services.test.ts b/packages/coding-agent/test/agent-session-services.test.tsindex 3b0f486db7..8123325114 100644--- a/packages/coding-agent/test/agent-session-services.test.ts+++ b/packages/coding-agent/test/agent-session-services.test.ts@@ -98,10 +98,9 @@ describe("createAgentSessionFromServices", () => {});try {- expect(session.handleAgentMessageHostRequest("agent_message.list")).toMatchObject({- current: { activeSessionId: "current" },- agents: [{ activeSessionId: "worker" }],- });+ expect(() => session.handleAgentMessageHostRequest("agent_message.list")).toThrow(+ "unknown agent message request",+ );expect((session as unknown as {diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex ae21cbe4cf..48302853b9 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -1,11 +1,16 @@import { EventEmitter } from "node:events";-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { createServer, type Server, type Socket } from "node:net";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import type { Api, Model } from "@earendil-works/pi-ai";import { describe, expect, it, vi } from "vitest";-import { type AgentSessionMessageController, DEFAULT_AGENT_MESSAGE_MAX_CHARS } from "../src/core/agent-messages.js";+import {+ AGENT_FAMILY_REACH_ERROR,+ type AgentSessionMessageController,+ DEFAULT_AGENT_MESSAGE_MAX_CHARS,+ sessionNameReservationKey,+} from "../src/core/agent-messages.js";import type { AgentObserveController } from "../src/core/agent-observe.js";import type { CreateAgentSessionRuntimeFactory } from "../src/core/agent-session-runtime.js";import type { AgentCronJob, AgentCronJobStore } from "../src/core/cron-jobs.js";@@ -14,6 +19,7 @@ import {createDefaultRlmSubagentSessionName,type SubagentRuntimeHost,} from "../src/core/rlm-runtime.js";+import { canonicalSessionPath } from "../src/core/session-lease.js";import { readSessionInfo, type SessionInfo, SessionManager } from "../src/core/session-manager.js";import type { ActiveSessionState, DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";import {@@ -79,6 +85,51 @@ describe("daemon mode helpers", () => {expect(setSessionName).toHaveBeenCalledOnce();});+ it("treats a depth-zero fork as a sibling of another root", () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-fork-family.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: vi.fn(),+ });+ const fork = makeState("fork");+ fork.runtime = {+ ...fork.runtime,+ metadata: {+ kind: "top-level",+ createdAt: 1,+ parentSessionId: "fork-origin",+ parentSessionFile: "/tmp/fork-origin.jsonl",+ },+ session: {+ sessionId: "session-fork",+ sessionFile: "/tmp/fork.jsonl",+ rlmDepth: 0,+ sessionManager: { getHeader: () => ({ parentSession: "/tmp/fork-origin.jsonl" }) },+ },+ } as never;+ const root = makeState("root");+ root.runtime = {+ ...root.runtime,+ metadata: { kind: "top-level", createdAt: 1 },+ session: {+ sessionId: "session-root",+ sessionFile: "/tmp/root.jsonl",+ rlmDepth: 0,+ },+ } as never;+ const internals = daemon as unknown as {+ agentFamilyEntry(state: ActiveSessionState): {+ parentSessionId?: string;+ parentSessionPath?: string;+ };+ isAgentFamilyReachable(current: ActiveSessionState, target: ActiveSessionState): boolean;+ };++ expect(internals.agentFamilyEntry(fork)).not.toHaveProperty("parentSessionId");+ expect(internals.agentFamilyEntry(fork)).not.toHaveProperty("parentSessionPath");+ expect(internals.isAgentFamilyReachable(root, fork)).toBe(true);+ expect(internals.isAgentFamilyReachable(fork, root)).toBe(true);+ });+it("finds only direct child active sessions", () => {const parent = makeState("parent");const child = makeState("child", "parent");@@ -228,10 +279,14 @@ describe("daemon mode helpers", () => {},} as never;const internals = daemon as unknown as {- cronStore: { getHeartbeat(activeSessionId: string): AgentCronJob | undefined };+ cronStore: {+ getHeartbeat(activeSessionId: string): AgentCronJob | undefined;+ listRlmHeartbeats(activeSessionId: string): AgentCronJob[];+ };createAgentMessageAgentSummary(state: ActiveSessionState): { status?: string };};const getHeartbeat = vi.spyOn(internals.cronStore, "getHeartbeat").mockReturnValue(undefined);+ const listRlmHeartbeats = vi.spyOn(internals.cronStore, "listRlmHeartbeats").mockReturnValue([]);expect(internals.createAgentMessageAgentSummary(state).status).toBe("running");hasRunningChildren = false;@@ -242,6 +297,148 @@ describe("daemon mode helpers", () => {expect(internals.createAgentMessageAgentSummary(state).status).toBe("idle");getHeartbeat.mockReturnValue({ status: "active" } as AgentCronJob);expect(internals.createAgentMessageAgentSummary(state).status).toBe("running");+ getHeartbeat.mockReturnValue(undefined);+ listRlmHeartbeats.mockReturnValue([{ status: "active" } as AgentCronJob]);+ expect(internals.createAgentMessageAgentSummary(state).status).toBe("running");+ });++ it("reserves a session name across equivalent session-relative parent headers", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-name-reservation.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: vi.fn(),+ });+ const first = makeState("first");+ const second = makeState("second");+ first.runtime = {+ ...first.runtime,+ session: {+ sessionId: "first-session",+ sessionFile: "/tmp/children/first.jsonl",+ rlmDepth: 1,+ sessionManager: { getHeader: vi.fn(() => ({ parentSession: "../parent.jsonl" })) },+ setSessionName: vi.fn(),+ },+ } as never;+ second.runtime = {+ ...second.runtime,+ session: {+ sessionId: "second-session",+ sessionFile: "/tmp/children/nested/second.jsonl",+ rlmDepth: 1,+ sessionManager: { getHeader: vi.fn(() => ({ parentSession: "../../parent.jsonl" })) },+ setSessionName: vi.fn(),+ },+ } as never;+ let releaseValidation!: () => void;+ const validationGate = new Promise<void>((resolve) => {+ releaseValidation = resolve;+ });+ const internals = daemon as unknown as {+ assertStateSessionNameAvailable: ReturnType<typeof vi.fn>;+ setStateSessionName(state: ActiveSessionState, name: string): Promise<void>;+ };+ internals.assertStateSessionNameAvailable = vi.fn(async () => validationGate);++ const firstRename = internals.setStateSessionName(first, "shared");+ await expect(internals.setStateSessionName(second, "shared")).rejects.toThrow(+ "an agent of that name already exists at depth 1 under this parent",+ );+ releaseValidation();+ await expect(firstRename).resolves.toBeUndefined();+ expect(first.runtime.session.setSessionName).toHaveBeenCalledWith("shared");+ expect(second.runtime.session.setSessionName).not.toHaveBeenCalled();+ });++ it("allows concurrent same-name renames under different parents", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-scoped-name-reservation.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: vi.fn(),+ });+ const first = makeState("first", "parent-a");+ const second = makeState("second", "parent-b");+ first.runtime = {+ ...first.runtime,+ metadata: { ...first.runtime.metadata, parentSessionId: "parent-session-a" },+ session: {+ sessionId: "first-session",+ rlmDepth: 1,+ sessionManager: { getHeader: vi.fn(() => undefined) },+ setSessionName: vi.fn(),+ },+ } as never;+ second.runtime = {+ ...second.runtime,+ metadata: { ...second.runtime.metadata, parentSessionId: "parent-session-b" },+ session: {+ sessionId: "second-session",+ rlmDepth: 1,+ sessionManager: { getHeader: vi.fn(() => undefined) },+ setSessionName: vi.fn(),+ },+ } as never;+ let releaseValidation!: () => void;+ const validationGate = new Promise<void>((resolve) => {+ releaseValidation = resolve;+ });+ const internals = daemon as unknown as {+ assertStateSessionNameAvailable: ReturnType<typeof vi.fn>;+ setStateSessionName(state: ActiveSessionState, name: string): Promise<void>;+ };+ internals.assertStateSessionNameAvailable = vi.fn(async () => validationGate);++ const firstRename = internals.setStateSessionName(first, "worker");+ const secondRename = internals.setStateSessionName(second, "worker");+ await vi.waitFor(() => expect(internals.assertStateSessionNameAvailable).toHaveBeenCalledTimes(2));+ releaseValidation();++ await expect(Promise.all([firstRename, secondRename])).resolves.toEqual([undefined, undefined]);+ expect(first.runtime.session.setSessionName).toHaveBeenCalledWith("worker");+ expect(second.runtime.session.setSessionName).toHaveBeenCalledWith("worker");+ });++ it("scopes a switched child rename from its session-relative persisted parent header", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-switched-child-name-"));+ try {+ const parentPath = join(tempDir, "parent.jsonl");+ const childDir = join(tempDir, "child");+ const childPath = join(childDir, "child.jsonl");+ mkdirSync(childDir);+ writeFileSync(parentPath, "");+ const state = makeState("switched-child");+ state.runtime = {+ ...state.runtime,+ metadata: { kind: "top-level", createdAt: 1 },+ session: {+ sessionId: "session-child",+ sessionFile: childPath,+ rlmDepth: 1,+ sessionManager: { getHeader: () => ({ parentSession: "../parent.jsonl" }) },+ },+ } as never;+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir: tempDir },+ createRuntime: vi.fn(),+ });+ const internals = daemon as unknown as {+ createAgentFamilyCatalog: ReturnType<typeof vi.fn>;+ assertStateSessionNameAvailable(state: ActiveSessionState, name: string): Promise<void>;+ };+ internals.createAgentFamilyCatalog = vi.fn(async () => [+ {+ id: "sibling",+ name: "taken",+ depth: 1,+ status: "idle",+ parentSessionPath: canonicalSessionPath(parentPath),+ },+ ]);++ await expect(internals.assertStateSessionNameAvailable(state, "taken")).rejects.toThrow(+ "an agent of that name already exists at depth 1 under this parent",+ );+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }});it("keeps fresh local rows over stale synced peers in the family catalog", async () => {@@ -288,6 +485,81 @@ describe("daemon mode helpers", () => {}});+ it("canonicalizes symlinked paths in the family catalog and name reservations", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-family-catalog-paths-"));+ try {+ const realDir = join(tempDir, "real");+ const aliasDir = join(tempDir, "alias");+ mkdirSync(realDir);+ symlinkSync(realDir, aliasDir, "dir");+ const parentPath = join(realDir, "parent.jsonl");+ writeFileSync(parentPath, "");+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir: tempDir },+ createRuntime: vi.fn(),+ });+ const parent = makeState("parent");+ parent.runtime = {+ ...parent.runtime,+ cwd: tempDir,+ metadata: { kind: "top-level", createdAt: 1 },+ session: {+ sessionId: "session-parent",+ sessionName: "parent",+ sessionFile: parentPath,+ sessionManager: { getSessionArtifactDir: () => undefined },+ rlmDepth: 0,+ isStreaming: false,+ isSessionActive: false,+ unfinishedActionCount: 0,+ hasRunningRlmChildren: () => false,+ },+ } as never;+ const child = {+ activeSessionId: "child-active",+ sessionId: "session-child",+ sessionName: "child",+ runtimeKind: "subagent",+ cwd: tempDir,+ isStreaming: false,+ unfinishedActionCount: 0,+ parentSessionPath: join(aliasDir, "parent.jsonl"),+ rlmDepth: 1,+ status: "idle",+ };+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ remoteAgentPeers: Map<string, typeof child>;+ createAgentFamilyRoster(state: ActiveSessionState): Promise<{ entries: Array<{ id: string }> }>;+ };+ internals.sessions.set(parent.activeSessionId, parent);+ internals.remoteAgentPeers.set(child.activeSessionId, child);+ const listAll = vi.spyOn(SessionManager, "listAll").mockResolvedValue([]);+ try {+ expect(await internals.createAgentFamilyRoster(parent)).toMatchObject({+ entries: [expect.objectContaining({ id: "session-child" })],+ });+ expect(+ sessionNameReservationKey({+ name: "worker",+ depth: 1,+ parentSessionPath: parentPath,+ }),+ ).toBe(+ sessionNameReservationKey({+ name: "worker",+ depth: 1,+ parentSessionPath: join(aliasDir, "parent.jsonl"),+ }),+ );+ } finally {+ listAll.mockRestore();+ }+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+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" },@@ -378,7 +650,7 @@ describe("daemon mode helpers", () => {expect(acceptAgentMessagePrompt.mock.calls[0]?.[0]).toContain("report current progress");});- it("closes a released hosted child through daemon session bookkeeping", async () => {+ it("closes a hosted child through the release hook and persists cancellation", async () => {const daemon = new AgentDaemon("/tmp/prime-agent-daemon-release-test.sock", {defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },createRuntime: vi.fn(),@@ -392,7 +664,8 @@ describe("daemon mode helpers", () => {});let internals: {sessions: Map<string, ActiveSessionState>;- closeSession: (state: ActiveSessionState, reason: "completed") => Promise<void>;+ closeSession: (state: ActiveSessionState, reason: "completed" | "killed") => Promise<void>;+ recordRlmSubagentDeletion(parentState: ActiveSessionState, childId: string): Promise<void>;createSubagentRuntimeHost(parentState: ActiveSessionState): SubagentRuntimeHost;};const closeSession = vi.fn(async (state: ActiveSessionState) => {@@ -402,6 +675,8 @@ describe("daemon mode helpers", () => {internals.sessions.set(parentState.activeSessionId, parentState);internals.sessions.set(childState.activeSessionId, childState);internals.closeSession = closeSession;+ const recordDeletion = vi.fn(async () => undefined);+ internals.recordRlmSubagentDeletion = recordDeletion;await internals.createSubagentRuntimeHost(parentState)@@ -411,7 +686,36 @@ describe("daemon mode helpers", () => {"error",);+ expect(recordDeletion).not.toHaveBeenCalled();expect(closeSession).toHaveBeenCalledWith(childState, "completed");+ internals.sessions.set(childState.activeSessionId, childState);+ await internals+ .createSubagentRuntimeHost(parentState)+ .releaseRlmSubagentRuntime?.(+ { session: childState.runtime.session },+ { id: "child-1" } as CreateRlmSubagentRuntimeOptions,+ "cancelled",+ );+ expect(recordDeletion).toHaveBeenCalledWith(parentState, "child-1");+ expect(recordDeletion.mock.invocationCallOrder[0]).toBeLessThan(closeSession.mock.invocationCallOrder[1]!);+ expect(closeSession).toHaveBeenLastCalledWith(childState, "killed");+ expect(internals.sessions.has(childState.activeSessionId)).toBe(false);++ // A registry failure must not strand the cancelled child as a stale resident session.+ internals.sessions.set(childState.activeSessionId, childState);+ internals.recordRlmSubagentDeletion = vi.fn(async () => {+ throw new Error("registry write failed");+ });+ await expect(+ internals+ .createSubagentRuntimeHost(parentState)+ .releaseRlmSubagentRuntime?.(+ { session: childState.runtime.session },+ { id: "child-1" } as CreateRlmSubagentRuntimeOptions,+ "cancelled",+ ),+ ).rejects.toThrow("registry write failed");+ expect(closeSession).toHaveBeenLastCalledWith(childState, "killed");expect(internals.sessions.has(childState.activeSessionId)).toBe(false);});@@ -516,6 +820,34 @@ describe("daemon mode helpers", () => {}});+ it("discovers a non-resident child left running in the persisted registry", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-orphan-running-child-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const registryPath = join(fixture.parentArtifactDir, "rlm-subagents.jsonl");+ const entry = JSON.parse(readFileSync(registryPath, "utf8")) as Record<string, unknown>;+ entry.status = "running";+ writeFileSync(registryPath, `${JSON.stringify(entry)}\n`);+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ listPassiveRlmSubagents(): Promise<Array<{ entry: { childId: string } }>>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });++ expect((await internals.listPassiveRlmSubagents()).map(({ entry }) => entry.childId)).toContain(+ fixture.childId,+ );+ await expect(internals.createAgentMessageController(() => parentState).roster?.()).resolves.toMatchObject({+ entries: [expect.objectContaining({ relationship: "child", name: "renamed-worker" })],+ });+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("persists explicit child depth for an in-memory daemon parent", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-in-memory-parent-depth-"));try {@@ -1224,6 +1556,87 @@ describe("daemon mode helpers", () => {}});+ it("routes worker-local session renames through the supervisor", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "pa-worker-rename-"));+ const socketPath = join(tempDir, "s");+ let receivedCommand: Record<string, unknown> | undefined;+ let releaseResponse: () => void = () => {};+ const responseGate = new Promise<void>((resolve) => {+ releaseResponse = resolve;+ });+ const server = createServer((socket) => {+ socket.write(+ `${JSON.stringify({+ type: "daemon_hello",+ socketPath,+ protocol: DAEMON_PROTOCOL_INFO,+ schemaRevision: DAEMON_SCHEMA_REVISION,+ serverCapabilities: [],+ clientId: "worker-rename-test",+ })}\n`,+ );+ let buffered = "";+ socket.on("data", (chunk: Buffer) => {+ buffered += chunk.toString("utf8");+ const newline = buffered.indexOf("\n");+ if (newline < 0 || receivedCommand) return;+ const wire = JSON.parse(buffered.slice(0, newline)) as Record<string, unknown>;+ receivedCommand = (wire.command as Record<string, unknown> | undefined) ?? wire;+ void responseGate.then(() => {+ socket.write(+ `${JSON.stringify({+ id: wire.id,+ type: "response",+ command: "set_session_name",+ success: true,+ })}\n`,+ );+ });+ });+ });+ const previousSocketPath = process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];+ try {+ await new Promise<void>((resolve, reject) => {+ server.once("error", reject);+ server.listen(socketPath, resolve);+ });+ process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = socketPath;+ const daemon = new AgentDaemon(join(tempDir, "worker.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir },+ createRuntime: vi.fn(),+ worker: { authenticationToken: "token" },+ });+ const setSessionName = vi.fn((_name: string) => undefined);+ const state = makeState("active");+ Object.assign(state.runtime, { session: { setSessionName } });+ const controller = (+ daemon as unknown as {+ createAgentMessageController(getCurrentState: () => ActiveSessionState): AgentSessionMessageController;+ }+ ).createAgentMessageController(() => state);++ const rename = controller.setSessionName?.("shared-root");+ // Workers and supervisors ship in one process tree, so no capability gate is needed; the+ // optional field remains compatible with old supervisors because envelope parsing preserves extra fields.+ await vi.waitFor(() =>+ expect(receivedCommand).toMatchObject({+ type: "set_session_name",+ activeSessionId: "active",+ name: "shared-root",+ workerToken: "token",+ }),+ );+ expect(setSessionName).not.toHaveBeenCalled();+ releaseResponse();+ await expect(rename).resolves.toBeUndefined();+ } finally {+ if (previousSocketPath === undefined) delete process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];+ else process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = previousSocketPath;+ await new Promise<void>((resolve) => server.close(() => resolve()));+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("does not retry permanent ambiguity errors from the supervisor", async () => {const tempDir = mkdtempSync(join(tmpdir(), "pa-ambiguous-"));const socketPath = join(tempDir, "s");@@ -1981,7 +2394,7 @@ describe("daemon mode helpers", () => {expect((await internals.createAgentMessageListResult(targetState)).agents[0]?.unfinishedActionCount).toBe(3);});- it("reports non-streaming busy sessions as active in agent-observe summaries", () => {+ it("reports non-streaming busy sessions as active in agent-observe summaries", async () => {const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },createRuntime: async () => {@@ -2016,17 +2429,366 @@ describe("daemon mode helpers", () => {} as never;const internals = daemon as unknown as {sessions: Map<string, ActiveSessionState>;- createAgentObserveListResult(current: ActiveSessionState): { current: { status: string } };+ createAgentObserveListResult(current: ActiveSessionState): Promise<{ current: { status: string } }>;};internals.sessions.set(targetState.activeSessionId, targetState);- expect(internals.createAgentObserveListResult(targetState).current.status).toBe("busy");+ expect((await internals.createAgentObserveListResult(targetState)).current.status).toBe("busy");(targetState.runtime.session as { isCompacting: boolean; unfinishedActionCount: number }).isCompacting = true;(targetState.runtime.session as { isCompacting: boolean; unfinishedActionCount: number }).unfinishedActionCount =0;- expect(internals.createAgentObserveListResult(targetState).current.status).toBe("compacting");+ expect((await internals.createAgentObserveListResult(targetState)).current.status).toBe("compacting");+ });++ it("canonicalizes symlinked family paths before comparison", () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-family-paths-"));+ try {+ const realDir = join(tempDir, "real");+ const aliasDir = join(tempDir, "alias");+ mkdirSync(realDir);+ symlinkSync(realDir, aliasDir, "dir");+ const daemon = new AgentDaemon("/tmp/prime-agent-family-paths.sock", {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir },+ createRuntime: vi.fn(),+ });+ const parent = makeState("parent");+ const child = makeState("child", "parent");+ parent.runtime = {+ ...parent.runtime,+ metadata: { ...parent.runtime.metadata, kind: "top-level" },+ session: { sessionId: "session-parent", sessionFile: join(realDir, "parent.jsonl") },+ } as never;+ child.runtime = {+ ...child.runtime,+ metadata: {+ ...child.runtime.metadata,+ parentSessionId: "session-parent",+ parentSessionFile: join(aliasDir, "parent.jsonl"),+ },+ session: { sessionId: "session-child", sessionFile: join(realDir, "child.jsonl") },+ } as never;+ const internals = daemon as unknown as {+ assertAgentFamilyReachable(current: ActiveSessionState, target: ActiveSessionState): void;+ };++ expect(() => internals.assertAgentFamilyReachable(parent, child)).not.toThrow();+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("resolves a reopened child's persisted header parent relative to its session file", () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-header-family-"));+ try {+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir },+ createRuntime: vi.fn(),+ });+ const parent = makeState("parent");+ const child = makeState("reopened-child");+ const otherRoot = makeState("other-root");+ parent.runtime = {+ ...parent.runtime,+ metadata: { kind: "top-level", createdAt: 1 },+ session: {+ sessionId: "session-parent",+ sessionFile: join(tempDir, "parent.jsonl"),+ sessionManager: { getHeader: () => ({ parentSession: undefined }) },+ },+ } as never;+ child.runtime = {+ ...child.runtime,+ metadata: { kind: "top-level", createdAt: 1 },+ session: {+ sessionId: "session-child",+ sessionFile: join(tempDir, "children", "child.jsonl"),+ rlmDepth: 1,+ sessionManager: { getHeader: () => ({ parentSession: "../parent.jsonl" }) },+ },+ } as never;+ otherRoot.runtime = {+ ...otherRoot.runtime,+ metadata: { kind: "top-level", createdAt: 1 },+ session: {+ sessionId: "session-other",+ sessionFile: join(tempDir, "other.jsonl"),+ sessionManager: { getHeader: () => ({ parentSession: undefined }) },+ },+ } as never;+ const internals = daemon as unknown as {+ assertAgentFamilyReachable(current: ActiveSessionState, target: ActiveSessionState): void;+ };++ expect(() => internals.assertAgentFamilyReachable(child, parent)).not.toThrow();+ expect(() => internals.assertAgentFamilyReachable(child, otherRoot)).toThrow(AGENT_FAMILY_REACH_ERROR);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("uses the persisted header parent after a runtime session replacement", () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-applied-family.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: vi.fn(),+ });+ const originalParent = makeState("original-parent");+ const persistedParent = makeState("persisted-parent");+ const child = makeState("child");+ originalParent.runtime = {+ ...originalParent.runtime,+ metadata: { kind: "top-level", createdAt: 1 },+ session: { sessionId: "session-original", sessionFile: "/tmp/original-parent.jsonl" },+ } as never;+ persistedParent.runtime = {+ ...persistedParent.runtime,+ metadata: { kind: "top-level", createdAt: 1 },+ session: { sessionId: "session-persisted", sessionFile: "/tmp/persisted-parent.jsonl" },+ } as never;+ child.runtime = {+ ...child.runtime,+ metadata: {+ kind: "subagent",+ createdAt: 1,+ parentSessionId: "session-original",+ parentSessionFile: "/tmp/original-parent.jsonl",+ },+ session: {+ sessionId: "session-child",+ sessionFile: "/tmp/child.jsonl",+ rlmDepth: 1,+ sessionManager: { getHeader: () => ({ parentSession: "/tmp/persisted-parent.jsonl" }) },+ },+ } as never;+ const internals = daemon as unknown as {+ assertAgentFamilyReachable(current: ActiveSessionState, target: ActiveSessionState): void;+ };++ expect(() => internals.assertAgentFamilyReachable(child, persistedParent)).not.toThrow();+ expect(() => internals.assertAgentFamilyReachable(child, originalParent)).toThrow(AGENT_FAMILY_REACH_ERROR);+ });++ it("labels a reopened header-linked child and parent consistently with family reach", () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-header-relationship.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: vi.fn(),+ });+ const parent = makeState("parent");+ const child = makeState("reopened-child");+ parent.runtime = {+ ...parent.runtime,+ metadata: { kind: "top-level", createdAt: 1 },+ session: {+ sessionId: "session-parent",+ sessionFile: "/tmp/parent.jsonl",+ sessionManager: { getHeader: () => ({ parentSession: undefined }) },+ },+ } as never;+ child.runtime = {+ ...child.runtime,+ metadata: { kind: "top-level", createdAt: 1 },+ session: {+ sessionId: "session-child",+ sessionFile: "/tmp/children/child.jsonl",+ rlmDepth: 1,+ sessionManager: { getHeader: () => ({ parentSession: "../parent.jsonl" }) },+ },+ } as never;+ const internals = daemon as unknown as {+ agentMessageRelationship(from: ActiveSessionState, target: ActiveSessionState): string | undefined;+ };++ expect(internals.agentMessageRelationship(child, parent)).toBe("child");+ expect(internals.agentMessageRelationship(parent, child)).toBe("parent");+ });++ it("limits agent send and observation to the nuclear family", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-family-reach.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const states = [+ makeState("root"),+ makeState("child", "root"),+ makeState("sibling", "root"),+ makeState("grandchild", "child"),+ makeState("cousin", "sibling"),+ ];+ const sessionIds = new Map(states.map((state) => [state.activeSessionId, `session-${state.activeSessionId}`]));+ for (const state of states) {+ const parentActiveSessionId = state.runtime.metadata.parentActiveSessionId;+ state.runtime = {+ ...state.runtime,+ cwd: "/tmp",+ diagnostics: [],+ modelFallbackMessage: undefined,+ metadata: {+ ...state.runtime.metadata,+ kind: parentActiveSessionId ? "subagent" : "top-level",+ ...(parentActiveSessionId+ ? {+ parentSessionId: sessionIds.get(parentActiveSessionId),+ parentSessionFile: `/tmp/${parentActiveSessionId}.jsonl`,+ }+ : {}),+ },+ session: {+ sessionId: sessionIds.get(state.activeSessionId),+ sessionName: state.activeSessionId,+ sessionFile: `/tmp/${state.activeSessionId}.jsonl`,+ sessionManager: {+ getCwd: () => "/tmp",+ getHeader: () => ({ created: new Date(0).toISOString() }),+ getSessionArtifactDir: () => undefined,+ },+ runtimeKind: parentActiveSessionId ? "subagent" : "top-level",+ rlmDepth: parentActiveSessionId+ ? state.activeSessionId === "grandchild" || state.activeSessionId === "cousin"+ ? 2+ : 1+ : 0,+ isStreaming: false,+ isCompacting: false,+ isBashRunning: false,+ isRetrying: false,+ isSessionActive: false,+ hasAcceptedPromptInFlight: false,+ unfinishedActionCount: 0,+ messages: [],+ state: { pendingToolCalls: new Set(), streamingMessage: undefined },+ hasRunningRlmChildren: () => false,+ getSessionActionSnapshot: () => ({ queuedCount: 0, steering: [], followUps: [] }),+ },+ } as never;+ }+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAgentMessageController(getCurrentState: () => ActiveSessionState): AgentSessionMessageController;+ createAgentObserveController(getCurrentState: () => ActiveSessionState): AgentObserveController;+ };+ for (const state of states) internals.sessions.set(state.activeSessionId, state);+ const child = states[1]!;+ const messaging = internals.createAgentMessageController(() => child);+ const observe = internals.createAgentObserveController(() => child);++ expect((await observe.listAgents()).agents.map((agent) => agent.activeSessionId)).toEqual([+ "root",+ "child",+ "sibling",+ "grandchild",+ ]);+ await expect(observe.getAgent("cousin")).rejects.toThrow(+ "Agent reach is limited to parent, siblings, and children",+ );+ await expect(observe.recentMessages({ target: "cousin" })).rejects.toThrow(+ "Agent reach is limited to parent, siblings, and children",+ );+ await expect(messaging.sendAgentMessage({ target: "cousin", message: "no" })).rejects.toThrow(+ "Agent reach is limited to parent, siblings, and children",+ );+ });++ it("resolves a duplicate session name to the only family-reachable agent", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-family-name-resolution.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: vi.fn(),+ });+ const observer = makeAgentFamilyState("observer", "observer");+ const familyHelper = makeAgentFamilyState("family-helper", "helper", observer.state);+ const otherRoot = makeAgentFamilyState("other-root", "other-root");+ const unrelatedHelper = makeAgentFamilyState("unrelated-helper", "helper", otherRoot.state);+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;+ createAgentObserveController(getCurrentState: () => ActiveSessionState | undefined): AgentObserveController;+ };+ for (const fixture of [observer, familyHelper, otherRoot, unrelatedHelper]) {+ internals.sessions.set(fixture.state.activeSessionId, fixture.state);+ }++ const observe = internals.createAgentObserveController(() => observer.state);+ await expect(observe.getAgent("helper")).resolves.toMatchObject({+ agent: { activeSessionId: familyHelper.state.activeSessionId },+ });+ await expect(observe.recentMessages({ target: "helper" })).resolves.toMatchObject({+ agent: { activeSessionId: familyHelper.state.activeSessionId },+ });+ await expect(+ internals+ .createAgentMessageController(() => observer.state)+ .sendAgentMessage({ target: "helper", message: "report progress" }),+ ).resolves.toMatchObject({ target: { activeSessionId: familyHelper.state.activeSessionId } });+ expect(familyHelper.acceptAgentMessagePrompt).toHaveBeenCalledOnce();+ expect(unrelatedHelper.acceptAgentMessagePrompt).not.toHaveBeenCalled();+ });++ it("keeps a session ID ambiguous when a reachable agent uses it as its name", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-family-id-ambiguity.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: vi.fn(),+ });+ const parent = makeAgentFamilyState("parent", "parent");+ const observer = makeAgentFamilyState("observer", "observer", parent.state);+ const sibling = makeAgentFamilyState("sibling", parent.state.runtime.session.sessionId, parent.state);+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;+ createAgentObserveController(getCurrentState: () => ActiveSessionState | undefined): AgentObserveController;+ };+ for (const fixture of [parent, observer, sibling]) {+ internals.sessions.set(fixture.state.activeSessionId, fixture.state);+ }+ const expectedError = `Ambiguous active session "${parent.state.runtime.session.sessionId}"`;++ await expect(+ internals.createAgentObserveController(() => observer.state).getAgent(parent.state.runtime.session.sessionId),+ ).rejects.toThrow(expectedError);+ await expect(+ internals+ .createAgentMessageController(() => observer.state)+ .sendAgentMessage({ target: parent.state.runtime.session.sessionId, message: "report progress" }),+ ).rejects.toThrow(expectedError);+ expect(parent.acceptAgentMessagePrompt).not.toHaveBeenCalled();+ expect(sibling.acceptAgentMessagePrompt).not.toHaveBeenCalled();+ });++ it("keeps a duplicate session name ambiguous when two family agents are reachable", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-family-name-ambiguity.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: vi.fn(),+ });+ const parent = makeAgentFamilyState("parent", "helper");+ const observer = makeAgentFamilyState("observer", "observer", parent.state);+ const sibling = makeAgentFamilyState("sibling", "helper", parent.state);+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;+ createAgentObserveController(getCurrentState: () => ActiveSessionState | undefined): AgentObserveController;+ };+ for (const fixture of [parent, observer, sibling]) {+ internals.sessions.set(fixture.state.activeSessionId, fixture.state);+ }+ const expectedError = 'Ambiguous active session "helper"';++ await expect(internals.createAgentObserveController(() => observer.state).getAgent("helper")).rejects.toThrow(+ expectedError,+ );+ await expect(+ internals+ .createAgentMessageController(() => observer.state)+ .sendAgentMessage({ target: "helper", message: "report progress" }),+ ).rejects.toThrow(expectedError);+ expect(parent.acceptAgentMessagePrompt).not.toHaveBeenCalled();+ expect(sibling.acceptAgentMessagePrompt).not.toHaveBeenCalled();});it("serializes concurrent agent messages to an idle target", async () => {@@ -3978,15 +4740,19 @@ describe("daemon mode helpers", () => {}});- it("makes daemon host controllers available during session_start extension binding", async () => {+ it("uses the binding session as its own list and roster context", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-controller-race-"));try {let listedAgentsDuringBind = 0;const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {const session = makeRuntimeSession(options.sessionManager);session.bindExtensions = vi.fn(async () => {- const result = await options.sessionOptions?.agentMessageController?.listAgents();+ const controller = options.sessionOptions?.agentMessageController;+ const result = await controller?.listAgents();expect(result?.current?.activeSessionId).toBeTruthy();+ await expect(controller?.roster?.()).resolves.toMatchObject({+ current: { id: session.sessionId },+ });listedAgentsDuringBind++;});return {@@ -4010,9 +4776,10 @@ describe("daemon mode helpers", () => {}).createRuntime.bind(daemon);- await create({ type: "create", sessionPath: join(tempDir, "session.jsonl") });+ await create({ type: "create", sessionPath: join(tempDir, "session-1.jsonl") });+ await create({ type: "create", sessionPath: join(tempDir, "session-2.jsonl") });- expect(listedAgentsDuringBind).toBe(1);+ expect(listedAgentsDuringBind).toBe(2);} finally {rmSync(tempDir, { recursive: true, force: true });}@@ -4350,7 +5117,7 @@ describe("daemon mode helpers", () => {}});- it("reopens a parent with completed children without creating child runtimes and lists them as passive", async () => {+ it("reports failed passive children as errors without creating child runtimes", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-list-"));try {const fixture = makePersistedRlmDaemonFixture(tempDir);@@ -4363,6 +5130,10 @@ describe("daemon mode helpers", () => {lines[0] = JSON.stringify(header);writeFileSync(sessionFile, lines.join("\n"));}+ const parentRegistry = join(fixture.parentArtifactDir, "rlm-subagents.jsonl");+ const failedEntry = JSON.parse(readFileSync(parentRegistry, "utf8").trim()) as Record<string, unknown>;+ // Failed children retain their last "running" registry row after the runtime is released.+ writeFileSync(parentRegistry, `${JSON.stringify({ ...failedEntry, status: "running" })}\n`);const internals = fixture.daemon as unknown as {sessions: Map<string, ActiveSessionState>;createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;@@ -4386,7 +5157,7 @@ describe("daemon mode helpers", () => {expect(children).toEqual([expect.objectContaining({id: fixture.childId,- status: "done",+ status: "error",}),expect.objectContaining({id: fixture.grandchildId,@@ -4397,7 +5168,8 @@ describe("daemon mode helpers", () => {expect(children.every((child) => child.activeSessionId === undefined)).toBe(true);// Snapshotting must reuse the passive registry walk without hydrating children.expect(fixture.createRuntime).toHaveBeenCalledOnce();- expect((await internals.createAgentMessageController(() => parentState).listAgents()).agents).toContainEqual(+ const listedAgents = await internals.createAgentMessageController(() => parentState).listAgents();+ expect(listedAgents.agents).toContainEqual(expect.objectContaining({activeSessionId: expect.any(String),sessionId: expect.any(String),@@ -4406,16 +5178,35 @@ describe("daemon mode helpers", () => {parentActiveSessionId: parentState.activeSessionId,status: "inactive",rlmChildId: fixture.childId,+ rlmChildRegistryStatus: "running",}),);- expect((await internals.createAgentMessageController(() => parentState).listAgents()).agents).toContainEqual(+ expect(listedAgents.agents).toContainEqual(expect.objectContaining({- activeSessionId: expect.any(String),sessionName: "nested-worker",status: "inactive",rlmChildId: fixture.grandchildId,+ rlmChildRegistryStatus: "completed",}),);+ const observeController = (+ fixture.daemon as unknown as {+ createAgentObserveController(getCurrentState: () => ActiveSessionState): AgentObserveController;+ }+ ).createAgentObserveController(() => parentState);+ const observedAgents = await observeController.listAgents();+ expect(observedAgents.agents).toContainEqual(+ expect.objectContaining({+ activeSessionId: expect.any(String),+ sessionName: "renamed-worker",+ runtimeKind: "subagent",+ status: "idle",+ messageCount: 1,+ rlmChildId: fixture.childId,+ }),+ );+ expect(fixture.createRuntime).toHaveBeenCalledOnce();+const messageController = internals.createAgentMessageController(() => parentState);await expect(messageController.roster?.()).resolves.toMatchObject({current: { id: parentState.runtime.session.sessionId, depth: 0 },@@ -4943,7 +5734,7 @@ describe("daemon mode helpers", () => {}});- it("hydrates only the ancestor chain when a nested passive child is messaged", async () => {+ it("rejects direct messages to nested passive grandchildren without hydrating them", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-nested-message-"));try {const fixture = makePersistedRlmDaemonFixture(tempDir);@@ -4953,23 +5744,28 @@ describe("daemon mode helpers", () => {createAgentMessageController(getCurrentState: () => ActiveSessionState | undefined,): AgentSessionMessageController;+ createAgentObserveController(getCurrentState: () => ActiveSessionState | undefined): AgentObserveController;};const parentState = await internals.createRuntime({type: "create",sessionPath: fixture.parentSessionFile,});+ const reachError = "Agent reach is limited to parent, siblings, and children";- await internals- .createAgentMessageController(() => parentState)- .sendAgentMessage({- target: "nested-worker",- message: "report nested progress",- });+ await expect(+ internals+ .createAgentMessageController(() => parentState)+ .sendAgentMessage({+ target: "nested-worker",+ message: "report nested progress",+ }),+ ).rejects.toThrow(reachError);+ const observe = internals.createAgentObserveController(() => parentState);+ await expect(observe.getAgent("nested-worker")).rejects.toThrow(reachError);+ await expect(observe.recentMessages({ target: "nested-worker" })).rejects.toThrow(reachError);- expect(fixture.createRuntime).toHaveBeenCalledTimes(3);- expect([...internals.sessions.values()].map((state) => state.runtime.metadata.rlmChildId)).toEqual(- expect.arrayContaining([fixture.childId, fixture.grandchildId]),- );+ expect([...internals.sessions.values()]).toEqual([parentState]);+ expect(fixture.createRuntime).toHaveBeenCalledOnce();} finally {rmSync(tempDir, { recursive: true, force: true });}@@ -6566,6 +7362,36 @@ describe("daemon mode helpers", () => {}});+ it("disposes a newly opened runtime when its requested root name collides", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-root-name-failure-"));+ try {+ const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => ({+ session: makeRuntimeSession(options.sessionManager),+ extensionsResult: { extensions: [], errors: [], runtime: {} } as never,+ services: { cwd: options.cwd, agentDir: options.agentDir } as never,+ diagnostics: [],+ }));+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir: tempDir },+ createRuntime,+ });+ const internals = daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ };+ await internals.createRuntime({ type: "create", sessionPath: join(tempDir, "first.jsonl"), name: "taken" });+ await expect(+ internals.createRuntime({ type: "create", sessionPath: join(tempDir, "second.jsonl"), name: "taken" }),+ ).rejects.toThrow("an agent of that name already exists at depth 0 under this parent");++ const failedSession = createRuntime.mock.results[1]?.value+ ? (await createRuntime.mock.results[1].value).session+ : undefined;+ expect(failedSession?.disposeAsync).toHaveBeenCalledOnce();+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("closes a registered RLM runtime when its requested session name cannot be persisted", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-child-name-failure-"));try {@@ -8985,6 +9811,54 @@ function makeRuntimeSession(} as unknown as Awaited<ReturnType<CreateAgentSessionRuntimeFactory>>["session"];}+function makeAgentFamilyState(+ activeSessionId: string,+ sessionName: string,+ parent?: ActiveSessionState,+): { state: ActiveSessionState; acceptAgentMessagePrompt: ReturnType<typeof vi.fn> } {+ const state = makeState(activeSessionId, parent?.activeSessionId);+ const acceptAgentMessagePrompt = vi.fn(+ (_message: string, options?: { preflightResult?: (didSucceed: boolean) => void }) => {+ options?.preflightResult?.(true);+ return Promise.resolve();+ },+ );+ const parentSessionId = parent?.runtime.session.sessionId;+ state.runtime = {+ ...state.runtime,+ cwd: "/tmp",+ diagnostics: [],+ metadata: {+ kind: parent ? "subagent" : "top-level",+ createdAt: 1,+ ...(parent ? { parentActiveSessionId: parent.activeSessionId, parentSessionId } : {}),+ },+ session: {+ sessionId: `session-${activeSessionId}`,+ sessionName,+ runtimeKind: parent ? "subagent" : "top-level",+ rlmDepth: parent ? (parent.runtime.session.rlmDepth ?? 0) + 1 : 0,+ isStreaming: false,+ isCompacting: false,+ isBashRunning: false,+ isRetrying: false,+ isSessionActive: false,+ hasAcceptedPromptInFlight: false,+ unfinishedActionCount: 0,+ messages: [],+ state: { pendingToolCalls: new Set(), streamingMessage: undefined },+ sessionManager: {+ getCwd: () => "/tmp",+ getHeader: () => ({ created: new Date(0).toISOString() }),+ },+ hasRunningRlmChildren: () => false,+ getSessionActionSnapshot: () => ({ queuedCount: 0, steering: [], followUps: [] }),+ acceptAgentMessagePrompt,+ },+ } as never;+ return { state, acceptAgentMessagePrompt };+}+function makeState(activeSessionId: string, parentActiveSessionId?: string): ActiveSessionState {return {activeSessionId,diff --git a/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.tsindex 6e1f784025..497c7e0170 100644--- a/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts@@ -2,7 +2,12 @@ import { mkdtempSync, rmSync } from "node:fs";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 {+ type AgentFamilyCatalogEntry,+ type AgentSessionMessageAgentSummary,+ assertAgentFamilyReach,+ sessionNameReservationKey,+} 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";@@ -13,8 +18,18 @@ 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>;+ createOrReuseWorker(+ clientId: string,+ command: { type: "create"; name?: string; sessionPath?: string },+ ): Promise<WorkerFixture>;assertSupervisorSavedSessionNameAvailable(sessionPath: string, name: string): Promise<void>;+ assertSavedSiblingNameAvailable(+ siblings: Array<Record<string, unknown>>,+ target: Record<string, unknown>,+ name: string,+ ): void;+ familyCatalogEntry(summary: SessionSummary): AgentFamilyCatalogEntry;+ handleCommand(client: object, command: Record<string, unknown>): Promise<unknown>;}interface WorkerFixture {@@ -24,6 +39,9 @@ interface WorkerFixture {rootActiveSessionId: string;rootSessionId: string;pid: number;+ authenticationToken: string;+ ownerClientId?: string;+ createCommand: { config: { cwd: string } };};client: {request: ReturnType<typeof vi.fn>;@@ -61,6 +79,8 @@ function worker(workerId: string, summaries: SessionSummary[] = []): WorkerFixturootActiveSessionId: `${workerId}-root-active`,rootSessionId: `${workerId}-root-session`,pid: 1,+ authenticationToken: `${workerId}-token`,+ createCommand: { config: { cwd: "/tmp/project" } },},client: {request: vi.fn(),@@ -199,7 +219,432 @@ describe("daemon supervisor passive subagent topology", () => {expect(launchWorker).not.toHaveBeenCalled();});- it("retains passive worker summaries and sends them to cross-worker agent peer maps", async () => {+ it("checks inactive root renames against every saved root", async () => {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-saved-root-rename-"));+ tempDirs.push(directory);+ const targetPath = join(directory, "target.jsonl");+ const duplicatePath = join(directory, "duplicate.jsonl");+ const target = {+ id: "target",+ path: targetPath,+ cwd: directory,+ created: new Date(0),+ modified: new Date(0),+ messageCount: 0,+ firstMessage: "",+ allMessagesText: "",+ };+ const duplicate = { ...target, id: "duplicate", path: duplicatePath, name: "taken" };+ 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 () => [target]),+ list: vi.fn(async () => [target, duplicate]),+ },+ });++ await expect(supervisor.assertSupervisorSavedSessionNameAvailable(targetPath, "taken")).rejects.toThrow(+ "an agent of that name already exists at depth 0 under this parent",+ );+ });++ it("retains a legacy child's parent edge when its depth is unknown", () => {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-legacy-family-"));+ 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 parentPath = join(directory, "parent.jsonl");+ const child = supervisor.familyCatalogEntry(+ summary({+ id: "legacy-child-active",+ sessionId: "legacy-child",+ parentSessionPath: parentPath,+ }),+ );+ const parent = supervisor.familyCatalogEntry(+ summary({ id: "parent-active", sessionId: "parent", sessionFile: parentPath, rlmDepth: 0 }),+ );+ const unrelated = supervisor.familyCatalogEntry(+ summary({ id: "unrelated-active", sessionId: "unrelated", rlmDepth: 0 }),+ );+ const forkedRoot = supervisor.familyCatalogEntry(+ summary({+ id: "forked-root-active",+ sessionId: "forked-root",+ parentSessionPath: parentPath,+ rlmDepth: 0,+ }),+ );++ expect(child).toMatchObject({ depth: 1, parentSessionPath: parent.sessionPath });+ expect(forkedRoot).not.toHaveProperty("parentSessionPath");+ expect(() => assertAgentFamilyReach(child, parent)).not.toThrow();+ expect(() => assertAgentFamilyReach(child, unrelated)).toThrow(+ "Agent reach is limited to parent, siblings, and children",+ );+ });++ it("compares legacy and modern saved siblings at one neutral depth", () => {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-legacy-sibling-name-"));+ tempDirs.push(directory);+ const parentSessionPath = join(directory, "parent.jsonl");+ const base = {+ cwd: directory,+ created: new Date(0),+ modified: new Date(0),+ messageCount: 0,+ firstMessage: "",+ allMessagesText: "",+ };+ const target = { ...base, id: "target", path: join(directory, "target.jsonl"), parentSessionPath, rlmDepth: 1 };+ const legacy = { ...base, id: "legacy", path: join(directory, "legacy.jsonl"), parentSessionPath, name: "taken" };+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {+ defaultSessionConfig: { agentDir: directory, cwd: directory },+ descriptorDir: join(directory, "workers"),+ }) as unknown as SupervisorInternals;++ expect(() => supervisor.assertSavedSiblingNameAvailable([target, legacy], target, "taken")).toThrow(+ "an agent of that name already exists at depth 1 under this parent",+ );+ });++ it("publishes an opening reservation before named create validation awaits", async () => {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-named-create-race-"));+ tempDirs.push(directory);+ const sessionPath = join(directory, "session.jsonl");+ let releaseSiblings!: () => void;+ const siblingGate = new Promise<void>((resolve) => {+ releaseSiblings = resolve;+ });+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {+ defaultSessionConfig: { agentDir: directory, cwd: directory },+ descriptorDir: join(directory, "workers"),+ }) as unknown as SupervisorInternals;+ const resident = worker("opened");+ const launchWorker = vi.fn(async () => resident);+ Object.assign(supervisor, {+ catalog: {+ resolve: vi.fn(async () => sessionPath),+ siblings: vi.fn(async () => {+ await siblingGate;+ return [];+ }),+ list: vi.fn(async () => []),+ },+ launchWorker,+ });++ const first = supervisor.createOrReuseWorker("client", { type: "create", name: "named", sessionPath });+ const second = supervisor.createOrReuseWorker("client", { type: "create", sessionPath });+ releaseSiblings();+ expect(await Promise.all([first, second])).toEqual([resident, resident]);+ expect(launchWorker).toHaveBeenCalledOnce();+ });++ it("uses injective structural session name reservation keys", () => {+ expect(sessionNameReservationKey({ name: "b:c", depth: 1, parentSessionPath: "/a" })).not.toBe(+ sessionNameReservationKey({ name: "c", depth: 1, parentSessionPath: "/a:b" }),+ );+ expect(sessionNameReservationKey({ name: "worker", depth: 1, parentSessionPath: "/a" })).toBe(+ sessionNameReservationKey({ name: "worker", depth: 1, parentSessionPath: "/a" }),+ );+ });++ it("holds a root rename reservation until the worker commits", async () => {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-root-rename-race-"));+ tempDirs.push(directory);+ const firstSummary = summary({+ id: "first-active",+ activeSessionId: "first-active",+ sessionId: "first-session",+ rlmDepth: 0,+ });+ const secondSummary = summary({+ id: "second-active",+ activeSessionId: "second-active",+ sessionId: "second-session",+ rlmDepth: 0,+ });+ let releaseRename: () => void = () => {};+ const renameGate = new Promise<void>((resolve) => {+ releaseRename = resolve;+ });+ const firstWorker = worker("first", [firstSummary]);+ firstWorker.client.request.mockImplementation(async (command: { type: string }) => {+ if (command.type === "list") return success(undefined, "list", { sessions: [firstSummary] });+ await renameGate;+ return success(undefined, "rename", firstSummary);+ });+ const secondWorker = worker("second", [secondSummary]);+ secondWorker.client.request.mockResolvedValue(success(undefined, "rename", secondSummary));+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {+ defaultSessionConfig: { agentDir: directory, cwd: directory },+ descriptorDir: join(directory, "workers"),+ }) as unknown as SupervisorInternals;+ supervisor.workers.set("first", firstWorker);+ supervisor.workers.set("second", secondWorker);+ Object.assign(supervisor, { catalog: { list: vi.fn(async () => []) } });+ const client = { id: "client", attachedActiveSessionIds: new Set<string>() };++ const first = supervisor.handleCommand(client, {+ type: "rename",+ activeSessionId: "first-active",+ name: "shared-root",+ });+ await vi.waitFor(() =>+ expect(firstWorker.client.request).toHaveBeenCalledWith(+ expect.objectContaining({ type: "rename" }),+ expect.any(Number),+ ),+ );+ await expect(+ supervisor.handleCommand(client, {+ type: "rename",+ activeSessionId: "second-active",+ name: "shared-root",+ }),+ ).rejects.toThrow("an agent of that name already exists at depth 0 under this parent");+ expect(secondWorker.client.request).not.toHaveBeenCalled();+ releaseRename();+ await expect(first).resolves.toMatchObject({ success: true });+ });++ it("allows only a resident worker token to rename a client-owned session", async () => {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-worker-rename-"));+ tempDirs.push(directory);+ const ownedSummary = summary({+ id: "owned-active",+ activeSessionId: "owned-active",+ sessionId: "owned-session",+ rlmDepth: 0,+ });+ const ownedWorker = worker("owned", [ownedSummary]);+ ownedWorker.descriptor.ownerClientId = "interactive-client";+ ownedWorker.client.request.mockResolvedValue(success(undefined, "set_session_name"));+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {+ defaultSessionConfig: { agentDir: directory, cwd: directory },+ descriptorDir: join(directory, "workers"),+ }) as unknown as SupervisorInternals;+ supervisor.workers.set("owned", ownedWorker);+ Object.assign(supervisor, { catalog: { list: vi.fn(async () => []) } });+ const workerClient = { id: "daemon-client:worker", attachedActiveSessionIds: new Set<string>() };++ await expect(+ supervisor.handleCommand(workerClient, {+ type: "set_session_name",+ activeSessionId: "owned-active",+ name: "renamed-by-worker",+ workerToken: "owned-token",+ }),+ ).resolves.toMatchObject({ success: true });+ expect(ownedWorker.client.request).toHaveBeenCalledWith(+ expect.objectContaining({ type: "set_session_name", activeSessionId: "owned-active" }),+ expect.any(Number),+ );++ ownedWorker.client.request.mockClear();+ for (const workerToken of [undefined, "foreign-token"]) {+ await expect(+ supervisor.handleCommand(workerClient, {+ type: "set_session_name",+ activeSessionId: "owned-active",+ name: "unauthorized",+ ...(workerToken ? { workerToken } : {}),+ }),+ ).rejects.toThrow("Unknown active session: owned-active");+ }+ expect(ownedWorker.client.request).not.toHaveBeenCalledWith(+ expect.objectContaining({ type: "set_session_name" }),+ expect.any(Number),+ );+ });++ it("serializes active saved-session renames until the worker commits", async () => {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-active-saved-rename-race-"));+ tempDirs.push(directory);+ const parentSessionPath = join(directory, "parent.jsonl");+ const firstPath = join(directory, "first.jsonl");+ const secondPath = join(directory, "second.jsonl");+ const firstSummary = summary({+ id: "first-active",+ activeSessionId: "first-active",+ sessionId: "first-session",+ sessionFile: firstPath,+ parentSessionPath,+ rlmDepth: 1,+ });+ const secondSummary = summary({+ id: "second-active",+ activeSessionId: "second-active",+ sessionId: "second-session",+ sessionFile: secondPath,+ parentSessionPath,+ rlmDepth: 1,+ });+ let releaseRename: () => void = () => {};+ const renameGate = new Promise<void>((resolve) => {+ releaseRename = resolve;+ });+ const firstWorker = worker("first", [firstSummary]);+ firstWorker.client.request.mockImplementation(async () => {+ await renameGate;+ return success(undefined, "rename_saved_session", firstSummary);+ });+ const secondWorker = worker("second", [secondSummary]);+ secondWorker.client.request.mockResolvedValue(success(undefined, "rename_saved_session", secondSummary));+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {+ defaultSessionConfig: { agentDir: directory, cwd: directory },+ descriptorDir: join(directory, "workers"),+ }) as unknown as SupervisorInternals;+ supervisor.workers.set("first", firstWorker);+ supervisor.workers.set("second", secondWorker);+ Object.assign(supervisor, {+ catalog: {+ siblings: vi.fn(async () => []),+ list: vi.fn(async () => []),+ },+ });+ const client = { id: "client", attachedActiveSessionIds: new Set<string>() };++ const first = supervisor.handleCommand(client, {+ type: "rename_saved_session",+ activeSessionId: "first-active",+ sessionPath: firstPath,+ name: "shared",+ });+ await vi.waitFor(() =>+ expect(firstWorker.client.request).toHaveBeenCalledWith(+ expect.objectContaining({ type: "rename_saved_session" }),+ expect.any(Number),+ ),+ );+ await expect(+ supervisor.handleCommand(client, {+ type: "rename_saved_session",+ activeSessionId: "second-active",+ sessionPath: secondPath,+ name: "shared",+ }),+ ).rejects.toThrow("an agent of that name already exists at depth 1 under this parent");+ expect(secondWorker.client.request).not.toHaveBeenCalled();+ releaseRename();+ await expect(first).resolves.toMatchObject({ success: true });+ });++ it("serializes same-scope inactive renames across catalog validation and commit", async () => {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-saved-rename-race-"));+ tempDirs.push(directory);+ const firstPath = join(directory, "first.jsonl");+ const secondPath = join(directory, "second.jsonl");+ const parentSessionPath = join(directory, "parent.jsonl");+ const saved = [firstPath, secondPath].map((path, index) => ({+ id: `saved-${index}`,+ path,+ cwd: directory,+ created: new Date(0),+ modified: new Date(0),+ messageCount: 0,+ firstMessage: "",+ allMessagesText: "",+ parentSessionPath,+ rlmDepth: 1,+ }));+ let releaseRename: () => void = () => {};+ const renameGate = new Promise<void>((resolve) => {+ releaseRename = resolve;+ });+ const rename = vi.fn(async () => renameGate);+ 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 () => saved),+ rename,+ },+ });+ const client = {};++ const first = supervisor.handleCommand(client, {+ type: "rename_saved_session",+ sessionPath: firstPath,+ name: "shared",+ });+ await vi.waitFor(() => expect(rename).toHaveBeenCalledOnce());+ await expect(+ supervisor.handleCommand(client, {+ type: "rename_saved_session",+ sessionPath: secondPath,+ name: "shared",+ }),+ ).rejects.toThrow("an agent of that name already exists at depth 1 under this parent");+ releaseRename();+ await expect(first).resolves.toMatchObject({ success: true });+ });++ it("reserves named child creates by parent scope until worker launch completes", async () => {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-child-create-race-"));+ tempDirs.push(directory);+ const parentSessionPath = join(directory, "parent.jsonl");+ const child = (id: string) => ({+ id,+ path: join(directory, `${id}.jsonl`),+ cwd: directory,+ created: new Date(0),+ modified: new Date(0),+ messageCount: 0,+ firstMessage: "",+ allMessagesText: "",+ parentSessionPath,+ rlmDepth: 1,+ });+ const firstChild = child("first-child");+ const secondChild = child("second-child");+ let releaseLaunch: () => void = () => {};+ const launchGate = new Promise<void>((resolve) => {+ releaseLaunch = resolve;+ });+ const launched = worker("opened");+ const launchWorker = vi.fn(async () => {+ await launchGate;+ return launched;+ });+ 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: {+ resolve: vi.fn(async (path: string) => path),+ siblings: vi.fn(async (path: string) => [path === firstChild.path ? firstChild : secondChild]),+ },+ launchWorker,+ });++ const first = supervisor.createOrReuseWorker("client", {+ type: "create",+ name: "shared-child",+ sessionPath: firstChild.path,+ });+ await vi.waitFor(() => expect(launchWorker).toHaveBeenCalledOnce());+ await expect(+ supervisor.createOrReuseWorker("client", {+ type: "create",+ name: "shared-child",+ sessionPath: secondChild.path,+ }),+ ).rejects.toThrow("an agent of that name already exists at depth 1 under this parent");+ releaseLaunch();+ await expect(first).resolves.toBe(launched);+ });++ it("retains passive worker summaries but syncs only roots to cross-worker peer maps", async () => {const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-passive-peers-"));tempDirs.push(directory);const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {@@ -215,6 +660,12 @@ describe("daemon supervisor passive subagent topology", () => {runtimeKind: "subagent",rlmChildId: "passive-child",});+ const firstRoot = summary({+ id: "first-root-active",+ activeSessionId: "first-root-active",+ sessionId: "first-root-session",+ runtimeKind: "top-level",+ });const first = worker("first");first.client.request.mockResolvedValue(success(undefined, "list", { sessions: [passive] }));const secondRoot = summary({@@ -233,20 +684,18 @@ describe("daemon supervisor passive subagent topology", () => {runtimeKind: "subagent",rlmChildId: "passive-child",});+ first.summaries.set(first.descriptor.rootActiveSessionId, firstRoot);await supervisor.syncAgentPeers();const secondPeerCommand = second.client.requestWorker.mock.calls[0]?.[0] as| { peers: AgentSessionMessageAgentSummary[] }| undefined;- expect(secondPeerCommand?.peers).toContainEqual(+ expect(secondPeerCommand?.peers).toEqual([expect.objectContaining({- activeSessionId: "passive-session",- sessionId: "passive-session",- sessionName: "passive-worker",- runtimeKind: "subagent",- status: "inactive",- rlmChildId: "passive-child",+ activeSessionId: "first-root-active",+ sessionId: "first-root-session",+ runtimeKind: "top-level",}),- );+ ]);});});diff --git a/packages/coding-agent/test/daemon-supervisor-process.test.ts b/packages/coding-agent/test/daemon-supervisor-process.test.tsindex 70e8c1a0e5..e013e9d134 100644--- a/packages/coding-agent/test/daemon-supervisor-process.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-process.test.ts@@ -546,6 +546,56 @@ describe("daemon supervisor resident workers", () => {await waitForSocketGone(socketPath);}, 60_000);+ it("delivers agent-origin messages between root siblings on separate workers", async () => {+ const root = tempDir();+ const agentDir = join(root, "agent");+ const projectDir = join(root, "project");+ const sessionDir = join(agentDir, "sessions");+ const socketPath = join(+ tmpdir(),+ `prime-supervisor-root-message-${process.pid}-${randomUUID().slice(0, 8)}.sock`,+ );+ mkdirSync(projectDir, { recursive: true });++ const supervisor = spawnSupervisor(agentDir, socketPath, projectDir);+ const client = await connectEventually(socketPath, supervisor);+ const createRoot = async (name: string) => {+ const response = await client.request({+ type: "create",+ name,+ config: { cwd: projectDir, agentDir, sessionDir, noTools: true, noExtensions: true },+ });+ expect(response.success).toBe(true);+ return requireSummary(response.success ? response.data : undefined);+ };+ const source = await createRoot("source-root");+ const target = await createRoot("target-root");+ expect(source.workerPid).not.toBe(target.workerPid);+ await startBlockingBash(client, target.activeSessionId ?? target.id, join(root, "target-root-blocker.ready"));++ const response = await client.request({+ type: "send_message",+ fromActiveSessionId: source.activeSessionId ?? source.id,+ targetActiveSessionId: target.activeSessionId ?? target.id,+ message: "hello sibling root",+ agentOrigin: true,+ });+ expect(response.success, JSON.stringify(response)).toBe(true);+ expect(response).toMatchObject({+ success: true,+ data: {+ source: "agent_message",+ target: { activeSessionId: target.activeSessionId ?? target.id },+ message: "hello sibling root",+ deliveryStatus: "queued",+ },+ });+ const shutdown = await client.request({ type: "shutdown" }, 10_000);+ expect(shutdown.success).toBe(true);+ client.close();+ await waitForSocketGone(socketPath);+ }, 30_000);+it("cancels an archived session heartbeat without spawning a worker", { tags: ["process-stress"] }, async () => {const root = tempDir();const agentDir = join(root, "agent");diff --git a/packages/coding-agent/test/extensions-runner.test.ts b/packages/coding-agent/test/extensions-runner.test.tsindex 228ab578ef..2f58f82538 100644--- a/packages/coding-agent/test/extensions-runner.test.ts+++ b/packages/coding-agent/test/extensions-runner.test.ts@@ -698,6 +698,20 @@ describe("ExtensionRunner", () => {});});+ describe("extension action plumbing", () => {+ it("returns asynchronous session-name failures to extensions", async () => {+ const runtime = createExtensionRuntime();+ const runner = new ExtensionRunner([], runtime, tempDir, sessionManager, modelRegistry);+ const failure = new Error("duplicate session name");+ runner.bindCore(+ { ...extensionActions, setSessionName: async () => Promise.reject(failure) },+ extensionContextActions,+ );++ await expect(runtime.setSessionName("duplicate")).rejects.toBe(failure);+ });+ });+describe("provider registration", () => {it("bindCore ignores invalid queued registrations and reports extension error", () => {const runtime = createExtensionRuntime();diff --git a/packages/coding-agent/test/fire-and-forget-protocol.test.ts b/packages/coding-agent/test/fire-and-forget-protocol.test.tsindex a5cda9eda6..17c5919725 100644--- a/packages/coding-agent/test/fire-and-forget-protocol.test.ts+++ b/packages/coding-agent/test/fire-and-forget-protocol.test.ts@@ -38,6 +38,21 @@ describe("fire-and-forget agent protocol", () => {expect(parseAgentSessionMessagePromptId(prompt)).toBe("agentmsg_spoof_attempt");});+ it("sanitizes relationship labels so routed messages remain parseable", () => {+ const prompt = createAgentSessionMessagePrompt({+ id: "agentmsg_relationship_label",+ source: "agent_message",+ message: "finished",+ from: { activeSessionId: "active-child", sessionId: "child-id", sessionName: "child\nextra" },+ fromRelationship: "child",+ target: endpoint,+ deliveryMode: "auto",+ });++ expect(prompt.startsWith("[from child:child extra]\nAgent-to-agent message received.")).toBe(true);+ expect(parseAgentSessionMessagePromptId(prompt)).toBe("agentmsg_relationship_label");+ });+it("labels a parent without requiring a name", () => {const prompt = createAgentSessionMessagePrompt({id: "agentmsg_task",diff --git a/packages/coding-agent/test/kernel-agent-message-skill.test.ts b/packages/coding-agent/test/kernel-agent-message-skill.test.tsindex 1093b047d3..053dde6ac7 100644--- a/packages/coding-agent/test/kernel-agent-message-skill.test.ts+++ b/packages/coding-agent/test/kernel-agent-message-skill.test.ts@@ -45,31 +45,8 @@ describe("agent-message skill over the kernel host bridge", () => {provisioner = new IpythonKernelProvisioner(tempDir, {pythonSkills: [bundledAgentMessageSkill()],hostHandlers: {- "agent_message.list": async (payload) => {- requests.push({ type: "agent_message.list", payload });- return {- current: { activeSessionId: "alpha", sessionId: "session-alpha" },- agents: [- {- activeSessionId: "alpha",- sessionId: "session-alpha",- cwd: tempDir,- isStreaming: false,- unfinishedActionCount: 0,- },- {- activeSessionId: "beta",- sessionId: "session-beta",- sessionName: "Beta",- cwd: tempDir,- isStreaming: true,- unfinishedActionCount: 1,- },- ],- };- },- "agent_message.roster": async (payload) => {- requests.push({ type: "agent_message.roster", payload });+ "agent_message.list_agents": async (payload) => {+ requests.push({ type: "agent_message.list_agents", payload });return {current: { name: "alpha", id: "session-alpha", depth: 0 },entries: [{ relationship: "sibling", name: "Beta", id: "session-beta", depth: 0, status: "idle" }],@@ -80,11 +57,7 @@ describe("agent-message skill over the kernel host bridge", () => {return {id: "agentmsg-test",source: "agent_message",- target: {- activeSessionId: payload.receiver_name ?? payload.target,- sessionId: "session-beta",- sessionName: "Beta",- },+ target: { activeSessionId: payload.receiver_name, sessionId: "session-beta", sessionName: "Beta" },from: { activeSessionId: "alpha", sessionId: "session-alpha" },message: payload.message,deliveryStatus: "queued",@@ -99,15 +72,15 @@ describe("agent-message skill over the kernel host bridge", () => {const result = await manager.execute(`import jsonagents = await agent_message.list_agents()-roster = await agent_message.roster()-receipt = await agent_message.send("hello beta", receiver_role="sibling", receiver_name="beta", mode="follow_up")-print(json.dumps({"agents": agents, "roster": roster, "receipt": receipt}, sort_keys=True))+receipt = await agent_message.send(+ "hello beta", receiver_role="sibling", receiver_name="beta", mode="follow_up"+)+print(json.dumps({"agents": agents, "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({+ expect(output.agents).toMatchObject({current: { id: "session-alpha", depth: 0 },entries: [{ relationship: "sibling", id: "session-beta", status: "idle" }],});@@ -127,9 +100,11 @@ print(json.dumps({"agents": agents, "roster": roster, "receipt": receipt}, sort_target: { activeSessionId: "beta", sessionId: "session-beta", sessionName: "Beta" },},]);- expect(requests[0]).toMatchObject({ type: "agent_message.list", payload: { type: "agent_message.list" } });- expect(requests[1]).toMatchObject({ type: "agent_message.roster", payload: { type: "agent_message.roster" } });- expect(requests[2]).toMatchObject({+ expect(requests[0]).toMatchObject({+ type: "agent_message.list_agents",+ payload: { type: "agent_message.list_agents" },+ });+ expect(requests[1]).toMatchObject({type: "agent_message.send",payload: {type: "agent_message.send",@@ -139,10 +114,76 @@ print(json.dumps({"agents": agents, "roster": roster, "receipt": receipt}, sort_mode: "follow_up",},});- expect(requests[2].payload).not.toHaveProperty("from");+ expect(requests[1].payload).not.toHaveProperty("from");+ });++ it("emits successful broadcast receipts and leaves short errors in the result", async () => {+ provisioner = new IpythonKernelProvisioner(tempDir, {+ pythonSkills: [bundledAgentMessageSkill()],+ hostHandlers: {+ "agent_message.send": async (payload) => ({+ receipts: [+ {+ id: "agentmsg-root",+ source: "agent_message",+ target: { activeSessionId: "root", sessionId: "session-root" },+ message: payload.message,+ deliveryStatus: "delivered",+ deliveredAt: "2026-08-03T00:00:00.000Z",+ deliveryMode: payload.mode,+ },+ { target: "sibling", error: "rate limited" },+ ],+ }),+ },+ });++ const manager = await provisioner.ensure();+ const result = await manager.execute(`+import json+receipt = await agent_message.send("all", "status")+print(json.dumps(receipt, sort_keys=True))+`);++ expect(result.status).toBe("ok");+ expect(JSON.parse(result.stdout.trim())).toMatchObject({+ receipts: [+ { id: "agentmsg-root", deliveryStatus: "delivered" },+ { target: "sibling", error: "rate limited" },+ ],+ });+ expect(result.sentAgentMessages).toEqual([+ {+ id: "agentmsg-root",+ message: "status",+ deliveryStatus: "delivered",+ target: { activeSessionId: "root", sessionId: "session-root" },+ },+ ]);+ });++ it("rejects broadcast combined with role selectors before reaching the host", async () => {+ provisioner = new IpythonKernelProvisioner(tempDir, {+ pythonSkills: [bundledAgentMessageSkill()],+ hostHandlers: {+ "agent_message.send": async () => {+ throw new Error("should not reach host");+ },+ },+ });++ const manager = await provisioner.ensure();+ const result = await manager.execute(`+try:+ await agent_message.send("all", "secret", receiver_role="sibling", receiver_name="beta")+except TypeError as error:+ print(f"TypeError: {error}")+`);+ expect(result.status).toBe("ok");+ expect(result.stdout.trim()).toBe("TypeError: broadcast cannot be combined with receiver_role/receiver_name");});- it("rejects an unknown receiver role instead of treating it as a legacy target", async () => {+ it("rejects a positional name target before reaching the host", async () => {provisioner = new IpythonKernelProvisioner(tempDir, {pythonSkills: [bundledAgentMessageSkill()],hostHandlers: {@@ -155,12 +196,14 @@ print(json.dumps({"agents": agents, "roster": roster, "receipt": receipt}, sort_const manager = await provisioner.ensure();const result = await manager.execute(`try:- await agent_message.send("done", receiver_role="Parent")-except ValueError as error:- print(f"ValueError: {error}")+ await agent_message.send("beta", "done")+except TypeError as error:+ print(f"TypeError: {error}")`);expect(result.status).toBe("ok");- expect(result.stdout.trim()).toBe('ValueError: receiver_role must be "parent", "sibling", or "child"');+ expect(result.stdout.trim()).toBe(+ "TypeError: positional agent_message.send targets are not supported; use receiver_role and receiver_name",+ );});it("validates mode before sending to the host", async () => {@@ -176,7 +219,7 @@ except ValueError as error:const manager = await provisioner.ensure();const result = await manager.execute(`try:- await agent_message.send("beta", "hello", mode="broadcast")+ await agent_message.send("hello", receiver_role="sibling", receiver_name="beta", mode="broadcast")except ValueError as error:print(f"ValueError: {error}")`);@@ -191,11 +234,7 @@ except ValueError as error:"agent_message.send": async (payload) => ({id: "agentmsg-background",source: "agent_message",- target: {- activeSessionId: payload.receiver_name ?? payload.target,- sessionId: "session-beta",- sessionName: "Beta",- },+ target: { activeSessionId: payload.receiver_name, sessionId: "session-beta", sessionName: "Beta" },message: payload.message,deliveryStatus: "delivered",deliveredAt: "2026-07-10T00:00:00.000Z",@@ -212,7 +251,7 @@ except ValueError as error:const result = await manager.execute(`async def send_later():await asyncio.sleep(0.05)- await agent_message.send("beta", "background hello")+ await agent_message.send("background hello", receiver_role="sibling", receiver_name="beta")background_send = asyncio.create_task(send_later())`,{ onLateSentAgentMessage: (message) => resolveLateMessage(message) },@@ -224,6 +263,7 @@ background_send = asyncio.create_task(send_later())`,id: "agentmsg-background",message: "background hello",deliveryStatus: "delivered",+ receiverRole: "sibling",target: { activeSessionId: "beta", sessionId: "session-beta", sessionName: "Beta" },});});diff --git a/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts b/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.tsindex 20d3dcc179..61de890c05 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@@ -260,15 +260,18 @@ describe("ENG-4649 subagent model selection", () => {try {harness.session.setThinkingLevel("high");const seenModels: string[] = [];- harness.setResponses([- (_context, _options, _state, model) => {+ const respond =+ (text: string) => (_context: unknown, _options: unknown, _state: unknown, model: { id: string }) => {seenModels.push(model.id);- return fauxAssistantMessage("initial child answer");- },- (_context, _options, _state, model) => {- seenModels.push(model.id);- return fauxAssistantMessage("follow-up child answer");- },+ return fauxAssistantMessage(text);+ };+ // The child completes without replying, so the parent receives a+ // host-injected terminal notice that consumes one parent-model turn.+ harness.setResponses([+ respond("initial child answer"),+ respond("terminal notice ack"),+ respond("follow-up child answer"),+ respond("terminal notice ack"),]);const result = await harness.session.runRlmChild("inspect the API", {@@ -287,7 +290,9 @@ describe("ENG-4649 subagent model selection", () => {await child!.prompt("check the follow-up", { expandPromptTemplates: false, source: "extension" });await child!.agent.waitForIdle();- expect(seenModels).toEqual(["child-model", "child-model"]);+ const childTurns = seenModels.filter((id) => id === "child-model");+ expect(childTurns).toHaveLength(2);+ expect(seenModels.filter((id) => id !== "child-model").every((id) => id.endsWith("parent-model"))).toBe(true);expect(child?.model?.id).toBe("child-model");expect(result.session_dir).not.toBeNull();const childSessions = await SessionManager.list(harness.tempDir, result.session_dir!);diff --git a/packages/coding-agent/test/system-prompt.test.ts b/packages/coding-agent/test/system-prompt.test.tsindex b601ffd48b..bbb128ef45 100644--- a/packages/coding-agent/test/system-prompt.test.ts+++ b/packages/coding-agent/test/system-prompt.test.ts@@ -80,7 +80,7 @@ describe("buildRlmPrompt", () => {"","Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, IPython kernel, and native call interface exposed to the model.","",- "RLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm('sub-task')`; admission returns a child handle immediately. Results arrive only through explicit `agent_message` replies or files, never as an `rlm()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.",+ "RLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm('sub-task')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.","","Treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.",].join("\n"),@@ -141,6 +141,54 @@ describe("buildRlmPrompt", () => {expect(prompt).not.toContain("Read each skill's SKILL.md for its API");});+ test("gates agent messaging and observation doctrine on installed Python skills", () => {+ const withoutCapabilities = buildRlmPrompt({+ cwd: "/repo",+ messagesPath: "/repo/session.jsonl",+ activeTools: ["ipython"],+ allowRecursion: true,+ depth: 1,+ });+ expect(withoutCapabilities).not.toContain("agent_message.send");+ expect(withoutCapabilities).not.toContain("agent_message.list_agents");+ expect(withoutCapabilities).not.toContain("agent_observe");++ const systemPromptWithoutCapabilities = buildSystemPrompt({+ selectedTools: ["ipython"],+ contextFiles: [],+ skills: [],+ cwd: "/repo",+ });+ expect(systemPromptWithoutCapabilities).not.toContain("agent_message.send");+ expect(systemPromptWithoutCapabilities).not.toContain("agent_observe");++ const withCapabilities = buildRlmPrompt({+ cwd: "/repo",+ messagesPath: "/repo/session.jsonl",+ installedSkills: ["agent_message", "agent_observe"],+ activeTools: ["ipython"],+ allowRecursion: true,+ depth: 1,+ });+ expect(withCapabilities).toContain("agent_message.send");+ expect(withCapabilities).toContain("agent_message.list_agents");+ expect(withCapabilities).toContain("agent_observe");+ expect(withCapabilities).toContain("restricted to your parent, siblings, and direct children");+ });++ test("does not prescribe kernel-only child replies without ipython", () => {+ const prompt = buildRlmPrompt({+ cwd: "/repo",+ messagesPath: "/repo/session.jsonl",+ installedSkills: ["agent_message"],+ activeTools: ["bash"],+ depth: 1,+ });++ expect(prompt).toContain("You are a child agent");+ expect(prompt).not.toContain("When a task calls for an answer, reply explicitly with `await agent_message.send");+ });+test("exposes the automatic child registry independently of observation skills", () => {const withoutObserve = buildRlmPrompt({cwd: "/repo",@@ -301,7 +349,7 @@ describe("buildSystemPrompt", () => {const prompt = buildSystemPrompt({selectedTools: ["ipython"],contextFiles: [],- skills: [pythonSkill("refine")],+ skills: [pythonSkill("refine"), pythonSkill("agent-message"), pythonSkill("agent-observe")],cwd: "/repo",messagesPath: "/repo/.pi/sessions/session.jsonl",harnessState,@@ -387,7 +435,7 @@ describe("buildSystemPrompt", () => {const prompt = buildSystemPrompt({selectedTools: ["ipython"],contextFiles: [],- skills: [pythonSkill("refine")],+ skills: [pythonSkill("refine"), pythonSkill("agent-message"), pythonSkill("agent-observe")],cwd: "/repo",messagesPath: "/repo/.pi/sessions/session.jsonl",});@@ -397,7 +445,7 @@ describe("buildSystemPrompt", () => {expect(prompt).toContain("Conversation log: /repo/.pi/sessions/session.jsonl");expect(prompt).toContain("await rlm('sub-task')");expect(prompt).toContain("returns at admission, not completion");- expect(prompt).toContain("Results arrive only through explicit `agent_message` replies or files");+ expect(prompt).toContain("Results arrive only through an available messaging capability or files");expect(prompt).toContain("recover direct child handles");expect(prompt).toContain("kernel restart or compaction");expect(prompt).toContain("rlm.list_subagents");@@ -406,6 +454,7 @@ describe("buildSystemPrompt", () => {expect(prompt).toContain("name='api-reviewer'");expect(prompt).toContain("session_dir");expect(prompt).toContain("agent_observe");+ expect(prompt).toContain("restricted to your parent, siblings, and direct children");});test("omits ipython-only subagent guidance when ipython is inactive", () => {diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.pyindex 83244c1443..0c746fec9b 100644--- a/prime-agent-runtime/src/rlm/__init__.py+++ b/prime-agent-runtime/src/rlm/__init__.py@@ -195,7 +195,7 @@ def _subagent_from_payload(payload: Any, operation: str = "rlm.list_subagents")raise RuntimeError(f"{operation} entry is missing session_name")if not isinstance(session_dir, str) or not session_dir:raise RuntimeError(f"{operation} entry is missing session_dir")- if status not in {"running", "completed"}:+ if status not in {"running", "completed", "error"}:raise RuntimeError(f"{operation} entry has invalid status")return RLMSubagent(rlm_child_id=child_id,diff --git a/prime-agent-runtime/test/test_subagent_registry.py b/prime-agent-runtime/test/test_subagent_registry.pyindex df1765e9ae..99b86038c0 100644--- a/prime-agent-runtime/test/test_subagent_registry.py+++ b/prime-agent-runtime/test/test_subagent_registry.py@@ -39,6 +39,28 @@ class RlmSubagentRegistryTest(unittest.TestCase):self.assertEqual(subagents[0].status, "completed")host_request.assert_awaited_once_with("rlm.list_subagents")++ def test_lists_failed_subagents_from_host(self) -> None:+ host_request = AsyncMock(+ return_value={+ "subagents": [+ {+ "rlm_child_id": "sub-failed",+ "active_session_id": None,+ "session_id": None,+ "session_name": "failed-worker",+ "session_dir": "/tmp/parent/sub-failed",+ "status": "error",+ }+ ]+ }+ )++ with patch.object(rlm_module, "host_request", host_request):+ subagents = asyncio.run(rlm_module.rlm.list_subagents())++ self.assertEqual(subagents[0].status, "error")+def test_forwards_orchestrator_chosen_name_and_model_to_host(self) -> None:host_request = AsyncMock(return_value={