@astratra/agent 1.2.0 → 1.4.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.fr.md +47 -3
- package/README.md +46 -4
- package/package.json +3 -3
- package/src/approvals.js +31 -10
- package/src/coordinationPostgres.js +118 -15
- package/src/feedback/router.js +1 -1
- package/src/index.d.ts +33 -8
- package/src/schedule.js +21 -3
- package/src/scheduler.js +43 -16
package/README.fr.md
CHANGED
|
@@ -186,6 +186,14 @@ scheduler.stop(); // arrête le passage périodiqu
|
|
|
186
186
|
changements d'heure sont gérés : 07:00 reste 07:00 à l'horloge murale. Une heure qui n'existe pas (02:30 au passage à
|
|
187
187
|
l'heure d'été) part juste après le trou ; une heure qui existe deux fois part une seule fois, à la première
|
|
188
188
|
occurrence. `nextRun(schedule, apresMs, timeZone)` est exportée.
|
|
189
|
+
- **Intervalle aligné (1.3.0)** : `{ type: 'interval', everyMs: 3600000, align: true }` part sur les marques rondes de
|
|
190
|
+
la journée locale (07:00, 08:00… ; toutes les 15 min : :00, :15, :30, :45), comptées depuis minuit local, quelle que
|
|
191
|
+
soit l'heure de démarrage. `everyMs` doit être un nombre entier de secondes, d'un jour au plus.
|
|
192
|
+
- **Réglages à chaud (1.3.0)** : `enabled` (booléen ou `async () => booléen`) et `schedule` (objet ou
|
|
193
|
+
`async () => programmation`) d'une tâche sont relus à chaque passage : un tableau de bord peut couper une tâche ou la
|
|
194
|
+
déplacer sans redémarrage. Une tâche coupée a `nextRunAt: null` ; une programmation changée est replanifiée au passage
|
|
195
|
+
suivant (résultat `'rescheduled'`, la tâche ne part pas dans ce passage). Une fonction qui échoue ou rend une mauvaise valeur est signalée à `onError` ; la tâche est
|
|
196
|
+
laissée de côté pour ce passage (son plan est gardé) et les autres continuent. `state()` montre `enabled` et `schedule` en vigueur.
|
|
189
197
|
- **Jamais deux fois en même temps** : chaque passage prend un `lock` (`acquire(cle)` → `{ release() }` ou `null`). Par
|
|
190
198
|
défaut un verrou dans le processus ; avec plusieurs processus, `createPostgresLock(pool)` (`pg_try_advisory_lock`,
|
|
191
199
|
tenu sur une connexion du pool jusqu'à `release()`, libéré si le processus meurt). L'état est relu sous le verrou :
|
|
@@ -228,6 +236,7 @@ const queue = createApprovalQueue({
|
|
|
228
236
|
const action = await queue.propose({ type: 'publier', input: { titre: 'Bonjour' }, requestedBy: 'assistant', ttlMs: 3 * 24 * 3600 * 1000 });
|
|
229
237
|
await queue.list({ status: 'pending' });
|
|
230
238
|
await queue.approve(action.id, { decider: { id: 'u-1', role: 'proprietaire' } }); // → { action, result }
|
|
239
|
+
await queue.approve(action.id, { decider, input: { titre: 'Bonjour à tous' } }); // l'action telle que corrigée
|
|
231
240
|
await queue.reject(action.id, { decider: { id: 'u-1', role: 'proprietaire' }, reason: 'pas maintenant' });
|
|
232
241
|
await queue.expire(); // fait aussi par list/approve/reject
|
|
233
242
|
```
|
|
@@ -244,11 +253,46 @@ await queue.expire();
|
|
|
244
253
|
- **Expiration** : `ttlMs` ou `expiresAt` à `propose`. Une action expirée ne peut plus être approuvée ni rejetée
|
|
245
254
|
(`ApprovalError('expired')`), même si le balayage n'est pas encore passé. `expire()` les marque `expired` ;
|
|
246
255
|
appelez-la depuis une minuterie ou une tâche de l'ordonnanceur.
|
|
256
|
+
- **Entrée corrigée (1.3.0)** : `approve(id, { decider, input })` approuve l'action *telle que la personne l'a lue et
|
|
257
|
+
corrigée*. `input` doit être un objet ; `validateInput({ action, input, decider })` (option) peut la refuser (`false`
|
|
258
|
+
ou une exception : `ApprovalError('invalid')`) ou la normaliser (`{ value }`). Elle est enregistrée en
|
|
259
|
+
`decisionInput` dans la même réservation atomique, avant toute exécution, et l'exécuteur la reçoit en `input` (la
|
|
260
|
+
proposition reste en `proposedInput`). `authorize` la voit aussi. Un refus ou un échec l'efface avec la réservation.
|
|
247
261
|
- **Erreurs** (`ApprovalError.code`) : `not_found`, `expired`, `already_decided`, `forbidden`, `no_executor`,
|
|
248
262
|
`execution_failed`, `invalid`.
|
|
249
|
-
- **Stockage** :
|
|
250
|
-
|
|
251
|
-
|
|
263
|
+
- **Stockage PostgreSQL** : `createPostgresApprovalStore(db)` avec `postgresApprovalSchema()` (qui ajoute aussi la
|
|
264
|
+
colonne `decision_input` à une table plus ancienne). Sur **votre propre table** (1.3.0), donnez la correspondance :
|
|
265
|
+
```js
|
|
266
|
+
createPostgresApprovalStore(db, {
|
|
267
|
+
table: 'journal_actions',
|
|
268
|
+
columns: { id: 'ref', type: 'outil', input: 'entree', requestedBy: 'demandeur', status: 'statut',
|
|
269
|
+
createdAt: 'cree_le', expiresAt: 'expire_le', decidedBy: 'decide_par', decidedAt: 'decide_le',
|
|
270
|
+
executedAt: 'execute_le', result: 'resultat', reason: 'motif', decisionInput: 'entree_validee',
|
|
271
|
+
meta: null, refusal: null }, // null : non conservé
|
|
272
|
+
statuses: { pending: 'en_attente', approved: 'approuvee', rejected: 'rejetee', expired: 'expiree' },
|
|
273
|
+
scope: { column: 'necessite_accord', value: true } // seules ces lignes appartiennent à la file
|
|
274
|
+
});
|
|
275
|
+
```
|
|
276
|
+
Les horodatages sont en `timestamptz` ; `input`, `meta`, `result`, `refusal`, `decision_input` en `jsonb`. Les noms
|
|
277
|
+
sont vérifiés (identifiants simples : lettres, chiffres, `_`, 48 caractères au plus) ; toutes les valeurs passent en paramètres. Les
|
|
278
|
+
lignes hors `scope` ne sont jamais lues ni modifiées. Sans colonne `decisionInput`, `approve` avec `input` est refusé
|
|
279
|
+
(rien ne s'exécute).
|
|
280
|
+
- **Votre propre stockage (contrat)** : mémoire par défaut ; tout objet qui a ces méthodes convient. Chaque transition
|
|
281
|
+
est une seule étape atomique qui rend l'action modifiée, ou `null` quand sa condition n'est plus vraie (sans lever
|
|
282
|
+
d'erreur pour cela) :
|
|
283
|
+
- `create(action)` enregistre une nouvelle action (tous les champs, `status: 'pending'`) ; `get(id)` → action ou `null` ;
|
|
284
|
+
- `list({ status?, type?, requestedBy?, limit = 50, before? })` → les plus récentes d'abord (`createdAt` décroissant,
|
|
285
|
+
puis `id`) ;
|
|
286
|
+
- `reserve(id, decidedBy, at, decisionInput)` : `pending` et non expirée à `at` → `approved`, fixe `decidedBy`,
|
|
287
|
+
`decidedAt`, `executedAt: null`, et **garde `decisionInput`** (le rend, `null` s'il est absent ; un stockage qui
|
|
288
|
+
rend `undefined` est refusé quand une entrée est donnée) ;
|
|
289
|
+
- `finish(id, result, at)` : `approved` et `executedAt` nul → fixe `result`, `executedAt` ;
|
|
290
|
+
- `revert(id, decidedBy, refusal)` : `approved` par ce décideur et non exécutée → `pending`, efface `decidedBy`,
|
|
291
|
+
`decidedAt`, `decisionInput`, fixe `refusal` ;
|
|
292
|
+
- `reject(id, decidedBy, reason, at)` : `pending` et non expirée → `rejected` ;
|
|
293
|
+
- `expire(at)` : toute `pending` dont `expiresAt <= at` → `expired` (`decidedAt: at`), et les rend.
|
|
294
|
+
Les instants sont en millisecondes. Avec plusieurs processus, la condition doit être vérifiée dans la même requête
|
|
295
|
+
que le changement (un `UPDATE … WHERE status = 'pending'` conditionnel), pas lue puis écrite.
|
|
252
296
|
- Les entrées et résultats conservés doivent être du JSON.
|
|
253
297
|
|
|
254
298
|
## Tests
|
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
[English](README.md) | [Français](README.fr.md)
|
|
4
4
|
|
|
5
5
|
Durable task execution built on `runToolLoop` from `@astratra/ai`. Models,
|
|
6
|
-
application tools, completion checks and persistence are injected. Node >=
|
|
6
|
+
application tools, completion checks and persistence are injected. Node >= 22,
|
|
7
7
|
CommonJS, MIT. No provider or database driver is included.
|
|
8
8
|
|
|
9
9
|
```sh
|
|
@@ -353,6 +353,15 @@ scheduler.stop(); // stops the periodic pass
|
|
|
353
353
|
`'monday'`), `{ type: 'interval', everyMs }`. `timeZone` is global or per task. Daylight saving is handled: 07:00
|
|
354
354
|
stays 07:00 on the wall clock. A time that does not exist (02:30 when clocks go forward) runs right after the gap; a
|
|
355
355
|
time that happens twice runs once, at the first occurrence. `nextRun(schedule, afterMs, timeZone)` is exported.
|
|
356
|
+
- **Aligned interval (1.3.0)**: `{ type: 'interval', everyMs: 3600000, align: true }` runs on the round marks of the
|
|
357
|
+
local day (07:00, 08:00…; every 15 min: :00, :15, :30, :45), counted from local midnight, whatever the start time.
|
|
358
|
+
`everyMs` must be whole seconds and at most one day.
|
|
359
|
+
- **Live settings (1.3.0)**: a task's `enabled` (boolean or `async () => boolean`) and `schedule` (object or
|
|
360
|
+
`async () => schedule`) are read at each pass, so a dashboard can switch a task off or move it without a restart. A
|
|
361
|
+
disabled task has `nextRunAt: null`; a changed schedule is replanned at the next pass (outcome `'rescheduled'`, the
|
|
362
|
+
task does not run in that pass). A function that throws or gives a wrong value is reported to `onError`; the task is left out of
|
|
363
|
+
that pass (its plan is kept) and the other tasks go on. `state()` shows the
|
|
364
|
+
current `enabled` and `schedule`.
|
|
356
365
|
- **Never twice at once**: each run takes a `lock` (`acquire(key)` → `{ release() }` or `null`). The default is an
|
|
357
366
|
in-process lock; with several processes pass `createPostgresLock(pool)` (`pg_try_advisory_lock`, held on one pooled
|
|
358
367
|
connection until released, freed if the process dies). The run state is re-read under the lock, so a process that
|
|
@@ -393,6 +402,7 @@ const queue = createApprovalQueue({
|
|
|
393
402
|
const action = await queue.propose({ type: 'publish', input: { title: 'Hello' }, requestedBy: 'assistant', ttlMs: 3 * 24 * 3600 * 1000 });
|
|
394
403
|
await queue.list({ status: 'pending' });
|
|
395
404
|
await queue.approve(action.id, { decider: { id: 'user-1', role: 'owner' } }); // → { action, result }
|
|
405
|
+
await queue.approve(action.id, { decider, input: { title: 'Hello, world' } }); // the action as the person corrected it
|
|
396
406
|
await queue.reject(action.id, { decider: { id: 'user-1', role: 'owner' }, reason: 'not now' });
|
|
397
407
|
await queue.expire(); // also done by list/approve/reject
|
|
398
408
|
```
|
|
@@ -408,11 +418,43 @@ await queue.expire();
|
|
|
408
418
|
- **Expiry**: `ttlMs` or `expiresAt` at `propose`. An expired action cannot be approved or rejected
|
|
409
419
|
(`ApprovalError('expired')`), even if the sweep has not run yet. `expire()` marks them `expired`; call it from a
|
|
410
420
|
timer or from a scheduler task.
|
|
421
|
+
- **Corrected input (1.3.0)**: `approve(id, { decider, input })` approves the action *as the person read and edited
|
|
422
|
+
it*. `input` must be an object; `validateInput({ action, input, decider })` (option) may refuse it (`false` or a
|
|
423
|
+
throw: `ApprovalError('invalid')`) or normalise it (`{ value }`). It is recorded as `decisionInput` in the same atomic
|
|
424
|
+
reservation, before anything runs, and the executor receives it as `input` (the proposal stays as
|
|
425
|
+
`proposedInput`). `authorize` sees it too. A refusal or failure clears it with the reservation.
|
|
411
426
|
- **Errors** (`ApprovalError.code`): `not_found`, `expired`, `already_decided`, `forbidden`, `no_executor`,
|
|
412
427
|
`execution_failed`, `invalid`.
|
|
413
|
-
- **
|
|
414
|
-
|
|
415
|
-
|
|
428
|
+
- **PostgreSQL store**: `createPostgresApprovalStore(db)` with `postgresApprovalSchema()` (it also adds the
|
|
429
|
+
`decision_input` column to an older table). On **your own table** (1.3.0), map it:
|
|
430
|
+
```js
|
|
431
|
+
createPostgresApprovalStore(db, {
|
|
432
|
+
table: 'journal_actions',
|
|
433
|
+
columns: { id: 'ref', type: 'outil', input: 'entree', requestedBy: 'demandeur', status: 'statut',
|
|
434
|
+
createdAt: 'cree_le', expiresAt: 'expire_le', decidedBy: 'decide_par', decidedAt: 'decide_le',
|
|
435
|
+
executedAt: 'execute_le', result: 'resultat', reason: 'motif', decisionInput: 'entree_validee',
|
|
436
|
+
meta: null, refusal: null }, // null: not kept
|
|
437
|
+
statuses: { pending: 'en_attente', approved: 'approuvee', rejected: 'rejetee', expired: 'expiree' },
|
|
438
|
+
scope: { column: 'necessite_accord', value: true } // only these rows belong to the queue
|
|
439
|
+
});
|
|
440
|
+
```
|
|
441
|
+
Timestamps are `timestamptz`; `input`, `meta`, `result`, `refusal`, `decision_input` are `jsonb`. Names are checked
|
|
442
|
+
(plain identifiers: letters, digits, `_`, at most 48 characters); all values are bound parameters. Rows outside `scope` are never read or
|
|
443
|
+
changed. Without a `decisionInput` column, `approve` with `input` is refused (nothing runs).
|
|
444
|
+
- **Your own store (contract)**: memory by default; any object with these methods works. Each transition is one atomic
|
|
445
|
+
step that returns the updated action, or `null` when its condition no longer holds (never throws for that):
|
|
446
|
+
- `create(action)` stores a new action (all fields, `status: 'pending'`); `get(id)` → action or `null`;
|
|
447
|
+
- `list({ status?, type?, requestedBy?, limit = 50, before? })` → most recent first (`createdAt` desc, then `id`);
|
|
448
|
+
- `reserve(id, decidedBy, at, decisionInput)`: `pending` and not expired at `at` → `approved`, sets `decidedBy`,
|
|
449
|
+
`decidedAt`, `executedAt: null`, and **stores `decisionInput`** (returns it, `null` when absent; a store that
|
|
450
|
+
returns `undefined` is refused when an input is given);
|
|
451
|
+
- `finish(id, result, at)`: `approved` and `executedAt` null → sets `result`, `executedAt`;
|
|
452
|
+
- `revert(id, decidedBy, refusal)`: `approved` by this decider and not executed → `pending`, clears `decidedBy`,
|
|
453
|
+
`decidedAt`, `decisionInput`, sets `refusal`;
|
|
454
|
+
- `reject(id, decidedBy, reason, at)`: `pending` and not expired → `rejected`;
|
|
455
|
+
- `expire(at)`: every `pending` with `expiresAt <= at` → `expired` (`decidedAt: at`), returns them.
|
|
456
|
+
Times are milliseconds. With several processes the conditions must be checked in the same statement as the
|
|
457
|
+
change (a conditional `UPDATE … WHERE status = 'pending'`), not read then written.
|
|
416
458
|
- Persisted inputs and results must be JSON.
|
|
417
459
|
|
|
418
460
|
## Tests
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/agent",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "Budgeted, verifiable and durable task execution with injected models and tools, plus user feedback (thumbs up/down) on runs that the agent learns from.",
|
|
5
5
|
"engines": {
|
|
6
|
-
"node": ">=
|
|
6
|
+
"node": ">=22"
|
|
7
7
|
},
|
|
8
8
|
"main": "src/index.js",
|
|
9
9
|
"types": "src/index.d.ts",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"@astratra/ai": "^1.8.0"
|
|
23
23
|
},
|
|
24
24
|
"devDependencies": {
|
|
25
|
-
"express": "^4.18.3",
|
|
25
|
+
"express": "^4.18.3 || ^5.0.0",
|
|
26
26
|
"pg": "^8.13.1",
|
|
27
27
|
"supertest": "^7.0.0"
|
|
28
28
|
},
|
package/src/approvals.js
CHANGED
|
@@ -28,10 +28,10 @@ function createMemoryApprovalStore() {
|
|
|
28
28
|
.sort((a, b) => b.createdAt - a.createdAt || (a.id < b.id ? -1 : 1)).slice(0, limit).map(out);
|
|
29
29
|
},
|
|
30
30
|
// Each transition below is one atomic step: it returns the action, or null when the condition no longer holds.
|
|
31
|
-
async reserve(id, decidedBy, at) {
|
|
31
|
+
async reserve(id, decidedBy, at, decisionInput = null) {
|
|
32
32
|
const a = actions.get(id);
|
|
33
33
|
if (!a || a.status !== 'pending' || (a.expiresAt != null && a.expiresAt <= at)) return null;
|
|
34
|
-
Object.assign(a, { status: 'approved', decidedBy, decidedAt: at, executedAt: null }); return out(a);
|
|
34
|
+
Object.assign(a, { status: 'approved', decidedBy, decidedAt: at, executedAt: null, decisionInput: copy(decisionInput) }); return out(a);
|
|
35
35
|
},
|
|
36
36
|
async finish(id, result, at) {
|
|
37
37
|
const a = actions.get(id);
|
|
@@ -41,7 +41,7 @@ function createMemoryApprovalStore() {
|
|
|
41
41
|
async revert(id, decidedBy, refusal) {
|
|
42
42
|
const a = actions.get(id);
|
|
43
43
|
if (!a || a.status !== 'approved' || a.decidedBy !== decidedBy || a.executedAt != null) return null;
|
|
44
|
-
Object.assign(a, { status: 'pending', decidedBy: null, decidedAt: null, refusal: copy(refusal) }); return out(a);
|
|
44
|
+
Object.assign(a, { status: 'pending', decidedBy: null, decidedAt: null, decisionInput: null, refusal: copy(refusal) }); return out(a);
|
|
45
45
|
},
|
|
46
46
|
async reject(id, decidedBy, reason, at) {
|
|
47
47
|
const a = actions.get(id);
|
|
@@ -60,7 +60,7 @@ function createApprovalQueue(options = {}) {
|
|
|
60
60
|
const now = () => toMs((options.now ?? Date.now)());
|
|
61
61
|
const executors = options.executors;
|
|
62
62
|
if (executors != null && typeof executors !== 'function' && (typeof executors !== 'object' || Object.values(executors).some((f) => typeof f !== 'function'))) throw new Error('executors must be a function or an object of functions by action type.');
|
|
63
|
-
for (const name of ['authorize', 'beforeExecute', 'onEvent']) if (options[name] != null && typeof options[name] !== 'function') throw new Error(`${name} must be a function.`);
|
|
63
|
+
for (const name of ['authorize', 'beforeExecute', 'onEvent', 'validateInput']) if (options[name] != null && typeof options[name] !== 'function') throw new Error(`${name} must be a function.`);
|
|
64
64
|
const executionTimeoutMs = options.executionTimeoutMs ?? 30000;
|
|
65
65
|
const emit = (type, action, extra) => { try { void Promise.resolve(options.onEvent?.({ type, action, ...extra })).catch(() => {}); } catch (_error) { /* An observer never breaks the queue. */ } };
|
|
66
66
|
const executorFor = (type) => typeof executors === 'function' ? executors : executors?.[type];
|
|
@@ -93,7 +93,7 @@ function createApprovalQueue(options = {}) {
|
|
|
93
93
|
const at = now();
|
|
94
94
|
const expiry = expiresAt != null ? toMs(expiresAt) : ttlMs != null ? at + ttlMs : null;
|
|
95
95
|
if (expiry != null && (!Number.isFinite(expiry) || expiry <= at)) throw new ApprovalError('invalid', 'The expiry must be in the future.');
|
|
96
|
-
const action = await store.create({ id, type, input: copy(input), requestedBy, meta: copy(meta), status: 'pending', createdAt: at, expiresAt: expiry, decidedBy: null, decidedAt: null, executedAt: null, result: null, reason: null, refusal: null });
|
|
96
|
+
const action = await store.create({ id, type, input: copy(input), requestedBy, meta: copy(meta), status: 'pending', createdAt: at, expiresAt: expiry, decidedBy: null, decidedAt: null, executedAt: null, result: null, reason: null, refusal: null, decisionInput: null });
|
|
97
97
|
emit('proposed', action);
|
|
98
98
|
return action;
|
|
99
99
|
},
|
|
@@ -104,23 +104,44 @@ function createApprovalQueue(options = {}) {
|
|
|
104
104
|
expire,
|
|
105
105
|
/**
|
|
106
106
|
* Approves and executes. The action is reserved atomically first, so concurrent approvals run it once.
|
|
107
|
-
*
|
|
107
|
+
* `input` (optional): the action as the person read and corrected it; checked by `validateInput`, recorded as
|
|
108
|
+
* `decisionInput` before the execution and given to the executor as `input` (the proposal stays as `proposedInput`).
|
|
109
|
+
* The executor (`({ action, input, proposedInput, decider, signal, idempotencyKey })`) may throw ApprovalRefused or any error:
|
|
108
110
|
* the action then goes back to `pending` with `refusal` set and the error is rethrown. Resolves `{ action, result }`.
|
|
109
111
|
*/
|
|
110
|
-
async approve(id, { decider, signal } = {}) {
|
|
112
|
+
async approve(id, { decider, signal, input } = {}) {
|
|
111
113
|
await expire();
|
|
112
114
|
const pending = await pendingOrThrow(id);
|
|
113
|
-
|
|
115
|
+
// `input`: the action as the person read and corrected it. Checked here, recorded with the decision before
|
|
116
|
+
// anything runs, then given to the executor in place of the proposed input (kept intact for the record).
|
|
117
|
+
const hasDecisionInput = input !== undefined;
|
|
118
|
+
let decisionInput = null;
|
|
119
|
+
if (hasDecisionInput) {
|
|
120
|
+
if (input === null || typeof input !== 'object' || Array.isArray(input)) throw new ApprovalError('invalid', 'input must be an object.');
|
|
121
|
+
decisionInput = copy(input);
|
|
122
|
+
if (options.validateInput) {
|
|
123
|
+
let verdict;
|
|
124
|
+
try { verdict = await options.validateInput({ action: pending, input: decisionInput, decider }); } catch (error) { throw new ApprovalError('invalid', 'The corrected input is not valid.', { cause: error }); }
|
|
125
|
+
if (verdict === false) throw new ApprovalError('invalid', 'The corrected input is not valid.');
|
|
126
|
+
if (verdict && typeof verdict === 'object' && 'value' in verdict) decisionInput = copy(verdict.value);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
await authorize(hasDecisionInput ? { ...pending, decisionInput } : pending, decider, 'approve');
|
|
114
130
|
const execute = executorFor(pending.type);
|
|
115
131
|
if (!execute) throw new ApprovalError('no_executor', `No executor for ${pending.type}.`);
|
|
116
132
|
const by = who(decider);
|
|
117
|
-
const action = await store.reserve(id, by, now());
|
|
133
|
+
const action = await store.reserve(id, by, now(), decisionInput);
|
|
118
134
|
if (!action) { await pendingOrThrow(id); throw new ApprovalError('already_decided'); } // Lost the race: say why.
|
|
119
135
|
const back = async (refusal) => { await store.revert(id, by, { ...refusal, at: now(), by }); };
|
|
136
|
+
if (hasDecisionInput && action.decisionInput === undefined) {
|
|
137
|
+
// A store written before decision inputs: it would run the action without keeping what was approved.
|
|
138
|
+
await back({ reason: 'store_without_decision_input', details: null });
|
|
139
|
+
throw new ApprovalError('invalid', 'This approval store does not record a decision input (reserve() must store its 4th argument).');
|
|
140
|
+
}
|
|
120
141
|
let result;
|
|
121
142
|
try {
|
|
122
143
|
await options.beforeExecute?.({ action, decider });
|
|
123
|
-
result = copy(await execute({ action, input: action.input, decider, idempotencyKey: action.id, signal: signal ?? globalThis.AbortSignal.timeout(executionTimeoutMs) }));
|
|
144
|
+
result = copy(await execute({ action, input: action.decisionInput ?? action.input, proposedInput: action.input, decider, idempotencyKey: action.id, signal: signal ?? globalThis.AbortSignal.timeout(executionTimeoutMs) }));
|
|
124
145
|
} catch (error) {
|
|
125
146
|
if (error instanceof ApprovalRefused) { await back({ reason: error.reason, details: error.details }); emit('refused', action, { reason: error.reason }); throw error; }
|
|
126
147
|
if (error instanceof ApprovalError) { await back({ reason: error.code, details: null }); throw error; }
|
|
@@ -62,33 +62,136 @@ function postgresApprovalSchema(options) {
|
|
|
62
62
|
executed_at timestamptz,
|
|
63
63
|
result jsonb,
|
|
64
64
|
reason text,
|
|
65
|
-
refusal jsonb
|
|
65
|
+
refusal jsonb,
|
|
66
|
+
decision_input jsonb
|
|
66
67
|
);
|
|
68
|
+
ALTER TABLE "${table}" ADD COLUMN IF NOT EXISTS decision_input jsonb;
|
|
67
69
|
CREATE INDEX IF NOT EXISTS "${table}_status_idx" ON "${table}" (status, created_at DESC);`;
|
|
68
70
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
+
|
|
72
|
+
/*
|
|
73
|
+
* The approval store maps the queue's fields to columns. By default it uses the table made by postgresApprovalSchema;
|
|
74
|
+
* `columns`, `statuses` and `scope` let it sit on a table you already have (one that is also your journal of actions,
|
|
75
|
+
* with its own column names and status words). Fields marked optional may be mapped to null: they are then not kept.
|
|
76
|
+
*/
|
|
71
77
|
const time = (value) => value == null ? null : Math.round(Number(value));
|
|
72
|
-
const
|
|
78
|
+
const DEFAULT_COLUMNS = Object.freeze({
|
|
79
|
+
id: 'id', type: 'type', input: 'input', requestedBy: 'requested_by', meta: 'meta', status: 'status',
|
|
80
|
+
createdAt: 'created_at', expiresAt: 'expires_at', decidedBy: 'decided_by', decidedAt: 'decided_at',
|
|
81
|
+
executedAt: 'executed_at', result: 'result', reason: 'reason', refusal: 'refusal', decisionInput: 'decision_input'
|
|
82
|
+
});
|
|
83
|
+
const OPTIONAL_COLUMNS = Object.freeze(['meta', 'expiresAt', 'result', 'reason', 'refusal', 'decisionInput']);
|
|
84
|
+
const JSON_FIELDS = new Set(['input', 'meta', 'result', 'refusal', 'decisionInput']);
|
|
85
|
+
const TIME_FIELDS = new Set(['createdAt', 'expiresAt', 'decidedAt', 'executedAt']);
|
|
86
|
+
const STATUS_WORDS = Object.freeze(['pending', 'approved', 'rejected', 'expired']);
|
|
87
|
+
|
|
88
|
+
function approvalMapping(options = {}) {
|
|
89
|
+
const extra = Object.keys(options.columns ?? {}).filter((field) => !(field in DEFAULT_COLUMNS));
|
|
90
|
+
if (extra.length) throw new Error(`columns: unknown field(s) ${extra.join(', ')}.`);
|
|
91
|
+
const columns = {};
|
|
92
|
+
for (const [field, fallback] of Object.entries(DEFAULT_COLUMNS)) {
|
|
93
|
+
const given = options.columns?.[field];
|
|
94
|
+
if (given === null) { if (!OPTIONAL_COLUMNS.includes(field)) throw new Error(`columns.${field} cannot be null.`); columns[field] = null; continue; }
|
|
95
|
+
columns[field] = given === undefined ? fallback : identifier(given);
|
|
96
|
+
}
|
|
97
|
+
const statuses = {};
|
|
98
|
+
for (const word of STATUS_WORDS) {
|
|
99
|
+
const value = options.statuses?.[word] ?? word;
|
|
100
|
+
if (typeof value !== 'string' || !value) throw new Error(`statuses.${word} must be a non-empty string.`);
|
|
101
|
+
statuses[word] = value;
|
|
102
|
+
}
|
|
103
|
+
if (new Set(Object.values(statuses)).size !== STATUS_WORDS.length) throw new Error('statuses must give a different word to each status.');
|
|
104
|
+
if (Object.keys(options.statuses ?? {}).some((word) => !STATUS_WORDS.includes(word))) throw new Error(`statuses: only ${STATUS_WORDS.join(', ')}.`);
|
|
105
|
+
let scope = null;
|
|
106
|
+
if (options.scope != null) {
|
|
107
|
+
if (typeof options.scope !== 'object' || options.scope.value === undefined) throw new Error('scope must be { column, value }.');
|
|
108
|
+
scope = { column: identifier(options.scope.column), value: options.scope.value };
|
|
109
|
+
}
|
|
110
|
+
return { columns, statuses, scope };
|
|
111
|
+
}
|
|
112
|
+
|
|
73
113
|
/** Approval store. Every transition is one conditional UPDATE, so two concurrent approvals cannot both win. */
|
|
74
114
|
function createPostgresApprovalStore(db, options) {
|
|
75
115
|
if (!db || typeof db.query !== 'function') throw new Error('A database with query(sql, params) is required.');
|
|
76
116
|
const t = `"${identifier(options?.table, 'astratra_agent_approvals')}"`;
|
|
77
|
-
const
|
|
117
|
+
const { columns, statuses, scope } = approvalMapping(options);
|
|
118
|
+
const c = (field) => `"${columns[field]}"`;
|
|
119
|
+
const has = (field) => columns[field] !== null;
|
|
120
|
+
const fromStatus = Object.fromEntries(Object.entries(statuses).map(([word, value]) => [value, word]));
|
|
121
|
+
const select = Object.keys(DEFAULT_COLUMNS).filter(has)
|
|
122
|
+
.map((field) => TIME_FIELDS.has(field) ? `(extract(epoch from ${c(field)}) * 1000)::float8 AS "f_${field}"` : `${c(field)} AS "f_${field}"`).join(', ');
|
|
123
|
+
const toAction = (row) => {
|
|
124
|
+
if (!row) return null;
|
|
125
|
+
const action = {};
|
|
126
|
+
for (const field of Object.keys(DEFAULT_COLUMNS)) {
|
|
127
|
+
if (!has(field)) { action[field] = field === 'decisionInput' ? undefined : null; continue; }
|
|
128
|
+
const value = row[`f_${field}`];
|
|
129
|
+
action[field] = TIME_FIELDS.has(field) ? time(value) : JSON_FIELDS.has(field) ? (json(value) ?? null) : (value ?? null);
|
|
130
|
+
}
|
|
131
|
+
// A status word that is not one of the four (a row of your journal that never needed approval) is given as is.
|
|
132
|
+
action.status = fromStatus[action.status] ?? action.status;
|
|
133
|
+
return action;
|
|
134
|
+
};
|
|
135
|
+
/* Parameters $1.. are the call's own; the scope value and the status words come after them. */
|
|
136
|
+
const build = (base) => {
|
|
137
|
+
const params = [...base];
|
|
138
|
+
const add = (value) => { params.push(value); return `$${params.length}`; };
|
|
139
|
+
const status = (word) => `${add(statuses[word])}::text`;
|
|
140
|
+
// Added only where a query uses it: an unused parameter would have no type and PostgreSQL would refuse it.
|
|
141
|
+
const inScope = () => scope ? ` AND "${scope.column}" = ${add(scope.value)}` : '';
|
|
142
|
+
return { params, add, status, inScope };
|
|
143
|
+
};
|
|
144
|
+
const ts = (p) => `to_timestamp(${p}::float8 / 1000)`;
|
|
145
|
+
const run = async (sql, params) => (await db.query(sql, params)).rows.map(toAction);
|
|
146
|
+
const one = async (sql, params) => (await run(sql, params))[0] ?? null;
|
|
147
|
+
const notExpired = (_q, at) => has('expiresAt') ? ` AND (${c('expiresAt')} IS NULL OR ${c('expiresAt')} > ${ts(at)})` : '';
|
|
78
148
|
return {
|
|
79
|
-
create
|
|
80
|
-
|
|
149
|
+
async create(a) {
|
|
150
|
+
const q = build([]);
|
|
151
|
+
const fields = ['id', 'type', 'input', 'requestedBy', 'meta', 'status', 'createdAt', 'expiresAt'].filter(has);
|
|
152
|
+
const values = fields.map((field) => {
|
|
153
|
+
if (field === 'status') return q.status('pending');
|
|
154
|
+
if (JSON_FIELDS.has(field)) return `${q.add(a[field] == null ? null : JSON.stringify(a[field]))}::jsonb`;
|
|
155
|
+
if (TIME_FIELDS.has(field)) { const p = q.add(a[field] ?? null); return `CASE WHEN ${p}::float8 IS NULL THEN NULL ELSE ${ts(p)} END`; }
|
|
156
|
+
return q.add(a[field]);
|
|
157
|
+
});
|
|
158
|
+
const names = fields.map(c);
|
|
159
|
+
if (scope) { names.push(`"${scope.column}"`); values.push(q.add(scope.value)); }
|
|
160
|
+
return one(`INSERT INTO ${t} (${names.join(', ')}) VALUES (${values.join(', ')}) RETURNING ${select}`, q.params);
|
|
161
|
+
},
|
|
162
|
+
async get(id) {
|
|
163
|
+
const q = build([id]);
|
|
164
|
+
return one(`SELECT ${select} FROM ${t} WHERE ${c('id')} = $1${q.inScope()}`, q.params);
|
|
165
|
+
},
|
|
81
166
|
async list({ status, type, requestedBy, limit = 50, before } = {}) {
|
|
82
|
-
const
|
|
83
|
-
|
|
167
|
+
const q = build([type ?? null, requestedBy ?? null, before ?? null, limit]);
|
|
168
|
+
const byStatus = status ? ` AND ${c('status')} = ${q.add(statuses[status] ?? status)}::text` : '';
|
|
169
|
+
return run(`SELECT ${select} FROM ${t} WHERE ($1::text IS NULL OR ${c('type')} = $1) AND ($2::text IS NULL OR ${c('requestedBy')} = $2) AND ($3::float8 IS NULL OR ${c('createdAt')} < ${ts('$3')})${byStatus}${q.inScope()} ORDER BY ${c('createdAt')} DESC, ${c('id')} LIMIT $4`, q.params);
|
|
170
|
+
},
|
|
171
|
+
async reserve(id, by, at, decisionInput = null) {
|
|
172
|
+
const q = build([id, by, at]);
|
|
173
|
+
const keep = has('decisionInput') ? `, ${c('decisionInput')} = ${q.add(decisionInput == null ? null : JSON.stringify(decisionInput))}::jsonb` : '';
|
|
174
|
+
return one(`UPDATE ${t} SET ${c('status')} = ${q.status('approved')}, ${c('decidedBy')} = $2, ${c('decidedAt')} = ${ts('$3')}, ${c('executedAt')} = NULL${keep} WHERE ${c('id')} = $1 AND ${c('status')} = ${q.status('pending')}${notExpired(q, '$3')}${q.inScope()} RETURNING ${select}`, q.params);
|
|
175
|
+
},
|
|
176
|
+
async finish(id, result, at) {
|
|
177
|
+
const q = build([id, at]);
|
|
178
|
+
const keep = has('result') ? `, ${c('result')} = ${q.add(JSON.stringify(result ?? null))}::jsonb` : '';
|
|
179
|
+
return one(`UPDATE ${t} SET ${c('executedAt')} = ${ts('$2')}${keep} WHERE ${c('id')} = $1 AND ${c('status')} = ${q.status('approved')} AND ${c('executedAt')} IS NULL${q.inScope()} RETURNING ${select}`, q.params);
|
|
180
|
+
},
|
|
181
|
+
async revert(id, by, refusal) {
|
|
182
|
+
const q = build([id, by]);
|
|
183
|
+
const keep = (has('refusal') ? `, ${c('refusal')} = ${q.add(JSON.stringify(refusal))}::jsonb` : '') + (has('decisionInput') ? `, ${c('decisionInput')} = NULL` : '');
|
|
184
|
+
return one(`UPDATE ${t} SET ${c('status')} = ${q.status('pending')}, ${c('decidedBy')} = NULL, ${c('decidedAt')} = NULL${keep} WHERE ${c('id')} = $1 AND ${c('status')} = ${q.status('approved')} AND ${c('decidedBy')} = $2 AND ${c('executedAt')} IS NULL${q.inScope()} RETURNING ${select}`, q.params);
|
|
185
|
+
},
|
|
186
|
+
async reject(id, by, reason, at) {
|
|
187
|
+
const q = build([id, by, at]);
|
|
188
|
+
const keep = has('reason') ? `, ${c('reason')} = ${q.add(reason)}` : '';
|
|
189
|
+
return one(`UPDATE ${t} SET ${c('status')} = ${q.status('rejected')}, ${c('decidedBy')} = $2, ${c('decidedAt')} = ${ts('$3')}${keep} WHERE ${c('id')} = $1 AND ${c('status')} = ${q.status('pending')}${notExpired(q, '$3')}${q.inScope()} RETURNING ${select}`, q.params);
|
|
84
190
|
},
|
|
85
|
-
reserve: (id, by, at) => one(`UPDATE ${t} SET status = 'approved', decided_by = $2, decided_at = to_timestamp($3::float8 / 1000), executed_at = NULL WHERE id = $1 AND status = 'pending' AND (expires_at IS NULL OR expires_at > to_timestamp($3::float8 / 1000)) RETURNING ${COLUMNS}`, [id, by, at]),
|
|
86
|
-
finish: (id, result, at) => one(`UPDATE ${t} SET result = $2::jsonb, executed_at = to_timestamp($3::float8 / 1000) WHERE id = $1 AND status = 'approved' AND executed_at IS NULL RETURNING ${COLUMNS}`, [id, JSON.stringify(result ?? null), at]),
|
|
87
|
-
revert: (id, by, refusal) => one(`UPDATE ${t} SET status = 'pending', decided_by = NULL, decided_at = NULL, refusal = $3::jsonb WHERE id = $1 AND status = 'approved' AND decided_by = $2 AND executed_at IS NULL RETURNING ${COLUMNS}`, [id, by, JSON.stringify(refusal)]),
|
|
88
|
-
reject: (id, by, reason, at) => one(`UPDATE ${t} SET status = 'rejected', decided_by = $2, decided_at = to_timestamp($4::float8 / 1000), reason = $3 WHERE id = $1 AND status = 'pending' AND (expires_at IS NULL OR expires_at > to_timestamp($4::float8 / 1000)) RETURNING ${COLUMNS}`, [id, by, reason, at]),
|
|
89
191
|
async expire(at) {
|
|
90
|
-
|
|
91
|
-
|
|
192
|
+
if (!has('expiresAt')) return [];
|
|
193
|
+
const q = build([at]);
|
|
194
|
+
return run(`UPDATE ${t} SET ${c('status')} = ${q.status('expired')}, ${c('decidedAt')} = ${ts('$1')} WHERE ${c('status')} = ${q.status('pending')} AND ${c('expiresAt')} IS NOT NULL AND ${c('expiresAt')} <= ${ts('$1')}${q.inScope()} RETURNING ${select}`, q.params);
|
|
92
195
|
}
|
|
93
196
|
};
|
|
94
197
|
}
|
package/src/feedback/router.js
CHANGED
|
@@ -23,7 +23,7 @@ function createFeedbackRouter(options = {}) {
|
|
|
23
23
|
if (typeof identify !== 'function' || typeof resolveRun !== 'function') throw new Error('createFeedbackRouter requires identify and resolveRun.');
|
|
24
24
|
let express = options.express;
|
|
25
25
|
if (!express) {
|
|
26
|
-
try { express = require('express'); } catch (
|
|
26
|
+
try { express = require('express'); } catch (error) { throw new Error('createFeedbackRouter needs express: install it or pass options.express.', { cause: error }); }
|
|
27
27
|
}
|
|
28
28
|
const router = express.Router();
|
|
29
29
|
router.use(express.json({ limit: options.maxBodyBytes ?? 8192, strict: true }));
|
package/src/index.d.ts
CHANGED
|
@@ -83,13 +83,20 @@ export type Schedule =
|
|
|
83
83
|
| { type: 'daily'; at: string }
|
|
84
84
|
| { type: 'weekly'; at: string; day: number | string; days?: never }
|
|
85
85
|
| { type: 'weekly'; at: string; days: Array<number | string>; day?: never }
|
|
86
|
-
| { type: 'interval'; everyMs: number };
|
|
86
|
+
| { type: 'interval'; everyMs: number; align?: boolean };
|
|
87
87
|
export interface ScheduledRunContext { id: string; signal: AbortSignal; manual: boolean; scheduledFor: number | null; previous: unknown; now: number }
|
|
88
|
-
|
|
88
|
+
/** `enabled` and `schedule` may be functions: read again before every pass (a setting changed in an admin applies at once). */
|
|
89
|
+
export interface ScheduledTask {
|
|
90
|
+
id: string; label?: string; timeZone?: string; maxLateMs?: number; run(context: ScheduledRunContext): unknown;
|
|
91
|
+
schedule: Schedule | ((task: { id: string }) => Schedule | Promise<Schedule>);
|
|
92
|
+
enabled?: boolean | ((task: { id: string }) => boolean | Promise<boolean>);
|
|
93
|
+
}
|
|
89
94
|
export interface Lock { acquire(key: string): Promise<{ release(): Promise<void> } | null> }
|
|
90
95
|
export interface ScheduleState {
|
|
91
96
|
id: string; status: 'scheduled' | 'running' | 'ok' | 'error' | 'skipped'; nextRunAt: number | null; lastStartedAt: number | null; lastRunAt: number | null;
|
|
92
97
|
lastResult: unknown; lastError: { message: string; at: number } | null; skipReason: string | null; lastManual: boolean;
|
|
98
|
+
/** The schedule the plan was made with; a different one is planned again. */
|
|
99
|
+
scheduleKey?: string | null;
|
|
93
100
|
}
|
|
94
101
|
export interface ScheduleStateStore { get(id: string): Promise<Record<string, unknown> | null>; set(id: string, state: Record<string, unknown>): Promise<void> }
|
|
95
102
|
export interface SchedulerEvent { type: 'start' | 'done' | 'error' | 'skipped'; id: string; manual?: boolean; reason?: string; error?: string }
|
|
@@ -98,8 +105,8 @@ export interface SchedulerOptions {
|
|
|
98
105
|
tickMs?: number; maxLateMs?: number; stopCheckMs?: number; shouldStop?(): boolean | Promise<boolean>;
|
|
99
106
|
onEvent?(event: SchedulerEvent): void | Promise<void>; onError?(error: unknown, taskId: string): void;
|
|
100
107
|
}
|
|
101
|
-
export type RunOutcome = { id: string; status: 'ok' | 'error' | 'skipped' | 'scheduled' | 'locked' | 'already_done'; result?: unknown; error?: string; reason?: string };
|
|
102
|
-
export type TaskView = ScheduleState & { label: string; enabled: boolean; timeZone: string };
|
|
108
|
+
export type RunOutcome = { id: string; status: 'ok' | 'error' | 'skipped' | 'scheduled' | 'rescheduled' | 'locked' | 'already_done'; result?: unknown; error?: string; reason?: string };
|
|
109
|
+
export type TaskView = ScheduleState & { label: string; enabled: boolean; schedule: Schedule; timeZone: string };
|
|
103
110
|
export interface Scheduler {
|
|
104
111
|
tick(): Promise<RunOutcome[]>; start(): void; stop(): void; readonly started: boolean; abortAll(reason?: unknown): void;
|
|
105
112
|
run(id: string, options?: { signal?: AbortSignal }): Promise<RunOutcome>;
|
|
@@ -120,31 +127,37 @@ export interface ApprovalAction<I = unknown, R = unknown> {
|
|
|
120
127
|
id: string; type: string; input: I; requestedBy: string; meta: unknown; status: ApprovalStatus; createdAt: number; expiresAt: number | null;
|
|
121
128
|
decidedBy: string | null; decidedAt: number | null; executedAt: number | null; result: R | null; reason: string | null;
|
|
122
129
|
refusal: { reason: string; details: unknown; at: number; by: string } | null;
|
|
130
|
+
/** The input as the person corrected it when approving; null without a correction. Undefined from a store that does not keep it. */
|
|
131
|
+
decisionInput?: I | null;
|
|
123
132
|
}
|
|
124
133
|
export interface ApprovalFilter { status?: ApprovalStatus; type?: string; requestedBy?: string; limit?: number; before?: number }
|
|
125
134
|
export interface ApprovalStore {
|
|
126
135
|
create(action: ApprovalAction): Promise<ApprovalAction>; get(id: string): Promise<ApprovalAction | null>;
|
|
127
136
|
list(filter?: ApprovalFilter): Promise<ApprovalAction[]>;
|
|
128
|
-
|
|
137
|
+
/** Must keep `decisionInput` and return it on the action (null when absent). */
|
|
138
|
+
reserve(id: string, decidedBy: string, at: number, decisionInput?: unknown): Promise<ApprovalAction | null>;
|
|
129
139
|
finish(id: string, result: unknown, at: number): Promise<ApprovalAction | null>;
|
|
130
140
|
revert(id: string, decidedBy: string, refusal: unknown): Promise<ApprovalAction | null>;
|
|
131
141
|
reject(id: string, decidedBy: string, reason: string | null, at: number): Promise<ApprovalAction | null>;
|
|
132
142
|
expire(at: number): Promise<ApprovalAction[]>;
|
|
133
143
|
}
|
|
134
144
|
export type Decider = string | { id: string; [key: string]: unknown };
|
|
135
|
-
|
|
145
|
+
/** `input`: the corrected input when the person gave one, else the proposal; `proposedInput`: always the proposal. */
|
|
146
|
+
export interface ExecutorContext<I = any> { action: ApprovalAction<I>; input: I; proposedInput: I; decider: Decider; idempotencyKey: string; signal: AbortSignal }
|
|
136
147
|
export type Executor = (context: ExecutorContext) => unknown;
|
|
137
148
|
export interface ApprovalEvent { type: 'proposed' | 'approved' | 'rejected' | 'refused' | 'failed' | 'expired'; action: ApprovalAction; result?: unknown; reason?: string; error?: string }
|
|
138
149
|
export interface ApprovalQueueOptions {
|
|
139
150
|
store?: ApprovalStore; now?(): number | Date; executors?: Executor | Record<string, Executor>; executionTimeoutMs?: number;
|
|
140
151
|
authorize?(input: { action: ApprovalAction; decider: Decider; decision: 'approve' | 'reject' }): boolean | void | Promise<boolean | void>;
|
|
141
152
|
beforeExecute?(input: { action: ApprovalAction; decider: Decider }): void | Promise<void>;
|
|
153
|
+
/** Checks a corrected input: false (or a throw) refuses with ApprovalError invalid; { value } replaces it. */
|
|
154
|
+
validateInput?(input: { action: ApprovalAction; input: Record<string, unknown>; decider: Decider }): boolean | void | { value: unknown } | Promise<boolean | void | { value: unknown }>;
|
|
142
155
|
onEvent?(event: ApprovalEvent): void | Promise<void>;
|
|
143
156
|
}
|
|
144
157
|
export interface ApprovalQueue {
|
|
145
158
|
propose(input: { type: string; input?: unknown; requestedBy: string; ttlMs?: number; expiresAt?: number | Date; meta?: unknown; id?: string }): Promise<ApprovalAction>;
|
|
146
159
|
get(id: string): Promise<ApprovalAction | null>; list(filter?: ApprovalFilter): Promise<ApprovalAction[]>; expire(): Promise<ApprovalAction[]>;
|
|
147
|
-
approve(id: string, options: { decider: Decider; signal?: AbortSignal }): Promise<{ action: ApprovalAction; result: unknown }>;
|
|
160
|
+
approve(id: string, options: { decider: Decider; signal?: AbortSignal; input?: Record<string, unknown> }): Promise<{ action: ApprovalAction; result: unknown }>;
|
|
148
161
|
reject(id: string, options: { decider: Decider; reason?: string }): Promise<ApprovalAction>;
|
|
149
162
|
}
|
|
150
163
|
export class ApprovalError extends Error { code: 'not_found' | 'expired' | 'already_decided' | 'forbidden' | 'no_executor' | 'execution_failed' | 'invalid' | (string & {}); constructor(code: string, message?: string, options?: { cause?: unknown }) }
|
|
@@ -158,4 +171,16 @@ export function createPostgresLock(pool: PgPool, options?: { prefix?: string }):
|
|
|
158
171
|
export function postgresScheduleSchema(options?: { table?: string }): string;
|
|
159
172
|
export function createPostgresScheduleStore(db: Queryable, options?: { table?: string }): ScheduleStateStore;
|
|
160
173
|
export function postgresApprovalSchema(options?: { table?: string }): string;
|
|
161
|
-
export
|
|
174
|
+
export type ApprovalField = 'id' | 'type' | 'input' | 'requestedBy' | 'meta' | 'status' | 'createdAt' | 'expiresAt' | 'decidedBy' | 'decidedAt' | 'executedAt' | 'result' | 'reason' | 'refusal' | 'decisionInput';
|
|
175
|
+
/** Fields that may be mapped to null (not kept). */
|
|
176
|
+
export type OptionalApprovalField = 'meta' | 'expiresAt' | 'result' | 'reason' | 'refusal' | 'decisionInput';
|
|
177
|
+
export interface PostgresApprovalStoreOptions {
|
|
178
|
+
table?: string;
|
|
179
|
+
/** Column of each field on an existing table (timestamps: timestamptz; input, meta, result, refusal, decisionInput: jsonb). */
|
|
180
|
+
columns?: { [F in Exclude<ApprovalField, OptionalApprovalField>]?: string } & { [F in OptionalApprovalField]?: string | null };
|
|
181
|
+
/** Your status words for the four statuses. */
|
|
182
|
+
statuses?: Partial<Record<ApprovalStatus, string>>;
|
|
183
|
+
/** Only the rows where `column = value` belong to the queue (a journal that also holds other actions). */
|
|
184
|
+
scope?: { column: string; value: unknown };
|
|
185
|
+
}
|
|
186
|
+
export function createPostgresApprovalStore(db: Queryable, options?: PostgresApprovalStoreOptions): ApprovalStore;
|
package/src/schedule.js
CHANGED
|
@@ -8,7 +8,7 @@ function formatter(timeZone) {
|
|
|
8
8
|
if (!format) {
|
|
9
9
|
try {
|
|
10
10
|
format = new Intl.DateTimeFormat('en-GB', { timeZone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
|
11
|
-
} catch (
|
|
11
|
+
} catch (error) { throw new Error(`Unknown time zone: ${timeZone}.`, { cause: error }); }
|
|
12
12
|
formats.set(timeZone, format);
|
|
13
13
|
}
|
|
14
14
|
return format;
|
|
@@ -45,7 +45,11 @@ function normalizeSchedule(schedule) {
|
|
|
45
45
|
if (!schedule || typeof schedule !== 'object') throw new Error('schedule is required.');
|
|
46
46
|
if (schedule.type === 'interval') {
|
|
47
47
|
if (!Number.isFinite(schedule.everyMs) || schedule.everyMs <= 0) throw new Error('interval schedule needs a positive everyMs.');
|
|
48
|
-
return { type: 'interval', everyMs: schedule.everyMs };
|
|
48
|
+
if (schedule.align === undefined || schedule.align === false) return { type: 'interval', everyMs: schedule.everyMs };
|
|
49
|
+
if (schedule.align !== true) throw new Error('interval align must be true or false.');
|
|
50
|
+
// Aligned on the wall clock of the zone, counted from local midnight: every hour on the hour, every 10 minutes on the 10.
|
|
51
|
+
if (schedule.everyMs > DAY_MS || !Number.isInteger(schedule.everyMs / 1000)) throw new Error('an aligned interval needs a whole number of seconds, at most one day.');
|
|
52
|
+
return { type: 'interval', everyMs: schedule.everyMs, align: true };
|
|
49
53
|
}
|
|
50
54
|
if (schedule.type !== 'daily' && schedule.type !== 'weekly') throw new Error('schedule.type must be daily, weekly or interval.');
|
|
51
55
|
const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(String(schedule.at));
|
|
@@ -62,8 +66,22 @@ function normalizeSchedule(schedule) {
|
|
|
62
66
|
/** First run strictly after `after` (ms). `schedule` is as given to the scheduler. */
|
|
63
67
|
function nextRun(schedule, after, timeZone = 'UTC') {
|
|
64
68
|
const s = normalizeSchedule(schedule);
|
|
65
|
-
if (s.type === 'interval') return after + s.everyMs;
|
|
69
|
+
if (s.type === 'interval' && !s.align) return after + s.everyMs;
|
|
66
70
|
checkTimeZone(timeZone);
|
|
71
|
+
if (s.type === 'interval') {
|
|
72
|
+
// Slots restart at each local midnight (a step that does not divide the day ends short before midnight).
|
|
73
|
+
// Counted in elapsed time from midnight: on a time change day the hours stay on the hour, as the offset moves by whole hours.
|
|
74
|
+
let date = localDate(after, timeZone);
|
|
75
|
+
for (let i = 0; i < 3; i += 1) {
|
|
76
|
+
const midnight = zonedTime(date, 0, 0, timeZone);
|
|
77
|
+
const nextMidnight = zonedTime(addDays(date, 1), 0, 0, timeZone);
|
|
78
|
+
const slot = after < midnight ? midnight : midnight + (Math.floor((after - midnight) / s.everyMs) + 1) * s.everyMs;
|
|
79
|
+
if (slot < nextMidnight) return slot;
|
|
80
|
+
date = addDays(date, 1);
|
|
81
|
+
if (nextMidnight > after) return nextMidnight;
|
|
82
|
+
}
|
|
83
|
+
throw new Error('No next run found.');
|
|
84
|
+
}
|
|
67
85
|
const start = localDate(after, timeZone);
|
|
68
86
|
for (let i = 0; i <= 8; i += 1) {
|
|
69
87
|
const date = addDays(start, i);
|
package/src/scheduler.js
CHANGED
|
@@ -43,27 +43,38 @@ function createScheduler(options = {}) {
|
|
|
43
43
|
for (const task of options.tasks) {
|
|
44
44
|
if (!task || typeof task.id !== 'string' || !task.id || typeof task.run !== 'function') throw new Error('Each task needs an id and a run function.');
|
|
45
45
|
if (tasks.has(task.id)) throw new Error(`Duplicate task id: ${task.id}.`);
|
|
46
|
-
|
|
47
|
-
|
|
46
|
+
// `enabled` and `schedule` may be functions (sync or async): read again before every pass, so a setting
|
|
47
|
+
// changed in an admin applies without rebuilding the scheduler. A plain value is checked right away.
|
|
48
|
+
if (typeof task.schedule !== 'function') normalizeSchedule(task.schedule);
|
|
49
|
+
if (task.enabled !== undefined && typeof task.enabled !== 'boolean' && typeof task.enabled !== 'function') throw new Error(`${task.id}: enabled must be a boolean or a function.`);
|
|
50
|
+
tasks.set(task.id, { id: task.id, label: task.label ?? task.id, run: task.run, enabled: task.enabled ?? true, timeZone: checkTimeZone(task.timeZone ?? defaultZone), maxLateMs: task.maxLateMs ?? maxLateMs, schedule: task.schedule });
|
|
48
51
|
}
|
|
49
52
|
const controllers = new Set();
|
|
50
53
|
let timer = null;
|
|
51
54
|
let ticking = null;
|
|
52
|
-
|
|
55
|
+
/** The task as it stands now: `enabled` and `schedule` resolved, the schedule checked, plus a key that changes with it. */
|
|
56
|
+
async function live(task) {
|
|
57
|
+
const enabled = typeof task.enabled === 'function' ? await task.enabled({ id: task.id }) : task.enabled;
|
|
58
|
+
if (typeof enabled !== 'boolean') throw new Error(`${task.id}: enabled() must resolve to a boolean.`);
|
|
59
|
+
const schedule = typeof task.schedule === 'function' ? await task.schedule({ id: task.id }) : task.schedule;
|
|
60
|
+
const key = JSON.stringify({ ...normalizeSchedule(schedule), timeZone: task.timeZone });
|
|
61
|
+
return { enabled, schedule, key };
|
|
62
|
+
}
|
|
63
|
+
const upcoming = (task, from, current) => nextRun(current.schedule, from, task.timeZone);
|
|
53
64
|
const stopped = async () => { try { return Boolean(await options.shouldStop?.()); } catch (_error) { return true; } }; // Fail closed.
|
|
54
65
|
const blank = (task) => ({ id: task.id, status: 'scheduled', nextRunAt: null, lastStartedAt: null, lastRunAt: null, lastResult: null, lastError: null, skipReason: null, lastManual: false });
|
|
55
66
|
const read = async (task) => ({ ...blank(task), ...(await store.get(task.id)) });
|
|
56
67
|
const find = (id) => { const task = tasks.get(id); if (!task) throw new SchedulerError('unknown_task'); return task; };
|
|
57
68
|
|
|
58
|
-
async function skip(task, reason, state) {
|
|
59
|
-
await store.set(task.id, { ...state, status: 'skipped', skipReason: reason, nextRunAt: upcoming(task, now()) });
|
|
69
|
+
async function skip(task, reason, state, current) {
|
|
70
|
+
await store.set(task.id, { ...state, status: 'skipped', skipReason: reason, nextRunAt: upcoming(task, now(), current), scheduleKey: current.key });
|
|
60
71
|
emit({ type: 'skipped', id: task.id, reason });
|
|
61
72
|
return { id: task.id, status: 'skipped', reason };
|
|
62
73
|
}
|
|
63
|
-
async function execute(task, { manual, signal }) {
|
|
74
|
+
async function execute(task, { manual, signal, current }) {
|
|
64
75
|
if (await stopped()) {
|
|
65
76
|
if (manual) throw new SchedulerError('stopped');
|
|
66
|
-
return skip(task, 'stopped', await read(task));
|
|
77
|
+
return skip(task, 'stopped', await read(task), current);
|
|
67
78
|
}
|
|
68
79
|
const held = await lock.acquire(task.id);
|
|
69
80
|
if (!held) { if (manual) throw new SchedulerError('running'); return { id: task.id, status: 'locked' }; }
|
|
@@ -98,7 +109,8 @@ function createScheduler(options = {}) {
|
|
|
98
109
|
...state, status, lastStartedAt: startedAt, lastManual: manual,
|
|
99
110
|
lastRunAt: status === 'skipped' ? state.lastRunAt : finished, lastResult: status === 'ok' ? result : state.lastResult,
|
|
100
111
|
lastError: status === 'ok' ? null : (error ?? state.lastError), skipReason: reason,
|
|
101
|
-
nextRunAt: !manual || !state.nextRunAt ? upcoming(task, finished) : state.nextRunAt
|
|
112
|
+
nextRunAt: !manual || !state.nextRunAt ? upcoming(task, finished, current) : state.nextRunAt,
|
|
113
|
+
scheduleKey: !manual || !state.nextRunAt ? current.key : state.scheduleKey
|
|
102
114
|
});
|
|
103
115
|
emit({ type: status === 'ok' ? 'done' : status, id: task.id, manual, ...(error ? { error: error.message } : {}) });
|
|
104
116
|
return { id: task.id, status, ...(status === 'ok' ? { result } : {}), ...(error ? { error: error.message } : {}), ...(reason ? { reason } : {}) };
|
|
@@ -112,14 +124,25 @@ function createScheduler(options = {}) {
|
|
|
112
124
|
async function pass() {
|
|
113
125
|
const results = [];
|
|
114
126
|
for (const task of tasks.values()) {
|
|
115
|
-
if (!task.enabled) continue;
|
|
116
127
|
try {
|
|
128
|
+
const current = await live(task);
|
|
117
129
|
const at = now();
|
|
118
130
|
const state = await read(task);
|
|
119
|
-
if (!
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
131
|
+
if (!current.enabled) {
|
|
132
|
+
// Forget the plan: switched back on, the task is planned afresh instead of being skipped as late.
|
|
133
|
+
if (state.nextRunAt != null) await store.set(task.id, { ...state, nextRunAt: null, scheduleKey: null });
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
// A state written before scheduleKey existed keeps its plan; a changed schedule is planned again.
|
|
137
|
+
const changed = state.nextRunAt != null && state.scheduleKey != null && state.scheduleKey !== current.key;
|
|
138
|
+
if (!state.nextRunAt || changed) {
|
|
139
|
+
await store.set(task.id, { ...state, nextRunAt: upcoming(task, at, current), scheduleKey: current.key });
|
|
140
|
+
results.push({ id: task.id, status: changed ? 'rescheduled' : 'scheduled' });
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (state.nextRunAt > at) { if (state.scheduleKey == null) await store.set(task.id, { ...state, scheduleKey: current.key }); continue; }
|
|
144
|
+
if (at - state.nextRunAt > task.maxLateMs) { results.push(await skip(task, 'late', state, current)); continue; }
|
|
145
|
+
results.push(await execute(task, { manual: false, current }));
|
|
123
146
|
} catch (error) { try { options.onError?.(error, task.id); } catch (_ignored) { /* An observer never breaks the scheduler. */ } }
|
|
124
147
|
}
|
|
125
148
|
return results;
|
|
@@ -134,11 +157,15 @@ function createScheduler(options = {}) {
|
|
|
134
157
|
get started() { return timer !== null; },
|
|
135
158
|
/** Aborts every run in progress in this process (their `signal` aborts). */
|
|
136
159
|
abortAll(reason = new SchedulerError('stopped')) { for (const c of controllers) c.abort(reason); },
|
|
137
|
-
/** Manual run. Throws SchedulerError: unknown_task, stopped, running. Does not move the next planned run. */
|
|
138
|
-
async run(id, { signal } = {}) {
|
|
160
|
+
/** Manual run (also allowed while the task is disabled). Throws SchedulerError: unknown_task, stopped, running. Does not move the next planned run. */
|
|
161
|
+
async run(id, { signal } = {}) { const task = find(id); return execute(task, { manual: true, signal, current: await live(task) }); },
|
|
139
162
|
/** State of one task, or of all of them. `nextRunAt` is computed when the task was never planned. */
|
|
140
163
|
async state(id) {
|
|
141
|
-
const describe = async (task) => {
|
|
164
|
+
const describe = async (task) => {
|
|
165
|
+
const s = await read(task);
|
|
166
|
+
const current = await live(task);
|
|
167
|
+
return { ...s, label: task.label, enabled: current.enabled, schedule: copy(current.schedule), timeZone: task.timeZone, nextRunAt: current.enabled ? (s.nextRunAt ?? upcoming(task, now(), current)) : null };
|
|
168
|
+
};
|
|
142
169
|
if (id !== undefined) return describe(find(id));
|
|
143
170
|
return Promise.all([...tasks.values()].map(describe));
|
|
144
171
|
}
|