A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
Derive daemon command sets and RLM spawn options from one definition each (#2954)
Sebastian Mülleref90ab0122ba
diff --git a/packages/coding-agent/.changes/daemon-guards.md b/packages/coding-agent/.changes/daemon-guards.mdnew file mode 100644index 0000000000..9d1d1b37d8--- /dev/null+++ b/packages/coding-agent/.changes/daemon-guards.md@@ -0,0 +1 @@+- Changed the daemon to take its supervisor and worker command lists from the protocol command table, and daemon-hosted subagents to take their session options from the same mapping as in-process subagents. No behavior change.diff --git a/packages/coding-agent/src/core/agent-session-runtime.ts b/packages/coding-agent/src/core/agent-session-runtime.tsindex 113f6ed92e..bf5efbac28 100644--- a/packages/coding-agent/src/core/agent-session-runtime.ts+++ b/packages/coding-agent/src/core/agent-session-runtime.ts@@ -49,6 +49,44 @@ export interface AgentSessionRuntimeMetadata {sessionDir?: string;}+/** Maps an RLM spawn request to child session options and runtime metadata. */+export function rlmSubagentRuntimeSpec(options: CreateRlmSubagentRuntimeOptions): {+ sessionOptions: AgentSessionCreationOptions;+ runtimeMetadata: AgentSessionRuntimeMetadata;+} {+ return {+ sessionOptions: {+ model: options.model,+ thinkingLevel: options.thinkingLevel,+ serviceTier: options.serviceTier,+ scopedModels: options.scopedModels,+ initialActiveToolNames: options.activeToolNames,+ allowedToolNames: options.allowedToolNames,+ customTools: options.customTools,+ includeGoals: options.includeGoals,+ includeCompactSkill: options.includeCompactSkill,+ rlmDepth: options.rlmDepth,+ rlmMaxDepth: options.rlmMaxDepth,+ rlmSessionDir: options.sessionDir,+ rlmParentNodeId: options.rlmParentNodeId,+ rlmParentAgent: options.parentSession.sessionName ?? options.parentSession.sessionId,+ semanticParentSessionId: options.parentSession.sessionId,+ semanticSpawnedByRequestId: options.spawnedByRequestId,+ },+ runtimeMetadata: {+ kind: "subagent",+ createdAt: Date.now(),+ parentSessionId: options.parentSession.sessionId,+ parentSessionFile: options.parentSession.sessionFile,+ rlmChildId: options.id,+ rlmParentNodeId: options.rlmParentNodeId,+ prompt: options.prompt,+ spawnCode: options.spawnCode,+ sessionDir: options.sessionDir,+ },+ };+}+function extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string {if (typeof content === "string") {return content;@@ -328,35 +366,7 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {sessionManager,sessionStartEvent: { type: "session_start", reason: "startup" },sessionConfig: this.sessionConfig,- sessionOptions: {- model: options.model,- thinkingLevel: options.thinkingLevel,- serviceTier: options.serviceTier,- scopedModels: options.scopedModels,- initialActiveToolNames: options.activeToolNames,- allowedToolNames: options.allowedToolNames,- customTools: options.customTools,- includeGoals: options.includeGoals,- includeCompactSkill: options.includeCompactSkill,- rlmDepth: options.rlmDepth,- rlmMaxDepth: options.rlmMaxDepth,- rlmSessionDir: options.sessionDir,- rlmParentNodeId: options.rlmParentNodeId,- rlmParentAgent: options.parentSession.sessionName ?? options.parentSession.sessionId,- semanticParentSessionId: options.parentSession.sessionId,- semanticSpawnedByRequestId: options.spawnedByRequestId,- },- runtimeMetadata: {- kind: "subagent",- createdAt: Date.now(),- parentSessionId: options.parentSession.sessionId,- parentSessionFile: options.parentSession.sessionFile,- rlmChildId: options.id,- rlmParentNodeId: options.rlmParentNodeId,- prompt: options.prompt,- spawnCode: options.spawnCode,- sessionDir: options.sessionDir,- },+ ...rlmSubagentRuntimeSpec(options),}),);this.subagentRuntimes.set(options.id, runtime);diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 3be6137192..2ab6b25a9c 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -74,6 +74,7 @@ import {type AgentSessionRuntimeMetadata,type CreateAgentSessionRuntimeFactory,createAgentSessionRuntime,+ rlmSubagentRuntimeSpec,} from "../../core/agent-session-runtime.js";import {type AgentCronJob,@@ -182,6 +183,7 @@ import {salvageDaemonCommandId,success,UPDATE_RESTART_DRAIN_COMMANDS,+ WORKER_DAEMON_COMMAND_TYPES,} from "./daemon-protocol.js";import { getDaemonRuntimeIdentity } from "./daemon-runtime-identity.js";import {@@ -288,109 +290,6 @@ function workerSupervisorLostExitMs(): number {return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_WORKER_SUPERVISOR_LOST_EXIT_MS;}-const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([- "ack_result",- "list",- "list_saved_sessions",- "create",- "attach",- "detach",- "kill",- "rename",- "prompt",- "cancel_prompt_admission",- "prompt_and_wait",- "steer",- "follow_up",- "restore_next_turn",- "restore_actions",- "append_custom_message",- "resume_queue",- "send_message",- "agent_messages_status",- "agent_messages_pause",- "agent_messages_resume",- "agent_messages_clear",- "abort",- "abort_and_send_queued",- "start_side_question",- "abort_side_question",- "execute_bash",- "execute_bash_and_wait",- "abort_bash",- "cancel_rlm_child",- "delete_rlm_subagent",- "wait_for_idle",- "wait_for_headless_completion",- "get_session_header",- "get_state",- "get_connection_state",- "get_messages",- "get_rlm_children",- "get_session_stats",- "get_context_tree",- "get_commands",- "get_resource_snapshot",- "replace_acp_mcp_servers",- "get_model_catalog",- "get_available_models",- "get_queue",- "mutate_queued_message",- "clear_queue",- "abort_and_clear_queue",- "acquire_session_input_pause",- "release_session_input_pause",- "cron_list",- "heartbeats_list",- "heartbeat_manage",- "cron_add",- "cron_cancel",- "heartbeat_get",- "heartbeat_set",- "heartbeat_update",- "set_model",- "cycle_model",- "set_scoped_models",- "set_thinking_level",- "set_service_tier",- "cycle_thinking_level",- "set_transport",- "set_steering_mode",- "set_follow_up_mode",- "set_auto_compaction",- "set_auto_retry",- "compact",- "refine",- "abort_compaction",- "abort_branch_summary",- "abort_retry",- "reload",- "new_session",- "switch_session",- "fork",- "navigate_tree",- "import_jsonl",- "export_html",- "export_jsonl",- "set_session_name",- "get_rlm_max_depth_status",- "set_rlm_max_depth",- "rename_saved_session",- "delete_saved_session",- "get_session_context",- "get_session_tree",- "get_user_messages_for_forking",- "get_last_assistant_text",- "get_system_prompt",- "get_tool_definition",- "set_session_entry_label",- "extension_ui_response",- "prepare_update_restart",- "retry_worker",- "restart",- "shutdown",-]);-const DAEMON_CLIENT_CAPABILITY_SET: ReadonlySet<string> = new Set(DAEMON_SUPPORTED_CLIENT_CAPABILITIES);const CLIENT_CATCHUP_RETRY_MS = 250;/**@@ -2947,23 +2846,16 @@ export class AgentDaemon {});let stateRef: ActiveSessionState | undefined;// Subagents inherit the parent's client env (e.g. herdr pane identity).- const runtime = await withClientEnv(parentState.clientEnv, () =>- createAgentSessionRuntime(this.options.createRuntime, {+ const runtime = await withClientEnv(parentState.clientEnv, () => {+ const spec = rlmSubagentRuntimeSpec(options);+ return createAgentSessionRuntime(this.options.createRuntime, {cwd: sessionManager.getCwd(),agentDir: parentState.runtime.services.agentDir,sessionManager,sessionStartEvent: { type: "session_start", reason: "startup" },sessionConfig: parentState.runtime.runtimeConfig,sessionOptions: {- model: options.model,- thinkingLevel: options.thinkingLevel,- serviceTier: options.serviceTier,- scopedModels: options.scopedModels,- initialActiveToolNames: options.activeToolNames,- allowedToolNames: options.allowedToolNames,- customTools: options.customTools,- includeGoals: options.includeGoals,- includeCompactSkill: options.includeCompactSkill,+ ...spec.sessionOptions,agentMessageController: this.createAgentMessageController(() => stateRef),agentObserveController: this.createAgentObserveController(() => stateRef),rlmHeartbeatController: {@@ -2992,28 +2884,10 @@ export class AgentDaemon {return this.deleteRlmHeartbeatForState(stateRef, id);},},- rlmDepth: options.rlmDepth,- rlmMaxDepth: options.rlmMaxDepth,- rlmSessionDir: options.sessionDir,- rlmParentNodeId: options.rlmParentNodeId,- rlmParentAgent: options.parentSession.sessionName ?? options.parentSession.sessionId,- semanticParentSessionId: options.parentSession.sessionId,- semanticSpawnedByRequestId: options.spawnedByRequestId,- },- runtimeMetadata: {- kind: "subagent",- createdAt: Date.now(),- parentActiveSessionId: parentState.activeSessionId,- parentSessionId: options.parentSession.sessionId,- parentSessionFile: options.parentSession.sessionFile,- rlmChildId: options.id,- rlmParentNodeId: options.rlmParentNodeId,- prompt: options.prompt,- spawnCode: options.spawnCode,- sessionDir: options.sessionDir,},- }),- );+ runtimeMetadata: { ...spec.runtimeMetadata, parentActiveSessionId: parentState.activeSessionId },+ });+ });let state: ActiveSessionState;try {state = await this.addRuntime(@@ -4031,7 +3905,7 @@ export class AgentDaemon {return;}- if (typeof parsed.type !== "string" || !DAEMON_COMMAND_TYPES.has(parsed.type)) {+ if (typeof parsed.type !== "string" || !WORKER_DAEMON_COMMAND_TYPES.has(parsed.type)) {const commandName = typeof parsed.type === "string" ? parsed.type : "unknown";const commandId = typeof parsed.id === "string" ? parsed.id : undefined;this.write(client, failure(commandId, commandName, `Unknown daemon command: ${commandName}`));diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.tsindex 72c44f0c43..2e27cb5b74 100644--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts@@ -863,6 +863,24 @@ export const DAEMON_COMMAND_COMPATIBILITY = {shutdown: LEGACY_DAEMON_COMMAND,} as const satisfies Record<DaemonCommandName, DaemonCommandCompatibility>;+/** Commands only the supervisor serves; a worker rejects them as unknown. */+const SUPERVISOR_ONLY_DAEMON_COMMANDS: ReadonlySet<string> = new Set([+ "complete_owned_session",+ "get_direct_worker_transport",+ "list_agent_peers",+ "promote_owned_session",+ "reattach",+ "roster_subscribe",+ "roster_unsubscribe",+] satisfies DaemonCommandName[]);++/** Commands the supervisor admits: every command in the compatibility table. */+export const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(Object.keys(DAEMON_COMMAND_COMPATIBILITY));++export const WORKER_DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(+ [...DAEMON_COMMAND_TYPES].filter((type) => !SUPERVISOR_ONLY_DAEMON_COMMANDS.has(type)),+);+/*** Which endpoint serves each command when a client holds both a supervisor* (control-plane) and a direct worker (session-plane) connection. Session isdiff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex bbf1fb89c6..298af07686 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -88,6 +88,7 @@ import {createDaemonEventMeta,DAEMON_COMMAND_COMPATIBILITY,DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION,+ DAEMON_COMMAND_TYPES,DAEMON_DEFAULT_CLIENT_CAPABILITIES,DAEMON_DEFAULT_SERVER_CAPABILITIES,DAEMON_PROTOCOL_INFO,@@ -257,115 +258,6 @@ const SCHEDULED_WAKE_CLIENT_ID = "scheduled-wake";const SUPERVISOR_CONFIG_FILE_NAME = "supervisor-config";const WORKER_STARTUP_GATE_FD = 3;-const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([- "ack_result",- "list",- "list_agent_peers",- "get_direct_worker_transport",- "roster_subscribe",- "roster_unsubscribe",- "list_saved_sessions",- "create",- "attach",- "reattach",- "detach",- "complete_owned_session",- "promote_owned_session",- "kill",- "rename",- "prompt",- "cancel_prompt_admission",- "prompt_and_wait",- "steer",- "follow_up",- "restore_next_turn",- "restore_actions",- "append_custom_message",- "resume_queue",- "send_message",- "agent_messages_status",- "agent_messages_pause",- "agent_messages_resume",- "agent_messages_clear",- "abort",- "abort_and_send_queued",- "start_side_question",- "abort_side_question",- "execute_bash",- "execute_bash_and_wait",- "abort_bash",- "cancel_rlm_child",- "delete_rlm_subagent",- "wait_for_idle",- "wait_for_headless_completion",- "get_session_header",- "get_state",- "get_connection_state",- "get_messages",- "get_rlm_children",- "get_session_stats",- "get_context_tree",- "get_commands",- "get_resource_snapshot",- "replace_acp_mcp_servers",- "get_model_catalog",- "get_available_models",- "get_queue",- "mutate_queued_message",- "clear_queue",- "abort_and_clear_queue",- "acquire_session_input_pause",- "release_session_input_pause",- "cron_list",- "heartbeats_list",- "heartbeat_manage",- "cron_add",- "cron_cancel",- "heartbeat_get",- "heartbeat_set",- "heartbeat_update",- "set_model",- "cycle_model",- "set_scoped_models",- "set_thinking_level",- "cycle_thinking_level",- "set_service_tier",- "set_transport",- "set_steering_mode",- "set_follow_up_mode",- "set_auto_compaction",- "set_auto_retry",- "compact",- "refine",- "abort_compaction",- "abort_branch_summary",- "abort_retry",- "reload",- "new_session",- "switch_session",- "fork",- "navigate_tree",- "import_jsonl",- "export_html",- "export_jsonl",- "set_session_name",- "get_rlm_max_depth_status",- "set_rlm_max_depth",- "rename_saved_session",- "delete_saved_session",- "get_session_context",- "get_session_tree",- "get_user_messages_for_forking",- "get_last_assistant_text",- "get_system_prompt",- "get_tool_definition",- "set_session_entry_label",- "extension_ui_response",- "prepare_update_restart",- "retry_worker",- "restart",- "shutdown",-]);// Commands proving the client tracks the catalog; only such clients receive heartbeats_changed pushes.const HEARTBEAT_TRACKING_COMMANDS: ReadonlySet<string> = new Set(["cron_list",diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex ac6922cdda..b115f76c97 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -23,7 +23,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { ENV_AGENT_DIR } from "../src/config.js";import { AGENT_FAMILY_REACH_ERROR, type AgentSessionMessageController } 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 CreateAgentSessionRuntimeFactory, rlmSubagentRuntimeSpec } from "../src/core/agent-session-runtime.js";import { installAgentTraceUpload } from "../src/core/agent-traces.js";import { AuthStorage } from "../src/core/auth-storage.js";import { type AgentCronJob, AgentCronJobStore } from "../src/core/cron-jobs.js";@@ -120,29 +120,43 @@ describe("daemon mode helpers", () => {hasRunningRlmChildren: () => false,getSessionActionSnapshot: () => ({ queuedCount: 0, steering: [], followUps: [] }),});+ const spawnOptions = (id: string, ignoreSessionIds?: string[]): CreateRlmSubagentRuntimeOptions => ({+ parentSession: parentState.runtime.session,+ id,+ prompt: "complete and persist",+ sessionName: "real-worker",+ sessionDir: join(parentManager.getSessionArtifactDir()!, id),+ model: { provider: "test", id: "model" } as Model<Api>,+ thinkingLevel: "off" as const,+ serviceTier: null,+ scopedModels: [],+ activeToolNames: [],+ customTools: [],+ includeGoals: false,+ includeCompactSkill: false,+ rlmDepth: 1,+ rlmMaxDepth: 4,+ rlmParentNodeId: id,+ spawnedByRequestId: "a".repeat(32),+ spawnCode: "rlm.spawn()",+ ...(ignoreSessionIds ? { ignoreSessionIds } : {}),+ });const spawn = (id: string, ignoreSessionIds?: string[]) =>- internals.createRlmSubagentRuntime(parentState, {- parentSession: parentState.runtime.session,- id,- prompt: "complete and persist",- sessionName: "real-worker",- sessionDir: join(parentManager.getSessionArtifactDir()!, id),- model: { provider: "test", id: "model" } as Model<Api>,- thinkingLevel: "off" as const,- serviceTier: null,- scopedModels: [],- activeToolNames: [],- customTools: [],- includeGoals: false,- includeCompactSkill: false,- rlmDepth: 1,- rlmMaxDepth: 4,- rlmParentNodeId: id,- ...(ignoreSessionIds ? { ignoreSessionIds } : {}),- });+ internals.createRlmSubagentRuntime(parentState, spawnOptions(id, ignoreSessionIds));const admission = spawn("child-1");await expect(spawn("child-2")).rejects.toThrow('Agent name "real-worker" is unavailable');const childRuntime = await admission;+ const spec = rlmSubagentRuntimeSpec(spawnOptions("child-1"));+ expect(createRuntime).toHaveBeenCalledWith(+ expect.objectContaining({+ sessionOptions: expect.objectContaining(spec.sessionOptions),+ runtimeMetadata: {+ ...spec.runtimeMetadata,+ createdAt: expect.any(Number),+ parentActiveSessionId: parentState.activeSessionId,+ },+ }),+ );const edges = await internals.rlmSpawnLedger().liveEdges();expect(edges.filter((edge) => edge.name === "real-worker")).toHaveLength(1);const childState = [...internals.sessions.values()].find(diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.tsindex f4411d172a..40d42a793c 100644--- a/packages/coding-agent/test/daemon-protocol.test.ts+++ b/packages/coding-agent/test/daemon-protocol.test.ts@@ -7,6 +7,7 @@ import {createDaemonReplayInfo,DAEMON_COMMAND_COMPATIBILITY,DAEMON_COMMAND_PLANE,+ DAEMON_COMMAND_TYPES,DAEMON_DEFAULT_SERVER_CAPABILITIES,DAEMON_PROTOCOL_INFO,type DaemonCommand,@@ -16,6 +17,7 @@ import {isSessionPlaneDaemonCommand,isSessionSummary,salvageDaemonCommandId,+ WORKER_DAEMON_COMMAND_TYPES,} from "../src/modes/daemon/daemon-protocol.js";import {type DaemonWorkerDescriptor,@@ -212,6 +214,21 @@ describe("daemon protocol helpers", () => {expect(isSessionPlaneDaemonCommand("no_such_command")).toBe(false);});+ it("admits every compatibility-table command, and workers reject only supervisor-only commands", () => {+ const supervisorOnly = [+ "complete_owned_session",+ "get_direct_worker_transport",+ "list_agent_peers",+ "promote_owned_session",+ "reattach",+ "roster_subscribe",+ "roster_unsubscribe",+ ];+ const commands = Object.keys(DAEMON_COMMAND_COMPATIBILITY);+ expect([...DAEMON_COMMAND_TYPES]).toEqual(commands);+ expect([...WORKER_DAEMON_COMMAND_TYPES]).toEqual(commands.filter((command) => !supervisorOnly.includes(command)));+ });+it("reports replay availability from resume cursors", () => {expect(createDaemonReplayInfo(undefined, 5, "generation-1")).toEqual({status: "complete",