@soffits/dsh-cron-jobs 0.13.1 → 0.15.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
@@ -110,7 +110,6 @@ Config jobs live in the config of the `cron-jobs` row. Add an override to your p
110
110
  | `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. |
111
111
  | `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. |
112
112
  | `agent.model.reasoningEffort` | Reasoning effort id for that model. The model's default when empty. |
113
- | `agent.answerCheck` | Command that checks the agent's final answer before its turn closes (see [Answer checks](#answer-checks)). No check when empty. |
114
113
 
115
114
  Next to `jobs`, the row also takes:
116
115
 
@@ -120,6 +119,8 @@ Next to `jobs`, the row also takes:
120
119
  | `autoArchive` | Default for `agent.autoArchive`. Default `true`. |
121
120
  | `reuseWithinHours` | Default for `agent.reuseWithinHours`. Default `0`. |
122
121
  | `deliver` | Default delivery target, `{ via, to }`, for jobs that do not set `deliver`. Unset: results are not delivered. |
122
+ | `problems.channel` | Also emit every problem note as an event on this channel, so an agent job with `on: [<channel>]` can handle it. See [Problem notes](#problem-notes). |
123
+ | `problems.deliver` | Where problem notes are sent instead of the job's own target: `{ via, to }`, or `false` for none once a job took the event. Unset: the job's target, as before. |
123
124
  | `historyRecords` | Runs kept per job for the Cron tasks page. Default 50, at most 1000. |
124
125
  | `runLog` | Optional JSON Lines file of run starts and ends, see below. |
125
126
  | `watchers` | Long-running commands whose output lines are events: `[{ id, channel, command, cwd, enabled }]`. See [Watchers](#watchers). |
@@ -168,19 +169,34 @@ Where results go is decided per job: its own `deliver` (or `false`), otherwise n
168
169
 
169
170
  Each run's delivery shows on the Cron tasks page and in the run log: not sent yet (waiting for the answer or for the channel), sent, nothing to send, or not sent with the reason. A delivery still waiting when DSH stops or the plugin reloads, whether for a turn that is still running or for a channel that is not there, is picked up and delivered after the next start.
170
171
 
171
- ### Runs cut off by a restart
172
+ ### Problem notes
172
173
 
173
- A woken turn that a DSH restart cuts off before it finishes is run again once. A turn a person stopped, or one that failed, is not. Finding the cut turns is left to [dsh-restart-resume](https://github.com/soffits/dsh-restart-resume) (0.4.0 or later), which reads every cut turn from DSH's log after a restart and hands the ones a job started back to this plugin; without it, a cut-off run is recorded but not run again. The cut-off turn delivers nothing; when it is handed back, the plugin sends a short follow-up into the same session saying the earlier turn was cut off and asking the agent to finish the job without repeating what is done. The session already holds the job's prompt, command output and events, and whatever the cut-off turn did. The rerun's answer is delivered like any other.
174
+ Failure notes (a command or gate that failed, a wake or rerun that failed, a watcher that is down or works again) go to the same place as the job's results unless the row says otherwise. That is the right default when whoever reads results also fixes the jobs. When the results go to someone who should not get raw failures, such as a person reading an agent's reports, the row's `problems` setting sends them elsewhere:
174
175
 
175
- The rerun is skipped, with the reason in the run history and a `rerun-skipped` run-log line, when the cut-off run started more than 2 hours ago, a later run of the job has woken the agent since, the job's next run is less than 15 minutes away, or the job is paused, disabled or deleted. A session the job opened for itself that a person has since taken over is left alone: the rerun fails with a note to the delivery target. A rerun that is cut off too is not run again. The run log marks the cut-off with a `cut-off` line, and the rerun's `start` line carries `rerunOf`.
176
+ ```yaml
177
+ - id: cron-jobs
178
+ config:
179
+ deliver: { via: telegramTopics, to: notify }
180
+ problems:
181
+ channel: cron.problem # hand each note to the jobs on this channel
182
+ deliver: false # and don't also send it to the job's target
183
+ jobs:
184
+ - name: Fix broken jobs
185
+ on: [cron.problem]
186
+ agent:
187
+ prompt: A scheduled job or watcher failed; the note is below. Find the cause and fix it. Tell the owner only what needs them.
188
+ ```
189
+
190
+ - `channel`: each note becomes an event with the note as its text and details as data: `kind` (`command-failed`, `gate-failed`, `wake-failed`, `rerun-failed`, `watcher-down`, `watcher-up`), `job` and `jobId` (or `watcher` and its `channel`), `trigger`, `startedAt`, `error`, `exitCode`, `sessionId` when known, and `text`. Events batch and are capped like any others. A run that this channel started never emits a note on it, so a failing handler can't feed itself.
191
+ - `deliver`: a target sends every note there instead (a log topic, an ops chat), with or without `channel`. `false` sends nothing, but only when a job listening on `channel` took the event; a note no job took (no channel, nobody listening, or the handler's own failure) still goes to the job's target, so a broken job never goes quiet.
176
192
 
177
- ### Answer checks
193
+ Ordinary results are not affected. Both are off by default.
178
194
 
179
- 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.
195
+ ### Runs cut off by a restart
180
196
 
181
- 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`).
197
+ A woken turn that a DSH restart cuts off before it finishes is run again once. A turn a person stopped, or one that failed, is not. Finding the cut turns is left to [dsh-restart-resume](https://github.com/soffits/dsh-restart-resume) (0.4.0 or later), which reads every cut turn from DSH's log after a restart and hands the ones a job started back to this plugin; without it, a cut-off run is recorded but not run again. The cut-off turn delivers nothing; when it is handed back, the plugin sends a short follow-up into the same session saying the earlier turn was cut off and asking the agent to finish the job without repeating what is done. The session already holds the job's prompt, command output and events, and whatever the cut-off turn did. The rerun's answer is delivered like any other.
182
198
 
183
- 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.
199
+ The rerun is skipped, with the reason in the run history and a `rerun-skipped` run-log line, when the cut-off run started more than 2 hours ago, a later run of the job has woken the agent since, the job's next run is less than 15 minutes away, or the job is paused, disabled or deleted. A session the job opened for itself that a person has since taken over is left alone: the rerun fails with a note to the delivery target. A rerun that is cut off too is not run again. The run log marks the cut-off with a `cut-off` line, and the rerun's `start` line carries `rerunOf`.
184
200
 
185
201
  ### Who sent a prompt
186
202
 
@@ -190,7 +206,7 @@ Every prompt a job puts into a session has the source kind `schedule`, which the
190
206
  { kind: 'cron-job', channel: 'cron', id, name, trigger, events }
191
207
  ```
192
208
 
193
- `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.
209
+ `id` is the job's id (its name for a config job), `name` its name, `trigger` what started the run (`schedule`, `manual`, `event`, or `rerun`), 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.
194
210
 
195
211
  ### Delivery channels
196
212
 
@@ -279,7 +295,7 @@ A watcher is a long-running command the plugin starts with the scheduler, restar
279
295
  - any other non-empty line is the event's text;
280
296
  - `{"wakeAgent": false}` lines are ignored.
281
297
 
282
- A watcher that exits is restarted after 1 s, doubling up to 5 minutes, and back to 1 s once a run lasted a minute. If it has not managed to stay up for a minute in 15 minutes, one note goes to the row's `deliver` target, and one more when it works again; exits, stderr tails and these notes are in the run log. The command runs with `bash -c` in its own process group, with `DSH_CRON_WATCHER` (its id), `DSH_CRON_CHANNEL` and `DSH_CRON_STATE_DIR` (`$DSH_HOME/cron-jobs/watchers/<id>`, a directory for its cursor) in its environment.
298
+ A watcher that exits is restarted after 1 s, doubling up to 5 minutes, and back to 1 s once a run lasted a minute. If it has not managed to stay up for a minute in 15 minutes, one note goes to the row's `deliver` target (or as set by [`problems`](#problem-notes)), and one more when it works again; exits, stderr tails and these notes are in the run log. The command runs with `bash -c` in its own process group, with `DSH_CRON_WATCHER` (its id), `DSH_CRON_CHANNEL` and `DSH_CRON_STATE_DIR` (`$DSH_HOME/cron-jobs/watchers/<id>`, a directory for its cursor) in its environment.
283
299
 
284
300
  Watchers come from the row's `watchers` list, or from a conversation with the `cron_job_watch` tool (`create`, `delete`, `list`), which keeps them in DSH storage. A tool-made watcher can be `once`: it runs one time and removes itself when it exits, for a one-off wait that has to survive a DSH restart:
285
301
 
@@ -319,7 +335,6 @@ Where the prompt goes (`target`):
319
335
 
320
336
  `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
337
 
322
- `answerCheck` sets the job's [answer check](#answer-checks) command; on `cron_job_edit`, an empty string removes it.
323
338
 
324
339
  `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.
325
340
 
package/index.js CHANGED
@@ -17,7 +17,6 @@ import { runCommand } from './src/command.js'
17
17
  import { archiveWhenIdle, deliverToSession, openAgentSession, waitForAnswer } from './src/session.js'
18
18
  import { sendMessage } from './src/deliver.js'
19
19
  import { CronJobs } from './src/controller.js'
20
- import { createAnswerChecks } from './src/answer-check.js'
21
20
  import { createRunLog } from './src/runlog.js'
22
21
  import { openHistory } from './src/history.js'
23
22
  import { createRoutes, createRpcHandler } from './src/rpc.js'
@@ -33,7 +32,7 @@ export { Config }
33
32
 
34
33
  /**
35
34
  * @param {import('@deepseek-ai/cordis').Context} ctx
36
- * @param {{ jobs: import('./src/job.js').Job[], watchers?: object[], events?: { coalesceSeconds?: number, maxRunsPerHour?: number }, runLog?: string, historyRecords?: number, defaultAgentCwd?: string, autoArchive?: boolean, reuseWithinHours?: number, deliver?: { via?: string, to?: string } }} config
35
+ * @param {{ jobs: import('./src/job.js').Job[], watchers?: object[], events?: { coalesceSeconds?: number, maxRunsPerHour?: number }, runLog?: string, historyRecords?: number, defaultAgentCwd?: string, autoArchive?: boolean, reuseWithinHours?: number, deliver?: { via?: string, to?: string }, problems?: { channel?: string, deliver?: { via?: string, to?: string } | false } }} config
37
36
  */
38
37
  export function apply(ctx, config) {
39
38
  const logger = ctx.logger('cron-jobs')
@@ -61,34 +60,31 @@ export function apply(ctx, config) {
61
60
  const controller = new AbortController()
62
61
  let jobs
63
62
  let history
64
- let checks
65
63
  let spool
66
- // A job's answerCheck runs as the turn its prompt started is about to close.
67
- const stopTurnHook = ctx.on?.('agent/turn-stopping', payload => checks?.onTurnStopping(payload))
68
64
  const ready = (async () => {
69
65
  history = await openHistory(ctx.storageDomain, {
70
66
  limit: config.historyRecords, logger, signal: controller.signal,
71
67
  })
72
68
  if (controller.signal.aborted) return
73
69
  const record = createRunLog(config.runLog || undefined, logger)
74
- checks = createAnswerChecks({ run: runCommand, logger, record })
75
70
  jobs = new CronJobs({
76
71
  jobs: config.jobs ?? [],
77
72
  logger,
78
73
  run: runCommand,
79
- wake: request => openAgentSession(ctx, request, logger),
80
- reuse: request => deliverToSession(ctx, request),
74
+ // Both wait for session services DSH has not registered yet (a run at startup).
75
+ wake: request => openAgentSession(ctx, request, logger, { signal: controller.signal }),
76
+ reuse: request => deliverToSession(ctx, request, { signal: controller.signal }),
81
77
  settle: (sessionId, options) => archiveWhenIdle(ctx, sessionId, options),
82
78
  // The channel is found by name at send time, so it may load after
83
79
  // this plugin, reload, or be missing for a while (the delivery waits).
84
80
  send: (target, message, from, options) => sendMessage({ lookup: name => ctx.get(name), target, message, from, signal: controller.signal, ...options }),
85
81
  answer: (sessionId, messageId, options) => waitForAnswer(ctx, sessionId, messageId, options),
86
- checks,
87
82
  defaults: {
88
83
  agentCwd: config.defaultAgentCwd || undefined,
89
84
  autoArchive: config.autoArchive ?? true,
90
85
  reuseWithinHours: config.reuseWithinHours ?? 0,
91
86
  deliver: config.deliver,
87
+ problems: config.problems,
92
88
  },
93
89
  signal: controller.signal,
94
90
  record,
@@ -114,7 +110,6 @@ export function apply(ctx, config) {
114
110
  started = ready
115
111
  return async () => {
116
112
  current = undefined
117
- stopTurnHook?.()
118
113
  // Stop reading events first, so none reaches a stopping scheduler.
119
114
  await spool?.stop()
120
115
  // Stop the timers first so no new run starts with an aborted signal.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-cron-jobs",
3
- "version": "0.13.1",
3
+ "version": "0.15.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
@@ -24,7 +24,6 @@ const Agent = z.object({
24
24
  sessionId: z.string().description('Send the prompt into this existing session instead of opening a new one. Empty: open a new session.'),
25
25
  model: Model,
26
26
  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.'),
27
- 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.'),
28
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.'),
29
28
  }).description('Wake an agent: run the command as a gate and open a new session only when its output asks for it.')
30
29
 
@@ -58,6 +57,11 @@ const Events = z.object({
58
57
  maxRunsPerHour: z.natural().default(DEFAULT_MAX_RUNS_PER_HOUR).description('Most event-started runs of one job in any hour; past that, events wait and run together. 0 means no cap.'),
59
58
  })
60
59
 
60
+ const Problems = z.object({
61
+ channel: z.string().description('Also emit every problem note (a failed command or gate, a failed wake or rerun, a watcher down or back) as an event on this channel, such as cron.problem, so a job with on: [cron.problem] can handle it. A run this channel started never emits one. Empty: no event.'),
62
+ deliver: z.union([z.const(false), DeliveryTarget]).description('Where problem notes are sent instead of the job\'s own target (or, for watchers, the plugin\'s deliver). false sends none when a job took the event on channel; a note no job took still goes to the job\'s target. Unset: the job\'s target, as before.'),
63
+ }).description('Where notes about failures go, so they can reach whoever fixes them rather than every job\'s audience.')
64
+
61
65
  export const Config = z.object({
62
66
  jobs: z.array(Job).default([]).description('Scheduled jobs.'),
63
67
  watchers: z.array(Watcher).default([]).description('Long-running commands whose output lines are events (see a job\'s on). Watchers can also be added from a conversation with the watch tool.'),
@@ -66,6 +70,7 @@ export const Config = z.object({
66
70
  autoArchive: z.boolean().default(true).description('Archive woken sessions once their turn ends, for jobs that do not set agent.autoArchive. Archived sessions leave the sidebar\'s active list but stay in DSH and in session search.'),
67
71
  reuseWithinHours: z.number().min(0).default(0).description('Reuse window for jobs that do not set agent.reuseWithinHours: send the prompt into the job\'s previous woken session when it was opened within this many hours. 0 always opens a new session.'),
68
72
  deliver: DeliveryTarget.description('Default delivery target for jobs that do not set deliver. Jobs that post into an existing session do not use it. Unset: results are not delivered.'),
73
+ problems: Problems,
69
74
  historyRecords: z.natural().min(1).max(1000).default(DEFAULT_HISTORY_RECORDS)
70
75
  .description('Runs kept per job for the Cron tasks page (start, duration, exit code, woken session, output tails). Older runs are dropped.'),
71
76
  runLog: z.string().description('JSON Lines file that gets one line when a run starts and one when it ends (outcome, exit code, duration, output tails), so past runs can be checked later. Directories are created as needed. No file when empty.'),
package/src/controller.js CHANGED
@@ -70,7 +70,7 @@ export class CronJobs {
70
70
  * @param {Function} [options.settle] - Archives a session after its turn.
71
71
  * @param {Function} [options.send] - Hands a result to its delivery service (see deliver.js sendMessage).
72
72
  * @param {Function} [options.answer] - Waits for a woken agent's final answer (see session.js waitForAnswer).
73
- * @param {{ agentCwd?: string, autoArchive?: boolean, reuseWithinHours?: number, deliver?: object }} [options.defaults] - Plugin-level agent settings and default delivery target.
73
+ * @param {{ agentCwd?: string, autoArchive?: boolean, reuseWithinHours?: number, deliver?: object, problems?: { channel?: string, deliver?: object | false } }} [options.defaults] - Plugin-level agent settings, default delivery target, and where problem notes go (see reportProblem).
74
74
  * @param {AbortSignal} [options.signal] - Stops running commands when aborted.
75
75
  * @param {(entry: object) => Promise<void>} [options.record] - Run log, see runlog.js.
76
76
  * @param {import('./history.js').HistoryStore} [options.history] - Saved runs, pause state and stored jobs.
@@ -85,7 +85,7 @@ export class CronJobs {
85
85
  * @param {object} [options.watcherOptions] - Passed to {@link WatcherSupervisor} (stateRoot, limits, spawn).
86
86
  * @param {{ maxAgeMs?: number, minLeadMs?: number }} [options.rerun] - Limits for rerunning cut-off runs (see continueCut).
87
87
  */
88
- 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, events = {}, timers, watchers = [], watcherOptions = {}, rerun = {} }) {
88
+ 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, events = {}, timers, watchers = [], watcherOptions = {}, rerun = {} }) {
89
89
  this.logger = logger
90
90
  this.defaults = defaults
91
91
  this.history = history
@@ -96,7 +96,7 @@ export class CronJobs {
96
96
  this.watchdogMs = watchdogMs
97
97
  this.overdueMs = overdueMs
98
98
  this.record = record ?? (async () => {})
99
- this.deps = { run, wake, reuse, settle, send, answer, checks, defaults, logger, signal, record, history, now }
99
+ this.deps = { run, wake, reuse, settle, send, answer, defaults, logger, signal, record, history, now, reportProblem: (problem, triggers) => this.reportProblem(problem, triggers) }
100
100
  this.eventSettings = {
101
101
  coalesceMs: (events.coalesceSeconds ?? DEFAULT_COALESCE_SECONDS) * 1000,
102
102
  maxRunsPerHour: events.maxRunsPerHour ?? DEFAULT_MAX_RUNS_PER_HOUR,
@@ -237,7 +237,7 @@ export class CronJobs {
237
237
  emit: event => this.emit(event),
238
238
  logger: this.logger,
239
239
  record: this.record,
240
- notify: (text, def) => this.notifyDefault(text, `watcher ${def.id}`),
240
+ notify: (text, def, kind) => this.notifyProblem(text, { kind, watcher: def.id, channel: def.channel }),
241
241
  onDone: id => this.watcherDone(id),
242
242
  })
243
243
  this.supervisor.set(this.watcherDefinitions())
@@ -253,13 +253,41 @@ export class CronJobs {
253
253
  return defs
254
254
  }
255
255
 
256
- /** Send a note to the plugin's default delivery target, if there is one. */
257
- async notifyDefault(text, from) {
258
- const target = resolveDelivery({}, this.defaults.deliver)
259
- if (target === undefined || this.deps.send === undefined) {
260
- this.logger.warn('%s: %s (no delivery target)', from, text)
256
+ /**
257
+ * Hand a problem note to the jobs on the `problems.channel` setting, as an
258
+ * event with the note as text and the details as data. Not emitted for a
259
+ * run that this channel started, so a failing handler cannot feed itself.
260
+ * @param {{ kind: string, text: string }} problem
261
+ * @param {string[]} [triggers] - Event channels that started the failed run.
262
+ * @returns {boolean} Whether a job listening on the channel took it.
263
+ */
264
+ reportProblem(problem, triggers = []) {
265
+ const channel = this.defaults.problems?.channel?.trim()
266
+ if (!channel || this.stopped || triggers.includes(channel)) return false
267
+ try {
268
+ return this.emit({ channel, source: 'cron-jobs', text: problem.text, data: problem }).matched.length > 0
269
+ } catch (error) {
270
+ this.logger.warn('problem note not emitted on %s: %s', channel, error instanceof Error ? error.message : String(error))
271
+ return false
272
+ }
273
+ }
274
+
275
+ /**
276
+ * A watcher's down or back-up note: emitted on the problems channel, and
277
+ * sent to `problems.deliver` or the plugin's default target (see
278
+ * JobRunner.problemTarget for the same rule).
279
+ */
280
+ async notifyProblem(text, details) {
281
+ const from = `watcher ${details.watcher}`
282
+ const handled = this.reportProblem({ ...details, text })
283
+ const routed = deliveryTarget(this.defaults.problems?.deliver)
284
+ const fallback = resolveDelivery({}, this.defaults.deliver)
285
+ const target = routed === undefined ? fallback : routed === false ? (handled ? undefined : fallback) : routed
286
+ if (target === undefined) {
287
+ if (!handled) this.logger.warn('%s: %s (no delivery target)', from, text)
261
288
  return
262
289
  }
290
+ if (this.deps.send === undefined) return
263
291
  const sent = await this.deps.send(target, { text, files: [] }, { job: from }, {})
264
292
  if (sent.status !== 'sent') this.logger.warn('%s: note not delivered: %s', from, sent.error)
265
293
  }
@@ -623,7 +651,6 @@ export class CronJobs {
623
651
  title: title(input.title),
624
652
  ...text('prompt', input.prompt),
625
653
  ...text('command', input.command),
626
- ...text('answerCheck', input.answerCheck),
627
654
  ...(spec ? { schedule: spec } : {}),
628
655
  ...(on.length > 0 ? { on } : {}),
629
656
  ...(input.once === true ? { once: true } : {}),
@@ -663,7 +690,7 @@ export class CronJobs {
663
690
  const current = entry.record
664
691
  const next = { ...current, updatedAt: now.toISOString() }
665
692
  if (patch.title !== undefined) next.title = title(patch.title)
666
- for (const field of ['prompt', 'command', 'answerCheck']) {
693
+ for (const field of ['prompt', 'command']) {
667
694
  if (patch[field] === undefined) continue
668
695
  delete next[field]
669
696
  Object.assign(next, text(field, patch[field]))
@@ -849,7 +876,7 @@ function fromStored(record) {
849
876
  ...(record.cwd ? { cwd: record.cwd } : {}),
850
877
  timeoutSeconds: record.timeoutSeconds ?? DEFAULT_STORED_TIMEOUT_SECONDS,
851
878
  timeZone: scheduleZone(record.schedule),
852
- ...(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 } : {}) } } : {}),
879
+ ...(record.prompt ? { agent: { prompt: record.prompt, ...(record.preset ? { preset: record.preset } : {}), ...(record.cwd ? { cwd: record.cwd } : {}), ...(record.model ? { model: record.model } : {}) } } : {}),
853
880
  target: record.target,
854
881
  ...(record.deliver !== undefined ? { deliver: record.deliver } : {}),
855
882
  spec: record.schedule,
@@ -940,7 +967,6 @@ function agentView(job, defaults) {
940
967
  // Where the cwd came from: the job, the plugin default, or the job's command cwd.
941
968
  cwdSource: job.agent.cwd ? 'job' : defaults.agentCwd ? 'default' : job.cwd ? 'command' : null,
942
969
  model: agentModel(job) ?? null,
943
- answerCheck: job.agent.answerCheck || null,
944
970
  // An explicit session is never archived or swapped for another one.
945
971
  autoArchive: target === 'session' ? false : settings.autoArchive,
946
972
  reuseWithinHours: target === 'new' ? settings.reuseWithinHours : 0,
package/src/job.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
  import { decideWake } from './wake.js'
3
- import { commandResultText, cutOff, describeTarget, messageFromText, resolveDelivery } from './deliver.js'
3
+ import { commandResultText, cutOff, deliveryTarget, describeTarget, messageFromText, resolveDelivery } from './deliver.js'
4
4
  import { buildAgentPrompt, buildRerunPrompt, formatLocalTime, sessionTitle } from './prompt.js'
5
5
  import { HISTORY_TAIL_CHARS } from './history.js'
6
6
  import { batchSummary, eventInput } from './events.js'
@@ -105,23 +105,23 @@ export class JobRunner {
105
105
  * @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.
106
106
  * @param {(target: { via: string, to: string }, message: { text: string, files: string[] }, from: { job: string, sessionId?: string }, options: { waitMs?: number, onWait?: Function }) => Promise<{ status: 'sent' | 'failed' | 'unavailable' | 'stopped', attempts: number, error?: string }>} [deps.send] - Hands a result to its delivery service (see deliver.js sendMessage); without it nothing is delivered.
107
107
  * @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).
108
- * @param {ReturnType<typeof import('./answer-check.js').createAnswerChecks>} [deps.checks] - Answer checks (see answer-check.js); without it a job's answerCheck is ignored.
109
- * @param {{ agentCwd?: string, autoArchive?: boolean, reuseWithinHours?: number, deliver?: object }} [deps.defaults] - Plugin-level agent settings and the default delivery target.
108
+ * @param {{ agentCwd?: string, autoArchive?: boolean, reuseWithinHours?: number, deliver?: object, problems?: { deliver?: object | false } }} [deps.defaults] - Plugin-level agent settings, the default delivery target, and where problem notes go.
109
+ * @param {(problem: object, triggers: string[]) => boolean} [deps.reportProblem] - Emits a problem note as an event (see CronJobs.reportProblem); true when a job took it.
110
110
  * @param {{ info: Function, warn: Function }} deps.logger
111
111
  * @param {AbortSignal} [deps.signal] - Stops a running command when aborted.
112
112
  * @param {(entry: object) => Promise<void>} [deps.record] - Appends a run record (see runlog.js).
113
113
  * @param {{ begin: Function, finish: Function }} [deps.history] - Saved run history (see history.js).
114
114
  * @param {() => Date} [deps.now]
115
115
  */
116
- constructor(job, { run, wake, reuse, keepSession, settle, send, answer, checks, defaults = {}, logger, signal, record = async () => {}, history = NO_HISTORY, now = () => new Date() }) {
116
+ constructor(job, { run, wake, reuse, keepSession, settle, send, answer, reportProblem, defaults = {}, logger, signal, record = async () => {}, history = NO_HISTORY, now = () => new Date() }) {
117
117
  this.job = job
118
118
  this.send = send
119
119
  this.answer = answer
120
- this.checks = checks
121
120
  this.reuse = reuse
122
121
  this.keepSession = keepSession
123
122
  this.settle = settle
124
123
  this.defaults = defaults
124
+ this.reportProblem = reportProblem
125
125
  /** Latest run that sent a prompt to each session; only that run archives it. */
126
126
  this.latestRun = new Map()
127
127
  /** Per-session queue that keeps a delivery and an archive from overlapping. */
@@ -247,22 +247,28 @@ export class JobRunner {
247
247
  * nothing.
248
248
  */
249
249
  async deliverResult({ messageId, ...outcome }, result, { rerun = false } = {}) {
250
- const target = this.deliveryTarget()
251
- if (target === undefined) return outcome
252
250
  const { job } = this
253
- const where = { via: target.via, to: target.to }
254
251
  if (outcome.status === 'woke') {
255
- if (outcome.turn?.status !== 'pending') return outcome
256
- return { ...outcome, delivery: { status: 'pending', ...where } }
252
+ const target = this.deliveryTarget()
253
+ if (target === undefined || outcome.turn?.status !== 'pending') return outcome
254
+ return { ...outcome, delivery: { status: 'pending', via: target.via, to: target.to } }
257
255
  }
258
256
  let text
257
+ let problem
259
258
  if (outcome.status === 'wake-failed') {
259
+ problem = rerun ? 'rerun-failed' : 'wake-failed'
260
260
  text = rerun
261
261
  ? `⚠️ ${job.name}: the run cut off by a DSH restart could not run again: ${outcome.error}`
262
262
  : `⚠️ ${job.name}: could not wake the agent: ${outcome.error}`
263
263
  }
264
- else if (result !== undefined && !result.aborted && (outcome.status === 'done' || outcome.status === 'failed')) text = commandResultText(job, result)
264
+ else if (result !== undefined && !result.aborted && (outcome.status === 'done' || outcome.status === 'failed')) {
265
+ text = commandResultText(job, result)
266
+ if (!result.ok) problem = isGated(job) ? 'gate-failed' : 'command-failed'
267
+ }
265
268
  else return outcome
269
+ const target = problem === undefined ? this.deliveryTarget() : this.problemTarget(problem, text, outcome, result)
270
+ if (target === undefined) return outcome
271
+ const where = { via: target.via, to: target.to }
266
272
  const message = messageFromText(text, job.cwd || undefined)
267
273
  if (message === undefined) return { ...outcome, delivery: { status: 'silent', ...where } }
268
274
  // No waiting inside the run: a missing service is waited for in the
@@ -271,6 +277,32 @@ export class JobRunner {
271
277
  return { ...outcome, delivery: delivery.status === 'pending' ? { ...delivery, message } : delivery }
272
278
  }
273
279
 
280
+ /**
281
+ * Where a problem note (a failed command or gate, a failed wake or rerun)
282
+ * goes, after handing it to the problems channel. Without a `problems`
283
+ * setting, the job's own target. `problems.deliver` set to a target sends
284
+ * it there instead; set to false sends nothing, but only when a job took
285
+ * the event, so a problem nobody handles still reaches the job's target.
286
+ */
287
+ problemTarget(kind, text, outcome, result) {
288
+ const { job, current } = this
289
+ const handled = this.reportProblem?.({
290
+ kind,
291
+ job: job.name,
292
+ jobId: jobKey(job),
293
+ trigger: current?.rerunOf ? 'rerun' : current?.trigger ?? 'schedule',
294
+ ...(current?.startedAt ? { startedAt: current.startedAt } : {}),
295
+ ...(outcome.sessionId ? { sessionId: outcome.sessionId } : {}),
296
+ ...(outcome.error ? { error: outcome.error } : {}),
297
+ ...(result ? { exitCode: result.exitCode ?? null } : {}),
298
+ text,
299
+ }, current?.events?.channels ?? []) === true
300
+ const routed = deliveryTarget(this.defaults.problems?.deliver)
301
+ if (routed === undefined) return this.deliveryTarget()
302
+ if (routed === false) return handled ? undefined : this.deliveryTarget()
303
+ return this.send === undefined ? undefined : routed
304
+ }
305
+
274
306
  /**
275
307
  * Send one message and log the result; resolves the run's delivery record.
276
308
  * Not sent because the plugin is stopping, or (with `waitMs` 0) because
@@ -324,8 +356,6 @@ export class JobRunner {
324
356
  const answer = await this.answer(sessionId, messageId, { signal: this.signal })
325
357
  if ('pending' in answer || this.signal?.aborted) return undefined
326
358
  const cut = 'text' in answer && cutOff(answer)
327
- if ('text' in answer && !cut) await this.checks?.recheck(messageId, answer.text, { sessionId, signal: this.signal })
328
- this.checks?.forget(messageId)
329
359
  const reason = 'error' in answer ? 'error' : answer.reason
330
360
  await this.history.update(jobKey(job), runId, { turn: { status: cut ? 'cut-off' : 'ended', messageId, ...(reason ? { reason } : {}) } })
331
361
  let delivery
@@ -446,7 +476,6 @@ export class JobRunner {
446
476
  if (delivery?.message !== undefined) {
447
477
  this.watchDelivery(run.sessionId, run.id, delivery)
448
478
  } else if (messageId && run.sessionId && this.answer !== undefined) {
449
- this.expectCheck(messageId)
450
479
  this.watchTurn(run.sessionId, run.id, messageId, delivery)
451
480
  }
452
481
  }
@@ -496,10 +525,7 @@ export class JobRunner {
496
525
  const target = job.target ?? { kind: 'new' }
497
526
  // Lets the answer to this prompt be found once its turn ends.
498
527
  const messageId = randomUUID()
499
- // Watched before the prompt is sent, so even a turn that ends at once is checked.
500
- this.expectCheck(messageId)
501
528
  const sent = await this.deliverPrompt({ job, target, text, messageId, settings, firedAt, localTime })
502
- if (sent.status !== 'woke') this.checks?.forget(messageId)
503
529
  return sent.status === 'woke' ? { ...sent, messageId } : sent
504
530
  }
505
531
 
@@ -523,7 +549,6 @@ export class JobRunner {
523
549
  delivery: this.deliveryTarget(),
524
550
  })
525
551
  const messageId = randomUUID()
526
- this.expectCheck(messageId)
527
552
  const archive = target.kind !== 'session' && settings.autoArchive && this.settle !== undefined ? { archive: 'pending' } : {}
528
553
  const fresh = target.kind === 'new'
529
554
  const sent = await this.sendToTarget(original.sessionId, text, {
@@ -533,7 +558,6 @@ export class JobRunner {
533
558
  messageId,
534
559
  fields: fresh ? { reused: true, sessionOpenedAt: original.sessionOpenedAt ?? original.startedAt } : { targeted: true },
535
560
  })
536
- if (sent.status !== 'woke') this.checks?.forget(messageId)
537
561
  return sent.status === 'woke' ? { ...sent, messageId } : sent
538
562
  }
539
563
 
@@ -554,14 +578,6 @@ export class JobRunner {
554
578
  }
555
579
  }
556
580
 
557
- /** Have the answer to this prompt checked before its turn closes, when the job names a check. */
558
- expectCheck(messageId) {
559
- const command = this.job.agent?.answerCheck
560
- if (!command || this.checks === undefined) return
561
- const cwd = agentSettings(this.job, this.defaults).cwd
562
- this.checks.expect(messageId, { job: this.job.name, jobId: jobKey(this.job), command, ...(cwd ? { cwd } : {}) })
563
- }
564
-
565
581
  /** Send the prompt to the target session, a reused one, or a new one. */
566
582
  async deliverPrompt({ job, target, text, messageId, settings, firedAt, localTime }) {
567
583
  const { logger } = this
package/src/session.js CHANGED
@@ -9,10 +9,11 @@ import { finalAnswer } from './deliver.js'
9
9
  * follow-up (which starts a turn), and wait until session persistence has
10
10
  * stored the message.
11
11
  *
12
- * Uses only public Host services, read with `ctx.get()` so that hosts
13
- * without them still run plain jobs:
14
- * `sessionController` (required), `sessions` (required), `agents`,
15
- * `workspaceRegistry`, `sessionTitle`, `llm` (optional).
12
+ * Uses only public Host services, so that hosts without them still run
13
+ * plain jobs: `sessionController` and `sessions` (required), `agents`,
14
+ * `workspaceRegistry`, `sessionTitle`, and `llm` when a model is requested.
15
+ * Every one is read through {@link sessionServices}, which waits for a
16
+ * service the host has not registered yet (a run right after a DSH start).
16
17
  *
17
18
  * A requested model is checked with `llm.resolveCallConfig()` before the
18
19
  * session is created, then set on the new session's agent with
@@ -30,16 +31,19 @@ import { finalAnswer } from './deliver.js'
30
31
  * @param {string} [request.cwd] - Session directory; the host default when omitted.
31
32
  * @param {{ provider: string, model: string, reasoningEffort?: string }} [request.model] - Model of the session; the preset or host default when omitted.
32
33
  * @param {{ warn: Function }} logger
34
+ * @param {ServiceWait} [wait]
33
35
  * @returns {Promise<string>} The new session id.
34
36
  */
35
- export async function openAgentSession(ctx, { text, messageId, principal, title, agentPreset, cwd, model }, logger) {
36
- const controller = ctx.get('sessionController')
37
- const sessions = ctx.get('sessions')
37
+ export async function openAgentSession(ctx, { text, messageId, principal, title, agentPreset, cwd, model }, logger, wait = {}) {
38
+ const { sessionController: controller, sessions, agents, workspaceRegistry, sessionTitle, llm } = await sessionServices(ctx, {
39
+ required: ['sessionController', 'sessions', ...(model !== undefined ? ['llm'] : [])],
40
+ optional: ['agents', 'workspaceRegistry', 'sessionTitle'],
41
+ }, wait)
38
42
  if (controller === undefined || sessions === undefined) {
39
43
  throw new Error('this host cannot create sessions (no sessionController service)')
40
44
  }
41
45
  const open = async () => {
42
- if (model !== undefined) await checkModel(ctx, model)
46
+ if (model !== undefined) await checkModel(llm, model)
43
47
  const { sessionId } = await controller.create({
44
48
  ...(cwd ? { cwd } : {}),
45
49
  ...(agentPreset ? { agentPreset } : {}),
@@ -49,8 +53,8 @@ export async function openAgentSession(ctx, { text, messageId, principal, title,
49
53
  const { agent } = resolved
50
54
  if (model !== undefined) agent.model.select({ ...model })
51
55
 
52
- await joinWorkspace(ctx, sessionId, cwd, logger)
53
- nameSession(ctx, agent, title, logger)
56
+ await joinWorkspace(workspaceRegistry, sessionId, cwd, logger)
57
+ nameSession(sessionTitle, agent, title, logger)
54
58
 
55
59
  agent.followup(userMessage(text, messageId, principal))
56
60
  if (!await sessions.flush(agent.session)) {
@@ -60,7 +64,6 @@ export async function openAgentSession(ctx, { text, messageId, principal, title,
60
64
  }
61
65
  // A timer callback has no initiating agent; clearing it anyway keeps the new
62
66
  // session a top-level session rather than a child of whatever is running.
63
- const agents = ctx.get('agents')
64
67
  return agents === undefined ? open() : agents.withoutInitiator(open)
65
68
  }
66
69
 
@@ -87,12 +90,15 @@ export async function openAgentSession(ctx, { text, messageId, principal, title,
87
90
  * @param {object} [request.principal] - Who sends the message, recorded on its source.
88
91
  * @param {boolean} [request.mayUnarchive]
89
92
  * @param {boolean} [request.ignoreHold] - Deliver even to a pinned session or one a person uses.
93
+ * @param {ServiceWait} [wait]
90
94
  * @returns {Promise<{ sessionId: string, queued: boolean, unarchived: boolean }>}
91
95
  * `queued`: the session was busy and the message waits for its next turn.
92
96
  */
93
- export async function deliverToSession(ctx, { sessionId, text, messageId, principal, mayUnarchive = false, ignoreHold = false }) {
94
- const controller = ctx.get('sessionController')
95
- const sessions = ctx.get('sessions')
97
+ export async function deliverToSession(ctx, { sessionId, text, messageId, principal, mayUnarchive = false, ignoreHold = false }, wait = {}) {
98
+ const { sessionController: controller, sessions, agents, workspaceRegistry: registry } = await sessionServices(ctx, {
99
+ required: ['sessionController', 'sessions'],
100
+ optional: ['agents', 'workspaceRegistry'],
101
+ }, wait)
96
102
  if (controller === undefined || sessions === undefined) {
97
103
  throw new Error('this host cannot resume sessions (no sessionController service)')
98
104
  }
@@ -100,9 +106,8 @@ export async function deliverToSession(ctx, { sessionId, text, messageId, princi
100
106
  const resolved = await controller.resolveAgent(sessionId)
101
107
  if ('error' in resolved) throw resolved.error
102
108
  const { agent } = resolved
103
- const hold = ignoreHold ? undefined : userHold(ctx, sessionId, agent.session)
109
+ const hold = ignoreHold ? undefined : userHold(registry, sessionId, agent.session)
104
110
  if (hold !== undefined) throw new Error(`the session is in use (${hold})`)
105
- const registry = ctx.get('workspaceRegistry')
106
111
  const archived = registry?.archivedSessionIds?.includes(sessionId) === true
107
112
  if (archived) {
108
113
  if (!mayUnarchive) throw new Error('the session is archived')
@@ -115,7 +120,6 @@ export async function deliverToSession(ctx, { sessionId, text, messageId, princi
115
120
  }
116
121
  return { sessionId, queued, unarchived: archived }
117
122
  }
118
- const agents = ctx.get('agents')
119
123
  return agents === undefined ? deliver() : agents.withoutInitiator(deliver)
120
124
  }
121
125
 
@@ -128,13 +132,13 @@ export async function deliverToSession(ctx, { sessionId, text, messageId, princi
128
132
  * results) have their own kinds. Such a session is neither archived nor
129
133
  * reused.
130
134
  *
131
- * @param {import('@deepseek-ai/cordis').Context} ctx
135
+ * @param {{ pinnedSessionIds?: string[] } | undefined} registry - The Workspace registry, when the host has one.
132
136
  * @param {string} sessionId
133
137
  * @param {{ log?: Array<{ type: string, data?: any }> }} [session] - The live session, to read its message log.
134
138
  * @returns {string | undefined}
135
139
  */
136
- export function userHold(ctx, sessionId, session) {
137
- if (ctx.get('workspaceRegistry')?.pinnedSessionIds?.includes(sessionId)) return 'pinned'
140
+ export function userHold(registry, sessionId, session) {
141
+ if (registry?.pinnedSessionIds?.includes(sessionId)) return 'pinned'
138
142
  if (session?.log?.some(event => event.type === 'user/message' && event.data?.source?.kind === 'user')) {
139
143
  return 'taken over by a person'
140
144
  }
@@ -189,7 +193,7 @@ export async function archiveWhenIdle(ctx, sessionId, {
189
193
  if (turnCutByShutdown(agent.session?.log ?? [])) return { archive: 'kept', note: 'its turn was cut off by a DSH stop' }
190
194
  const result = await lock(async () => {
191
195
  if (!isLatest()) return { archive: 'superseded' }
192
- const hold = userHold(ctx, sessionId, agent.session)
196
+ const hold = userHold(registry, sessionId, agent.session)
193
197
  if (hold !== undefined) return { archive: 'kept', note: hold }
194
198
  try {
195
199
  await registry.archiveSession(sessionId)
@@ -280,6 +284,38 @@ export async function hostService(ctx, name, { signal, waitMs = SERVICE_WAIT_MS,
280
284
  }
281
285
  }
282
286
 
287
+ /** How long an optional service is waited for once the required ones are there. */
288
+ export const OPTIONAL_SERVICE_WAIT_MS = 10_000
289
+
290
+ /**
291
+ * @typedef {object} ServiceWait
292
+ * @property {AbortSignal} [signal] - Plugin unload: stop waiting.
293
+ * @property {number} [waitMs] - Wait for a required service; {@link SERVICE_WAIT_MS} by default.
294
+ * @property {number} [optionalWaitMs] - Wait for an optional one after that; {@link OPTIONAL_SERVICE_WAIT_MS} by default.
295
+ * @property {number} [pollMs]
296
+ */
297
+
298
+ /**
299
+ * Read the Host services a session path needs, waiting for them the way
300
+ * {@link hostService} does: a job that fires while DSH is still starting
301
+ * (a catch-up run, an event from a watcher) would otherwise find no
302
+ * `sessionController` and fail (2026-11-16, a check-in's catch-up run ten
303
+ * seconds after a restart). Required services are waited for fully; optional
304
+ * ones, which come from other plugins of the same start, a short time more,
305
+ * so a host that lacks one still runs jobs without a long delay.
306
+ *
307
+ * @param {import('@deepseek-ai/cordis').Context} ctx
308
+ * @param {{ required: string[], optional?: string[] }} names
309
+ * @param {ServiceWait} [wait]
310
+ * @returns {Promise<Record<string, any>>} Each name mapped to its service, or undefined.
311
+ */
312
+ export async function sessionServices(ctx, { required, optional = [] }, { signal, waitMs = SERVICE_WAIT_MS, optionalWaitMs = OPTIONAL_SERVICE_WAIT_MS, pollMs } = {}) {
313
+ const read = (names, ms) => Promise.all(names.map(name => hostService(ctx, name, { signal, waitMs: ms, ...(pollMs !== undefined ? { pollMs } : {}) })))
314
+ const found = await read(required, waitMs)
315
+ const extra = await read(optional, found.every(service => service !== undefined) ? optionalWaitMs : 0)
316
+ return Object.fromEntries([...required, ...optional].map((name, i) => [name, i < found.length ? found[i] : extra[i - found.length]]))
317
+ }
318
+
283
319
  function sleep(ms, signal) {
284
320
  return new Promise((resolve) => {
285
321
  const timer = setTimeout(done, ms)
@@ -317,8 +353,7 @@ export function userMessage(text, id = randomUUID(), principal) {
317
353
  }
318
354
 
319
355
  /** Reject a model the host cannot route, before any session is created. */
320
- async function checkModel(ctx, model) {
321
- const llm = ctx.get('llm')
356
+ async function checkModel(llm, model) {
322
357
  if (llm === undefined) throw new Error('this host cannot select models (no llm service)')
323
358
  try {
324
359
  await llm.resolveCallConfig({ ...model })
@@ -328,8 +363,7 @@ async function checkModel(ctx, model) {
328
363
  }
329
364
  }
330
365
 
331
- async function joinWorkspace(ctx, sessionId, cwd, logger) {
332
- const registry = ctx.get('workspaceRegistry')
366
+ async function joinWorkspace(registry, sessionId, cwd, logger) {
333
367
  if (registry === undefined || !cwd) return
334
368
  try {
335
369
  await (await registry.resolveByPath(cwd))?.attachSession(sessionId)
@@ -338,8 +372,7 @@ async function joinWorkspace(ctx, sessionId, cwd, logger) {
338
372
  }
339
373
  }
340
374
 
341
- function nameSession(ctx, agent, title, logger) {
342
- const titles = ctx.get('sessionTitle')
375
+ function nameSession(titles, agent, title, logger) {
343
376
  if (titles === undefined) return
344
377
  try {
345
378
  titles.rename(agent.session, title)
package/src/store.js CHANGED
@@ -32,8 +32,6 @@ 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(),
37
35
  // Omitted for a job that runs only on events.
38
36
  schedule: scheduleSchema.optional(),
39
37
  // Channel patterns whose events start a run (events.js).
package/src/watchers.js CHANGED
@@ -81,7 +81,7 @@ export class WatcherSupervisor {
81
81
  * @param {(event: object) => void} options.emit - Receives each event.
82
82
  * @param {{ info: Function, warn: Function }} options.logger
83
83
  * @param {(entry: object) => Promise<void>} [options.record] - Run log.
84
- * @param {(text: string, watcher: object) => Promise<void>} [options.notify] - Sends a down or back-up note.
84
+ * @param {(text: string, watcher: object, kind: 'watcher-down' | 'watcher-up') => Promise<void>} [options.notify] - Sends a down or back-up note.
85
85
  * @param {(id: string) => Promise<void>} [options.onDone] - A once watcher finished.
86
86
  * @param {string} [options.stateRoot] - Each watcher gets `<stateRoot>/<id>` as DSH_CRON_STATE_DIR.
87
87
  * @param {() => number} [options.now]
@@ -270,7 +270,7 @@ class Watcher {
270
270
  if (wasDown && this.alerted) {
271
271
  this.alerted = false
272
272
  sup.record({ time: new Date(sup.now()).toISOString(), job: null, event: 'watcher-up', watcher: def.id })
273
- sup.notify(`✅ Watcher ${def.id} (${def.channel}) works again.`, def).catch(() => {})
273
+ sup.notify(`✅ Watcher ${def.id} (${def.channel}) works again.`, def, 'watcher-up').catch(() => {})
274
274
  }
275
275
  }
276
276
 
@@ -324,7 +324,7 @@ class Watcher {
324
324
  // The last run's, not this.stderr: a restarted run may be going already, with its own empty tail.
325
325
  const stderr = (exit?.stderrTail ?? '').slice(-300)
326
326
  sup.record({ time: new Date(sup.now()).toISOString(), job: null, event: 'watcher-down', watcher: def.id, downMs: sup.now() - this.downSince })
327
- sup.notify(`⚠️ Watcher ${def.id} (${def.channel}) has been down for ${minutes} min (${this.restarts} restarts, last: ${how})${stderr ? `: ${stderr}` : ''}. Jobs on this channel only run on their schedule until it is back.`, def).catch(() => {})
327
+ sup.notify(`⚠️ Watcher ${def.id} (${def.channel}) has been down for ${minutes} min (${this.restarts} restarts, last: ${how})${stderr ? `: ${stderr}` : ''}. Jobs on this channel only run on their schedule until it is back.`, def, 'watcher-down').catch(() => {})
328
328
  }
329
329
 
330
330
  async stop() {
package/tools.js CHANGED
@@ -43,7 +43,6 @@ 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].' },
47
46
  cwd: { type: 'string', description: 'Working directory of the command and of new sessions; defaults to this session\'s.' },
48
47
  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.' },
49
48
  on: {
@@ -107,7 +106,6 @@ export function toolSchemas(prefix) {
107
106
  command: { ...fields.command, description: 'New command; an empty string removes it.' },
108
107
  prompt_replace: replacements('prompt'),
109
108
  command_replace: replacements('command'),
110
- answerCheck: { ...fields.answerCheck, description: 'New answer check command; an empty string removes it.' },
111
109
  cron: { ...schedule.cron, description: `${schedule.cron.description} An empty cron, rrule or at removes the schedule of a job with on.` },
112
110
  rrule: schedule.rrule,
113
111
  at: schedule.at,
@@ -163,7 +161,6 @@ export function createTools({ prefix = 'cron_job', getJobs, ctx }) {
163
161
  title: args.title,
164
162
  prompt: args.prompt,
165
163
  command: args.command,
166
- answerCheck: args.answerCheck,
167
164
  schedule: { cron: args.cron, rrule: args.rrule, at: args.at, timeZone: args.timeZone },
168
165
  ...(args.on !== undefined ? { on: args.on } : {}),
169
166
  ...(args.once !== undefined ? { once: args.once } : {}),
@@ -180,7 +177,7 @@ export function createTools({ prefix = 'cron_job', getJobs, ctx }) {
180
177
  `Update, pause, resume or delete one job created with ${prefix}_create, by id. Jobs from the plugin config are read-only.`,
181
178
  async (args, jobs, agent) => {
182
179
  const { id, action } = args
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)
180
+ const changes = ['title', 'prompt', 'command', 'prompt_replace', 'command_replace', 'cron', 'rrule', 'at', 'timeZone', 'target', 'sessionId', 'cwd', 'deliver', 'model', 'on', 'once', 'coalesceSeconds'].filter(key => args[key] !== undefined)
184
181
  if (action !== 'update' && changes.length > 0) return failure('invalid_arguments', `${action} takes only id and action.`)
185
182
  if (action === 'delete') return await jobs.remove(id)
186
183
  if (action === 'pause' || action === 'resume') {
@@ -206,7 +203,6 @@ export function createTools({ prefix = 'cron_job', getJobs, ctx }) {
206
203
  title: args.title,
207
204
  prompt: args.prompt,
208
205
  command: args.command,
209
- answerCheck: args.answerCheck,
210
206
  cwd: args.cwd,
211
207
  on: args.on,
212
208
  once: args.once,
@@ -364,7 +360,7 @@ export function modelJob(job, { brief = false } = {}) {
364
360
  ...(job.agent?.model ? { model: job.agent.model } : {}),
365
361
  deliver: job.deliver?.via ? (job.deliver.to ? `${job.deliver.via}:${job.deliver.to}` : job.deliver.via) : 'none',
366
362
  ...(brief ? {} : {
367
- ...(job.agent ? { prompt: job.agent.prompt, preset: job.agent.preset, sessionCwd: job.agent.cwd, ...(job.agent.answerCheck ? { answerCheck: job.agent.answerCheck } : {}) } : {}),
363
+ ...(job.agent ? { prompt: job.agent.prompt, preset: job.agent.preset, sessionCwd: job.agent.cwd } : {}),
368
364
  ...(job.command ? { command: job.command, cwd: job.cwd } : {}),
369
365
  ...(job.createdBy ? { createdBy: job.createdBy } : {}),
370
366
  }),
@@ -1,159 +0,0 @@
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, jobId?: 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, jobId?: string, command: string, cwd?: string }} options
84
- */
85
- expect(messageId, { job, jobId, 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, ...(jobId ? { jobId } : {}), 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(), { kind: 'cron-job', channel: 'cron', id: entry.jobId ?? entry.job, name: entry.job, trigger: 'answer-check' }))
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
- }