@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/src/agent.js ADDED
@@ -0,0 +1,310 @@
1
+ 'use strict';
2
+ const { randomUUID } = require('node:crypto');
3
+ const { runToolLoop, createToolCaller, toolSpecs, validateNativeTools } = require('@astratra/ai');
4
+ const { normalizeBudget, usageOf, budgetReason } = require('./budget');
5
+ const { createPlanTool } = require('./plan');
6
+ const { summarizeContext } = require('./context');
7
+ const { createMemoryTaskStore } = require('./taskStore');
8
+
9
+ class BudgetStop extends Error {}
10
+ const GUARD_FUNCTIONS = ['newRun', 'input', 'toolResult', 'beforeAction', 'output'];
11
+ const GUARDS_REQUIRED = 'guards required in production: pass guards or guards:false';
12
+ const guardBlocked = (what) => Object.assign(new Error(`${what} blocked by a guard.`), { code: 'GUARD_BLOCKED' });
13
+ class ConfirmationStop extends Error {}
14
+ function abortable(work, signal) {
15
+ if (signal.aborted) return Promise.reject(signal.reason);
16
+ return new Promise((resolve, reject) => {
17
+ const stop = () => reject(signal.reason);
18
+ signal.addEventListener('abort', stop, { once: true });
19
+ Promise.resolve().then(work).then(resolve, reject).finally(() => signal.removeEventListener('abort', stop));
20
+ });
21
+ }
22
+ function createAgent(options = {}) {
23
+ if (typeof options.turn !== 'function') throw new Error('turn is required.');
24
+ const store = options.store || createMemoryTaskStore();
25
+ const budget = normalizeBudget(options.budget);
26
+ const maxRetries = options.maxVerificationRetries ?? 3;
27
+ if (!Number.isInteger(maxRetries) || maxRetries < 0) throw new Error('maxVerificationRetries must be a non-negative integer.');
28
+ const leaseMs = options.leaseMs ?? 30000;
29
+ const finalMs = options.finalMs ?? 30000;
30
+ if (!Number.isFinite(leaseMs) || leaseMs < 30 || !Number.isFinite(finalMs) || finalMs <= 0) throw new Error('Invalid leaseMs or finalMs.');
31
+ validateNativeTools(options.tools || []);
32
+ if ((options.tools || []).some((tool) => tool.name === 'update_plan')) throw new Error('update_plan is reserved.');
33
+ const now = options.now || Date.now;
34
+ // Guards: protected by default. Without a choice, production refuses to start; elsewhere a single warning is sent.
35
+ if (options.guards === undefined && process.env.NODE_ENV === 'production') throw new Error(GUARDS_REQUIRED);
36
+ if (options.guards !== undefined && options.guards !== false && (!options.guards || GUARD_FUNCTIONS.some((name) => typeof options.guards[name] !== 'function'))) throw new Error(`guards must be false or an object from createGuards (${GUARD_FUNCTIONS.join(', ')}).`);
37
+ const guards = options.guards || null;
38
+ const guardMode = (options.tools || []).some((tool) => tool.kind === 'write' || tool.kind === 'confirm') ? 'action' : 'read';
39
+ let warned = false;
40
+ const feedback = options.feedback;
41
+ if (feedback != null && typeof feedback !== 'function' && typeof feedback.feedbackDigest !== 'function' && typeof feedback.digest !== 'function') throw new Error('feedback must be a function or an object with feedbackDigest().');
42
+ const digestOf = feedback && (typeof feedback === 'function' ? feedback : (input) => (feedback.feedbackDigest || feedback.digest).call(feedback, input));
43
+ const emit = async (type, data) => { if (options.onEvent) await options.onEvent({ type, ...JSON.parse(JSON.stringify(data)) }); };
44
+ async function create({ id = randomUUID(), question, messages = [], userId, tenantId }) {
45
+ if (typeof question !== 'string' || !question.trim()) throw new Error('question is required.');
46
+ if (tenantId != null && (typeof tenantId !== 'string' || !tenantId || tenantId.length > 200)) throw new Error('tenantId must be a non-empty string of at most 200 characters.');
47
+ if (userId != null && (typeof userId !== 'string' || !userId || userId.length > 200)) throw new Error('userId must be a non-empty string of at most 200 characters.');
48
+ return store.create({ id, question, ...(userId != null ? { userId } : {}), ...(tenantId != null ? { tenantId } : {}), messages: [...messages, { role: 'user', text: question }], plan: [], state: 'pending', turns: 0, elapsedMs: 0, usage: { inputTokens: 0, outputTokens: 0, cost: 0 }, usageHistory: [], steps: [], pending: null, verificationRetries: 0, verified: false, createdAt: now(), updatedAt: now() });
49
+ }
50
+ async function resume(id, { signal: externalSignal, confirmation } = {}) {
51
+ const owner = randomUUID();
52
+ if (!await store.acquire(id, owner, leaseMs)) throw new Error('Task is missing or already locked.');
53
+ let task;
54
+ let heartbeat;
55
+ let deadline;
56
+ let run;
57
+ let unsubscribe;
58
+ let subscribed = false;
59
+ const guardEvents = [];
60
+ const controller = new globalThis.AbortController();
61
+ const signal = externalSignal ? globalThis.AbortSignal.any([externalSignal, controller.signal]) : controller.signal;
62
+ const began = now();
63
+ let elapsed = 0;
64
+ let queue = Promise.resolve();
65
+ const save = async () => {
66
+ task.elapsedMs = elapsed + Math.max(0, now() - began);
67
+ task.updatedAt = now();
68
+ await store.save(task, owner);
69
+ };
70
+ try {
71
+ task = await store.get(id);
72
+ elapsed = task.elapsedMs;
73
+ if (['completed', 'cancelled'].includes(task.state)) return task;
74
+ if (task.state === 'waiting_confirmation' && !confirmation) return task;
75
+ task.state = 'running';
76
+ await save();
77
+ heartbeat = setInterval(() => {
78
+ store.renew(id, owner, leaseMs).then((ok) => { if (!ok) controller.abort(new Error('Task lock lost.')); }, (error) => controller.abort(error));
79
+ }, Math.max(10, Math.floor(leaseMs / 3)));
80
+ deadline = setTimeout(() => controller.abort(new BudgetStop('time')), Math.max(0, budget.maxMs - task.elapsedMs));
81
+ // Guards: events are relayed through onEvent, the run state is kept in the task.
82
+ const flushGuardEvents = async () => {
83
+ while (guardEvents.length) { const event = { ...guardEvents.shift() }; delete event.type; await emit('guard', { taskId: id, ...event }); }
84
+ };
85
+ const guarded = async (work) => {
86
+ const value = await abortable(work, signal);
87
+ if (!subscribed && value?.event) guardEvents.push(value.event);
88
+ await flushGuardEvents();
89
+ return value;
90
+ };
91
+ const persistGuards = (inputDone = task.guards?.inputDone === true) => {
92
+ task.guards = { version: 1, inputDone, ...(typeof guards.exportRun === 'function' ? { run: guards.exportRun(run) } : {}) };
93
+ };
94
+ const toolContext = (key) => ({ ...(options.context || {}), taskId: id, idempotencyKey: key, ...(guards ? { unmask: (text) => run.unmask(text) } : {}) });
95
+ const tools = [...(options.tools || []), createPlanTool(async (plan) => { signal.throwIfAborted(); task.plan = plan; await save(); await emit('plan', { taskId: id, plan }); })];
96
+ async function execute(call) {
97
+ signal.throwIfAborted();
98
+ task.elapsedMs = elapsed + Math.max(0, now() - began);
99
+ const reason = budgetReason(task, budget);
100
+ if (reason) throw new BudgetStop(reason);
101
+ const index = task.pending.calls.findIndex((item) => item.id === call.id);
102
+ if (task.pending.results[index]) return task.pending.results[index];
103
+ const key = `${id}:${task.pending.step}:${index}`;
104
+ const tool = tools.find((item) => item.name === call.name);
105
+ let result;
106
+ const rejected = () => ({ role: 'tool', toolCallId: call.id, name: call.name, result: { status: 'rejected' } });
107
+ const refused = (verdict) => ({ role: 'tool', toolCallId: call.id, name: call.name, result: { error: `Blocked by a guard: ${verdict.reason || 'refused'}.` } });
108
+ // What the model reads from a tool goes through the guards: masked, and framed as data when the tool is external.
109
+ const finish = async (message) => {
110
+ if (!guards) return message;
111
+ const outcome = await guarded(() => guards.toolResult(message.result, run, { tool: call.name, external: tool?.external === true }));
112
+ persistGuards();
113
+ return { ...message, result: outcome.content };
114
+ };
115
+ const beforeAction = async (humanConfirmed) => {
116
+ const verdict = await guarded(() => guards.beforeAction({ name: call.name, kind: tool.kind, args: call.args }, run, { humanConfirmed }));
117
+ persistGuards();
118
+ return verdict;
119
+ };
120
+ const waitForHuman = async (extra) => {
121
+ task.state = 'waiting_confirmation'; task.confirmation = { key, call, ...extra };
122
+ await save(); await emit('confirmation', { taskId: id, confirmation: task.confirmation });
123
+ throw new ConfirmationStop();
124
+ };
125
+ if (tool?.kind === 'confirm') {
126
+ task.pending.preparations ||= [];
127
+ if (!task.pending.preparations[index]) {
128
+ const prepared = await createToolCaller({ tools: [tool], context: toolContext(key), signal, timeoutMs: options.toolTimeoutMs })(call);
129
+ task.pending.preparations[index] = prepared;
130
+ await save();
131
+ }
132
+ const prepared = task.pending.preparations[index];
133
+ if (prepared.result?.error) {
134
+ const failed = await finish(prepared);
135
+ task.pending.results[index] = failed;
136
+ task.steps.push({ key, call, result: failed });
137
+ await save(); await emit('step', { taskId: id, key, call, result: failed });
138
+ return failed;
139
+ }
140
+ if (!confirmation || confirmation.key !== key) await waitForHuman({ prepared: prepared.result, ...(guards && run.requiresConfirmation ? { guard: { requiresConfirmation: true } } : {}) });
141
+ if (confirmation.approved) {
142
+ // The person's confirmation comes from the application, never from the model.
143
+ const verdict = guards ? await beforeAction(true) : null;
144
+ if (verdict?.decision === 'block') result = refused(verdict);
145
+ else {
146
+ const approved = { ...tool, kind: 'read', run: tool.perform };
147
+ result = await createToolCaller({ tools: [approved], context: toolContext(key), signal, timeoutMs: options.toolTimeoutMs })(call);
148
+ }
149
+ } else result = rejected();
150
+ delete task.confirmation;
151
+ confirmation = undefined;
152
+ } else if (guards && tool?.kind === 'write') {
153
+ // A tool that writes alone: refused after a suspected injection until a person confirms this very call.
154
+ const mine = Boolean(confirmation && confirmation.key === key);
155
+ if (mine && !confirmation.approved) result = rejected();
156
+ else {
157
+ const verdict = await beforeAction(mine && confirmation.approved === true);
158
+ if (verdict.decision === 'block') {
159
+ if (verdict.needsConfirmation) await waitForHuman({ guard: { reason: verdict.reason } });
160
+ result = refused(verdict);
161
+ } else result = await createToolCaller({ tools, context: toolContext(key), signal, timeoutMs: options.toolTimeoutMs })(call);
162
+ }
163
+ if (mine) { delete task.confirmation; confirmation = undefined; }
164
+ } else {
165
+ result = await createToolCaller({ tools, context: toolContext(key), signal, timeoutMs: options.toolTimeoutMs })(call);
166
+ }
167
+ result = await finish(result);
168
+ task.pending.results[index] = result;
169
+ task.steps.push({ key, call, result });
170
+ await save(); await emit('step', { taskId: id, key, call, result });
171
+ return result;
172
+ }
173
+ const callTool = (call) => {
174
+ const next = queue.then(() => execute(call));
175
+ queue = next;
176
+ return next;
177
+ };
178
+ async function model(request, activeSignal = signal, reserve = false, phase = 'execution') {
179
+ activeSignal.throwIfAborted();
180
+ task.elapsedMs = elapsed + Math.max(0, now() - began);
181
+ const reason = budgetReason(task, budget);
182
+ if (!reserve && reason) throw new BudgetStop(reason);
183
+ task.turns += 1;
184
+ await save();
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);
187
+ activeSignal.throwIfAborted();
188
+ const usage = usageOf(request, response, options.pricing);
189
+ for (const field of ['inputTokens', 'outputTokens', 'cost']) task.usage[field] += usage[field];
190
+ task.usageHistory.push({ turn: task.turns, phase, ...usage });
191
+ if (phase === 'execution' && response.toolCalls?.length) {
192
+ const ids = response.toolCalls.map((call) => call.id);
193
+ if (ids.some((value) => typeof value !== 'string' || !value) || new Set(ids).size !== ids.length) throw new Error('Tool calls need unique non-empty ids.');
194
+ task.pending = { step: task.turns, calls: response.toolCalls, results: [] };
195
+ task.messages = JSON.parse(JSON.stringify(task.messages));
196
+ task.messages.push({ role: 'assistant', text: response.text ?? null, toolCalls: response.toolCalls });
197
+ }
198
+ await save(); await emit('usage', { taskId: id, turn: task.turns, phase, usage, total: task.usage });
199
+ return response;
200
+ }
201
+ // The person's recent dislikes, computed once per task and kept so a resumed task sees the same prompt.
202
+ if (digestOf && task.feedbackDigest === undefined && (task.userId || typeof feedback === 'function')) {
203
+ let text = '';
204
+ try { const value = await abortable(() => digestOf({ userId: task.userId, tenantId: task.tenantId, task: JSON.parse(JSON.stringify(task)), signal }), signal); if (typeof value === 'string') text = value.trim().slice(0, 4000); } catch (_error) { signal.throwIfAborted(); }
205
+ task.feedbackDigest = text; await save();
206
+ }
207
+ if (guards) {
208
+ if (typeof guards.subscribe === 'function') { subscribed = true; unsubscribe = guards.subscribe((event) => { if (event.runId === id) guardEvents.push(event); }); }
209
+ run = task.guards?.run && typeof guards.restoreRun === 'function' ? guards.restoreRun(task.guards.run) : guards.newRun({ id, mode: guardMode });
210
+ if (!task.guards?.inputDone) {
211
+ // The question and the earlier messages are masked once, before any model sees them.
212
+ const question = task.messages.at(-1);
213
+ const asked = question?.text === task.question;
214
+ for (const message of task.messages) {
215
+ if (!['user', 'assistant', 'system'].includes(message.role) || typeof message.text !== 'string' || !message.text) continue;
216
+ const out = await guarded(() => guards.input(message.text, run));
217
+ if (out.decision === 'block' || typeof out.text !== 'string') throw guardBlocked('Input');
218
+ message.text = out.text;
219
+ }
220
+ if (asked) task.maskedQuestion = question.text;
221
+ persistGuards(true); await save();
222
+ }
223
+ } else if (options.guards === undefined && !warned) {
224
+ warned = true;
225
+ await emit('warning', { taskId: id, code: 'guards_missing', message: 'No guards: pass guards (createGuards / recommendedGuards from @astratra/ai/guards) or guards:false to silence this.' });
226
+ }
227
+ await emit('run', { taskId: id, runId: id });
228
+ const system = () => `${options.system || ''}${task.feedbackDigest ? `\n${task.feedbackDigest}` : ''}\nTask: ${task.maskedQuestion ?? task.question}\nCurrent plan: ${JSON.stringify(task.plan)}`;
229
+ const summarize = options.summarize || (async ({ messages, plan }) => {
230
+ const response = await model({ system: options.summaryInstruction || 'Summarize the completed work, evidence, constraints and remaining work. Preserve references needed to continue.', messages: [...messages, { role: 'system', text: JSON.stringify(plan) }], tools: [] }, signal, false, 'summary');
231
+ return response.text;
232
+ });
233
+ let text;
234
+ let blocked = false;
235
+ // The reply is unmasked and checked (grounding, leaks, moderation); a blocked reply is never given out.
236
+ const checkOutput = async (raw) => {
237
+ if (!guards) return raw;
238
+ const out = await guarded(() => guards.output(raw, run));
239
+ if (out.decision !== 'allow' || out.degraded.length) task.guard = { decision: out.decision, reasons: out.reasons, degraded: out.degraded, groundingScore: out.groundingScore, unsupportedClaims: out.unsupported.length };
240
+ else delete task.guard;
241
+ if (out.decision === 'block' || typeof out.text !== 'string') { blocked = true; task.stopReason ||= 'guard'; return undefined; }
242
+ return out.text;
243
+ };
244
+ try {
245
+ if (task.pending) {
246
+ const results = [];
247
+ for (const call of task.pending.calls) results.push(await callTool(call));
248
+ task.messages.push(...results); task.pending = null; await save();
249
+ }
250
+ while (true) {
251
+ signal.throwIfAborted();
252
+ if (options.contextSummary && await summarizeContext(task.messages, task.plan, options.contextSummary, (input) => abortable(() => summarize({ ...input, signal }), signal))) {
253
+ await save(); await emit('summary', { taskId: id, messages: task.messages });
254
+ }
255
+ // runToolLoop owns tool dispatch and transcript ordering. The wrapper checkpoints each turn.
256
+ const local = task.messages.map((message) => JSON.parse(JSON.stringify(message)));
257
+ const response = await runToolLoop({ system: system(), messages: local, tools: toolSpecs(tools), maxTurns: Number.MAX_SAFE_INTEGER, maxMs: Number.MAX_SAFE_INTEGER, signal, callTool, turn: async (request) => {
258
+ if (task.pending) { task.messages = request.messages; task.pending = null; await save(); }
259
+ else task.messages = request.messages;
260
+ return model({ ...request, system: system() });
261
+ } });
262
+ task.messages.push({ role: 'assistant', text: response.text }); await save();
263
+ text = await checkOutput(response.text);
264
+ if (blocked) break;
265
+ let verdict = { complete: true };
266
+ if (options.verify) verdict = await abortable(() => options.verify({ task: JSON.parse(JSON.stringify(task)), text, signal }), signal);
267
+ else if (options.verificationInstruction) {
268
+ const checked = await model({ system: `${options.verificationInstruction}\nReturn JSON: {"complete": boolean, "feedback": string}.`, messages: task.messages, tools: [] }, signal, false, 'verification');
269
+ verdict = JSON.parse(checked.text);
270
+ }
271
+ if (typeof verdict === 'boolean') verdict = { complete: verdict };
272
+ if (!verdict || typeof verdict.complete !== 'boolean') throw new Error('Verification must return a boolean or { complete, feedback }.');
273
+ task.verified = verdict.complete; await save(); await emit('verification', { taskId: id, verdict });
274
+ if (verdict.complete) break;
275
+ if (task.verificationRetries >= maxRetries) { task.stopReason = 'verification'; break; }
276
+ task.verificationRetries += 1;
277
+ task.messages.push({ role: 'user', text: verdict.feedback || 'The task is incomplete. Finish the remaining work and verify it.' }); await save();
278
+ }
279
+ } catch (error) {
280
+ if (!(error instanceof BudgetStop)) throw error;
281
+ task.stopReason = error.message;
282
+ clearTimeout(deadline);
283
+ const finalController = new globalThis.AbortController();
284
+ const finalSignal = externalSignal ? globalThis.AbortSignal.any([externalSignal, finalController.signal]) : finalController.signal;
285
+ const timer = setTimeout(() => finalController.abort(new Error('Final response timed out.')), finalMs);
286
+ try {
287
+ const finalMessages = JSON.parse(JSON.stringify(task.messages));
288
+ if (task.pending) finalMessages.push(...task.pending.calls.map((call, index) => task.pending.results[index] || { role: 'tool', toolCallId: call.id, name: call.name, result: { error: 'Not executed: task budget exhausted.' } }));
289
+ const response = await model({ system: `${system()}\n${options.finalInstruction || 'The task budget is exhausted. Give a final answer stating completed work and remaining work accurately.'}`, messages: finalMessages, tools: [] }, finalSignal, true, 'final');
290
+ text = await checkOutput(response.text);
291
+ } finally { clearTimeout(timer); }
292
+ }
293
+ if (!blocked && (typeof text !== 'string' || !text.trim())) throw new Error('The model gave no final text.');
294
+ if (!blocked) task.text = text;
295
+ task.state = blocked ? 'failed' : task.verified || !options.verify && !options.verificationInstruction && !task.stopReason ? 'completed' : 'failed';
296
+ await save(); await emit('final', { taskId: id, runId: id, text, state: task.state, stopReason: task.stopReason, verified: task.verified });
297
+ return task;
298
+ } catch (error) {
299
+ if (error instanceof ConfirmationStop) return task;
300
+ if (task) { task.state = externalSignal?.aborted ? 'cancelled' : 'failed'; task.error = error?.message || 'Task interrupted.'; await save(); }
301
+ throw error;
302
+ } finally {
303
+ clearInterval(heartbeat); clearTimeout(deadline);
304
+ if (unsubscribe) unsubscribe();
305
+ await store.release(id, owner);
306
+ }
307
+ }
308
+ return { store, create, resume, async run(input, execution) { const task = await create(input); return resume(task.id, execution); } };
309
+ }
310
+ module.exports = { createAgent };
package/src/budget.js ADDED
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+
3
+ function estimateTokens(value) {
4
+ return Math.ceil((typeof value === 'string' ? value : JSON.stringify(value ?? '')).length / 4);
5
+ }
6
+ function normalizeBudget(value = {}) {
7
+ const out = { maxMs: 3600000, maxTurns: 1000, ...value };
8
+ for (const key of ['maxMs', 'maxTurns', 'maxTokens', 'maxCost']) {
9
+ if (out[key] !== undefined && (!Number.isFinite(out[key]) || out[key] < 0)) throw new Error(`${key} must be a finite non-negative number.`);
10
+ }
11
+ if (!Number.isInteger(out.maxTurns)) throw new Error('maxTurns must be an integer.');
12
+ return out;
13
+ }
14
+ function usageOf(request, response, pricing = {}) {
15
+ const raw = response?.usage || {};
16
+ const input = raw.inputTokens ?? raw.prompt_tokens;
17
+ const output = raw.outputTokens ?? raw.completion_tokens;
18
+ const valid = (n) => Number.isFinite(n) && n >= 0;
19
+ const inputTokens = valid(input) ? input : estimateTokens(request);
20
+ const outputTokens = valid(output) ? output : estimateTokens(response);
21
+ for (const price of Object.values(pricing)) if (!valid(price)) throw new Error('Prices must be finite non-negative numbers.');
22
+ return { inputTokens, outputTokens, estimated: !valid(input) || !valid(output), cost: valid(raw.cost) ? raw.cost : (inputTokens * (pricing.inputPerMillion || 0) + outputTokens * (pricing.outputPerMillion || 0)) / 1000000 };
23
+ }
24
+ function budgetReason(task, budget) {
25
+ if (task.elapsedMs >= budget.maxMs) return 'time';
26
+ if (task.turns >= budget.maxTurns) return 'turns';
27
+ if (budget.maxTokens !== undefined && task.usage.inputTokens + task.usage.outputTokens >= budget.maxTokens) return 'tokens';
28
+ if (budget.maxCost !== undefined && task.usage.cost >= budget.maxCost) return 'cost';
29
+ return null;
30
+ }
31
+ module.exports = { estimateTokens, normalizeBudget, usageOf, budgetReason };
package/src/context.js ADDED
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+ const { estimateTokens } = require('./budget');
3
+ function contextBoundary(messages, options = {}) {
4
+ const keepLast = options.keepLast ?? 8;
5
+ if (!Number.isInteger(keepLast) || keepLast < 0) throw new Error('keepLast must be a non-negative integer.');
6
+ for (const key of ['maxChars', 'maxTokens']) if (options[key] !== undefined && (!Number.isFinite(options[key]) || options[key] < 0)) throw new Error(`${key} must be non-negative.`);
7
+ const text = JSON.stringify(messages);
8
+ if (!(options.maxChars !== undefined && text.length > options.maxChars) && !(options.maxTokens !== undefined && estimateTokens(text) > options.maxTokens)) return 0;
9
+ let end = Math.max(0, messages.length - keepLast);
10
+ // Keep complete tool exchanges together at the retained boundary.
11
+ while (end > 0 && messages[end]?.role === 'tool') end -= 1;
12
+ return end;
13
+ }
14
+ async function summarizeContext(messages, plan, options, summarize) {
15
+ const end = contextBoundary(messages, options);
16
+ if (!end) return false;
17
+ const summary = await summarize({ messages: messages.slice(0, end), plan });
18
+ if (typeof summary !== 'string' || !summary.trim()) throw new Error('Summary must be non-empty text.');
19
+ messages.splice(0, end, { role: 'system', text: `Context summary:\n${summary}` });
20
+ return true;
21
+ }
22
+ module.exports = { contextBoundary, summarizeContext };
@@ -0,0 +1,79 @@
1
+ export type Rating = 'up' | 'down';
2
+ export type FeedbackReason = 'inaccurate' | 'incomplete' | 'off_topic' | 'wrong_source' | 'too_long' | 'unsafe' | 'other' | (string & {});
3
+ export interface Feedback {
4
+ id: string; tenantId: string | null; userId: string; runId: string; messageId: string | null;
5
+ rating: Rating; reason: FeedbackReason | null; comment: string | null; agent: string | null; mode: string | null;
6
+ createdAt: number; updatedAt: number;
7
+ }
8
+ export interface FeedbackKey { tenantId?: string | null; userId: string; runId: string }
9
+ export interface FeedbackInput extends FeedbackKey {
10
+ rating: Rating; reason?: FeedbackReason | null; comment?: string | null; messageId?: string | null; agent?: string | null; mode?: string | null;
11
+ }
12
+ export interface FeedbackPatch { rating?: Rating; reason?: FeedbackReason | null; comment?: string | null; messageId?: string | null }
13
+ export interface FeedbackFilter {
14
+ /** `undefined` matches every tenant; `null` matches records without one. */
15
+ tenantId?: string | null; userId?: string; runId?: string; rating?: Rating; reason?: string; agent?: string; mode?: string;
16
+ since?: number; until?: number; limit?: number;
17
+ }
18
+ export type FeedbackGroupBy = 'agent' | 'mode' | 'reason' | 'day';
19
+ export interface FeedbackStore {
20
+ put(record: Omit<Feedback, never>): Promise<{ record: Feedback; created: boolean }>;
21
+ get(key: FeedbackKey): Promise<Feedback | null>;
22
+ remove(key: FeedbackKey): Promise<boolean>;
23
+ list(filter?: FeedbackFilter): Promise<Feedback[]>;
24
+ aggregate(filter?: Omit<FeedbackFilter, 'limit' | 'userId' | 'runId' | 'rating' | 'reason'> & { groupBy?: FeedbackGroupBy }): Promise<Array<{ key: string | null; up: number; down: number }>>;
25
+ }
26
+ export interface FeedbackRates { total: number; up: number; down: number; upRate: number | null; downRate: number | null }
27
+ export interface FeedbackStats extends FeedbackRates { groupBy: FeedbackGroupBy | null; groups: Array<FeedbackRates & { key: string }> }
28
+ export type Masker = (text: string) => string | Promise<string>;
29
+ export interface RunSnapshot { question: string; mode?: string; tools?: Array<string | { name: string }>; answer?: string }
30
+ export type RunReader = (input: { runId: string; tenantId: string | null }) => Promise<RunSnapshot | null | undefined> | RunSnapshot | null | undefined;
31
+ export interface FeedbackOptions {
32
+ store: FeedbackStore; reasons?: string[]; maxComment?: number; mask?: Masker; readRun?: RunReader; salt?: string;
33
+ reasonHints?: Record<string, string>; now?(): number; newId?(): string;
34
+ }
35
+ export interface DigestOptions {
36
+ userId: string; tenantId?: string | null; since?: number; limit?: number; maxChars?: number;
37
+ includeNotes?: boolean; maxNotes?: number; noteChars?: number; mask?: Masker;
38
+ }
39
+ export interface ScenarioCandidate {
40
+ id: string; name: string; input: string; question: string; mode: string | null;
41
+ tools: Array<{ name: string }>; expect: { tools: string[]; content: Array<string | RegExp> }; score: null;
42
+ feedback: { rating: Rating; reason: string | null; comment: string | null }; answer?: string;
43
+ }
44
+ export interface ExportOptions {
45
+ rating?: Rating; since?: number; until?: number; tenantId?: string | null; limit?: number;
46
+ mask?: Masker; readRun?: RunReader; salt?: string; includeAnswer?: boolean;
47
+ }
48
+ export interface FeedbackService {
49
+ reasons: readonly string[]; maxComment: number;
50
+ give(input: FeedbackInput): Promise<{ feedback: Feedback; created: boolean }>;
51
+ get(key: FeedbackKey): Promise<Feedback | null>;
52
+ update(key: FeedbackKey, patch: FeedbackPatch): Promise<Feedback>;
53
+ remove(key: FeedbackKey): Promise<boolean>;
54
+ list(filter?: FeedbackFilter): Promise<Feedback[]>;
55
+ stats(filter?: Omit<FeedbackFilter, 'limit' | 'userId' | 'runId' | 'rating' | 'reason'> & { groupBy?: FeedbackGroupBy }): Promise<FeedbackStats>;
56
+ feedbackDigest(options: DigestOptions): Promise<string>;
57
+ digest(options: DigestOptions): Promise<string>;
58
+ exportScenarioCandidates(options?: ExportOptions): Promise<ScenarioCandidate[]>;
59
+ }
60
+ export class FeedbackError extends Error { code: 'invalid' | 'not_found' | 'unauthorized'; status: number }
61
+ export const RATINGS: readonly Rating[];
62
+ export const FEEDBACK_REASONS: readonly string[];
63
+ export function createFeedback(options: FeedbackOptions): FeedbackService;
64
+ export function createMemoryFeedbackStore(): FeedbackStore;
65
+ export interface Queryable { query(sql: string, params?: unknown[]): Promise<{ rows: any[] }> }
66
+ export function createPostgresFeedbackStore(db: Queryable, options?: { table?: string }): FeedbackStore;
67
+ export function postgresFeedbackSchema(options?: { table?: string }): string;
68
+ export function scrubPersonalData(text: string, who?: { userId?: string; tenantId?: string | null }): string;
69
+ export function toAgentScenarios(candidates: ScenarioCandidate[], options?: { fixtures?: Record<string, (args: any, context: any) => unknown> }): Array<{ id: string; question: string; tools: any[]; expect: { tools: string[]; content: Array<string | RegExp> } }>;
70
+ export const REASON_HINTS: Readonly<Record<string, string>>;
71
+ /** Structural express types: no @types/express needed. */
72
+ export interface FeedbackRouterOptions {
73
+ feedback: FeedbackService;
74
+ identify(req: any): { userId: string; tenantId?: string | null } | null | undefined | Promise<{ userId: string; tenantId?: string | null } | null | undefined>;
75
+ /** Return the run only if it belongs to the person; falsy answers 404. May carry `agent` and `mode`. */
76
+ resolveRun(req: any, runId: string, identity: { userId: string; tenantId?: string | null }): Promise<({ agent?: string; mode?: string } & Record<string, unknown>) | null | undefined | false> | ({ agent?: string; mode?: string } & Record<string, unknown>) | null | undefined | false;
77
+ express?: any; maxBodyBytes?: number;
78
+ }
79
+ export function createFeedbackRouter(options: FeedbackRouterOptions): any;
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+ const model = require('./model');
3
+ module.exports = {
4
+ RATINGS: model.RATINGS, FEEDBACK_REASONS: model.FEEDBACK_REASONS, FeedbackError: model.FeedbackError, scrubPersonalData: model.scrubPersonalData,
5
+ createMemoryFeedbackStore: require('./stores').createMemoryFeedbackStore,
6
+ ...require('./postgres'), ...require('./service'), ...require('./router')
7
+ };
@@ -0,0 +1,97 @@
1
+ 'use strict';
2
+ // Modèle commun des retours : constantes, validation stricte, nettoyage des données personnelles.
3
+
4
+ const RATINGS = Object.freeze(['up', 'down']);
5
+ const FEEDBACK_REASONS = Object.freeze(['inaccurate', 'incomplete', 'off_topic', 'wrong_source', 'too_long', 'unsafe', 'other']);
6
+ const REASON_PATTERN = /^[a-z][a-z0-9_]{0,31}$/;
7
+ const TAG_PATTERN = /^[A-Za-z0-9_.:-]{1,64}$/;
8
+ // eslint-disable-next-line no-control-regex -- refusing control characters is the point
9
+ const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f]/;
10
+
11
+ class FeedbackError extends Error {
12
+ constructor(code, message, status) {
13
+ super(message);
14
+ this.name = 'FeedbackError';
15
+ this.code = code;
16
+ this.status = status ?? (code === 'not_found' ? 404 : code === 'unauthorized' ? 401 : 400);
17
+ }
18
+ }
19
+ const invalid = (message) => new FeedbackError('invalid', message);
20
+
21
+ function resolveReasons(extra = []) {
22
+ if (!Array.isArray(extra)) throw new Error('reasons must be an array.');
23
+ for (const reason of extra) if (typeof reason !== 'string' || !REASON_PATTERN.test(reason)) throw new Error(`Invalid reason name: ${String(reason)}.`);
24
+ return Object.freeze([...new Set([...FEEDBACK_REASONS, ...extra])]);
25
+ }
26
+
27
+ function identifier(value, name, { optional = false, max = 200 } = {}) {
28
+ if (value == null || value === '') {
29
+ if (optional) return null;
30
+ throw invalid(`${name} is required.`);
31
+ }
32
+ if (typeof value !== 'string') throw invalid(`${name} must be a string.`);
33
+ const text = value.trim();
34
+ if (!text || text.length > max || CONTROL.test(text) || /[\n\r\t]/.test(text)) throw invalid(`${name} must be 1 to ${max} printable characters.`);
35
+ return text;
36
+ }
37
+
38
+ function tag(value, name) {
39
+ if (value == null || value === '') return null;
40
+ if (typeof value !== 'string' || !TAG_PATTERN.test(value)) throw invalid(`${name} must match ${TAG_PATTERN}.`);
41
+ return value;
42
+ }
43
+
44
+ function commentOf(value, maxComment) {
45
+ if (value == null) return null;
46
+ if (typeof value !== 'string') throw invalid('comment must be a string.');
47
+ if (CONTROL.test(value)) throw invalid('comment contains control characters.');
48
+ const text = value.trim();
49
+ if (text.length > maxComment) throw invalid(`comment is limited to ${maxComment} characters.`);
50
+ return text || null;
51
+ }
52
+
53
+ /** Checks one feedback; returns the normalized fields (never partial). */
54
+ function normalizeFeedback(input, { reasons, maxComment }) {
55
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw invalid('Feedback must be an object.');
56
+ if (!RATINGS.includes(input.rating)) throw invalid("rating must be 'up' or 'down'.");
57
+ let reason = input.reason ?? null;
58
+ if (reason !== null) {
59
+ if (input.rating !== 'down') throw invalid("reason is only allowed with rating 'down'.");
60
+ if (typeof reason !== 'string' || !reasons.includes(reason)) throw invalid('Unknown reason.');
61
+ }
62
+ return {
63
+ tenantId: identifier(input.tenantId, 'tenantId', { optional: true }),
64
+ userId: identifier(input.userId, 'userId'),
65
+ runId: identifier(input.runId, 'runId'),
66
+ messageId: identifier(input.messageId, 'messageId', { optional: true }),
67
+ rating: input.rating,
68
+ reason,
69
+ comment: commentOf(input.comment, maxComment),
70
+ agent: tag(input.agent, 'agent'),
71
+ mode: tag(input.mode, 'mode')
72
+ };
73
+ }
74
+
75
+ function keyOf(input) {
76
+ return { tenantId: identifier(input?.tenantId, 'tenantId', { optional: true }), userId: identifier(input?.userId, 'userId'), runId: identifier(input?.runId, 'runId') };
77
+ }
78
+
79
+ /** Removes what identifies a person even if the injected masker missed it. */
80
+ function scrubPersonalData(text, { userId, tenantId } = {}) {
81
+ if (typeof text !== 'string') return '';
82
+ let out = text;
83
+ for (const secret of [userId, tenantId]) if (typeof secret === 'string' && secret.length >= 3) out = out.split(secret).join('[user]');
84
+ return out
85
+ .replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, '[email]')
86
+ .replace(/https?:\/\/\S+/gi, '[link]')
87
+ .replace(/(?:\+|\b)\d[\d\s().-]{6,}\d/g, '[number]');
88
+ }
89
+
90
+ function boundText(text, max) {
91
+ if (text.length <= max) return text;
92
+ const cut = text.slice(0, max);
93
+ const blank = cut.search(/\s\S*$/);
94
+ return `${(blank > 0 ? cut.slice(0, blank) : cut).trimEnd()}…`;
95
+ }
96
+
97
+ module.exports = { RATINGS, FEEDBACK_REASONS, FeedbackError, resolveReasons, normalizeFeedback, keyOf, identifier, scrubPersonalData, boundText };
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+ const { GROUPS } = require('./stores');
3
+
4
+ function tableOf(options = {}) {
5
+ const name = options.table ?? 'astratra_agent_feedback';
6
+ if (typeof name !== 'string' || !/^[a-zA-Z_][a-zA-Z0-9_]{0,47}$/.test(name)) throw new Error('table must be a plain SQL identifier of at most 48 characters.');
7
+ return name;
8
+ }
9
+ function postgresFeedbackSchema(options) {
10
+ const name = tableOf(options);
11
+ return `CREATE TABLE IF NOT EXISTS "${name}" (
12
+ id text PRIMARY KEY,
13
+ tenant_id text NOT NULL DEFAULT '',
14
+ user_id text NOT NULL,
15
+ run_id text NOT NULL,
16
+ message_id text,
17
+ rating text NOT NULL CHECK (rating IN ('up', 'down')),
18
+ reason text,
19
+ comment text,
20
+ agent text,
21
+ mode text,
22
+ created_at timestamptz NOT NULL,
23
+ updated_at timestamptz NOT NULL,
24
+ UNIQUE (tenant_id, user_id, run_id)
25
+ );
26
+ CREATE INDEX IF NOT EXISTS "${name}_user_idx" ON "${name}" (user_id, updated_at DESC);
27
+ CREATE INDEX IF NOT EXISTS "${name}_updated_idx" ON "${name}" (updated_at DESC);`;
28
+ }
29
+ const COLUMNS = `id, tenant_id, user_id, run_id, message_id, rating, reason, comment, agent, mode,
30
+ (extract(epoch from created_at) * 1000)::float8 AS created_ms, (extract(epoch from updated_at) * 1000)::float8 AS updated_ms`;
31
+ const read = (row) => row ? ({ id: row.id, tenantId: row.tenant_id || null, userId: row.user_id, runId: row.run_id, messageId: row.message_id, rating: row.rating, reason: row.reason, comment: row.comment, agent: row.agent, mode: row.mode, createdAt: Math.round(Number(row.created_ms)), updatedAt: Math.round(Number(row.updated_ms)) }) : null;
32
+
33
+ function where(filter, params) {
34
+ const parts = [];
35
+ const add = (sql, value) => { params.push(value); parts.push(sql.replace('?', `$${params.length}`)); };
36
+ if (filter.tenantId !== undefined) add('tenant_id = ?', filter.tenantId ?? '');
37
+ for (const [field, column] of [['userId', 'user_id'], ['runId', 'run_id'], ['rating', 'rating'], ['reason', 'reason'], ['agent', 'agent'], ['mode', 'mode']]) if (filter[field] != null) add(`${column} = ?`, filter[field]);
38
+ if (filter.since != null) add('updated_at >= to_timestamp(?::double precision / 1000)', filter.since);
39
+ if (filter.until != null) add('updated_at < to_timestamp(?::double precision / 1000)', filter.until);
40
+ return parts.length ? ` WHERE ${parts.join(' AND ')}` : '';
41
+ }
42
+
43
+ /** PostgreSQL store; `db` is any `{ query(sql, params) }`. Every value is a SQL parameter. */
44
+ function createPostgresFeedbackStore(db, options) {
45
+ if (!db || typeof db.query !== 'function') throw new Error('A database with query(sql, params) is required.');
46
+ const table = `"${tableOf(options)}"`;
47
+ return {
48
+ async put(r) {
49
+ const result = await db.query(
50
+ `INSERT INTO ${table} (id, tenant_id, user_id, run_id, message_id, rating, reason, comment, agent, mode, created_at, updated_at)
51
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, to_timestamp($11::double precision / 1000), to_timestamp($12::double precision / 1000))
52
+ ON CONFLICT (tenant_id, user_id, run_id) DO UPDATE SET message_id = EXCLUDED.message_id, rating = EXCLUDED.rating, reason = EXCLUDED.reason,
53
+ comment = EXCLUDED.comment, agent = EXCLUDED.agent, mode = EXCLUDED.mode, updated_at = EXCLUDED.updated_at
54
+ RETURNING ${COLUMNS}, (xmax = 0) AS inserted`,
55
+ [r.id, r.tenantId ?? '', r.userId, r.runId, r.messageId, r.rating, r.reason, r.comment, r.agent, r.mode, r.createdAt, r.updatedAt]);
56
+ return { record: read(result.rows[0]), created: Boolean(result.rows[0].inserted) };
57
+ },
58
+ async get(key) {
59
+ return read((await db.query(`SELECT ${COLUMNS} FROM ${table} WHERE tenant_id = $1 AND user_id = $2 AND run_id = $3`, [key.tenantId ?? '', key.userId, key.runId])).rows[0]);
60
+ },
61
+ async remove(key) {
62
+ return (await db.query(`DELETE FROM ${table} WHERE tenant_id = $1 AND user_id = $2 AND run_id = $3 RETURNING id`, [key.tenantId ?? '', key.userId, key.runId])).rows.length > 0;
63
+ },
64
+ async list(filter = {}) {
65
+ const params = [];
66
+ const clause = where(filter, params);
67
+ params.push(Math.min(Math.max(Number(filter.limit) || 100, 1), 1000));
68
+ return (await db.query(`SELECT ${COLUMNS} FROM ${table}${clause} ORDER BY updated_at DESC, id ASC LIMIT $${params.length}`, params)).rows.map(read);
69
+ },
70
+ async aggregate(filter = {}) {
71
+ if (filter.groupBy != null && !GROUPS.includes(filter.groupBy)) throw new Error('Unknown groupBy.');
72
+ const expression = { agent: 'agent', mode: 'mode', reason: 'reason', day: `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD')` }[filter.groupBy] || 'NULL::text';
73
+ const params = [];
74
+ let clause = where(filter, params);
75
+ if (filter.groupBy === 'reason') clause += `${clause ? ' AND' : ' WHERE'} rating = 'down'`;
76
+ const rows = (await db.query(`SELECT ${expression} AS key, count(*) FILTER (WHERE rating = 'up') AS up, count(*) FILTER (WHERE rating = 'down') AS down FROM ${table}${clause} GROUP BY 1 ORDER BY 1`, params)).rows;
77
+ return rows.map((row) => ({ key: row.key, up: Number(row.up), down: Number(row.down) }));
78
+ }
79
+ };
80
+ }
81
+ module.exports = { postgresFeedbackSchema, createPostgresFeedbackStore };