Keep idle Claude agents running while a session cron or /loop wakeup is pending (#9744)
* fix(claude): keep an idle agent running while it has a session cron Claude keeps session-only crons and /loop wakeups in its own process, so stopping that process drops them. The idle runtime cleanup asked the Claude session whether it could stop, and the session never knew about these jobs: they appear nowhere on the message stream. Claude lists them as session_crons on every Stop hook. The session now records that list, and canStopRuntime() refuses while it is non-empty. The next Stop after a fire, a CronDelete or an expiry updates the list. Co-authored-by: KronixDev <35991992+KronixDev@users.noreply.github.com> * refactor(claude): type the Stop hook with the SDK's hook input Co-authored-by: KronixDev <35991992+KronixDev@users.noreply.github.com> * fix(claude): hold the runtime after a cron tool call until the next Stop Claude lists session crons only in the Stop hook, and runs Stop only for turns that complete. A turn that called CronCreate and was interrupted or failed left the count at zero, so idle cleanup could still stop the process holding the cron. A CronCreate, CronDelete or ScheduleWakeup call now marks the count unknown until the next Stop reports it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: KronixDev <35991992+KronixDev@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
5 files changed
+188
-4
No files matched your search
+27
-2
@@ -1,5 +1,12 @@
|
||||
import { ClaudeRuntimeSafety } from "./runtime-safety.js";
|
||||
import type { Query, SDKMessage, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import type {
|
||||
HookCallback,
|
||||
Query,
|
||||
SDKMessage,
|
||||
SDKUserMessage,
|
||||
SessionCronSummary,
|
||||
StopHookInput,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -884,6 +891,7 @@ test("Claude session runtime safety observes pumped background work and autonomo
|
||||
wake?.();
|
||||
};
|
||||
let nativeInput!: AsyncIterator<SDKUserMessage>;
|
||||
let stopHook: HookCallback | undefined;
|
||||
let connected!: () => void;
|
||||
const connection = new Promise<void>((resolve) => {
|
||||
connected = resolve;
|
||||
@@ -908,9 +916,10 @@ test("Claude session runtime safety observes pumped background work and autonomo
|
||||
const session = await new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
queryFactory: ({ prompt }) => {
|
||||
queryFactory: ({ prompt, options }) => {
|
||||
if (typeof prompt === "string") throw new Error("Expected streaming input");
|
||||
nativeInput = prompt[Symbol.asyncIterator]();
|
||||
stopHook = options?.hooks?.Stop?.[0]?.hooks[0];
|
||||
connected();
|
||||
return query;
|
||||
},
|
||||
@@ -957,6 +966,22 @@ test("Claude session runtime safety observes pumped background work and autonomo
|
||||
expect(await session.canStopRuntime!()).toBe(false);
|
||||
await push(result);
|
||||
expect(await session.canStopRuntime!()).toBe(true);
|
||||
// A session-only cron lives in this process, and Claude reports it only to the Stop hook.
|
||||
const stop = (session_crons: SessionCronSummary[]) => {
|
||||
const stopInput: StopHookInput = {
|
||||
hook_event_name: "Stop",
|
||||
session_id: "runtime-safety",
|
||||
transcript_path: "",
|
||||
cwd: process.cwd(),
|
||||
stop_hook_active: false,
|
||||
session_crons,
|
||||
};
|
||||
return stopHook!(stopInput, undefined, { signal: new AbortController().signal });
|
||||
};
|
||||
await stop([{ id: "99eb0b69", schedule: "0 */6 * * *", recurring: true, prompt: "say hi" }]);
|
||||
expect(await session.canStopRuntime!()).toBe(false);
|
||||
await stop([]);
|
||||
expect(await session.canStopRuntime!()).toBe(true);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import { createImportDescriptorScheduler } from "./import-descriptor-scheduler.j
|
||||
import {
|
||||
type AgentDefinition,
|
||||
type CanUseTool,
|
||||
type HookCallback,
|
||||
type McpServerConfig as ClaudeSdkMcpServerConfig,
|
||||
type PermissionMode,
|
||||
type PermissionResult,
|
||||
@@ -3804,7 +3805,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
// subagents keep running. Without this declaration an interrupt kills every one of them.
|
||||
// Claude stops a helper itself with its TaskStop tool.
|
||||
perTaskStopAffordance: true,
|
||||
hooks: this.buildSubagentEffortHooks(),
|
||||
hooks: { ...this.buildSubagentEffortHooks(), Stop: [{ hooks: [this.observeStopHook] }] },
|
||||
...(this.persistSession === undefined ? {} : { persistSession: this.persistSession }),
|
||||
env: sdkEnv,
|
||||
};
|
||||
@@ -5480,6 +5481,12 @@ class ClaudeAgentSession implements AgentSession {
|
||||
};
|
||||
}
|
||||
|
||||
// Observation-only, like the effort hooks: it never alters turn control.
|
||||
private readonly observeStopHook: HookCallback = async (input) => {
|
||||
if (input.hook_event_name === "Stop") this.runtimeSafety.observeStop(input.session_crons);
|
||||
return {};
|
||||
};
|
||||
|
||||
private notifySubscribers(event: AgentStreamEvent): void {
|
||||
const turnId =
|
||||
getAgentStreamEventTurnId(event) ?? this.activeForegroundTurnId ?? this.autonomousTurn?.id;
|
||||
|
||||
@@ -46,3 +46,47 @@ test("enriches only live tasks with their correlated launch metadata", () => {
|
||||
runtime.observe(message({ type: "system", subtype: "background_tasks_changed", tasks: [] })),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test("keeps the runtime while Claude's last Stop hook lists session crons", () => {
|
||||
const runtime = new ClaudeRuntimeSafety();
|
||||
runtime.observe(message({ type: "system", subtype: "init", claude_code_version: "2.1.321" }));
|
||||
const cron = { id: "99eb0b69", schedule: "0 */6 * * *", recurring: true, prompt: "say hi" };
|
||||
|
||||
runtime.observeStop([cron]);
|
||||
expect(runtime.canStopRuntime()).toBe(false);
|
||||
|
||||
runtime.observeStop(undefined);
|
||||
expect(runtime.canStopRuntime()).toBe(false);
|
||||
|
||||
runtime.observeStop([]);
|
||||
expect(runtime.canStopRuntime()).toBe(true);
|
||||
|
||||
runtime.observeStop([cron]);
|
||||
runtime.reset();
|
||||
runtime.observe(message({ type: "system", subtype: "init", claude_code_version: "2.1.321" }));
|
||||
expect(runtime.canStopRuntime()).toBe(true);
|
||||
});
|
||||
|
||||
test("holds the runtime when a turn that called a cron tool ends without a Stop hook", () => {
|
||||
const runtime = new ClaudeRuntimeSafety();
|
||||
runtime.observe(message({ type: "system", subtype: "init", claude_code_version: "2.1.321" }));
|
||||
const callTool = (name: string) =>
|
||||
runtime.observe(
|
||||
message({
|
||||
type: "assistant",
|
||||
message: { content: [{ type: "tool_use", id: `${name}-1`, name, input: {} }] },
|
||||
}),
|
||||
);
|
||||
|
||||
// The turn schedules a cron and is interrupted, so no Stop hook reports it.
|
||||
callTool("CronCreate");
|
||||
expect(runtime.canStopRuntime()).toBe(false);
|
||||
|
||||
runtime.observeStop([{ id: "99eb0b69", schedule: "0 */6 * * *", recurring: true, prompt: "hi" }]);
|
||||
callTool("CronDelete");
|
||||
runtime.observeStop([]);
|
||||
expect(runtime.canStopRuntime()).toBe(true);
|
||||
|
||||
callTool("ScheduleWakeup");
|
||||
expect(runtime.canStopRuntime()).toBe(false);
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import type { SDKMessage, SessionCronSummary } from "@anthropic-ai/claude-agent-sdk";
|
||||
import type { AgentBackgroundWorkInput } from "../../background-work/index.js";
|
||||
import { parseClaudeCodeVersion } from "./model-manifest.js";
|
||||
import { toBackgroundWorkInputs, type ClaudeBackgroundTask } from "./background-work.js";
|
||||
|
||||
const SESSION_CRON_TOOLS = new Set(["CronCreate", "CronDelete", "ScheduleWakeup"]);
|
||||
|
||||
/** Process-local background ownership. Completion delivery can follow an empty roster. */
|
||||
export class ClaudeRuntimeSafety {
|
||||
private inventoryState: "unknown" | "supported" | "retired" = "unknown";
|
||||
@@ -16,8 +18,15 @@ export class ClaudeRuntimeSafety {
|
||||
private readonly monitorTools = new Set<string>();
|
||||
private readonly toolInputs = new Map<string, { description?: string; command?: string }>();
|
||||
private readonly taskTools = new Map<string, string>();
|
||||
// Session-only crons and wakeups live in the process and die with it. Only the Stop hook
|
||||
// lists them, and Claude runs it only for turns that complete. A cron tool call makes the
|
||||
// count unknown until the next Stop, so an interrupted or failed turn keeps the runtime.
|
||||
private sessionCrons = 0;
|
||||
private sessionCronsUnknown = false;
|
||||
|
||||
reset(): void {
|
||||
this.sessionCrons = 0;
|
||||
this.sessionCronsUnknown = false;
|
||||
this.inventoryState = "unknown";
|
||||
this.turnSeen = false;
|
||||
this.liveTasks = [];
|
||||
@@ -38,6 +47,13 @@ export class ClaudeRuntimeSafety {
|
||||
this.turnSeen = true;
|
||||
}
|
||||
|
||||
/** Called with the session crons of each main-thread Stop hook. Older CLIs omit them. */
|
||||
observeStop(sessionCrons: readonly SessionCronSummary[] | undefined): void {
|
||||
if (this.inventoryState === "retired") return;
|
||||
this.sessionCronsUnknown = false;
|
||||
if (sessionCrons) this.sessionCrons = sessionCrons.length;
|
||||
}
|
||||
|
||||
/** Returns a full replacement only when the visible inventory changes. */
|
||||
observe(message: SDKMessage): AgentBackgroundWorkInput[] | undefined {
|
||||
if (this.inventoryState === "retired") return undefined;
|
||||
@@ -54,6 +70,8 @@ export class ClaudeRuntimeSafety {
|
||||
if (message.type === "assistant") {
|
||||
let relevant = false;
|
||||
for (const block of message.message.content) {
|
||||
if (block.type === "tool_use" && SESSION_CRON_TOOLS.has(block.name))
|
||||
this.sessionCronsUnknown = true;
|
||||
if (block.type === "tool_use" && (block.name === "Monitor" || block.name === "Bash")) {
|
||||
if (block.name === "Monitor") relevant = this.observeMonitor(block.id) || relevant;
|
||||
relevant = this.observeInput(block.id, block.input) || relevant;
|
||||
@@ -129,6 +147,8 @@ export class ClaudeRuntimeSafety {
|
||||
if (this.inventoryState === "unknown" && !this.turnSeen) return true;
|
||||
return (
|
||||
this.inventoryState === "supported" &&
|
||||
this.sessionCrons === 0 &&
|
||||
!this.sessionCronsUnknown &&
|
||||
this.liveTasks.length === 0 &&
|
||||
this.awaitingNotifications.size === 0
|
||||
);
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import pino from "pino";
|
||||
import { beforeAll, beforeEach, describe, expect, test } from "vitest";
|
||||
|
||||
import type { AgentStreamEvent } from "../agent/agent-sdk-types.js";
|
||||
import {
|
||||
canRunRealProvider,
|
||||
createRealProviderClient,
|
||||
getRealProviderConfig,
|
||||
} from "./real-provider-test-config.js";
|
||||
|
||||
describe("real claude: idle runtime cleanup and session crons", () => {
|
||||
let canRun = false;
|
||||
beforeAll(async () => {
|
||||
canRun = await canRunRealProvider("claude");
|
||||
});
|
||||
beforeEach((context) => {
|
||||
if (!canRun) context.skip();
|
||||
});
|
||||
|
||||
test("a runtime holding a session-only cron is kept until the cron is deleted", async () => {
|
||||
const logger = pino({ level: "silent" });
|
||||
const client = createRealProviderClient("claude", logger);
|
||||
const cwd = mkdtempSync(path.join(tmpdir(), "paseo-claude-session-cron-"));
|
||||
const session = await client.createSession({
|
||||
cwd,
|
||||
...getRealProviderConfig("claude"),
|
||||
});
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
try {
|
||||
await session.run(
|
||||
"Call the CronCreate tool exactly once with cron '0 */6 * * *', recurring true, durable false, prompt 'say hi'. Then reply with exactly: DONE",
|
||||
);
|
||||
const cronResult = events.find(
|
||||
(event) =>
|
||||
event.type === "timeline" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.name === "CronCreate" &&
|
||||
event.item.status === "completed",
|
||||
);
|
||||
expect(cronResult, JSON.stringify(events.slice(-5))).toBeDefined();
|
||||
expect(await session.canStopRuntime!()).toBe(false);
|
||||
|
||||
await session.run(
|
||||
"Delete every scheduled cron job with the CronDelete tool. Then reply with exactly: DONE",
|
||||
);
|
||||
expect(await session.canStopRuntime!()).toBe(true);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
}, 240_000);
|
||||
|
||||
test("a turn interrupted after it creates a session-only cron keeps the runtime", async () => {
|
||||
const logger = pino({ level: "silent" });
|
||||
const client = createRealProviderClient("claude", logger);
|
||||
const cwd = mkdtempSync(path.join(tmpdir(), "paseo-claude-session-cron-"));
|
||||
const session = await client.createSession({
|
||||
cwd,
|
||||
...getRealProviderConfig("claude"),
|
||||
});
|
||||
const cronCreated = new Promise<void>((resolve) => {
|
||||
session.subscribe((event) => {
|
||||
if (
|
||||
event.type === "timeline" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.name === "CronCreate" &&
|
||||
event.item.status === "completed"
|
||||
)
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
try {
|
||||
await session.startTurn(
|
||||
"Call the CronCreate tool exactly once with cron '0 */6 * * *', recurring true, durable false, prompt 'say hi'. Then run the Bash command 'sleep 120' in the foreground. Then reply with exactly: DONE",
|
||||
);
|
||||
await cronCreated;
|
||||
await session.interrupt();
|
||||
// The cancelled turn settles about a second after interrupt() resolves.
|
||||
await new Promise((resolve) => setTimeout(resolve, 5_000));
|
||||
expect(await session.canStopRuntime!()).toBe(false);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
}, 240_000);
|
||||
});
|
||||
Reference in new issue
Block a user