A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
offer to stop a stale-version daemon at startup instead of erroring out (#218)
kt283874127907
diff --git a/packages/coding-agent/src/cli/daemon-launch.ts b/packages/coding-agent/src/cli/daemon-launch.tsindex 85148f8156..81cd4c589a 100644--- a/packages/coding-agent/src/cli/daemon-launch.ts+++ b/packages/coding-agent/src/cli/daemon-launch.ts@@ -84,10 +84,10 @@ export async function listActiveDaemonSessionSummaries(client: DaemonClient): Pr/** Thrown when a stale-version daemon can't be replaced. The message is user-facing. */export class StaleDaemonError extends Error {- constructor(socketPath: string) {+ constructor(readonly socketPath: string) {super(- `A previous prime-agent version's background daemon on ${socketPath} couldn't be replaced — it may be mid-turn ` +- `or still shutting down, and this version can't drive it. Wait a moment and retry, or run "prime-agent daemon shutdown" to stop it and upgrade.`,+ `A background daemon from a different prime-agent version is running on ${socketPath} and can't be driven by ` ++ `this version. Run "prime-agent daemon shutdown" to stop it, then retry.`,);this.name = "StaleDaemonError";}diff --git a/packages/coding-agent/src/cli/daemon-stop-confirm.ts b/packages/coding-agent/src/cli/daemon-stop-confirm.tsnew file mode 100644index 0000000000..250e2523ff--- /dev/null+++ b/packages/coding-agent/src/cli/daemon-stop-confirm.ts@@ -0,0 +1,75 @@+/**+ * Shared confirmation for stopping a running daemon that has live sessions.+ *+ * Both `prime-agent update --self` and interactive startup (when taking over a+ * stale-version daemon) need to ask before discarding busy sessions. They keep+ * the same busy-session semantics here and only vary the wording via `copy`.+ *+ * Kept out of daemon-launch.ts so the early fire-and-forget launch path stays+ * light on imports (no readline/chalk); this module is only reached on the+ * interactive, post-startup paths.+ */++import { createInterface } from "node:readline";+import chalk from "chalk";+import { isSessionBusy, type RunningDaemonProbe } from "./daemon-launch.js";++/** Prompt for a yes/no answer at a TTY. Empty/anything-but-yes resolves false (default No). */+export function promptYesNo(message: string): Promise<boolean> {+ return new Promise((resolve) => {+ const rl = createInterface({ input: process.stdin, output: process.stdout });+ rl.question(`${message} [y/N] `, (answer) => {+ rl.close();+ const normalized = answer.trim().toLowerCase();+ resolve(normalized === "y" || normalized === "yes");+ });+ });+}++export function pluralizeSessions(count: number): { noun: string; pronoun: string } {+ return count === 1 ? { noun: "session", pronoun: "it" } : { noun: "sessions", pronoun: "them" };+}++export interface DaemonSessionLossCopy {+ /** Full sentence describing the busy sessions and what stopping the daemon does. */+ busyDetail(count: number): string;+ /** Full sentence for the reachable-but-unlistable case (work may be lost). */+ unlistableDetail: string;+ /** Question appended after the detail when prompting at a TTY (before " [y/N]"). */+ question: string;+ /** Remediation appended after the detail when not at a TTY. */+ nonTtyHint: string;+}++/**+ * Returns true when it is safe to proceed with stopping the daemon: it is not+ * reachable, `force` is set, no sessions are busy, or the user confirmed at a+ * TTY. Returns false to abort (busy/unlistable and either declined or non-TTY).+ * Only busy sessions (streaming, compacting, or pending messages) lose work;+ * idle loaded sessions reload from disk on the fresh daemon.+ */+export async function confirmDaemonSessionLoss(+ probe: RunningDaemonProbe,+ options: { force: boolean; copy: DaemonSessionLossCopy },+): Promise<boolean> {+ const { force, copy } = options;+ if (!probe.reachable || force) {+ return true;+ }+ let detail: string;+ if (probe.activeSessions === undefined) {+ // Reachable but couldn't list sessions: assume work may be lost.+ detail = copy.unlistableDetail;+ } else {+ const busySessions = probe.activeSessions.filter(isSessionBusy);+ if (busySessions.length === 0) {+ return true;+ }+ detail = copy.busyDetail(busySessions.length);+ }+ if (!process.stdin.isTTY) {+ console.error(chalk.red(`${detail} ${copy.nonTtyHint}`));+ return false;+ }+ return promptYesNo(`${detail} ${copy.question}`);+}diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.tsindex 80b1eca8b4..6ec9ace2dc 100644--- a/packages/coding-agent/src/main.ts+++ b/packages/coding-agent/src/main.ts@@ -16,8 +16,11 @@ import {ensureInteractiveDaemonRunning,isDaemonSessionSummary,listActiveDaemonSessionSummaries,+ probeRunningDaemonSessions,StaleDaemonError,+ shutdownDaemonAndWait,} from "./cli/daemon-launch.js";+import { confirmDaemonSessionLoss, type DaemonSessionLossCopy, pluralizeSessions } from "./cli/daemon-stop-confirm.js";import { processFileArguments } from "./cli/file-processor.js";import { buildInitialMessage } from "./cli/initial-message.js";import { listModels } from "./cli/list-models.js";@@ -363,16 +366,66 @@ async function promptConfirm(message: string): Promise<boolean> {});}-async function awaitDaemonReady(daemonReady: Promise<void> | undefined): Promise<void> {+// Only busy sessions (streaming, compacting, or pending messages) lose work;+// idle loaded sessions reload from disk on the fresh daemon.+const STARTUP_SESSION_LOSS_COPY: DaemonSessionLossCopy = {+ busyDetail(count) {+ const { noun, pronoun } = pluralizeSessions(count);+ return `A background daemon from a different prime-agent version is running with ${count} busy ${noun}. Stopping it will terminate ${pronoun}.`;+ },+ unlistableDetail:+ "A background daemon from a different prime-agent version is running and its sessions could not be listed. Stopping it may terminate active sessions.",+ question: "Stop it and continue?",+ nonTtyHint: 'Run "prime-agent daemon shutdown" to stop it, then retry.',+};++// The promise to keep after awaiting readiness. Wrapped in an object so it+// survives `await` (which would otherwise flatten a returned Promise to void).+type DaemonReadyResult = { ready: Promise<void> | undefined };++// A stale-version daemon couldn't be taken over automatically (busy or stuck).+// Offer to stop it (default No) and start a fresh daemon, or exit. Returns the+// fresh ready promise so callers stop re-handling the original rejection.+async function takeOverStaleDaemonOrExit(socketPath: string): Promise<DaemonReadyResult> {+ const probe = await probeRunningDaemonSessions(socketPath);+ const confirmed = await confirmDaemonSessionLoss(probe, { force: false, copy: STARTUP_SESSION_LOSS_COPY });+ if (!confirmed) {+ // Non-TTY already printed the reason; at a TTY the user declined.+ if (process.stdin.isTTY) {+ console.error(chalk.dim("Cancelled."));+ }+ process.exit(1);+ }+ if (!(await shutdownDaemonAndWait(socketPath))) {+ console.error(+ chalk.red(`Could not stop the daemon on ${socketPath}. Run "prime-agent daemon shutdown" and retry.`),+ );+ process.exit(1);+ }+ const ready = ensureInteractiveDaemonRunning(socketPath);+ try {+ await ready;+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ console.error(chalk.red(`Could not start the daemon: ${message}`));+ process.exit(1);+ }+ return { ready };+}++// Resolves the daemon-ready promise, returning the promise to keep (the same+// one on success, or the fresh one from a stale-daemon takeover) so repeat+// calls don't re-handle the original rejection.+async function awaitDaemonReady(daemonReady: Promise<void> | undefined): Promise<DaemonReadyResult> {if (!daemonReady) {- return;+ return { ready: daemonReady };}try {await daemonReady;+ return { ready: daemonReady };} catch (error) {if (error instanceof StaleDaemonError) {- console.error(chalk.red(error.message));- process.exit(1);+ return takeOverStaleDaemonOrExit(error.socketPath);}throw error;}@@ -1106,7 +1159,7 @@ export async function main(args: string[], options?: MainOptions) {const daemonSocketPath = parsed.daemonSocket ?? defaultDaemonSocketPath();// Kick off daemon spawn/readiness immediately so it overlaps session-manager// and runtime-services preparation; awaited wherever the daemon is first used.- const daemonReady = useDaemonInteractive ? ensureInteractiveDaemonRunning(daemonSocketPath) : undefined;+ let daemonReady = useDaemonInteractive ? ensureInteractiveDaemonRunning(daemonSocketPath) : undefined;// Errors are rethrown at the await sites below; this only avoids an unhandled// rejection if startup exits before reaching them.daemonReady?.catch(() => {});@@ -1115,7 +1168,7 @@ export async function main(args: string[], options?: MainOptions) {session: parsed.session,});if (shouldLookupDaemonActiveSession && daemonReady) {- await awaitDaemonReady(daemonReady);+ daemonReady = (await awaitDaemonReady(daemonReady)).ready;}const activeDaemonSessionSummary =shouldLookupDaemonActiveSession && parsed.session@@ -1303,14 +1356,14 @@ export async function main(args: string[], options?: MainOptions) {fork: parsed.fork,})) {- await awaitDaemonReady(daemonReady);+ daemonReady = (await awaitDaemonReady(daemonReady)).ready;await preloadCodeHighlighter();printTimings();await launchAgentsView(true);return;}- await awaitDaemonReady(daemonReady);+ daemonReady = (await awaitDaemonReady(daemonReady)).ready;// No attach and no session selector means a fresh default chat. Defer the// daemon session until the first action so startup is instant and leaving// straight to the agents view (or quitting) creates nothing to clean up.diff --git a/packages/coding-agent/src/package-manager-cli.ts b/packages/coding-agent/src/package-manager-cli.tsindex db27c50843..aff93faf67 100644--- a/packages/coding-agent/src/package-manager-cli.ts+++ b/packages/coding-agent/src/package-manager-cli.ts@@ -1,14 +1,13 @@-import { createInterface } from "node:readline";import chalk from "chalk";import { spawn } from "child_process";import { selectConfig } from "./cli/config-selector.js";import {ensureInteractiveDaemonRunning,- isSessionBusy,probeRunningDaemonSessions,type RunningDaemonProbe,shutdownDaemonAndWait,} from "./cli/daemon-launch.js";+import { confirmDaemonSessionLoss, type DaemonSessionLossCopy, pluralizeSessions } from "./cli/daemon-stop-confirm.js";import {APP_NAME,CONFIG_DIR_NAME,@@ -355,44 +354,22 @@ async function runSelfUpdate(command: SelfUpdateCommand): Promise<void> {}}-function promptUpdateConfirm(message: string): Promise<boolean> {- return new Promise((resolve) => {- const rl = createInterface({ input: process.stdin, output: process.stdout });- rl.question(`${message} [y/N] `, (answer) => {- rl.close();- const normalized = answer.trim().toLowerCase();- resolve(normalized === "y" || normalized === "yes");- });- });-}--// Returns false when the update should be aborted to avoid terminating live sessions.// Only busy sessions (streaming, compacting, or pending messages) would lose work;// idle loaded sessions reload from disk on the fresh daemon.-async function confirmDaemonSessionLossBeforeUpdate(probe: RunningDaemonProbe, force: boolean): Promise<boolean> {- if (!probe.reachable || force) {- return true;- }- let detail: string;- if (probe.activeSessions === undefined) {- // Reachable but couldn't list sessions: assume work may be lost.- detail =- "A running daemon's sessions could not be listed. Updating will stop the daemon and may terminate active sessions.";- } else {- const busySessions = probe.activeSessions.filter(isSessionBusy);- if (busySessions.length === 0) {- return true;- }- const count = busySessions.length;- const noun = count === 1 ? "session" : "sessions";- const pronoun = count === 1 ? "it" : "them";- detail = `The running daemon has ${count} busy ${noun}. Updating will stop the daemon and terminate ${pronoun}.`;- }- if (!process.stdin.isTTY) {- console.error(chalk.red(`${detail} Re-run with --force to proceed.`));- return false;- }- return promptUpdateConfirm(`${detail} Continue?`);+const UPDATE_SESSION_LOSS_COPY: DaemonSessionLossCopy = {+ busyDetail(count) {+ const { noun, pronoun } = pluralizeSessions(count);+ return `The running daemon has ${count} busy ${noun}. Updating will stop the daemon and terminate ${pronoun}.`;+ },+ unlistableDetail:+ "A running daemon's sessions could not be listed. Updating will stop the daemon and may terminate active sessions.",+ question: "Continue?",+ nonTtyHint: "Re-run with --force to proceed.",+};++// Returns false when the update should be aborted to avoid terminating live sessions.+function confirmDaemonSessionLossBeforeUpdate(probe: RunningDaemonProbe, force: boolean): Promise<boolean> {+ return confirmDaemonSessionLoss(probe, { force, copy: UPDATE_SESSION_LOSS_COPY });}async function restartDaemonAfterSelfUpdate(socketPath: string, daemonWasRunning: boolean): Promise<void> {diff --git a/packages/coding-agent/test/daemon-stop-confirm.test.ts b/packages/coding-agent/test/daemon-stop-confirm.test.tsnew file mode 100644index 0000000000..2660309ce8--- /dev/null+++ b/packages/coding-agent/test/daemon-stop-confirm.test.ts@@ -0,0 +1,93 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { RunningDaemonProbe } from "../src/cli/daemon-launch.js";+import {+ confirmDaemonSessionLoss,+ type DaemonSessionLossCopy,+ pluralizeSessions,+} from "../src/cli/daemon-stop-confirm.js";+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";++const COPY: DaemonSessionLossCopy = {+ busyDetail: (count) => `busy:${count}`,+ unlistableDetail: "unlistable",+ question: "Continue?",+ nonTtyHint: "hint",+};++function session(overrides: Partial<SessionSummary>): SessionSummary {+ return {+ isStreaming: false,+ isCompacting: false,+ pendingMessageCount: 0,+ ...overrides,+ } as unknown as SessionSummary;+}++const ttyDescriptor = Object.getOwnPropertyDescriptor(process.stdin, "isTTY");+function setTTY(value: boolean): void {+ Object.defineProperty(process.stdin, "isTTY", { value, configurable: true });+}++describe("confirmDaemonSessionLoss", () => {+ beforeEach(() => {+ vi.spyOn(console, "error").mockImplementation(() => {});+ });+ afterEach(() => {+ vi.restoreAllMocks();+ if (ttyDescriptor) {+ Object.defineProperty(process.stdin, "isTTY", ttyDescriptor);+ }+ });++ it("proceeds without prompting when the daemon is unreachable", async () => {+ setTTY(true);+ const probe: RunningDaemonProbe = { reachable: false };+ expect(await confirmDaemonSessionLoss(probe, { force: false, copy: COPY })).toBe(true);+ });++ it("proceeds without prompting when force is set", async () => {+ setTTY(true);+ const probe: RunningDaemonProbe = { reachable: true, activeSessions: [session({ isStreaming: true })] };+ expect(await confirmDaemonSessionLoss(probe, { force: true, copy: COPY })).toBe(true);+ });++ it("proceeds without prompting when no session is busy", async () => {+ setTTY(true);+ const probe: RunningDaemonProbe = {+ reachable: true,+ activeSessions: [session({ isStreaming: false }), session({ pendingMessageCount: 0 })],+ };+ expect(await confirmDaemonSessionLoss(probe, { force: false, copy: COPY })).toBe(true);+ });++ it("aborts without prompting when not at a TTY and a session is busy", async () => {+ setTTY(false);+ const probe: RunningDaemonProbe = { reachable: true, activeSessions: [session({ pendingMessageCount: 2 })] };+ expect(await confirmDaemonSessionLoss(probe, { force: false, copy: COPY })).toBe(false);+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining("hint"));+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining("busy:1"));+ });++ it("aborts without prompting when not at a TTY and sessions cannot be listed", async () => {+ setTTY(false);+ const probe: RunningDaemonProbe = { reachable: true };+ expect(await confirmDaemonSessionLoss(probe, { force: false, copy: COPY })).toBe(false);+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining("unlistable"));+ });++ it("treats compacting and pending-message sessions as busy", async () => {+ setTTY(false);+ for (const overrides of [{ isCompacting: true }, { pendingMessageCount: 1 }, { isStreaming: true }]) {+ vi.mocked(console.error).mockClear();+ const probe: RunningDaemonProbe = { reachable: true, activeSessions: [session(overrides)] };+ expect(await confirmDaemonSessionLoss(probe, { force: false, copy: COPY })).toBe(false);+ }+ });+});++describe("pluralizeSessions", () => {+ it("uses singular for one and plural otherwise", () => {+ expect(pluralizeSessions(1)).toEqual({ noun: "session", pronoun: "it" });+ expect(pluralizeSessions(2)).toEqual({ noun: "sessions", pronoun: "them" });+ });+});