@astratra/ai 1.1.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.md CHANGED
@@ -108,3 +108,80 @@ construire dans votre propre boucle, ou à couvrir dans un futur spec.
108
108
  ```bash
109
109
  npm test --workspace @astratra/ai
110
110
  ```
111
+
112
+ ## Le sas : un agent propose, un humain dispose
113
+
114
+ Un agent autorisé à écrire est dangereux d'une façon qu'un agent qui répond
115
+ n'est pas. Le mode de panne n'est pas la malveillance, c'est l'assurance : le
116
+ modèle appelle `send_email` avec un destinataire plausible et un corps
117
+ plausible, et une vraie famille reçoit un vrai message que personne n'a
118
+ approuvé.
119
+
120
+ ```js
121
+ const { createPendingActions } = require('@astratra/ai');
122
+
123
+ const sas = createPendingActions({
124
+ store,
125
+ // Seul ce qui figure ici peut JAMAIS s'exécuter.
126
+ tools: {
127
+ send_email: async (payload) => mailer.send(payload),
128
+ send_fee_reminders: async (payload) => finance.remind(payload),
129
+ },
130
+ onPending: (action) => notifier.tell(action), // « quelque chose attend »
131
+ });
132
+
133
+ // L'agent propose — rien ne part.
134
+ await sas.propose({ action: 'send_email', payload, proposedBy: 'agent', dedupeKey });
135
+
136
+ // Un humain tranche.
137
+ await sas.approve(id, { approvedBy: userId, amend: { to: 'bonne-adresse@x.cd' } });
138
+ await sas.reject(id, { rejectedBy: userId, note: 'mauvais destinataire' });
139
+ ```
140
+
141
+ `createMemoryActionStore()` fournit un store en mémoire pour les tests et le
142
+ développement — non persistant, donc à remplacer par une vraie table dès qu'il
143
+ y a plusieurs instances : la revendication atomique n'a de sens que partagée.
144
+
145
+ Ce que le cycle garantit :
146
+
147
+ - **une exécution, jamais deux** — la transition vers `executing` est une
148
+ revendication atomique : deux approbations simultanées produisent un envoi ;
149
+ - **`dedupeKey`** empêche un modèle insistant d'empiler cinq propositions
150
+ identiques ;
151
+ - **`amend`** : l'humain corrige le brouillon du modèle — destinataire, liste —
152
+ et la correction est consignée ;
153
+ - un outil qui **retourne** une erreur est marqué `failed`, jamais `executed` :
154
+ « Envoyé » à l'écran pour un message jamais parti est le mensonge que ce sas
155
+ existe pour empêcher ;
156
+ - un canal de notification mort ne fait pas échouer l'agent — l'action reste
157
+ visible dans sa liste.
158
+
159
+ ## Le repli déterministe : répondre quand tout est tombé
160
+
161
+ La norme, quand le dernier fournisseur de la chaîne échoue, est un message
162
+ d'erreur. L'alternative est une réponse calculée SANS modèle, depuis les données
163
+ qu'on a déjà. Ce n'est pas aussi bien — et ce n'est jamais un écran vide.
164
+
165
+ ```js
166
+ const { createDeterministicFallback } = require('@astratra/ai');
167
+
168
+ const repli = createDeterministicFallback({
169
+ responders: {
170
+ average: async ({ grades }) => ({ text: `La moyenne est de ${mean(grades)}/20.` }),
171
+ },
172
+ classify: (input) => input.question.includes('moyenne') ? 'average' : null,
173
+ });
174
+
175
+ const { degraded, answer, providerError } = await repli.withFallback(
176
+ (input) => router.ask(input),
177
+ input,
178
+ );
179
+ ```
180
+
181
+ La règle d'honnêteté est la partie qui compte : une réponse de repli **dit**
182
+ qu'elle en est une (`degraded: true`). Servir une réponse dégradée comme si de
183
+ rien n'était apprend aux utilisateurs à se méfier des bonnes.
184
+
185
+ Et l'erreur du fournisseur est **transportée**, pas avalée : la gober en
186
+ silence cacherait la panne à ta propre supervision. Une question sans réponse
187
+ déterministe est déclinée, pas inventée.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/ai",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Generic AI provider routing, tool registry, and agent loop utilities for Astratra.",
5
5
  "engines": {
6
6
  "node": ">=20"
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Answering when every provider is down.
3
+ *
4
+ * The norm, when the last AI provider in the chain fails, is an error message.
5
+ * The alternative is a DETERMINISTIC answer: computed without any model, from
6
+ * the data you already have. It is not as good — and it is never a blank
7
+ * screen. A parent asking about their child's average gets the average and a
8
+ * plain sentence, not "service unavailable, try later".
9
+ *
10
+ * The honesty rule is the part that matters: a fallback answer SAYS it is one.
11
+ * Serving a degraded answer as if nothing happened teaches users to distrust
12
+ * the good ones.
13
+ */
14
+
15
+ /**
16
+ * @param {object} options
17
+ * @param {Record<string, Function>} options.responders intent -> async (input) => answer.
18
+ * Each one is plain code: a template over data, no model anywhere.
19
+ * @param {Function} [options.classify] (input) => intent. Defaults to reading
20
+ * `input.intent`. Keyword matching is the usual implementation — crude, and
21
+ * crude is fine here: this path only runs when everything better is down.
22
+ * @param {Function} [options.markDegraded] (answer) => answer, applied to every
23
+ * fallback response so the caller — and the user — can tell.
24
+ */
25
+ function createDeterministicFallback(options = {}) {
26
+ const responders = options.responders || {};
27
+ if (!Object.keys(responders).length) {
28
+ throw new Error('createDeterministicFallback requires at least one responder.');
29
+ }
30
+
31
+ const classify = options.classify || ((input) => input && input.intent);
32
+ const markDegraded = options.markDegraded
33
+ || ((answer) => ({ ...answer, degraded: true }));
34
+
35
+ /**
36
+ * @returns {Promise<{handled: boolean, answer?: object}>}
37
+ * handled: false means "no deterministic answer exists for this" — the
38
+ * caller then apologises honestly instead of inventing.
39
+ */
40
+ async function answer(input) {
41
+ const intent = classify(input);
42
+ const responder = intent && responders[intent];
43
+ if (!responder) return { handled: false };
44
+
45
+ const produced = await responder(input);
46
+ if (produced === null || produced === undefined) return { handled: false };
47
+
48
+ const shaped = typeof produced === 'object' ? produced : { text: String(produced) };
49
+ return { handled: true, answer: markDegraded(shaped) };
50
+ }
51
+
52
+ /**
53
+ * Wrap a provider call: try it, fall back when it throws.
54
+ *
55
+ * The provider error is carried alongside the fallback answer — silently
56
+ * eating it would hide the outage from your own monitoring.
57
+ */
58
+ async function withFallback(ask, input) {
59
+ try {
60
+ return { degraded: false, answer: await ask(input) };
61
+ } catch (error) {
62
+ const fallen = await answer(input);
63
+ if (fallen.handled) return { degraded: true, answer: fallen.answer, providerError: error };
64
+ throw error;
65
+ }
66
+ }
67
+
68
+ return { answer, withFallback, intents: Object.keys(responders) };
69
+ }
70
+
71
+ module.exports = { createDeterministicFallback };
package/src/index.d.ts CHANGED
@@ -118,3 +118,98 @@ export interface AgentLoopOptions {
118
118
  }
119
119
 
120
120
  export function runAgentLoop(options: AgentLoopOptions): Promise<string>;
121
+
122
+ export type ActionStatus = 'proposed' | 'approved' | 'rejected' | 'executing' | 'executed' | 'failed';
123
+
124
+ export interface PendingAction {
125
+ id: string;
126
+ action: string;
127
+ payload: Record<string, unknown>;
128
+ description: string | null;
129
+ proposedBy: unknown;
130
+ tenant: unknown;
131
+ dedupeKey: string | null;
132
+ status: ActionStatus;
133
+ proposedAt: Date;
134
+ approvedBy?: unknown;
135
+ approvedAt?: Date;
136
+ rejectedBy?: unknown;
137
+ rejectedAt?: Date;
138
+ executedAt?: Date;
139
+ failedAt?: Date;
140
+ lastError?: string;
141
+ amendedWith?: Record<string, unknown> | null;
142
+ reviewNote?: string | null;
143
+ [key: string]: unknown;
144
+ }
145
+
146
+ export interface ActionStore {
147
+ create(data: Record<string, unknown>): Awaitable<PendingAction>;
148
+ find(id: string): Awaitable<PendingAction | null>;
149
+ /** Atomic status transition: returns null when the record was not in `from`. */
150
+ claim(id: string, from: ActionStatus[], patch: Record<string, unknown>): Awaitable<PendingAction | null>;
151
+ update(id: string, patch: Record<string, unknown>): Awaitable<PendingAction | null>;
152
+ findOpenByKey?(dedupeKey: string, statuses: ActionStatus[]): Awaitable<PendingAction | null>;
153
+ list?(filter?: Record<string, unknown>): Awaitable<PendingAction[]>;
154
+ }
155
+
156
+ export type ActionTool = (
157
+ payload: Record<string, unknown>,
158
+ context: { action: PendingAction; approvedBy: unknown }
159
+ ) => Awaitable<unknown>;
160
+
161
+ export interface PendingActions {
162
+ /** The agent proposes a write. Nothing runs yet. */
163
+ propose(input: {
164
+ action: string;
165
+ payload?: Record<string, unknown>;
166
+ description?: string;
167
+ proposedBy?: unknown;
168
+ tenant?: unknown;
169
+ dedupeKey?: string;
170
+ }): Promise<{ created: boolean; action: PendingAction }>;
171
+ /** A human says yes — the tool runs once, atomically claimed. */
172
+ approve(id: string, review: { approvedBy: unknown; amend?: Record<string, unknown> }): Promise<
173
+ | { executed: true; action: PendingAction; result: unknown }
174
+ | { executed: false; reason: 'already-handled' | 'failed'; error?: string }
175
+ >;
176
+ reject(id: string, review: { rejectedBy: unknown; note?: string }): Promise<PendingAction>;
177
+ pending(filter?: Record<string, unknown>): Promise<PendingAction[]>;
178
+ tools: string[];
179
+ OPEN_STATUSES: ActionStatus[];
180
+ }
181
+
182
+ export function createPendingActions(options: {
183
+ store: ActionStore;
184
+ tools: Record<string, ActionTool>;
185
+ onPending?: (action: PendingAction) => Awaitable<void>;
186
+ now?: () => Date;
187
+ logger?: { info?(m: string): void; warn?(m: string): void; error?(m: string): void };
188
+ }): PendingActions;
189
+
190
+ export function createMemoryActionStore(): ActionStore & {
191
+ findOpenByKey(dedupeKey: string, statuses: ActionStatus[]): Promise<PendingAction | null>;
192
+ list(filter?: Record<string, unknown>): Promise<PendingAction[]>;
193
+ size(): number;
194
+ };
195
+
196
+ export interface FallbackAnswer {
197
+ handled: boolean;
198
+ answer?: Record<string, unknown> & { degraded?: boolean };
199
+ }
200
+
201
+ export interface DeterministicFallback<Input = Record<string, unknown>> {
202
+ answer(input: Input): Promise<FallbackAnswer>;
203
+ /** Try the provider; serve the deterministic answer when it throws, carrying the provider error. */
204
+ withFallback<T>(ask: (input: Input) => Awaitable<T>, input: Input): Promise<
205
+ | { degraded: false; answer: T }
206
+ | { degraded: true; answer: Record<string, unknown>; providerError: unknown }
207
+ >;
208
+ intents: string[];
209
+ }
210
+
211
+ export function createDeterministicFallback<Input = Record<string, unknown>>(options: {
212
+ responders: Record<string, (input: Input) => Awaitable<unknown>>;
213
+ classify?: (input: Input) => string | null | undefined;
214
+ markDegraded?: (answer: Record<string, unknown>) => Record<string, unknown>;
215
+ }): DeterministicFallback<Input>;
package/src/index.js CHANGED
@@ -1,5 +1,7 @@
1
1
  module.exports = {
2
2
  ...require('./providerRouter'),
3
3
  ...require('./toolRegistry'),
4
- ...require('./agentLoop')
4
+ ...require('./agentLoop'),
5
+ ...require('./pendingActions'),
6
+ ...require('./fallback')
5
7
  };
@@ -0,0 +1,216 @@
1
+ /**
2
+ * The airlock between an agent that proposes and a human who decides.
3
+ *
4
+ * An agent allowed to write is dangerous in a way an agent that answers is not.
5
+ * The failure is not malice, it is confidence: the model calls send_email with
6
+ * a plausible recipient and a plausible body, and a real family receives a real
7
+ * message nobody approved.
8
+ *
9
+ * So a write is never executed on the model's say-so. It becomes a PENDING
10
+ * ACTION: recorded, visible, waiting. A person approves it, and only then does
11
+ * it run — through a lifecycle that also guarantees it cannot run twice.
12
+ *
13
+ * proposed -> approved -> executing -> executed
14
+ * \-> rejected \-> failed
15
+ *
16
+ * The `executing` step is not decoration. The transition INTO it is atomic
17
+ * (one findOneAndUpdate-style claim in the store): two people clicking
18
+ * "approve" at the same moment produce one send, not two.
19
+ */
20
+ const { AppError } = require('@astratra/core');
21
+
22
+ const PROPOSED = 'proposed';
23
+ const APPROVED = 'approved';
24
+ const REJECTED = 'rejected';
25
+ const EXECUTING = 'executing';
26
+ const EXECUTED = 'executed';
27
+ const FAILED = 'failed';
28
+
29
+ const OPEN_STATUSES = [PROPOSED, APPROVED, EXECUTING];
30
+
31
+ /**
32
+ * @param {object} options
33
+ * @param {object} options.store adapter:
34
+ * create(data), find(id), claim(id, from[], patch) — atomic status change,
35
+ * update(id, patch), findOpenByKey(dedupeKey), list(filter).
36
+ * @param {Record<string, Function>} options.tools action name -> executor.
37
+ * Only what is listed here can EVER run. An action recorded with a name this
38
+ * map does not carry is refused at execution, however it got approved.
39
+ * @param {Function} [options.onPending] async (action) => void — tell the
40
+ * humans something waits. Failures are swallowed: the action stays visible
41
+ * in its list even if the notification channel is down.
42
+ * @param {Function} [options.now]
43
+ * @param {object} [options.logger]
44
+ */
45
+ function createPendingActions(options = {}) {
46
+ const store = options.store;
47
+ for (const method of ['create', 'find', 'claim', 'update']) {
48
+ if (!store || typeof store[method] !== 'function') {
49
+ throw new Error(`createPendingActions requires options.store.${method}().`);
50
+ }
51
+ }
52
+
53
+ const tools = options.tools || {};
54
+ if (!Object.keys(tools).length) {
55
+ throw new Error('createPendingActions requires at least one tool in options.tools.');
56
+ }
57
+
58
+ const onPending = options.onPending || null;
59
+ const now = options.now || (() => new Date());
60
+ const logger = options.logger || { info() {}, warn() {}, error() {} };
61
+
62
+ /**
63
+ * The agent proposes a write. Nothing happens yet.
64
+ *
65
+ * `dedupeKey` is what stops an insistent model from stacking five identical
66
+ * proposals: the same open action is returned instead of a new one.
67
+ */
68
+ async function propose({ action, payload = {}, description, proposedBy, tenant, dedupeKey } = {}) {
69
+ if (!action || !tools[action]) {
70
+ throw new AppError(`"${action}" is not a tool this airlock knows.`, 400);
71
+ }
72
+
73
+ if (dedupeKey && typeof store.findOpenByKey === 'function') {
74
+ const existing = await store.findOpenByKey(dedupeKey, OPEN_STATUSES);
75
+ if (existing) return { created: false, action: existing };
76
+ }
77
+
78
+ const record = await store.create({
79
+ action, payload, description: description || null,
80
+ proposedBy: proposedBy || null, tenant: tenant || null,
81
+ dedupeKey: dedupeKey || null,
82
+ status: PROPOSED, proposedAt: now()
83
+ });
84
+
85
+ if (onPending) {
86
+ try {
87
+ await onPending(record);
88
+ } catch (error) {
89
+ /* The action stays visible in its list either way. The agent must not
90
+ fail because the notification backend blinked. */
91
+ logger.warn(`[pending-actions] notification failed: ${error.message}`);
92
+ }
93
+ }
94
+
95
+ return { created: true, action: record };
96
+ }
97
+
98
+ /**
99
+ * A human says yes — and the action runs, once.
100
+ */
101
+ async function approve(id, { approvedBy, amend } = {}) {
102
+ if (approvedBy === undefined || approvedBy === null) {
103
+ throw new AppError('An approval must record who approved it.', 400);
104
+ }
105
+
106
+ const pending = await store.find(id);
107
+ if (!pending) throw new AppError('This action could not be found.', 404);
108
+ if (pending.status !== PROPOSED) {
109
+ throw new AppError(`This action has already been ${pending.status}.`, 409);
110
+ }
111
+
112
+ const tool = tools[pending.action];
113
+ if (!tool) {
114
+ /* Recorded under one catalogue, approved under another — a deploy
115
+ between the two, or a tampered record. Refuse. */
116
+ throw new AppError(`Tool "${pending.action}" is not available any more.`, 400);
117
+ }
118
+
119
+ /* The atomic claim. Whoever loses this race gets a clean "already
120
+ handled", not a second execution. */
121
+ const claimed = await store.claim(id, [PROPOSED], {
122
+ status: EXECUTING, approvedBy, approvedAt: now()
123
+ });
124
+ if (!claimed) return { executed: false, reason: 'already-handled' };
125
+
126
+ /* An amendment comes from the HUMAN — correcting a recipient, trimming a
127
+ list. The model's payload is never silently replaced; the two are
128
+ merged with the human's values on top, and the amendment is recorded. */
129
+ const payload = amend ? { ...claimed.payload, ...amend } : claimed.payload;
130
+
131
+ try {
132
+ const result = await tool(payload, { action: claimed, approvedBy });
133
+ /* A tool that RETURNS an error has not succeeded, even though it did not
134
+ throw. Marking it executed would show "sent" for a message that never
135
+ left. */
136
+ if (result && result.error) throw new AppError(String(result.error), 502);
137
+
138
+ const done = await store.update(id, { status: EXECUTED, executedAt: now(), amendedWith: amend || null });
139
+ logger.info(`[pending-actions] "${claimed.action}" executed (approved by ${approvedBy})`);
140
+ return { executed: true, action: done, result };
141
+ } catch (error) {
142
+ await store.update(id, { status: FAILED, failedAt: now(), lastError: error.message });
143
+ logger.error(`[pending-actions] "${claimed.action}" failed: ${error.message}`);
144
+ return { executed: false, reason: 'failed', error: error.message };
145
+ }
146
+ }
147
+
148
+ /** A human says no. The record stays — a refused proposal is information. */
149
+ async function reject(id, { rejectedBy, note } = {}) {
150
+ if (rejectedBy === undefined || rejectedBy === null) {
151
+ throw new AppError('A rejection must record who rejected it.', 400);
152
+ }
153
+ const pending = await store.find(id);
154
+ if (!pending) throw new AppError('This action could not be found.', 404);
155
+ if (pending.status !== PROPOSED) {
156
+ throw new AppError(`This action has already been ${pending.status}.`, 409);
157
+ }
158
+ return store.update(id, { status: REJECTED, rejectedBy, rejectedAt: now(), reviewNote: note || null });
159
+ }
160
+
161
+ /** What waits for a human. */
162
+ async function pending(filter = {}) {
163
+ if (typeof store.list !== 'function') {
164
+ throw new Error('createPendingActions: options.store.list is required to list.');
165
+ }
166
+ return store.list({ ...filter, status: PROPOSED });
167
+ }
168
+
169
+ return {
170
+ propose, approve, reject, pending,
171
+ tools: Object.keys(tools),
172
+ PROPOSED, APPROVED, REJECTED, EXECUTING, EXECUTED, FAILED, OPEN_STATUSES
173
+ };
174
+ }
175
+
176
+ /** In-process store for tests and development. Not persistent. */
177
+ function createMemoryActionStore() {
178
+ const records = new Map();
179
+ let sequence = 0;
180
+ const clone = (r) => (r ? JSON.parse(JSON.stringify(r)) : r);
181
+
182
+ return {
183
+ async create(data) {
184
+ const id = String(++sequence);
185
+ records.set(id, { id, ...data });
186
+ return clone(records.get(id));
187
+ },
188
+ async find(id) { return clone(records.get(String(id))) || null; },
189
+ async claim(id, fromStatuses, patch) {
190
+ const record = records.get(String(id));
191
+ if (!record || !fromStatuses.includes(record.status)) return null;
192
+ Object.assign(record, patch);
193
+ return clone(record);
194
+ },
195
+ async update(id, patch) {
196
+ const record = records.get(String(id));
197
+ if (!record) return null;
198
+ Object.assign(record, patch);
199
+ return clone(record);
200
+ },
201
+ async findOpenByKey(dedupeKey, statuses) {
202
+ for (const record of records.values()) {
203
+ if (record.dedupeKey === dedupeKey && statuses.includes(record.status)) return clone(record);
204
+ }
205
+ return null;
206
+ },
207
+ async list(filter = {}) {
208
+ return [...records.values()]
209
+ .filter((r) => Object.entries(filter).every(([k, v]) => r[k] === v))
210
+ .map(clone);
211
+ },
212
+ size: () => records.size
213
+ };
214
+ }
215
+
216
+ module.exports = { createPendingActions, createMemoryActionStore };