Skip to content

Commit 61b3c74

Browse files
anagnorisis2peripeteiaobviyus
authored andcommitted
feat(cron): on-exit cron schedule kind — fire a job when a watched command exits
Adds an `on-exit` cron schedule kind: a job fires once when a watched command/process exits, via gateway ProcessSupervisor exit watchers. Covers CLI (`--on-exit`/`--on-exit-cwd`), tool/protocol schema, RPC list-filter, Control UI + macOS read-only display, SQLite round-trip, and origin-aware wake routing. Restart-safe one-shot (persists completion before firing); platform-aware shell; bounded watched-command execution. Squashed from 22 iterative commits for a clean rebase onto current main.
1 parent adcfebc commit 61b3c74

45 files changed

Lines changed: 1869 additions & 45 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎DESIGN-cron-on-exit.md‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# feat(cron): `on-exit` schedule — fire a job when a watched command/process exits
2+
3+
## Problem
4+
5+
Event-driven wakes that start a fresh agent turn already work (the `wake`/`system event` RPC). But an agent cannot reliably arm "wake me when this command/process exits" itself: CLI backends run each turn as a supervisor-spawned **detached process group** that is `signalProcessTree(SIGTERM→SIGKILL)`'d at turn end (`src/process/supervisor/adapters/child.ts`, intentional, #71662). Any process the agent backgrounds via `exec` is in that tree and dies with the turn. The only escape (`setsid` + raw `node dist/entry.js system event …`) is hand-rolled, fragile, and observed to take down the host. Applies to **all** spawn-and-kill CLI backends (claude-cli verified), not the TLS proxy.
6+
7+
## Design
8+
9+
A new cron **schedule kind** `on-exit`, executed by a **gateway-supervisor-owned watcher** — independent of #83738 (rides the existing main-session cron run pipeline, not the manual wake path).
10+
11+
- `CronSchedule` gains `{ kind: "on-exit"; command: string; cwd?: string }` (PID-watch variant deferred).
12+
- `computeNextRunAtMs()` returns `undefined` for `on-exit` → the time-based timer never fires it.
13+
- `createCronExitWatchers()` (extracted into `src/gateway/cron-exit-watchers.ts`, wired from `buildGatewayCronService` via `reconcileExitWatchers()` / `stopExitWatchers()`) owns the watcher lifecycle, backed by `getProcessSupervisor()`. It exposes `reconcile(jobs) / cancel(jobId) / cancelAll() / activeJobIds()`.
14+
- On reconcile, each enabled `on-exit` job reserves a watcher slot synchronously (with an `armToken`), then spawns the command via `supervisor.spawn({ mode:"child", scopeKey:"cron-exit:<jobId>", replaceExistingScope:true, argv:[shell.command, ...shell.argsFor(command)], cwd?, captureOutput:true })`. The shell is platform-aware via `resolveExitWatchShell()`: `cmd.exe /d /s /c` on Windows, `bash -lc` on POSIX.
15+
- The watcher lives under the **gateway** supervisor tree, so per-turn CLI teardown never touches it. An async spawn/wait that loses ownership (job cancelled or re-armed for a changed command/cwd) is a no-op via the `armToken`/slot-identity check.
16+
- `await run.wait()` → on exit, the one-shot completion is **persisted (the job disabled in the store) BEFORE the job fires**, fail-closed: if the store write or `run.wait()` rejects, the job does NOT fire — so a gateway restart cannot re-arm and double-fire the same exit. Only then does it fire via the existing cron run pipeline; the woken turn sees the exit code + last output lines.
17+
- Job `remove`/`disable`, or a changed command/cwd → `reconcile()` cancels or re-arms the watcher (`cancel(jobId)`; `cancelAll()` on shutdown).
18+
- Delivery to the originating conversation is the **existing** `executeMainSessionCronJob` path (`resolveMainSessionCronDeliveryContext`) — already correct on main; no dependency on #83738.
19+
20+
## Reuse / no new delivery code
21+
22+
Everything after "process exited" is the current cron run→system-event→delivery pipeline. The only new surface: the schedule kind, its validation, the watcher lifecycle, and the tool/schema plumbing to create such a job.
23+
24+
## Out of scope
25+
26+
- PID-watch (`{ kind:"on-exit"; pid }`) — follow-up.
27+
- Re-arm/repeat on each exit — v1 is one-shot (job disables after firing, like a one-shot `at`).
28+
- This PR **stacks on #83738** and reuses its origin-aware wake as the firing
29+
mechanism; it adds only the process-exit _trigger_ (the supervisor watcher).

‎apps/macos/Sources/OpenClaw/CronJobEditor+Helpers.swift‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,12 @@ extension CronJobEditor {
3939
self.scheduleKind = .cron
4040
self.cronExpr = expr
4141
self.cronTz = tz ?? ""
42+
case .onExit:
43+
// on-exit jobs are CLI-managed and have no editor form yet; fall back to
44+
// the cron form so the editor still OPENS instead of failing to compile.
45+
// Saving an on-exit job from the editor should be gated to avoid rewriting
46+
// it as cron — tracked as a macOS read-only-editor follow-up.
47+
self.scheduleKind = .cron
4248
}
4349

4450
switch job.payload {
@@ -74,6 +80,18 @@ extension CronJobEditor {
7480
}
7581

7682
func buildPayload() throws -> [String: AnyCodable] {
83+
// Gate on-exit saves: the editor has no on-exit schedule form (it falls back to
84+
// the cron form), so saving would rewrite the on-exit schedule as cron and
85+
// corrupt the job. Block it until a read-only/native on-exit editor exists.
86+
if let job, case .onExit = job.schedule {
87+
throw NSError(
88+
domain: "Cron",
89+
code: 0,
90+
userInfo: [
91+
NSLocalizedDescriptionKey:
92+
"on-exit cron jobs can't be edited in the macOS app yet; manage them with the CLI.",
93+
])
94+
}
7795
let name = try self.requireName()
7896
let description = self.trimmed(self.description)
7997
let agentId = self.trimmed(self.agentId)

‎apps/macos/Sources/OpenClaw/CronModels.swift‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,14 +66,16 @@ enum CronSchedule: Codable, Equatable {
6666
case at(at: String)
6767
case every(everyMs: Int, anchorMs: Int?)
6868
case cron(expr: String, tz: String?)
69+
case onExit(command: String, cwd: String?)
6970

70-
enum CodingKeys: String, CodingKey { case kind, at, atMs, everyMs, anchorMs, expr, tz }
71+
enum CodingKeys: String, CodingKey { case kind, at, atMs, everyMs, anchorMs, expr, tz, command, cwd }
7172

7273
var kind: String {
7374
switch self {
7475
case .at: "at"
7576
case .every: "every"
7677
case .cron: "cron"
78+
case .onExit: "on-exit"
7779
}
7880
}
7981

@@ -105,6 +107,10 @@ enum CronSchedule: Codable, Equatable {
105107
self = try .cron(
106108
expr: container.decode(String.self, forKey: .expr),
107109
tz: container.decodeIfPresent(String.self, forKey: .tz))
110+
case "on-exit":
111+
self = try .onExit(
112+
command: container.decode(String.self, forKey: .command),
113+
cwd: container.decodeIfPresent(String.self, forKey: .cwd))
108114
default:
109115
throw DecodingError.dataCorruptedError(
110116
forKey: .kind,
@@ -125,6 +131,9 @@ enum CronSchedule: Codable, Equatable {
125131
case let .cron(expr, tz):
126132
try container.encode(expr, forKey: .expr)
127133
try container.encodeIfPresent(tz, forKey: .tz)
134+
case let .onExit(command, cwd):
135+
try container.encode(command, forKey: .command)
136+
try container.encodeIfPresent(cwd, forKey: .cwd)
128137
}
129138
}
130139

‎apps/macos/Sources/OpenClaw/CronSettings+Helpers.swift‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ extension CronSettings {
2727
case let .cron(expr, tz):
2828
if let tz, !tz.isEmpty { return "cron \(expr) (\(tz))" }
2929
return "cron \(expr)"
30+
case let .onExit(command, cwd):
31+
if let cwd, !cwd.isEmpty { return "on exit: \(command) (cwd: \(cwd))" }
32+
return "on exit: \(command)"
3033
}
3134
}
3235

‎packages/gateway-protocol/src/schema/cron.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ const CronJobsScheduleKindFilterSchema = Type.Union([
8383
Type.Literal("at"),
8484
Type.Literal("every"),
8585
Type.Literal("cron"),
86+
Type.Literal("on-exit"),
8687
]);
8788
const CronJobsLastRunStatusFilterSchema = Type.Union([
8889
Type.Literal("all"),
@@ -223,6 +224,17 @@ export const CronScheduleSchema = Type.Union([
223224
},
224225
{ additionalProperties: false },
225226
),
227+
Type.Object(
228+
{
229+
// Event-driven trigger: fires once when the gateway-owned watcher running
230+
// `command` exits. Survives per-turn CLI teardown (runs under the gateway
231+
// ProcessSupervisor, not the turn process tree).
232+
kind: Type.Literal("on-exit"),
233+
command: NonEmptyString,
234+
cwd: Type.Optional(NonEmptyString),
235+
},
236+
{ additionalProperties: false },
237+
),
226238
]);
227239

228240
/** Full cron payload for new jobs. */

‎scripts/proof-cron-on-exit.mts‎

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
// Live-proof harness for PR #92037 (cron `on-exit` schedule kind).
2+
//
3+
// Drives the REAL gateway exit-watcher (`createCronExitWatchers`) against the
4+
// REAL ProcessSupervisor (`getProcessSupervisor`) with a REAL short-lived child
5+
// command, and captures the actual arm -> exit -> persist-before-fire -> fire
6+
// lifecycle. The persistCompletion/fireOnExit sinks mirror the real wiring in
7+
// server-cron.ts (disable-before-fire; force-run after exit) and only RECORD/LOG.
8+
//
9+
// Run: pnpm exec tsx scripts/proof-cron-on-exit.mts
10+
//
11+
// All identifiers are synthetic. No real Telegram chat ids / session keys.
12+
13+
import type { CronJob } from "../src/cron/types.js";
14+
import {
15+
createCronExitWatchers,
16+
resolveExitWatchShell,
17+
} from "../src/gateway/cron-exit-watchers.js";
18+
import { getProcessSupervisor } from "../src/process/supervisor/index.js";
19+
20+
const isWin = process.platform === "win32";
21+
// Commands phrased for the shell the watcher actually resolves on this host
22+
// (cmd.exe /d /s /c on Windows, bash -lc on POSIX).
23+
const delayThenExit = (code: number) =>
24+
isWin ? `ping -n 3 127.0.0.1 > nul & exit ${code}` : `sleep 2; exit ${code}`;
25+
const longRunning = () => (isWin ? `ping -n 31 127.0.0.1 > nul` : `sleep 30`);
26+
27+
type FireEvent = { jobId: string; exitCode: number | null };
28+
29+
const events: { armed: string[]; persisted: string[]; fired: FireEvent[] } = {
30+
armed: [],
31+
persisted: [],
32+
fired: [],
33+
};
34+
// Monotonic call-order log so we can assert persist-before-fire directly
35+
// (the watcher's fail-closed guarantee), not merely that both happened.
36+
const order: string[] = [];
37+
38+
const logger = {
39+
info: (obj: unknown, msg?: string) => {
40+
const o = obj as { jobId?: string; exitCode?: number | null; reason?: string };
41+
if (msg?.includes("watcher armed") && o.jobId) {
42+
events.armed.push(o.jobId);
43+
}
44+
console.log(`[cron-exit] ${msg ?? ""} ${JSON.stringify(obj)}`);
45+
},
46+
warn: (obj: unknown, msg?: string) =>
47+
console.log(`[cron-exit][warn] ${msg ?? ""} ${JSON.stringify(obj)}`),
48+
};
49+
50+
const watchers = createCronExitWatchers({
51+
getProcessSupervisor,
52+
// Real wiring disables the one-shot job in the store before firing.
53+
persistCompletion: async (jobId) => {
54+
events.persisted.push(jobId);
55+
order.push(`persist:${jobId}`);
56+
console.log(`[cron-exit] persistCompletion (job disabled, enabled=false) jobId=${jobId}`);
57+
},
58+
// Real wiring routes this into cron.run(job.id, "force").
59+
fireOnExit: (job, exit) => {
60+
events.fired.push({ jobId: job.id, exitCode: exit.exitCode });
61+
order.push(`fire:${job.id}`);
62+
console.log(`[gateway/cron] cron.run force jobId=${job.id}`);
63+
},
64+
logger,
65+
});
66+
67+
function onExitJob(id: string, command: string, extra?: Partial<CronJob>): CronJob {
68+
return {
69+
id,
70+
enabled: true,
71+
schedule: { kind: "on-exit", command },
72+
sessionKey: `agent:main:telegram:direct:SYN:thread:SYN`,
73+
payload: { text: `on-exit[${id}]` },
74+
...extra,
75+
} as unknown as CronJob;
76+
}
77+
78+
const sleep = (ms: number) =>
79+
new Promise<void>((r) => {
80+
setTimeout(r, ms);
81+
});
82+
async function waitFor(pred: () => boolean, timeoutMs: number, pollMs = 100): Promise<boolean> {
83+
const start = Date.now();
84+
while (Date.now() - start < timeoutMs) {
85+
if (pred()) {
86+
return true;
87+
}
88+
await sleep(pollMs);
89+
}
90+
return pred();
91+
}
92+
93+
let failures = 0;
94+
function assert(label: string, cond: boolean): void {
95+
console.log(` ${cond ? "PASS" : "FAIL"}: ${label}`);
96+
if (!cond) {
97+
failures++;
98+
}
99+
}
100+
101+
async function run(): Promise<void> {
102+
const shell = resolveExitWatchShell();
103+
console.log(`=== PR #92037 on-exit live proof (real watcher + real ProcessSupervisor) ===`);
104+
console.log(
105+
`platform=${process.platform} shell=${shell.command} argv=${JSON.stringify(shell.argsFor("<cmd>"))}`,
106+
);
107+
108+
// Scenario A: arm a real watcher; the watched command runs ~2s then exits 7.
109+
// Expect: armed -> exited -> persistCompletion BEFORE fire -> fire with exitCode 7.
110+
console.log(`\n=== A. arm -> watched command exits (code 7) -> force-run fires ===`);
111+
const a = onExitJob("onexit-A", delayThenExit(7));
112+
watchers.reconcile([a]);
113+
assert(
114+
"watcher is active immediately after reconcile",
115+
watchers.activeJobIds().includes("onexit-A"),
116+
);
117+
const aFired = await waitFor(() => events.fired.some((e) => e.jobId === "onexit-A"), 15000);
118+
assert("watcher armed (logged) for onexit-A", events.armed.includes("onexit-A"));
119+
assert("job fired after the command exited", aFired);
120+
const aEvt = events.fired.find((e) => e.jobId === "onexit-A");
121+
assert("exit code 7 captured from the real child", aEvt?.exitCode === 7);
122+
assert(
123+
"persistCompletion ran BEFORE fire (fail-closed ordering)",
124+
order.includes("persist:onexit-A") &&
125+
order.indexOf("persist:onexit-A") < order.indexOf("fire:onexit-A"),
126+
);
127+
assert("fire routed to the cron force-run sink", aEvt?.jobId === a.id);
128+
129+
// Scenario B: arm a long-running watcher, cancel before exit -> NO fire.
130+
console.log(`\n=== B. arm -> cancel before exit -> no fire (revocation) ===`);
131+
const b = onExitJob("onexit-B", longRunning());
132+
watchers.reconcile([b]);
133+
await waitFor(() => events.armed.includes("onexit-B"), 8000);
134+
assert("watcher armed for onexit-B", events.armed.includes("onexit-B"));
135+
watchers.cancel("onexit-B");
136+
assert(
137+
"watcher removed from active set after cancel",
138+
!watchers.activeJobIds().includes("onexit-B"),
139+
);
140+
await sleep(2500);
141+
assert("cancelled watcher never fired", !events.fired.some((e) => e.jobId === "onexit-B"));
142+
143+
// Scenario C: reconcile without the job cancels its watcher.
144+
console.log(`\n=== C. reconcile-removal cancels the watcher ===`);
145+
const c = onExitJob("onexit-C", longRunning());
146+
watchers.reconcile([c]);
147+
await waitFor(() => watchers.activeJobIds().includes("onexit-C"), 8000);
148+
assert("watcher active for onexit-C", watchers.activeJobIds().includes("onexit-C"));
149+
watchers.reconcile([]); // job gone
150+
assert("reconcile([]) cancelled onexit-C", !watchers.activeJobIds().includes("onexit-C"));
151+
}
152+
153+
async function main(): Promise<void> {
154+
try {
155+
await run();
156+
} finally {
157+
// Always tear down watchers so a thrown assertion can't leak the
158+
// long-running ping/sleep children (B, C) until their 24h timeout.
159+
watchers.cancelAll();
160+
await sleep(300);
161+
}
162+
console.log(`\n=== RESULT: ${failures === 0 ? "ALL PASS" : `${failures} FAILURE(S)`} ===`);
163+
process.exit(failures === 0 ? 0 : 1);
164+
}
165+
166+
main().catch((err: unknown) => {
167+
console.error("proof harness crashed:", err);
168+
watchers.cancelAll();
169+
process.exit(1);
170+
});

‎src/agents/tools/cron-tool-canonicalize.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import { timestampMsToIsoString } from "@openclaw/normalization-core/number-coercion";
77
import { isRecord } from "../../utils.js";
88

9-
const CRON_SCHEDULE_KINDS = ["at", "every", "cron"] as const;
9+
const CRON_SCHEDULE_KINDS = ["at", "every", "cron", "on-exit"] as const;
1010
const CRON_PAYLOAD_KINDS = ["systemEvent", "agentTurn"] as const;
1111
const CRON_FLAT_PAYLOAD_KEYS = [
1212
"message",
@@ -32,6 +32,8 @@ const CRON_FLAT_SCHEDULE_KEYS = [
3232
"stagger",
3333
"staggerMs",
3434
"exact",
35+
"command",
36+
"cwd",
3537
] as const;
3638
const CRON_RECOVERABLE_OBJECT_KEYS: ReadonlySet<string> = new Set([
3739
"name",
@@ -54,7 +56,7 @@ const CRON_RECOVERABLE_OBJECT_KEYS: ReadonlySet<string> = new Set([
5456
]);
5557

5658
function isCronScheduleKind(value: unknown): value is (typeof CRON_SCHEDULE_KINDS)[number] {
57-
return value === "at" || value === "every" || value === "cron";
59+
return typeof value === "string" && (CRON_SCHEDULE_KINDS as readonly string[]).includes(value);
5860
}
5961

6062
function isCronPayloadKind(value: unknown): value is (typeof CRON_PAYLOAD_KINDS)[number] {
@@ -178,7 +180,12 @@ function canonicalizeCronToolSchedule(value: Record<string, unknown>): void {
178180
schedule.kind = "cron";
179181
}
180182

181-
for (const key of ["anchorMs", "tz", "staggerMs"] as const) {
183+
const movedCommand = moveDefinedField({ source: value, target: schedule, from: "command" });
184+
if (movedCommand && !isCronScheduleKind(schedule.kind)) {
185+
schedule.kind = "on-exit";
186+
}
187+
188+
for (const key of ["anchorMs", "tz", "staggerMs", "cwd"] as const) {
182189
hasSchedule = moveDefinedField({ source: value, target: schedule, from: key }) || hasSchedule;
183190
}
184191
hasSchedule =
@@ -198,6 +205,8 @@ function canonicalizeCronToolSchedule(value: Record<string, unknown>): void {
198205
schedule.kind = "every";
199206
} else if (schedule.expr !== undefined) {
200207
schedule.kind = "cron";
208+
} else if (schedule.command !== undefined) {
209+
schedule.kind = "on-exit";
201210
}
202211
}
203212

0 commit comments

Comments
 (0)