@soffits/dsh-cron-jobs 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -5
- package/client.js +7 -0
- package/package.json +1 -1
- package/src/config.js +1 -0
- package/src/controller.js +14 -0
- package/src/store.js +2 -0
- package/tools.js +58 -2
package/README.md
CHANGED
|
@@ -93,6 +93,7 @@ Config jobs live in the config of the `cron-jobs` row. Add an override to your p
|
|
|
93
93
|
| `name` | Job name, used in logs and session titles. Must be unique. |
|
|
94
94
|
| `cron` | Cron expression: 5 fields, or 6 with seconds first. Parsed by [croner](https://github.com/hexagon/croner), which handles daylight-saving changes like Vixie cron: a fixed time skipped by a spring forward runs at the first valid time after the gap, a fixed time repeated by a fall back runs once, and patterns with several hours, minutes or seconds run on both repeated occurrences. Set exactly one of `cron`, `rrule` and `at`, or none when the job has `on`. |
|
|
95
95
|
| `on` | Event channel patterns that start a run, such as `[mail.inbox, alerts.*]`. See [Events](#events). |
|
|
96
|
+
| `coalesceSeconds` | How long this job's events gather before it runs once. `0` runs at once. The row's `events.coalesceSeconds` when unset. |
|
|
96
97
|
| `rrule` | RFC 5545 schedule: a `DTSTART` line and an `RRULE` line. The time zone comes from `DTSTART` (`TZID=...`, or `Z` for UTC). See [Schedules](#schedules). |
|
|
97
98
|
| `at` | Run once at this time: ISO 8601 with an offset, or a local date-time read in `timeZone`. |
|
|
98
99
|
| `timeZone` | IANA time zone for the cron expression or an `at` without offset. The Host's zone when empty. |
|
|
@@ -122,7 +123,7 @@ Next to `jobs`, the row also takes:
|
|
|
122
123
|
| `historyRecords` | Runs kept per job for the Cron tasks page. Default 50, at most 1000. |
|
|
123
124
|
| `runLog` | Optional JSON Lines file of run starts and ends, see below. |
|
|
124
125
|
| `watchers` | Long-running commands whose output lines are events: `[{ id, channel, command, cwd, enabled }]`. See [Watchers](#watchers). |
|
|
125
|
-
| `events.coalesceSeconds` | Events for one job that arrive within this many seconds of the first start one run. Default 30. |
|
|
126
|
+
| `events.coalesceSeconds` | Events for one job that arrive within this many seconds of the first start one run. Default 30; a job's own `coalesceSeconds` replaces it. |
|
|
126
127
|
| `events.maxRunsPerHour` | Most event-started runs of one job in any hour; past that, events wait and run together. Default 6; `0` means no cap. |
|
|
127
128
|
|
|
128
129
|
## How runs work
|
|
@@ -257,7 +258,7 @@ echo '{"subject": "hi"}' | dsh-cron-event mail.me --data -
|
|
|
257
258
|
|
|
258
259
|
It writes one file into the plugin's inbox, `$DSH_HOME/cron-jobs/events/` (mode 700), and waits up to ten seconds for DSH to take it, printing the ids of the jobs it matched. No port, token or network path into DSH is needed, and an event written while DSH is down waits there and is taken at the next start. `--id <key>` drops a second event with the same channel and key within an hour; `--no-wait` returns at once; `--text` sends plain text instead of JSON. Exit code 3 means DSH did not take it in time (it stays queued). The CLI is in the profile's `node_modules/.bin`; link it somewhere on `PATH` to call it by name.
|
|
259
260
|
|
|
260
|
-
**What a run sees.** Events for one job that arrive within
|
|
261
|
+
**What a run sees.** Events for one job that arrive within its window, counted from the first one, are gathered, and the job runs once with all of them. The window is the job's own `coalesceSeconds` (set it to 900 for a mailbox that is fine to read every quarter of an hour, or 0 to run at once), or `events.coalesceSeconds` (30 s) for a job without one:
|
|
261
262
|
|
|
262
263
|
- The command gets them on stdin as one JSON document, `{"trigger": "event", "events": [{"channel", "at", "data" or "text", "key", "source"}], "dropped": 0}`, and every command gets `DSH_CRON_TRIGGER` (`schedule`, `manual` or `event`) and `DSH_CRON_JOB` in its environment. A gate still decides whether to wake the agent.
|
|
263
264
|
- The agent prompt gets the events appended, one JSON line each, in a block marked as untrusted data from outside DSH. An event is a hint: the job should read the truth from its source (the mailbox, the CI run), so a forged or garbled event costs one wasted run, and a message's subject never reaches the agent as an instruction.
|
|
@@ -300,8 +301,8 @@ The `cron-jobs-tools` row registers five tools. Their names start with `cron_job
|
|
|
300
301
|
|
|
301
302
|
| Tool | What it does |
|
|
302
303
|
|---|---|
|
|
303
|
-
| `cron_job_create` | Create a job: a title, a prompt and/or a command, one of `cron`, `rrule` and `at` (with `timeZone` where needed) and/or `on` (event channels), where the prompt goes, and optionally `once`, where the result is delivered and which model its sessions use. |
|
|
304
|
-
| `cron_job_edit` | `update` the given fields, `pause`, `resume` (continues from now), or `delete` a job by id. An empty `cron`, `rrule` or `at` removes the schedule of a job with `on`; an empty `on` removes its subscriptions. |
|
|
304
|
+
| `cron_job_create` | Create a job: a title, a prompt and/or a command, one of `cron`, `rrule` and `at` (with `timeZone` where needed) and/or `on` (event channels), where the prompt goes, and optionally `once`, `coalesceSeconds` (the event window), where the result is delivered and which model its sessions use. |
|
|
305
|
+
| `cron_job_edit` | `update` the given fields, `pause`, `resume` (continues from now), or `delete` a job by id. An empty `cron`, `rrule` or `at` removes the schedule of a job with `on`; an empty `on` removes its subscriptions. `coalesceSeconds` sets the event window; a negative number removes it, so the row's setting applies again. `prompt_replace` and `command_replace` change the text in place; see below. |
|
|
305
306
|
| `cron_job_list` | Every job, from the config and from tools, with its id, state, schedule, next run, target and last run. |
|
|
306
307
|
| `cron_job_view` | One job's full definition and its five latest runs. |
|
|
307
308
|
| `cron_job_watch` | `create`, `delete` or `list` [watchers](#watchers). |
|
|
@@ -316,6 +317,8 @@ Where the prompt goes (`target`):
|
|
|
316
317
|
|
|
317
318
|
`deliver` takes `<service>:<address>` (such as `telegramTopics:notify`) or `none`; the service must be running when the job is created. Left out, the job uses the row's default target, or delivers nothing when its prompt goes to an existing session. On `cron_job_edit`, an empty `deliver` goes back to the default.
|
|
318
319
|
|
|
320
|
+
`prompt_replace` and `command_replace` on `cron_job_edit` change a long prompt or command without resending it: a list of literal `{ "old": "...", "new": "...", "replace_all": false }` replacements, applied in order, each to the result of the one before. Every `old` must match exactly once unless that item sets `replace_all`; otherwise the call fails naming the item (`prompt_replace[1] (old "..."): no match` or `matches 3 times`) and changes nothing. They cannot be combined with `prompt` or `command`.
|
|
321
|
+
|
|
319
322
|
`answerCheck` sets the job's [answer check](#answer-checks) command; on `cron_job_edit`, an empty string removes it.
|
|
320
323
|
|
|
321
324
|
`model` is an object, `{ "provider": "anthropic", "model": "claude-sonnet-4-5", "reasoningEffort": "high" }`, with the same ids the model picker uses; `provider` and `model` are required together and `reasoningEffort` is optional. The sessions the job opens start on that model, like `agent.model` on a config job; left out, the preset's or host default applies. `cron_job_edit` with `model` sets it on an existing job, and an empty object (`{}`) clears it. `cron_job_list` and `cron_job_view` show the model when one is set. A job that posts into an existing session (`this_session`, `sessionId`) does not open a session, so its model has no effect.
|
|
@@ -359,7 +362,7 @@ All three are kept in DSH's storage domain service under the domain `cron_jobs`
|
|
|
359
362
|
}
|
|
360
363
|
```
|
|
361
364
|
|
|
362
|
-
`schedule` is `{ "kind": "cron", "expression", "timeZone" }`, `{ "kind": "rrule", "rrule" }` or `{ "kind": "at", "at" }` (a UTC instant); `target` is `{ "kind": "new" }`, `{ "kind": "new_once", "sessionId"? }` or `{ "kind": "session", "sessionId" }`; `status` is `active`, `paused` or `ended`; `command`, `timeoutSeconds`, `model` (`{ "provider", "model", "reasoningEffort"? }`) and `deliver` (`{ "via", "to" }` or `false`; the default when missing) are optional. `scheduledAt` is the next run.
|
|
365
|
+
`schedule` is `{ "kind": "cron", "expression", "timeZone" }`, `{ "kind": "rrule", "rrule" }` or `{ "kind": "at", "at" }` (a UTC instant); `target` is `{ "kind": "new" }`, `{ "kind": "new_once", "sessionId"? }` or `{ "kind": "session", "sessionId" }`; `status` is `active`, `paused` or `ended`; `command`, `timeoutSeconds`, `coalesceSeconds`, `model` (`{ "provider", "model", "reasoningEffort"? }`) and `deliver` (`{ "via", "to" }` or `false`; the default when missing) are optional. `scheduledAt` is the next run.
|
|
363
366
|
|
|
364
367
|
For run history and pausing:
|
|
365
368
|
|
package/client.js
CHANGED
|
@@ -85,6 +85,9 @@ window.__ModuleLoader__.load({
|
|
|
85
85
|
'field.on': 'Runs on events',
|
|
86
86
|
'field.once': 'Runs once',
|
|
87
87
|
'field.onceValue': 'Ends after its first run that was not started by hand',
|
|
88
|
+
'field.coalesce': 'Event window',
|
|
89
|
+
'field.coalesceValue': 'Events gather for {seconds} s before one run',
|
|
90
|
+
'field.coalesceDefault': 'Events gather for {seconds} s before one run (plugin default)',
|
|
88
91
|
'field.pendingEvents': 'Waiting events',
|
|
89
92
|
'field.pendingEventsValue': '{count}, run at {time}',
|
|
90
93
|
'field.timeZone': 'Time zone',
|
|
@@ -225,6 +228,9 @@ window.__ModuleLoader__.load({
|
|
|
225
228
|
'field.on': '事件触发',
|
|
226
229
|
'field.once': '只运行一次',
|
|
227
230
|
'field.onceValue': '第一次非手动运行后结束',
|
|
231
|
+
'field.coalesce': '事件窗口',
|
|
232
|
+
'field.coalesceValue': '事件汇集 {seconds} 秒后运行一次',
|
|
233
|
+
'field.coalesceDefault': '事件汇集 {seconds} 秒后运行一次(插件默认)',
|
|
228
234
|
'field.pendingEvents': '等待中的事件',
|
|
229
235
|
'field.pendingEventsValue': '{count} 个,{time} 运行',
|
|
230
236
|
'field.timeZone': '时区',
|
|
@@ -602,6 +608,7 @@ window.__ModuleLoader__.load({
|
|
|
602
608
|
: t('field.scheduleNone')),
|
|
603
609
|
(job.schedule || job.cron) && h(RuleRow, { key: 'zone', label: t('field.timeZone') }, job.timeZone || t('field.timeZoneHost')),
|
|
604
610
|
job.on?.length > 0 && h(RuleRow, { key: 'on', label: t('field.on') }, h('span', { className: 'dcj-code' }, job.on.join(', '))),
|
|
611
|
+
job.coalesceEffectiveSeconds != null && h(RuleRow, { key: 'coalesce', label: t('field.coalesce') }, t(job.coalesceSeconds == null ? 'field.coalesceDefault' : 'field.coalesceValue', { seconds: job.coalesceEffectiveSeconds })),
|
|
605
612
|
job.once && h(RuleRow, { key: 'once', label: t('field.once') }, t('field.onceValue')),
|
|
606
613
|
job.pendingEvents && h(RuleRow, { key: 'pending', label: t('field.pendingEvents') }, t('field.pendingEventsValue', { count: job.pendingEvents.count, time: formatAbsolute(job.pendingEvents.dueAt, t('time.locale')) })),
|
|
607
614
|
h(RuleRow, { key: 'kind', label: t('field.kind') }, t(kindLabel)),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@soffits/dsh-cron-jobs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Scheduled jobs for DeepSeek Harness: shell commands and agent prompts on cron, RRULE or one-time schedules, a gate that wakes an agent only when there is something to do, result delivery through any plugin that can send messages, tools to manage jobs from a conversation, and a Cron tasks page in the Web GUI.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
package/src/config.js
CHANGED
|
@@ -35,6 +35,7 @@ const Job = z.object({
|
|
|
35
35
|
at: z.string().description('Run once at this time: ISO 8601 with an offset, or a local date-time read in timeZone.'),
|
|
36
36
|
timeZone: z.string().description('IANA time zone for the cron expression or an at without offset, such as Europe/Berlin. The host zone when empty (an at without offset needs it).'),
|
|
37
37
|
on: z.array(z.string()).default([]).description('Event channels that start a run, such as mail.inbox or alerts.* (* matches any characters). Events arriving close together run the job once; the gate command gets them as JSON on stdin and the prompt gets them appended. Keep a slower schedule as a safety net.'),
|
|
38
|
+
coalesceSeconds: z.natural().description('Events for this job that arrive within this many seconds of the first one start a single run. 0 runs at once. The events.coalesceSeconds setting when unset.'),
|
|
38
39
|
command: z.string().role('textarea').description('Shell command, run with bash (or sh when bash is missing). Leave empty for an agent-only job, which sends agent.prompt at every run.'),
|
|
39
40
|
cwd: z.string().description('Working directory of the command. The host process directory when empty.'),
|
|
40
41
|
timeoutSeconds: z.natural().default(DEFAULT_TIMEOUT_SECONDS)
|
package/src/controller.js
CHANGED
|
@@ -166,6 +166,7 @@ export class CronJobs {
|
|
|
166
166
|
if (!(entry.job.on?.length > 0)) return
|
|
167
167
|
entry.batcher = new EventBatcher({
|
|
168
168
|
...this.eventSettings,
|
|
169
|
+
...(entry.job.coalesceSeconds !== undefined ? { coalesceMs: entry.job.coalesceSeconds * 1000 } : {}),
|
|
169
170
|
now: () => this.now().getTime(),
|
|
170
171
|
busy: () => entry.runner.running,
|
|
171
172
|
start: batch => this.runEvents(entry, batch),
|
|
@@ -624,6 +625,7 @@ export class CronJobs {
|
|
|
624
625
|
...(spec ? { schedule: spec } : {}),
|
|
625
626
|
...(on.length > 0 ? { on } : {}),
|
|
626
627
|
...(input.once === true ? { once: true } : {}),
|
|
628
|
+
...(input.coalesceSeconds !== undefined ? { coalesceSeconds: coalesceSeconds(input.coalesceSeconds) } : {}),
|
|
627
629
|
...(input.cwd ? { cwd: input.cwd } : {}),
|
|
628
630
|
...(input.preset ? { preset: input.preset } : {}),
|
|
629
631
|
target: input.target ?? { kind: 'new' },
|
|
@@ -678,6 +680,10 @@ export class CronJobs {
|
|
|
678
680
|
if (patch.once) next.once = true
|
|
679
681
|
else delete next.once
|
|
680
682
|
}
|
|
683
|
+
if (patch.coalesceSeconds !== undefined) {
|
|
684
|
+
if (patch.coalesceSeconds === null) delete next.coalesceSeconds
|
|
685
|
+
else next.coalesceSeconds = coalesceSeconds(patch.coalesceSeconds)
|
|
686
|
+
}
|
|
681
687
|
if (patch.schedule !== undefined) {
|
|
682
688
|
const schedule = changedSchedule(current.schedule, patch.schedule)
|
|
683
689
|
if (schedule === null) {
|
|
@@ -751,6 +757,8 @@ export class CronJobs {
|
|
|
751
757
|
schedule: spec ? { ...spec, text: describeSchedule(spec) } : null,
|
|
752
758
|
on: job.on?.length > 0 ? job.on : null,
|
|
753
759
|
once: job.once === true,
|
|
760
|
+
coalesceSeconds: job.coalesceSeconds ?? null,
|
|
761
|
+
coalesceEffectiveSeconds: job.on?.length > 0 ? (job.coalesceSeconds ?? this.eventSettings.coalesceMs / 1000) : null,
|
|
754
762
|
pendingEvents: entry.batcher?.size > 0 ? { count: entry.batcher.size, dueAt: new Date(entry.batcher.dueAt).toISOString() } : null,
|
|
755
763
|
cron: spec?.kind === 'cron' ? spec.expression : null,
|
|
756
764
|
timeZone: scheduleZone(spec) ?? null,
|
|
@@ -845,6 +853,7 @@ function fromStored(record) {
|
|
|
845
853
|
spec: record.schedule,
|
|
846
854
|
on: record.on ?? [],
|
|
847
855
|
...(record.once ? { once: true } : {}),
|
|
856
|
+
...(record.coalesceSeconds !== undefined ? { coalesceSeconds: record.coalesceSeconds } : {}),
|
|
848
857
|
}
|
|
849
858
|
}
|
|
850
859
|
|
|
@@ -882,6 +891,11 @@ function hasSchedule(input) {
|
|
|
882
891
|
return input !== undefined && ['cron', 'rrule', 'at'].some(key => typeof input[key] === 'string' && input[key].trim() !== '')
|
|
883
892
|
}
|
|
884
893
|
|
|
894
|
+
function coalesceSeconds(value) {
|
|
895
|
+
if (!Number.isInteger(value) || value < 0) throw new JobInputError('invalid_job', 'coalesceSeconds must be a whole number of seconds, 0 or more')
|
|
896
|
+
return value
|
|
897
|
+
}
|
|
898
|
+
|
|
885
899
|
function patterns(list) {
|
|
886
900
|
try {
|
|
887
901
|
return checkPatterns(list)
|
package/src/store.js
CHANGED
|
@@ -40,6 +40,8 @@ export const storedJobSchema = z.object({
|
|
|
40
40
|
on: z.array(z.string().min(1)).optional(),
|
|
41
41
|
// End the job after its first run that was not started by hand.
|
|
42
42
|
once: z.boolean().optional(),
|
|
43
|
+
// Seconds events gather before a run; the plugin's events.coalesceSeconds when omitted.
|
|
44
|
+
coalesceSeconds: z.number().int().min(0).optional(),
|
|
43
45
|
// Directory of the command and of new sessions.
|
|
44
46
|
cwd: z.string().optional(),
|
|
45
47
|
preset: z.string().optional(),
|
package/tools.js
CHANGED
|
@@ -52,6 +52,7 @@ export function toolSchemas(prefix) {
|
|
|
52
52
|
description: `Event channels that start a run, with * for any characters (mail.inbox, ci.*, dsh.started). Events come from \`dsh-cron-event <channel>\` (any script or hook), from watchers (${prefix}_watch), and dsh.started once after each DSH start. Events within about 30 s run the job once; the command gets them as JSON on stdin and the prompt gets them appended as untrusted data. A job with on may leave out the schedule; keep a slower one as a safety net when events can be missed.`,
|
|
53
53
|
},
|
|
54
54
|
once: { type: 'boolean', description: 'End the job after its first run that was not started by hand (an event or a scheduled run). With on: dsh.started, it waits for the next DSH start.' },
|
|
55
|
+
coalesceSeconds: { type: 'number', description: 'How long events for this job gather, counted from the first one, before it runs once with all of them (for example 900 for a quarter of an hour). 0 runs at once. Left out, the plugin\'s events.coalesceSeconds (30 by default) applies. Only matters with on.' },
|
|
55
56
|
}
|
|
56
57
|
const model = {
|
|
57
58
|
type: 'object',
|
|
@@ -64,6 +65,20 @@ export function toolSchemas(prefix) {
|
|
|
64
65
|
required: [],
|
|
65
66
|
additionalProperties: false,
|
|
66
67
|
}
|
|
68
|
+
const replacements = field => ({
|
|
69
|
+
type: 'array',
|
|
70
|
+
description: `Change the ${field} in place instead of resending it: literal {old, new} replacements applied in order. Each old must match exactly once, or set replace_all. Not with ${field}.`,
|
|
71
|
+
items: {
|
|
72
|
+
type: 'object',
|
|
73
|
+
properties: {
|
|
74
|
+
old: { type: 'string', description: 'Exact text to find.' },
|
|
75
|
+
new: { type: 'string', description: 'Replacement text; empty deletes the match.' },
|
|
76
|
+
replace_all: { type: 'boolean', description: 'Replace every match, not only a single one.' },
|
|
77
|
+
},
|
|
78
|
+
required: ['old', 'new'],
|
|
79
|
+
additionalProperties: false,
|
|
80
|
+
},
|
|
81
|
+
})
|
|
67
82
|
return {
|
|
68
83
|
create: object({
|
|
69
84
|
title: { type: 'string', description: 'Job name in the user\'s language, at most 200 characters: action plus object, without timing or status.' },
|
|
@@ -90,6 +105,8 @@ export function toolSchemas(prefix) {
|
|
|
90
105
|
title: { type: 'string', description: 'New job name.' },
|
|
91
106
|
prompt: { ...fields.prompt, description: 'New prompt; an empty string removes it.' },
|
|
92
107
|
command: { ...fields.command, description: 'New command; an empty string removes it.' },
|
|
108
|
+
prompt_replace: replacements('prompt'),
|
|
109
|
+
command_replace: replacements('command'),
|
|
93
110
|
answerCheck: { ...fields.answerCheck, description: 'New answer check command; an empty string removes it.' },
|
|
94
111
|
cron: { ...schedule.cron, description: `${schedule.cron.description} An empty cron, rrule or at removes the schedule of a job with on.` },
|
|
95
112
|
rrule: schedule.rrule,
|
|
@@ -102,6 +119,7 @@ export function toolSchemas(prefix) {
|
|
|
102
119
|
model: { ...model, description: `New model, as in ${prefix}_create. An empty object ({}) returns to the preset's or host default.` },
|
|
103
120
|
on: { ...fields.on, description: `New event channels, as in ${prefix}_create; an empty list removes them.` },
|
|
104
121
|
once: fields.once,
|
|
122
|
+
coalesceSeconds: { ...fields.coalesceSeconds, description: `New event gathering time in seconds, as in ${prefix}_create. A negative number (-1) removes the job's own setting, so the plugin's default applies again.` },
|
|
105
123
|
}, ['id', 'action']),
|
|
106
124
|
list: object({}, []),
|
|
107
125
|
view: object({ id: { type: 'string', description: 'Job id.' } }, ['id']),
|
|
@@ -149,6 +167,7 @@ export function createTools({ prefix = 'cron_job', getJobs, ctx }) {
|
|
|
149
167
|
schedule: { cron: args.cron, rrule: args.rrule, at: args.at, timeZone: args.timeZone },
|
|
150
168
|
...(args.on !== undefined ? { on: args.on } : {}),
|
|
151
169
|
...(args.once !== undefined ? { once: args.once } : {}),
|
|
170
|
+
...(args.coalesceSeconds !== undefined ? { coalesceSeconds: args.coalesceSeconds } : {}),
|
|
152
171
|
cwd: args.cwd || callerCwd(agent),
|
|
153
172
|
preset: callerPreset(agent),
|
|
154
173
|
...(toModel(args.model) ? { model: toModel(args.model) } : {}),
|
|
@@ -161,7 +180,7 @@ export function createTools({ prefix = 'cron_job', getJobs, ctx }) {
|
|
|
161
180
|
`Update, pause, resume or delete one job created with ${prefix}_create, by id. Jobs from the plugin config are read-only.`,
|
|
162
181
|
async (args, jobs, agent) => {
|
|
163
182
|
const { id, action } = args
|
|
164
|
-
const changes = ['title', 'prompt', 'command', 'answerCheck', 'cron', 'rrule', 'at', 'timeZone', 'target', 'sessionId', 'cwd', 'deliver', 'model', 'on', 'once'].filter(key => args[key] !== undefined)
|
|
183
|
+
const changes = ['title', 'prompt', 'command', 'prompt_replace', 'command_replace', 'answerCheck', 'cron', 'rrule', 'at', 'timeZone', 'target', 'sessionId', 'cwd', 'deliver', 'model', 'on', 'once', 'coalesceSeconds'].filter(key => args[key] !== undefined)
|
|
165
184
|
if (action !== 'update' && changes.length > 0) return failure('invalid_arguments', `${action} takes only id and action.`)
|
|
166
185
|
if (action === 'delete') return await jobs.remove(id)
|
|
167
186
|
if (action === 'pause' || action === 'resume') {
|
|
@@ -171,6 +190,16 @@ export function createTools({ prefix = 'cron_job', getJobs, ctx }) {
|
|
|
171
190
|
return modelJob(result.job)
|
|
172
191
|
}
|
|
173
192
|
if (changes.length === 0) return failure('invalid_arguments', 'update needs at least one field to change.')
|
|
193
|
+
for (const [field, list] of [['prompt', args.prompt_replace], ['command', args.command_replace]]) {
|
|
194
|
+
if (list === undefined) continue
|
|
195
|
+
if (list.length === 0) return failure('invalid_arguments', `${field}_replace needs at least one replacement.`)
|
|
196
|
+
if (args[field] !== undefined) return failure('invalid_arguments', `give either ${field} or ${field}_replace, not both.`)
|
|
197
|
+
const current = jobs.storedEntry(id).record[field]
|
|
198
|
+
if (current === undefined) return failure('invalid_arguments', `The job has no ${field} to change.`)
|
|
199
|
+
const replaced = applyReplacements(current, list, `${field}_replace`)
|
|
200
|
+
if (replaced.error) return failure('invalid_arguments', replaced.error)
|
|
201
|
+
args = { ...args, [field]: replaced.text }
|
|
202
|
+
}
|
|
174
203
|
const scheduleGiven = ['cron', 'rrule', 'at', 'timeZone'].some(key => args[key] !== undefined)
|
|
175
204
|
const targetGiven = args.target !== undefined || args.sessionId !== undefined
|
|
176
205
|
return modelJob(await jobs.update(id, {
|
|
@@ -181,6 +210,7 @@ export function createTools({ prefix = 'cron_job', getJobs, ctx }) {
|
|
|
181
210
|
cwd: args.cwd,
|
|
182
211
|
on: args.on,
|
|
183
212
|
once: args.once,
|
|
213
|
+
...(args.coalesceSeconds !== undefined ? { coalesceSeconds: args.coalesceSeconds < 0 ? null : args.coalesceSeconds } : {}),
|
|
184
214
|
...(args.model !== undefined ? { model: toModel(args.model) ?? null } : {}),
|
|
185
215
|
...(scheduleGiven ? { schedule: { cron: args.cron, rrule: args.rrule, at: args.at, timeZone: args.timeZone } } : {}),
|
|
186
216
|
...(targetGiven ? { target: await resolveTarget(ctx, agent, args.target ?? 'new', args.sessionId) } : {}),
|
|
@@ -249,6 +279,25 @@ function parseDeliver(ctx, value) {
|
|
|
249
279
|
return { via, to }
|
|
250
280
|
}
|
|
251
281
|
|
|
282
|
+
/**
|
|
283
|
+
* Apply literal {old, new, replace_all} replacements in order, each to the
|
|
284
|
+
* result of the one before. Without replace_all an `old` must match exactly
|
|
285
|
+
* once. All or nothing: returns `{ text }`, or `{ error }` naming the item.
|
|
286
|
+
*/
|
|
287
|
+
export function applyReplacements(source, list, label) {
|
|
288
|
+
let text = source
|
|
289
|
+
for (const [index, { old, new: replacement, replace_all: all }] of list.entries()) {
|
|
290
|
+
const where = `${label}[${index}] (old ${JSON.stringify(old.length > 50 ? `${old.slice(0, 50)}…` : old)})`
|
|
291
|
+
if (old === '') return { error: `${where}: old must not be empty. Nothing was changed.` }
|
|
292
|
+
const parts = text.split(old)
|
|
293
|
+
const count = parts.length - 1
|
|
294
|
+
if (count === 0) return { error: `${where}: no match${index > 0 ? ' in the text after the earlier replacements' : ''}. Nothing was changed.` }
|
|
295
|
+
if (count > 1 && all !== true) return { error: `${where}: matches ${count} times; add surrounding text to make it unique or set replace_all. Nothing was changed.` }
|
|
296
|
+
text = parts.join(replacement)
|
|
297
|
+
}
|
|
298
|
+
return { text }
|
|
299
|
+
}
|
|
300
|
+
|
|
252
301
|
/** The model argument for the controller: undefined or null when it names no model (clears it on edit). */
|
|
253
302
|
function toModel(value) {
|
|
254
303
|
if (value === undefined || value === null) return undefined
|
|
@@ -309,6 +358,7 @@ export function modelJob(job, { brief = false } = {}) {
|
|
|
309
358
|
...(job.nextRunAt ? { nextRunAt: job.nextRunAt, nextRunAtLocal: `${formatLocalTime(new Date(job.nextRunAt), zone)}${zone ? ` ${zone}` : ''}` } : { nextRunAt: null }),
|
|
310
359
|
...(job.on ? { on: job.on } : {}),
|
|
311
360
|
...(job.once ? { once: true } : {}),
|
|
361
|
+
...(job.coalesceEffectiveSeconds !== null && job.coalesceEffectiveSeconds !== undefined ? { coalesceSeconds: job.coalesceEffectiveSeconds, ...(job.coalesceSeconds === null ? { coalesceIsDefault: true } : {}) } : {}),
|
|
312
362
|
...(job.pendingEvents ? { pendingEvents: job.pendingEvents } : {}),
|
|
313
363
|
...(job.target ? { target: job.target.sessionId ? `${job.target.kind} ${job.target.sessionId}` : job.target.kind } : {}),
|
|
314
364
|
...(job.agent?.model ? { model: job.agent.model } : {}),
|
|
@@ -354,7 +404,13 @@ export function checkArgs(schema, args) {
|
|
|
354
404
|
if (value === undefined) continue
|
|
355
405
|
if (property.type === 'array') {
|
|
356
406
|
if (!Array.isArray(value)) return `${key} must be an array`
|
|
357
|
-
if (value.some(item => typeof item !== property.items.type)) return `${key} must hold only ${property.items.type}s`
|
|
407
|
+
if (value.some(item => typeof item !== property.items.type || (property.items.type === 'object' && (item === null || Array.isArray(item))))) return `${key} must hold only ${property.items.type}s`
|
|
408
|
+
if (property.items.type === 'object') {
|
|
409
|
+
for (const [index, item] of value.entries()) {
|
|
410
|
+
const inner = checkArgs(property.items, item)
|
|
411
|
+
if (inner) return `${key}[${index}]: ${inner}`
|
|
412
|
+
}
|
|
413
|
+
}
|
|
358
414
|
continue
|
|
359
415
|
}
|
|
360
416
|
if (property.type === 'object') {
|