@astratra/agent 0.0.0-stage → 1.1.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/LICENSE +21 -0
- package/README.fr.md +163 -0
- package/README.md +331 -2
- package/package.json +46 -4
- package/src/agent.js +310 -0
- package/src/budget.js +31 -0
- package/src/context.js +22 -0
- package/src/feedback/index.d.ts +79 -0
- package/src/feedback/index.js +7 -0
- package/src/feedback/model.js +97 -0
- package/src/feedback/postgres.js +81 -0
- package/src/feedback/router.js +77 -0
- package/src/feedback/service.js +154 -0
- package/src/feedback/stores.js +46 -0
- package/src/index.d.ts +79 -0
- package/src/index.js +6 -0
- package/src/plan.js +19 -0
- package/src/postgres.js +25 -0
- package/src/taskStore.js +26 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Astratra contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.fr.md
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
# @astratra/agent
|
|
2
|
+
|
|
3
|
+
[English](README.md) | [Français](README.fr.md)
|
|
4
|
+
|
|
5
|
+
Exécution de tâches durables au-dessus de `runToolLoop` de `@astratra/ai` :
|
|
6
|
+
budgets (temps, tours, jetons, coût), annulation, plans, vérification de fin,
|
|
7
|
+
résumés de contexte, reprise après arrêt, confirmation avant les actions
|
|
8
|
+
sensibles, et retours des utilisateurs (pouce haut / bas) dont l'agent tient
|
|
9
|
+
compte. Modèles, outils, vérifications et stockage sont injectés. Node ≥ 20,
|
|
10
|
+
CommonJS, MIT. Aucun fournisseur d'IA ni pilote de base de données inclus.
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @astratra/agent
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```js
|
|
17
|
+
const { createAgent, createMemoryTaskStore } = require('@astratra/agent');
|
|
18
|
+
|
|
19
|
+
const agent = createAgent({
|
|
20
|
+
guards: false, // ou recommendedGuards({ models }) de '@astratra/ai/guards' : voir « Gardes »
|
|
21
|
+
store: createMemoryTaskStore(),
|
|
22
|
+
turn: async ({ system, messages, tools, signal, phase }) => ({ text: 'Le résultat est 3.', usage: { inputTokens: 40, outputTokens: 8 } }),
|
|
23
|
+
budget: { maxMs: 600000, maxTurns: 200, maxTokens: 100000, maxCost: 2 },
|
|
24
|
+
verify: ({ text }) => ({ complete: text.includes('3'), feedback: 'Calculez le résultat.' })
|
|
25
|
+
});
|
|
26
|
+
const task = await agent.run({ question: 'Calcule 1 + 2.' });
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
La référence complète de l'exécution (budgets, plans, vérifications, baux,
|
|
30
|
+
confirmations, événements) est dans le [README anglais](README.md). Cette page
|
|
31
|
+
détaille les retours.
|
|
32
|
+
|
|
33
|
+
## Retours des utilisateurs
|
|
34
|
+
|
|
35
|
+
`@astratra/agent/feedback` (aussi réexporté par l'entrée principale) recueille
|
|
36
|
+
un pouce haut ou bas sur une exécution et permet à l'agent d'en tenir compte.
|
|
37
|
+
Stockage, identité, masquage et lecture des exécutions sont injectés.
|
|
38
|
+
|
|
39
|
+
```js
|
|
40
|
+
const { createAgent, createFeedback, createFeedbackRouter,
|
|
41
|
+
createPostgresFeedbackStore, postgresFeedbackSchema } = require('@astratra/agent');
|
|
42
|
+
|
|
43
|
+
await db.query(postgresFeedbackSchema());
|
|
44
|
+
const feedback = createFeedback({
|
|
45
|
+
store: createPostgresFeedbackStore(db), // ou createMemoryFeedbackStore()
|
|
46
|
+
mask: (texte) => masqueur.mask(texte), // noms -> jetons
|
|
47
|
+
readRun: async ({ runId, tenantId }) => chargerExecution(runId) // { question, mode, tools, answer }
|
|
48
|
+
});
|
|
49
|
+
const agent = createAgent({ turn, feedback });
|
|
50
|
+
const task = await agent.run({ question, userId, tenantId }); // task.id = identifiant d'exécution
|
|
51
|
+
app.use('/api', createFeedbackRouter({
|
|
52
|
+
feedback,
|
|
53
|
+
identify: (req) => ({ userId: req.user.id, tenantId: req.user.orgId }),
|
|
54
|
+
resolveRun: async (req, runId, qui) => executionDe(runId, qui) // faux => 404
|
|
55
|
+
}));
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
- **Modèle** : un seul retour par personne et par exécution (et par
|
|
59
|
+
organisation). Donner à nouveau le remplace ; `update` en modifie des champs ;
|
|
60
|
+
`remove` le retire. La raison n'existe que pour `down` et vient d'une liste
|
|
61
|
+
fixe (`inaccurate`, `incomplete`, `off_topic`, `wrong_source`, `too_long`,
|
|
62
|
+
`unsafe`, `other`), extensible par `reasons`. Le commentaire est borné
|
|
63
|
+
(`maxComment`, 500 par défaut) et refusé au-delà, jamais tronqué en silence.
|
|
64
|
+
- **Magasins** : mémoire et PostgreSQL (SQL paramétré uniquement, schéma
|
|
65
|
+
exporté, clé unique organisation + personne + exécution).
|
|
66
|
+
- **Routeur Express** (express est une dépendance de pair facultative) :
|
|
67
|
+
`POST`, `PATCH`, `GET`, `DELETE` sur `/runs/:runId/feedback`. L'application
|
|
68
|
+
fournit l'identité (`identify`, 401 sinon) et vérifie que l'exécution
|
|
69
|
+
appartient à la personne (`resolveRun`) : une exécution étrangère répond 404,
|
|
70
|
+
comme une inconnue. Champs inconnus refusés, corps limité à 8 Kio.
|
|
71
|
+
- **L'agent en tient compte** : `createAgent({ feedback })` ajoute au prompt
|
|
72
|
+
système, en début de tâche, le résumé de ce que la personne n'a pas aimé
|
|
73
|
+
récemment (`feedbackDigest`), conservé dans la tâche pour une reprise
|
|
74
|
+
identique. Il est borné (800 caractères par défaut, 4000 au plus côté agent),
|
|
75
|
+
présenté comme une préférence et non une consigne, et ses commentaires sont
|
|
76
|
+
masqués, nettoyés et coupés. Une panne du résumé ne fait jamais échouer la
|
|
77
|
+
tâche. L'identifiant d'exécution est `task.id`, repris par les événements
|
|
78
|
+
`run` et `final` (`runId`).
|
|
79
|
+
- **Des 👎 aux tests** : `exportScenarioCandidates({ rating: 'down', since })`
|
|
80
|
+
produit des scénarios candidats anonymes (masqueur obligatoire, aucun
|
|
81
|
+
identifiant de personne ni d'organisation) ; `toAgentScenarios` les convertit
|
|
82
|
+
pour `evaluateAgent` de `@astratra/testkit` après relecture.
|
|
83
|
+
- **Statistiques** : `stats({ groupBy: 'agent' | 'mode' | 'reason' | 'day', since, until })`
|
|
84
|
+
donne totaux, taux 👍/👎 et groupes.
|
|
85
|
+
|
|
86
|
+
Les composants d'interface sont `FeedbackBar` dans `@astratra/native-ui`
|
|
87
|
+
(React Native) et `@astratra/saas-kit-ui` (web).
|
|
88
|
+
|
|
89
|
+
## Gardes (actives par défaut)
|
|
90
|
+
|
|
91
|
+
`createAgent({ guards })` accepte les gardes de `@astratra/ai/guards`
|
|
92
|
+
(`recommendedGuards` ou `createGuards`, fondées sur le client
|
|
93
|
+
`@astratra/models` injecté) : tout agent créé avec le paquet est protégé.
|
|
94
|
+
|
|
95
|
+
```js
|
|
96
|
+
const { recommendedGuards } = require('@astratra/ai/guards');
|
|
97
|
+
const guards = recommendedGuards({ models }); // readOnly: true pour un agent qui n'agit pas
|
|
98
|
+
const agent = createAgent({ guards, turn, tools, onEvent });
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
| Moment | Garde |
|
|
102
|
+
| --- | --- |
|
|
103
|
+
| début d'une tâche | `newRun` : mode `action` si un outil est de genre `write` ou `confirm`, sinon `read` (la politique de panne suit le mode) |
|
|
104
|
+
| la question et les messages précédents, avant tout modèle | `input` : noms et données personnelles masqués. Une saisie bloquée fait échouer la tâche (`error.code === 'GUARD_BLOCKED'`) |
|
|
105
|
+
| chaque résultat d'outil | `toolResult` : masqué ; pour un outil marqué `external: true` (web, e-mail, fichiers), contrôlé aussi contre l'injection et encadré comme donnée non fiable. Un résultat `{ untrusted: true, content }` est traité comme externe |
|
|
106
|
+
| avant un outil `write` ou `confirm` | `beforeAction` |
|
|
107
|
+
| la réponse finale | `output` : démasquée, puis ancrage dans les sources lues, fuite de données personnelles, modération |
|
|
108
|
+
|
|
109
|
+
**Action refusée.** Une injection suspectée, un outil `write` ne s'exécute pas :
|
|
110
|
+
la tâche passe en `waiting_confirmation` avec
|
|
111
|
+
`confirmation: { key, call, guard: { reason: 'confirmation_required' } }`. On
|
|
112
|
+
reprend avec `{ confirmation: { key, approved: true } }` (depuis votre
|
|
113
|
+
interface, jamais depuis le modèle) pour exécuter cet appel, ou `approved: false`
|
|
114
|
+
pour enregistrer un refus que le modèle lit. Un refus pour toute autre raison est
|
|
115
|
+
rendu au modèle comme une erreur d'outil (`Blocked by a guard: ...`), sans
|
|
116
|
+
exécution. Les outils `confirm` attendent déjà une personne ; leur confirmation
|
|
117
|
+
porte `guard: { requiresConfirmation: true }` quand une injection est suspectée,
|
|
118
|
+
et `beforeAction` est interrogée à nouveau, avec la confirmation, avant `perform`.
|
|
119
|
+
|
|
120
|
+
**Réponse.** Une réponse bloquée n'est jamais livrée : la tâche est `failed`,
|
|
121
|
+
`stopReason: 'guard'`, sans `task.text`. Une réponse signalée (par exemple des
|
|
122
|
+
affirmations que les sources ne soutiennent pas) est livrée, et `task.guard`
|
|
123
|
+
garde `{ decision, reasons, degraded, groundingScore, unsupportedClaims }`
|
|
124
|
+
(nombres et codes, aucun texte). `verify` reçoit la réponse démasquée et contrôlée.
|
|
125
|
+
|
|
126
|
+
**Événements.** Les décisions arrivent dans `onEvent` sous la forme
|
|
127
|
+
`{ type: 'guard', taskId, guard, decision, reasons, degraded, metrics, runId, mode, at }`
|
|
128
|
+
(l'identifiant d'exécution est celui de la tâche). Jamais de texte.
|
|
129
|
+
|
|
130
|
+
**État et reprise.** L'état des gardes est gardé dans la tâche (`task.guards`)
|
|
131
|
+
après la saisie et après chaque résultat d'outil : table de masquage, drapeau de
|
|
132
|
+
confirmation, empreintes des données personnelles données, sources externes lues
|
|
133
|
+
(masquées). Une tâche reprise, même dans un autre processus avec de nouvelles
|
|
134
|
+
gardes, démasque avec les mêmes jetons et exige toujours la confirmation. Les
|
|
135
|
+
messages de la tâche sont stockés masqués et `task.maskedQuestion` est ce que le
|
|
136
|
+
modèle lit. La table de masquage contient les vraies valeurs (c'est ainsi que la
|
|
137
|
+
réponse est démasquée) et `task.question` reste telle quelle : protégez le
|
|
138
|
+
magasin de tâches comme les données qu'il contient. Les outils reçoivent
|
|
139
|
+
`context.unmask(texte)` pour retrouver la vraie valeur d'un jeton écrit par le
|
|
140
|
+
modèle ; les arguments sont sinon transmis comme le modèle les a écrits.
|
|
141
|
+
|
|
142
|
+
**Par défaut.** `guards` est un choix à faire, pas une option à oublier :
|
|
143
|
+
|
|
144
|
+
- `NODE_ENV=production` sans `guards` : `createAgent` lève
|
|
145
|
+
`guards required in production: pass guards or guards:false`.
|
|
146
|
+
- ailleurs, sans `guards` : rien n'est gardé et un événement `warning`
|
|
147
|
+
(`code: 'guards_missing'`) est envoyé par agent.
|
|
148
|
+
- `guards: false` : choix explicite et silencieux.
|
|
149
|
+
|
|
150
|
+
Pour les tests : `createMockGuards` et `createFakeModels` de
|
|
151
|
+
`@astratra/ai/guards/testing`.
|
|
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
|
+
## Tests
|
|
160
|
+
|
|
161
|
+
`npm test -w @astratra/agent`. Les tests PostgreSQL réels ne tournent qu'avec
|
|
162
|
+
`AGENT_TEST_DATABASE_URL` désignant une base dont le nom finit par `_test` ;
|
|
163
|
+
sinon ils sont ignorés.
|
package/README.md
CHANGED
|
@@ -1,3 +1,332 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @astratra/agent
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[English](README.md) | [Français](README.fr.md)
|
|
4
|
+
|
|
5
|
+
Durable task execution built on `runToolLoop` from `@astratra/ai`. Models,
|
|
6
|
+
application tools, completion checks and persistence are injected. Node >= 20,
|
|
7
|
+
CommonJS, MIT. No provider or database driver is included.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @astratra/agent
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```js
|
|
14
|
+
const { createAgent, createMemoryTaskStore } = require('@astratra/agent');
|
|
15
|
+
|
|
16
|
+
const agent = createAgent({
|
|
17
|
+
guards: false, // or recommendedGuards({ models }) from '@astratra/ai/guards': see "Guards" below
|
|
18
|
+
store: createMemoryTaskStore(),
|
|
19
|
+
turn: async ({ system, messages, tools, signal, phase }) => {
|
|
20
|
+
// Adapt the application's provider to this response shape.
|
|
21
|
+
return { text: 'The result is 3.', toolCalls: [],
|
|
22
|
+
usage: { inputTokens: 40, outputTokens: 8 } };
|
|
23
|
+
},
|
|
24
|
+
budget: { maxMs: 600000, maxTurns: 200, maxTokens: 100000, maxCost: 2 },
|
|
25
|
+
pricing: { inputPerMillion: 1, outputPerMillion: 4 },
|
|
26
|
+
verify: ({ text }) => ({ complete: text.includes('3'), feedback: 'Compute the result.' }),
|
|
27
|
+
onEvent: async (event) => { /* Forward or persist application events. */ }
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const task = await agent.run({ question: 'Compute 1 + 2.' });
|
|
31
|
+
console.log(task.state, task.text, task.usage);
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Execution API
|
|
35
|
+
|
|
36
|
+
- `createAgent(options)` returns `{ store, create, run, resume }`.
|
|
37
|
+
- `create({ id?, question, messages? })` stores a pending task without running it.
|
|
38
|
+
- `run(input, { signal?, confirmation? }?)` creates and executes a task.
|
|
39
|
+
- `resume(id, { signal?, confirmation? }?)` acquires the lease and continues the
|
|
40
|
+
saved transcript, pending tool calls, plan, usage and verification count.
|
|
41
|
+
Completed and cancelled tasks are returned unchanged. Failed tasks can resume
|
|
42
|
+
with a new runner, for example with a larger budget.
|
|
43
|
+
|
|
44
|
+
`turn({ system, messages, tools, signal, phase })` returns
|
|
45
|
+
`{ text?, toolCalls?, usage? }`. Each tool call has `{ id, name, args }`; IDs
|
|
46
|
+
must be non-empty and unique within a turn. Phases are `execution`, `summary`,
|
|
47
|
+
`verification` and `final`. Tools use the native `@astratra/ai` contract:
|
|
48
|
+
`{ name, description, parameters, kind, run, perform?, undo? }`. The injected
|
|
49
|
+
context adds `taskId`, `idempotencyKey` and `signal` for each tool execution.
|
|
50
|
+
The runner executes tool groups serially to checkpoint each result separately.
|
|
51
|
+
Tool errors remain visible to the model through `createToolCaller`.
|
|
52
|
+
|
|
53
|
+
## Budgets and consumption
|
|
54
|
+
|
|
55
|
+
Defaults: one hour and 1000 model requests. `maxTokens` and `maxCost` are optional.
|
|
56
|
+
`maxMs` measures active execution time across resumptions; time spent waiting for
|
|
57
|
+
confirmation or between processes is excluded. Model summary and verification
|
|
58
|
+
requests count toward the same budget. The next request is prevented once a
|
|
59
|
+
limit is reached. A request already started can exceed a token or money limit:
|
|
60
|
+
this is accounting, not a provider-side spending cap.
|
|
61
|
+
|
|
62
|
+
When a budget is exhausted, a final model request with no tools has a separate
|
|
63
|
+
`finalMs` timeout (default 30000 ms). This one request is recorded and may exceed
|
|
64
|
+
the configured token, cost and turn limits. `finalInstruction` customizes its
|
|
65
|
+
instruction. External cancellation interrupts models, checks and summaries even
|
|
66
|
+
when they do not settle their promises, and propagates to tools. Providers and
|
|
67
|
+
tools must honor their signal to stop underlying work.
|
|
68
|
+
|
|
69
|
+
Usage accepts `inputTokens` / `outputTokens` or `prompt_tokens` /
|
|
70
|
+
`completion_tokens`, plus optional `cost`. Missing counts are estimated from
|
|
71
|
+
serialized characters divided by four, rounded up. `pricing` specifies input
|
|
72
|
+
and output prices per million tokens in the application's currency; absent
|
|
73
|
+
prices mean cost zero. The `estimated` flag is recorded for each turn. Requests
|
|
74
|
+
that fail before returning usage are counted as turns but their provider cost
|
|
75
|
+
is unknown. `usageHistory` and `usage` expose per-turn and aggregate accounting.
|
|
76
|
+
|
|
77
|
+
## Plans, checks and summaries
|
|
78
|
+
|
|
79
|
+
The built-in `update_plan` tool replaces the plan with
|
|
80
|
+
`{ steps: [{ id, text, state }] }`. States: `todo`, `in_progress`, `done`,
|
|
81
|
+
`abandoned`. Duplicate IDs and malformed steps are rejected. The name is
|
|
82
|
+
reserved. The current plan is included in the execution system instruction
|
|
83
|
+
and is stored separately from the transcript.
|
|
84
|
+
|
|
85
|
+
`verify({ task, text, signal })` returns a boolean or `{ complete, feedback? }`.
|
|
86
|
+
Alternatively, `verificationInstruction` runs a model request without tools,
|
|
87
|
+
expecting JSON `{ "complete": boolean, "feedback": string }`. An incomplete
|
|
88
|
+
answer adds feedback and resumes execution, at most `maxVerificationRetries`
|
|
89
|
+
times (default 3). Checks are optional; without one, normal model completion is
|
|
90
|
+
accepted. `verified` and `stopReason` distinguish accepted completion from
|
|
91
|
+
budget exhaustion or verification failure. An incomplete final task is `failed`.
|
|
92
|
+
Malformed checks fail explicitly.
|
|
93
|
+
|
|
94
|
+
`contextSummary: { maxChars?, maxTokens?, keepLast? }` enables compaction.
|
|
95
|
+
The default retained tail is eight messages. Complete tool exchanges are retained
|
|
96
|
+
when the boundary falls inside one, so more than N messages may remain.
|
|
97
|
+
`summarize({ messages, plan, signal })` returns non-empty summary text. Without
|
|
98
|
+
it, a model request without tools uses `summaryInstruction` or a default
|
|
99
|
+
instruction. The tail and separate plan remain intact; previous messages are
|
|
100
|
+
replaced by a system summary. Compaction failure preserves the original history.
|
|
101
|
+
|
|
102
|
+
## Persistence, confirmation and leases
|
|
103
|
+
|
|
104
|
+
States: `pending`, `running`, `waiting_confirmation`, `completed`, `failed`,
|
|
105
|
+
`cancelled`. `TaskStore` requires:
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
create(task: Task): Promise<Task>
|
|
109
|
+
get(id: string): Promise<Task | null>
|
|
110
|
+
acquire(id: string, owner: string, leaseMs: number): Promise<boolean>
|
|
111
|
+
renew(id: string, owner: string, leaseMs: number): Promise<boolean>
|
|
112
|
+
save(task: Task, owner: string): Promise<Task>
|
|
113
|
+
release(id: string, owner: string): Promise<void>
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Create refuses duplicates. Acquire is atomic and exclusive; renew and save
|
|
117
|
+
require the current, unexpired owner. Release must never clear another owner's
|
|
118
|
+
lease. The runner renews its lease every third of `leaseMs` (default 30000 ms).
|
|
119
|
+
A restarted process can resume after the previous lease expires. The memory
|
|
120
|
+
store copies values but is lost when the process exits.
|
|
121
|
+
|
|
122
|
+
Model responses, consumption, plans and each tool result are checkpointed.
|
|
123
|
+
Completed tool results are reused on resume. A crash between an external effect
|
|
124
|
+
and its checkpoint can replay the tool: use the stable `idempotencyKey` in the
|
|
125
|
+
external system. Exactly-once external effects cannot be guaranteed by a task
|
|
126
|
+
store. A process that loses its lease is aborted and cannot save stale results;
|
|
127
|
+
non-cooperative external operations may still finish, so enforce idempotency
|
|
128
|
+
and cancellation at their boundary. Application authorization and tenant access
|
|
129
|
+
to task IDs remain the application's responsibility.
|
|
130
|
+
|
|
131
|
+
A `confirm` tool pauses before `perform`; the task exposes
|
|
132
|
+
`confirmation: { key, call }`. Resume with
|
|
133
|
+
`{ confirmation: { key, approved: true } }` to perform it, or `approved: false`
|
|
134
|
+
to record rejection. No application write is performed before approval. The
|
|
135
|
+
runner itself does not authenticate the person approving the action.
|
|
136
|
+
|
|
137
|
+
```js
|
|
138
|
+
const { createPostgresTaskStore, postgresTaskSchema } = require('@astratra/agent');
|
|
139
|
+
// db is an application-owned pg Pool or compatible query adapter.
|
|
140
|
+
await db.query(postgresTaskSchema({ table: 'background_tasks' }));
|
|
141
|
+
const store = createPostgresTaskStore(db, { table: 'background_tasks' });
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Schema creation is explicit and idempotent, with a JSONB task record and lease
|
|
145
|
+
columns. All data uses SQL parameters. Table names must be plain identifiers.
|
|
146
|
+
No other package's migration is changed. PostgreSQL is not a runtime dependency.
|
|
147
|
+
|
|
148
|
+
## Guards (on by default)
|
|
149
|
+
|
|
150
|
+
`createAgent({ guards })` takes the guards of `@astratra/ai/guards`
|
|
151
|
+
(`recommendedGuards` or `createGuards`, built on the injected
|
|
152
|
+
`@astratra/models` client) so every agent made with the package is protected:
|
|
153
|
+
|
|
154
|
+
```js
|
|
155
|
+
const { recommendedGuards } = require('@astratra/ai/guards');
|
|
156
|
+
const guards = recommendedGuards({ models }); // add readOnly: true for an agent that cannot act
|
|
157
|
+
const agent = createAgent({ guards, turn, tools, onEvent });
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
| Moment | Guard |
|
|
161
|
+
| --- | --- |
|
|
162
|
+
| start of a task | `newRun`: mode `action` when a tool has kind `write` or `confirm`, otherwise `read` (the failure policy follows the mode) |
|
|
163
|
+
| the question and earlier messages, before any model | `input`: names and personal data masked. A blocked input fails the task (`error.code === 'GUARD_BLOCKED'`) |
|
|
164
|
+
| each tool result | `toolResult`: masked; for a tool marked `external: true` (web, e-mail, files) also scanned for injection and framed as untrusted data. A result `{ untrusted: true, content }` is treated as external too |
|
|
165
|
+
| before a tool of kind `write` or `confirm` | `beforeAction` |
|
|
166
|
+
| the final reply | `output`: unmasked, then grounding in the sources read, personal-data leak, moderation |
|
|
167
|
+
|
|
168
|
+
**Refused action.** After an injection is suspected, a `write` tool does not
|
|
169
|
+
run: the task becomes `waiting_confirmation` with
|
|
170
|
+
`confirmation: { key, call, guard: { reason: 'confirmation_required' } }`.
|
|
171
|
+
Resume with `{ confirmation: { key, approved: true } }` (from your interface,
|
|
172
|
+
never from the model) to run that call, or `approved: false` to record a
|
|
173
|
+
rejection the model reads. A refusal for any other reason is returned to the
|
|
174
|
+
model as a tool error (`Blocked by a guard: ...`) and the tool does not run.
|
|
175
|
+
`confirm` tools already wait for a person; their confirmation carries
|
|
176
|
+
`guard: { requiresConfirmation: true }` when an injection was suspected, and
|
|
177
|
+
`beforeAction` is asked again, with the person's confirmation, before `perform`.
|
|
178
|
+
|
|
179
|
+
**Reply.** A blocked reply is never delivered: the task is `failed`,
|
|
180
|
+
`stopReason: 'guard'`, `task.text` is absent. A flagged reply (for example
|
|
181
|
+
claims the sources do not support) is delivered, and `task.guard` keeps
|
|
182
|
+
`{ decision, reasons, degraded, groundingScore, unsupportedClaims }` (numbers
|
|
183
|
+
and codes, no text). `verify` receives the unmasked, checked reply.
|
|
184
|
+
|
|
185
|
+
**Events.** Guard decisions reach `onEvent` as `{ type: 'guard', taskId, guard,
|
|
186
|
+
decision, reasons, degraded, metrics, runId, mode, at }` (the run id is the task
|
|
187
|
+
id). They never contain text.
|
|
188
|
+
|
|
189
|
+
**State and resumption.** The state of the guards is kept in the task
|
|
190
|
+
(`task.guards`) after the input and after each tool result: the masking table,
|
|
191
|
+
the confirmation flag, hashes of the personal data the person gave, and the
|
|
192
|
+
external sources read, masked. A resumed task, even in a new process with new
|
|
193
|
+
guards, unmasks with the same tokens and still requires the confirmation.
|
|
194
|
+
The messages in the task are stored masked and `task.maskedQuestion` is what
|
|
195
|
+
the model reads. Note that the masking table holds the real values (it is how a
|
|
196
|
+
reply is unmasked) and `task.question` is kept as given: protect the task store
|
|
197
|
+
as the data it holds. Tools receive `context.unmask(text)` to turn a token the
|
|
198
|
+
model wrote back into the real value; arguments are otherwise passed as the
|
|
199
|
+
model wrote them.
|
|
200
|
+
|
|
201
|
+
**Default.** `guards` is a choice, not an option to forget:
|
|
202
|
+
|
|
203
|
+
- `NODE_ENV=production` and no `guards`: `createAgent` throws
|
|
204
|
+
`guards required in production: pass guards or guards:false`.
|
|
205
|
+
- elsewhere and no `guards`: nothing is guarded and one `warning` event
|
|
206
|
+
(`code: 'guards_missing'`) is sent per agent.
|
|
207
|
+
- `guards: false`: explicit, silent opt-out.
|
|
208
|
+
|
|
209
|
+
Tests can use `createMockGuards` and `createFakeModels` from
|
|
210
|
+
`@astratra/ai/guards/testing`.
|
|
211
|
+
|
|
212
|
+
## Events and helper exports
|
|
213
|
+
|
|
214
|
+
`onEvent(event)` is awaited. Events: `plan`, `step`, `usage`, `summary`,
|
|
215
|
+
`verification`, `confirmation`, `final`, `guard`, `warning`; each carries `taskId`. Event delivery
|
|
216
|
+
is not transactional with the checkpoint; use application outbox infrastructure
|
|
217
|
+
if delivery must survive a crash. Handler errors fail execution explicitly.
|
|
218
|
+
|
|
219
|
+
Also exported: `PLAN_STATES`, `TASK_STATES`, `validatePlan`, `createPlanTool`,
|
|
220
|
+
`validateTask`, `estimateTokens`, `normalizeBudget`, `usageOf`, `budgetReason`,
|
|
221
|
+
`contextBoundary`, `summarizeContext`. Full signatures are in `src/index.d.ts`.
|
|
222
|
+
|
|
223
|
+
## User feedback (thumbs up / down)
|
|
224
|
+
|
|
225
|
+
`@astratra/agent/feedback` (also re-exported from the main entry) collects a
|
|
226
|
+
thumbs up or down on an agent run and lets the agent take it into account. It
|
|
227
|
+
has no AI-provider dependency; storage, identity, masking and run lookup are
|
|
228
|
+
injected.
|
|
229
|
+
|
|
230
|
+
```js
|
|
231
|
+
const express = require('express');
|
|
232
|
+
const { createAgent, createFeedback, createFeedbackRouter,
|
|
233
|
+
createPostgresFeedbackStore, postgresFeedbackSchema } = require('@astratra/agent');
|
|
234
|
+
|
|
235
|
+
await db.query(postgresFeedbackSchema()); // explicit, idempotent
|
|
236
|
+
const feedback = createFeedback({
|
|
237
|
+
store: createPostgresFeedbackStore(db), // or createMemoryFeedbackStore()
|
|
238
|
+
mask: (text) => masker.mask(text), // names -> tokens (see @astratra/ai masking)
|
|
239
|
+
readRun: async ({ runId, tenantId }) => loadRun(runId) // { question, mode, tools, answer }
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
const agent = createAgent({ turn, feedback }); // the digest joins the system prompt
|
|
243
|
+
const task = await agent.run({ question, userId, tenantId });
|
|
244
|
+
// task.id is the run id to give to the interface; events 'run' and 'final' carry runId.
|
|
245
|
+
|
|
246
|
+
app.use('/api', createFeedbackRouter({
|
|
247
|
+
feedback,
|
|
248
|
+
identify: (req) => ({ userId: req.user.id, tenantId: req.user.orgId }),
|
|
249
|
+
resolveRun: async (req, runId, who) => ownedRun(runId, who) // falsy => 404
|
|
250
|
+
}));
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
**Model.** `{ id, tenantId?, userId, runId, messageId?, rating: 'up' | 'down',
|
|
254
|
+
reason?, comment?, agent?, mode?, createdAt, updatedAt }`, with times in epoch
|
|
255
|
+
milliseconds. One feedback per person and run (per tenant): giving again
|
|
256
|
+
replaces it, `update` modifies some fields, `remove` withdraws it. `reason`
|
|
257
|
+
belongs to `down` only and comes from a fixed list, `FEEDBACK_REASONS`
|
|
258
|
+
(`inaccurate`, `incomplete`, `off_topic`, `wrong_source`, `too_long`, `unsafe`,
|
|
259
|
+
`other`), extensible with `createFeedback({ reasons: ['slow'] })` (lowercase
|
|
260
|
+
names). `comment` is limited (`maxComment`, default 500) and refused above it,
|
|
261
|
+
never truncated silently. Invalid input throws `FeedbackError` (`invalid`,
|
|
262
|
+
`not_found`).
|
|
263
|
+
|
|
264
|
+
**Stores.** `createMemoryFeedbackStore()` and
|
|
265
|
+
`createPostgresFeedbackStore(db, { table })` with `postgresFeedbackSchema({ table })`.
|
|
266
|
+
Every value is a SQL parameter; table names must be plain identifiers (48
|
|
267
|
+
characters at most). A unique key on tenant, user and run makes concurrent
|
|
268
|
+
gives safe.
|
|
269
|
+
|
|
270
|
+
**Router.** `createFeedbackRouter({ feedback, identify, resolveRun, express?, maxBodyBytes? })`
|
|
271
|
+
(`express` is an optional peer dependency):
|
|
272
|
+
|
|
273
|
+
| Route | Effect |
|
|
274
|
+
| --- | --- |
|
|
275
|
+
| `POST /runs/:runId/feedback` | give or replace; 201 created, 200 replaced |
|
|
276
|
+
| `PATCH /runs/:runId/feedback` | change some of `rating`, `reason`, `comment`, `messageId` |
|
|
277
|
+
| `GET /runs/:runId/feedback` | read your own |
|
|
278
|
+
| `DELETE /runs/:runId/feedback` | withdraw; 204 |
|
|
279
|
+
|
|
280
|
+
The application supplies the identity (`identify`, 401 when falsy) and checks
|
|
281
|
+
that the run belongs to that person (`resolveRun`; falsy answers 404, exactly
|
|
282
|
+
like an unknown run). The identity never comes from the body; unknown body
|
|
283
|
+
fields are refused; the body is limited (default 8 KiB). `resolveRun` may
|
|
284
|
+
return `{ agent, mode }`, stored with the feedback for the statistics.
|
|
285
|
+
|
|
286
|
+
**The agent learns.** `createAgent({ feedback })` accepts a service from
|
|
287
|
+
`createFeedback` or a function `({ userId, tenantId, task, signal }) => string`.
|
|
288
|
+
At the start of a task with a `userId`, the text is added to the system
|
|
289
|
+
prompt, then kept in the task (`task.feedbackDigest`) so a resumed task sees the
|
|
290
|
+
same prompt. It is capped at 4000 characters, and a failing digest never fails
|
|
291
|
+
the task.
|
|
292
|
+
|
|
293
|
+
`feedback.feedbackDigest({ userId, tenantId?, since?, limit?, maxChars?, includeNotes?, maxNotes?, noteChars?, mask? })`
|
|
294
|
+
returns a short text (default: last 30 days, 20 feedbacks, 800 characters):
|
|
295
|
+
the number of disliked answers, the reasons aggregated with a hint each
|
|
296
|
+
(`reasonHints` overrides the sentences), and up to three quoted comments, each
|
|
297
|
+
masked with `mask`, scrubbed of e-mail addresses, links and numbers, stripped
|
|
298
|
+
of quotes and brackets, and cut to 120 characters. The text states that it is
|
|
299
|
+
preference data, not instructions. If the mask fails, notes are dropped, never
|
|
300
|
+
sent raw.
|
|
301
|
+
|
|
302
|
+
**From dislikes to tests.** `feedback.exportScenarioCandidates({ rating: 'down', since, tenantId?, limit? })`
|
|
303
|
+
reads each disliked run with the injected `readRun` and returns anonymous
|
|
304
|
+
candidates `{ id, name, input, question, mode, tools, expect: { tools, content: [] }, score: null, feedback, answer? }`.
|
|
305
|
+
A `mask` is mandatory (the call throws without one). No user or tenant id
|
|
306
|
+
appears; the id is a salted hash of the run; e-mails, links, numbers and the
|
|
307
|
+
person's own ids are scrubbed after masking. Review each candidate, fill
|
|
308
|
+
`expect.content`, then `toAgentScenarios(candidates, { fixtures })` gives
|
|
309
|
+
scenarios for `evaluateAgent` from `@astratra/testkit` (`fixtures` maps a tool
|
|
310
|
+
name to a deterministic `run`).
|
|
311
|
+
|
|
312
|
+
**Statistics.** `feedback.stats({ tenantId?, agent?, mode?, since?, until?, groupBy? })`
|
|
313
|
+
returns `{ total, up, down, upRate, downRate, groups }`, grouped by `agent`,
|
|
314
|
+
`mode`, `reason` (down only; missing reasons are `unspecified`) or `day` (UTC).
|
|
315
|
+
Rates are `null` when there is nothing. Omitting `tenantId` counts every
|
|
316
|
+
tenant: scope it for tenant dashboards.
|
|
317
|
+
|
|
318
|
+
The interface parts are `FeedbackBar` in `@astratra/native-ui` (React Native)
|
|
319
|
+
and `@astratra/saas-kit-ui` (web).
|
|
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
|
+
## Tests
|
|
328
|
+
|
|
329
|
+
`npm test -w @astratra/agent` uses `node --test`; the guard tests run on
|
|
330
|
+
`@astratra/ai/guards/testing` with no model. Real PostgreSQL tests run only
|
|
331
|
+
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.
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/agent",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
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
|
+
"engines": {
|
|
6
|
+
"node": ">=20"
|
|
7
|
+
},
|
|
8
|
+
"main": "src/index.js",
|
|
9
|
+
"types": "src/index.d.ts",
|
|
10
|
+
"type": "commonjs",
|
|
11
|
+
"files": [
|
|
12
|
+
"src"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"test": "node --test test/*.test.js"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@astratra/ai": "^1.8.0"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"express": "^4.18.3",
|
|
26
|
+
"pg": "^8.13.1",
|
|
27
|
+
"supertest": "^7.0.0"
|
|
28
|
+
},
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./src/index.d.ts",
|
|
32
|
+
"default": "./src/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./feedback": {
|
|
35
|
+
"types": "./src/feedback/index.d.ts",
|
|
36
|
+
"default": "./src/feedback/index.js"
|
|
37
|
+
},
|
|
38
|
+
"./package.json": "./package.json"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"express": ">=4"
|
|
42
|
+
},
|
|
43
|
+
"peerDependenciesMeta": {
|
|
44
|
+
"express": {
|
|
45
|
+
"optional": true
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|