-
-
Notifications
You must be signed in to change notification settings - Fork 76.3k
Expand file tree
/
Copy pathcron-tool.ts
More file actions
846 lines (792 loc) · 31.2 KB
/
cron-tool.ts
File metadata and controls
846 lines (792 loc) · 31.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
import { Type, type TSchema } from "typebox";
import { getRuntimeConfig } from "../../config/config.js";
import { normalizeCronJobCreate, normalizeCronJobPatch } from "../../cron/normalize.js";
import type { CronDelivery, CronMessageChannel } from "../../cron/types.js";
import { normalizeHttpWebhookUrl } from "../../cron/webhook-url.js";
import {
parseAgentSessionKey,
parseThreadSessionSuffix,
} from "../../sessions/session-key-utils.js";
import { extractTextFromChatContent } from "../../shared/chat-content.js";
import {
normalizeLowercaseStringOrEmpty,
normalizeOptionalLowercaseString,
normalizeOptionalString,
} from "../../shared/string-coerce.js";
import { isRecord, truncateUtf16Safe } from "../../utils.js";
import {
normalizeDeliveryContext,
type DeliveryContext,
} from "../../utils/delivery-context.shared.js";
import { resolveSessionAgentId } from "../agent-scope.js";
import { optionalStringEnum, stringEnum } from "../schema/typebox.js";
import { CRON_TOOL_DISPLAY_SUMMARY } from "../tool-description-presets.js";
import { type AnyAgentTool, jsonResult, readStringParam } from "./common.js";
import { callGatewayTool, readGatewayCallOptions, type GatewayCallOptions } from "./gateway.js";
import { isOpenClawOwnerOnlyCoreToolName } from "./owner-only-tools.js";
import { resolveInternalSessionKey, resolveMainSessionAlias } from "./sessions-helpers.js";
// We spell out job/patch properties so that LLMs know what fields to send.
// Nested unions are avoided; runtime validation happens in normalizeCronJob*.
const CRON_ACTIONS = ["status", "list", "add", "update", "remove", "run", "runs", "wake"] as const;
const CRON_SCHEDULE_KINDS = ["at", "every", "cron"] as const;
const CRON_WAKE_MODES = ["now", "next-heartbeat"] as const;
const CRON_PAYLOAD_KINDS = ["systemEvent", "agentTurn"] as const;
const CRON_DELIVERY_MODES = ["none", "announce", "webhook"] as const;
const CRON_RUN_MODES = ["due", "force"] as const;
const CRON_FLAT_PAYLOAD_KEYS = [
"message",
"text",
"model",
"fallbacks",
"toolsAllow",
"thinking",
"timeoutSeconds",
"lightContext",
"allowUnsafeExternalContent",
] as const;
const CRON_FLAT_SCHEDULE_KEYS = [
"kind",
"at",
"atMs",
"every",
"everyMs",
"anchorMs",
"cron",
"expr",
"tz",
"stagger",
"staggerMs",
"exact",
] as const;
const CRON_RECOVERABLE_OBJECT_KEYS: ReadonlySet<string> = new Set([
"name",
"schedule",
"sessionTarget",
"wakeMode",
"payload",
"delivery",
"enabled",
"description",
"deleteAfterRun",
"agentId",
"sessionKey",
"failureAlert",
...CRON_FLAT_PAYLOAD_KEYS,
...CRON_FLAT_SCHEDULE_KEYS,
]);
const REMINDER_CONTEXT_MESSAGES_MAX = 10;
const REMINDER_CONTEXT_PER_MESSAGE_MAX = 220;
const REMINDER_CONTEXT_TOTAL_MAX = 700;
const REMINDER_CONTEXT_MARKER = "\n\nRecent context:\n";
function isMissingOrEmptyObject(value: unknown): boolean {
return !value || (isRecord(value) && Object.keys(value).length === 0);
}
function recoverCronObjectFromFlatParams(params: Record<string, unknown>): {
found: boolean;
value: Record<string, unknown>;
} {
const value: Record<string, unknown> = {};
let found = false;
for (const key of Object.keys(params)) {
if (CRON_RECOVERABLE_OBJECT_KEYS.has(key) && params[key] !== undefined) {
value[key] = params[key];
found = true;
}
}
if (value.everyMs === undefined && value.every !== undefined) {
value.everyMs = value.every;
}
if (value.staggerMs === undefined && value.stagger !== undefined) {
value.staggerMs = value.stagger;
}
if (value.exact === true && value.staggerMs === undefined) {
value.staggerMs = 0;
}
delete value.every;
delete value.stagger;
delete value.exact;
return { found, value };
}
function hasCronCreateSignal(value: Record<string, unknown>): boolean {
return (
value.schedule !== undefined ||
value.at !== undefined ||
value.atMs !== undefined ||
value.everyMs !== undefined ||
value.cron !== undefined ||
value.expr !== undefined ||
value.payload !== undefined ||
value.message !== undefined ||
value.text !== undefined
);
}
function nullableStringSchema(description: string) {
return Type.Optional(Type.String({ description }));
}
function nullableStringArraySchema(description: string) {
return Type.Optional(Type.Array(Type.String(), { description }));
}
function cronPayloadObjectSchema(params: { toolsAllow: TSchema }) {
return Type.Object(
{
kind: optionalStringEnum(CRON_PAYLOAD_KINDS, { description: "Payload type" }),
text: Type.Optional(Type.String({ description: "Message text (kind=systemEvent)" })),
message: Type.Optional(Type.String({ description: "Agent prompt (kind=agentTurn)" })),
model: Type.Optional(Type.String({ description: "Model override" })),
thinking: Type.Optional(Type.String({ description: "Thinking level override" })),
timeoutSeconds: Type.Optional(Type.Number()),
lightContext: Type.Optional(Type.Boolean()),
allowUnsafeExternalContent: Type.Optional(Type.Boolean()),
fallbacks: Type.Optional(Type.Array(Type.String(), { description: "Fallback model ids" })),
toolsAllow: params.toolsAllow,
},
{ additionalProperties: true },
);
}
const CronScheduleSchema = Type.Optional(
Type.Object(
{
kind: optionalStringEnum(CRON_SCHEDULE_KINDS, { description: "Schedule type" }),
at: Type.Optional(Type.String({ description: "ISO-8601 timestamp (kind=at)" })),
everyMs: Type.Optional(Type.Number({ description: "Interval in milliseconds (kind=every)" })),
anchorMs: Type.Optional(
Type.Number({ description: "Optional start anchor in milliseconds (kind=every)" }),
),
expr: Type.Optional(
Type.String({
description:
'Cron expression (kind=cron) written in the supplied tz\'s local wall-clock time, or the Gateway host local timezone when tz is omitted; do not convert the requested local time to UTC first. Example: 6pm Shanghai daily is "0 18 * * *" with tz "Asia/Shanghai".',
}),
),
tz: Type.Optional(
Type.String({
description:
'IANA timezone for interpreting cron wall-clock fields (kind=cron), e.g. "Asia/Shanghai"; if omitted, cron uses the Gateway host local timezone.',
}),
),
staggerMs: Type.Optional(Type.Number({ description: "Random jitter in ms (kind=cron)" })),
},
{ additionalProperties: true },
),
);
const CronPayloadSchema = Type.Optional(
cronPayloadObjectSchema({
toolsAllow: Type.Optional(Type.Array(Type.String(), { description: "Allowed tool ids" })),
}),
);
const CronDeliverySchema = Type.Optional(
Type.Object(
{
mode: optionalStringEnum(CRON_DELIVERY_MODES, { description: "Delivery mode" }),
channel: Type.Optional(Type.String({ description: "Delivery channel" })),
to: Type.Optional(Type.String({ description: "Delivery target" })),
threadId: Type.Optional(
Type.Union([Type.String(), Type.Number()], {
description: "Thread/topic id for channels that support threaded delivery",
}),
),
bestEffort: Type.Optional(Type.Boolean()),
accountId: Type.Optional(Type.String({ description: "Account target for delivery" })),
failureDestination: Type.Optional(
Type.Object(
{
channel: Type.Optional(Type.String()),
to: Type.Optional(Type.String()),
accountId: Type.Optional(Type.String()),
mode: optionalStringEnum(["announce", "webhook"] as const),
},
{ additionalProperties: true },
),
),
},
{ additionalProperties: true },
),
);
// Omitting `failureAlert` means "leave defaults/unchanged"; `false` explicitly disables alerts.
// Runtime handles `failureAlert === false` in cron/service/timer.ts.
// The schema declares `type: "object"` to stay compatible with providers that
// enforce an OpenAPI 3.0 subset (e.g. Gemini via GitHub Copilot). The
// description tells the LLM that `false` is also accepted.
const CronFailureAlertSchema = Type.Optional(
Type.Unsafe<Record<string, unknown> | false>({
type: "object",
properties: {
after: Type.Optional(Type.Number({ description: "Failures before alerting" })),
channel: Type.Optional(Type.String({ description: "Alert channel" })),
to: Type.Optional(Type.String({ description: "Alert target" })),
cooldownMs: Type.Optional(Type.Number({ description: "Cooldown between alerts in ms" })),
includeSkipped: Type.Optional(
Type.Boolean({ description: "Count consecutive skipped runs toward alerting" }),
),
mode: optionalStringEnum(["announce", "webhook"] as const),
accountId: Type.Optional(Type.String()),
},
additionalProperties: true,
description:
"Failure alert config object, or the boolean value false to disable alerts for this job",
}),
);
const CronJobObjectSchema = Type.Optional(
Type.Object(
{
name: Type.Optional(Type.String({ description: "Job name" })),
schedule: CronScheduleSchema,
sessionTarget: Type.Optional(
Type.String({
description: 'Session target: "main", "isolated", "current", or "session:<id>"',
}),
),
wakeMode: optionalStringEnum(CRON_WAKE_MODES, { description: "When to wake the session" }),
payload: CronPayloadSchema,
delivery: CronDeliverySchema,
agentId: nullableStringSchema("Agent id, or null to keep it unset"),
description: Type.Optional(Type.String({ description: "Human-readable description" })),
enabled: Type.Optional(Type.Boolean()),
deleteAfterRun: Type.Optional(Type.Boolean({ description: "Delete after first execution" })),
sessionKey: nullableStringSchema("Explicit session key, or null to clear it"),
failureAlert: CronFailureAlertSchema,
},
{ additionalProperties: true },
),
);
const CronPatchObjectSchema = Type.Optional(
Type.Object(
{
name: Type.Optional(Type.String({ description: "Job name" })),
schedule: CronScheduleSchema,
sessionTarget: Type.Optional(Type.String({ description: "Session target" })),
wakeMode: optionalStringEnum(CRON_WAKE_MODES),
payload: Type.Optional(
cronPayloadObjectSchema({
toolsAllow: nullableStringArraySchema("Allowed tool ids, or null to clear"),
}),
),
delivery: CronDeliverySchema,
description: Type.Optional(Type.String()),
enabled: Type.Optional(Type.Boolean()),
deleteAfterRun: Type.Optional(Type.Boolean()),
agentId: nullableStringSchema("Agent id, or null to clear it"),
sessionKey: nullableStringSchema("Explicit session key, or null to clear it"),
failureAlert: CronFailureAlertSchema,
},
{ additionalProperties: true },
),
);
// Flattened schema: runtime validates per-action requirements.
export const CronToolSchema = Type.Object(
{
action: stringEnum(CRON_ACTIONS),
gatewayUrl: Type.Optional(Type.String()),
gatewayToken: Type.Optional(Type.String()),
timeoutMs: Type.Optional(Type.Number()),
includeDisabled: Type.Optional(Type.Boolean()),
job: CronJobObjectSchema,
jobId: Type.Optional(Type.String()),
id: Type.Optional(Type.String()),
patch: CronPatchObjectSchema,
text: Type.Optional(Type.String()),
mode: optionalStringEnum(CRON_WAKE_MODES),
runMode: optionalStringEnum(CRON_RUN_MODES),
contextMessages: Type.Optional(
Type.Number({ minimum: 0, maximum: REMINDER_CONTEXT_MESSAGES_MAX }),
),
},
{ additionalProperties: true },
);
type CronToolOptions = {
agentSessionKey?: string;
currentDeliveryContext?: DeliveryContext;
/** Restrict this cron tool instance to removing only this active cron job. */
selfRemoveOnlyJobId?: string;
};
type GatewayToolCaller = typeof callGatewayTool;
type CronToolDeps = {
callGatewayTool?: GatewayToolCaller;
};
type ChatMessage = {
role?: unknown;
content?: unknown;
};
function stripExistingContext(text: string) {
const index = text.indexOf(REMINDER_CONTEXT_MARKER);
if (index === -1) {
return text;
}
return text.slice(0, index).trim();
}
function truncateText(input: string, maxLen: number) {
if (input.length <= maxLen) {
return input;
}
const truncated = truncateUtf16Safe(input, Math.max(0, maxLen - 3)).trimEnd();
return `${truncated}...`;
}
function readCronJobIdParam(params: Record<string, unknown>) {
return readStringParam(params, "jobId") ?? readStringParam(params, "id");
}
function assertCronSelfRemoveScope(
opts: CronToolOptions | undefined,
action: string,
params: Record<string, unknown>,
) {
const selfRemoveOnlyJobId = opts?.selfRemoveOnlyJobId?.trim();
if (!selfRemoveOnlyJobId) {
return;
}
if (action !== "remove") {
throw new Error("Cron tool is restricted to removing the current cron job.");
}
const id = readCronJobIdParam(params);
if (id && id === selfRemoveOnlyJobId) {
return;
}
throw new Error("Cron tool is restricted to removing the current cron job.");
}
function extractMessageText(message: ChatMessage): { role: string; text: string } | null {
const role = typeof message.role === "string" ? message.role : "";
if (role !== "user" && role !== "assistant") {
return null;
}
const text = extractTextFromChatContent(message.content);
return text ? { role, text } : null;
}
async function buildReminderContextLines(params: {
agentSessionKey?: string;
gatewayOpts: GatewayCallOptions;
contextMessages: number;
callGatewayTool: GatewayToolCaller;
}) {
const maxMessages = Math.min(
REMINDER_CONTEXT_MESSAGES_MAX,
Math.max(0, Math.floor(params.contextMessages)),
);
if (maxMessages <= 0) {
return [];
}
const sessionKey = params.agentSessionKey?.trim();
if (!sessionKey) {
return [];
}
const cfg = getRuntimeConfig();
const { mainKey, alias } = resolveMainSessionAlias(cfg);
const resolvedKey = resolveInternalSessionKey({ key: sessionKey, alias, mainKey });
try {
const res = await params.callGatewayTool<{ messages: Array<unknown> }>(
"chat.history",
params.gatewayOpts,
{
sessionKey: resolvedKey,
limit: maxMessages,
},
);
const messages = Array.isArray(res?.messages) ? res.messages : [];
const parsed = messages
.map((msg) => extractMessageText(msg as ChatMessage))
.filter((msg): msg is { role: string; text: string } => Boolean(msg));
const recent = parsed.slice(-maxMessages);
if (recent.length === 0) {
return [];
}
const lines: string[] = [];
let total = 0;
for (const entry of recent) {
const label = entry.role === "user" ? "User" : "Assistant";
const text = truncateText(entry.text, REMINDER_CONTEXT_PER_MESSAGE_MAX);
const line = `- ${label}: ${text}`;
total += line.length;
if (total > REMINDER_CONTEXT_TOTAL_MAX) {
break;
}
lines.push(line);
}
return lines;
} catch {
return [];
}
}
function stripThreadSuffixFromSessionKey(sessionKey: string): string {
const normalized = normalizeLowercaseStringOrEmpty(sessionKey);
const idx = normalized.lastIndexOf(":thread:");
if (idx <= 0) {
return sessionKey;
}
const parent = sessionKey.slice(0, idx).trim();
return parent ? parent : sessionKey;
}
function resolveTelegramDirectThreadId(params: {
peerId: string;
threadId?: string;
}): string | undefined {
const threadId = normalizeOptionalString(params.threadId);
if (!threadId) {
return undefined;
}
const peerId = normalizeOptionalString(params.peerId);
if (!peerId) {
return undefined;
}
const [threadChatId, ...threadIdParts] = threadId.split(":");
if (threadIdParts.length === 0) {
return threadId;
}
if (normalizeOptionalLowercaseString(threadChatId) !== peerId) {
return undefined;
}
return normalizeOptionalString(threadIdParts.join(":"));
}
function inferDeliveryFromSessionKey(agentSessionKey?: string): CronDelivery | null {
const rawSessionKey = agentSessionKey?.trim();
if (!rawSessionKey) {
return null;
}
const threadSuffix = parseThreadSessionSuffix(rawSessionKey);
const parsed = parseAgentSessionKey(
threadSuffix.baseSessionKey ?? stripThreadSuffixFromSessionKey(rawSessionKey),
);
if (!parsed || !parsed.rest) {
return null;
}
const parts = parsed.rest.split(":").filter(Boolean);
if (parts.length === 0) {
return null;
}
const head = normalizeOptionalLowercaseString(parts[0]);
if (!head || head === "main" || head === "subagent" || head === "acp") {
return null;
}
// buildAgentPeerSessionKey encodes peers as:
// - direct:<peerId>
// - <channel>:direct:<peerId>
// - <channel>:<accountId>:direct:<peerId>
// - <channel>:group:<peerId>
// - <channel>:channel:<peerId>
// Note: legacy keys may use "dm" instead of "direct".
// Threaded sessions append :thread:<id>, which we strip so delivery targets the parent peer.
// NOTE: Telegram forum topics encode as <chatId>:topic:<topicId> and should be preserved.
const markerIndex = parts.findIndex(
(part) => part === "direct" || part === "dm" || part === "group" || part === "channel",
);
if (markerIndex === -1) {
return null;
}
const peerId = parts
.slice(markerIndex + 1)
.join(":")
.trim();
if (!peerId) {
return null;
}
let channel: CronMessageChannel | undefined;
if (markerIndex >= 1) {
channel = normalizeOptionalLowercaseString(parts[0]) as CronMessageChannel | undefined;
}
const marker = parts[markerIndex];
const delivery: CronDelivery = { mode: "announce", to: peerId };
if (channel) {
delivery.channel = channel;
}
if (channel === "telegram" && markerIndex === 2) {
const accountId = normalizeOptionalString(parts[1]);
if (accountId) {
delivery.accountId = accountId;
}
}
if (channel === "telegram" && (marker === "direct" || marker === "dm")) {
const threadId = resolveTelegramDirectThreadId({
peerId,
threadId: threadSuffix.threadId,
});
if (threadId) {
delivery.threadId = threadId;
}
}
return delivery;
}
function inferDeliveryFromContext(context?: DeliveryContext): CronDelivery | null {
const normalized = normalizeDeliveryContext(context);
if (!normalized?.to) {
return null;
}
const delivery: CronDelivery = {
mode: "announce",
to: normalized.to,
};
if (normalized.channel) {
delivery.channel = normalized.channel as CronMessageChannel;
}
if (normalized.accountId) {
delivery.accountId = normalized.accountId;
}
if (normalized.threadId != null) {
delivery.threadId = normalized.threadId;
}
return delivery;
}
export function createCronTool(opts?: CronToolOptions, deps?: CronToolDeps): AnyAgentTool {
const callGateway = deps?.callGatewayTool ?? callGatewayTool;
return {
label: "Cron",
name: "cron",
ownerOnly: isOpenClawOwnerOnlyCoreToolName("cron"),
displaySummary: CRON_TOOL_DISPLAY_SUMMARY,
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.
Main-session cron jobs enqueue system events for heartbeat handling. Isolated cron jobs create background task runs that appear in \`openclaw tasks\`.
ACTIONS:
- status: Check cron scheduler status
- list: List jobs (use includeDisabled:true to include disabled)
- add: Create job (requires job object, see schema below)
- update: Modify job (requires jobId + patch object)
- remove: Delete job (requires jobId)
- run: Trigger job immediately (requires jobId)
- runs: Get job run history (requires jobId)
- wake: Send wake event (requires text, optional mode)
JOB SCHEMA (for add action):
{
"name": "string (optional)",
"schedule": { ... }, // Required: when to run
"payload": { ... }, // Required: what to execute
"delivery": { ... }, // Optional: announce summary (isolated/current/session:xxx only) or webhook POST
"sessionTarget": "main" | "isolated" | "current" | "session:<custom-id>", // Optional, defaults based on context
"enabled": true | false // Optional, default true
}
SESSION TARGET OPTIONS:
- "main": Run in the main session (requires payload.kind="systemEvent")
- "isolated": Run in an ephemeral isolated session (requires payload.kind="agentTurn")
- "current": Bind to the current session where the cron is created (resolved at creation time)
- "session:<custom-id>": Run in a persistent named session (e.g., "session:project-alpha-daily")
DEFAULT BEHAVIOR (unchanged for backward compatibility):
- payload.kind="systemEvent" → defaults to "main"
- payload.kind="agentTurn" → defaults to "isolated"
To use current session binding, explicitly set sessionTarget="current".
SCHEDULE TYPES (schedule.kind):
- "at": One-shot at absolute time
{ "kind": "at", "at": "<ISO-8601 timestamp>" }
- "every": Recurring interval
{ "kind": "every", "everyMs": <interval-ms>, "anchorMs": <optional-start-ms> }
- "cron": Cron expression evaluated in the supplied timezone, or the Gateway host local timezone when tz is omitted
{ "kind": "cron", "expr": "<cron-expression>", "tz": "<optional-IANA-timezone>" }
Write expr in the selected timezone's local wall-clock time; do not convert the requested local time to UTC first.
If tz is omitted, do not assume UTC; the Gateway host local timezone is used.
Example: "Remind me every day at 6pm Shanghai time" -> { "kind": "cron", "expr": "0 18 * * *", "tz": "Asia/Shanghai" }
For schedule.kind="at", ISO timestamps without an explicit timezone are treated as UTC.
PAYLOAD TYPES (payload.kind):
- "systemEvent": Injects text as system event into session
{ "kind": "systemEvent", "text": "<message>" }
- "agentTurn": Runs agent with message (isolated sessions only)
{ "kind": "agentTurn", "message": "<prompt>", "model": "<optional>", "thinking": "<optional>", "timeoutSeconds": <optional, 0 means no timeout> }
DELIVERY (top-level):
{ "mode": "none|announce|webhook", "channel": "<optional>", "to": "<optional>", "threadId": "<optional>", "bestEffort": <optional-bool> }
- Default for isolated agentTurn jobs (when delivery omitted): "announce"
- announce: send to chat channel (optional channel/to target)
- threadId: chat thread/topic id for channels that support threaded delivery
- webhook: send finished-run event as HTTP POST to delivery.to (URL required)
- If the task needs to send to a specific chat/recipient, set announce delivery.channel/to; do not call messaging tools inside the run.
CRITICAL CONSTRAINTS:
- sessionTarget="main" REQUIRES payload.kind="systemEvent"
- sessionTarget="isolated" | "current" | "session:xxx" REQUIRES payload.kind="agentTurn"
- For webhook callbacks, use delivery.mode="webhook" with delivery.to set to a URL.
Default: prefer isolated agentTurn jobs unless the user explicitly wants current-session binding.
WAKE MODES (for wake action):
- "next-heartbeat" (default): Wake on next heartbeat
- "now": Wake immediately
Use jobId as the canonical identifier; id is accepted for compatibility. Use contextMessages (0-10) to add previous messages as context to the job text.`,
parameters: CronToolSchema,
execute: async (_toolCallId, args) => {
const params = args as Record<string, unknown>;
const action = readStringParam(params, "action", { required: true });
assertCronSelfRemoveScope(opts, action, params);
const gatewayOpts: GatewayCallOptions = {
...readGatewayCallOptions(params),
timeoutMs:
typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs)
? params.timeoutMs
: 60_000,
};
switch (action) {
case "status":
return jsonResult(await callGateway("cron.status", gatewayOpts, {}));
case "list":
return jsonResult(
await callGateway("cron.list", gatewayOpts, {
includeDisabled: Boolean(params.includeDisabled),
}),
);
case "add": {
// Flat-params recovery: non-frontier models (e.g. Grok) sometimes flatten
// job properties to the top level alongside `action` instead of nesting
// them inside `job`. When `params.job` is missing or empty, reconstruct
// a synthetic job object from any recognised top-level job fields.
// See: https://github.com/openclaw/openclaw/issues/11310
if (isMissingOrEmptyObject(params.job)) {
const synthetic = recoverCronObjectFromFlatParams(params);
// Only use the synthetic job if at least one meaningful field is present
// (schedule, payload, message, or text are the minimum signals that the
// LLM intended to create a job).
if (synthetic.found && hasCronCreateSignal(synthetic.value)) {
params.job = synthetic.value;
}
}
if (!params.job || typeof params.job !== "object") {
throw new Error("job required");
}
const job =
normalizeCronJobCreate(params.job, {
sessionContext: { sessionKey: opts?.agentSessionKey },
}) ?? params.job;
if (job && typeof job === "object") {
const cfg = getRuntimeConfig();
const { mainKey, alias } = resolveMainSessionAlias(cfg);
const resolvedSessionKey = opts?.agentSessionKey
? resolveInternalSessionKey({ key: opts.agentSessionKey, alias, mainKey })
: undefined;
if (!("agentId" in job) || (job as { agentId?: unknown }).agentId === undefined) {
const agentId = opts?.agentSessionKey
? resolveSessionAgentId({ sessionKey: opts.agentSessionKey, config: cfg })
: undefined;
if (agentId) {
(job as { agentId?: string }).agentId = agentId;
}
}
if (!("sessionKey" in job) && resolvedSessionKey) {
(job as { sessionKey?: string }).sessionKey = resolvedSessionKey;
}
}
if (
(opts?.agentSessionKey || opts?.currentDeliveryContext) &&
job &&
typeof job === "object" &&
"payload" in job &&
(job as { payload?: { kind?: string } }).payload?.kind === "agentTurn"
) {
const deliveryValue = (job as { delivery?: unknown }).delivery;
const delivery = isRecord(deliveryValue) ? deliveryValue : undefined;
const modeRaw = typeof delivery?.mode === "string" ? delivery.mode : "";
const mode = normalizeLowercaseStringOrEmpty(modeRaw);
if (mode === "webhook") {
const webhookUrl = normalizeHttpWebhookUrl(delivery?.to);
if (!webhookUrl) {
throw new Error(
'delivery.mode="webhook" requires delivery.to to be a valid http(s) URL',
);
}
if (delivery) {
delivery.to = webhookUrl;
}
}
const hasTarget =
(typeof delivery?.channel === "string" && delivery.channel.trim()) ||
(typeof delivery?.to === "string" && delivery.to.trim());
const shouldInfer =
(deliveryValue == null || delivery) &&
(mode === "" || mode === "announce") &&
!hasTarget;
if (shouldInfer) {
const inferred =
inferDeliveryFromContext(opts.currentDeliveryContext) ??
inferDeliveryFromSessionKey(opts.agentSessionKey);
if (inferred) {
(job as { delivery?: unknown }).delivery = {
...inferred,
...delivery,
} satisfies CronDelivery;
}
}
}
const contextMessages =
typeof params.contextMessages === "number" && Number.isFinite(params.contextMessages)
? params.contextMessages
: 0;
if (
job &&
typeof job === "object" &&
"payload" in job &&
(job as { payload?: { kind?: string; text?: string } }).payload?.kind === "systemEvent"
) {
const payload = (job as { payload: { kind: string; text: string } }).payload;
if (typeof payload.text === "string" && payload.text.trim()) {
const contextLines = await buildReminderContextLines({
agentSessionKey: opts?.agentSessionKey,
gatewayOpts,
contextMessages,
callGatewayTool: callGateway,
});
if (contextLines.length > 0) {
const baseText = stripExistingContext(payload.text);
payload.text = `${baseText}${REMINDER_CONTEXT_MARKER}${contextLines.join("\n")}`;
}
}
}
return jsonResult(await callGateway("cron.add", gatewayOpts, job));
}
case "update": {
const id = readCronJobIdParam(params);
if (!id) {
throw new Error("jobId required (id accepted for backward compatibility)");
}
// Flat-params recovery for patch
let recoveredFlatPatch = false;
if (isMissingOrEmptyObject(params.patch)) {
const synthetic = recoverCronObjectFromFlatParams(params);
if (synthetic.found) {
params.patch = synthetic.value;
recoveredFlatPatch = true;
}
}
if (!params.patch || typeof params.patch !== "object") {
throw new Error("patch required");
}
const patch = normalizeCronJobPatch(params.patch) ?? params.patch;
if (
recoveredFlatPatch &&
typeof patch === "object" &&
patch !== null &&
Object.keys(patch as Record<string, unknown>).length === 0
) {
throw new Error("patch required");
}
return jsonResult(
await callGateway("cron.update", gatewayOpts, {
id,
patch,
}),
);
}
case "remove": {
const id = readCronJobIdParam(params);
if (!id) {
throw new Error("jobId required (id accepted for backward compatibility)");
}
return jsonResult(await callGateway("cron.remove", gatewayOpts, { id }));
}
case "run": {
const id = readCronJobIdParam(params);
if (!id) {
throw new Error("jobId required (id accepted for backward compatibility)");
}
const runMode =
params.runMode === "due" || params.runMode === "force" ? params.runMode : "force";
return jsonResult(await callGateway("cron.run", gatewayOpts, { id, mode: runMode }));
}
case "runs": {
const id = readCronJobIdParam(params);
if (!id) {
throw new Error("jobId required (id accepted for backward compatibility)");
}
return jsonResult(await callGateway("cron.runs", gatewayOpts, { id }));
}
case "wake": {
const text = readStringParam(params, "text", { required: true });
const mode =
params.mode === "now" || params.mode === "next-heartbeat"
? params.mode
: "next-heartbeat";
return jsonResult(
await callGateway("wake", gatewayOpts, { mode, text }, { expectFinal: false }),
);
}
default:
throw new Error(`Unknown action: ${action}`);
}
},
};
}