Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(daemon): self-sleep after prolonged inactivity (#535)
Gustavo Ye65d28cd1ea7d
diff --git a/src/daemon/src/cli/daemonRunner.test.ts b/src/daemon/src/cli/daemonRunner.test.tsindex 922210301..d55b5eb0b 100644--- a/src/daemon/src/cli/daemonRunner.test.ts+++ b/src/daemon/src/cli/daemonRunner.test.ts@@ -481,6 +481,57 @@ describe("daemon runner logger", () => {}});+ it("routes self-sleep through the existing ordered successful shutdown", async () => {+ resetDiagnosticHarness();+ vi.useFakeTimers();+ const listenersBefore = processListenerSnapshot();+ const events: string[] = [];+ const daemonHarness = installDaemonHarness(dir, events);+ runnerDiagnosticHarness.shutdown.mockImplementation(async () => { events.push("coordinator-shutdown"); });+ const releaseOwnership = vi.fn(() => { events.push("ownership-release"); });+ const exit = vi.spyOn(process, "exit").mockImplementation((() => {+ events.push("process-exit");+ return undefined;+ }) as never);+ exit.mockClear();+ let ready!: () => void;+ const readyPromise = new Promise<void>((resolve) => { ready = resolve; });++ try {+ void runPreparedDaemon(preparedDaemon(dir), {+ foreground: false,+ releaseOwnership,+ onReady: ready,+ });+ await readyPromise;++ const onSelfSleep = daemonHarness.state.options?.onSelfSleep as (() => void) | undefined;+ expect(onSelfSleep).toEqual(expect.any(Function));+ onSelfSleep!();+ await vi.waitFor(() => {+ expect(events).toEqual([+ "coordinator-shutdown",+ "daemon-stop",+ "ownership-release",+ "process-exit",+ ]);+ });+ expect(exit).toHaveBeenCalledWith(0);+ const records = fs.readFileSync(path.join(dir, "daemon.log"), "utf8")+ .trimEnd()+ .split("\n")+ .map((line) => JSON.parse(line));+ expect(records).toContainEqual(expect.objectContaining({+ level: "info",+ message: "daemon self-sleep threshold reached",+ }));+ } finally {+ removeNewProcessListeners(listenersBefore);+ vi.clearAllTimers();+ vi.useRealTimers();+ }+ });+it("maps collection errors to fixed PATCH codes without leaking a rejection to createDaemon", async () => {resetDiagnosticHarness();vi.useFakeTimers();diff --git a/src/daemon/src/cli/daemonRunner.ts b/src/daemon/src/cli/daemonRunner.tsindex 49af49a8b..e2e82e542 100644--- a/src/daemon/src/cli/daemonRunner.ts+++ b/src/daemon/src/cli/daemonRunner.ts@@ -398,6 +398,10 @@ export async function runPreparedDaemon(log.error("machine key rejected by server — is it correct / has it expired?");void shutdown(1);},+ onSelfSleep: () => {+ log.info("daemon self-sleep threshold reached");+ void shutdown(0);+ },});} catch (error) {clearInterval(keepAlive);diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.tsindex 47c04cd35..b17ced323 100644--- a/src/daemon/src/daemon/createDaemon.test.ts+++ b/src/daemon/src/daemon/createDaemon.test.ts@@ -25,6 +25,10 @@ import { AgentRouter } from "../manager/agentRouter";import { CredentialBroker } from "../credentials/credentialProxy";import type { AgentBackend as Driver } from "../drivers/index.js";import type { Logger } from "../logger";+import {+ DAEMON_SELF_SLEEP_TIMEOUT_MS,+ type DaemonSelfSleepClock,+} from "./daemonSelfSleep";const timelineSweepHarness = vi.hoisted(() => {let implementation: (workingDirectoryBase: string) => Promise<unknown> =@@ -543,6 +547,87 @@ for await (const line of createInterface({ input: process.stdin })) {}});+ it("resets self-sleep only for newer wakes and suspends it while an agent works", async () => {+ const sockets: FakeSocket[] = [];+ const sessions: DaemonFakeSession[] = [];+ const timers: Array<{+ callback: () => void;+ delayMs: number;+ cancelled: boolean;+ handle: ReturnType<typeof setTimeout>;+ }> = [];+ const clock: DaemonSelfSleepClock = {+ setTimer: (callback, delayMs) => {+ const handle = { unref() {} } as ReturnType<typeof setTimeout>;+ timers.push({ callback, delayMs, cancelled: false, handle });+ return handle;+ },+ clearTimer: (handle) => {+ const timer = timers.find((candidate) => candidate.handle === handle);+ if (timer) timer.cancelled = true;+ },+ };+ const onSelfSleep = vi.fn();+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request) => {+ const url = String(input);+ if (url.includes("/enroll-agent")) return Response.json({ runnerKey: "runner_test" });+ if (url.includes("/daemon/bots")) {+ return Response.json({ bots: [{ id: "bot_1", name: "Bot", discriminator: "0001" }] });+ }+ return Response.json({ attempted: 0 });+ }));++ const daemon = await createDaemon({+ machineKey: "cmk_self_sleep",+ serverUrl: "http://server.invalid",+ serverWsUrl: "ws://x",+ webSocketFactory: factory(sockets) as never,+ runtimeReport: [{ id: "codex" }],+ driverFor: () => fullFakeDriver("codex"),+ sessionFactory: () => {+ const session = daemonFakeSession();+ sessions.push(session);+ return session;+ },+ capabilities: [],+ onSelfSleep,+ selfSleepClock: clock,+ });+ const wake = (seq: number) => sockets[0]!.emit("message", JSON.stringify({+ type: "agent:wake",+ agentId: "bot_1",+ config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: `launch_${seq}`,+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: seq },+ }));++ try {+ expect(timers).toHaveLength(1);+ expect(timers[0]?.delayMs).toBe(DAEMON_SELF_SLEEP_TIMEOUT_MS);+ sockets[0]!.emit("open");+ wake(1);+ await vi.waitFor(() => expect(sessions).toHaveLength(1));+ await vi.waitFor(() => expect(timers).toHaveLength(2));+ expect(timers.every((timer) => timer.cancelled)).toBe(true);++ await sessions[0]!.fire("runtime_event", { kind: "turn_end", sessionId: "test-session" });+ await vi.waitFor(() => expect(timers).toHaveLength(3));+ expect(timers[2]?.cancelled).toBe(false);++ wake(1);+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(timers).toHaveLength(3);++ wake(2);+ await vi.waitFor(() => expect(timers.length).toBeGreaterThanOrEqual(4));+ expect(timers[2]?.cancelled).toBe(true);+ timers[2]?.callback();+ expect(onSelfSleep).not.toHaveBeenCalled();+ } finally {+ await daemon.stop();+ }+ });+it("supplies only the canonical default FSM snapshot source and status path", async () => {const sockets: FakeSocket[] = [];const root = mkdtempSync(join(tmpdir(), "daemon-diagnostic-sources-"));diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex d7dc9a9b9..857ab5291 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -53,6 +53,10 @@ import {} from "./messageReminderScheduler.js";import { createDaemonAgentDriverHost } from "../manager/agentDriverHost.js";import { toAgentBackendSelection } from "../runtimeConfig.js";+import {+ DaemonSelfSleepScheduler,+ type DaemonSelfSleepClock,+} from "./daemonSelfSleep.js";// Cold-start warmup backoff schedule (ms).const WARMUP_BACKOFF_MS = [250, 500, 1000, 2000, 4000] as const;@@ -320,6 +324,10 @@ export interface CreateDaemonOptions {reportDiagnosticFailure?: (failure: DiagnosticFailureReport) => void | Promise<void>;/** Injectable daemon-local reminder clock; tests only, defaults to Node timers. */messageReminderClock?: Pick<MessageReminderSchedulerOptions, "now" | "setTimer" | "clearTimer">;+ /** Called after one continuous 15-day window with no new message and no working agent. */+ onSelfSleep?: () => void;+ /** Injectable self-sleep clock; tests only, defaults to Node timers. */+ selfSleepClock?: DaemonSelfSleepClock;/** Supplies only the bounded default FSM snapshot source and status snapshot path. */onDiagnosticSources?: (sources: {fsmTraceSource: Pick<RotatingFileSink, "openSnapshot"> | null;@@ -407,6 +415,12 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa// `auditContext(agentId)` off it inside `onProxyRequest`.let managerRef: AgentProcessManager | null = null;let reminderSchedulerRef: MessageReminderScheduler | null = null;+ const selfSleepScheduler = opts.onSelfSleep+ ? new DaemonSelfSleepScheduler({+ onSleep: opts.onSelfSleep,+ ...(opts.selfSleepClock ? { clock: opts.selfSleepClock } : {}),+ })+ : null;const emitBotAuditEvent = (agentId: string,event:@@ -841,6 +855,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDatickIntervalMs: opts.tickIntervalMs ?? 2000,onAgentSession: (info) => void channel.reportAgentSession(info),onAgentActivity: (info) => {+ selfSleepScheduler?.observeAgentActivity(info.agentId, info.state === "running");void channel.reportAgentActivity?.(info);// Bot typing indicator (DM-only) — install / tear down the daemon-metered// heartbeat off the derived FSM activity, so the pill lifecycle exactly@@ -966,6 +981,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa// when an active agent coalesces the wake before AgentRouter. Replayed/old// wakes do not create a second observation or enter agent routing.channel.onWakeDesiredAdvance((cmd) => {+ selfSleepScheduler?.observeMessage();reminderSchedulerRef?.observe(cmd.agentId, cmd.unreadNotice.channel, cmd.unreadNotice.latestSeq);});channel.onCommand((cmd) => {@@ -994,6 +1010,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDachannel.connect();await router!.start();+ selfSleepScheduler?.start();return {isOpen: () => channel.status === "open",@@ -1008,6 +1025,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa},proxyUrl: proxy.url,stop: async () => {+ selfSleepScheduler?.stop();reminderSchedulerRef?.clearAll();// Clear all bot-typing heartbeat intervals and emit final stops for// any outstanding scopes so no pill is left dangling.diff --git a/src/daemon/src/daemon/daemonSelfSleep.test.ts b/src/daemon/src/daemon/daemonSelfSleep.test.tsnew file mode 100644index 000000000..9a9b454ab--- /dev/null+++ b/src/daemon/src/daemon/daemonSelfSleep.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it, vi } from "vitest";+import {+ DAEMON_SELF_SLEEP_TIMEOUT_MS,+ DaemonSelfSleepScheduler,+ type DaemonSelfSleepClock,+} from "./daemonSelfSleep";++function manualClock() {+ const timers: Array<{+ callback: () => void;+ delayMs: number;+ cancelled: boolean;+ handle: ReturnType<typeof setTimeout>;+ }> = [];+ const clock: DaemonSelfSleepClock = {+ setTimer: (callback, delayMs) => {+ const handle = { unref() {} } as ReturnType<typeof setTimeout>;+ timers.push({ callback, delayMs, cancelled: false, handle });+ return handle;+ },+ clearTimer: (handle) => {+ const timer = timers.find((candidate) => candidate.handle === handle);+ if (timer) timer.cancelled = true;+ },+ };+ return { clock, timers };+}++describe("DaemonSelfSleepScheduler", () => {+ it("sleeps once after the exact default idle window", () => {+ const { clock, timers } = manualClock();+ const onSleep = vi.fn();+ const scheduler = new DaemonSelfSleepScheduler({ clock, onSleep });++ scheduler.start();++ expect(timers).toHaveLength(1);+ expect(timers[0]?.delayMs).toBe(DAEMON_SELF_SLEEP_TIMEOUT_MS);+ timers[0]?.callback();+ timers[0]?.callback();+ expect(onSleep).toHaveBeenCalledOnce();+ });++ it("starts correctly after activity observations during initialization", () => {+ const { clock, timers } = manualClock();+ const scheduler = new DaemonSelfSleepScheduler({ clock, onSleep: vi.fn() });++ scheduler.observeAgentActivity("idle", false);+ scheduler.observeMessage();+ scheduler.start();++ expect(timers).toHaveLength(1);+ expect(timers[0]?.delayMs).toBe(DAEMON_SELF_SLEEP_TIMEOUT_MS);+ });++ it("resets for a new message and rejects a stale queued callback", () => {+ const { clock, timers } = manualClock();+ const onSleep = vi.fn();+ const scheduler = new DaemonSelfSleepScheduler({ clock, onSleep });++ scheduler.start();+ scheduler.observeMessage();++ expect(timers).toHaveLength(2);+ expect(timers[0]?.cancelled).toBe(true);+ timers[0]?.callback();+ expect(onSleep).not.toHaveBeenCalled();+ timers[1]?.callback();+ expect(onSleep).toHaveBeenCalledOnce();+ });++ it("stays awake until the final working agent stops", () => {+ const { clock, timers } = manualClock();+ const onSleep = vi.fn();+ const scheduler = new DaemonSelfSleepScheduler({ clock, onSleep });++ scheduler.start();+ scheduler.observeAgentActivity("a", true);+ scheduler.observeAgentActivity("b", true);+ expect(timers).toHaveLength(1);+ expect(timers[0]?.cancelled).toBe(true);++ scheduler.observeMessage();+ scheduler.observeAgentActivity("a", false);+ expect(timers).toHaveLength(1);++ scheduler.observeAgentActivity("b", false);+ expect(timers).toHaveLength(2);+ timers[1]?.callback();+ expect(onSleep).toHaveBeenCalledOnce();+ });++ it("clears the timer permanently on stop", () => {+ const { clock, timers } = manualClock();+ const onSleep = vi.fn();+ const scheduler = new DaemonSelfSleepScheduler({ clock, onSleep });++ scheduler.start();+ scheduler.stop();+ scheduler.observeMessage();+ timers[0]?.callback();++ expect(timers[0]?.cancelled).toBe(true);+ expect(timers).toHaveLength(1);+ expect(onSleep).not.toHaveBeenCalled();+ });+});diff --git a/src/daemon/src/daemon/daemonSelfSleep.ts b/src/daemon/src/daemon/daemonSelfSleep.tsnew file mode 100644index 000000000..b84a84d1d--- /dev/null+++ b/src/daemon/src/daemon/daemonSelfSleep.ts@@ -0,0 +1,77 @@+export const DAEMON_SELF_SLEEP_TIMEOUT_MS = 15 * 24 * 60 * 60 * 1_000;++export interface DaemonSelfSleepClock {+ setTimer(callback: () => void, delayMs: number): ReturnType<typeof setTimeout>;+ clearTimer(timer: ReturnType<typeof setTimeout>): void;+}++export interface DaemonSelfSleepSchedulerOptions {+ onSleep: () => void;+ clock?: DaemonSelfSleepClock;+}++const systemClock: DaemonSelfSleepClock = {+ setTimer: (callback, delayMs) => setTimeout(callback, delayMs),+ clearTimer: (timer) => clearTimeout(timer),+};++export class DaemonSelfSleepScheduler {+ private readonly clock: DaemonSelfSleepClock;+ private readonly workingAgents = new Set<string>();+ private timer: ReturnType<typeof setTimeout> | null = null;+ private generation = 0;+ private started = false;+ private stopped = false;++ constructor(private readonly opts: DaemonSelfSleepSchedulerOptions) {+ this.clock = opts.clock ?? systemClock;+ }++ start(): void {+ if (this.started || this.stopped) return;+ this.started = true;+ this.arm();+ }++ observeMessage(): void {+ if (!this.started || this.stopped) return;+ this.arm();+ }++ observeAgentActivity(agentId: string, working: boolean): void {+ if (this.stopped) return;+ if (working) {+ this.workingAgents.add(agentId);+ if (this.started) this.cancel();+ return;+ }+ if (this.workingAgents.delete(agentId) && this.started && this.workingAgents.size === 0) this.arm();+ }++ stop(): void {+ if (this.stopped) return;+ this.stopped = true;+ this.workingAgents.clear();+ this.cancel();+ }++ private arm(): void {+ this.cancel();+ if (this.workingAgents.size > 0) return;+ const generation = this.generation;+ this.timer = this.clock.setTimer(() => {+ if (this.stopped || this.generation !== generation || this.workingAgents.size > 0) return;+ this.timer = null;+ this.generation += 1;+ this.opts.onSleep();+ }, DAEMON_SELF_SLEEP_TIMEOUT_MS);+ this.timer.unref?.();+ }++ private cancel(): void {+ this.generation += 1;+ if (!this.timer) return;+ this.clock.clearTimer(this.timer);+ this.timer = null;+ }+}