@soffits/dsh-cron-jobs 0.6.1 → 0.7.1
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 +14 -3
- package/client.js +3 -3
- package/index.js +11 -3
- package/package.json +1 -1
- package/src/answer-check.js +159 -0
- package/src/command.js +10 -4
- package/src/config.js +1 -0
- package/src/controller.js +6 -4
- package/src/deliver.js +60 -18
- package/src/history.js +6 -2
- package/src/job.js +84 -27
- package/src/store.js +2 -0
- package/tools.js +6 -2
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
|
|
|
@@ -124,7 +125,7 @@ Next to `jobs`, the row also takes:
|
|
|
124
125
|
|
|
125
126
|
- One run of a job at a time: if a tick arrives while the previous run is still going, the tick is skipped and logged.
|
|
126
127
|
- Start, exit status, duration and a short tail of stdout and stderr go to the DSH log under `cron-jobs`. Sending the result anywhere else is what [Result delivery](#result-delivery) is for.
|
|
127
|
-
- Set `runLog` (next to `jobs`) to a file path to also keep that record as JSON Lines: one `start` line per run, one `end` line with `status`, `outcome`, `exitCode`, `durationMs`, the output tails and the delivery state, a `delivery` line when a
|
|
128
|
+
- Set `runLog` (next to `jobs`) to a file path to also keep that record as JSON Lines: one `start` line per run, one `end` line with `status`, `outcome`, `exitCode`, `durationMs`, the output tails and the delivery state, a `delivery` line when a result waits for its channel (`waiting`), is left for the next start (`pending`), or has been delivered or not (`sent`, `silent`, `failed`), a `skipped` line for a skipped tick, an `overdue` line (with `dueAt` and `lateMs`) when a tick did not start on time and the watchdog ran it late, and `scheduler-start` / `scheduler-stop` lines (with `job: null`) when the scheduler starts or stops, so a gap in the log can be told apart from a lost tick. A `start` with no `end` means DSH stopped during the run. The file is only appended to; rotate it yourself if it grows.
|
|
128
129
|
- Ticks of config jobs missed while DSH is down are not caught up; the next tick runs normally. While DSH runs, a watchdog checks every minute that each job's next run is not more than a minute in the past; a tick whose timer was lost runs late instead of being missed. (Jobs created from a conversation catch up once, see below.)
|
|
129
130
|
- Unloading the plugin (stopping DSH or changing its config) stops the timers and terminates running commands.
|
|
130
131
|
|
|
@@ -160,7 +161,15 @@ A job with a delivery target sends its result when a run is over:
|
|
|
160
161
|
|
|
161
162
|
Where results go is decided per job: its own `deliver` (or `false`), otherwise nothing for jobs that post into an existing session (`agent.sessionId`, or the tools' `this_session` / `sessionId`), since the answer is already in that conversation, otherwise the row's `deliver`. A run stopped because DSH is shutting down delivers nothing.
|
|
162
163
|
|
|
163
|
-
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.
|
|
164
|
+
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.
|
|
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.
|
|
164
173
|
|
|
165
174
|
### Delivery channels
|
|
166
175
|
|
|
@@ -178,7 +187,7 @@ await service.send({
|
|
|
178
187
|
})
|
|
179
188
|
```
|
|
180
189
|
|
|
181
|
-
The promise resolves when the message is sent and rejects with an `Error` when it is not. A rejected send is tried again twice (after 5 and 30 seconds)
|
|
190
|
+
The promise resolves when the message is sent and rejects with an `Error` when it is not. A rejected send is tried again twice (after 5 and 30 seconds). A service that is not running (for example while its plugin reloads or is stuck unloading) is not a failed try: the delivery waits for it, looking again every 10 seconds for up to an hour, and a restart in that time leaves it pending for the next start, which waits again. Set `retryable: false` on the error to stop the retries for a failure that will not go away, such as an unknown address. The return value is ignored. A send that still fails is recorded in the run's history and the run log; the job itself carries on.
|
|
182
191
|
|
|
183
192
|
To make a plugin a delivery channel, provide a service with that method:
|
|
184
193
|
|
|
@@ -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/client.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* tokens (--dsw-*). Icon paths are copied from DSH's icon set (MIT).
|
|
11
11
|
*/
|
|
12
12
|
window.__ModuleLoader__.load({
|
|
13
|
-
id: 'dsh-cron-jobs',
|
|
13
|
+
id: '@soffits/dsh-cron-jobs',
|
|
14
14
|
factory(require) {
|
|
15
15
|
const React = require('react')
|
|
16
16
|
const h = React.createElement
|
|
@@ -128,7 +128,7 @@ window.__ModuleLoader__.load({
|
|
|
128
128
|
'field.deliverOff': 'Nothing: turned off for this job',
|
|
129
129
|
'field.deliverSession': 'Nothing: the answer stays in its session',
|
|
130
130
|
'field.deliverUnset': 'Nothing',
|
|
131
|
-
'delivery.pending': 'result:
|
|
131
|
+
'delivery.pending': 'result: not sent yet',
|
|
132
132
|
'delivery.sent': 'result sent',
|
|
133
133
|
'delivery.silent': 'nothing to send',
|
|
134
134
|
'delivery.failed': 'result not sent',
|
|
@@ -259,7 +259,7 @@ window.__ModuleLoader__.load({
|
|
|
259
259
|
'field.deliverOff': '不发送:此任务已关闭',
|
|
260
260
|
'field.deliverSession': '不发送:回答留在它的会话里',
|
|
261
261
|
'field.deliverUnset': '不发送',
|
|
262
|
-
'delivery.pending': '
|
|
262
|
+
'delivery.pending': '结果:尚未发送',
|
|
263
263
|
'delivery.sent': '结果已发送',
|
|
264
264
|
'delivery.silent': '无需发送',
|
|
265
265
|
'delivery.failed': '结果未发送',
|
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,
|
|
@@ -52,9 +58,10 @@ export function apply(ctx, config) {
|
|
|
52
58
|
reuse: request => deliverToSession(ctx, request),
|
|
53
59
|
settle: (sessionId, options) => archiveWhenIdle(ctx, sessionId, options),
|
|
54
60
|
// The channel is found by name at send time, so it may load after
|
|
55
|
-
// this plugin, reload, or be missing
|
|
56
|
-
send: (target, message, from) => sendMessage({ lookup: name => ctx.get(name), target, message, from, signal: controller.signal }),
|
|
61
|
+
// this plugin, reload, or be missing for a while (the delivery waits).
|
|
62
|
+
send: (target, message, from, options) => sendMessage({ lookup: name => ctx.get(name), target, message, from, signal: controller.signal, ...options }),
|
|
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
|
|
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.
|
|
3
|
+
"version": "0.7.1",
|
|
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/deliver.js
CHANGED
|
@@ -21,6 +21,15 @@ export const DELIVERY_ATTEMPTS = 3
|
|
|
21
21
|
/** Wait before each retry, in milliseconds. */
|
|
22
22
|
export const DELIVERY_RETRY_MS = [5_000, 30_000]
|
|
23
23
|
|
|
24
|
+
/**
|
|
25
|
+
* How long a delivery waits for its service to be running again (a plugin
|
|
26
|
+
* reload, a stuck unload) before it fails. A restart in between leaves the
|
|
27
|
+
* delivery pending, and the next start waits again.
|
|
28
|
+
*/
|
|
29
|
+
export const SERVICE_WAIT_MS = 60 * 60_000
|
|
30
|
+
/** How often a waiting delivery looks for its service. */
|
|
31
|
+
export const SERVICE_POLL_MS = 10_000
|
|
32
|
+
|
|
24
33
|
/** Lines of stderr shown in a failure note. */
|
|
25
34
|
export const FAILURE_STDERR_LINES = 15
|
|
26
35
|
|
|
@@ -167,44 +176,77 @@ function permanent(error) {
|
|
|
167
176
|
|
|
168
177
|
/**
|
|
169
178
|
* Hand one message to the target's service, retrying transient failures.
|
|
170
|
-
*
|
|
179
|
+
* A service that is not running is waited for (looked up every `pollMs`, up
|
|
180
|
+
* to `waitMs` in all) instead of counting as a failed attempt. Never rejects.
|
|
181
|
+
*
|
|
182
|
+
* Results: `sent`; `failed` (the service threw on every attempt, or a
|
|
183
|
+
* permanent error); `unavailable` (the service was still not running after
|
|
184
|
+
* `waitMs`); `stopped` (the signal fired before the message was sent). The
|
|
185
|
+
* last two are not final: the caller decides whether to keep the message
|
|
186
|
+
* pending.
|
|
171
187
|
* @param {object} options
|
|
172
188
|
* @param {(name: string) => any} options.lookup - Finds a service by name.
|
|
173
189
|
* @param {DeliveryTarget} options.target
|
|
174
190
|
* @param {{ text: string, files: string[] }} options.message
|
|
175
191
|
* @param {{ job: string, sessionId?: string }} options.from
|
|
176
|
-
* @param {AbortSignal} [options.signal] - Stops waiting
|
|
192
|
+
* @param {AbortSignal} [options.signal] - Stops waiting.
|
|
177
193
|
* @param {number} [options.attempts]
|
|
178
194
|
* @param {number[]} [options.retryMs]
|
|
179
|
-
* @
|
|
195
|
+
* @param {number} [options.waitMs] - Longest wait for a missing service; 0 gives up at once.
|
|
196
|
+
* @param {number} [options.pollMs]
|
|
197
|
+
* @param {(error: string) => void} [options.onWait] - Called once, when the wait for a missing service starts.
|
|
198
|
+
* @returns {Promise<{ status: 'sent' | 'failed' | 'unavailable' | 'stopped', attempts: number, error?: string }>}
|
|
180
199
|
*/
|
|
181
|
-
export async function sendMessage({
|
|
200
|
+
export async function sendMessage({
|
|
201
|
+
lookup, target, message, from, signal, attempts = DELIVERY_ATTEMPTS, retryMs = DELIVERY_RETRY_MS,
|
|
202
|
+
waitMs = SERVICE_WAIT_MS, pollMs = SERVICE_POLL_MS, onWait,
|
|
203
|
+
}) {
|
|
204
|
+
const deadline = Date.now() + waitMs
|
|
205
|
+
const missing = `no service named ${target.via} is running`
|
|
206
|
+
let waiting = false
|
|
182
207
|
let error
|
|
183
|
-
|
|
184
|
-
|
|
208
|
+
let tried = 0
|
|
209
|
+
while (tried < attempts) {
|
|
210
|
+
if (signal?.aborted) return { status: 'stopped', attempts: tried, error: error ?? 'stopped before sending' }
|
|
211
|
+
let service
|
|
185
212
|
try {
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
213
|
+
service = lookup(target.via)
|
|
214
|
+
} catch {
|
|
215
|
+
service = undefined
|
|
216
|
+
}
|
|
217
|
+
if (service === undefined || service === null) {
|
|
218
|
+
error = missing
|
|
219
|
+
if (Date.now() >= deadline) {
|
|
220
|
+
return { status: 'unavailable', attempts: tried, error: waitMs > 0 ? `${error} (waited ${minutes(waitMs)})` : error }
|
|
189
221
|
}
|
|
190
|
-
if (
|
|
191
|
-
|
|
192
|
-
|
|
222
|
+
if (!waiting) {
|
|
223
|
+
waiting = true
|
|
224
|
+
onWait?.(error)
|
|
193
225
|
}
|
|
226
|
+
await sleep(Math.min(pollMs, Math.max(0, deadline - Date.now())), signal)
|
|
227
|
+
continue
|
|
228
|
+
}
|
|
229
|
+
if (typeof service.send !== 'function') {
|
|
230
|
+
return { status: 'failed', attempts: tried + 1, error: `service ${target.via} has no send method` }
|
|
231
|
+
}
|
|
232
|
+
tried++
|
|
233
|
+
try {
|
|
194
234
|
await service.send({ to: target.to, text: message.text, files: [...message.files], from: { ...from } })
|
|
195
|
-
return { status: 'sent', attempts:
|
|
235
|
+
return { status: 'sent', attempts: tried }
|
|
196
236
|
} catch (caught) {
|
|
197
237
|
error = describe(caught)
|
|
198
|
-
if (
|
|
199
|
-
}
|
|
200
|
-
if (attempt < attempts) {
|
|
201
|
-
await sleep(retryMs[Math.min(attempt - 1, retryMs.length - 1)] ?? 0, signal)
|
|
202
|
-
if (signal?.aborted) return { status: 'failed', attempts: attempt, error: `${error} (stopped before retrying)` }
|
|
238
|
+
if (permanent(caught)) return { status: 'failed', attempts: tried, error }
|
|
203
239
|
}
|
|
240
|
+
if (tried < attempts) await sleep(retryMs[Math.min(tried - 1, retryMs.length - 1)] ?? 0, signal)
|
|
204
241
|
}
|
|
205
242
|
return { status: 'failed', attempts, error }
|
|
206
243
|
}
|
|
207
244
|
|
|
245
|
+
function minutes(ms) {
|
|
246
|
+
const count = Math.round(ms / 60_000)
|
|
247
|
+
return count >= 1 ? `${count} min` : `${Math.round(ms / 1000)} s`
|
|
248
|
+
}
|
|
249
|
+
|
|
208
250
|
function sleep(ms, signal) {
|
|
209
251
|
return new Promise((done) => {
|
|
210
252
|
const timer = setTimeout(finish, ms)
|
package/src/history.js
CHANGED
|
@@ -34,14 +34,18 @@ const runSchema = z.object({
|
|
|
34
34
|
// archived, kept (see archiveNote), or superseded (a later run reused it).
|
|
35
35
|
archive: z.enum(['pending', 'archived', 'kept', 'superseded']).optional(),
|
|
36
36
|
archiveNote: z.string().optional(),
|
|
37
|
-
// Result delivery: pending until the woken agent's turn ends
|
|
38
|
-
// silent (nothing to send) or
|
|
37
|
+
// Result delivery: pending until the woken agent's turn ends or the
|
|
38
|
+
// delivery service is running, then sent, silent (nothing to send) or
|
|
39
|
+
// failed (see error).
|
|
39
40
|
delivery: z.object({
|
|
40
41
|
status: z.enum(['pending', 'sent', 'silent', 'failed']),
|
|
41
42
|
via: z.string(),
|
|
42
43
|
to: z.string(),
|
|
43
44
|
// The prompt whose answer is delivered; kept while pending, for a restart.
|
|
44
45
|
messageId: z.string().optional(),
|
|
46
|
+
// A result ready before its service was running (a command's output, a
|
|
47
|
+
// failure note); kept while pending, for a restart.
|
|
48
|
+
message: z.object({ text: z.string(), files: z.array(z.string()) }).optional(),
|
|
45
49
|
attempts: z.number().optional(),
|
|
46
50
|
at: z.string().optional(),
|
|
47
51
|
error: z.string().optional(),
|
package/src/job.js
CHANGED
|
@@ -102,8 +102,9 @@ export class JobRunner {
|
|
|
102
102
|
* @param {(request: { sessionId: string, text: string, mayUnarchive: boolean, ignoreHold?: boolean }) => Promise<{ queued?: boolean }>} [deps.reuse] - Sends the prompt into an existing session (see session.js deliverToSession); without it every wake opens a new session.
|
|
103
103
|
* @param {(sessionId: string) => Promise<void>} [deps.keepSession] - Saves the session a new_once job opened, so later runs go to it.
|
|
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
|
-
* @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.
|
|
105
|
+
* @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.
|
|
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
|
|
@@ -243,57 +245,96 @@ export class JobRunner {
|
|
|
243
245
|
else return outcome
|
|
244
246
|
const message = messageFromText(text, job.cwd || undefined)
|
|
245
247
|
if (message === undefined) return { ...outcome, delivery: { status: 'silent', ...where } }
|
|
246
|
-
|
|
248
|
+
// No waiting inside the run: a missing service is waited for in the
|
|
249
|
+
// background (see watchDelivery), with the message kept for a restart.
|
|
250
|
+
const delivery = await this.deliverMessage(target, message, { waitMs: 0 })
|
|
251
|
+
return { ...outcome, delivery: delivery.status === 'pending' ? { ...delivery, message } : delivery }
|
|
247
252
|
}
|
|
248
253
|
|
|
249
|
-
/**
|
|
250
|
-
|
|
254
|
+
/**
|
|
255
|
+
* Send one message and log the result; resolves the run's delivery record.
|
|
256
|
+
* Not sent because the plugin is stopping, or (with `waitMs` 0) because
|
|
257
|
+
* the service is not running: `pending`. Still not running after a longer
|
|
258
|
+
* wait: `failed`.
|
|
259
|
+
* @param {{ via: string, to: string }} target
|
|
260
|
+
* @param {{ text: string, files: string[] }} message
|
|
261
|
+
* @param {{ sessionId?: string, waitMs?: number, onWait?: (error: string) => void }} options
|
|
262
|
+
*/
|
|
263
|
+
async deliverMessage(target, message, { sessionId, waitMs, onWait }) {
|
|
251
264
|
const { job, logger } = this
|
|
252
|
-
const sent = await this.send(target, message, { job: job.name, ...(sessionId ? { sessionId } : {}) }
|
|
265
|
+
const sent = await this.send(target, message, { job: job.name, ...(sessionId ? { sessionId } : {}) }, {
|
|
266
|
+
...(waitMs !== undefined ? { waitMs } : {}), ...(onWait ? { onWait } : {}),
|
|
267
|
+
})
|
|
253
268
|
const where = describeTarget(target)
|
|
254
|
-
|
|
269
|
+
const pending = sent.status === 'stopped' || (sent.status === 'unavailable' && waitMs === 0)
|
|
270
|
+
const status = sent.status === 'sent' ? 'sent' : pending ? 'pending' : 'failed'
|
|
271
|
+
if (status === 'sent') logger.info('[%s] delivered the result to %s', job.name, where)
|
|
272
|
+
else if (status === 'pending') logger.info('[%s] result for %s not sent yet: %s', job.name, where, sent.error)
|
|
255
273
|
else logger.warn('[%s] result not delivered to %s after %s attempt(s): %s', job.name, where, sent.attempts, sent.error)
|
|
256
274
|
return {
|
|
257
|
-
status
|
|
275
|
+
status,
|
|
258
276
|
via: target.via,
|
|
259
277
|
to: target.to,
|
|
260
|
-
attempts: sent.attempts,
|
|
261
|
-
at: this.now().toISOString(),
|
|
278
|
+
...(status === 'pending' ? {} : { attempts: sent.attempts, at: this.now().toISOString() }),
|
|
262
279
|
...(sent.error ? { error: sent.error } : {}),
|
|
263
280
|
}
|
|
264
281
|
}
|
|
265
282
|
|
|
266
283
|
/**
|
|
267
|
-
*
|
|
268
|
-
*
|
|
269
|
-
*
|
|
270
|
-
*
|
|
284
|
+
* Deliver a pending result in the background and save the outcome in the
|
|
285
|
+
* run's history: a message kept with the delivery (a command's output, a
|
|
286
|
+
* failure note), or else the woken agent's final answer once its turn
|
|
287
|
+
* ends. An empty answer or exactly [SILENT] sends nothing. A service that
|
|
288
|
+
* is not running is waited for (see deliver.js sendMessage). Left pending
|
|
289
|
+
* when the plugin unloads, for the next copy to finish (see
|
|
290
|
+
* resumeDeliveries).
|
|
271
291
|
*/
|
|
272
292
|
watchDelivery(sessionId, runId, pending) {
|
|
273
293
|
const { job, logger } = this
|
|
274
294
|
const target = { via: pending.via, to: pending.to ?? '' }
|
|
275
295
|
const save = delivery => this.history.update(jobKey(job), runId, { delivery })
|
|
276
296
|
const logEntry = delivery => this.record({
|
|
277
|
-
time: this.now().toISOString(), job: job.name, event: 'delivery', sessionId,
|
|
297
|
+
time: this.now().toISOString(), job: job.name, event: 'delivery', ...(sessionId ? { sessionId } : {}),
|
|
278
298
|
status: delivery.status, via: target.via, to: target.to, ...(delivery.error ? { error: delivery.error } : {}),
|
|
279
299
|
})
|
|
300
|
+
// Shown on the page and in the run log while the service is missing.
|
|
301
|
+
const onWait = (error) => {
|
|
302
|
+
logger.warn('[%s] %s; waiting for it to deliver the result', job.name, error)
|
|
303
|
+
save({ ...pending, error }).then(() => logEntry({ status: 'waiting', error })).catch(() => {})
|
|
304
|
+
}
|
|
305
|
+
const send = async (message) => {
|
|
306
|
+
const delivery = await this.deliverMessage(target, message, { sessionId, onWait })
|
|
307
|
+
// Unloading: the next copy of the plugin sends it.
|
|
308
|
+
if (delivery.status === 'pending') {
|
|
309
|
+
await logEntry({ status: 'pending', error: `${delivery.error}; left for the next start` })
|
|
310
|
+
return undefined
|
|
311
|
+
}
|
|
312
|
+
return delivery
|
|
313
|
+
}
|
|
280
314
|
const watch = (async () => {
|
|
281
|
-
if (this.answer === undefined) return
|
|
282
|
-
const answer = await this.answer(sessionId, pending.messageId, { signal: this.signal })
|
|
283
|
-
if ('pending' in answer || this.signal?.aborted) return
|
|
284
315
|
let delivery
|
|
285
|
-
if (
|
|
286
|
-
delivery =
|
|
287
|
-
logger.warn('[%s] no answer to deliver from session %s: %s', job.name, sessionId, answer.error)
|
|
316
|
+
if (pending.message !== undefined) {
|
|
317
|
+
delivery = await send(pending.message)
|
|
288
318
|
} else {
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
319
|
+
if (this.answer === undefined) return
|
|
320
|
+
const answer = await this.answer(sessionId, pending.messageId, { signal: this.signal })
|
|
321
|
+
if ('pending' in answer || this.signal?.aborted) return
|
|
322
|
+
if ('text' in answer) await this.checks?.recheck(pending.messageId, answer.text, { sessionId, signal: this.signal })
|
|
323
|
+
this.checks?.forget(pending.messageId)
|
|
324
|
+
if ('error' in answer) {
|
|
325
|
+
delivery = { status: 'failed', ...target, at: this.now().toISOString(), error: answer.error }
|
|
326
|
+
logger.warn('[%s] no answer to deliver from session %s: %s', job.name, sessionId, answer.error)
|
|
293
327
|
} else {
|
|
294
|
-
|
|
328
|
+
const message = messageFromText(answer.text, agentSettings(job, this.defaults).cwd)
|
|
329
|
+
if (message === undefined) {
|
|
330
|
+
delivery = { status: 'silent', ...target, at: this.now().toISOString(), ...(answer.reason && answer.reason !== 'completed' ? { error: `turn ended: ${answer.reason}` } : {}) }
|
|
331
|
+
logger.info('[%s] nothing to deliver from session %s', job.name, sessionId)
|
|
332
|
+
} else {
|
|
333
|
+
delivery = await send(message)
|
|
334
|
+
}
|
|
295
335
|
}
|
|
296
336
|
}
|
|
337
|
+
if (delivery === undefined) return
|
|
297
338
|
await save(delivery)
|
|
298
339
|
await logEntry(delivery)
|
|
299
340
|
})().catch((error) => {
|
|
@@ -307,7 +348,12 @@ export class JobRunner {
|
|
|
307
348
|
/** After a restart or reload: finish deliveries an earlier copy of the plugin left pending. */
|
|
308
349
|
async resumeDeliveries() {
|
|
309
350
|
for (const run of this.history.runs(jobKey(this.job))) {
|
|
310
|
-
if (run.delivery?.status
|
|
351
|
+
if (run.delivery?.status !== 'pending') continue
|
|
352
|
+
if (run.delivery.message !== undefined) {
|
|
353
|
+
this.watchDelivery(run.sessionId, run.id, run.delivery)
|
|
354
|
+
} else if (run.sessionId && run.delivery.messageId) {
|
|
355
|
+
// The turn may still be running (a plugin reload, a turn that outlived a restart).
|
|
356
|
+
this.expectCheck(run.delivery.messageId)
|
|
311
357
|
this.watchDelivery(run.sessionId, run.id, run.delivery)
|
|
312
358
|
}
|
|
313
359
|
}
|
|
@@ -353,10 +399,21 @@ export class JobRunner {
|
|
|
353
399
|
const target = job.target ?? { kind: 'new' }
|
|
354
400
|
// Lets the answer to this prompt be found once its turn ends.
|
|
355
401
|
const messageId = randomUUID()
|
|
402
|
+
// Watched before the prompt is sent, so even a turn that ends at once is checked.
|
|
403
|
+
this.expectCheck(messageId)
|
|
356
404
|
const sent = await this.deliverPrompt({ job, target, text, messageId, settings, firedAt, localTime })
|
|
405
|
+
if (sent.status !== 'woke') this.checks?.forget(messageId)
|
|
357
406
|
return sent.status === 'woke' ? { ...sent, messageId } : sent
|
|
358
407
|
}
|
|
359
408
|
|
|
409
|
+
/** Have the answer to this prompt checked before its turn closes, when the job names a check. */
|
|
410
|
+
expectCheck(messageId) {
|
|
411
|
+
const command = this.job.agent?.answerCheck
|
|
412
|
+
if (!command || this.checks === undefined) return
|
|
413
|
+
const cwd = agentSettings(this.job, this.defaults).cwd
|
|
414
|
+
this.checks.expect(messageId, { job: this.job.name, command, ...(cwd ? { cwd } : {}) })
|
|
415
|
+
}
|
|
416
|
+
|
|
360
417
|
/** Send the prompt to the target session, a reused one, or a new one. */
|
|
361
418
|
async deliverPrompt({ job, target, text, messageId, settings, firedAt, localTime }) {
|
|
362
419
|
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
|
}),
|