@astratra/agent 1.0.0 → 1.2.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 +101 -0
- package/README.md +98 -1
- package/package.json +1 -1
- package/src/agent.js +2 -1
- package/src/approvals.js +147 -0
- package/src/coordinationPostgres.js +95 -0
- package/src/index.d.ts +90 -1
- package/src/index.js +3 -1
- package/src/schedule.js +76 -0
- package/src/scheduler.js +147 -0
package/README.fr.md
CHANGED
|
@@ -150,6 +150,107 @@ modèle ; les arguments sont sinon transmis comme le modèle les a écrits.
|
|
|
150
150
|
Pour les tests : `createMockGuards` et `createFakeModels` de
|
|
151
151
|
`@astratra/ai/guards/testing`.
|
|
152
152
|
|
|
153
|
+
### Montrer la réponse pendant qu'elle s'écrit
|
|
154
|
+
|
|
155
|
+
Avec des gardes, `turn` reçoit `unmask(texte)` : il rend les vrais mots d'un texte du modèle (masqué). Avec `onText`
|
|
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
|
+
passe toujours par la garde de sortie (fuites, modération) ; ce qui part au modèle reste masqué.
|
|
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
|
+
- **Jamais deux fois en même temps** : chaque passage prend un `lock` (`acquire(cle)` → `{ release() }` ou `null`). Par
|
|
190
|
+
défaut un verrou dans le processus ; avec plusieurs processus, `createPostgresLock(pool)` (`pg_try_advisory_lock`,
|
|
191
|
+
tenu sur une connexion du pool jusqu'à `release()`, libéré si le processus meurt). L'état est relu sous le verrou :
|
|
192
|
+
un processus qui perd la course ne relance pas une tâche qu'un autre vient de finir. Partagez le `store` (plus bas)
|
|
193
|
+
entre les processus.
|
|
194
|
+
- **Passages manqués** : un passage échu depuis plus de `maxLateMs` (par tâche ou global, 1 h par défaut) est sauté
|
|
195
|
+
(`skipReason: 'late'`) et le suivant est programmé. En deçà du délai, il part quand même.
|
|
196
|
+
- **Arrêt global** : `shouldStop()` est lu avant chaque passage (un passage programmé est sauté avec `'stopped'`, un
|
|
197
|
+
lancement manuel lève `SchedulerError('stopped')`) puis toutes les `stopCheckMs` (1 s) pendant l'exécution ; s'il
|
|
198
|
+
rend vrai, le `signal` de la tâche s'annule. Un `shouldStop` qui échoue vaut arrêt. Un passage coupé ainsi n'est pas
|
|
199
|
+
compté comme fait.
|
|
200
|
+
- **État** : `status` vaut `scheduled`, `running` (indicatif : le verrou fait foi), `ok`, `error` ou `skipped`.
|
|
201
|
+
`lastResult` (JSON) est repassé au passage suivant en `previous`, pour les tâches qui évitent de se répéter.
|
|
202
|
+
- **Stockage de l'état** : mémoire par défaut ; `createPostgresScheduleStore(db)` le garde dans une table
|
|
203
|
+
(`postgresScheduleSchema()` la crée).
|
|
204
|
+
- **Tests** : injectez `now` (fonction rendant des ms ou une `Date`) et appelez `tick()` vous-même.
|
|
205
|
+
- `onEvent` (`start`, `done`, `error`, `skipped`) et `onError` observent l'ordonnanceur sans jamais le casser.
|
|
206
|
+
|
|
207
|
+
## File d'actions en attente d'approbation
|
|
208
|
+
|
|
209
|
+
Des actions qu'une personne doit approuver, **détachées de toute exécution en cours** : on propose maintenant, on décide
|
|
210
|
+
des heures ou des jours plus tard. Le paquet n'authentifie personne : vous contrôlez l'identité et le rôle (dans votre
|
|
211
|
+
route, ou dans `authorize`) et passez le décideur. L'action est exécutée par **votre** exécuteur.
|
|
212
|
+
|
|
213
|
+
```js
|
|
214
|
+
const { createApprovalQueue, ApprovalRefused } = require('@astratra/agent');
|
|
215
|
+
|
|
216
|
+
const queue = createApprovalQueue({
|
|
217
|
+
executors: {
|
|
218
|
+
publier: async ({ input, idempotencyKey, signal }) => {
|
|
219
|
+
if (!input.titre) throw new ApprovalRefused('incomplet', { manquants: ['titre'] }); // rien n'a été fait
|
|
220
|
+
return await publierArticle(input, { idempotencyKey, signal }); // le résultat est gardé
|
|
221
|
+
}
|
|
222
|
+
},
|
|
223
|
+
authorize: ({ decider }) => decider.role === 'proprietaire', // votre règle ; false ou une exception = interdit
|
|
224
|
+
beforeExecute: () => { if (reglages.arretUrgence) throw new Error('arrêt'); }, // dernier contrôle, facultatif
|
|
225
|
+
onEvent: ({ type, action }) => journal(type, action.id) // proposed, approved, rejected, refused, failed, expired
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
const action = await queue.propose({ type: 'publier', input: { titre: 'Bonjour' }, requestedBy: 'assistant', ttlMs: 3 * 24 * 3600 * 1000 });
|
|
229
|
+
await queue.list({ status: 'pending' });
|
|
230
|
+
await queue.approve(action.id, { decider: { id: 'u-1', role: 'proprietaire' } }); // → { action, result }
|
|
231
|
+
await queue.reject(action.id, { decider: { id: 'u-1', role: 'proprietaire' }, reason: 'pas maintenant' });
|
|
232
|
+
await queue.expire(); // fait aussi par list/approve/reject
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
- **Une seule exécution** : `approve` *réserve* d'abord l'action (`pending` → `approved`) en une étape atomique du
|
|
236
|
+
stockage, puis lance l'exécuteur. Deux approbations simultanées : l'une s'exécute, l'autre reçoit
|
|
237
|
+
`ApprovalError('already_decided')`. Avec PostgreSQL, la réservation est un seul `UPDATE` conditionnel. L'exécuteur
|
|
238
|
+
reçoit `idempotencyKey` (l'identifiant de l'action) : utilisez-la côté système externe, car une file ne peut pas
|
|
239
|
+
défaire un effet survenu avant un plantage. Une action restée `approved` avec `executedAt: null` après un plantage se
|
|
240
|
+
retrouve par `list({ status: 'approved' })`.
|
|
241
|
+
- **Refus** : si l'exécuteur lève `ApprovalRefused(reason, details)`, rien n'a eu lieu : l'action repasse en `pending`
|
|
242
|
+
avec `refusal: { reason, details, at, by }` et l'erreur est relancée. Toute autre erreur fait de même avec
|
|
243
|
+
`reason: 'execution_failed'` et est relancée en `ApprovalError('execution_failed')` (l'originale est dans `cause`).
|
|
244
|
+
- **Expiration** : `ttlMs` ou `expiresAt` à `propose`. Une action expirée ne peut plus être approuvée ni rejetée
|
|
245
|
+
(`ApprovalError('expired')`), même si le balayage n'est pas encore passé. `expire()` les marque `expired` ;
|
|
246
|
+
appelez-la depuis une minuterie ou une tâche de l'ordonnanceur.
|
|
247
|
+
- **Erreurs** (`ApprovalError.code`) : `not_found`, `expired`, `already_decided`, `forbidden`, `no_executor`,
|
|
248
|
+
`execution_failed`, `invalid`.
|
|
249
|
+
- **Stockage** : mémoire par défaut ; `createPostgresApprovalStore(db)` avec `postgresApprovalSchema()`. Un stockage
|
|
250
|
+
maison implémente `create/get/list/reserve/finish/revert/reject/expire`, chaque transition étant atomique et rendant
|
|
251
|
+
`null` quand sa condition n'est plus vraie.
|
|
252
|
+
- Les entrées et résultats conservés doivent être du JSON.
|
|
253
|
+
|
|
153
254
|
## Tests
|
|
154
255
|
|
|
155
256
|
`npm test -w @astratra/agent`. Les tests PostgreSQL réels ne tournent qu'avec
|
package/README.md
CHANGED
|
@@ -318,9 +318,106 @@ tenant: scope it for tenant dashboards.
|
|
|
318
318
|
The interface parts are `FeedbackBar` in `@astratra/native-ui` (React Native)
|
|
319
319
|
and `@astratra/saas-kit-ui` (web).
|
|
320
320
|
|
|
321
|
+
### Showing the answer while it is written
|
|
322
|
+
|
|
323
|
+
With guards, `turn` receives `unmask(text)`: the real words of a (masked) model text. With `onText` from
|
|
324
|
+
`@astratra/ai` (1.10.0) you can show a streamed answer without its masking markers (`#PERSON_0001`). The final answer
|
|
325
|
+
still goes through the output guard (leaks, moderation); what is sent to the model stays masked.
|
|
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
|
+
- **Never twice at once**: each run takes a `lock` (`acquire(key)` → `{ release() }` or `null`). The default is an
|
|
357
|
+
in-process lock; with several processes pass `createPostgresLock(pool)` (`pg_try_advisory_lock`, held on one pooled
|
|
358
|
+
connection until released, freed if the process dies). The run state is re-read under the lock, so a process that
|
|
359
|
+
lost the race does not run a task another one just finished. Share the `store` (below) between processes.
|
|
360
|
+
- **Missed runs**: a due run late by more than `maxLateMs` (per task or global, 1 h by default) is skipped with
|
|
361
|
+
`skipReason: 'late'`, and the next one is planned. Within the delay it still runs.
|
|
362
|
+
- **Global stop**: `shouldStop()` is read before each run (a scheduled run is skipped with `'stopped'`, a manual run
|
|
363
|
+
throws `SchedulerError('stopped')`) and every `stopCheckMs` (1 s) during a run; when it returns true the task's
|
|
364
|
+
`signal` aborts. A failing `shouldStop` counts as stopped. A run cut this way is not counted as done.
|
|
365
|
+
- **State**: `status` is `scheduled`, `running` (informative: the lock is the truth), `ok`, `error` or `skipped`.
|
|
366
|
+
`lastResult` (JSON) is passed to the next run as `previous`, for tasks that avoid repeating themselves.
|
|
367
|
+
- **State store**: memory by default; `createPostgresScheduleStore(db)` keeps it in a table
|
|
368
|
+
(`postgresScheduleSchema()` creates it).
|
|
369
|
+
- **Tests**: inject `now` (a function returning ms or a `Date`) and call `tick()` yourself.
|
|
370
|
+
- `onEvent` (`start`, `done`, `error`, `skipped`) and `onError` observe the scheduler; they never break it.
|
|
371
|
+
|
|
372
|
+
## Approval queue (actions waiting for a decision)
|
|
373
|
+
|
|
374
|
+
Actions that a person must approve, **detached from any running task**: an action is proposed now and decided hours or
|
|
375
|
+
days later. The package does not authenticate anyone: you check identity and role (in your route, or in `authorize`) and
|
|
376
|
+
pass the decider. The action is executed by **your** executor.
|
|
377
|
+
|
|
378
|
+
```js
|
|
379
|
+
const { createApprovalQueue, ApprovalRefused } = require('@astratra/agent');
|
|
380
|
+
|
|
381
|
+
const queue = createApprovalQueue({
|
|
382
|
+
executors: {
|
|
383
|
+
publish: async ({ input, idempotencyKey, signal }) => {
|
|
384
|
+
if (!input.title) throw new ApprovalRefused('incomplete', { missing: ['title'] }); // nothing done
|
|
385
|
+
return await publishPost(input, { idempotencyKey, signal }); // the result is stored
|
|
386
|
+
}
|
|
387
|
+
},
|
|
388
|
+
authorize: ({ decider }) => decider.role === 'owner', // your rule; false or a throw = forbidden
|
|
389
|
+
beforeExecute: () => { if (settings.killSwitch) throw new Error('stopped'); }, // optional last check
|
|
390
|
+
onEvent: ({ type, action }) => audit(type, action.id) // proposed, approved, rejected, refused, failed, expired
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
const action = await queue.propose({ type: 'publish', input: { title: 'Hello' }, requestedBy: 'assistant', ttlMs: 3 * 24 * 3600 * 1000 });
|
|
394
|
+
await queue.list({ status: 'pending' });
|
|
395
|
+
await queue.approve(action.id, { decider: { id: 'user-1', role: 'owner' } }); // → { action, result }
|
|
396
|
+
await queue.reject(action.id, { decider: { id: 'user-1', role: 'owner' }, reason: 'not now' });
|
|
397
|
+
await queue.expire(); // also done by list/approve/reject
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
- **Once only**: `approve` first *reserves* the action (`pending` → `approved`) in one atomic step of the store, then
|
|
401
|
+
runs the executor. Two approvals at the same time: one runs, the other gets `ApprovalError('already_decided')`.
|
|
402
|
+
With PostgreSQL the reservation is one conditional `UPDATE`. The executor receives `idempotencyKey` (the action id):
|
|
403
|
+
use it with the external system, because a crash after the effect cannot be undone by a queue. An action stuck in
|
|
404
|
+
`approved` with `executedAt: null` after a crash is findable with `list({ status: 'approved' })`.
|
|
405
|
+
- **Refusal**: if the executor throws `ApprovalRefused(reason, details)`, nothing happened: the action goes back to
|
|
406
|
+
`pending` with `refusal: { reason, details, at, by }`, and the error is rethrown. Any other error does the same with
|
|
407
|
+
`reason: 'execution_failed'` and is rethrown as `ApprovalError('execution_failed')` (the original is in `cause`).
|
|
408
|
+
- **Expiry**: `ttlMs` or `expiresAt` at `propose`. An expired action cannot be approved or rejected
|
|
409
|
+
(`ApprovalError('expired')`), even if the sweep has not run yet. `expire()` marks them `expired`; call it from a
|
|
410
|
+
timer or from a scheduler task.
|
|
411
|
+
- **Errors** (`ApprovalError.code`): `not_found`, `expired`, `already_decided`, `forbidden`, `no_executor`,
|
|
412
|
+
`execution_failed`, `invalid`.
|
|
413
|
+
- **Store**: memory by default; `createPostgresApprovalStore(db)` with `postgresApprovalSchema()`. Custom stores
|
|
414
|
+
implement `create/get/list/reserve/finish/revert/reject/expire`, each transition atomic and returning `null` when
|
|
415
|
+
its condition no longer holds.
|
|
416
|
+
- Persisted inputs and results must be JSON.
|
|
417
|
+
|
|
321
418
|
## Tests
|
|
322
419
|
|
|
323
420
|
`npm test -w @astratra/agent` uses `node --test`; the guard tests run on
|
|
324
421
|
`@astratra/ai/guards/testing` with no model. Real PostgreSQL tests run only
|
|
325
422
|
with `AGENT_TEST_DATABASE_URL` naming a database ending in `_test`; otherwise
|
|
326
|
-
that test is skipped (feedback tests included). The tests create and drop their own randomly named tables.
|
|
423
|
+
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.2.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/agent.js
CHANGED
|
@@ -182,7 +182,8 @@ function createAgent(options = {}) {
|
|
|
182
182
|
if (!reserve && reason) throw new BudgetStop(reason);
|
|
183
183
|
task.turns += 1;
|
|
184
184
|
await save();
|
|
185
|
-
|
|
185
|
+
// `unmask` : de quoi montrer à la personne un texte du modèle pendant qu'il s'écrit (réponse en flux).
|
|
186
|
+
const response = await abortable(() => options.turn({ ...request, signal: activeSignal, phase, ...(guards && run ? { unmask: (text) => run.unmask(text) } : {}) }), activeSignal);
|
|
186
187
|
activeSignal.throwIfAborted();
|
|
187
188
|
const usage = usageOf(request, response, options.pricing);
|
|
188
189
|
for (const field of ['inputTokens', 'outputTokens', 'cost']) task.usage[field] += usage[field];
|
package/src/approvals.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
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) {
|
|
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 }); 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, 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']) 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 });
|
|
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
|
+
* The executor (`({ action, input, decider, signal, idempotencyKey })`) may throw ApprovalRefused or any error:
|
|
108
|
+
* the action then goes back to `pending` with `refusal` set and the error is rethrown. Resolves `{ action, result }`.
|
|
109
|
+
*/
|
|
110
|
+
async approve(id, { decider, signal } = {}) {
|
|
111
|
+
await expire();
|
|
112
|
+
const pending = await pendingOrThrow(id);
|
|
113
|
+
await authorize(pending, decider, 'approve');
|
|
114
|
+
const execute = executorFor(pending.type);
|
|
115
|
+
if (!execute) throw new ApprovalError('no_executor', `No executor for ${pending.type}.`);
|
|
116
|
+
const by = who(decider);
|
|
117
|
+
const action = await store.reserve(id, by, now());
|
|
118
|
+
if (!action) { await pendingOrThrow(id); throw new ApprovalError('already_decided'); } // Lost the race: say why.
|
|
119
|
+
const back = async (refusal) => { await store.revert(id, by, { ...refusal, at: now(), by }); };
|
|
120
|
+
let result;
|
|
121
|
+
try {
|
|
122
|
+
await options.beforeExecute?.({ action, decider });
|
|
123
|
+
result = copy(await execute({ action, input: action.input, decider, idempotencyKey: action.id, signal: signal ?? globalThis.AbortSignal.timeout(executionTimeoutMs) }));
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (error instanceof ApprovalRefused) { await back({ reason: error.reason, details: error.details }); emit('refused', action, { reason: error.reason }); throw error; }
|
|
126
|
+
if (error instanceof ApprovalError) { await back({ reason: error.code, details: null }); throw error; }
|
|
127
|
+
await back({ reason: 'execution_failed', details: null });
|
|
128
|
+
emit('failed', action, { error: String(error?.message ?? error) });
|
|
129
|
+
throw new ApprovalError('execution_failed', 'The execution failed.', { cause: error });
|
|
130
|
+
}
|
|
131
|
+
const finished = await store.finish(id, result, now());
|
|
132
|
+
emit('approved', finished, { result });
|
|
133
|
+
return { action: finished, result };
|
|
134
|
+
},
|
|
135
|
+
/** Rejects a pending action. Resolves the rejected action. */
|
|
136
|
+
async reject(id, { decider, reason } = {}) {
|
|
137
|
+
await expire();
|
|
138
|
+
const pending = await pendingOrThrow(id);
|
|
139
|
+
await authorize(pending, decider, 'reject');
|
|
140
|
+
const action = await store.reject(id, who(decider), reason ?? null, now());
|
|
141
|
+
if (!action) { await pendingOrThrow(id); throw new ApprovalError('already_decided'); }
|
|
142
|
+
emit('rejected', action);
|
|
143
|
+
return action;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
module.exports = { APPROVAL_STATUSES: STATUSES, ApprovalError, ApprovalRefused, createApprovalQueue, createMemoryApprovalStore };
|
|
@@ -0,0 +1,95 @@
|
|
|
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
|
+
);
|
|
67
|
+
CREATE INDEX IF NOT EXISTS "${table}_status_idx" ON "${table}" (status, created_at DESC);`;
|
|
68
|
+
}
|
|
69
|
+
const ms = (column) => `(extract(epoch from ${column}) * 1000)::float8`;
|
|
70
|
+
const COLUMNS = `id, type, input, requested_by, meta, status, ${ms('created_at')} AS created_ms, ${ms('expires_at')} AS expires_ms, decided_by, ${ms('decided_at')} AS decided_ms, ${ms('executed_at')} AS executed_ms, result, reason, refusal`;
|
|
71
|
+
const time = (value) => value == null ? null : Math.round(Number(value));
|
|
72
|
+
const toAction = (row) => row ? ({ id: row.id, type: row.type, input: json(row.input), requestedBy: row.requested_by, meta: json(row.meta) ?? null, status: row.status, createdAt: time(row.created_ms), expiresAt: time(row.expires_ms), decidedBy: row.decided_by, decidedAt: time(row.decided_ms), executedAt: time(row.executed_ms), result: json(row.result) ?? null, reason: row.reason, refusal: json(row.refusal) ?? null }) : null;
|
|
73
|
+
/** Approval store. Every transition is one conditional UPDATE, so two concurrent approvals cannot both win. */
|
|
74
|
+
function createPostgresApprovalStore(db, options) {
|
|
75
|
+
if (!db || typeof db.query !== 'function') throw new Error('A database with query(sql, params) is required.');
|
|
76
|
+
const t = `"${identifier(options?.table, 'astratra_agent_approvals')}"`;
|
|
77
|
+
const one = async (sql, params) => toAction((await db.query(sql, params)).rows[0]);
|
|
78
|
+
return {
|
|
79
|
+
create: (a) => one(`INSERT INTO ${t} (id, type, input, requested_by, meta, status, created_at, expires_at) VALUES ($1, $2, $3::jsonb, $4, $5::jsonb, 'pending', to_timestamp($6::float8 / 1000), CASE WHEN $7::float8 IS NULL THEN NULL ELSE to_timestamp($7::float8 / 1000) END) RETURNING ${COLUMNS}`, [a.id, a.type, JSON.stringify(a.input), a.requestedBy, a.meta == null ? null : JSON.stringify(a.meta), a.createdAt, a.expiresAt]),
|
|
80
|
+
get: (id) => one(`SELECT ${COLUMNS} FROM ${t} WHERE id = $1`, [id]),
|
|
81
|
+
async list({ status, type, requestedBy, limit = 50, before } = {}) {
|
|
82
|
+
const { rows } = await db.query(`SELECT ${COLUMNS} FROM ${t} WHERE ($1::text IS NULL OR status = $1) AND ($2::text IS NULL OR type = $2) AND ($3::text IS NULL OR requested_by = $3) AND ($4::float8 IS NULL OR created_at < to_timestamp($4::float8 / 1000)) ORDER BY created_at DESC, id LIMIT $5`, [status ?? null, type ?? null, requestedBy ?? null, before ?? null, limit]);
|
|
83
|
+
return rows.map(toAction);
|
|
84
|
+
},
|
|
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
|
+
async expire(at) {
|
|
90
|
+
const { rows } = await db.query(`UPDATE ${t} SET status = 'expired', decided_at = to_timestamp($1::float8 / 1000) WHERE status = 'pending' AND expires_at IS NOT NULL AND expires_at <= to_timestamp($1::float8 / 1000) RETURNING ${COLUMNS}`, [at]);
|
|
91
|
+
return rows.map(toAction);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
module.exports = { createPostgresLock, postgresScheduleSchema, createPostgresScheduleStore, postgresApprovalSchema, createPostgresApprovalStore };
|
package/src/index.d.ts
CHANGED
|
@@ -29,7 +29,14 @@ export interface TaskStore {
|
|
|
29
29
|
save(task: Task, owner: string): Promise<Task>; release(id: string, owner: string): Promise<void>;
|
|
30
30
|
}
|
|
31
31
|
export interface Budget { maxMs?: number; maxTurns?: number; maxTokens?: number; maxCost?: number }
|
|
32
|
-
export interface TurnRequest {
|
|
32
|
+
export interface TurnRequest {
|
|
33
|
+
system: string; messages: Message[]; tools: Array<Record<string, unknown>>; signal: AbortSignal; phase: string;
|
|
34
|
+
/**
|
|
35
|
+
* Avec des gardes : rend les vrais mots d'un texte du modèle (masqué). Pour montrer une réponse pendant qu'elle
|
|
36
|
+
* s'écrit (`onText` de @astratra/ai) ; la réponse finale, elle, passe toujours par la garde de sortie.
|
|
37
|
+
*/
|
|
38
|
+
unmask?: (text: string) => string;
|
|
39
|
+
}
|
|
33
40
|
export interface TurnResponse { text?: string; toolCalls?: NativeToolCall[]; usage?: { inputTokens?: number; outputTokens?: number; prompt_tokens?: number; completion_tokens?: number; cost?: number } }
|
|
34
41
|
export interface Verification { complete: boolean; feedback?: string }
|
|
35
42
|
export interface SummaryInput { messages: Message[]; plan: PlanStep[]; signal: AbortSignal }
|
|
@@ -70,3 +77,85 @@ export function usageOf(request: unknown, response: TurnResponse, pricing?: Agen
|
|
|
70
77
|
export function budgetReason(task: Pick<Task, 'turns' | 'elapsedMs' | 'usage'>, budget: ReturnType<typeof normalizeBudget>): string | null;
|
|
71
78
|
export function contextBoundary(messages: Message[], options?: ContextSummaryOptions): number;
|
|
72
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 };
|
|
87
|
+
export interface ScheduledRunContext { id: string; signal: AbortSignal; manual: boolean; scheduledFor: number | null; previous: unknown; now: number }
|
|
88
|
+
export interface ScheduledTask { id: string; label?: string; schedule: Schedule; timeZone?: string; enabled?: boolean; maxLateMs?: number; run(context: ScheduledRunContext): unknown }
|
|
89
|
+
export interface Lock { acquire(key: string): Promise<{ release(): Promise<void> } | null> }
|
|
90
|
+
export interface ScheduleState {
|
|
91
|
+
id: string; status: 'scheduled' | 'running' | 'ok' | 'error' | 'skipped'; nextRunAt: number | null; lastStartedAt: number | null; lastRunAt: number | null;
|
|
92
|
+
lastResult: unknown; lastError: { message: string; at: number } | null; skipReason: string | null; lastManual: boolean;
|
|
93
|
+
}
|
|
94
|
+
export interface ScheduleStateStore { get(id: string): Promise<Record<string, unknown> | null>; set(id: string, state: Record<string, unknown>): Promise<void> }
|
|
95
|
+
export interface SchedulerEvent { type: 'start' | 'done' | 'error' | 'skipped'; id: string; manual?: boolean; reason?: string; error?: string }
|
|
96
|
+
export interface SchedulerOptions {
|
|
97
|
+
tasks: ScheduledTask[]; timeZone?: string; lock?: Lock; store?: ScheduleStateStore; now?(): number | Date;
|
|
98
|
+
tickMs?: number; maxLateMs?: number; stopCheckMs?: number; shouldStop?(): boolean | Promise<boolean>;
|
|
99
|
+
onEvent?(event: SchedulerEvent): void | Promise<void>; onError?(error: unknown, taskId: string): void;
|
|
100
|
+
}
|
|
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 };
|
|
103
|
+
export interface Scheduler {
|
|
104
|
+
tick(): Promise<RunOutcome[]>; start(): void; stop(): void; readonly started: boolean; abortAll(reason?: unknown): void;
|
|
105
|
+
run(id: string, options?: { signal?: AbortSignal }): Promise<RunOutcome>;
|
|
106
|
+
state(): Promise<TaskView[]>;
|
|
107
|
+
state(id: string): Promise<TaskView>;
|
|
108
|
+
}
|
|
109
|
+
export class SchedulerError extends Error { code: 'unknown_task' | 'stopped' | 'running' | (string & {}); constructor(code: string, message?: string) }
|
|
110
|
+
export function createScheduler(options: SchedulerOptions): Scheduler;
|
|
111
|
+
export function createMemoryLock(): Lock;
|
|
112
|
+
export function createMemoryScheduleStore(): ScheduleStateStore;
|
|
113
|
+
export function nextRun(schedule: Schedule, after: number, timeZone?: string): number;
|
|
114
|
+
export function zonedTime(date: string, hour: number, minute: number, timeZone: string): number;
|
|
115
|
+
|
|
116
|
+
// Approval queue: proposed actions decided later by an authenticated person (the caller authenticates).
|
|
117
|
+
export type ApprovalStatus = 'pending' | 'approved' | 'rejected' | 'expired';
|
|
118
|
+
export const APPROVAL_STATUSES: readonly ApprovalStatus[];
|
|
119
|
+
export interface ApprovalAction<I = unknown, R = unknown> {
|
|
120
|
+
id: string; type: string; input: I; requestedBy: string; meta: unknown; status: ApprovalStatus; createdAt: number; expiresAt: number | null;
|
|
121
|
+
decidedBy: string | null; decidedAt: number | null; executedAt: number | null; result: R | null; reason: string | null;
|
|
122
|
+
refusal: { reason: string; details: unknown; at: number; by: string } | null;
|
|
123
|
+
}
|
|
124
|
+
export interface ApprovalFilter { status?: ApprovalStatus; type?: string; requestedBy?: string; limit?: number; before?: number }
|
|
125
|
+
export interface ApprovalStore {
|
|
126
|
+
create(action: ApprovalAction): Promise<ApprovalAction>; get(id: string): Promise<ApprovalAction | null>;
|
|
127
|
+
list(filter?: ApprovalFilter): Promise<ApprovalAction[]>;
|
|
128
|
+
reserve(id: string, decidedBy: string, at: number): Promise<ApprovalAction | null>;
|
|
129
|
+
finish(id: string, result: unknown, at: number): Promise<ApprovalAction | null>;
|
|
130
|
+
revert(id: string, decidedBy: string, refusal: unknown): Promise<ApprovalAction | null>;
|
|
131
|
+
reject(id: string, decidedBy: string, reason: string | null, at: number): Promise<ApprovalAction | null>;
|
|
132
|
+
expire(at: number): Promise<ApprovalAction[]>;
|
|
133
|
+
}
|
|
134
|
+
export type Decider = string | { id: string; [key: string]: unknown };
|
|
135
|
+
export interface ExecutorContext<I = any> { action: ApprovalAction<I>; input: I; decider: Decider; idempotencyKey: string; signal: AbortSignal }
|
|
136
|
+
export type Executor = (context: ExecutorContext) => unknown;
|
|
137
|
+
export interface ApprovalEvent { type: 'proposed' | 'approved' | 'rejected' | 'refused' | 'failed' | 'expired'; action: ApprovalAction; result?: unknown; reason?: string; error?: string }
|
|
138
|
+
export interface ApprovalQueueOptions {
|
|
139
|
+
store?: ApprovalStore; now?(): number | Date; executors?: Executor | Record<string, Executor>; executionTimeoutMs?: number;
|
|
140
|
+
authorize?(input: { action: ApprovalAction; decider: Decider; decision: 'approve' | 'reject' }): boolean | void | Promise<boolean | void>;
|
|
141
|
+
beforeExecute?(input: { action: ApprovalAction; decider: Decider }): void | Promise<void>;
|
|
142
|
+
onEvent?(event: ApprovalEvent): void | Promise<void>;
|
|
143
|
+
}
|
|
144
|
+
export interface ApprovalQueue {
|
|
145
|
+
propose(input: { type: string; input?: unknown; requestedBy: string; ttlMs?: number; expiresAt?: number | Date; meta?: unknown; id?: string }): Promise<ApprovalAction>;
|
|
146
|
+
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 }>;
|
|
148
|
+
reject(id: string, options: { decider: Decider; reason?: string }): Promise<ApprovalAction>;
|
|
149
|
+
}
|
|
150
|
+
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 }) }
|
|
151
|
+
export class ApprovalRefused extends Error { reason: string; details: unknown; constructor(reason: string, details?: unknown) }
|
|
152
|
+
export function createApprovalQueue(options?: ApprovalQueueOptions): ApprovalQueue;
|
|
153
|
+
export function createMemoryApprovalStore(): ApprovalStore;
|
|
154
|
+
|
|
155
|
+
// PostgreSQL implementations.
|
|
156
|
+
export interface PgPool extends Queryable { connect(): Promise<Queryable & { release(): void }> }
|
|
157
|
+
export function createPostgresLock(pool: PgPool, options?: { prefix?: string }): Lock;
|
|
158
|
+
export function postgresScheduleSchema(options?: { table?: string }): string;
|
|
159
|
+
export function createPostgresScheduleStore(db: Queryable, options?: { table?: string }): ScheduleStateStore;
|
|
160
|
+
export function postgresApprovalSchema(options?: { table?: string }): string;
|
|
161
|
+
export function createPostgresApprovalStore(db: Queryable, options?: { table?: string }): 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,76 @@
|
|
|
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
|
+
return { type: 'interval', everyMs: schedule.everyMs };
|
|
49
|
+
}
|
|
50
|
+
if (schedule.type !== 'daily' && schedule.type !== 'weekly') throw new Error('schedule.type must be daily, weekly or interval.');
|
|
51
|
+
const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(String(schedule.at));
|
|
52
|
+
if (!match) throw new Error('schedule.at must be HH:MM (24 hours).');
|
|
53
|
+
const result = { type: schedule.type, hour: +match[1], minute: +match[2] };
|
|
54
|
+
if (schedule.type === 'weekly') {
|
|
55
|
+
const raw = schedule.days ?? schedule.day;
|
|
56
|
+
const days = (Array.isArray(raw) ? raw : [raw]).map((v) => typeof v === 'string' ? DAYS[v.toLowerCase()] : v);
|
|
57
|
+
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.');
|
|
58
|
+
result.days = [...new Set(days)].sort();
|
|
59
|
+
}
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
/** First run strictly after `after` (ms). `schedule` is as given to the scheduler. */
|
|
63
|
+
function nextRun(schedule, after, timeZone = 'UTC') {
|
|
64
|
+
const s = normalizeSchedule(schedule);
|
|
65
|
+
if (s.type === 'interval') return after + s.everyMs;
|
|
66
|
+
checkTimeZone(timeZone);
|
|
67
|
+
const start = localDate(after, timeZone);
|
|
68
|
+
for (let i = 0; i <= 8; i += 1) {
|
|
69
|
+
const date = addDays(start, i);
|
|
70
|
+
if (s.type === 'weekly' && !s.days.includes(weekday(date))) continue;
|
|
71
|
+
const t = zonedTime(date, s.hour, s.minute, timeZone);
|
|
72
|
+
if (t > after) return t;
|
|
73
|
+
}
|
|
74
|
+
throw new Error('No next run found.');
|
|
75
|
+
}
|
|
76
|
+
module.exports = { checkTimeZone, normalizeSchedule, nextRun, zonedTime, localDate };
|
package/src/scheduler.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
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
|
+
normalizeSchedule(task.schedule);
|
|
47
|
+
tasks.set(task.id, { id: task.id, label: task.label ?? task.id, run: task.run, enabled: task.enabled !== false, timeZone: checkTimeZone(task.timeZone ?? defaultZone), maxLateMs: task.maxLateMs ?? maxLateMs, schedule: task.schedule });
|
|
48
|
+
}
|
|
49
|
+
const controllers = new Set();
|
|
50
|
+
let timer = null;
|
|
51
|
+
let ticking = null;
|
|
52
|
+
const upcoming = (task, from) => nextRun(task.schedule, from, task.timeZone);
|
|
53
|
+
const stopped = async () => { try { return Boolean(await options.shouldStop?.()); } catch (_error) { return true; } }; // Fail closed.
|
|
54
|
+
const blank = (task) => ({ id: task.id, status: 'scheduled', nextRunAt: null, lastStartedAt: null, lastRunAt: null, lastResult: null, lastError: null, skipReason: null, lastManual: false });
|
|
55
|
+
const read = async (task) => ({ ...blank(task), ...(await store.get(task.id)) });
|
|
56
|
+
const find = (id) => { const task = tasks.get(id); if (!task) throw new SchedulerError('unknown_task'); return task; };
|
|
57
|
+
|
|
58
|
+
async function skip(task, reason, state) {
|
|
59
|
+
await store.set(task.id, { ...state, status: 'skipped', skipReason: reason, nextRunAt: upcoming(task, now()) });
|
|
60
|
+
emit({ type: 'skipped', id: task.id, reason });
|
|
61
|
+
return { id: task.id, status: 'skipped', reason };
|
|
62
|
+
}
|
|
63
|
+
async function execute(task, { manual, signal }) {
|
|
64
|
+
if (await stopped()) {
|
|
65
|
+
if (manual) throw new SchedulerError('stopped');
|
|
66
|
+
return skip(task, 'stopped', await read(task));
|
|
67
|
+
}
|
|
68
|
+
const held = await lock.acquire(task.id);
|
|
69
|
+
if (!held) { if (manual) throw new SchedulerError('running'); return { id: task.id, status: 'locked' }; }
|
|
70
|
+
const controller = new globalThis.AbortController();
|
|
71
|
+
controllers.add(controller);
|
|
72
|
+
let poll;
|
|
73
|
+
let relay;
|
|
74
|
+
try {
|
|
75
|
+
const state = await read(task); // Read under the lock: another process may have just run it.
|
|
76
|
+
const startedAt = now();
|
|
77
|
+
if (!manual && state.nextRunAt && state.nextRunAt > startedAt) return { id: task.id, status: 'already_done' };
|
|
78
|
+
if (signal) {
|
|
79
|
+
if (signal.aborted) controller.abort(signal.reason);
|
|
80
|
+
else { relay = () => controller.abort(signal.reason); signal.addEventListener('abort', relay, { once: true }); }
|
|
81
|
+
}
|
|
82
|
+
poll = setInterval(() => { stopped().then((yes) => { if (yes) controller.abort(new SchedulerError('stopped')); }); }, stopCheckMs);
|
|
83
|
+
poll.unref?.();
|
|
84
|
+
await store.set(task.id, { ...state, status: 'running', lastStartedAt: startedAt, lastManual: manual });
|
|
85
|
+
emit({ type: 'start', id: task.id, manual });
|
|
86
|
+
let status = 'ok';
|
|
87
|
+
let result = state.lastResult;
|
|
88
|
+
let error = null;
|
|
89
|
+
let reason = null;
|
|
90
|
+
try {
|
|
91
|
+
if (controller.signal.aborted) throw controller.signal.reason;
|
|
92
|
+
result = copy(await task.run({ id: task.id, signal: controller.signal, manual, scheduledFor: state.nextRunAt, previous: state.lastResult, now: startedAt }));
|
|
93
|
+
} catch (caught) {
|
|
94
|
+
if (controller.signal.aborted) { status = 'skipped'; reason = 'stopped'; } else { status = 'error'; error = { message: String(caught?.message ?? caught), at: now() }; }
|
|
95
|
+
}
|
|
96
|
+
const finished = now();
|
|
97
|
+
await store.set(task.id, {
|
|
98
|
+
...state, status, lastStartedAt: startedAt, lastManual: manual,
|
|
99
|
+
lastRunAt: status === 'skipped' ? state.lastRunAt : finished, lastResult: status === 'ok' ? result : state.lastResult,
|
|
100
|
+
lastError: status === 'ok' ? null : (error ?? state.lastError), skipReason: reason,
|
|
101
|
+
nextRunAt: !manual || !state.nextRunAt ? upcoming(task, finished) : state.nextRunAt
|
|
102
|
+
});
|
|
103
|
+
emit({ type: status === 'ok' ? 'done' : status, id: task.id, manual, ...(error ? { error: error.message } : {}) });
|
|
104
|
+
return { id: task.id, status, ...(status === 'ok' ? { result } : {}), ...(error ? { error: error.message } : {}), ...(reason ? { reason } : {}) };
|
|
105
|
+
} finally {
|
|
106
|
+
clearInterval(poll);
|
|
107
|
+
if (relay) signal.removeEventListener('abort', relay);
|
|
108
|
+
controllers.delete(controller);
|
|
109
|
+
await held.release();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
async function pass() {
|
|
113
|
+
const results = [];
|
|
114
|
+
for (const task of tasks.values()) {
|
|
115
|
+
if (!task.enabled) continue;
|
|
116
|
+
try {
|
|
117
|
+
const at = now();
|
|
118
|
+
const state = await read(task);
|
|
119
|
+
if (!state.nextRunAt) { await store.set(task.id, { ...state, nextRunAt: upcoming(task, at) }); results.push({ id: task.id, status: 'scheduled' }); continue; }
|
|
120
|
+
if (state.nextRunAt > at) continue;
|
|
121
|
+
if (at - state.nextRunAt > task.maxLateMs) { results.push(await skip(task, 'late', state)); continue; }
|
|
122
|
+
results.push(await execute(task, { manual: false }));
|
|
123
|
+
} catch (error) { try { options.onError?.(error, task.id); } catch (_ignored) { /* An observer never breaks the scheduler. */ } }
|
|
124
|
+
}
|
|
125
|
+
return results;
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
/** One pass: plans the tasks never planned, skips the ones too late, runs the ones due. Resolves to what happened. */
|
|
129
|
+
tick() { if (!ticking) ticking = pass().finally(() => { ticking = null; }); return ticking; },
|
|
130
|
+
/** Starts the periodic pass (and one right away). Never called by the package itself. */
|
|
131
|
+
start() { if (timer) return; timer = setInterval(() => { void this.tick(); }, tickMs); timer.unref?.(); void this.tick(); },
|
|
132
|
+
/** Stops the periodic pass. A run in progress goes on; use abortAll() to cut it. */
|
|
133
|
+
stop() { if (timer) clearInterval(timer); timer = null; },
|
|
134
|
+
get started() { return timer !== null; },
|
|
135
|
+
/** Aborts every run in progress in this process (their `signal` aborts). */
|
|
136
|
+
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 } = {}) { return execute(find(id), { manual: true, signal }); },
|
|
139
|
+
/** State of one task, or of all of them. `nextRunAt` is computed when the task was never planned. */
|
|
140
|
+
async state(id) {
|
|
141
|
+
const describe = async (task) => { const s = await read(task); return { ...s, label: task.label, enabled: task.enabled, timeZone: task.timeZone, nextRunAt: s.nextRunAt ?? (task.enabled ? upcoming(task, now()) : null) }; };
|
|
142
|
+
if (id !== undefined) return describe(find(id));
|
|
143
|
+
return Promise.all([...tasks.values()].map(describe));
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
module.exports = { SchedulerError, createScheduler, createMemoryLock, createMemoryScheduleStore };
|