@soffits/dsh-cron-jobs 0.6.1 → 0.7.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
@@ -108,6 +108,7 @@ Config jobs live in the config of the `cron-jobs` row. Add an override to your p
108
108
  | `agent.reuseWithinHours` | Send the prompt into the job's previous woken session when that session was opened less than this many hours ago (see below). `0` always opens a new session. The row's `reuseWithinHours` when unset. |
109
109
  | `agent.model.provider`, `agent.model.model` | Model of the new session, with the same provider and model ids the model picker uses. Both must be set; otherwise the preset's or the Host's default model applies. |
110
110
  | `agent.model.reasoningEffort` | Reasoning effort id for that model. The model's default when empty. |
111
+ | `agent.answerCheck` | Command that checks the agent's final answer before its turn closes (see [Answer checks](#answer-checks)). No check when empty. |
111
112
 
112
113
  Next to `jobs`, the row also takes:
113
114
 
@@ -162,6 +163,14 @@ Where results go is decided per job: its own `deliver` (or `false`), otherwise n
162
163
 
163
164
  Each run's delivery shows on the Cron tasks page and in the run log: waiting for the answer, sent, nothing to send, or not sent with the reason. The answer of a turn still running when DSH stops is picked up and delivered after the next start.
164
165
 
166
+ ### Answer checks
167
+
168
+ A job can name a command, `agent.answerCheck` (or `answerCheck` in the tools), that looks at the agent's final answer while the turn can still change it. When the turn that the job's prompt started is about to close, the command runs with the answer on stdin, in the session's working directory, with a 60-second limit. Empty stdout passes the answer. Anything it prints goes back into the same turn as a message asking for a rewrite, and the agent's next answer is the one delivered. Each run is steered at most once, so a check that never passes cannot keep a turn going. Empty answers, `[SILENT]` and answers with only `MEDIA:` lines are not checked. A command that fails or times out lets the answer through.
169
+
170
+ Use it for checks that are cheap to script and costly to miss, such as the answer's language or a format the channel needs. The run log gets an `answer-check` line per check (`passed`, `steered` or `error`) and, after a rewrite, an `answer-recheck` line saying whether the delivered answer passed (`fixed` or `still-flagged`).
171
+
172
+ 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.
173
+
165
174
  ### Delivery channels
166
175
 
167
176
  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:
@@ -223,6 +232,8 @@ Where the prompt goes (`target`):
223
232
 
224
233
  `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.
225
234
 
235
+ `answerCheck` sets the job's [answer check](#answer-checks) command; on `cron_job_edit`, an empty string removes it.
236
+
226
237
  `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.
227
238
 
228
239
  The prompt arrives as a scheduled message from the user, with the job's title and id, so the agent can look the job up or delete it when it is done. A message for an existing session is queued behind a turn that is still running. It is delivered even if the session is pinned or a person is using it, since that is what the job was created for; an archived target session is unarchived first. Target sessions are never auto-archived.
package/index.js CHANGED
@@ -14,6 +14,7 @@ import { runCommand } from './src/command.js'
14
14
  import { archiveWhenIdle, deliverToSession, openAgentSession, waitForAnswer } from './src/session.js'
15
15
  import { sendMessage } from './src/deliver.js'
16
16
  import { CronJobs } from './src/controller.js'
17
+ import { createAnswerChecks } from './src/answer-check.js'
17
18
  import { createRunLog } from './src/runlog.js'
18
19
  import { openHistory } from './src/history.js'
19
20
  import { createRoutes, createRpcHandler } from './src/rpc.js'
@@ -39,11 +40,16 @@ export function apply(ctx, config) {
39
40
  const controller = new AbortController()
40
41
  let jobs
41
42
  let history
43
+ let checks
44
+ // A job's answerCheck runs as the turn its prompt started is about to close.
45
+ const stopTurnHook = ctx.on?.('agent/turn-stopping', payload => checks?.onTurnStopping(payload))
42
46
  const ready = (async () => {
43
47
  history = await openHistory(ctx.storageDomain, {
44
48
  limit: config.historyRecords, logger, signal: controller.signal,
45
49
  })
46
50
  if (controller.signal.aborted) return
51
+ const record = createRunLog(config.runLog || undefined, logger)
52
+ checks = createAnswerChecks({ run: runCommand, logger, record })
47
53
  jobs = new CronJobs({
48
54
  jobs: config.jobs ?? [],
49
55
  logger,
@@ -55,6 +61,7 @@ export function apply(ctx, config) {
55
61
  // this plugin, reload, or be missing (the run records the failure).
56
62
  send: (target, message, from) => sendMessage({ lookup: name => ctx.get(name), target, message, from, signal: controller.signal }),
57
63
  answer: (sessionId, messageId, options) => waitForAnswer(ctx, sessionId, messageId, options),
64
+ checks,
58
65
  defaults: {
59
66
  agentCwd: config.defaultAgentCwd || undefined,
60
67
  autoArchive: config.autoArchive ?? true,
@@ -62,13 +69,14 @@ export function apply(ctx, config) {
62
69
  deliver: config.deliver,
63
70
  },
64
71
  signal: controller.signal,
65
- record: createRunLog(config.runLog || undefined, logger),
72
+ record,
66
73
  history,
67
74
  }).start()
68
75
  current = jobs
69
76
  })().catch(error => logger.error('cron jobs not started: %s', error instanceof Error ? error.message : String(error)))
70
77
  return async () => {
71
78
  current = undefined
79
+ stopTurnHook?.()
72
80
  // Stop the timers first so no new run starts with an aborted signal.
73
81
  const stopping = jobs?.stop()
74
82
  controller.abort()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-cron-jobs",
3
- "version": "0.6.1",
3
+ "version": "0.7.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",
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Answer checks: a job may name a command that reads its agent's final answer
3
+ * on stdin before the turn closes. Empty stdout passes the answer; anything
4
+ * else is steered back into the same turn as a rewrite request, so the agent
5
+ * writes the answer again and the job delivers that one. Each prompt is
6
+ * steered at most once, so a check that never passes cannot loop a turn.
7
+ *
8
+ * The hook is DSH's `agent/turn-stopping` (serial): when a turn is about to
9
+ * close with an empty next-step inbox, a listener that calls `agent.steer()`
10
+ * makes the loop run one more step in the same turn.
11
+ */
12
+ import { randomUUID } from 'node:crypto'
13
+ import { messageFromText } from './deliver.js'
14
+ import { userMessage } from './session.js'
15
+
16
+ /** Limit for one run of a check command. */
17
+ export const ANSWER_CHECK_TIMEOUT_MS = 60_000
18
+
19
+ /**
20
+ * How long a prompt stays watched. A run whose answer is not delivered (no
21
+ * delivery target) is never forgotten by its delivery, so old entries are
22
+ * dropped when new ones come.
23
+ */
24
+ export const ANSWER_CHECK_TTL_MS = 12 * 60 * 60 * 1000
25
+
26
+ /**
27
+ * The answer a turn has so far: the last text block of the last assistant
28
+ * message after the prompt with `messageId`, when that prompt is in the turn
29
+ * still open at the end of the log. Undefined when the prompt is not there or
30
+ * a turn has ended since.
31
+ * @param {Array<{ type: string, data?: any }>} log
32
+ * @param {string} messageId
33
+ * @returns {string | undefined}
34
+ */
35
+ export function openTurnAnswer(log, messageId) {
36
+ let text
37
+ for (let i = log.length - 1; i >= 0; i--) {
38
+ const event = log[i]
39
+ if (event.type === 'turn/end') return undefined
40
+ if (event.type === 'user/message' && event.data?.id === messageId) return text ?? ''
41
+ if (text === undefined && event.type === 'assistant/message') {
42
+ const parts = event.data?.message?.content ?? []
43
+ const texts = parts.filter(part => part?.type === 'text' && typeof part.text === 'string')
44
+ .map(part => part.text.trim()).filter(Boolean)
45
+ if (texts.length > 0) text = texts.at(-1)
46
+ }
47
+ }
48
+ return undefined
49
+ }
50
+
51
+ /**
52
+ * Whether an answer is worth checking: not empty, not [SILENT], and not only
53
+ * MEDIA lines.
54
+ * @param {string} text
55
+ */
56
+ export function checkable(text) {
57
+ const message = messageFromText(text)
58
+ return message !== undefined && message.text.trim() !== ''
59
+ }
60
+
61
+ /**
62
+ * Pending checks, keyed by the prompt's message id.
63
+ * @param {object} deps
64
+ * @param {(options: object) => Promise<import('./command.js').CommandResult>} deps.run - Runs a command (command.js runCommand).
65
+ * @param {{ info: Function, warn: Function }} deps.logger
66
+ * @param {(entry: object) => Promise<void>} [deps.record] - Appends a run-log line.
67
+ * @param {() => Date} [deps.now]
68
+ */
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 }>} */
71
+ const pending = new Map()
72
+
73
+ async function check(entry, text, signal) {
74
+ const result = await run({ command: entry.command, cwd: entry.cwd, input: text, timeoutMs: ANSWER_CHECK_TIMEOUT_MS, signal })
75
+ if (!result.ok) return { error: result.error ?? (result.timedOut ? 'timed out' : `exit code ${result.exitCode}`) }
76
+ return { request: result.stdout.trim() }
77
+ }
78
+
79
+ return {
80
+ /**
81
+ * Check the answer to this prompt before its turn closes.
82
+ * @param {string} messageId
83
+ * @param {{ job: string, command: string, cwd?: string }} options
84
+ */
85
+ expect(messageId, { job, command, cwd }) {
86
+ const at = now().getTime()
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 })
89
+ },
90
+
91
+ /** Stop watching a prompt; returns what its check did ('steered', 'passed', 'error' or undefined). */
92
+ forget(messageId) {
93
+ const entry = pending.get(messageId)
94
+ pending.delete(messageId)
95
+ return entry?.verdict
96
+ },
97
+
98
+ /** Number of prompts watched, for tests. */
99
+ get size() {
100
+ return pending.size
101
+ },
102
+
103
+ /**
104
+ * The `agent/turn-stopping` listener. Finds a watched prompt in the
105
+ * closing turn, runs its check on the answer and steers a rewrite
106
+ * request when the check prints one.
107
+ * @param {{ agent: { session?: { id?: string, log?: any[] }, steer: (message: object) => void }, signal?: AbortSignal }} payload
108
+ */
109
+ async onTurnStopping({ agent, signal }) {
110
+ if (pending.size === 0) return
111
+ const log = agent?.session?.log ?? []
112
+ for (const [messageId, entry] of pending) {
113
+ if (entry.steered) continue
114
+ const text = openTurnAnswer(log, messageId)
115
+ if (text === undefined) continue
116
+ if (!checkable(text)) return
117
+ const outcome = await check(entry, text, signal).catch(error => ({ error: error instanceof Error ? error.message : String(error) }))
118
+ if (signal?.aborted) return
119
+ const sessionId = agent.session?.id
120
+ const line = { time: now().toISOString(), job: entry.job, event: 'answer-check', ...(sessionId ? { sessionId } : {}) }
121
+ if ('error' in outcome) {
122
+ entry.verdict = 'error'
123
+ logger.warn('[%s] answer check failed: %s', entry.job, outcome.error)
124
+ await record({ ...line, status: 'error', error: outcome.error })
125
+ } else if (outcome.request === '') {
126
+ entry.verdict = 'passed'
127
+ await record({ ...line, status: 'passed' })
128
+ } else {
129
+ entry.steered = true
130
+ entry.verdict = 'steered'
131
+ logger.info('[%s] answer check asked for a rewrite', entry.job)
132
+ await record({ ...line, status: 'steered', request: outcome.request })
133
+ agent.steer(userMessage(outcome.request, randomUUID()))
134
+ }
135
+ return
136
+ }
137
+ },
138
+
139
+ /**
140
+ * Run a prompt's check once more on its delivered answer, only to log
141
+ * whether a steered rewrite fixed it. Never steers.
142
+ * @param {string} messageId
143
+ * @param {string} text
144
+ * @param {{ sessionId?: string, signal?: AbortSignal }} [options]
145
+ */
146
+ async recheck(messageId, text, { sessionId, signal } = {}) {
147
+ const entry = pending.get(messageId)
148
+ if (entry?.verdict !== 'steered' || !checkable(text)) return
149
+ const outcome = await check(entry, text, signal).catch(error => ({ error: error instanceof Error ? error.message : String(error) }))
150
+ if (signal?.aborted) return
151
+ const status = 'error' in outcome ? 'error' : outcome.request === '' ? 'fixed' : 'still-flagged'
152
+ if (status === 'still-flagged') logger.warn('[%s] the rewritten answer still fails its check', entry.job)
153
+ await record({
154
+ time: now().toISOString(), job: entry.job, event: 'answer-recheck', ...(sessionId ? { sessionId } : {}), status,
155
+ ...('error' in outcome ? { error: outcome.error } : {}),
156
+ })
157
+ },
158
+ }
159
+ }
package/src/command.js CHANGED
@@ -53,6 +53,7 @@ class TailBuffer {
53
53
  * @param {number} [options.timeoutMs] - Stop the run after this many milliseconds; 0 or omitted means no limit.
54
54
  * @param {AbortSignal} [options.signal] - Stops the run when aborted.
55
55
  * @param {NodeJS.ProcessEnv} [options.env] - Environment; the host environment when omitted.
56
+ * @param {string} [options.input] - Text written to the command's stdin; stdin is closed (ignored) when omitted.
56
57
  * @param {string[]} [options.shells] - Shells tried in order until one starts.
57
58
  * @returns {Promise<CommandResult>}
58
59
  *
@@ -68,7 +69,7 @@ class TailBuffer {
68
69
  * @property {number} stdoutDropped - Bytes of stdout dropped from the front.
69
70
  * @property {number} durationMs
70
71
  */
71
- export async function runCommand({ command, cwd, timeoutMs, signal, env, shells = ['bash', 'sh'] }) {
72
+ export async function runCommand({ command, cwd, timeoutMs, signal, env, input, shells = ['bash', 'sh'] }) {
72
73
  const started = Date.now()
73
74
  if (cwd !== undefined && !(await isDirectory(cwd))) {
74
75
  return {
@@ -79,7 +80,7 @@ export async function runCommand({ command, cwd, timeoutMs, signal, env, shells
79
80
  }
80
81
  let last
81
82
  for (const shell of shells) {
82
- last = await runWith(shell, { command, cwd, timeoutMs, signal, env })
83
+ last = await runWith(shell, { command, cwd, timeoutMs, signal, env, input })
83
84
  if (last.spawnMissing !== true) break
84
85
  }
85
86
  const { spawnMissing, ...result } = last
@@ -94,7 +95,7 @@ async function isDirectory(path) {
94
95
  }
95
96
  }
96
97
 
97
- function runWith(shell, { command, cwd, timeoutMs, signal, env }) {
98
+ function runWith(shell, { command, cwd, timeoutMs, signal, env, input }) {
98
99
  return new Promise((resolve) => {
99
100
  const stdout = new TailBuffer(MAX_STDOUT_BYTES)
100
101
  const stderr = new TailBuffer(MAX_STDERR_BYTES)
@@ -115,7 +116,7 @@ function runWith(shell, { command, cwd, timeoutMs, signal, env }) {
115
116
  child = spawn(shell, ['-c', command], {
116
117
  cwd,
117
118
  env: env ?? process.env,
118
- stdio: ['ignore', 'pipe', 'pipe'],
119
+ stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
119
120
  detached: process.platform !== 'win32',
120
121
  windowsHide: true,
121
122
  })
@@ -142,6 +143,11 @@ function runWith(shell, { command, cwd, timeoutMs, signal, env }) {
142
143
  timer.unref?.()
143
144
  }
144
145
 
146
+ if (input !== undefined) {
147
+ // A command that exits without reading its stdin closes the pipe; that is not a failure.
148
+ child.stdin.on('error', () => {})
149
+ child.stdin.end(input)
150
+ }
145
151
  child.stdout.on('data', chunk => stdout.push(chunk))
146
152
  child.stderr.on('data', chunk => stderr.push(chunk))
147
153
  child.on('error', (error) => {
package/src/config.js CHANGED
@@ -23,6 +23,7 @@ const Agent = z.object({
23
23
  sessionId: z.string().description('Send the prompt into this existing session instead of opening a new one. Empty: open a new session.'),
24
24
  model: Model,
25
25
  autoArchive: z.boolean().description('Archive the woken session once its turn ends, unless it is pinned or a person has sent it a message (such a session is also never reused). The plugin\'s autoArchive when unset.'),
26
+ answerCheck: z.string().description('Command that reads the agent\'s final answer on stdin before the turn closes. Empty output passes it; any output is sent back into the turn as a request to rewrite the answer (once per run). Empty: no check.'),
26
27
  reuseWithinHours: z.number().min(0).description('Send the prompt into this job\'s previous woken session instead of opening a new one, when that session was opened within this many hours. 0 always opens a new session. The plugin\'s reuseWithinHours when unset.'),
27
28
  }).description('Wake an agent: run the command as a gate and open a new session only when its output asks for it.')
28
29
 
package/src/controller.js CHANGED
@@ -72,7 +72,7 @@ export class CronJobs {
72
72
  * @param {number} [options.watchdogMs] - How often the watchdog looks for lost timers; 0 turns it off.
73
73
  * @param {number} [options.overdueMs] - How far past its due time a tick must be before the watchdog runs it.
74
74
  */
75
- constructor({ jobs, logger, run, wake, reuse, settle, send, answer, defaults = {}, signal, record, history, CronClass = CronTimer, TimerClass = ScheduleTimer, now = () => new Date(), watchdogMs = WATCHDOG_MS, overdueMs = OVERDUE_MS }) {
75
+ constructor({ jobs, logger, run, wake, reuse, settle, send, answer, checks, defaults = {}, signal, record, history, CronClass = CronTimer, TimerClass = ScheduleTimer, now = () => new Date(), watchdogMs = WATCHDOG_MS, overdueMs = OVERDUE_MS }) {
76
76
  this.logger = logger
77
77
  this.defaults = defaults
78
78
  this.history = history
@@ -83,7 +83,7 @@ export class CronJobs {
83
83
  this.watchdogMs = watchdogMs
84
84
  this.overdueMs = overdueMs
85
85
  this.record = record ?? (async () => {})
86
- this.deps = { run, wake, reuse, settle, send, answer, defaults, logger, signal, record, history, now }
86
+ this.deps = { run, wake, reuse, settle, send, answer, checks, defaults, logger, signal, record, history, now }
87
87
  /** @type {Map<string, { job: object, runner: JobRunner, spec?: object, record?: object, timer?: any, error?: string }>} */
88
88
  this.entries = new Map()
89
89
  this.inflight = new Set()
@@ -357,6 +357,7 @@ export class CronJobs {
357
357
  title: title(input.title),
358
358
  ...text('prompt', input.prompt),
359
359
  ...text('command', input.command),
360
+ ...text('answerCheck', input.answerCheck),
360
361
  schedule: spec,
361
362
  ...(input.cwd ? { cwd: input.cwd } : {}),
362
363
  ...(input.preset ? { preset: input.preset } : {}),
@@ -393,7 +394,7 @@ export class CronJobs {
393
394
  const current = entry.record
394
395
  const next = { ...current, updatedAt: now.toISOString() }
395
396
  if (patch.title !== undefined) next.title = title(patch.title)
396
- for (const field of ['prompt', 'command']) {
397
+ for (const field of ['prompt', 'command', 'answerCheck']) {
397
398
  if (patch[field] === undefined) continue
398
399
  delete next[field]
399
400
  Object.assign(next, text(field, patch[field]))
@@ -536,7 +537,7 @@ function fromStored(record) {
536
537
  ...(record.cwd ? { cwd: record.cwd } : {}),
537
538
  timeoutSeconds: record.timeoutSeconds ?? DEFAULT_STORED_TIMEOUT_SECONDS,
538
539
  timeZone: scheduleZone(record.schedule),
539
- ...(record.prompt ? { agent: { prompt: record.prompt, ...(record.preset ? { preset: record.preset } : {}), ...(record.cwd ? { cwd: record.cwd } : {}), ...(record.model ? { model: record.model } : {}) } } : {}),
540
+ ...(record.prompt ? { agent: { prompt: record.prompt, ...(record.preset ? { preset: record.preset } : {}), ...(record.cwd ? { cwd: record.cwd } : {}), ...(record.model ? { model: record.model } : {}), ...(record.answerCheck ? { answerCheck: record.answerCheck } : {}) } } : {}),
540
541
  target: record.target,
541
542
  ...(record.deliver !== undefined ? { deliver: record.deliver } : {}),
542
543
  spec: record.schedule,
@@ -604,6 +605,7 @@ function agentView(job, defaults) {
604
605
  // Where the cwd came from: the job, the plugin default, or the job's command cwd.
605
606
  cwdSource: job.agent.cwd ? 'job' : defaults.agentCwd ? 'default' : job.cwd ? 'command' : null,
606
607
  model: agentModel(job) ?? null,
608
+ answerCheck: job.agent.answerCheck || null,
607
609
  // An explicit session is never archived or swapped for another one.
608
610
  autoArchive: target === 'session' ? false : settings.autoArchive,
609
611
  reuseWithinHours: target === 'new' ? settings.reuseWithinHours : 0,
package/src/job.js CHANGED
@@ -104,6 +104,7 @@ export class JobRunner {
104
104
  * @param {(sessionId: string, options: { signal?: AbortSignal, isLatest: () => boolean, lock: Function }) => Promise<{ archive: string, note?: string }>} [deps.settle] - Archives a session after its turn (see session.js archiveWhenIdle); without it nothing is archived.
105
105
  * @param {(target: { via: string, to: string }, message: { text: string, files: string[] }, from: { job: string, sessionId?: string }) => Promise<{ status: 'sent' | 'failed', attempts: number, error?: string }>} [deps.send] - Hands a result to its delivery service (see deliver.js sendMessage); without it nothing is delivered.
106
106
  * @param {(sessionId: string, messageId: string, options: { signal?: AbortSignal }) => Promise<{ pending: true } | { text: string, reason?: string } | { error: string }>} [deps.answer] - Waits for the final answer to a prompt (see session.js waitForAnswer).
107
+ * @param {ReturnType<typeof import('./answer-check.js').createAnswerChecks>} [deps.checks] - Answer checks (see answer-check.js); without it a job's answerCheck is ignored.
107
108
  * @param {{ agentCwd?: string, autoArchive?: boolean, reuseWithinHours?: number, deliver?: object }} [deps.defaults] - Plugin-level agent settings and the default delivery target.
108
109
  * @param {{ info: Function, warn: Function }} deps.logger
109
110
  * @param {AbortSignal} [deps.signal] - Stops a running command when aborted.
@@ -111,10 +112,11 @@ export class JobRunner {
111
112
  * @param {{ begin: Function, finish: Function }} [deps.history] - Saved run history (see history.js).
112
113
  * @param {() => Date} [deps.now]
113
114
  */
114
- constructor(job, { run, wake, reuse, keepSession, settle, send, answer, defaults = {}, logger, signal, record = async () => {}, history = NO_HISTORY, now = () => new Date() }) {
115
+ constructor(job, { run, wake, reuse, keepSession, settle, send, answer, checks, defaults = {}, logger, signal, record = async () => {}, history = NO_HISTORY, now = () => new Date() }) {
115
116
  this.job = job
116
117
  this.send = send
117
118
  this.answer = answer
119
+ this.checks = checks
118
120
  this.reuse = reuse
119
121
  this.keepSession = keepSession
120
122
  this.settle = settle
@@ -281,6 +283,8 @@ export class JobRunner {
281
283
  if (this.answer === undefined) return
282
284
  const answer = await this.answer(sessionId, pending.messageId, { signal: this.signal })
283
285
  if ('pending' in answer || this.signal?.aborted) return
286
+ if ('text' in answer) await this.checks?.recheck(pending.messageId, answer.text, { sessionId, signal: this.signal })
287
+ this.checks?.forget(pending.messageId)
284
288
  let delivery
285
289
  if ('error' in answer) {
286
290
  delivery = { status: 'failed', ...target, at: this.now().toISOString(), error: answer.error }
@@ -308,6 +312,8 @@ export class JobRunner {
308
312
  async resumeDeliveries() {
309
313
  for (const run of this.history.runs(jobKey(this.job))) {
310
314
  if (run.delivery?.status === 'pending' && run.sessionId && run.delivery.messageId) {
315
+ // The turn may still be running (a plugin reload, a turn that outlived a restart).
316
+ this.expectCheck(run.delivery.messageId)
311
317
  this.watchDelivery(run.sessionId, run.id, run.delivery)
312
318
  }
313
319
  }
@@ -353,10 +359,21 @@ export class JobRunner {
353
359
  const target = job.target ?? { kind: 'new' }
354
360
  // Lets the answer to this prompt be found once its turn ends.
355
361
  const messageId = randomUUID()
362
+ // Watched before the prompt is sent, so even a turn that ends at once is checked.
363
+ this.expectCheck(messageId)
356
364
  const sent = await this.deliverPrompt({ job, target, text, messageId, settings, firedAt, localTime })
365
+ if (sent.status !== 'woke') this.checks?.forget(messageId)
357
366
  return sent.status === 'woke' ? { ...sent, messageId } : sent
358
367
  }
359
368
 
369
+ /** Have the answer to this prompt checked before its turn closes, when the job names a check. */
370
+ expectCheck(messageId) {
371
+ const command = this.job.agent?.answerCheck
372
+ if (!command || this.checks === undefined) return
373
+ const cwd = agentSettings(this.job, this.defaults).cwd
374
+ this.checks.expect(messageId, { job: this.job.name, command, ...(cwd ? { cwd } : {}) })
375
+ }
376
+
360
377
  /** Send the prompt to the target session, a reused one, or a new one. */
361
378
  async deliverPrompt({ job, target, text, messageId, settings, firedAt, localTime }) {
362
379
  const { logger } = this
package/src/store.js CHANGED
@@ -32,6 +32,8 @@ export const storedJobSchema = z.object({
32
32
  title: z.string().min(1),
33
33
  prompt: z.string().optional(),
34
34
  command: z.string().optional(),
35
+ // Command that checks the agent's final answer before its turn closes (answer-check.js).
36
+ answerCheck: z.string().optional(),
35
37
  schedule: scheduleSchema,
36
38
  // Directory of the command and of new sessions.
37
39
  cwd: z.string().optional(),
package/tools.js CHANGED
@@ -43,6 +43,7 @@ export function toolSchemas(prefix) {
43
43
  description: 'Where the prompt goes; defaults to new. this_session: this session, for reminders and follow-ups to this conversation. new_once: one new session, opened by the first run and used by every later run. new: a new session for each run, archived once its turn ends. New sessions use cwd and this session\'s agent preset.',
44
44
  },
45
45
  sessionId: { type: 'string', description: 'Deliver to this other existing session instead of target.' },
46
+ answerCheck: { type: 'string', description: 'Shell command run in the session\'s cwd on the agent\'s final answer (on stdin) before its turn closes. Empty stdout passes the answer; any stdout is sent back into the turn as a request to rewrite it, once per run. Skipped for [SILENT].' },
46
47
  cwd: { type: 'string', description: 'Working directory of the command and of new sessions; defaults to this session\'s.' },
47
48
  deliver: { type: 'string', description: 'Where each run\'s result is sent: "<service>:<address>", a DSH service that delivers messages and an address it understands (such as telegramTopics:notify), or "none". The result is the agent\'s final answer (exactly [SILENT] sends nothing; MEDIA:<path> lines become attachments), or for a job without a prompt the command\'s stdout and failures. Defaults to the plugin\'s default target, or none when the prompt goes to an existing session.' },
48
49
  }
@@ -75,6 +76,7 @@ export function toolSchemas(prefix) {
75
76
  title: { type: 'string', description: 'New job name.' },
76
77
  prompt: { ...fields.prompt, description: 'New prompt; an empty string removes it.' },
77
78
  command: { ...fields.command, description: 'New command; an empty string removes it.' },
79
+ answerCheck: { ...fields.answerCheck, description: 'New answer check command; an empty string removes it.' },
78
80
  ...schedule,
79
81
  timeZone: { type: 'string', description: `Zone for a new cron or at, as in ${prefix}_create; given alone, it moves a cron schedule to this zone.` },
80
82
  target: { ...fields.target, description: `New target, as in ${prefix}_create.` },
@@ -125,6 +127,7 @@ export function createTools({ prefix = 'cron_job', getJobs, ctx }) {
125
127
  title: args.title,
126
128
  prompt: args.prompt,
127
129
  command: args.command,
130
+ answerCheck: args.answerCheck,
128
131
  schedule: { cron: args.cron, rrule: args.rrule, at: args.at, timeZone: args.timeZone },
129
132
  cwd: args.cwd || callerCwd(agent),
130
133
  preset: callerPreset(agent),
@@ -138,7 +141,7 @@ export function createTools({ prefix = 'cron_job', getJobs, ctx }) {
138
141
  `Update, pause, resume or delete one job created with ${prefix}_create, by id. Jobs from the plugin config are read-only.`,
139
142
  async (args, jobs, agent) => {
140
143
  const { id, action } = args
141
- const changes = ['title', 'prompt', 'command', 'cron', 'rrule', 'at', 'timeZone', 'target', 'sessionId', 'cwd', 'deliver', 'model'].filter(key => args[key] !== undefined)
144
+ const changes = ['title', 'prompt', 'command', 'answerCheck', 'cron', 'rrule', 'at', 'timeZone', 'target', 'sessionId', 'cwd', 'deliver', 'model'].filter(key => args[key] !== undefined)
142
145
  if (action !== 'update' && changes.length > 0) return failure('invalid_arguments', `${action} takes only id and action.`)
143
146
  if (action === 'delete') return await jobs.remove(id)
144
147
  if (action === 'pause' || action === 'resume') {
@@ -154,6 +157,7 @@ export function createTools({ prefix = 'cron_job', getJobs, ctx }) {
154
157
  title: args.title,
155
158
  prompt: args.prompt,
156
159
  command: args.command,
160
+ answerCheck: args.answerCheck,
157
161
  cwd: args.cwd,
158
162
  ...(args.model !== undefined ? { model: toModel(args.model) ?? null } : {}),
159
163
  ...(scheduleGiven ? { schedule: { cron: args.cron, rrule: args.rrule, at: args.at, timeZone: args.timeZone } } : {}),
@@ -266,7 +270,7 @@ export function modelJob(job, { brief = false } = {}) {
266
270
  ...(job.agent?.model ? { model: job.agent.model } : {}),
267
271
  deliver: job.deliver?.via ? (job.deliver.to ? `${job.deliver.via}:${job.deliver.to}` : job.deliver.via) : 'none',
268
272
  ...(brief ? {} : {
269
- ...(job.agent ? { prompt: job.agent.prompt, preset: job.agent.preset, sessionCwd: job.agent.cwd } : {}),
273
+ ...(job.agent ? { prompt: job.agent.prompt, preset: job.agent.preset, sessionCwd: job.agent.cwd, ...(job.agent.answerCheck ? { answerCheck: job.agent.answerCheck } : {}) } : {}),
270
274
  ...(job.command ? { command: job.command, cwd: job.cwd } : {}),
271
275
  ...(job.createdBy ? { createdBy: job.createdBy } : {}),
272
276
  }),