@soffits/dsh-cron-jobs 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -92,7 +92,7 @@ Config jobs live in the config of the `cron-jobs` row. Add an override to your p
92
92
  |---|---|
93
93
  | `name` | Job name, used in logs and session titles. Must be unique. |
94
94
  | `cron` | Cron expression: 5 fields, or 6 with seconds first. Parsed by [croner](https://github.com/hexagon/croner), which handles daylight-saving changes like Vixie cron: a fixed time skipped by a spring forward runs at the first valid time after the gap, a fixed time repeated by a fall back runs once, and patterns with several hours, minutes or seconds run on both repeated occurrences. Set exactly one of `cron`, `rrule` and `at`, or none when the job has `on`. |
95
- | `on` | Event channel patterns that start a run, such as `[mail.sakina, alerts.*]`. See [Events](#events). |
95
+ | `on` | Event channel patterns that start a run, such as `[mail.inbox, alerts.*]`. See [Events](#events). |
96
96
  | `rrule` | RFC 5545 schedule: a `DTSTART` line and an `RRULE` line. The time zone comes from `DTSTART` (`TZID=...`, or `Z` for UTC). See [Schedules](#schedules). |
97
97
  | `at` | Run once at this time: ISO 8601 with an offset, or a local date-time read in `timeZone`. |
98
98
  | `timeZone` | IANA time zone for the cron expression or an `at` without offset. The Host's zone when empty. |
@@ -181,6 +181,16 @@ Use it for checks that are cheap to script and costly to miss, such as the answe
181
181
 
182
182
  It works on DSH's `agent/turn-stopping` hook: a listener that steers a message there makes the agent loop run one more step in the same turn.
183
183
 
184
+ ### Who sent a prompt
185
+
186
+ Every prompt a job puts into a session has the source kind `schedule`, which the Web GUI shows as a scheduled run, and names the job as `principal`, the field DSH uses for the caller behind a user message:
187
+
188
+ ```js
189
+ { kind: 'cron-job', channel: 'cron', id, name, trigger, events }
190
+ ```
191
+
192
+ `id` is the job's id (its name for a config job), `name` its name, `trigger` what started the run (`schedule`, `manual`, `event`, `rerun`, or `answer-check` for an answer check's rewrite request), and `events` the channels of the events that started an event run. Scripts that read session logs can tell job prompts apart, and which job sent each, without parsing the text.
193
+
184
194
  ### Delivery channels
185
195
 
186
196
  A delivery target is `{ via, to }`: `via` names a DSH service, `to` is an address that service understands (a chat topic, a mailbox, a webhook name; it can be empty). When a result is ready, the plugin looks the service up by name with `ctx.get(via)` and calls:
@@ -192,6 +202,7 @@ await service.send({
192
202
  files, // string[]: absolute file paths
193
203
  from: {
194
204
  job, // string: the job's name
205
+ jobId, // string: the job's id (its name for a config job)
195
206
  sessionId, // string, agent and gated jobs only: the session that wrote the answer
196
207
  },
197
208
  })
@@ -13,7 +13,7 @@ import { enqueueEvent, waitForEventResult } from '../src/spool.js'
13
13
  const usage = `Usage: dsh-cron-event <channel> [--data <json> | --data - | --text <text>]
14
14
  [--id <dedupe key>] [--source <label>] [--no-wait] [--timeout <seconds>]
15
15
 
16
- Emits one event on <channel> (dot-separated names, such as mail.sakina or
16
+ Emits one event on <channel> (dot-separated names, such as mail.inbox or
17
17
  ci.run.123). Jobs whose on patterns match it run once the events around it are
18
18
  gathered (about 30 s). The event is a hint: jobs check the source themselves.
19
19
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-cron-jobs",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Scheduled jobs for DeepSeek Harness: shell commands and agent prompts on cron, RRULE or one-time schedules, a gate that wakes an agent only when there is something to do, result delivery through any plugin that can send messages, tools to manage jobs from a conversation, and a Cron tasks page in the Web GUI.",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -67,7 +67,7 @@ export function checkable(text) {
67
67
  * @param {() => Date} [deps.now]
68
68
  */
69
69
  export function createAnswerChecks({ run, logger, record = async () => {}, now = () => new Date() }) {
70
- /** @type {Map<string, { job: string, command: string, cwd?: string, at: number, steered: boolean, verdict?: string }>} */
70
+ /** @type {Map<string, { job: string, jobId?: string, command: string, cwd?: string, at: number, steered: boolean, verdict?: string }>} */
71
71
  const pending = new Map()
72
72
 
73
73
  async function check(entry, text, signal) {
@@ -80,12 +80,12 @@ export function createAnswerChecks({ run, logger, record = async () => {}, now =
80
80
  /**
81
81
  * Check the answer to this prompt before its turn closes.
82
82
  * @param {string} messageId
83
- * @param {{ job: string, command: string, cwd?: string }} options
83
+ * @param {{ job: string, jobId?: string, command: string, cwd?: string }} options
84
84
  */
85
- expect(messageId, { job, command, cwd }) {
85
+ expect(messageId, { job, jobId, command, cwd }) {
86
86
  const at = now().getTime()
87
87
  for (const [id, entry] of pending) if (at - entry.at > ANSWER_CHECK_TTL_MS) pending.delete(id)
88
- pending.set(messageId, { job, command, ...(cwd ? { cwd } : {}), at, steered: false })
88
+ pending.set(messageId, { job, ...(jobId ? { jobId } : {}), command, ...(cwd ? { cwd } : {}), at, steered: false })
89
89
  },
90
90
 
91
91
  /** Stop watching a prompt; returns what its check did ('steered', 'passed', 'error' or undefined). */
@@ -130,7 +130,7 @@ export function createAnswerChecks({ run, logger, record = async () => {}, now =
130
130
  entry.verdict = 'steered'
131
131
  logger.info('[%s] answer check asked for a rewrite', entry.job)
132
132
  await record({ ...line, status: 'steered', request: outcome.request })
133
- agent.steer(userMessage(outcome.request, randomUUID()))
133
+ agent.steer(userMessage(outcome.request, randomUUID(), { kind: 'cron-job', channel: 'cron', id: entry.jobId ?? entry.job, name: entry.job, trigger: 'answer-check' }))
134
134
  }
135
135
  return
136
136
  }
package/src/config.js CHANGED
@@ -34,7 +34,7 @@ const Job = z.object({
34
34
  rrule: z.string().role('textarea').description('RFC 5545 schedule: a DTSTART line and an RRULE line, such as "DTSTART;TZID=Europe/Berlin:20260901T080000" and "RRULE:FREQ=WEEKLY;BYDAY=MO". The zone comes from DTSTART.'),
35
35
  at: z.string().description('Run once at this time: ISO 8601 with an offset, or a local date-time read in timeZone.'),
36
36
  timeZone: z.string().description('IANA time zone for the cron expression or an at without offset, such as Europe/Berlin. The host zone when empty (an at without offset needs it).'),
37
- on: z.array(z.string()).default([]).description('Event channels that start a run, such as mail.sakina or alerts.* (* matches any characters). Events arriving close together run the job once; the gate command gets them as JSON on stdin and the prompt gets them appended. Keep a slower schedule as a safety net.'),
37
+ on: z.array(z.string()).default([]).description('Event channels that start a run, such as mail.inbox or alerts.* (* matches any characters). Events arriving close together run the job once; the gate command gets them as JSON on stdin and the prompt gets them appended. Keep a slower schedule as a safety net.'),
38
38
  command: z.string().role('textarea').description('Shell command, run with bash (or sh when bash is missing). Leave empty for an agent-only job, which sends agent.prompt at every run.'),
39
39
  cwd: z.string().description('Working directory of the command. The host process directory when empty.'),
40
40
  timeoutSeconds: z.natural().default(DEFAULT_TIMEOUT_SECONDS)
@@ -46,7 +46,7 @@ const Job = z.object({
46
46
 
47
47
  const Watcher = z.object({
48
48
  id: z.string().required().description('Watcher id (letters, digits, _ . -), shown in logs and alerts.'),
49
- channel: z.string().required().description('Channel each output line is emitted on, such as mail.sakina.'),
49
+ channel: z.string().required().description('Channel each output line is emitted on, such as mail.inbox.'),
50
50
  command: z.string().role('textarea').required().description('Long-running shell command, run with bash. Each stdout line is an event: a JSON object line is its data, any other line its text; {"wakeAgent": false} lines are ignored. It is restarted with backoff when it exits.'),
51
51
  cwd: z.string().description('Working directory. The host process directory when empty.'),
52
52
  enabled: z.boolean().default(true).description('Run this watcher.'),
package/src/events.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * job reads the truth from its source, so a lost or forged event costs at
5
5
  * most one missed or wasted run (the job's schedule is the safety net).
6
6
  *
7
- * - Channels are dot-separated names such as `mail.sakina` or `dsh.started`.
7
+ * - Channels are dot-separated names such as `mail.inbox` or `dsh.started`.
8
8
  * - A job's `on` lists channel patterns; `*` matches one or more characters
9
9
  * of any kind, dots included (`mail.*` matches `mail.icloud.inbox`).
10
10
  * - An event may carry a dedupe key: a second event with the same channel and
package/src/job.js CHANGED
@@ -284,7 +284,7 @@ export class JobRunner {
284
284
  */
285
285
  async deliverMessage(target, message, { sessionId, waitMs, onWait }) {
286
286
  const { job, logger } = this
287
- const sent = await this.send(target, message, { job: job.name, ...(sessionId ? { sessionId } : {}) }, {
287
+ const sent = await this.send(target, message, { job: job.name, jobId: jobKey(job), ...(sessionId ? { sessionId } : {}) }, {
288
288
  ...(waitMs !== undefined ? { waitMs } : {}), ...(onWait ? { onWait } : {}),
289
289
  })
290
290
  const where = describeTarget(target)
@@ -539,12 +539,29 @@ export class JobRunner {
539
539
  return sent.status === 'woke' ? { ...sent, messageId } : sent
540
540
  }
541
541
 
542
+ /**
543
+ * Who sends this run's prompt, recorded as `source.principal` on it: the
544
+ * job, what started the run, and the event channels of an event run.
545
+ * @returns {{ kind: 'cron-job', channel: 'cron', id: string, name: string, trigger: string, events?: string[] }}
546
+ */
547
+ promptPrincipal() {
548
+ const { job, current } = this
549
+ return {
550
+ kind: 'cron-job',
551
+ channel: 'cron',
552
+ id: jobKey(job),
553
+ name: job.name,
554
+ trigger: current?.rerunOf ? 'rerun' : current?.trigger ?? 'schedule',
555
+ ...(current?.events?.channels?.length ? { events: [...current.events.channels] } : {}),
556
+ }
557
+ }
558
+
542
559
  /** Have the answer to this prompt checked before its turn closes, when the job names a check. */
543
560
  expectCheck(messageId) {
544
561
  const command = this.job.agent?.answerCheck
545
562
  if (!command || this.checks === undefined) return
546
563
  const cwd = agentSettings(this.job, this.defaults).cwd
547
- this.checks.expect(messageId, { job: this.job.name, command, ...(cwd ? { cwd } : {}) })
564
+ this.checks.expect(messageId, { job: this.job.name, jobId: jobKey(this.job), command, ...(cwd ? { cwd } : {}) })
548
565
  }
549
566
 
550
567
  /** Send the prompt to the target session, a reused one, or a new one. */
@@ -564,7 +581,7 @@ export class JobRunner {
564
581
  if (previous !== undefined) {
565
582
  try {
566
583
  const sent = await this.withSessionLock(previous.sessionId, async () => {
567
- const delivered = await this.reuse({ sessionId: previous.sessionId, text, messageId, mayUnarchive: settings.autoArchive })
584
+ const delivered = await this.reuse({ sessionId: previous.sessionId, text, messageId, principal: this.promptPrincipal(), mayUnarchive: settings.autoArchive })
568
585
  // Inside the lock, so an earlier run's archive wait sees it was superseded.
569
586
  this.latestRun.set(previous.sessionId, null)
570
587
  return delivered
@@ -587,6 +604,7 @@ export class JobRunner {
587
604
  const opened = await this.wake({
588
605
  text,
589
606
  messageId,
607
+ principal: this.promptPrincipal(),
590
608
  title: sessionTitle(job.name, localTime),
591
609
  ...(job.agent.preset ? { agentPreset: job.agent.preset } : {}),
592
610
  ...(agentModel(job) ? { model: agentModel(job) } : {}),
@@ -631,7 +649,7 @@ export class JobRunner {
631
649
  if (this.reuse === undefined) return { status: 'wake-failed', error: 'this host cannot deliver to existing sessions' }
632
650
  try {
633
651
  const sent = await this.withSessionLock(sessionId, async () => {
634
- const delivered = await this.reuse({ sessionId, text, messageId, mayUnarchive, ignoreHold })
652
+ const delivered = await this.reuse({ sessionId, text, messageId, principal: this.promptPrincipal(), mayUnarchive, ignoreHold })
635
653
  this.latestRun.set(sessionId, null)
636
654
  return delivered
637
655
  })
package/src/session.js CHANGED
@@ -24,6 +24,7 @@ import { finalAnswer } from './deliver.js'
24
24
  * @param {object} request
25
25
  * @param {string} request.text - Message text.
26
26
  * @param {string} [request.messageId] - Id of the message, so its answer can be found later.
27
+ * @param {object} [request.principal] - Who sends the message, recorded on its source.
27
28
  * @param {string} request.title - Session title.
28
29
  * @param {string} [request.agentPreset] - Agent preset id; the host default when omitted.
29
30
  * @param {string} [request.cwd] - Session directory; the host default when omitted.
@@ -31,7 +32,7 @@ import { finalAnswer } from './deliver.js'
31
32
  * @param {{ warn: Function }} logger
32
33
  * @returns {Promise<string>} The new session id.
33
34
  */
34
- export async function openAgentSession(ctx, { text, messageId, title, agentPreset, cwd, model }, logger) {
35
+ export async function openAgentSession(ctx, { text, messageId, principal, title, agentPreset, cwd, model }, logger) {
35
36
  const controller = ctx.get('sessionController')
36
37
  const sessions = ctx.get('sessions')
37
38
  if (controller === undefined || sessions === undefined) {
@@ -51,7 +52,7 @@ export async function openAgentSession(ctx, { text, messageId, title, agentPrese
51
52
  await joinWorkspace(ctx, sessionId, cwd, logger)
52
53
  nameSession(ctx, agent, title, logger)
53
54
 
54
- agent.followup(userMessage(text, messageId))
55
+ agent.followup(userMessage(text, messageId, principal))
55
56
  if (!await sessions.flush(agent.session)) {
56
57
  throw new Error('session persistence did not acknowledge the message')
57
58
  }
@@ -83,12 +84,13 @@ export async function openAgentSession(ctx, { text, messageId, title, agentPrese
83
84
  * @param {string} request.sessionId
84
85
  * @param {string} request.text
85
86
  * @param {string} [request.messageId] - Id of the message, so its answer can be found later.
87
+ * @param {object} [request.principal] - Who sends the message, recorded on its source.
86
88
  * @param {boolean} [request.mayUnarchive]
87
89
  * @param {boolean} [request.ignoreHold] - Deliver even to a pinned session or one a person uses.
88
90
  * @returns {Promise<{ sessionId: string, queued: boolean, unarchived: boolean }>}
89
91
  * `queued`: the session was busy and the message waits for its next turn.
90
92
  */
91
- export async function deliverToSession(ctx, { sessionId, text, messageId, mayUnarchive = false, ignoreHold = false }) {
93
+ export async function deliverToSession(ctx, { sessionId, text, messageId, principal, mayUnarchive = false, ignoreHold = false }) {
92
94
  const controller = ctx.get('sessionController')
93
95
  const sessions = ctx.get('sessions')
94
96
  if (controller === undefined || sessions === undefined) {
@@ -107,7 +109,7 @@ export async function deliverToSession(ctx, { sessionId, text, messageId, mayUna
107
109
  await registry.unarchiveSession(sessionId)
108
110
  }
109
111
  const queued = agent.status !== undefined && agent.status !== 'idle'
110
- agent.followup(userMessage(text, messageId))
112
+ agent.followup(userMessage(text, messageId, principal))
111
113
  if (!await sessions.flush(agent.session)) {
112
114
  throw new Error('session persistence did not acknowledge the message')
113
115
  }
@@ -283,14 +285,19 @@ function describe(error) {
283
285
 
284
286
  /**
285
287
  * A user-role message from a scheduled source. `kind: 'schedule'` makes the
286
- * Web GUI show it as a scheduled run.
288
+ * Web GUI show it as a scheduled run. `principal`, DSH's field for the caller
289
+ * behind a user message, names the job that sent it (see
290
+ * `JobRunner.promptPrincipal`), so session readers need not parse the text.
291
+ * @param {string} text
292
+ * @param {string} [id]
293
+ * @param {object} [principal]
287
294
  */
288
- export function userMessage(text, id = randomUUID()) {
295
+ export function userMessage(text, id = randomUUID(), principal) {
289
296
  return deepFreeze({
290
297
  id,
291
298
  role: 'user',
292
299
  content: [{ type: 'text', text }],
293
- source: { kind: 'schedule' },
300
+ source: { kind: 'schedule', ...(principal ? { principal: { ...principal } } : {}) },
294
301
  })
295
302
  }
296
303
 
package/tools.js CHANGED
@@ -49,7 +49,7 @@ export function toolSchemas(prefix) {
49
49
  on: {
50
50
  type: 'array',
51
51
  items: { type: 'string' },
52
- description: `Event channels that start a run, with * for any characters (mail.sakina, ci.*, dsh.started). Events come from \`dsh-cron-event <channel>\` (any script or hook), from watchers (${prefix}_watch), and dsh.started once after each DSH start. Events within about 30 s run the job once; the command gets them as JSON on stdin and the prompt gets them appended as untrusted data. A job with on may leave out the schedule; keep a slower one as a safety net when events can be missed.`,
52
+ description: `Event channels that start a run, with * for any characters (mail.inbox, ci.*, dsh.started). Events come from \`dsh-cron-event <channel>\` (any script or hook), from watchers (${prefix}_watch), and dsh.started once after each DSH start. Events within about 30 s run the job once; the command gets them as JSON on stdin and the prompt gets them appended as untrusted data. A job with on may leave out the schedule; keep a slower one as a safety net when events can be missed.`,
53
53
  },
54
54
  once: { type: 'boolean', description: 'End the job after its first run that was not started by hand (an event or a scheduled run). With on: dsh.started, it waits for the next DSH start.' },
55
55
  }
@@ -75,7 +75,7 @@ export function toolSchemas(prefix) {
75
75
  watch: object({
76
76
  action: { type: 'string', enum: ['create', 'delete', 'list'], description: 'create starts a new watcher; delete stops and removes one; list shows every watcher with its state.' },
77
77
  id: { type: 'string', description: 'Watcher id: letters, digits, _ . - (create, delete).' },
78
- channel: { type: 'string', description: 'Channel its output lines are emitted on, such as mail.sakina (create).' },
78
+ channel: { type: 'string', description: 'Channel its output lines are emitted on, such as mail.inbox (create).' },
79
79
  command: { type: 'string', description: 'Shell command run with bash that keeps running and prints one line per change (create). A JSON object line is the event\'s data (its "id" field dedupes), any other line its text; {"wakeAgent": false} lines are ignored. It is restarted with backoff when it exits; down for 15 minutes sends one alert. It gets DSH_CRON_STATE_DIR, a directory for its cursor, so it can catch up after a restart.' },
80
80
  cwd: { type: 'string', description: 'Working directory; defaults to this session\'s (create).' },
81
81
  once: { type: 'boolean', description: 'Run the command one time and remove the watcher when it exits, for a one-off wait such as `gh run watch 123 --exit-status >/dev/null; echo "{\\"exit\\": $?}"` (create).' },