@soffits/dsh-cron-jobs 0.9.0 → 0.11.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 CHANGED
@@ -92,7 +92,7 @@ Config jobs live in the config of the `cron-jobs` row. Add an override to your p
92
92
  |---|---|
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
- | `on` | Event channel patterns that start a run, such as `[mail.sakina, alerts.*]`. See [Events](#events). |
95
+ | `on` | Event channel patterns that start a run, such as `[mail.inbox, alerts.*]`. See [Events](#events). |
96
96
  | `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
97
  | `at` | Run once at this time: ISO 8601 with an offset, or a local date-time read in `timeZone`. |
98
98
  | `timeZone` | IANA time zone for the cron expression or an `at` without offset. The Host's zone when empty. |
@@ -181,6 +181,16 @@ Use it for checks that are cheap to script and costly to miss, such as the answe
181
181
 
182
182
  It works on DSH's `agent/turn-stopping` hook: a listener that steers a message there makes the agent loop run one more step in the same turn.
183
183
 
184
+ ### Who sent a prompt
185
+
186
+ Every prompt a job puts into a session has the source kind `schedule`, which the Web GUI shows as a scheduled run, and names the job as `principal`, the field DSH uses for the caller behind a user message:
187
+
188
+ ```js
189
+ { kind: 'cron-job', channel: 'cron', id, name, trigger, events }
190
+ ```
191
+
192
+ `id` is the job's id (its name for a config job), `name` its name, `trigger` what started the run (`schedule`, `manual`, `event`, `rerun`, or `answer-check` for an answer check's rewrite request), and `events` the channels of the events that started an event run. Scripts that read session logs can tell job prompts apart, and which job sent each, without parsing the text.
193
+
184
194
  ### Delivery channels
185
195
 
186
196
  A delivery target is `{ via, to }`: `via` names a DSH service, `to` is an address that service understands (a chat topic, a mailbox, a webhook name; it can be empty). When a result is ready, the plugin looks the service up by name with `ctx.get(via)` and calls:
@@ -192,6 +202,7 @@ await service.send({
192
202
  files, // string[]: absolute file paths
193
203
  from: {
194
204
  job, // string: the job's name
205
+ jobId, // string: the job's id (its name for a config job)
195
206
  sessionId, // string, agent and gated jobs only: the session that wrote the answer
196
207
  },
197
208
  })
@@ -290,7 +301,7 @@ The `cron-jobs-tools` row registers five tools. Their names start with `cron_job
290
301
  | Tool | What it does |
291
302
  |---|---|
292
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. |
293
- | `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_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. `prompt_replace` and `command_replace` change the text in place; see below. |
294
305
  | `cron_job_list` | Every job, from the config and from tools, with its id, state, schedule, next run, target and last run. |
295
306
  | `cron_job_view` | One job's full definition and its five latest runs. |
296
307
  | `cron_job_watch` | `create`, `delete` or `list` [watchers](#watchers). |
@@ -305,6 +316,8 @@ Where the prompt goes (`target`):
305
316
 
306
317
  `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.
307
318
 
319
+ `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`.
320
+
308
321
  `answerCheck` sets the job's [answer check](#answer-checks) command; on `cron_job_edit`, an empty string removes it.
309
322
 
310
323
  `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.
@@ -13,7 +13,7 @@ import { enqueueEvent, waitForEventResult } from '../src/spool.js'
13
13
  const usage = `Usage: dsh-cron-event <channel> [--data <json> | --data - | --text <text>]
14
14
  [--id <dedupe key>] [--source <label>] [--no-wait] [--timeout <seconds>]
15
15
 
16
- Emits one event on <channel> (dot-separated names, such as mail.sakina or
16
+ Emits one event on <channel> (dot-separated names, such as mail.inbox or
17
17
  ci.run.123). Jobs whose on patterns match it run once the events around it are
18
18
  gathered (about 30 s). The event is a hint: jobs check the source themselves.
19
19
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-cron-jobs",
3
- "version": "0.9.0",
3
+ "version": "0.11.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",
@@ -67,7 +67,7 @@ export function checkable(text) {
67
67
  * @param {() => Date} [deps.now]
68
68
  */
69
69
  export function createAnswerChecks({ run, logger, record = async () => {}, now = () => new Date() }) {
70
- /** @type {Map<string, { job: string, command: string, cwd?: string, at: number, steered: boolean, verdict?: string }>} */
70
+ /** @type {Map<string, { job: string, jobId?: string, command: string, cwd?: string, at: number, steered: boolean, verdict?: string }>} */
71
71
  const pending = new Map()
72
72
 
73
73
  async function check(entry, text, signal) {
@@ -80,12 +80,12 @@ export function createAnswerChecks({ run, logger, record = async () => {}, now =
80
80
  /**
81
81
  * Check the answer to this prompt before its turn closes.
82
82
  * @param {string} messageId
83
- * @param {{ job: string, command: string, cwd?: string }} options
83
+ * @param {{ job: string, jobId?: string, command: string, cwd?: string }} options
84
84
  */
85
- expect(messageId, { job, command, cwd }) {
85
+ expect(messageId, { job, jobId, command, cwd }) {
86
86
  const at = now().getTime()
87
87
  for (const [id, entry] of pending) if (at - entry.at > ANSWER_CHECK_TTL_MS) pending.delete(id)
88
- pending.set(messageId, { job, command, ...(cwd ? { cwd } : {}), at, steered: false })
88
+ pending.set(messageId, { job, ...(jobId ? { jobId } : {}), command, ...(cwd ? { cwd } : {}), at, steered: false })
89
89
  },
90
90
 
91
91
  /** Stop watching a prompt; returns what its check did ('steered', 'passed', 'error' or undefined). */
@@ -130,7 +130,7 @@ export function createAnswerChecks({ run, logger, record = async () => {}, now =
130
130
  entry.verdict = 'steered'
131
131
  logger.info('[%s] answer check asked for a rewrite', entry.job)
132
132
  await record({ ...line, status: 'steered', request: outcome.request })
133
- agent.steer(userMessage(outcome.request, randomUUID()))
133
+ agent.steer(userMessage(outcome.request, randomUUID(), { kind: 'cron-job', channel: 'cron', id: entry.jobId ?? entry.job, name: entry.job, trigger: 'answer-check' }))
134
134
  }
135
135
  return
136
136
  }
package/src/config.js CHANGED
@@ -34,7 +34,7 @@ const Job = z.object({
34
34
  rrule: z.string().role('textarea').description('RFC 5545 schedule: a DTSTART line and an RRULE line, such as "DTSTART;TZID=Europe/Berlin:20260901T080000" and "RRULE:FREQ=WEEKLY;BYDAY=MO". The zone comes from DTSTART.'),
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
- on: z.array(z.string()).default([]).description('Event channels that start a run, such as mail.sakina 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.'),
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
38
  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
39
  cwd: z.string().description('Working directory of the command. The host process directory when empty.'),
40
40
  timeoutSeconds: z.natural().default(DEFAULT_TIMEOUT_SECONDS)
@@ -46,7 +46,7 @@ const Job = z.object({
46
46
 
47
47
  const Watcher = z.object({
48
48
  id: z.string().required().description('Watcher id (letters, digits, _ . -), shown in logs and alerts.'),
49
- channel: z.string().required().description('Channel each output line is emitted on, such as mail.sakina.'),
49
+ channel: z.string().required().description('Channel each output line is emitted on, such as mail.inbox.'),
50
50
  command: z.string().role('textarea').required().description('Long-running shell command, run with bash. Each stdout line is an event: a JSON object line is its data, any other line its text; {"wakeAgent": false} lines are ignored. It is restarted with backoff when it exits.'),
51
51
  cwd: z.string().description('Working directory. The host process directory when empty.'),
52
52
  enabled: z.boolean().default(true).description('Run this watcher.'),
package/src/events.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * job reads the truth from its source, so a lost or forged event costs at
5
5
  * most one missed or wasted run (the job's schedule is the safety net).
6
6
  *
7
- * - Channels are dot-separated names such as `mail.sakina` or `dsh.started`.
7
+ * - Channels are dot-separated names such as `mail.inbox` or `dsh.started`.
8
8
  * - A job's `on` lists channel patterns; `*` matches one or more characters
9
9
  * of any kind, dots included (`mail.*` matches `mail.icloud.inbox`).
10
10
  * - An event may carry a dedupe key: a second event with the same channel and
package/src/job.js CHANGED
@@ -284,7 +284,7 @@ export class JobRunner {
284
284
  */
285
285
  async deliverMessage(target, message, { sessionId, waitMs, onWait }) {
286
286
  const { job, logger } = this
287
- const sent = await this.send(target, message, { job: job.name, ...(sessionId ? { sessionId } : {}) }, {
287
+ const sent = await this.send(target, message, { job: job.name, jobId: jobKey(job), ...(sessionId ? { sessionId } : {}) }, {
288
288
  ...(waitMs !== undefined ? { waitMs } : {}), ...(onWait ? { onWait } : {}),
289
289
  })
290
290
  const where = describeTarget(target)
@@ -539,12 +539,29 @@ export class JobRunner {
539
539
  return sent.status === 'woke' ? { ...sent, messageId } : sent
540
540
  }
541
541
 
542
+ /**
543
+ * Who sends this run's prompt, recorded as `source.principal` on it: the
544
+ * job, what started the run, and the event channels of an event run.
545
+ * @returns {{ kind: 'cron-job', channel: 'cron', id: string, name: string, trigger: string, events?: string[] }}
546
+ */
547
+ promptPrincipal() {
548
+ const { job, current } = this
549
+ return {
550
+ kind: 'cron-job',
551
+ channel: 'cron',
552
+ id: jobKey(job),
553
+ name: job.name,
554
+ trigger: current?.rerunOf ? 'rerun' : current?.trigger ?? 'schedule',
555
+ ...(current?.events?.channels?.length ? { events: [...current.events.channels] } : {}),
556
+ }
557
+ }
558
+
542
559
  /** Have the answer to this prompt checked before its turn closes, when the job names a check. */
543
560
  expectCheck(messageId) {
544
561
  const command = this.job.agent?.answerCheck
545
562
  if (!command || this.checks === undefined) return
546
563
  const cwd = agentSettings(this.job, this.defaults).cwd
547
- this.checks.expect(messageId, { job: this.job.name, command, ...(cwd ? { cwd } : {}) })
564
+ this.checks.expect(messageId, { job: this.job.name, jobId: jobKey(this.job), command, ...(cwd ? { cwd } : {}) })
548
565
  }
549
566
 
550
567
  /** Send the prompt to the target session, a reused one, or a new one. */
@@ -564,7 +581,7 @@ export class JobRunner {
564
581
  if (previous !== undefined) {
565
582
  try {
566
583
  const sent = await this.withSessionLock(previous.sessionId, async () => {
567
- const delivered = await this.reuse({ sessionId: previous.sessionId, text, messageId, mayUnarchive: settings.autoArchive })
584
+ const delivered = await this.reuse({ sessionId: previous.sessionId, text, messageId, principal: this.promptPrincipal(), mayUnarchive: settings.autoArchive })
568
585
  // Inside the lock, so an earlier run's archive wait sees it was superseded.
569
586
  this.latestRun.set(previous.sessionId, null)
570
587
  return delivered
@@ -587,6 +604,7 @@ export class JobRunner {
587
604
  const opened = await this.wake({
588
605
  text,
589
606
  messageId,
607
+ principal: this.promptPrincipal(),
590
608
  title: sessionTitle(job.name, localTime),
591
609
  ...(job.agent.preset ? { agentPreset: job.agent.preset } : {}),
592
610
  ...(agentModel(job) ? { model: agentModel(job) } : {}),
@@ -631,7 +649,7 @@ export class JobRunner {
631
649
  if (this.reuse === undefined) return { status: 'wake-failed', error: 'this host cannot deliver to existing sessions' }
632
650
  try {
633
651
  const sent = await this.withSessionLock(sessionId, async () => {
634
- const delivered = await this.reuse({ sessionId, text, messageId, mayUnarchive, ignoreHold })
652
+ const delivered = await this.reuse({ sessionId, text, messageId, principal: this.promptPrincipal(), mayUnarchive, ignoreHold })
635
653
  this.latestRun.set(sessionId, null)
636
654
  return delivered
637
655
  })
package/src/session.js CHANGED
@@ -24,6 +24,7 @@ import { finalAnswer } from './deliver.js'
24
24
  * @param {object} request
25
25
  * @param {string} request.text - Message text.
26
26
  * @param {string} [request.messageId] - Id of the message, so its answer can be found later.
27
+ * @param {object} [request.principal] - Who sends the message, recorded on its source.
27
28
  * @param {string} request.title - Session title.
28
29
  * @param {string} [request.agentPreset] - Agent preset id; the host default when omitted.
29
30
  * @param {string} [request.cwd] - Session directory; the host default when omitted.
@@ -31,7 +32,7 @@ import { finalAnswer } from './deliver.js'
31
32
  * @param {{ warn: Function }} logger
32
33
  * @returns {Promise<string>} The new session id.
33
34
  */
34
- export async function openAgentSession(ctx, { text, messageId, title, agentPreset, cwd, model }, logger) {
35
+ export async function openAgentSession(ctx, { text, messageId, principal, title, agentPreset, cwd, model }, logger) {
35
36
  const controller = ctx.get('sessionController')
36
37
  const sessions = ctx.get('sessions')
37
38
  if (controller === undefined || sessions === undefined) {
@@ -51,7 +52,7 @@ export async function openAgentSession(ctx, { text, messageId, title, agentPrese
51
52
  await joinWorkspace(ctx, sessionId, cwd, logger)
52
53
  nameSession(ctx, agent, title, logger)
53
54
 
54
- agent.followup(userMessage(text, messageId))
55
+ agent.followup(userMessage(text, messageId, principal))
55
56
  if (!await sessions.flush(agent.session)) {
56
57
  throw new Error('session persistence did not acknowledge the message')
57
58
  }
@@ -83,12 +84,13 @@ export async function openAgentSession(ctx, { text, messageId, title, agentPrese
83
84
  * @param {string} request.sessionId
84
85
  * @param {string} request.text
85
86
  * @param {string} [request.messageId] - Id of the message, so its answer can be found later.
87
+ * @param {object} [request.principal] - Who sends the message, recorded on its source.
86
88
  * @param {boolean} [request.mayUnarchive]
87
89
  * @param {boolean} [request.ignoreHold] - Deliver even to a pinned session or one a person uses.
88
90
  * @returns {Promise<{ sessionId: string, queued: boolean, unarchived: boolean }>}
89
91
  * `queued`: the session was busy and the message waits for its next turn.
90
92
  */
91
- export async function deliverToSession(ctx, { sessionId, text, messageId, mayUnarchive = false, ignoreHold = false }) {
93
+ export async function deliverToSession(ctx, { sessionId, text, messageId, principal, mayUnarchive = false, ignoreHold = false }) {
92
94
  const controller = ctx.get('sessionController')
93
95
  const sessions = ctx.get('sessions')
94
96
  if (controller === undefined || sessions === undefined) {
@@ -107,7 +109,7 @@ export async function deliverToSession(ctx, { sessionId, text, messageId, mayUna
107
109
  await registry.unarchiveSession(sessionId)
108
110
  }
109
111
  const queued = agent.status !== undefined && agent.status !== 'idle'
110
- agent.followup(userMessage(text, messageId))
112
+ agent.followup(userMessage(text, messageId, principal))
111
113
  if (!await sessions.flush(agent.session)) {
112
114
  throw new Error('session persistence did not acknowledge the message')
113
115
  }
@@ -283,14 +285,19 @@ function describe(error) {
283
285
 
284
286
  /**
285
287
  * A user-role message from a scheduled source. `kind: 'schedule'` makes the
286
- * Web GUI show it as a scheduled run.
288
+ * Web GUI show it as a scheduled run. `principal`, DSH's field for the caller
289
+ * behind a user message, names the job that sent it (see
290
+ * `JobRunner.promptPrincipal`), so session readers need not parse the text.
291
+ * @param {string} text
292
+ * @param {string} [id]
293
+ * @param {object} [principal]
287
294
  */
288
- export function userMessage(text, id = randomUUID()) {
295
+ export function userMessage(text, id = randomUUID(), principal) {
289
296
  return deepFreeze({
290
297
  id,
291
298
  role: 'user',
292
299
  content: [{ type: 'text', text }],
293
- source: { kind: 'schedule' },
300
+ source: { kind: 'schedule', ...(principal ? { principal: { ...principal } } : {}) },
294
301
  })
295
302
  }
296
303
 
package/tools.js CHANGED
@@ -49,7 +49,7 @@ export function toolSchemas(prefix) {
49
49
  on: {
50
50
  type: 'array',
51
51
  items: { type: 'string' },
52
- description: `Event channels that start a run, with * for any characters (mail.sakina, 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.`,
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
55
  }
@@ -64,6 +64,20 @@ export function toolSchemas(prefix) {
64
64
  required: [],
65
65
  additionalProperties: false,
66
66
  }
67
+ const replacements = field => ({
68
+ type: 'array',
69
+ 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}.`,
70
+ items: {
71
+ type: 'object',
72
+ properties: {
73
+ old: { type: 'string', description: 'Exact text to find.' },
74
+ new: { type: 'string', description: 'Replacement text; empty deletes the match.' },
75
+ replace_all: { type: 'boolean', description: 'Replace every match, not only a single one.' },
76
+ },
77
+ required: ['old', 'new'],
78
+ additionalProperties: false,
79
+ },
80
+ })
67
81
  return {
68
82
  create: object({
69
83
  title: { type: 'string', description: 'Job name in the user\'s language, at most 200 characters: action plus object, without timing or status.' },
@@ -75,7 +89,7 @@ export function toolSchemas(prefix) {
75
89
  watch: object({
76
90
  action: { type: 'string', enum: ['create', 'delete', 'list'], description: 'create starts a new watcher; delete stops and removes one; list shows every watcher with its state.' },
77
91
  id: { type: 'string', description: 'Watcher id: letters, digits, _ . - (create, delete).' },
78
- channel: { type: 'string', description: 'Channel its output lines are emitted on, such as mail.sakina (create).' },
92
+ channel: { type: 'string', description: 'Channel its output lines are emitted on, such as mail.inbox (create).' },
79
93
  command: { type: 'string', description: 'Shell command run with bash that keeps running and prints one line per change (create). A JSON object line is the event\'s data (its "id" field dedupes), any other line its text; {"wakeAgent": false} lines are ignored. It is restarted with backoff when it exits; down for 15 minutes sends one alert. It gets DSH_CRON_STATE_DIR, a directory for its cursor, so it can catch up after a restart.' },
80
94
  cwd: { type: 'string', description: 'Working directory; defaults to this session\'s (create).' },
81
95
  once: { type: 'boolean', description: 'Run the command one time and remove the watcher when it exits, for a one-off wait such as `gh run watch 123 --exit-status >/dev/null; echo "{\\"exit\\": $?}"` (create).' },
@@ -90,6 +104,8 @@ export function toolSchemas(prefix) {
90
104
  title: { type: 'string', description: 'New job name.' },
91
105
  prompt: { ...fields.prompt, description: 'New prompt; an empty string removes it.' },
92
106
  command: { ...fields.command, description: 'New command; an empty string removes it.' },
107
+ prompt_replace: replacements('prompt'),
108
+ command_replace: replacements('command'),
93
109
  answerCheck: { ...fields.answerCheck, description: 'New answer check command; an empty string removes it.' },
94
110
  cron: { ...schedule.cron, description: `${schedule.cron.description} An empty cron, rrule or at removes the schedule of a job with on.` },
95
111
  rrule: schedule.rrule,
@@ -161,7 +177,7 @@ export function createTools({ prefix = 'cron_job', getJobs, ctx }) {
161
177
  `Update, pause, resume or delete one job created with ${prefix}_create, by id. Jobs from the plugin config are read-only.`,
162
178
  async (args, jobs, agent) => {
163
179
  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)
180
+ const changes = ['title', 'prompt', 'command', 'prompt_replace', 'command_replace', 'answerCheck', 'cron', 'rrule', 'at', 'timeZone', 'target', 'sessionId', 'cwd', 'deliver', 'model', 'on', 'once'].filter(key => args[key] !== undefined)
165
181
  if (action !== 'update' && changes.length > 0) return failure('invalid_arguments', `${action} takes only id and action.`)
166
182
  if (action === 'delete') return await jobs.remove(id)
167
183
  if (action === 'pause' || action === 'resume') {
@@ -171,6 +187,16 @@ export function createTools({ prefix = 'cron_job', getJobs, ctx }) {
171
187
  return modelJob(result.job)
172
188
  }
173
189
  if (changes.length === 0) return failure('invalid_arguments', 'update needs at least one field to change.')
190
+ for (const [field, list] of [['prompt', args.prompt_replace], ['command', args.command_replace]]) {
191
+ if (list === undefined) continue
192
+ if (list.length === 0) return failure('invalid_arguments', `${field}_replace needs at least one replacement.`)
193
+ if (args[field] !== undefined) return failure('invalid_arguments', `give either ${field} or ${field}_replace, not both.`)
194
+ const current = jobs.storedEntry(id).record[field]
195
+ if (current === undefined) return failure('invalid_arguments', `The job has no ${field} to change.`)
196
+ const replaced = applyReplacements(current, list, `${field}_replace`)
197
+ if (replaced.error) return failure('invalid_arguments', replaced.error)
198
+ args = { ...args, [field]: replaced.text }
199
+ }
174
200
  const scheduleGiven = ['cron', 'rrule', 'at', 'timeZone'].some(key => args[key] !== undefined)
175
201
  const targetGiven = args.target !== undefined || args.sessionId !== undefined
176
202
  return modelJob(await jobs.update(id, {
@@ -249,6 +275,25 @@ function parseDeliver(ctx, value) {
249
275
  return { via, to }
250
276
  }
251
277
 
278
+ /**
279
+ * Apply literal {old, new, replace_all} replacements in order, each to the
280
+ * result of the one before. Without replace_all an `old` must match exactly
281
+ * once. All or nothing: returns `{ text }`, or `{ error }` naming the item.
282
+ */
283
+ export function applyReplacements(source, list, label) {
284
+ let text = source
285
+ for (const [index, { old, new: replacement, replace_all: all }] of list.entries()) {
286
+ const where = `${label}[${index}] (old ${JSON.stringify(old.length > 50 ? `${old.slice(0, 50)}…` : old)})`
287
+ if (old === '') return { error: `${where}: old must not be empty. Nothing was changed.` }
288
+ const parts = text.split(old)
289
+ const count = parts.length - 1
290
+ if (count === 0) return { error: `${where}: no match${index > 0 ? ' in the text after the earlier replacements' : ''}. Nothing was changed.` }
291
+ 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.` }
292
+ text = parts.join(replacement)
293
+ }
294
+ return { text }
295
+ }
296
+
252
297
  /** The model argument for the controller: undefined or null when it names no model (clears it on edit). */
253
298
  function toModel(value) {
254
299
  if (value === undefined || value === null) return undefined
@@ -354,7 +399,13 @@ export function checkArgs(schema, args) {
354
399
  if (value === undefined) continue
355
400
  if (property.type === 'array') {
356
401
  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`
402
+ 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`
403
+ if (property.items.type === 'object') {
404
+ for (const [index, item] of value.entries()) {
405
+ const inner = checkArgs(property.items, item)
406
+ if (inner) return `${key}[${index}]: ${inner}`
407
+ }
408
+ }
358
409
  continue
359
410
  }
360
411
  if (property.type === 'object') {