Skip to content

Commit d52ac64

Browse files
samzongsteipete
authored andcommitted
feat(cron): add direct job lookup
Signed-off-by: samzong <[email protected]>
1 parent 3775532 commit d52ac64

31 files changed

Lines changed: 263 additions & 31 deletions

‎docs/automation/cron-jobs.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ Cron is the Gateway's built-in scheduler. It persists jobs, wakes the agent at t
2727
<Step title="Check your jobs">
2828
```bash
2929
openclaw cron list
30+
openclaw cron get <job-id>
3031
openclaw cron show <job-id>
3132
```
3233
</Step>
@@ -359,6 +360,9 @@ When `hooks.enabled=true` and `hooks.gmail.account` is set, the Gateway starts `
359360
# List all jobs
360361
openclaw cron list
361362

363+
# Get one stored job as JSON
364+
openclaw cron get <jobId>
365+
362366
# Show one job, including resolved delivery route
363367
openclaw cron show <jobId>
364368

‎docs/cli/cron.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,7 @@ Manual run and inspection:
220220
```bash
221221
openclaw cron list
222222
openclaw cron list --agent ops
223+
openclaw cron get <job-id>
223224
openclaw cron show <job-id>
224225
openclaw cron run <job-id>
225226
openclaw cron run <job-id> --due
@@ -228,6 +229,8 @@ openclaw cron runs --id <job-id> --limit 50
228229

229230
`openclaw cron list` shows all matching jobs by default. Pass `--agent <id>` to show only jobs whose effective normalized agent id matches; jobs without a stored agent id count as the configured default agent.
230231

232+
`openclaw cron get <job-id>` returns the stored job JSON directly. Use `cron show <job-id>` when you want the human-readable view with delivery-route preview.
233+
231234
`cron list --json` and `cron show <job-id> --json` include a top-level `status` field on each job, computed from `enabled`, `state.runningAtMs`, and `state.lastRunStatus`. Values: `disabled`, `running`, `ok`, `error`, `skipped`, or `idle`. This mirrors the human-readable status column so external tooling can read job state without re-deriving it.
232235

233236
`cron runs` entries include delivery diagnostics with the intended cron target, the resolved target, message-tool sends, fallback use, and delivered state.

‎docs/cli/index.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,7 @@ openclaw [--dev] [--profile <name>] <command>
256256
cron
257257
status
258258
list
259+
get
259260
add
260261
edit
261262
rm

‎docs/gateway/protocol.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ enumeration of `src/gateway/server-methods/*.ts`.
467467
</Accordion>
468468

469469
<Accordion title="Automation, skills, and tools">
470-
- Automation: `wake` schedules an immediate or next-heartbeat wake text injection; `cron.list`, `cron.status`, `cron.add`, `cron.update`, `cron.remove`, `cron.run`, `cron.runs` manage scheduled work.
470+
- Automation: `wake` schedules an immediate or next-heartbeat wake text injection; `cron.get`, `cron.list`, `cron.status`, `cron.add`, `cron.update`, `cron.remove`, `cron.run`, `cron.runs` manage scheduled work.
471471
- Skills and tools: `commands.list`, `skills.*`, `tools.catalog`, `tools.effective`, `tools.invoke`.
472472

473473
</Accordion>

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

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ describe("cron tool", () => {
193193
action: "remove",
194194
jobId: "job-other",
195195
}),
196-
).rejects.toThrow("Cron tool is restricted to removing the current cron job.");
196+
).rejects.toThrow("Cron tool is restricted to the current cron job.");
197197

198198
expect(callGatewayMock).not.toHaveBeenCalled();
199199
});
@@ -233,7 +233,7 @@ describe("cron tool", () => {
233233
const tool = createTestCronTool({ selfRemoveOnlyJobId: "job-current" });
234234

235235
await expect(tool.execute("call-runs-denied", args)).rejects.toThrow(
236-
"Cron tool is restricted to removing the current cron job.",
236+
"Cron tool is restricted to the current cron job.",
237237
);
238238

239239
expect(callGatewayMock).not.toHaveBeenCalled();
@@ -258,6 +258,33 @@ describe("cron tool", () => {
258258
expect(result.details).toEqual({ enabled: true });
259259
});
260260

261+
it("allows scoped isolated cron runs to get the current job", async () => {
262+
callGatewayMock.mockResolvedValueOnce({ id: "job-current", name: "current" });
263+
const tool = createTestCronTool({ selfRemoveOnlyJobId: "job-current" });
264+
265+
const result = await tool.execute("call-get", {
266+
action: "get",
267+
jobId: "job-current",
268+
});
269+
270+
const params = expectSingleGatewayCallMethod("cron.get");
271+
expect(params).toStrictEqual({ id: "job-current" });
272+
expect(result.details).toEqual({ id: "job-current", name: "current" });
273+
});
274+
275+
it.each([
276+
["another job", { action: "get", jobId: "job-other" }],
277+
["missing job id", { action: "get" }],
278+
])("denies scoped isolated cron runs from getting %s", async (_label, args) => {
279+
const tool = createTestCronTool({ selfRemoveOnlyJobId: "job-current" });
280+
281+
await expect(tool.execute("call-get-denied", args)).rejects.toThrow(
282+
"Cron tool is restricted to the current cron job.",
283+
);
284+
285+
expect(callGatewayMock).not.toHaveBeenCalled();
286+
});
287+
261288
it("allows scoped isolated cron runs to list only the current job", async () => {
262289
callGatewayMock.mockResolvedValueOnce({
263290
jobs: [
@@ -366,7 +393,7 @@ describe("cron tool", () => {
366393
const tool = createTestCronTool({ selfRemoveOnlyJobId: "job-current" });
367394

368395
await expect(tool.execute("call-denied", args)).rejects.toThrow(
369-
"Cron tool is restricted to removing the current cron job.",
396+
"Cron tool is restricted to the current cron job.",
370397
);
371398

372399
expect(callGatewayMock).not.toHaveBeenCalled();
@@ -437,6 +464,8 @@ describe("cron tool", () => {
437464
["remove", { action: "remove", id: "job-2" }, { id: "job-2" }],
438465
["run", { action: "run", jobId: "job-1" }, { id: "job-1", mode: "force" }],
439466
["run", { action: "run", id: "job-2" }, { id: "job-2", mode: "force" }],
467+
["get", { action: "get", jobId: "job-1" }, { id: "job-1" }],
468+
["get", { action: "get", id: "job-2" }, { id: "job-2" }],
440469
["runs", { action: "runs", jobId: "job-1" }, { id: "job-1" }],
441470
["runs", { action: "runs", id: "job-2" }, { id: "job-2" }],
442471
])("%s sends id to gateway", async (action, args, expectedParams) => {

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

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,17 @@ import { resolveInternalSessionKey, resolveMainSessionAlias } from "./sessions-h
2929
// We spell out job/patch properties so that LLMs know what fields to send.
3030
// Nested unions are avoided; runtime validation happens in normalizeCronJob*.
3131

32-
const CRON_ACTIONS = ["status", "list", "add", "update", "remove", "run", "runs", "wake"] as const;
32+
const CRON_ACTIONS = [
33+
"status",
34+
"list",
35+
"get",
36+
"add",
37+
"update",
38+
"remove",
39+
"run",
40+
"runs",
41+
"wake",
42+
] as const;
3343

3444
const CRON_SCHEDULE_KINDS = ["at", "every", "cron"] as const;
3545
const CRON_WAKE_MODES = ["now", "next-heartbeat"] as const;
@@ -315,7 +325,6 @@ export const CronToolSchema = Type.Object(
315325
type CronToolOptions = {
316326
agentSessionKey?: string;
317327
currentDeliveryContext?: DeliveryContext;
318-
/** Restrict this cron tool instance to removing only this active cron job. */
319328
selfRemoveOnlyJobId?: string;
320329
};
321330

@@ -350,7 +359,7 @@ function readCronJobIdParam(params: Record<string, unknown>) {
350359
return readStringParam(params, "jobId") ?? readStringParam(params, "id");
351360
}
352361

353-
const CRON_SELF_REMOVE_SCOPE_ERROR = "Cron tool is restricted to removing the current cron job.";
362+
const CRON_SELF_REMOVE_SCOPE_ERROR = "Cron tool is restricted to the current cron job.";
354363

355364
function readCronSelfRemoveOnlyJobId(opts: CronToolOptions | undefined) {
356365
return opts?.selfRemoveOnlyJobId?.trim() || undefined;
@@ -369,7 +378,7 @@ function assertCronSelfRemoveScope(
369378
if (!selfRemoveOnlyJobId || isCronSelfIntrospectionAction(action)) {
370379
return;
371380
}
372-
if (action === "remove" || action === "runs") {
381+
if (action === "get" || action === "remove" || action === "runs") {
373382
const id = readCronJobIdParam(params);
374383
if (id && id === selfRemoveOnlyJobId) {
375384
return;
@@ -623,13 +632,14 @@ export function createCronTool(opts?: CronToolOptions, deps?: CronToolDeps): Any
623632
name: "cron",
624633
ownerOnly: isOpenClawOwnerOnlyCoreToolName("cron"),
625634
displaySummary: CRON_TOOL_DISPLAY_SUMMARY,
626-
description: `Manage Gateway cron jobs (status/list/add/update/remove/run/runs) and send wake events. Use this for reminders, "check back later" requests, delayed follow-ups, and recurring tasks. Do not emulate scheduling with exec sleep or process polling.
635+
description: `Manage Gateway cron jobs (status/list/get/add/update/remove/run/runs) and send wake events. Use this for reminders, "check back later" requests, delayed follow-ups, and recurring tasks. Do not emulate scheduling with exec sleep or process polling.
627636
628637
Main-session cron jobs enqueue system events for heartbeat handling. Isolated cron jobs create background task runs that appear in \`openclaw tasks\`.
629638
630639
ACTIONS:
631640
- status: Check cron scheduler status
632641
- list: List jobs (use includeDisabled:true to include disabled; agentId filters by agent, auto-filled from session)
642+
- get: Get one job by id (requires jobId)
633643
- add: Create job (requires job object, see schema below)
634644
- update: Modify job (requires jobId + patch object)
635645
- remove: Delete job (requires jobId)
@@ -692,7 +702,7 @@ CRITICAL CONSTRAINTS:
692702
Default: prefer isolated agentTurn jobs unless the user explicitly wants current-session binding.
693703
694704
RESTRICTED CRON RUNS:
695-
- Some isolated cron runs receive a narrow cron grant for self-cleanup. In that mode, read-only status and list are for self-introspection only, runs (job run history) is allowed for the current job only, and mutation actions remain limited to removing the current cron job.
705+
- Some isolated cron runs receive a narrow cron grant for self-cleanup. In that mode, read-only status and list are for self-introspection only, get/runs are allowed for the current job only, and mutation actions remain limited to removing the current cron job.
696706
697707
WAKE MODES (for wake action):
698708
- "next-heartbeat" (default): Wake on next heartbeat
@@ -756,6 +766,13 @@ Use jobId as the canonical identifier; id is accepted for compatibility. Use con
756766
selfRemoveOnlyJobId ? filterCronListResultToJobId(result, selfRemoveOnlyJobId) : result,
757767
);
758768
}
769+
case "get": {
770+
const id = readCronJobIdParam(params);
771+
if (!id) {
772+
throw new Error("jobId required (id accepted for backward compatibility)");
773+
}
774+
return jsonResult(await callGateway("cron.get", gatewayOpts, { id }));
775+
}
759776
case "add": {
760777
// Flat-params recovery: non-frontier models (e.g. Grok) sometimes flatten
761778
// job properties to the top level alongside `action` instead of nesting

‎src/cli/cron-cli.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,14 @@ describe("cron cli", () => {
513513
expect(listCall?.[2]).toEqual({ includeDisabled: false, agentId: "ops" });
514514
});
515515

516+
it("routes cron get to cron.get with the provided id", async () => {
517+
await runCronCommand(["cron", "get", "job-1"]);
518+
519+
const getCall = callGatewayFromCli.mock.calls.find((call) => call[0] === "cron.get");
520+
expect(getCall?.[2]).toEqual({ id: "job-1" });
521+
expect(stdoutText()).toContain('"id": "job-1"');
522+
});
523+
516524
it("paginates cron show lookups", async () => {
517525
resetGatewayMock();
518526
callGatewayFromCli.mockImplementation(

‎src/cli/cron-cli/register.cron-simple.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,21 @@ export function registerCronSimpleCommands(cron: Command) {
110110
enabled: false,
111111
});
112112

113+
addGatewayClientOptions(
114+
cron
115+
.command("get")
116+
.description("Get a cron job as JSON")
117+
.argument("<id>", "Job id")
118+
.action(async (id, opts) => {
119+
try {
120+
const res = await callGatewayFromCli("cron.get", opts, { id: String(id) });
121+
printCronJson(res);
122+
} catch (err) {
123+
handleCronCliError(err);
124+
}
125+
}),
126+
);
127+
113128
addGatewayClientOptions(
114129
cron
115130
.command("show")

‎src/cron/service-contract.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export interface CronServiceContract {
2929
run(id: string, mode?: CronRunMode): Promise<CronServiceRunResult>;
3030
enqueueRun(id: string, mode?: CronRunMode): Promise<CronServiceRunResult>;
3131
getJob(id: string): CronJob | undefined;
32+
readJob(id: string): Promise<CronJob | undefined>;
3233
getDefaultAgentId(): string | undefined;
3334
wake(opts: { mode: CronWakeMode; text: string; sessionKey?: string }): CronWakeResult;
3435
}

‎src/cron/service.get-job.test.ts‎

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ const logger = createNoopLogger();
1010
const { makeStorePath } = createCronStoreHarness({ prefix: "openclaw-cron-get-job-" });
1111
installCronTestHooks({ logger });
1212

13-
function createCronService(storePath: string) {
13+
function createCronService(storePath: string, cronEnabled = true) {
1414
return new CronService({
1515
storePath,
16-
cronEnabled: true,
16+
cronEnabled,
1717
log: logger,
1818
enqueueSystemEvent: vi.fn(),
1919
requestHeartbeat: vi.fn(),
@@ -38,7 +38,8 @@ describe("CronService.getJob", () => {
3838
});
3939

4040
expect(cron.getJob(added.id)?.id).toBe(added.id);
41-
expect(cron.getJob("missing-job-id")).toBeUndefined();
41+
await expect(cron.readJob(added.id)).resolves.toEqual(added);
42+
await expect(cron.readJob("missing-job-id")).resolves.toBeUndefined();
4243
} finally {
4344
cron.stop();
4445
}
@@ -59,6 +60,12 @@ describe("CronService.getJob", () => {
5960
payload: { kind: "systemEvent", text: "ping" },
6061
delivery: { mode: "webhook", to: "https://example.invalid/cron" },
6162
});
63+
await expect(cron.readJob(webhookJob.id)).resolves.toMatchObject({
64+
delivery: {
65+
mode: "webhook",
66+
to: "https://example.invalid/cron",
67+
},
68+
});
6269
expect(cron.getJob(webhookJob.id)?.delivery).toEqual({
6370
mode: "webhook",
6471
to: "https://example.invalid/cron",
@@ -67,4 +74,27 @@ describe("CronService.getJob", () => {
6774
cron.stop();
6875
}
6976
});
77+
78+
it("loads persisted jobs for direct reads without starting the scheduler", async () => {
79+
const { storePath } = await makeStorePath();
80+
const writer = createCronService(storePath);
81+
await writer.start();
82+
const persisted = await writer.add({
83+
name: "persisted-job",
84+
enabled: true,
85+
schedule: { kind: "every", everyMs: 60_000 },
86+
sessionTarget: "main",
87+
wakeMode: "next-heartbeat",
88+
payload: { kind: "systemEvent", text: "ping" },
89+
});
90+
writer.stop();
91+
92+
const reader = createCronService(storePath, false);
93+
94+
await expect(reader.readJob(persisted.id)).resolves.toMatchObject({
95+
id: persisted.id,
96+
name: "persisted-job",
97+
});
98+
expect(reader.getJob(persisted.id)).toBeDefined();
99+
});
70100
});

0 commit comments

Comments
 (0)