A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(coding-agent): whole-tree idle eviction (#588)
Sebastian Müllerd93b3cbe0bca
diff --git a/packages/ai/src/models.generated.ts b/packages/ai/src/models.generated.tsindex 09bbafa213..dcff7be885 100644--- a/packages/ai/src/models.generated.ts+++ b/packages/ai/src/models.generated.ts@@ -4093,6 +4093,23 @@ export const MODELS = {contextWindow: 1000000,maxTokens: 384000,} satisfies Model<"anthropic-messages">,+ "accounts/fireworks/models/deepseek-v4-flash-0731": {+ id: "accounts/fireworks/models/deepseek-v4-flash-0731",+ name: "DeepSeek V4 Flash 0731",+ api: "anthropic-messages",+ provider: "fireworks",+ baseUrl: "https://api.fireworks.ai/inference",+ reasoning: true,+ input: ["text"],+ cost: {+ input: 0.14,+ output: 0.28,+ cacheRead: 0.028,+ cacheWrite: 0,+ },+ contextWindow: 1000000,+ maxTokens: 384000,+ } satisfies Model<"anthropic-messages">,"accounts/fireworks/models/deepseek-v4-pro": {id: "accounts/fireworks/models/deepseek-v4-pro",name: "DeepSeek V4 Pro",@@ -10658,13 +10675,13 @@ export const MODELS = {thinkingLevelMap: {"minimal":null,"low":null,"medium":null,"high":"high","xhigh":"max"},input: ["text"],cost: {- input: 0.14,- output: 0.28,- cacheRead: 0.0028,+ input: 0.09,+ output: 0.18,+ cacheRead: 0.018,cacheWrite: 0,},contextWindow: 1048576,- maxTokens: 384000,+ maxTokens: 65536,} satisfies Model<"openai-completions">,"deepseek/deepseek-v4-pro": {id: "deepseek/deepseek-v4-pro",@@ -11748,9 +11765,9 @@ export const MODELS = {reasoning: true,input: ["text", "image"],cost: {- input: 0.95,- output: 4,- cacheRead: 0.16,+ input: 0.6,+ output: 3.41,+ cacheRead: 0.19999999999999998,cacheWrite: 0,},contextWindow: 262144,@@ -12318,23 +12335,6 @@ export const MODELS = {contextWindow: 400000,maxTokens: 128000,} satisfies Model<"openai-completions">,- "openai/gpt-5.1-chat": {- id: "openai/gpt-5.1-chat",- name: "OpenAI: GPT-5.1 Chat",- api: "openai-completions",- provider: "openrouter",- baseUrl: "https://openrouter.ai/api/v1",- reasoning: false,- input: ["text", "image"],- cost: {- input: 1.25,- output: 10,- cacheRead: 0.13,- cacheWrite: 0,- },- contextWindow: 128000,- maxTokens: 32000,- } satisfies Model<"openai-completions">,"openai/gpt-5.1-codex": {id: "openai/gpt-5.1-codex",name: "OpenAI: GPT-5.1-Codex",@@ -12788,8 +12788,8 @@ export const MODELS = {input: ["text"],cost: {input: 0.03,- output: 0.14,- cacheRead: 0,+ output: 0.13,+ cacheRead: 0.03,cacheWrite: 0,},contextWindow: 131072,@@ -13332,12 +13332,12 @@ export const MODELS = {input: ["text"],cost: {input: 0.07,- output: 0.27,+ output: 0.28,cacheRead: 0,cacheWrite: 0,},contextWindow: 262144,- maxTokens: 32768,+ maxTokens: 262144,} satisfies Model<"openai-completions">,"qwen/qwen3-coder-flash": {id: "qwen/qwen3-coder-flash",@@ -14019,6 +14019,23 @@ export const MODELS = {contextWindow: 1048576,maxTokens: 4096,} satisfies Model<"openai-completions">,+ "thinkingmachines/inkling-small": {+ id: "thinkingmachines/inkling-small",+ name: "Thinking Machines: Inkling Small",+ api: "openai-completions",+ provider: "openrouter",+ baseUrl: "https://openrouter.ai/api/v1",+ reasoning: true,+ input: ["text", "image"],+ cost: {+ input: 0.5,+ output: 1.2,+ cacheRead: 0.09999999999999999,+ cacheWrite: 0,+ },+ contextWindow: 524288,+ maxTokens: 4096,+ } satisfies Model<"openai-completions">,"upstage/solar-pro-3": {id: "upstage/solar-pro-3",name: "Upstage: Solar Pro 3",@@ -14317,13 +14334,13 @@ export const MODELS = {reasoning: true,input: ["text"],cost: {- input: 1.12,- output: 3.52,- cacheRead: 0.20800000000000002,+ input: 0.2842,+ output: 0.8932,+ cacheRead: 0.05278,cacheWrite: 0,},contextWindow: 1048576,- maxTokens: 128000,+ maxTokens: 131072,} satisfies Model<"openai-completions">,"z-ai/glm-5v-turbo": {id: "z-ai/glm-5v-turbo",@@ -14410,6 +14427,25 @@ export const MODELS = {contextWindow: 1000000,maxTokens: 128000,} satisfies Model<"openai-completions">,+ "~deepseek/deepseek-v4-flash-latest": {+ id: "~deepseek/deepseek-v4-flash-latest",+ name: "DeepSeek V4 Flash Latest",+ api: "openai-completions",+ provider: "openrouter",+ baseUrl: "https://openrouter.ai/api/v1",+ compat: {"requiresReasoningContentOnAssistantMessages":true,"thinkingFormat":"deepseek"},+ reasoning: true,+ thinkingLevelMap: {"minimal":null,"low":null,"medium":null,"high":"high","xhigh":"max"},+ input: ["text"],+ cost: {+ input: 0.09,+ output: 0.18,+ cacheRead: 0.018,+ cacheWrite: 0,+ },+ contextWindow: 1048576,+ maxTokens: 65536,+ } satisfies Model<"openai-completions">,"~google/gemini-flash-latest": {id: "~google/gemini-flash-latest",name: "Google Gemini Flash Latest",@@ -16421,7 +16457,7 @@ export const MODELS = {cacheWrite: 0,},contextWindow: 1048576,- maxTokens: 128000,+ maxTokens: 131072,featured: true,} satisfies Model<"openai-completions">,},@@ -17396,8 +17432,25 @@ export const MODELS = {reasoning: true,input: ["text"],cost: {- input: 0.13799999999999998,- output: 0.275,+ input: 0.14,+ output: 0.28,+ cacheRead: 0.0028,+ cacheWrite: 0,+ },+ contextWindow: 1000000,+ maxTokens: 384000,+ } satisfies Model<"anthropic-messages">,+ "deepseek/deepseek-v4-flash-0731": {+ id: "deepseek/deepseek-v4-flash-0731",+ name: "DeepSeek V4 Flash 0731",+ api: "anthropic-messages",+ provider: "vercel-ai-gateway",+ baseUrl: "https://ai-gateway.vercel.sh",+ reasoning: true,+ input: ["text"],+ cost: {+ input: 0.13,+ output: 0.26,cacheRead: 0.028,cacheWrite: 0,},@@ -17683,7 +17736,7 @@ export const MODELS = {provider: "vercel-ai-gateway",baseUrl: "https://ai-gateway.vercel.sh",reasoning: true,- input: ["text"],+ input: ["text", "image"],cost: {input: 0.15,output: 0.6,@@ -17734,7 +17787,7 @@ export const MODELS = {provider: "vercel-ai-gateway",baseUrl: "https://ai-gateway.vercel.sh",reasoning: true,- input: ["text"],+ input: ["text", "image"],cost: {input: 0.74,output: 2.96,@@ -18091,7 +18144,7 @@ export const MODELS = {provider: "vercel-ai-gateway",baseUrl: "https://ai-gateway.vercel.sh",reasoning: false,- input: ["text"],+ input: ["text", "image"],cost: {input: 0.09999999999999999,output: 0.09999999999999999,@@ -18108,7 +18161,7 @@ export const MODELS = {provider: "vercel-ai-gateway",baseUrl: "https://ai-gateway.vercel.sh",reasoning: false,- input: ["text"],+ input: ["text", "image"],cost: {input: 0.15,output: 0.15,@@ -18176,7 +18229,7 @@ export const MODELS = {provider: "vercel-ai-gateway",baseUrl: "https://ai-gateway.vercel.sh",reasoning: false,- input: ["text"],+ input: ["text", "image"],cost: {input: 0.15,output: 0.15,@@ -19195,7 +19248,7 @@ export const MODELS = {provider: "vercel-ai-gateway",baseUrl: "https://ai-gateway.vercel.sh",reasoning: true,- input: ["text"],+ input: ["text", "image"],cost: {input: 0.09,output: 0.3,@@ -20271,24 +20324,6 @@ export const MODELS = {} satisfies Model<"anthropic-messages">,},"zai": {- "glm-4.5-air": {- id: "glm-4.5-air",- name: "GLM-4.5-Air",- api: "openai-completions",- provider: "zai",- baseUrl: "https://api.z.ai/api/coding/paas/v4",- compat: {"supportsDeveloperRole":false,"thinkingFormat":"zai"},- reasoning: true,- input: ["text"],- cost: {- input: 0,- output: 0,- cacheRead: 0,- cacheWrite: 0,- },- contextWindow: 131072,- maxTokens: 98304,- } satisfies Model<"openai-completions">,"glm-4.7": {id: "glm-4.7",name: "GLM-4.7",@@ -20325,24 +20360,6 @@ export const MODELS = {contextWindow: 200000,maxTokens: 131072,} satisfies Model<"openai-completions">,- "glm-5.1": {- id: "glm-5.1",- name: "GLM-5.1",- api: "openai-completions",- provider: "zai",- baseUrl: "https://api.z.ai/api/coding/paas/v4",- compat: {"supportsDeveloperRole":false,"thinkingFormat":"zai","zaiToolStream":true},- reasoning: true,- input: ["text"],- cost: {- input: 0,- output: 0,- cacheRead: 0,- cacheWrite: 0,- },- contextWindow: 200000,- maxTokens: 131072,- } satisfies Model<"openai-completions">,"glm-5.2": {id: "glm-5.2",name: "GLM-5.2",@@ -20361,22 +20378,22 @@ export const MODELS = {contextWindow: 1000000,maxTokens: 131072,} satisfies Model<"openai-completions">,- "glm-5v-turbo": {- id: "glm-5v-turbo",- name: "GLM-5V-Turbo",+ "glm-5.2-highspeed": {+ id: "glm-5.2-highspeed",+ name: "GLM-5.2 Highspeed",api: "openai-completions",provider: "zai",baseUrl: "https://api.z.ai/api/coding/paas/v4",compat: {"supportsDeveloperRole":false,"thinkingFormat":"zai","zaiToolStream":true},reasoning: true,- input: ["text", "image"],+ input: ["text"],cost: {input: 0,output: 0,cacheRead: 0,cacheWrite: 0,},- contextWindow: 200000,+ contextWindow: 1000000,maxTokens: 131072,} satisfies Model<"openai-completions">,},diff --git a/packages/coding-agent/src/core/session-action-store.ts b/packages/coding-agent/src/core/session-action-store.tsindex 8ed4979854..91ea4816b1 100644--- a/packages/coding-agent/src/core/session-action-store.ts+++ b/packages/coding-agent/src/core/session-action-store.ts@@ -309,6 +309,56 @@ export interface RuntimeActivity {disposing: boolean;}+export type IdleEvictionMinutes = number | "off";++export interface SessionEvictionSnapshot {+ isSessionActive: boolean;+ attachedClients: number;+ hasRegisteredHeartbeat: boolean;+ hasRegisteredCronJob: boolean;+ lastActivityAt: number;+}++export interface WorkerEvictionSnapshot {+ lifecycle: "starting" | "ready" | "recovering" | "failed";+ isConnected: boolean;+ isStopping: boolean;+ hasOwnerClient: boolean;+ isPreparingUpdateRestart: boolean;+ sessions: readonly SessionEvictionSnapshot[];+}++/** Pure whole-tree residency policy. Callers must supply supervisor-owned attachment state. */+export function canEvictWorker(+ worker: WorkerEvictionSnapshot,+ idleEvictionMinutes: IdleEvictionMinutes,+ now = Date.now(),+): boolean {+ if (+ idleEvictionMinutes === "off" ||+ !Number.isFinite(idleEvictionMinutes) ||+ idleEvictionMinutes <= 0 ||+ worker.lifecycle !== "ready" ||+ !worker.isConnected ||+ worker.isStopping ||+ worker.hasOwnerClient ||+ worker.isPreparingUpdateRestart ||+ worker.sessions.length === 0+ ) {+ return false;+ }+ const idleThresholdMs = idleEvictionMinutes * 60_000;+ return worker.sessions.every(+ (session) =>+ !session.isSessionActive &&+ session.attachedClients === 0 &&+ !session.hasRegisteredHeartbeat &&+ !session.hasRegisteredCronJob &&+ Number.isFinite(session.lastActivityAt) &&+ now - session.lastActivityAt >= idleThresholdMs,+ );+}+export function canSelectSessionAction(activity: RuntimeActivity): boolean {return (!activity.lowerAgentRun &&diff --git a/packages/coding-agent/src/core/settings-manager.ts b/packages/coding-agent/src/core/settings-manager.tsindex a6458508af..da98aed7b0 100644--- a/packages/coding-agent/src/core/settings-manager.ts+++ b/packages/coding-agent/src/core/settings-manager.ts@@ -6,6 +6,7 @@ import lockfile from "proper-lockfile";import { CONFIG_DIR_NAME, getAgentDir } from "../config.js";const RECENT_MODELS_LIMIT = 20;+export const DEFAULT_IDLE_EVICTION_MINUTES = 90;export interface CompactionSettings {enabled?: boolean; // default: true@@ -127,6 +128,7 @@ export interface Settings {defaultThinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";defaultServiceTier?: ServiceTier;rlmMaxDepth?: number; // default for new sessions; unset falls through to RLM_MAX_DEPTH, then 1+ idleEvictionMinutes?: number | "off"; // global daemon policy; default: 90transport?: TransportSetting; // default: "auto"steeringMode?: "all" | "one-at-a-time";followUpMode?: "all" | "one-at-a-time";@@ -754,6 +756,21 @@ export class SettingsManager {this.save();}+ getIdleEvictionMinutes(): number | "off" {+ const value: unknown = this.globalSettings.idleEvictionMinutes;+ if (value === "off" || value === "none") return "off";+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : DEFAULT_IDLE_EVICTION_MINUTES;+ }++ setIdleEvictionMinutes(value: number | "off"): void {+ if (value !== "off" && (!Number.isFinite(value) || value <= 0)) {+ throw new Error("Idle eviction minutes must be a positive number or off");+ }+ this.globalSettings.idleEvictionMinutes = value;+ this.markModified("idleEvictionMinutes");+ this.save();+ }+getTransport(): TransportSetting {return this.settings.transport ?? "auto";}diff --git a/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts b/packages/coding-agent/src/modes/daemon/daemon-catalog-process.tsindex 27fc7e0e6b..aabe580008 100644--- a/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts@@ -56,6 +56,21 @@ function deserializeSessionInfo(session: SessionInfoWire): SessionInfo {};}+/** @internal Exported to pin catalog selector semantics without spawning a catalog process. */+export function resolveCatalogSessionMatch(+ sessions: readonly SessionInfo[],+ selector: string,+): SessionInfo | undefined {+ // Deliberate broadening for create/resume as well as a2a wake: exact names+ // participate alongside id prefixes. Therefore a name that collides with an+ // id prefix is now ambiguous instead of the id-prefix match winning.+ const matches = sessions.filter((session) => session.id.startsWith(selector) || session.name === selector);+ if (matches.length > 1) {+ throw new Error(`Ambiguous session selector "${selector}"`);+ }+ return matches[0];+}+function isCatalogOutbound(value: unknown): value is CatalogOutbound {if (!value || typeof value !== "object") {return false;@@ -130,36 +145,32 @@ async function handleCatalogRequest(request: CatalogRequest): Promise<void> {return;}case "resolve": {- const localMatches = (await SessionManager.list(request.cwd, request.sessionDir)).filter((session) =>- session.id.startsWith(request.selector),+ const localMatch = resolveCatalogSessionMatch(+ await SessionManager.list(request.cwd, request.sessionDir),+ request.selector,);- if (localMatches.length === 1) {+ if (localMatch) {sendCatalogMessage({type: "response",id: request.id,success: true,- data: { sessionPath: localMatches[0]!.path },+ data: { sessionPath: localMatch.path },});return;}- if (localMatches.length > 1) {- throw new Error(`Ambiguous session selector "${request.selector}"`);- }- const globalMatches = (await SessionManager.listAll(undefined, request.sessionDir)).filter((session) =>- session.id.startsWith(request.selector),+ const globalMatch = resolveCatalogSessionMatch(+ await SessionManager.listAll(undefined, request.sessionDir),+ request.selector,);- if (globalMatches.length === 1) {+ if (globalMatch) {sendCatalogMessage({type: "response",id: request.id,success: true,- data: { sessionPath: globalMatches[0]!.path },+ data: { sessionPath: globalMatch.path },});return;}- if (globalMatches.length > 1) {- throw new Error(`Ambiguous session selector "${request.selector}"`);- }throw new Error(`No session found matching '${request.selector}'`);}case "rename":diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 9493175ad3..cf181df280 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -4426,15 +4426,6 @@ export class AgentDaemon {};}- private findRemoteAgentPeer(selector: string): AgentSessionMessageAgentSummary | undefined {- for (const peer of this.remoteAgentPeers.values()) {- if (peer.activeSessionId === selector || peer.sessionId === selector || peer.sessionName === selector) {- return peer;- }- }- return undefined;- }-// Half-bound sessions are hidden from other sessions' listings; the current// session stays visible to itself (controllers run during its own bind).private listTargetableSessionStates(current: ActiveSessionState): ActiveSessionState[] {@@ -4527,6 +4518,7 @@ export class AgentDaemon {throw new Error("Agent messaging is paused");}const targetSelector = assertDirectAgentMessageTarget(options.targetSelector);+ const message = normalizeAgentSessionMessage(options.message, DEFAULT_AGENT_MESSAGE_MAX_CHARS);let targetState: ActiveSessionState;try {targetState = this.getBoundSessionState(targetSelector);@@ -4544,11 +4536,13 @@ export class AgentDaemon {);if (hydratingChild) {targetState = await this.waitForBoundSession(hydratingChild);- } else if (this.options.worker && options.fromState && this.findRemoteAgentPeer(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,- options.message,+ message,options.deliveryMode,);} else {@@ -4560,7 +4554,6 @@ export class AgentDaemon {if (options.fromState?.activeSessionId === targetState.activeSessionId) {throw new Error("Agent messaging cannot target the sending session");}- const message = normalizeAgentSessionMessage(options.message, DEFAULT_AGENT_MESSAGE_MAX_CHARS);const releaseQueueSlot = this.reserveAgentMessageQueueSlot(targetState);const senderKey =options.senderKey ?? options.fromState?.activeSessionId ?? `client:${options.clientId ?? "unknown"}`;@@ -4620,6 +4613,7 @@ export class AgentDaemon {let lastError: unknown;while (Date.now() < deadline && !this.shuttingDown) {const client = new DaemonClient(supervisorSocketPath);+ let receivedResponse = false;try {await client.connect(1000);await client.waitForHello(1000);@@ -4633,6 +4627,7 @@ export class AgentDaemon {},30_000,);+ receivedResponse = true;if (!response.success) {throw deserializeDaemonError(response);}@@ -4641,10 +4636,10 @@ export class AgentDaemon {}return response.data as AgentSessionMessageReceipt;} catch (error) {- lastError = error;- if (error instanceof Error && error.message.startsWith("Unknown active session:")) {+ if (receivedResponse) {throw error;}+ lastError = error;} finally {client.close();}diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.tsindex 9c5a73ca89..27a4f68c1e 100644--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts@@ -54,8 +54,9 @@ export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 7;// Revision 9 publishes persisted RLM spawn depth on passive session rows.// 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.-export const DAEMON_SCHEMA_REVISION = 11;-export const DAEMON_SCHEMA_ID = "protocol-7-schema-11-5bd6b0b12204";+// Revision 12 publishes idle-residency metadata on session summary rows.+export const DAEMON_SCHEMA_REVISION = 12;+export const DAEMON_SCHEMA_ID = "protocol-7-schema-12-5bd6b0b12204";export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;export type DaemonProtocolVersion = number;diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.tsindex f81d81d680..5ba0a8e93e 100644--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts@@ -23,6 +23,7 @@ export type SessionActivity = "working" | "idle";// Upper bound on the spawn-code source carried in a session summary. Generous// enough for real spawn cells while keeping the daemon wire payload bounded.const SPAWN_CODE_MAX_CHARS = 4000;+const MAX_DATE_TIMESTAMP_MS = 8.64e15;// Lightweight daemon session shape used by list, create, rename, attach, and state responses.export interface SessionSummary {@@ -31,6 +32,12 @@ export interface SessionSummary {activity: SessionActivity;isSessionActive: boolean;hasActiveHeartbeat?: boolean;+ /** Any active heartbeat registered for this session. Paused heartbeats do not pin residency. */+ hasRegisteredHeartbeat?: boolean;+ /** Any active or paused non-heartbeat scheduled job registered for this session. */+ hasRegisteredCronJob?: boolean;+ /** Latest message activity, used by the supervisor residency policy. */+ lastActivityAt?: string;runtimeKind?: "top-level" | "subagent";/** RLM spawn depth (0 for roots); fork edges preserve the source depth. */rlmDepth?: number;@@ -102,11 +109,23 @@ export function buildSessionList(scheduledJobs: readonly AgentCronJob[] = [],): SessionSummary[] {const activeBySessionFile = new Map<string, ActiveSessionState>();- const heartbeatSessionIds = new Set(- scheduledJobs- .filter((job) => job.status === "active" && isHeartbeatCronJob(job))- .map((job) => job.activeSessionId),- );+ const heartbeatSessionIds = new Set<string>();+ const registeredHeartbeatSessionIds = new Set<string>();+ const registeredCronSessionIds = new Set<string>();+ const registeredHeartbeatSessionFiles = new Set<string>();+ const registeredCronSessionFiles = new Set<string>();+ for (const job of scheduledJobs) {+ const heartbeat = isHeartbeatCronJob(job);+ if (heartbeat && job.status === "active") heartbeatSessionIds.add(job.activeSessionId);+ // A paused heartbeat cannot fire, so unlike a live heartbeat (or a registered+ // cron job) it must not silently pin a worker forever.+ const registered = heartbeat ? job.status === "active" : job.status === "active" || job.status === "paused";+ if (!registered) continue;+ const ids = heartbeat ? registeredHeartbeatSessionIds : registeredCronSessionIds;+ const files = heartbeat ? registeredHeartbeatSessionFiles : registeredCronSessionFiles;+ ids.add(job.activeSessionId);+ files.add(resolve(job.sessionFile));+ }for (const activeSession of activeSessions) {const sessionFile = activeSession.runtime.session.sessionFile;@@ -126,18 +145,32 @@ export function buildSessionList(activeSession,savedSession,heartbeatSessionIds.has(activeSession.activeSessionId),+ registeredHeartbeatSessionIds.has(activeSession.activeSessionId),+ registeredCronSessionIds.has(activeSession.activeSessionId),),);seenActiveSessionIds.add(activeSession.activeSessionId);continue;}- entries.push(summaryForInactiveSession(savedSession));+ entries.push(+ summaryForInactiveSession(+ savedSession,+ registeredHeartbeatSessionFiles.has(sessionFile),+ registeredCronSessionFiles.has(sessionFile),+ ),+ );}for (const activeSession of activeSessions) {if (!seenActiveSessionIds.has(activeSession.activeSessionId)) {entries.push(- summaryForActiveSession(activeSession, undefined, heartbeatSessionIds.has(activeSession.activeSessionId)),+ summaryForActiveSession(+ activeSession,+ undefined,+ heartbeatSessionIds.has(activeSession.activeSessionId),+ registeredHeartbeatSessionIds.has(activeSession.activeSessionId),+ registeredCronSessionIds.has(activeSession.activeSessionId),+ ),);}}@@ -148,6 +181,8 @@ export function summaryForActiveSession(activeSession: ActiveSessionState,savedSession?: SessionInfo,hasActiveHeartbeat = false,+ hasRegisteredHeartbeat = hasActiveHeartbeat,+ hasRegisteredCronJob = false,): SessionSummary {const session = activeSession.runtime.session;const metadata = activeSession.runtime.metadata ?? { kind: "top-level" as const };@@ -166,6 +201,10 @@ export function summaryForActiveSession(activity: activeActivityForSession(activeSession),isSessionActive: session.isSessionActive,hasActiveHeartbeat: hasActiveHeartbeat || undefined,+ hasRegisteredHeartbeat: hasRegisteredHeartbeat || undefined,+ hasRegisteredCronJob: hasRegisteredCronJob || undefined,+ lastActivityAt:+ latestMessageActivityAt(session.messages) ?? modified ?? session.sessionManager.getHeader?.()?.timestamp,runtimeKind: metadata.kind,rlmDepth: session.rlmDepth,activeSessionId: activeSession.activeSessionId,@@ -214,17 +253,39 @@ export function summaryForActiveSession(};}+function latestMessageActivityAt(messages: readonly AgentMessage[]): string | undefined {+ let latest: number | undefined;+ for (const message of messages) {+ // Tool results and custom messages are real session activity too. Looking at+ // every timestamp also keeps this correct for future AgentMessage variants.+ if (+ typeof message.timestamp === "number" &&+ Number.isFinite(message.timestamp) &&+ Math.abs(message.timestamp) <= MAX_DATE_TIMESTAMP_MS+ ) {+ latest = latest === undefined ? message.timestamp : Math.max(latest, message.timestamp);+ }+ }+ return latest === undefined ? undefined : new Date(latest).toISOString();+}+export function isSummaryCurrent(activeSession: ActiveSessionState): boolean {const status = activeSession.summaryState;return status !== undefined && status.basedOnMessageCount === activeSession.runtime.session.messages.length;}-export function summaryForInactiveSession(session: SessionInfo): SessionSummary {+export function summaryForInactiveSession(+ session: SessionInfo,+ hasRegisteredHeartbeat = false,+ hasRegisteredCronJob = false,+): SessionSummary {return {id: session.id,lifecycle: inactiveLifecycleForSession(session),activity: "idle",isSessionActive: false,+ hasRegisteredHeartbeat: hasRegisteredHeartbeat || undefined,+ hasRegisteredCronJob: hasRegisteredCronJob || undefined,sessionId: session.id,sessionFile: session.path,sessionName: session.name,@@ -237,6 +298,7 @@ export function summaryForInactiveSession(session: SessionInfo): SessionSummarysessionActions: { queuedCount: 0, steering: [], followUps: [] },created: session.created.toISOString(),modified: session.modified.toISOString(),+ lastActivityAt: session.modified.toISOString(),firstMessage: session.firstMessage,parentSessionPath: session.parentSessionPath,rlmDepth: session.rlmDepth,diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex 54581b4274..d8546cd5f7 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -28,8 +28,14 @@ import {readActiveOrphanProcesses,} from "../../core/orphan-process-journal.js";import { PromptAdmissionCancelledError, waitForPromptAdmission } from "../../core/prompt-admission.js";+import {+ canEvictWorker,+ type IdleEvictionMinutes,+ 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 { SettingsManager } from "../../core/settings-manager.js";import { signalProcessGroupOrProcess } from "../../utils/child-process.js";import type { AgentConnectionHeartbeat } from "../agent-connection/types.js";import { attachJsonlLineReader, serializeJsonLine } from "../rpc/jsonl.js";@@ -118,6 +124,9 @@ const UPDATE_RESTART_PREPARE_DEADLINE_MS = 100_000;const WORKER_RETRY_DELAYS_MS = [250, 1000, 5000] as const;const DEFERRED_RECOVERY_RECHECK_MS = 5000;const OWNED_WORKER_DISCONNECT_GRACE_MS = 30_000;+const IDLE_EVICTION_MAX_SWEEP_INTERVAL_MS = 5 * 60_000;+const IDLE_EVICTION_MIN_SWEEP_INTERVAL_MS = 60_000;+const IDLE_EVICTION_DRAIN_TIMEOUT_MS = 5_000;const SUPERVISOR_CONFIG_FILE_NAME = "supervisor-config";const WORKER_STARTUP_GATE_FD = 3;@@ -466,6 +475,14 @@ function defaultWorkerDescriptorDir(agentDir: string, socketPath: string): strinreturn join(agentDir, "daemon-workers", descriptorKey(socketPath));}+export function idleEvictionSweepIntervalMs(idleEvictionMinutes: IdleEvictionMinutes): number {+ if (idleEvictionMinutes === "off") return IDLE_EVICTION_MAX_SWEEP_INTERVAL_MS;+ return Math.max(+ IDLE_EVICTION_MIN_SWEEP_INTERVAL_MS,+ Math.min(IDLE_EVICTION_MAX_SWEEP_INTERVAL_MS, (idleEvictionMinutes * 60_000) / 3),+ );+}+function workerSocketPath(supervisorSocketPath: string, workerId: string): string {const key = descriptorKey(supervisorSocketPath);if (process.platform === "win32") {@@ -575,6 +592,10 @@ export class DaemonSupervisor {private readonly compactCatchupInProgress = new Set<string>();private agentPeerSyncQueue: Promise<void> = Promise.resolve();private readonly catalog: DaemonCatalogClient;+ private readonly settingsManager: SettingsManager;+ private idleEvictionTimer?: ReturnType<typeof setTimeout>;+ private idleEvictionSweep?: Promise<void>;+ private idleEvictionFence?: Promise<void>;constructor(private readonly socketPath: string,@@ -594,6 +615,7 @@ export class DaemonSupervisor {this.defaultSessionConfig = this.loadPersistedSupervisorConfig() ?? options.defaultSessionConfig;this.snapshotCacheRoot = join(this.descriptorDir, "snapshot-cache", this.generation);this.catalog = new DaemonCatalogClient((message) => this.log(message));+ this.settingsManager = SettingsManager.create(process.cwd(), this.defaultSessionConfig.agentDir ?? agentDir);}async start(): Promise<void> {@@ -666,6 +688,7 @@ export class DaemonSupervisor {for (const worker of this.workers.values()) {this.scheduleOwnedWorkerCleanup(worker);}+ this.scheduleIdleEvictionSweep();await this.ownership.updatePhase("owner");this.log(`Prime Agent daemon supervisor ${this.generation} listening on ${this.socketPath}`);this.markReady();@@ -699,6 +722,121 @@ export class DaemonSupervisor {appendRotatingLog(getDaemonLogPath(this.socketPath), `[${new Date().toISOString()}] supervisor: ${message}`);}+ private clearIdleEvictionTimer(): void {+ if (!this.idleEvictionTimer) return;+ clearTimeout(this.idleEvictionTimer);+ this.idleEvictionTimer = undefined;+ }++ private scheduleIdleEvictionSweep(): void {+ if (this.shuttingDown || this.idleEvictionTimer || this.idleEvictionSweep) return;+ const delayMs = idleEvictionSweepIntervalMs(this.settingsManager.getIdleEvictionMinutes());+ this.idleEvictionTimer = setTimeout(() => {+ this.idleEvictionTimer = undefined;+ const sweep = this.runIdleEvictionSweep()+ .catch((error) => this.log(`Idle eviction sweep failed: ${String(error)}`))+ .finally(() => {+ if (this.idleEvictionSweep === sweep) this.idleEvictionSweep = undefined;+ this.scheduleIdleEvictionSweep();+ });+ this.idleEvictionSweep = sweep;+ }, delayMs);+ this.idleEvictionTimer.unref();+ }++ private workerEvictionSnapshot(worker: ResidentWorker): WorkerEvictionSnapshot {+ return {+ lifecycle: worker.descriptor.lifecycle,+ isConnected: worker.client !== undefined,+ isStopping: worker.intentionalStop || worker.descriptor.stopRequestedAt !== undefined,+ hasOwnerClient: worker.descriptor.ownerClientId !== undefined,+ isPreparingUpdateRestart:+ this.updateRestartPhase !== undefined || worker.updateRestartPrepareClient !== undefined,+ sessions: [...worker.summaries.values()].map((summary) => {+ const activeSessionId = summary.activeSessionId ?? summary.id;+ return {+ // Use the canonical busy projection: a parent remains active for+ // residency purposes while any of its RLM descendants is running.+ isSessionActive: isSessionSummaryBusy(summary),+ attachedClients: [...this.clients].filter((client) =>+ client.attachedActiveSessionIds.has(activeSessionId),+ ).length,+ hasRegisteredHeartbeat: summary.hasRegisteredHeartbeat === true,+ hasRegisteredCronJob: summary.hasRegisteredCronJob === true,+ lastActivityAt: Date.parse(summary.lastActivityAt ?? ""),+ };+ }),+ };+ }++ private async runIdleEvictionSweep(now = Date.now()): Promise<void> {+ if (this.shuttingDown || this.updateRestartPhase !== undefined || this.idleEvictionFence) return;+ await this.settingsManager.reload();+ if (this.shuttingDown || this.updateRestartPhase !== undefined) return;+ const idleEvictionMinutes = this.settingsManager.getIdleEvictionMinutes();+ if (idleEvictionMinutes === "off") return;++ const refreshed = new Set<ResidentWorker>();+ await Promise.all(+ [...this.workers.values()].map(async (worker) => {+ try {+ await this.refreshWorkerSummaries(worker);+ refreshed.add(worker);+ } catch {+ // A disconnected or transitioning worker is never an eviction candidate.+ }+ }),+ );+ const candidates = [...refreshed].filter((worker) =>+ canEvictWorker(this.workerEvictionSnapshot(worker), idleEvictionMinutes, now),+ );+ if (candidates.length === 0 || this.shuttingDown || this.updateRestartPhase !== undefined) return;++ let releaseFence: () => void = () => {};+ const fence = new Promise<void>((resolveFence) => {+ releaseFence = resolveFence;+ });+ this.idleEvictionFence = fence;+ try {+ await this.mutationDrain.waitForDrain(+ 0,+ AbortSignal.timeout(IDLE_EVICTION_DRAIN_TIMEOUT_MS),+ "Timed out draining daemon mutations for idle eviction",+ );+ if (this.shuttingDown || this.updateRestartPhase !== undefined) return;+ await Promise.all(+ candidates.map((worker) => this.refreshWorkerSummaries(worker).catch(() => refreshed.delete(worker))),+ );+ if (this.shuttingDown || this.updateRestartPhase !== undefined) return;+ const evictable = candidates.filter(+ (worker) =>+ refreshed.has(worker) &&+ this.workers.get(worker.descriptor.workerId) === worker &&+ canEvictWorker(this.workerEvictionSnapshot(worker), idleEvictionMinutes, now),+ );+ // Promise.all may reject and release the fence while sibling stops are still+ // finishing. That is safe: a racing mutation either reaches a live worker or+ // gets a clean disconnected/unknown-session error.+ await Promise.all(+ evictable.map(async (worker) => {+ if (this.shuttingDown || this.updateRestartPhase !== undefined) return;+ const snapshot = this.workerEvictionSnapshot(worker);+ const idleMinutes = Math.floor(+ Math.min(...snapshot.sessions.map((session) => now - session.lastActivityAt)) / 60_000,+ );+ const root = worker.summaries.get(worker.descriptor.rootActiveSessionId);+ await this.stopWorker(worker, true);+ this.log(+ `Evicted idle worker ${worker.descriptor.workerId} root=${root?.sessionId ?? worker.descriptor.rootSessionId ?? worker.descriptor.rootActiveSessionId} idleMinutes=${idleMinutes} sessions=${snapshot.sessions.length}`,+ );+ }),+ );+ } finally {+ if (this.idleEvictionFence === fence) this.idleEvictionFence = undefined;+ releaseFence();+ }+ }+private async assertCurrentOwnership(): Promise<void> {const ownership = this.ownership;if (!ownership) {@@ -1160,6 +1298,13 @@ export class DaemonSupervisor {}}+ if (mutation && !UPDATE_RESTART_DRAIN_COMMANDS.has(command.type)) {+ const idleEvictionFence = this.idleEvictionFence;+ if (idleEvictionFence) await idleEvictionFence;+ }+ // Attach is intentionally read-only and is not fence-gated. If eviction wins+ // the race, attach fails cleanly with "Session worker is not connected" and+ // the client retries through the saved-session path instead of mutating state.if (mutation) this.mutationDrain.begin();try {const response = await this.handleCommand(client, command, cancellationAdmission);@@ -1584,18 +1729,53 @@ export class DaemonSupervisor {}if (command.type === "send_message") {- const target = await this.findWorkerForClient(client, command.targetActiveSessionId);const source = command.fromActiveSessionId? await this.findWorkerForClient(client, command.fromActiveSessionId): undefined;- if (source && source.worker !== target.worker) {+ let target: WorkerMatch;+ try {+ target = await this.findWorkerForClient(client, command.targetActiveSessionId);+ } catch (error) {+ if (!(error instanceof Error) || !error.message.startsWith("Unknown active session:")) throw error;+ const cwd = source?.summary.cwd ?? this.defaultSessionConfig.cwd ?? process.cwd();+ let sessionPath: string;+ try {+ sessionPath = await this.catalog.resolve(+ command.targetActiveSessionId,+ cwd,+ source?.worker.descriptor.createCommand.config?.sessionDir ?? this.defaultSessionConfig.sessionDir,+ );+ } catch (catalogError) {+ // Preserve selector ambiguity so a2a senders can distinguish it from+ // the original unknown-active-session lookup failure.+ if (catalogError instanceof Error && catalogError.message.startsWith("Ambiguous session selector")) {+ throw catalogError;+ }+ throw error;+ }+ const worker = await this.createOrReuseWorker(this.protocolClientId(client), {+ type: "create",+ sessionPath,+ continueRecent: false,+ });+ const summary =+ this.findSummaryInWorker(worker, sessionPath) ??+ worker.summaries.get(worker.descriptor.rootActiveSessionId);+ if (!summary) throw new Error("Woken session worker has no target session");+ target = { worker, summary };+ }+ const targetActiveSessionId = target.summary.activeSessionId ?? target.summary.id;+ if (source) {+ if ((source.summary.activeSessionId ?? source.summary.id) === targetActiveSessionId) {+ throw new Error("Agent messaging cannot target the sending session");+ }if (!target.worker.client) {throw new Error("Target session worker is not connected");}const response = await target.worker.client.requestWorker({type: "worker_deliver_message",- targetActiveSessionId: target.summary.activeSessionId ?? target.summary.id,+ targetActiveSessionId,message: command.message,sender: {activeSessionId: source.summary.activeSessionId ?? source.summary.id,@@ -1610,7 +1790,7 @@ export class DaemonSupervisor {);return { ...response, id: command.id, command: command.type };}- return this.forwardToWorker(target.worker, command);+ return this.forwardToWorker(target.worker, { ...command, targetActiveSessionId });}if (!("activeSessionId" in command) || typeof command.activeSessionId !== "string") {@@ -4271,6 +4451,8 @@ export class DaemonSupervisor {private async cleanupSupervisorResourcesOnce(): Promise<void> {this.shuttingDown = true;+ this.clearIdleEvictionTimer();+ await this.idleEvictionSweep?.catch(() => undefined);for (const cleanup of this.signalCleanupHandlers.splice(0)) {await this.runCleanupStep("signal handler", cleanup);}@@ -4368,6 +4550,8 @@ export class DaemonSupervisor {process.exit(exitCode);}this.shuttingDown = true;+ this.clearIdleEvictionTimer();+ await this.idleEvictionSweep?.catch(() => undefined);if (closingReason) {for (const client of this.clients) {this.write(client, { type: "daemon_closing", reason: closingReason });diff --git a/packages/coding-agent/src/modes/interactive/components/settings-selector.ts b/packages/coding-agent/src/modes/interactive/components/settings-selector.tsindex 416d851568..3f8c757658 100644--- a/packages/coding-agent/src/modes/interactive/components/settings-selector.ts+++ b/packages/coding-agent/src/modes/interactive/components/settings-selector.ts@@ -10,6 +10,7 @@ import {Spacer,Text,} from "@earendil-works/pi-tui";+import type { IdleEvictionMinutes } from "../../../core/session-action-store.js";import type { WarningSettings } from "../../../core/settings-manager.js";import { getSelectListTheme, getSettingsListTheme, theme } from "../theme/theme.js";import { DynamicBorder } from "./dynamic-border.js";@@ -31,6 +32,7 @@ const THINKING_DESCRIPTIONS: Record<ThinkingLevel, string> = {export interface SettingsConfig {autoCompact: boolean;+ idleEvictionMinutes: IdleEvictionMinutes;showImages: boolean;autoResizeImages: boolean;blockImages: boolean;@@ -57,6 +59,7 @@ export interface SettingsConfig {export interface SettingsCallbacks {onAutoCompactChange: (enabled: boolean) => void;+ onIdleEvictionMinutesChange: (value: IdleEvictionMinutes) => void;onShowImagesChange: (enabled: boolean) => void;onAutoResizeImagesChange: (enabled: boolean) => void;onBlockImagesChange: (blocked: boolean) => void;@@ -209,6 +212,13 @@ export class SettingsSelectorComponent extends Container {currentValue: config.autoCompact ? "true" : "false",values: ["true", "false"],},+ {+ id: "idle-eviction-minutes",+ label: "Idle worker eviction",+ description: "Stop fully idle agent trees after this many minutes (global daemon policy)",+ currentValue: String(config.idleEvictionMinutes),+ values: ["off", "30", "60", "90", "180", "360"],+ },{id: "steering-mode",label: "Steering mode",@@ -440,6 +450,9 @@ export class SettingsSelectorComponent extends Container {case "autocompact":callbacks.onAutoCompactChange(newValue === "true");break;+ case "idle-eviction-minutes":+ callbacks.onIdleEvictionMinutesChange(newValue === "off" ? "off" : parseInt(newValue, 10));+ break;case "show-images":callbacks.onShowImagesChange(newValue === "true");break;diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 4f6fadc54b..5b3ff9f1ee 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -7195,6 +7195,7 @@ export class InteractiveMode {const selector = new SettingsSelectorComponent({autoCompact: state.autoCompactionEnabled,+ idleEvictionMinutes: this.settingsManager.getIdleEvictionMinutes(),showImages: this.settingsManager.getShowImages(),autoResizeImages: this.settingsManager.getImageAutoResize(),blockImages: this.settingsManager.getBlockImages(),@@ -7226,6 +7227,9 @@ export class InteractiveMode {});this.footer.setAutoCompactEnabled(enabled);},+ onIdleEvictionMinutesChange: (value) => {+ this.settingsManager.setIdleEvictionMinutes(value);+ },onShowImagesChange: (enabled) => {this.settingsManager.setShowImages(enabled);for (const child of this.chatContainer.children) {diff --git a/packages/coding-agent/test/daemon-catalog-process.test.ts b/packages/coding-agent/test/daemon-catalog-process.test.tsnew file mode 100644index 0000000000..98282f4e43--- /dev/null+++ b/packages/coding-agent/test/daemon-catalog-process.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import type { SessionInfo } from "../src/core/session-manager.js";+import { resolveCatalogSessionMatch } from "../src/modes/daemon/daemon-catalog-process.js";++function session(id: string, name: string | undefined, path: string): SessionInfo {+ return {+ id,+ name,+ path,+ cwd: "/tmp/project",+ rlmDepth: 0,+ created: new Date(0),+ modified: new Date(0),+ messageCount: 0,+ firstMessage: "",+ allMessagesText: "",+ };+}++describe("daemon catalog selector resolution", () => {+ it("treats an exact name colliding with another session id prefix as ambiguous", () => {+ const sessions = [+ session("named-session-id", "target", "/tmp/by-name.jsonl"),+ session("target-prefix-id", "other", "/tmp/by-prefix.jsonl"),+ ];++ expect(() => resolveCatalogSessionMatch(sessions, "target")).toThrow('Ambiguous session selector "target"');+ });+});diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex 85f8f77175..91a5afd71c 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -1,11 +1,11 @@import { EventEmitter } from "node:events";import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";-import type { Socket } from "node:net";+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 } from "../src/core/agent-messages.js";+import { type AgentSessionMessageController, DEFAULT_AGENT_MESSAGE_MAX_CHARS } 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 { installAgentTraceUpload } from "../src/core/agent-traces.js";@@ -31,11 +31,14 @@ import {} from "../src/modes/daemon/daemon-mode.js";import {createDaemonCommandEnvelope,+ DAEMON_PROTOCOL_INFO,+ DAEMON_SCHEMA_ID,type DaemonAttachResult,type DaemonCommand,type DaemonOutbound,} from "../src/modes/daemon/daemon-protocol.js";import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";+import { DAEMON_WORKER_SUPERVISOR_SOCKET_ENV } from "../src/modes/daemon/daemon-worker-protocol.js";describe("daemon mode helpers", () => {it("preserves envelope client identity while registering prompt admission", () => {@@ -925,7 +928,7 @@ describe("daemon mode helpers", () => {);});- it("fails unknown local agent-message targets without worker remote retries", async () => {+ it("routes nonresident agent-message targets through the supervisor wake path", async () => {const daemon = new AgentDaemon("/tmp/prime-agent-worker-test.sock", {defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },createRuntime: async () => {@@ -944,7 +947,9 @@ describe("daemon mode helpers", () => {sessionActions: { queuedCount: 0, steering: [], followUps: [] },},} as never;- const sendRemoteAgentSessionMessage = vi.fn();+ const sendRemoteAgentSessionMessage = vi+ .fn()+ .mockRejectedValue(new Error("Unknown active session: deleted-child"));const internals = daemon as unknown as {sessions: Map<string, ActiveSessionState>;sendRemoteAgentSessionMessage: typeof sendRemoteAgentSessionMessage;@@ -966,9 +971,126 @@ describe("daemon mode helpers", () => {origin: "agent",}),).rejects.toThrow("Unknown active session: deleted-child");+ expect(sendRemoteAgentSessionMessage).toHaveBeenCalledWith(source, "deleted-child", "continue", undefined);+ });++ it("rejects invalid nonresident agent messages before remote fallback", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-worker-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ worker: { authenticationToken: "worker-token" },+ });+ const source = makeState("source");+ const sendRemoteAgentSessionMessage = vi.fn();+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ sendRemoteAgentSessionMessage: typeof sendRemoteAgentSessionMessage;+ sendAgentSessionMessage(options: {+ targetSelector: string;+ message: string;+ fromState: ActiveSessionState;+ origin: "agent";+ }): Promise<unknown>;+ };+ internals.sessions.set(source.activeSessionId, source);+ internals.sendRemoteAgentSessionMessage = sendRemoteAgentSessionMessage;++ await expect(+ internals.sendAgentSessionMessage({+ targetSelector: "nonresident-target",+ message: " ",+ fromState: source,+ origin: "agent",+ }),+ ).rejects.toThrow("Agent session message cannot be empty");+ await expect(+ internals.sendAgentSessionMessage({+ targetSelector: "nonresident-target",+ message: "x".repeat(DEFAULT_AGENT_MESSAGE_MAX_CHARS + 1),+ fromState: source,+ origin: "agent",+ }),+ ).rejects.toThrow("Agent session message is too long");expect(sendRemoteAgentSessionMessage).not.toHaveBeenCalled();});+ it("does not retry supervisor agent-message rejections", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "pa-msg-"));+ const socketPath = join(tempDir, "d.sock");+ let connectionCount = 0;+ const server: Server = createServer((socket) => {+ connectionCount++;+ socket.on("error", () => undefined);+ socket.write(+ `${JSON.stringify({+ type: "daemon_hello",+ socketPath,+ protocol: DAEMON_PROTOCOL_INFO,+ schemaId: DAEMON_SCHEMA_ID,+ clientId: "supervisor",+ serverCapabilities: [],+ })}\n`,+ );+ let buffer = "";+ socket.on("data", (chunk) => {+ buffer += chunk.toString();+ const newline = buffer.indexOf("\n");+ if (newline === -1) return;+ const wire = JSON.parse(buffer.slice(0, newline)) as {+ id: string;+ command?: { type: string };+ type: string;+ };+ const command = wire.command ?? wire;+ socket.write(+ `${JSON.stringify({+ type: "response",+ id: wire.id,+ command: command.type,+ success: false,+ error: "Target session has too many pending messages",+ })}\n`,+ );+ });+ });+ const previousSupervisorSocket = process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];+ try {+ await new Promise<void>((resolve) => server.listen(socketPath, resolve));+ process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = socketPath;+ const daemon = new AgentDaemon("/tmp/prime-agent-worker-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ worker: { authenticationToken: "worker-token" },+ });+ const sendRemoteAgentSessionMessage = (+ daemon as unknown as {+ sendRemoteAgentSessionMessage(+ fromState: ActiveSessionState,+ targetSelector: string,+ message: string,+ ): Promise<unknown>;+ }+ ).sendRemoteAgentSessionMessage.bind(daemon);++ await expect(sendRemoteAgentSessionMessage(makeState("source"), "remote", "continue")).rejects.toThrow(+ "Target session has too many pending messages",+ );+ expect(connectionCount).toBe(1);+ } finally {+ if (previousSupervisorSocket === undefined) {+ delete process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];+ } else {+ process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = previousSupervisorSocket;+ }+ await new Promise<void>((resolve) => server.close(() => resolve()));+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("reports queued status when a direct accept races into the queue", async () => {const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.tsindex 835af38166..5f53903ae1 100644--- a/packages/coding-agent/test/daemon-session-list.test.ts+++ b/packages/coding-agent/test/daemon-session-list.test.ts@@ -61,9 +61,56 @@ describe("buildSessionList", () => {const first = summaryForActiveSession(state);const second = summaryForActiveSession(state);expect(first.created).toBe("2026-05-01T00:00:00.000Z");+ expect(first.lastActivityAt).toBe("2026-05-01T00:00:00.000Z");expect(second.created).toBe(first.created);});+ it("takes last activity from custom messages and tool results", () => {+ const oldMessage = {+ role: "user",+ content: "old",+ timestamp: Date.parse("2026-05-02T00:00:00.000Z"),+ } as AgentMessage;+ const customTimestamp = Date.parse("2026-05-03T00:00:00.000Z");+ const customMessage = {+ role: "custom",+ customType: "activity",+ content: "newer",+ display: false,+ timestamp: customTimestamp,+ } as AgentMessage;+ const toolResultTimestamp = Date.parse("2026-05-04T00:00:00.000Z");+ const toolResult = {+ role: "toolResult",+ toolCallId: "tool-1",+ toolName: "example",+ content: [],+ isError: false,+ timestamp: toolResultTimestamp,+ } as AgentMessage;++ expect(+ summaryForActiveSession(makeState({ activeSessionId: "custom-active", messages: [oldMessage, customMessage] }))+ .lastActivityAt,+ ).toBe(new Date(customTimestamp).toISOString());+ expect(+ summaryForActiveSession(makeState({ activeSessionId: "tool-active", messages: [oldMessage, toolResult] }))+ .lastActivityAt,+ ).toBe(new Date(toolResultTimestamp).toISOString());+ });++ it("ignores message timestamps outside the valid Date range", () => {+ const validTimestamp = Date.parse("2026-05-04T00:00:00.000Z");+ const messages = [+ { role: "user", content: "valid", timestamp: validTimestamp },+ { role: "assistant", content: "corrupt", timestamp: 8.64e15 + 1 },+ ] as AgentMessage[];++ const summary = summaryForActiveSession(makeState({ activeSessionId: "invalid-timestamp", messages }));++ expect(summary.lastActivityAt).toBe(new Date(validTimestamp).toISOString());+ });+it("keeps a session working while background subagents run", () => {const oneMessage = [{ role: "user", content: "hi" }] as unknown as AgentMessage[];const entries = buildSessionList(@@ -89,7 +136,7 @@ describe("buildSessionList", () => {const activeSessionIds = ["heartbeat", "rlm-heartbeat", "paused-heartbeat", "cron"];const entries = buildSessionList(activeSessionIds.map((activeSessionId) => makeState({ activeSessionId, messages, summaryState })),- [],+ [makeSessionInfo({ id: "passive", path: "/tmp/passive.jsonl" })],[makeCronJob({ id: "heartbeat-job", activeSessionId: "heartbeat", source: "heartbeat" }),makeCronJob({ id: "rlm-job", activeSessionId: "rlm-heartbeat", source: "rlm_heartbeat" }),@@ -100,6 +147,12 @@ describe("buildSessionList", () => {status: "paused",}),makeCronJob({ id: "cron-job", activeSessionId: "cron", source: "cron" }),+ makeCronJob({+ id: "passive-job",+ activeSessionId: "old-passive-active-id",+ sessionFile: "/tmp/passive.jsonl",+ source: "rlm_heartbeat",+ }),],);@@ -108,6 +161,21 @@ describe("buildSessionList", () => {"rlm-heartbeat": true,"paused-heartbeat": undefined,cron: undefined,+ passive: undefined,+ });+ expect(Object.fromEntries(entries.map((entry) => [entry.id, entry.hasRegisteredHeartbeat]))).toEqual({+ heartbeat: true,+ "rlm-heartbeat": true,+ "paused-heartbeat": undefined,+ cron: undefined,+ passive: true,+ });+ expect(Object.fromEntries(entries.map((entry) => [entry.id, entry.hasRegisteredCronJob]))).toEqual({+ heartbeat: undefined,+ "rlm-heartbeat": undefined,+ "paused-heartbeat": undefined,+ cron: true,+ passive: undefined,});});@@ -676,7 +744,7 @@ function makeCronJob(overrides: Pick<AgentCronJob, "id" | "activeSessionId"> & Psource: overrides.source,activeSessionId: overrides.activeSessionId,sessionId: `session-${overrides.activeSessionId}`,- sessionFile: `/tmp/${overrides.activeSessionId}.jsonl`,+ sessionFile: overrides.sessionFile ?? `/tmp/${overrides.activeSessionId}.jsonl`,cwd: "/tmp/project",prompt: "Check for follow-up work",schedule: { kind: "interval", expression: "every 5m", intervalMs: 300_000 },diff --git a/packages/coding-agent/test/daemon-supervisor-eviction.test.ts b/packages/coding-agent/test/daemon-supervisor-eviction.test.tsnew file mode 100644index 0000000000..990e16e248--- /dev/null+++ b/packages/coding-agent/test/daemon-supervisor-eviction.test.ts@@ -0,0 +1,384 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import { success } from "../src/modes/daemon/daemon-protocol.js";+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";+import { DaemonSupervisor, idleEvictionSweepIntervalMs } from "../src/modes/daemon/daemon-supervisor.js";++interface WorkerFixture {+ descriptor: {+ workerId: string;+ lifecycle: "starting" | "ready" | "recovering" | "failed";+ rootActiveSessionId: string;+ rootSessionId: string;+ pid: number;+ ownerClientId?: string;+ stopRequestedAt?: string;+ createCommand: { type: "create"; config?: { sessionDir?: string } };+ };+ client?: {+ request: ReturnType<typeof vi.fn>;+ requestWorker: ReturnType<typeof vi.fn>;+ close: ReturnType<typeof vi.fn>;+ };+ summaries: Map<string, SessionSummary>;+ intentionalStop: boolean;+ updateRestartPrepareClient?: object;+}++interface SupervisorInternals {+ workers: Map<string, WorkerFixture>;+ clients: Set<{ id: string; attachedActiveSessionIds: Set<string> }>;+ catalog: { resolve: ReturnType<typeof vi.fn>; stop: ReturnType<typeof vi.fn> };+ createOrReuseWorker: ReturnType<typeof vi.fn>;+ stopWorker: ReturnType<typeof vi.fn>;+ log: ReturnType<typeof vi.fn>;+ scheduleIdleEvictionSweep(): void;+ runIdleEvictionSweep(now?: number): Promise<void>;+ shutdown(exitCode: number, stopWorkers: boolean): Promise<never>;+ handleCommand(client: object, command: object): Promise<unknown>;+}++const tempDirs: string[] = [];++afterEach(() => {+ for (const directory of tempDirs.splice(0)) rmSync(directory, { recursive: true, force: true });+});++function makeSummary(id: string, now: number, overrides: Partial<SessionSummary> = {}): SessionSummary {+ return {+ id,+ activeSessionId: id,+ sessionId: `${id}-session`,+ lifecycle: "live",+ activity: "idle",+ isSessionActive: false,+ lastActivityAt: new Date(now - 120 * 60_000).toISOString(),+ cwd: "/tmp/project",+ isStreaming: false,+ isCompacting: false,+ attachedClients: 0,+ messageCount: 1,+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },+ ...overrides,+ };+}++function makeWorker(id: string, summaries: SessionSummary[]): WorkerFixture {+ const client = {+ request: vi.fn(async () => success(undefined, "list", { sessions: summaries })),+ requestWorker: vi.fn(),+ close: vi.fn(),+ };+ return {+ descriptor: {+ workerId: id,+ lifecycle: "ready",+ rootActiveSessionId: `${id}-descriptor-root`,+ rootSessionId: `${id}-root-session`,+ pid: 1,+ createCommand: { type: "create" },+ },+ client,+ summaries: new Map(summaries.map((summary) => [summary.activeSessionId ?? summary.id, summary])),+ intentionalStop: false,+ };+}++function makeSupervisor(idleEvictionMinutes: number | "off" = 90): SupervisorInternals {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-eviction-"));+ tempDirs.push(directory);+ mkdirSync(directory, { recursive: true });+ writeFileSync(join(directory, "settings.json"), JSON.stringify({ idleEvictionMinutes }));+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {+ defaultSessionConfig: { agentDir: directory, cwd: directory },+ descriptorDir: join(directory, "workers"),+ }) as unknown as SupervisorInternals;+ supervisor.stopWorker = vi.fn(async (worker: WorkerFixture) => {+ supervisor.workers.delete(worker.descriptor.workerId);+ });+ supervisor.log = vi.fn();+ return supervisor;+}++describe("daemon supervisor whole-tree eviction", () => {+ it("derives a bounded sweep interval from the live threshold", () => {+ expect(idleEvictionSweepIntervalMs("off")).toBe(5 * 60_000);+ expect(idleEvictionSweepIntervalMs(90)).toBe(5 * 60_000);+ expect(idleEvictionSweepIntervalMs(6)).toBe(2 * 60_000);+ expect(idleEvictionSweepIntervalMs(1)).toBe(60_000);+ });++ it("stops a fully idle worker and leaves pinned workers resident", async () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const supervisor = makeSupervisor();+ const idle = makeWorker("idle", [makeSummary("idle-root", now), makeSummary("idle-child", now)]);+ const active = makeWorker("active", [makeSummary("active-root", now, { isSessionActive: true })]);+ const heartbeat = makeWorker("heartbeat", [makeSummary("heartbeat-root", now, { hasRegisteredHeartbeat: true })]);+ const cron = makeWorker("cron", [makeSummary("cron-root", now, { hasRegisteredCronJob: true })]);+ const attached = makeWorker("attached", [makeSummary("attached-root", now)]);+ for (const worker of [idle, active, heartbeat, cron, attached]) {+ supervisor.workers.set(worker.descriptor.workerId, worker);+ }+ supervisor.clients.add({ id: "viewer", attachedActiveSessionIds: new Set(["attached-root"]) });++ await supervisor.runIdleEvictionSweep(now);++ expect(supervisor.stopWorker).toHaveBeenCalledTimes(1);+ expect(supervisor.stopWorker).toHaveBeenCalledWith(idle, true);+ expect(supervisor.log).toHaveBeenCalledWith(+ expect.stringMatching(/Evicted idle worker idle .*idleMinutes=120 sessions=2/),+ );+ expect([...supervisor.workers.keys()].sort()).toEqual(["active", "attached", "cron", "heartbeat"]);+ });++ it("uses canonical busy state so a stale parent with a running child is not evicted", async () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const supervisor = makeSupervisor();+ const parent = makeWorker("parent", [makeSummary("parent-root", now, { hasRunningRlmChildren: true })]);+ supervisor.workers.set("parent", parent);++ await supervisor.runIdleEvictionSweep(now);++ expect(supervisor.stopWorker).not.toHaveBeenCalled();+ expect(supervisor.workers.has("parent")).toBe(true);+ });++ it("evicts a paused-heartbeat session but pins an active-heartbeat session", async () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const supervisor = makeSupervisor();+ const paused = makeWorker("paused", [makeSummary("paused-root", now)]);+ const active = makeWorker("active-heartbeat", [+ makeSummary("active-heartbeat-root", now, { hasRegisteredHeartbeat: true }),+ ]);+ supervisor.workers.set("paused", paused);+ supervisor.workers.set("active-heartbeat", active);++ await supervisor.runIdleEvictionSweep(now);++ expect(supervisor.stopWorker).toHaveBeenCalledTimes(1);+ expect(supervisor.stopWorker).toHaveBeenCalledWith(paused, true);+ expect(supervisor.workers.has("active-heartbeat")).toBe(true);+ });++ it("honors off after reloading settings at sweep time", async () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const supervisor = makeSupervisor("off");+ const idle = makeWorker("idle", [makeSummary("idle-root", now)]);+ supervisor.workers.set("idle", idle);++ await supervisor.runIdleEvictionSweep(now);++ expect(supervisor.stopWorker).not.toHaveBeenCalled();+ expect(idle.client?.request).not.toHaveBeenCalled();+ });++ it("awaits an in-flight eviction sweep before shutdown tears down workers", async () => {+ vi.useFakeTimers();+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ vi.setSystemTime(now);+ let resolveList: (response: ReturnType<typeof success>) => void = () => undefined;+ const listResponse = new Promise<ReturnType<typeof success>>((resolve) => {+ resolveList = resolve;+ });+ const supervisor = makeSupervisor();+ const idle = makeWorker("idle", [makeSummary("idle-root", now)]);+ idle.client!.request = vi.fn(() => listResponse);+ supervisor.workers.set("idle", idle);+ supervisor.catalog.stop = vi.fn(async () => undefined);+ const exit = vi.spyOn(process, "exit").mockImplementation(((code?: string | number | null) => {+ throw new Error(`exit ${code}`);+ }) as typeof process.exit);++ try {+ supervisor.scheduleIdleEvictionSweep();+ await vi.advanceTimersByTimeAsync(5 * 60_000);+ expect(idle.client?.request).toHaveBeenCalledOnce();++ const shutdown = supervisor.shutdown(42, false).then(+ () => undefined,+ (error: unknown) => error,+ );+ await Promise.resolve();+ expect(exit).not.toHaveBeenCalled();+ expect(supervisor.stopWorker).not.toHaveBeenCalled();++ resolveList(success(undefined, "list", { sessions: [makeSummary("idle-root", now)] }));+ await expect(shutdown).resolves.toEqual(new Error("exit 42"));+ expect(supervisor.stopWorker).not.toHaveBeenCalled();+ expect(exit).toHaveBeenCalledWith(42);+ } finally {+ exit.mockRestore();+ vi.useRealTimers();+ }+ });++ it("reopens an inactive saved session through the existing create path used before attach", async () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const supervisor = makeSupervisor();+ const rootSummary = makeSummary("new-active-id", now, {+ sessionId: "saved-session",+ sessionFile: "/tmp/saved.jsonl",+ });+ const reopened = makeWorker("reopened", [rootSummary]);+ reopened.descriptor.rootActiveSessionId = "new-active-id";+ supervisor.createOrReuseWorker = vi.fn(async () => reopened);+ const client = { id: "viewer", attachedActiveSessionIds: new Set<string>() };++ const response = await supervisor.handleCommand(client, {+ id: "create-1",+ type: "create",+ sessionPath: "/tmp/saved.jsonl",+ continueRecent: false,+ });++ expect(supervisor.createOrReuseWorker).toHaveBeenCalledWith(+ "viewer",+ expect.objectContaining({ sessionPath: "/tmp/saved.jsonl" }),+ );+ expect(response).toMatchObject({+ success: true,+ command: "create",+ data: { activeSessionId: "new-active-id", sessionId: "saved-session" },+ });+ });++ it("resolves a saved target in the source worker's create-time session directory", async () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const supervisor = makeSupervisor();+ const sourceSummary = makeSummary("source-active", now, { sessionId: "source-session" });+ const source = makeWorker("source", [sourceSummary]);+ source.descriptor.createCommand.config = { sessionDir: "/tmp/custom-sessions" };+ source.summaries = new Map([["source-active", sourceSummary]]);+ const targetSummary = makeSummary("target-active", now, {+ sessionId: "target-session",+ sessionFile: "/tmp/target.jsonl",+ });+ const target = makeWorker("target", [targetSummary]);+ target.descriptor.rootActiveSessionId = "target-active";+ target.client!.requestWorker.mockResolvedValue({+ type: "response",+ command: "worker_deliver_message",+ success: true,+ data: { deliveryStatus: "delivered" },+ });+ supervisor.workers.set("source", source);+ supervisor.catalog.resolve = vi.fn(async () => "/tmp/target.jsonl");+ supervisor.createOrReuseWorker = vi.fn(async () => target);+ const client = { id: "sender", attachedActiveSessionIds: new Set<string>() };++ const response = await supervisor.handleCommand(client, {+ id: "message-1",+ type: "send_message",+ targetActiveSessionId: "target-session",+ fromActiveSessionId: "source-active",+ message: "wake up",+ });++ expect(supervisor.catalog.resolve).toHaveBeenCalledWith("target-session", "/tmp/project", "/tmp/custom-sessions");+ expect(supervisor.createOrReuseWorker).toHaveBeenCalledWith(+ "sender",+ expect.objectContaining({ type: "create", sessionPath: "/tmp/target.jsonl", continueRecent: false }),+ );+ expect(target.client?.requestWorker).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "worker_deliver_message",+ targetActiveSessionId: "target-active",+ message: "wake up",+ }),+ 24 * 60 * 60 * 1000,+ );+ expect(response).toMatchObject({ success: true, id: "message-1", command: "send_message" });+ });++ it("delivers a same-worker name selector through its canonical active session id", async () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const supervisor = makeSupervisor();+ const sourceSummary = makeSummary("source-active", now, { sessionId: "source-session" });+ const targetSummary = makeSummary("target-active", now, {+ sessionId: "target-session",+ sessionName: "Saved target",+ });+ const worker = makeWorker("shared", [sourceSummary, targetSummary]);+ worker.client!.requestWorker.mockResolvedValue({+ type: "response",+ command: "worker_deliver_message",+ success: true,+ data: { deliveryStatus: "delivered" },+ });+ supervisor.workers.set("shared", worker);+ const client = { id: "sender", attachedActiveSessionIds: new Set<string>() };++ const response = await supervisor.handleCommand(client, {+ id: "message-same-worker",+ type: "send_message",+ targetActiveSessionId: "Saved target",+ fromActiveSessionId: "source-active",+ message: "continue",+ });++ expect(worker.client?.requestWorker).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "worker_deliver_message",+ targetActiveSessionId: "target-active",+ message: "continue",+ }),+ 24 * 60 * 60 * 1000,+ );+ expect(worker.client?.request).not.toHaveBeenCalled();+ expect(response).toMatchObject({+ success: true,+ id: "message-same-worker",+ command: "send_message",+ data: { deliveryStatus: "delivered" },+ });+ });++ it("fails an unknown agent-message selector without forwarding it back to the worker", async () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const supervisor = makeSupervisor();+ const source = makeWorker("source", [makeSummary("source-active", now)]);+ supervisor.workers.set("source", source);+ supervisor.catalog.resolve = vi.fn(async () => {+ throw new Error("Unknown saved session: missing-target");+ });+ const client = { id: "sender", attachedActiveSessionIds: new Set<string>() };++ await expect(+ supervisor.handleCommand(client, {+ id: "message-missing",+ type: "send_message",+ targetActiveSessionId: "missing-target",+ fromActiveSessionId: "source-active",+ message: "continue",+ }),+ ).rejects.toThrow("Unknown active session: missing-target");+ expect(source.client?.requestWorker).not.toHaveBeenCalled();+ expect(source.client?.request).toHaveBeenCalledOnce();+ expect(source.client?.request).toHaveBeenCalledWith({ type: "list" }, 5000);+ });++ it("propagates an ambiguous saved-session selector during a2a wake", async () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const supervisor = makeSupervisor();+ const source = makeWorker("source", [makeSummary("source-active", now)]);+ supervisor.workers.set("source", source);+ supervisor.catalog.resolve = vi.fn(async () => {+ throw new Error('Ambiguous session selector "target"');+ });+ supervisor.createOrReuseWorker = vi.fn();+ const client = { id: "sender", attachedActiveSessionIds: new Set<string>() };++ await expect(+ supervisor.handleCommand(client, {+ id: "message-ambiguous",+ type: "send_message",+ targetActiveSessionId: "target",+ fromActiveSessionId: "source-active",+ message: "wake up",+ }),+ ).rejects.toThrow('Ambiguous session selector "target"');+ expect(supervisor.createOrReuseWorker).not.toHaveBeenCalled();+ });+});diff --git a/packages/coding-agent/test/session-action-store.test.ts b/packages/coding-agent/test/session-action-store.test.tsindex 2df70f9ddb..1c204704c6 100644--- a/packages/coding-agent/test/session-action-store.test.ts+++ b/packages/coding-agent/test/session-action-store.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";import {type ActionLifecycle,ActionStore,+ canEvictWorker,canSelectSessionAction,type DeliveryPolicy,type RuntimeActivity,@@ -230,3 +231,61 @@ describe("scheduler capabilities", () => {}});});++describe("whole-tree eviction capability", () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const idleSession = {+ isSessionActive: false,+ attachedClients: 0,+ hasRegisteredHeartbeat: false,+ hasRegisteredCronJob: false,+ lastActivityAt: now - 90 * 60_000,+ };+ const idleWorker = {+ lifecycle: "ready" as const,+ isConnected: true,+ isStopping: false,+ hasOwnerClient: false,+ isPreparingUpdateRestart: false,+ sessions: [idleSession],+ };++ it("evicts only when every session has reached the inclusive idle threshold", () => {+ expect(canEvictWorker(idleWorker, 90, now)).toBe(true);+ expect(+ canEvictWorker(+ { ...idleWorker, sessions: [idleSession, { ...idleSession, lastActivityAt: now - 89 * 60_000 }] },+ 90,+ now,+ ),+ ).toBe(false);+ });++ it.each([+ ["active session", { sessions: [{ ...idleSession, isSessionActive: true }] }],+ [+ "parent session with a running child and stale timestamps",+ // The supervisor's canonical busy projection sets isSessionActive for this snapshot.+ { sessions: [{ ...idleSession, isSessionActive: true }] },+ ],+ ["attached client", { sessions: [{ ...idleSession, attachedClients: 1 }] }],+ ["heartbeat", { sessions: [{ ...idleSession, hasRegisteredHeartbeat: true }] }],+ ["cron job", { sessions: [{ ...idleSession, hasRegisteredCronJob: true }] }],+ ["missing activity timestamp", { sessions: [{ ...idleSession, lastActivityAt: Number.NaN }] }],+ ["owner client", { hasOwnerClient: true }],+ ["update preparation", { isPreparingUpdateRestart: true }],+ ["disconnected worker", { isConnected: false }],+ ["stopping worker", { isStopping: true }],+ ["starting worker", { lifecycle: "starting" as const }],+ ["recovering worker", { lifecycle: "recovering" as const }],+ ["empty worker", { sessions: [] }],+ ])("rejects a pinned or unavailable %s", (_name, overrides) => {+ expect(canEvictWorker({ ...idleWorker, ...overrides }, 90, now)).toBe(false);+ });++ it("treats off and invalid thresholds as disabled", () => {+ expect(canEvictWorker(idleWorker, "off", now)).toBe(false);+ expect(canEvictWorker(idleWorker, 0, now)).toBe(false);+ expect(canEvictWorker(idleWorker, Number.NaN, now)).toBe(false);+ });+});diff --git a/packages/coding-agent/test/settings-manager.test.ts b/packages/coding-agent/test/settings-manager.test.tsindex 5e5b6c3d06..24c051fc3f 100644--- a/packages/coding-agent/test/settings-manager.test.ts+++ b/packages/coding-agent/test/settings-manager.test.ts@@ -493,4 +493,28 @@ describe("SettingsManager", () => {expect(servers?.shared).toEqual({ type: "http", url: "https://project.shared/mcp" });});});+ describe("idle worker eviction", () => {+ it("defaults to 90 minutes and treats none as off", () => {+ const manager = SettingsManager.create(projectDir, agentDir);+ expect(manager.getIdleEvictionMinutes()).toBe(90);++ writeFileSync(join(agentDir, "settings.json"), JSON.stringify({ idleEvictionMinutes: "none" }));+ const disabled = SettingsManager.create(projectDir, agentDir);+ expect(disabled.getIdleEvictionMinutes()).toBe("off");+ });++ it("reads and writes the global daemon policy without project overrides", async () => {+ writeFileSync(join(agentDir, "settings.json"), JSON.stringify({ idleEvictionMinutes: 60 }));+ writeFileSync(+ join(projectDir, ".prime", "agent", "settings.json"),+ JSON.stringify({ idleEvictionMinutes: 30 }),+ );+ const manager = SettingsManager.create(projectDir, agentDir);+ expect(manager.getIdleEvictionMinutes()).toBe(60);++ manager.setIdleEvictionMinutes("off");+ await manager.flush();+ expect(JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8")).idleEvictionMinutes).toBe("off");+ });+ });});diff --git a/packages/coding-agent/test/settings-selector.test.ts b/packages/coding-agent/test/settings-selector.test.tsindex 3c01b00c00..28492b8f5f 100644--- a/packages/coding-agent/test/settings-selector.test.ts+++ b/packages/coding-agent/test/settings-selector.test.ts@@ -10,6 +10,7 @@ import { initTheme } from "../src/modes/interactive/theme/theme.js";const config: SettingsConfig = {autoCompact: true,+ idleEvictionMinutes: 90,showImages: true,autoResizeImages: true,blockImages: false,@@ -36,6 +37,7 @@ const config: SettingsConfig = {const callbacks: SettingsCallbacks = {onAutoCompactChange: () => {},+ onIdleEvictionMinutesChange: () => {},onShowImagesChange: () => {},onAutoResizeImagesChange: () => {},onBlockImagesChange: () => {},@@ -72,6 +74,8 @@ describe("SettingsSelectorComponent", () => {expect(rendered).toContain("Show image metadata");expect(rendered).toContain("Auto-resize images");+ for (const character of "idle") component.getSettingsList().handleInput(character);+ expect(stripAnsi(component.render(120).join("\n"))).toContain("Idle worker eviction");} finally {resetCapabilitiesCache();}