@astratra/agent 1.1.0 → 1.3.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 +139 -0
- package/README.md +134 -1
- package/package.json +1 -1
- package/src/approvals.js +168 -0
- package/src/coordinationPostgres.js +198 -0
- package/src/index.d.ts +107 -0
- package/src/index.js +3 -1
- package/src/schedule.js +94 -0
- package/src/scheduler.js +174 -0
package/README.fr.md
CHANGED
|
@@ -156,6 +156,145 @@ Avec des gardes, `turn` reçoit `unmask(texte)` : il rend les vrais mots d'un te
|
|
|
156
156
|
de `@astratra/ai` (1.10.0), on montre ainsi la réponse en flux, sans ses repères (`#PERSON_0001`). La réponse finale
|
|
157
157
|
passe toujours par la garde de sortie (fuites, modération) ; ce qui part au modèle reste masqué.
|
|
158
158
|
|
|
159
|
+
## Ordonnanceur (tâches programmées)
|
|
160
|
+
|
|
161
|
+
Des tâches qui tournent à heure fixe chaque jour, un jour de la semaine, ou à intervalle, dans un fuseau horaire IANA.
|
|
162
|
+
Rien ne démarre au chargement du module : on appelle `start()`.
|
|
163
|
+
|
|
164
|
+
```js
|
|
165
|
+
const { createScheduler } = require('@astratra/agent');
|
|
166
|
+
|
|
167
|
+
const scheduler = createScheduler({
|
|
168
|
+
timeZone: 'Europe/Paris',
|
|
169
|
+
maxLateMs: 6 * 3600 * 1000, // un passage manqué de plus de 6 h est sauté, pas lancé
|
|
170
|
+
shouldStop: () => reglages.arretUrgence, // consulté avant ET pendant chaque passage
|
|
171
|
+
tasks: [
|
|
172
|
+
{ id: 'rapport-du-jour', schedule: { type: 'daily', at: '07:00' }, run: ({ signal }) => produireRapport(signal) },
|
|
173
|
+
{ id: 'resume-hebdo', schedule: { type: 'weekly', day: 'monday', at: '07:30' }, run: envoyerResume },
|
|
174
|
+
{ id: 'nettoyage', schedule: { type: 'interval', everyMs: 15 * 60 * 1000 }, run: nettoyer }
|
|
175
|
+
]
|
|
176
|
+
});
|
|
177
|
+
scheduler.start(); // passage périodique (tous les tickMs, 30 s par défaut)
|
|
178
|
+
await scheduler.run('nettoyage'); // lancement manuel ; ne déplace pas le prochain passage prévu
|
|
179
|
+
await scheduler.state(); // lastRunAt, nextRunAt, status, lastResult, lastError, skipReason
|
|
180
|
+
scheduler.abortAll(); // coupe tous les passages en cours (leur signal s'annule)
|
|
181
|
+
scheduler.stop(); // arrête le passage périodique
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
- **Programmations** : `{ type: 'daily', at: 'HH:MM' }`, `{ type: 'weekly', day | days, at }` (1 = lundi … 7 =
|
|
185
|
+
dimanche, ou `'monday'`), `{ type: 'interval', everyMs }`. `timeZone` est global ou propre à la tâche. Les
|
|
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
|
+
l'heure d'été) part juste après le trou ; une heure qui existe deux fois part une seule fois, à la première
|
|
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.
|
|
197
|
+
- **Jamais deux fois en même temps** : chaque passage prend un `lock` (`acquire(cle)` → `{ release() }` ou `null`). Par
|
|
198
|
+
défaut un verrou dans le processus ; avec plusieurs processus, `createPostgresLock(pool)` (`pg_try_advisory_lock`,
|
|
199
|
+
tenu sur une connexion du pool jusqu'à `release()`, libéré si le processus meurt). L'état est relu sous le verrou :
|
|
200
|
+
un processus qui perd la course ne relance pas une tâche qu'un autre vient de finir. Partagez le `store` (plus bas)
|
|
201
|
+
entre les processus.
|
|
202
|
+
- **Passages manqués** : un passage échu depuis plus de `maxLateMs` (par tâche ou global, 1 h par défaut) est sauté
|
|
203
|
+
(`skipReason: 'late'`) et le suivant est programmé. En deçà du délai, il part quand même.
|
|
204
|
+
- **Arrêt global** : `shouldStop()` est lu avant chaque passage (un passage programmé est sauté avec `'stopped'`, un
|
|
205
|
+
lancement manuel lève `SchedulerError('stopped')`) puis toutes les `stopCheckMs` (1 s) pendant l'exécution ; s'il
|
|
206
|
+
rend vrai, le `signal` de la tâche s'annule. Un `shouldStop` qui échoue vaut arrêt. Un passage coupé ainsi n'est pas
|
|
207
|
+
compté comme fait.
|
|
208
|
+
- **État** : `status` vaut `scheduled`, `running` (indicatif : le verrou fait foi), `ok`, `error` ou `skipped`.
|
|
209
|
+
`lastResult` (JSON) est repassé au passage suivant en `previous`, pour les tâches qui évitent de se répéter.
|
|
210
|
+
- **Stockage de l'état** : mémoire par défaut ; `createPostgresScheduleStore(db)` le garde dans une table
|
|
211
|
+
(`postgresScheduleSchema()` la crée).
|
|
212
|
+
- **Tests** : injectez `now` (fonction rendant des ms ou une `Date`) et appelez `tick()` vous-même.
|
|
213
|
+
- `onEvent` (`start`, `done`, `error`, `skipped`) et `onError` observent l'ordonnanceur sans jamais le casser.
|
|
214
|
+
|
|
215
|
+
## File d'actions en attente d'approbation
|
|
216
|
+
|
|
217
|
+
Des actions qu'une personne doit approuver, **détachées de toute exécution en cours** : on propose maintenant, on décide
|
|
218
|
+
des heures ou des jours plus tard. Le paquet n'authentifie personne : vous contrôlez l'identité et le rôle (dans votre
|
|
219
|
+
route, ou dans `authorize`) et passez le décideur. L'action est exécutée par **votre** exécuteur.
|
|
220
|
+
|
|
221
|
+
```js
|
|
222
|
+
const { createApprovalQueue, ApprovalRefused } = require('@astratra/agent');
|
|
223
|
+
|
|
224
|
+
const queue = createApprovalQueue({
|
|
225
|
+
executors: {
|
|
226
|
+
publier: async ({ input, idempotencyKey, signal }) => {
|
|
227
|
+
if (!input.titre) throw new ApprovalRefused('incomplet', { manquants: ['titre'] }); // rien n'a été fait
|
|
228
|
+
return await publierArticle(input, { idempotencyKey, signal }); // le résultat est gardé
|
|
229
|
+
}
|
|
230
|
+
},
|
|
231
|
+
authorize: ({ decider }) => decider.role === 'proprietaire', // votre règle ; false ou une exception = interdit
|
|
232
|
+
beforeExecute: () => { if (reglages.arretUrgence) throw new Error('arrêt'); }, // dernier contrôle, facultatif
|
|
233
|
+
onEvent: ({ type, action }) => journal(type, action.id) // proposed, approved, rejected, refused, failed, expired
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
const action = await queue.propose({ type: 'publier', input: { titre: 'Bonjour' }, requestedBy: 'assistant', ttlMs: 3 * 24 * 3600 * 1000 });
|
|
237
|
+
await queue.list({ status: 'pending' });
|
|
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
|
|
240
|
+
await queue.reject(action.id, { decider: { id: 'u-1', role: 'proprietaire' }, reason: 'pas maintenant' });
|
|
241
|
+
await queue.expire(); // fait aussi par list/approve/reject
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
- **Une seule exécution** : `approve` *réserve* d'abord l'action (`pending` → `approved`) en une étape atomique du
|
|
245
|
+
stockage, puis lance l'exécuteur. Deux approbations simultanées : l'une s'exécute, l'autre reçoit
|
|
246
|
+
`ApprovalError('already_decided')`. Avec PostgreSQL, la réservation est un seul `UPDATE` conditionnel. L'exécuteur
|
|
247
|
+
reçoit `idempotencyKey` (l'identifiant de l'action) : utilisez-la côté système externe, car une file ne peut pas
|
|
248
|
+
défaire un effet survenu avant un plantage. Une action restée `approved` avec `executedAt: null` après un plantage se
|
|
249
|
+
retrouve par `list({ status: 'approved' })`.
|
|
250
|
+
- **Refus** : si l'exécuteur lève `ApprovalRefused(reason, details)`, rien n'a eu lieu : l'action repasse en `pending`
|
|
251
|
+
avec `refusal: { reason, details, at, by }` et l'erreur est relancée. Toute autre erreur fait de même avec
|
|
252
|
+
`reason: 'execution_failed'` et est relancée en `ApprovalError('execution_failed')` (l'originale est dans `cause`).
|
|
253
|
+
- **Expiration** : `ttlMs` ou `expiresAt` à `propose`. Une action expirée ne peut plus être approuvée ni rejetée
|
|
254
|
+
(`ApprovalError('expired')`), même si le balayage n'est pas encore passé. `expire()` les marque `expired` ;
|
|
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.
|
|
261
|
+
- **Erreurs** (`ApprovalError.code`) : `not_found`, `expired`, `already_decided`, `forbidden`, `no_executor`,
|
|
262
|
+
`execution_failed`, `invalid`.
|
|
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.
|
|
296
|
+
- Les entrées et résultats conservés doivent être du JSON.
|
|
297
|
+
|
|
159
298
|
## Tests
|
|
160
299
|
|
|
161
300
|
`npm test -w @astratra/agent`. Les tests PostgreSQL réels ne tournent qu'avec
|
package/README.md
CHANGED
|
@@ -324,9 +324,142 @@ With guards, `turn` receives `unmask(text)`: the real words of a (masked) model
|
|
|
324
324
|
`@astratra/ai` (1.10.0) you can show a streamed answer without its masking markers (`#PERSON_0001`). The final answer
|
|
325
325
|
still goes through the output guard (leaks, moderation); what is sent to the model stays masked.
|
|
326
326
|
|
|
327
|
+
## Scheduler (timed tasks)
|
|
328
|
+
|
|
329
|
+
Tasks that run at a fixed time of day, on a weekday, or at an interval, in an IANA time zone. Nothing starts when the
|
|
330
|
+
module is loaded: you call `start()`.
|
|
331
|
+
|
|
332
|
+
```js
|
|
333
|
+
const { createScheduler } = require('@astratra/agent');
|
|
334
|
+
|
|
335
|
+
const scheduler = createScheduler({
|
|
336
|
+
timeZone: 'Europe/Paris',
|
|
337
|
+
maxLateMs: 6 * 3600 * 1000, // a run missed by more than 6 h is skipped, not run
|
|
338
|
+
shouldStop: () => settings.killSwitch, // checked before AND during each run
|
|
339
|
+
tasks: [
|
|
340
|
+
{ id: 'daily-report', schedule: { type: 'daily', at: '07:00' }, run: ({ signal }) => buildReport(signal) },
|
|
341
|
+
{ id: 'weekly-digest', schedule: { type: 'weekly', day: 'monday', at: '07:30' }, run: sendDigest },
|
|
342
|
+
{ id: 'cleanup', schedule: { type: 'interval', everyMs: 15 * 60 * 1000 }, run: cleanUp }
|
|
343
|
+
]
|
|
344
|
+
});
|
|
345
|
+
scheduler.start(); // periodic pass (every tickMs, 30 s by default)
|
|
346
|
+
await scheduler.run('cleanup'); // manual run; does not move the next planned run
|
|
347
|
+
await scheduler.state(); // lastRunAt, nextRunAt, status, lastResult, lastError, skipReason
|
|
348
|
+
scheduler.abortAll(); // cuts every run in progress (their signal aborts)
|
|
349
|
+
scheduler.stop(); // stops the periodic pass
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
- **Schedules**: `{ type: 'daily', at: 'HH:MM' }`, `{ type: 'weekly', day | days, at }` (1 = Monday … 7 = Sunday, or
|
|
353
|
+
`'monday'`), `{ type: 'interval', everyMs }`. `timeZone` is global or per task. Daylight saving is handled: 07:00
|
|
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
|
+
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`.
|
|
365
|
+
- **Never twice at once**: each run takes a `lock` (`acquire(key)` → `{ release() }` or `null`). The default is an
|
|
366
|
+
in-process lock; with several processes pass `createPostgresLock(pool)` (`pg_try_advisory_lock`, held on one pooled
|
|
367
|
+
connection until released, freed if the process dies). The run state is re-read under the lock, so a process that
|
|
368
|
+
lost the race does not run a task another one just finished. Share the `store` (below) between processes.
|
|
369
|
+
- **Missed runs**: a due run late by more than `maxLateMs` (per task or global, 1 h by default) is skipped with
|
|
370
|
+
`skipReason: 'late'`, and the next one is planned. Within the delay it still runs.
|
|
371
|
+
- **Global stop**: `shouldStop()` is read before each run (a scheduled run is skipped with `'stopped'`, a manual run
|
|
372
|
+
throws `SchedulerError('stopped')`) and every `stopCheckMs` (1 s) during a run; when it returns true the task's
|
|
373
|
+
`signal` aborts. A failing `shouldStop` counts as stopped. A run cut this way is not counted as done.
|
|
374
|
+
- **State**: `status` is `scheduled`, `running` (informative: the lock is the truth), `ok`, `error` or `skipped`.
|
|
375
|
+
`lastResult` (JSON) is passed to the next run as `previous`, for tasks that avoid repeating themselves.
|
|
376
|
+
- **State store**: memory by default; `createPostgresScheduleStore(db)` keeps it in a table
|
|
377
|
+
(`postgresScheduleSchema()` creates it).
|
|
378
|
+
- **Tests**: inject `now` (a function returning ms or a `Date`) and call `tick()` yourself.
|
|
379
|
+
- `onEvent` (`start`, `done`, `error`, `skipped`) and `onError` observe the scheduler; they never break it.
|
|
380
|
+
|
|
381
|
+
## Approval queue (actions waiting for a decision)
|
|
382
|
+
|
|
383
|
+
Actions that a person must approve, **detached from any running task**: an action is proposed now and decided hours or
|
|
384
|
+
days later. The package does not authenticate anyone: you check identity and role (in your route, or in `authorize`) and
|
|
385
|
+
pass the decider. The action is executed by **your** executor.
|
|
386
|
+
|
|
387
|
+
```js
|
|
388
|
+
const { createApprovalQueue, ApprovalRefused } = require('@astratra/agent');
|
|
389
|
+
|
|
390
|
+
const queue = createApprovalQueue({
|
|
391
|
+
executors: {
|
|
392
|
+
publish: async ({ input, idempotencyKey, signal }) => {
|
|
393
|
+
if (!input.title) throw new ApprovalRefused('incomplete', { missing: ['title'] }); // nothing done
|
|
394
|
+
return await publishPost(input, { idempotencyKey, signal }); // the result is stored
|
|
395
|
+
}
|
|
396
|
+
},
|
|
397
|
+
authorize: ({ decider }) => decider.role === 'owner', // your rule; false or a throw = forbidden
|
|
398
|
+
beforeExecute: () => { if (settings.killSwitch) throw new Error('stopped'); }, // optional last check
|
|
399
|
+
onEvent: ({ type, action }) => audit(type, action.id) // proposed, approved, rejected, refused, failed, expired
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
const action = await queue.propose({ type: 'publish', input: { title: 'Hello' }, requestedBy: 'assistant', ttlMs: 3 * 24 * 3600 * 1000 });
|
|
403
|
+
await queue.list({ status: 'pending' });
|
|
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
|
|
406
|
+
await queue.reject(action.id, { decider: { id: 'user-1', role: 'owner' }, reason: 'not now' });
|
|
407
|
+
await queue.expire(); // also done by list/approve/reject
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
- **Once only**: `approve` first *reserves* the action (`pending` → `approved`) in one atomic step of the store, then
|
|
411
|
+
runs the executor. Two approvals at the same time: one runs, the other gets `ApprovalError('already_decided')`.
|
|
412
|
+
With PostgreSQL the reservation is one conditional `UPDATE`. The executor receives `idempotencyKey` (the action id):
|
|
413
|
+
use it with the external system, because a crash after the effect cannot be undone by a queue. An action stuck in
|
|
414
|
+
`approved` with `executedAt: null` after a crash is findable with `list({ status: 'approved' })`.
|
|
415
|
+
- **Refusal**: if the executor throws `ApprovalRefused(reason, details)`, nothing happened: the action goes back to
|
|
416
|
+
`pending` with `refusal: { reason, details, at, by }`, and the error is rethrown. Any other error does the same with
|
|
417
|
+
`reason: 'execution_failed'` and is rethrown as `ApprovalError('execution_failed')` (the original is in `cause`).
|
|
418
|
+
- **Expiry**: `ttlMs` or `expiresAt` at `propose`. An expired action cannot be approved or rejected
|
|
419
|
+
(`ApprovalError('expired')`), even if the sweep has not run yet. `expire()` marks them `expired`; call it from a
|
|
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.
|
|
426
|
+
- **Errors** (`ApprovalError.code`): `not_found`, `expired`, `already_decided`, `forbidden`, `no_executor`,
|
|
427
|
+
`execution_failed`, `invalid`.
|
|
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.
|
|
458
|
+
- Persisted inputs and results must be JSON.
|
|
459
|
+
|
|
327
460
|
## Tests
|
|
328
461
|
|
|
329
462
|
`npm test -w @astratra/agent` uses `node --test`; the guard tests run on
|
|
330
463
|
`@astratra/ai/guards/testing` with no model. Real PostgreSQL tests run only
|
|
331
464
|
with `AGENT_TEST_DATABASE_URL` naming a database ending in `_test`; otherwise
|
|
332
|
-
that test is skipped (feedback tests included). The tests create and drop their own randomly named tables.
|
|
465
|
+
that test is skipped (feedback, scheduler lock and approval store tests included). The tests create and drop their own randomly named tables.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/agent",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.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
6
|
"node": ">=20"
|
package/src/approvals.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Queue of proposed actions waiting for a person's decision. Detached from any running task: an action is
|
|
3
|
+
// proposed now and decided hours or days later. The package never authenticates the decider: the caller does,
|
|
4
|
+
// then passes the identity (and an `authorize` callback for roles). The action runs once, by the caller's executor.
|
|
5
|
+
const { randomUUID } = require('node:crypto');
|
|
6
|
+
|
|
7
|
+
const STATUSES = Object.freeze(['pending', 'approved', 'rejected', 'expired']);
|
|
8
|
+
class ApprovalError extends Error {
|
|
9
|
+
constructor(code, message, options) { super(message || code, options); this.name = 'ApprovalError'; this.code = code; }
|
|
10
|
+
}
|
|
11
|
+
/** Thrown by an executor that declines to act (incomplete record, amount too high…): nothing happened, the action stays pending. */
|
|
12
|
+
class ApprovalRefused extends Error {
|
|
13
|
+
constructor(reason, details) { super(reason); this.name = 'ApprovalRefused'; this.reason = reason; this.details = details ?? null; }
|
|
14
|
+
}
|
|
15
|
+
const copy = (value) => value == null ? null : JSON.parse(JSON.stringify(value));
|
|
16
|
+
const toMs = (value) => value instanceof Date ? value.getTime() : value;
|
|
17
|
+
const who = (decider) => typeof decider === 'string' ? decider : decider?.id;
|
|
18
|
+
|
|
19
|
+
function createMemoryApprovalStore() {
|
|
20
|
+
const actions = new Map();
|
|
21
|
+
const out = (a) => copy(a);
|
|
22
|
+
return {
|
|
23
|
+
async create(action) { if (actions.has(action.id)) throw new Error('Action already exists.'); actions.set(action.id, copy(action)); return out(action); },
|
|
24
|
+
async get(id) { return out(actions.get(id)); },
|
|
25
|
+
async list({ status, type, requestedBy, limit = 50, before } = {}) {
|
|
26
|
+
return [...actions.values()]
|
|
27
|
+
.filter((a) => (!status || a.status === status) && (!type || a.type === type) && (!requestedBy || a.requestedBy === requestedBy) && (before == null || a.createdAt < before))
|
|
28
|
+
.sort((a, b) => b.createdAt - a.createdAt || (a.id < b.id ? -1 : 1)).slice(0, limit).map(out);
|
|
29
|
+
},
|
|
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, decisionInput = null) {
|
|
32
|
+
const a = actions.get(id);
|
|
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, decisionInput: copy(decisionInput) }); return out(a);
|
|
35
|
+
},
|
|
36
|
+
async finish(id, result, at) {
|
|
37
|
+
const a = actions.get(id);
|
|
38
|
+
if (!a || a.status !== 'approved' || a.executedAt != null) return null;
|
|
39
|
+
Object.assign(a, { result: copy(result), executedAt: at }); return out(a);
|
|
40
|
+
},
|
|
41
|
+
async revert(id, decidedBy, refusal) {
|
|
42
|
+
const a = actions.get(id);
|
|
43
|
+
if (!a || a.status !== 'approved' || a.decidedBy !== decidedBy || a.executedAt != null) return null;
|
|
44
|
+
Object.assign(a, { status: 'pending', decidedBy: null, decidedAt: null, decisionInput: null, refusal: copy(refusal) }); return out(a);
|
|
45
|
+
},
|
|
46
|
+
async reject(id, decidedBy, reason, at) {
|
|
47
|
+
const a = actions.get(id);
|
|
48
|
+
if (!a || a.status !== 'pending' || (a.expiresAt != null && a.expiresAt <= at)) return null;
|
|
49
|
+
Object.assign(a, { status: 'rejected', decidedBy, decidedAt: at, reason: reason ?? null }); return out(a);
|
|
50
|
+
},
|
|
51
|
+
async expire(at) {
|
|
52
|
+
const expired = [];
|
|
53
|
+
for (const a of actions.values()) if (a.status === 'pending' && a.expiresAt != null && a.expiresAt <= at) { Object.assign(a, { status: 'expired', decidedAt: at }); expired.push(out(a)); }
|
|
54
|
+
return expired;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function createApprovalQueue(options = {}) {
|
|
59
|
+
const store = options.store ?? createMemoryApprovalStore();
|
|
60
|
+
const now = () => toMs((options.now ?? Date.now)());
|
|
61
|
+
const executors = options.executors;
|
|
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', 'validateInput']) if (options[name] != null && typeof options[name] !== 'function') throw new Error(`${name} must be a function.`);
|
|
64
|
+
const executionTimeoutMs = options.executionTimeoutMs ?? 30000;
|
|
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
|
+
const executorFor = (type) => typeof executors === 'function' ? executors : executors?.[type];
|
|
67
|
+
|
|
68
|
+
async function expire() {
|
|
69
|
+
const expired = await store.expire(now());
|
|
70
|
+
for (const action of expired) emit('expired', action);
|
|
71
|
+
return expired;
|
|
72
|
+
}
|
|
73
|
+
async function pendingOrThrow(id) {
|
|
74
|
+
const action = await store.get(id);
|
|
75
|
+
if (!action) throw new ApprovalError('not_found');
|
|
76
|
+
if (action.status === 'expired' || (action.status === 'pending' && action.expiresAt != null && action.expiresAt <= now())) throw new ApprovalError('expired');
|
|
77
|
+
if (action.status !== 'pending') throw new ApprovalError('already_decided');
|
|
78
|
+
return action;
|
|
79
|
+
}
|
|
80
|
+
async function authorize(action, decider, decision) {
|
|
81
|
+
if (!who(decider)) throw new ApprovalError('invalid', 'decider is required.');
|
|
82
|
+
if (!options.authorize) return;
|
|
83
|
+
let allowed;
|
|
84
|
+
try { allowed = await options.authorize({ action, decider, decision }); } catch (error) { throw new ApprovalError('forbidden', 'Not allowed to decide this action.', { cause: error }); }
|
|
85
|
+
if (allowed === false) throw new ApprovalError('forbidden', 'Not allowed to decide this action.');
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
/** Records a proposed action. `ttlMs` or `expiresAt` (ms or Date) set its expiry; without either it never expires. */
|
|
89
|
+
async propose({ type, input = {}, requestedBy, ttlMs, expiresAt, meta, id = randomUUID() } = {}) {
|
|
90
|
+
if (typeof type !== 'string' || !type) throw new ApprovalError('invalid', 'type is required.');
|
|
91
|
+
if (typeof requestedBy !== 'string' || !requestedBy) throw new ApprovalError('invalid', 'requestedBy is required.');
|
|
92
|
+
if (executors && typeof executors === 'object' && !executors[type]) throw new ApprovalError('no_executor', `No executor for ${type}.`);
|
|
93
|
+
const at = now();
|
|
94
|
+
const expiry = expiresAt != null ? toMs(expiresAt) : ttlMs != null ? at + ttlMs : null;
|
|
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, decisionInput: null });
|
|
97
|
+
emit('proposed', action);
|
|
98
|
+
return action;
|
|
99
|
+
},
|
|
100
|
+
get: (id) => store.get(id),
|
|
101
|
+
/** Lists actions, most recent first. Expired ones are swept first. */
|
|
102
|
+
async list(filter) { await expire(); return store.list(filter); },
|
|
103
|
+
/** Marks the pending actions past their expiry as `expired`. Safe to call from a timer or a scheduler task. */
|
|
104
|
+
expire,
|
|
105
|
+
/**
|
|
106
|
+
* Approves and executes. The action is reserved atomically first, so concurrent approvals run it once.
|
|
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:
|
|
110
|
+
* the action then goes back to `pending` with `refusal` set and the error is rethrown. Resolves `{ action, result }`.
|
|
111
|
+
*/
|
|
112
|
+
async approve(id, { decider, signal, input } = {}) {
|
|
113
|
+
await expire();
|
|
114
|
+
const pending = await pendingOrThrow(id);
|
|
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');
|
|
130
|
+
const execute = executorFor(pending.type);
|
|
131
|
+
if (!execute) throw new ApprovalError('no_executor', `No executor for ${pending.type}.`);
|
|
132
|
+
const by = who(decider);
|
|
133
|
+
const action = await store.reserve(id, by, now(), decisionInput);
|
|
134
|
+
if (!action) { await pendingOrThrow(id); throw new ApprovalError('already_decided'); } // Lost the race: say why.
|
|
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
|
+
}
|
|
141
|
+
let result;
|
|
142
|
+
try {
|
|
143
|
+
await options.beforeExecute?.({ action, decider });
|
|
144
|
+
result = copy(await execute({ action, input: action.decisionInput ?? action.input, proposedInput: action.input, decider, idempotencyKey: action.id, signal: signal ?? globalThis.AbortSignal.timeout(executionTimeoutMs) }));
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (error instanceof ApprovalRefused) { await back({ reason: error.reason, details: error.details }); emit('refused', action, { reason: error.reason }); throw error; }
|
|
147
|
+
if (error instanceof ApprovalError) { await back({ reason: error.code, details: null }); throw error; }
|
|
148
|
+
await back({ reason: 'execution_failed', details: null });
|
|
149
|
+
emit('failed', action, { error: String(error?.message ?? error) });
|
|
150
|
+
throw new ApprovalError('execution_failed', 'The execution failed.', { cause: error });
|
|
151
|
+
}
|
|
152
|
+
const finished = await store.finish(id, result, now());
|
|
153
|
+
emit('approved', finished, { result });
|
|
154
|
+
return { action: finished, result };
|
|
155
|
+
},
|
|
156
|
+
/** Rejects a pending action. Resolves the rejected action. */
|
|
157
|
+
async reject(id, { decider, reason } = {}) {
|
|
158
|
+
await expire();
|
|
159
|
+
const pending = await pendingOrThrow(id);
|
|
160
|
+
await authorize(pending, decider, 'reject');
|
|
161
|
+
const action = await store.reject(id, who(decider), reason ?? null, now());
|
|
162
|
+
if (!action) { await pendingOrThrow(id); throw new ApprovalError('already_decided'); }
|
|
163
|
+
emit('rejected', action);
|
|
164
|
+
return action;
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
module.exports = { APPROVAL_STATUSES: STATUSES, ApprovalError, ApprovalRefused, createApprovalQueue, createMemoryApprovalStore };
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// PostgreSQL implementations for the scheduler (lock, run state) and the approval queue (actions).
|
|
3
|
+
// Schema creation is explicit and idempotent; every value goes through SQL parameters.
|
|
4
|
+
function identifier(name, fallback) {
|
|
5
|
+
const value = name ?? fallback;
|
|
6
|
+
if (typeof value !== 'string' || !/^[a-zA-Z_][a-zA-Z0-9_]{0,47}$/.test(value)) throw new Error('table must be a plain SQL identifier of at most 48 characters.');
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
const json = (value) => typeof value === 'string' ? JSON.parse(value) : value;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Lock on `pg_try_advisory_lock`. It belongs to a database session, so `pool` must offer `connect()` (a pg Pool):
|
|
13
|
+
* one client is held per lock until `release()`, and a crashed process frees its locks when its connection drops.
|
|
14
|
+
*/
|
|
15
|
+
function createPostgresLock(pool, options = {}) {
|
|
16
|
+
if (!pool || typeof pool.connect !== 'function') throw new Error('A pool with connect() is required (advisory locks belong to one session).');
|
|
17
|
+
const prefix = options.prefix ?? 'astratra:agent:lock:';
|
|
18
|
+
return {
|
|
19
|
+
async acquire(key) {
|
|
20
|
+
const client = await pool.connect();
|
|
21
|
+
const name = `${prefix}${key}`;
|
|
22
|
+
try {
|
|
23
|
+
const { rows: [row] } = await client.query('SELECT pg_try_advisory_lock(hashtext($1)::bigint) AS ok', [name]);
|
|
24
|
+
if (!row.ok) { client.release(); return null; }
|
|
25
|
+
} catch (error) { client.release(); throw error; }
|
|
26
|
+
let done = false;
|
|
27
|
+
return {
|
|
28
|
+
async release() {
|
|
29
|
+
if (done) return; done = true;
|
|
30
|
+
try { await client.query('SELECT pg_advisory_unlock(hashtext($1)::bigint)', [name]); } finally { client.release(); }
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
function postgresScheduleSchema(options) {
|
|
37
|
+
const table = identifier(options?.table, 'astratra_agent_schedule');
|
|
38
|
+
return `CREATE TABLE IF NOT EXISTS "${table}" (id text PRIMARY KEY, data jsonb NOT NULL);`;
|
|
39
|
+
}
|
|
40
|
+
/** Run state of the scheduler tasks, shared by every process. */
|
|
41
|
+
function createPostgresScheduleStore(db, options) {
|
|
42
|
+
if (!db || typeof db.query !== 'function') throw new Error('A database with query(sql, params) is required.');
|
|
43
|
+
const table = identifier(options?.table, 'astratra_agent_schedule');
|
|
44
|
+
return {
|
|
45
|
+
async get(id) { const { rows } = await db.query(`SELECT data FROM "${table}" WHERE id = $1`, [id]); return rows[0] ? json(rows[0].data) : null; },
|
|
46
|
+
async set(id, state) { await db.query(`INSERT INTO "${table}" (id, data) VALUES ($1, $2::jsonb) ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data`, [id, JSON.stringify(state)]); }
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function postgresApprovalSchema(options) {
|
|
50
|
+
const table = identifier(options?.table, 'astratra_agent_approvals');
|
|
51
|
+
return `CREATE TABLE IF NOT EXISTS "${table}" (
|
|
52
|
+
id text PRIMARY KEY,
|
|
53
|
+
type text NOT NULL,
|
|
54
|
+
input jsonb NOT NULL,
|
|
55
|
+
requested_by text NOT NULL,
|
|
56
|
+
meta jsonb,
|
|
57
|
+
status text NOT NULL CHECK (status IN ('pending', 'approved', 'rejected', 'expired')),
|
|
58
|
+
created_at timestamptz NOT NULL,
|
|
59
|
+
expires_at timestamptz,
|
|
60
|
+
decided_by text,
|
|
61
|
+
decided_at timestamptz,
|
|
62
|
+
executed_at timestamptz,
|
|
63
|
+
result jsonb,
|
|
64
|
+
reason text,
|
|
65
|
+
refusal jsonb,
|
|
66
|
+
decision_input jsonb
|
|
67
|
+
);
|
|
68
|
+
ALTER TABLE "${table}" ADD COLUMN IF NOT EXISTS decision_input jsonb;
|
|
69
|
+
CREATE INDEX IF NOT EXISTS "${table}_status_idx" ON "${table}" (status, created_at DESC);`;
|
|
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
|
+
*/
|
|
77
|
+
const time = (value) => value == null ? null : Math.round(Number(value));
|
|
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
|
+
|
|
113
|
+
/** Approval store. Every transition is one conditional UPDATE, so two concurrent approvals cannot both win. */
|
|
114
|
+
function createPostgresApprovalStore(db, options) {
|
|
115
|
+
if (!db || typeof db.query !== 'function') throw new Error('A database with query(sql, params) is required.');
|
|
116
|
+
const t = `"${identifier(options?.table, 'astratra_agent_approvals')}"`;
|
|
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)})` : '';
|
|
148
|
+
return {
|
|
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
|
+
},
|
|
166
|
+
async list({ status, type, requestedBy, limit = 50, before } = {}) {
|
|
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);
|
|
190
|
+
},
|
|
191
|
+
async expire(at) {
|
|
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);
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
module.exports = { createPostgresLock, postgresScheduleSchema, createPostgresScheduleStore, postgresApprovalSchema, createPostgresApprovalStore };
|
package/src/index.d.ts
CHANGED
|
@@ -77,3 +77,110 @@ export function usageOf(request: unknown, response: TurnResponse, pricing?: Agen
|
|
|
77
77
|
export function budgetReason(task: Pick<Task, 'turns' | 'elapsedMs' | 'usage'>, budget: ReturnType<typeof normalizeBudget>): string | null;
|
|
78
78
|
export function contextBoundary(messages: Message[], options?: ContextSummaryOptions): number;
|
|
79
79
|
export function summarizeContext(messages: Message[], plan: PlanStep[], options: ContextSummaryOptions, summarize: (input: { messages: Message[]; plan: PlanStep[] }) => Promise<string> | string): Promise<boolean>;
|
|
80
|
+
|
|
81
|
+
// Scheduler: timed tasks, one run at a time, injectable lock and state store.
|
|
82
|
+
export type Schedule =
|
|
83
|
+
| { type: 'daily'; at: string }
|
|
84
|
+
| { type: 'weekly'; at: string; day: number | string; days?: never }
|
|
85
|
+
| { type: 'weekly'; at: string; days: Array<number | string>; day?: never }
|
|
86
|
+
| { type: 'interval'; everyMs: number; align?: boolean };
|
|
87
|
+
export interface ScheduledRunContext { id: string; signal: AbortSignal; manual: boolean; scheduledFor: number | null; previous: unknown; now: number }
|
|
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
|
+
}
|
|
94
|
+
export interface Lock { acquire(key: string): Promise<{ release(): Promise<void> } | null> }
|
|
95
|
+
export interface ScheduleState {
|
|
96
|
+
id: string; status: 'scheduled' | 'running' | 'ok' | 'error' | 'skipped'; nextRunAt: number | null; lastStartedAt: number | null; lastRunAt: number | null;
|
|
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;
|
|
100
|
+
}
|
|
101
|
+
export interface ScheduleStateStore { get(id: string): Promise<Record<string, unknown> | null>; set(id: string, state: Record<string, unknown>): Promise<void> }
|
|
102
|
+
export interface SchedulerEvent { type: 'start' | 'done' | 'error' | 'skipped'; id: string; manual?: boolean; reason?: string; error?: string }
|
|
103
|
+
export interface SchedulerOptions {
|
|
104
|
+
tasks: ScheduledTask[]; timeZone?: string; lock?: Lock; store?: ScheduleStateStore; now?(): number | Date;
|
|
105
|
+
tickMs?: number; maxLateMs?: number; stopCheckMs?: number; shouldStop?(): boolean | Promise<boolean>;
|
|
106
|
+
onEvent?(event: SchedulerEvent): void | Promise<void>; onError?(error: unknown, taskId: string): void;
|
|
107
|
+
}
|
|
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 };
|
|
110
|
+
export interface Scheduler {
|
|
111
|
+
tick(): Promise<RunOutcome[]>; start(): void; stop(): void; readonly started: boolean; abortAll(reason?: unknown): void;
|
|
112
|
+
run(id: string, options?: { signal?: AbortSignal }): Promise<RunOutcome>;
|
|
113
|
+
state(): Promise<TaskView[]>;
|
|
114
|
+
state(id: string): Promise<TaskView>;
|
|
115
|
+
}
|
|
116
|
+
export class SchedulerError extends Error { code: 'unknown_task' | 'stopped' | 'running' | (string & {}); constructor(code: string, message?: string) }
|
|
117
|
+
export function createScheduler(options: SchedulerOptions): Scheduler;
|
|
118
|
+
export function createMemoryLock(): Lock;
|
|
119
|
+
export function createMemoryScheduleStore(): ScheduleStateStore;
|
|
120
|
+
export function nextRun(schedule: Schedule, after: number, timeZone?: string): number;
|
|
121
|
+
export function zonedTime(date: string, hour: number, minute: number, timeZone: string): number;
|
|
122
|
+
|
|
123
|
+
// Approval queue: proposed actions decided later by an authenticated person (the caller authenticates).
|
|
124
|
+
export type ApprovalStatus = 'pending' | 'approved' | 'rejected' | 'expired';
|
|
125
|
+
export const APPROVAL_STATUSES: readonly ApprovalStatus[];
|
|
126
|
+
export interface ApprovalAction<I = unknown, R = unknown> {
|
|
127
|
+
id: string; type: string; input: I; requestedBy: string; meta: unknown; status: ApprovalStatus; createdAt: number; expiresAt: number | null;
|
|
128
|
+
decidedBy: string | null; decidedAt: number | null; executedAt: number | null; result: R | null; reason: string | null;
|
|
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;
|
|
132
|
+
}
|
|
133
|
+
export interface ApprovalFilter { status?: ApprovalStatus; type?: string; requestedBy?: string; limit?: number; before?: number }
|
|
134
|
+
export interface ApprovalStore {
|
|
135
|
+
create(action: ApprovalAction): Promise<ApprovalAction>; get(id: string): Promise<ApprovalAction | null>;
|
|
136
|
+
list(filter?: ApprovalFilter): Promise<ApprovalAction[]>;
|
|
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>;
|
|
139
|
+
finish(id: string, result: unknown, at: number): Promise<ApprovalAction | null>;
|
|
140
|
+
revert(id: string, decidedBy: string, refusal: unknown): Promise<ApprovalAction | null>;
|
|
141
|
+
reject(id: string, decidedBy: string, reason: string | null, at: number): Promise<ApprovalAction | null>;
|
|
142
|
+
expire(at: number): Promise<ApprovalAction[]>;
|
|
143
|
+
}
|
|
144
|
+
export type Decider = string | { id: string; [key: string]: unknown };
|
|
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 }
|
|
147
|
+
export type Executor = (context: ExecutorContext) => unknown;
|
|
148
|
+
export interface ApprovalEvent { type: 'proposed' | 'approved' | 'rejected' | 'refused' | 'failed' | 'expired'; action: ApprovalAction; result?: unknown; reason?: string; error?: string }
|
|
149
|
+
export interface ApprovalQueueOptions {
|
|
150
|
+
store?: ApprovalStore; now?(): number | Date; executors?: Executor | Record<string, Executor>; executionTimeoutMs?: number;
|
|
151
|
+
authorize?(input: { action: ApprovalAction; decider: Decider; decision: 'approve' | 'reject' }): boolean | void | Promise<boolean | void>;
|
|
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 }>;
|
|
155
|
+
onEvent?(event: ApprovalEvent): void | Promise<void>;
|
|
156
|
+
}
|
|
157
|
+
export interface ApprovalQueue {
|
|
158
|
+
propose(input: { type: string; input?: unknown; requestedBy: string; ttlMs?: number; expiresAt?: number | Date; meta?: unknown; id?: string }): Promise<ApprovalAction>;
|
|
159
|
+
get(id: string): Promise<ApprovalAction | null>; list(filter?: ApprovalFilter): Promise<ApprovalAction[]>; expire(): Promise<ApprovalAction[]>;
|
|
160
|
+
approve(id: string, options: { decider: Decider; signal?: AbortSignal; input?: Record<string, unknown> }): Promise<{ action: ApprovalAction; result: unknown }>;
|
|
161
|
+
reject(id: string, options: { decider: Decider; reason?: string }): Promise<ApprovalAction>;
|
|
162
|
+
}
|
|
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 }) }
|
|
164
|
+
export class ApprovalRefused extends Error { reason: string; details: unknown; constructor(reason: string, details?: unknown) }
|
|
165
|
+
export function createApprovalQueue(options?: ApprovalQueueOptions): ApprovalQueue;
|
|
166
|
+
export function createMemoryApprovalStore(): ApprovalStore;
|
|
167
|
+
|
|
168
|
+
// PostgreSQL implementations.
|
|
169
|
+
export interface PgPool extends Queryable { connect(): Promise<Queryable & { release(): void }> }
|
|
170
|
+
export function createPostgresLock(pool: PgPool, options?: { prefix?: string }): Lock;
|
|
171
|
+
export function postgresScheduleSchema(options?: { table?: string }): string;
|
|
172
|
+
export function createPostgresScheduleStore(db: Queryable, options?: { table?: string }): ScheduleStateStore;
|
|
173
|
+
export function postgresApprovalSchema(options?: { table?: string }): string;
|
|
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/index.js
CHANGED
|
@@ -2,5 +2,7 @@
|
|
|
2
2
|
module.exports = {
|
|
3
3
|
...require('./agent'), ...require('./budget'), ...require('./plan'),
|
|
4
4
|
...require('./context'), ...require('./taskStore'), ...require('./postgres'),
|
|
5
|
-
...require('./feedback')
|
|
5
|
+
...require('./feedback'), ...require('./scheduler'), ...require('./approvals'),
|
|
6
|
+
...require('./coordinationPostgres'),
|
|
7
|
+
nextRun: require('./schedule').nextRun, zonedTime: require('./schedule').zonedTime
|
|
6
8
|
};
|
package/src/schedule.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Wall-clock arithmetic in an IANA time zone (daylight saving handled) and the next run of a schedule.
|
|
3
|
+
const DAY_MS = 86400000;
|
|
4
|
+
const DAYS = { monday: 1, tuesday: 2, wednesday: 3, thursday: 4, friday: 5, saturday: 6, sunday: 7 };
|
|
5
|
+
const formats = new Map();
|
|
6
|
+
function formatter(timeZone) {
|
|
7
|
+
let format = formats.get(timeZone);
|
|
8
|
+
if (!format) {
|
|
9
|
+
try {
|
|
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 (_error) { throw new Error(`Unknown time zone: ${timeZone}.`); }
|
|
12
|
+
formats.set(timeZone, format);
|
|
13
|
+
}
|
|
14
|
+
return format;
|
|
15
|
+
}
|
|
16
|
+
function checkTimeZone(timeZone) { if (typeof timeZone !== 'string' || !timeZone) throw new Error('timeZone must be an IANA time zone name.'); formatter(timeZone); return timeZone; }
|
|
17
|
+
function partsOf(ms, timeZone) {
|
|
18
|
+
const p = Object.fromEntries(formatter(timeZone).formatToParts(new Date(ms)).map((x) => [x.type, x.value]));
|
|
19
|
+
return { year: +p.year, month: +p.month, day: +p.day, hour: +p.hour % 24, minute: +p.minute, second: +p.second };
|
|
20
|
+
}
|
|
21
|
+
/** Offset of the zone from UTC, in ms, at the instant `ms` (positive east of Greenwich). */
|
|
22
|
+
function offsetAt(ms, timeZone) {
|
|
23
|
+
const p = partsOf(ms, timeZone);
|
|
24
|
+
return Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) - Math.floor(ms / 1000) * 1000;
|
|
25
|
+
}
|
|
26
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
27
|
+
/** Calendar date `YYYY-MM-DD` of an instant in the zone. */
|
|
28
|
+
function localDate(ms, timeZone) { const p = partsOf(ms, timeZone); return `${p.year}-${pad(p.month)}-${pad(p.day)}`; }
|
|
29
|
+
const addDays = (date, n) => new Date(Date.parse(`${date}T00:00:00Z`) + n * DAY_MS).toISOString().slice(0, 10);
|
|
30
|
+
/** 1 = Monday … 7 = Sunday for a `YYYY-MM-DD` date. */
|
|
31
|
+
function weekday(date) { const d = new Date(`${date}T12:00:00Z`).getUTCDay(); return d === 0 ? 7 : d; }
|
|
32
|
+
/**
|
|
33
|
+
* The instant at which the wall clock of `timeZone` reads `hour:minute` on `date`.
|
|
34
|
+
* A time that happens twice (clocks go back) is the first occurrence; a time that does not exist
|
|
35
|
+
* (clocks go forward) is read with the offset in force before the change, i.e. it lands after the gap.
|
|
36
|
+
*/
|
|
37
|
+
function zonedTime(date, hour, minute, timeZone) {
|
|
38
|
+
const [y, m, d] = date.split('-').map(Number);
|
|
39
|
+
const wall = Date.UTC(y, m - 1, d, hour, minute, 0);
|
|
40
|
+
const before = offsetAt(wall - DAY_MS, timeZone);
|
|
41
|
+
const valid = [...new Set([before, offsetAt(wall + DAY_MS, timeZone)])].map((o) => wall - o).filter((t) => offsetAt(t, timeZone) === wall - t);
|
|
42
|
+
return valid.length ? Math.min(...valid) : wall - before;
|
|
43
|
+
}
|
|
44
|
+
function normalizeSchedule(schedule) {
|
|
45
|
+
if (!schedule || typeof schedule !== 'object') throw new Error('schedule is required.');
|
|
46
|
+
if (schedule.type === 'interval') {
|
|
47
|
+
if (!Number.isFinite(schedule.everyMs) || schedule.everyMs <= 0) throw new Error('interval schedule needs a positive 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 };
|
|
53
|
+
}
|
|
54
|
+
if (schedule.type !== 'daily' && schedule.type !== 'weekly') throw new Error('schedule.type must be daily, weekly or interval.');
|
|
55
|
+
const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(String(schedule.at));
|
|
56
|
+
if (!match) throw new Error('schedule.at must be HH:MM (24 hours).');
|
|
57
|
+
const result = { type: schedule.type, hour: +match[1], minute: +match[2] };
|
|
58
|
+
if (schedule.type === 'weekly') {
|
|
59
|
+
const raw = schedule.days ?? schedule.day;
|
|
60
|
+
const days = (Array.isArray(raw) ? raw : [raw]).map((v) => typeof v === 'string' ? DAYS[v.toLowerCase()] : v);
|
|
61
|
+
if (!days.length || days.some((v) => !Number.isInteger(v) || v < 1 || v > 7)) throw new Error('weekly schedule needs day(s): 1 (Monday) to 7 (Sunday) or day names.');
|
|
62
|
+
result.days = [...new Set(days)].sort();
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
/** First run strictly after `after` (ms). `schedule` is as given to the scheduler. */
|
|
67
|
+
function nextRun(schedule, after, timeZone = 'UTC') {
|
|
68
|
+
const s = normalizeSchedule(schedule);
|
|
69
|
+
if (s.type === 'interval' && !s.align) return after + s.everyMs;
|
|
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
|
+
}
|
|
85
|
+
const start = localDate(after, timeZone);
|
|
86
|
+
for (let i = 0; i <= 8; i += 1) {
|
|
87
|
+
const date = addDays(start, i);
|
|
88
|
+
if (s.type === 'weekly' && !s.days.includes(weekday(date))) continue;
|
|
89
|
+
const t = zonedTime(date, s.hour, s.minute, timeZone);
|
|
90
|
+
if (t > after) return t;
|
|
91
|
+
}
|
|
92
|
+
throw new Error('No next run found.');
|
|
93
|
+
}
|
|
94
|
+
module.exports = { checkTimeZone, normalizeSchedule, nextRun, zonedTime, localDate };
|
package/src/scheduler.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Timed task scheduler: wall-clock schedules in a time zone, one run at a time per task (injectable lock),
|
|
3
|
+
// missed runs skipped past a delay, global stop checked before and during a run, manual runs, readable state.
|
|
4
|
+
// Nothing starts at require time: call start().
|
|
5
|
+
const { checkTimeZone, normalizeSchedule, nextRun } = require('./schedule');
|
|
6
|
+
|
|
7
|
+
class SchedulerError extends Error {
|
|
8
|
+
constructor(code, message) { super(message || code); this.name = 'SchedulerError'; this.code = code; }
|
|
9
|
+
}
|
|
10
|
+
const toMs = (value) => value instanceof Date ? value.getTime() : value;
|
|
11
|
+
const copy = (value) => value == null ? null : JSON.parse(JSON.stringify(value));
|
|
12
|
+
|
|
13
|
+
/** In-process lock. `acquire(key)` resolves to `{ release() }`, or to `null` when the key is already held. */
|
|
14
|
+
function createMemoryLock() {
|
|
15
|
+
const held = new Set();
|
|
16
|
+
return {
|
|
17
|
+
async acquire(key) {
|
|
18
|
+
if (held.has(key)) return null;
|
|
19
|
+
held.add(key);
|
|
20
|
+
let done = false;
|
|
21
|
+
return { async release() { if (!done) { done = true; held.delete(key); } } };
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/** Run state per task, kept in memory. A shared store (see createPostgresScheduleStore) is needed with several processes. */
|
|
26
|
+
function createMemoryScheduleStore() {
|
|
27
|
+
const states = new Map();
|
|
28
|
+
return { async get(id) { return copy(states.get(id)); }, async set(id, state) { states.set(id, copy(state)); } };
|
|
29
|
+
}
|
|
30
|
+
function createScheduler(options = {}) {
|
|
31
|
+
if (!Array.isArray(options.tasks) || !options.tasks.length) throw new Error('tasks is required.');
|
|
32
|
+
const defaultZone = checkTimeZone(options.timeZone ?? 'UTC');
|
|
33
|
+
if (options.lock && typeof options.lock.acquire !== 'function') throw new Error('lock must have acquire(key).');
|
|
34
|
+
const lock = options.lock ?? createMemoryLock();
|
|
35
|
+
const store = options.store ?? createMemoryScheduleStore();
|
|
36
|
+
const now = () => toMs((options.now ?? Date.now)());
|
|
37
|
+
const tickMs = options.tickMs ?? 30000;
|
|
38
|
+
const maxLateMs = options.maxLateMs ?? 3600000;
|
|
39
|
+
const stopCheckMs = options.stopCheckMs ?? 1000;
|
|
40
|
+
if (!Number.isFinite(tickMs) || tickMs <= 0 || !Number.isFinite(stopCheckMs) || stopCheckMs <= 0 || !(maxLateMs >= 0)) throw new Error('Invalid tickMs, stopCheckMs or maxLateMs.');
|
|
41
|
+
const emit = (event) => { try { void Promise.resolve(options.onEvent?.(event)).catch(() => {}); } catch (_error) { /* An observer never breaks the scheduler. */ } };
|
|
42
|
+
const tasks = new Map();
|
|
43
|
+
for (const task of options.tasks) {
|
|
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
|
+
if (tasks.has(task.id)) throw new Error(`Duplicate task id: ${task.id}.`);
|
|
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 });
|
|
51
|
+
}
|
|
52
|
+
const controllers = new Set();
|
|
53
|
+
let timer = null;
|
|
54
|
+
let ticking = null;
|
|
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);
|
|
64
|
+
const stopped = async () => { try { return Boolean(await options.shouldStop?.()); } catch (_error) { return true; } }; // Fail closed.
|
|
65
|
+
const blank = (task) => ({ id: task.id, status: 'scheduled', nextRunAt: null, lastStartedAt: null, lastRunAt: null, lastResult: null, lastError: null, skipReason: null, lastManual: false });
|
|
66
|
+
const read = async (task) => ({ ...blank(task), ...(await store.get(task.id)) });
|
|
67
|
+
const find = (id) => { const task = tasks.get(id); if (!task) throw new SchedulerError('unknown_task'); return task; };
|
|
68
|
+
|
|
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 });
|
|
71
|
+
emit({ type: 'skipped', id: task.id, reason });
|
|
72
|
+
return { id: task.id, status: 'skipped', reason };
|
|
73
|
+
}
|
|
74
|
+
async function execute(task, { manual, signal, current }) {
|
|
75
|
+
if (await stopped()) {
|
|
76
|
+
if (manual) throw new SchedulerError('stopped');
|
|
77
|
+
return skip(task, 'stopped', await read(task), current);
|
|
78
|
+
}
|
|
79
|
+
const held = await lock.acquire(task.id);
|
|
80
|
+
if (!held) { if (manual) throw new SchedulerError('running'); return { id: task.id, status: 'locked' }; }
|
|
81
|
+
const controller = new globalThis.AbortController();
|
|
82
|
+
controllers.add(controller);
|
|
83
|
+
let poll;
|
|
84
|
+
let relay;
|
|
85
|
+
try {
|
|
86
|
+
const state = await read(task); // Read under the lock: another process may have just run it.
|
|
87
|
+
const startedAt = now();
|
|
88
|
+
if (!manual && state.nextRunAt && state.nextRunAt > startedAt) return { id: task.id, status: 'already_done' };
|
|
89
|
+
if (signal) {
|
|
90
|
+
if (signal.aborted) controller.abort(signal.reason);
|
|
91
|
+
else { relay = () => controller.abort(signal.reason); signal.addEventListener('abort', relay, { once: true }); }
|
|
92
|
+
}
|
|
93
|
+
poll = setInterval(() => { stopped().then((yes) => { if (yes) controller.abort(new SchedulerError('stopped')); }); }, stopCheckMs);
|
|
94
|
+
poll.unref?.();
|
|
95
|
+
await store.set(task.id, { ...state, status: 'running', lastStartedAt: startedAt, lastManual: manual });
|
|
96
|
+
emit({ type: 'start', id: task.id, manual });
|
|
97
|
+
let status = 'ok';
|
|
98
|
+
let result = state.lastResult;
|
|
99
|
+
let error = null;
|
|
100
|
+
let reason = null;
|
|
101
|
+
try {
|
|
102
|
+
if (controller.signal.aborted) throw controller.signal.reason;
|
|
103
|
+
result = copy(await task.run({ id: task.id, signal: controller.signal, manual, scheduledFor: state.nextRunAt, previous: state.lastResult, now: startedAt }));
|
|
104
|
+
} catch (caught) {
|
|
105
|
+
if (controller.signal.aborted) { status = 'skipped'; reason = 'stopped'; } else { status = 'error'; error = { message: String(caught?.message ?? caught), at: now() }; }
|
|
106
|
+
}
|
|
107
|
+
const finished = now();
|
|
108
|
+
await store.set(task.id, {
|
|
109
|
+
...state, status, lastStartedAt: startedAt, lastManual: manual,
|
|
110
|
+
lastRunAt: status === 'skipped' ? state.lastRunAt : finished, lastResult: status === 'ok' ? result : state.lastResult,
|
|
111
|
+
lastError: status === 'ok' ? null : (error ?? state.lastError), skipReason: reason,
|
|
112
|
+
nextRunAt: !manual || !state.nextRunAt ? upcoming(task, finished, current) : state.nextRunAt,
|
|
113
|
+
scheduleKey: !manual || !state.nextRunAt ? current.key : state.scheduleKey
|
|
114
|
+
});
|
|
115
|
+
emit({ type: status === 'ok' ? 'done' : status, id: task.id, manual, ...(error ? { error: error.message } : {}) });
|
|
116
|
+
return { id: task.id, status, ...(status === 'ok' ? { result } : {}), ...(error ? { error: error.message } : {}), ...(reason ? { reason } : {}) };
|
|
117
|
+
} finally {
|
|
118
|
+
clearInterval(poll);
|
|
119
|
+
if (relay) signal.removeEventListener('abort', relay);
|
|
120
|
+
controllers.delete(controller);
|
|
121
|
+
await held.release();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
async function pass() {
|
|
125
|
+
const results = [];
|
|
126
|
+
for (const task of tasks.values()) {
|
|
127
|
+
try {
|
|
128
|
+
const current = await live(task);
|
|
129
|
+
const at = now();
|
|
130
|
+
const state = await read(task);
|
|
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 }));
|
|
146
|
+
} catch (error) { try { options.onError?.(error, task.id); } catch (_ignored) { /* An observer never breaks the scheduler. */ } }
|
|
147
|
+
}
|
|
148
|
+
return results;
|
|
149
|
+
}
|
|
150
|
+
return {
|
|
151
|
+
/** One pass: plans the tasks never planned, skips the ones too late, runs the ones due. Resolves to what happened. */
|
|
152
|
+
tick() { if (!ticking) ticking = pass().finally(() => { ticking = null; }); return ticking; },
|
|
153
|
+
/** Starts the periodic pass (and one right away). Never called by the package itself. */
|
|
154
|
+
start() { if (timer) return; timer = setInterval(() => { void this.tick(); }, tickMs); timer.unref?.(); void this.tick(); },
|
|
155
|
+
/** Stops the periodic pass. A run in progress goes on; use abortAll() to cut it. */
|
|
156
|
+
stop() { if (timer) clearInterval(timer); timer = null; },
|
|
157
|
+
get started() { return timer !== null; },
|
|
158
|
+
/** Aborts every run in progress in this process (their `signal` aborts). */
|
|
159
|
+
abortAll(reason = new SchedulerError('stopped')) { for (const c of controllers) c.abort(reason); },
|
|
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) }); },
|
|
162
|
+
/** State of one task, or of all of them. `nextRunAt` is computed when the task was never planned. */
|
|
163
|
+
async state(id) {
|
|
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
|
+
};
|
|
169
|
+
if (id !== undefined) return describe(find(id));
|
|
170
|
+
return Promise.all([...tasks.values()].map(describe));
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
module.exports = { SchedulerError, createScheduler, createMemoryLock, createMemoryScheduleStore };
|