@astratra/conscience 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.fr.md CHANGED
@@ -141,6 +141,83 @@ Changements réversibles ci-dessous).
141
141
  constat) est écrite au journal d'audit avant d'être rendue :
142
142
  `listAudit({ organisationId })`.
143
143
 
144
+ ### Politique d'outils, budget calendaire, arrêt d'urgence des outils (1.3.0)
145
+
146
+ Le reste du gouverneur décide des changements qu'un agent propose pour
147
+ lui-même. `createToolPolicy` décide d'**un appel d'un outil**, par code, hors
148
+ de tout modèle. Il ne sait pas ce que fait un outil : familles, niveaux,
149
+ plafonds et chaque mot rendu viennent de votre configuration.
150
+
151
+ ```js
152
+ const { createToolPolicy, createPostgresGovernorStore, createPostgresToolBudgetStore,
153
+ postgresToolBudgetSchema } = require('@astratra/conscience/governor');
154
+
155
+ await pool.query(postgresToolBudgetSchema()); // une fois, idempotent
156
+ const policy = createToolPolicy({
157
+ store: createPostgresGovernorStore(pool), // journal d'audit + interrupteur
158
+ tools: [
159
+ { name: 'lire_elements', family: 'catalogue', level: 'read', maxPerRun: 5 },
160
+ { name: 'modifier_element', family: 'catalogue', level: 'controlled',
161
+ validate: (input) => Number.isInteger(input?.amount),
162
+ overThreshold: (input, settings) => input.amount > settings.maxAmount },
163
+ { name: 'supprimer_element', family: 'catalogue', level: 'sensitive' }
164
+ ],
165
+ // Lu avant CHAQUE appel (une ligne en base, un tableau de bord...). S'il échoue, l'appel est refusé.
166
+ settings: async ({ organisationId }) => ({ enabled: true, families: { catalogue: true }, budgetLimit: 15000, maxCallsPerRun: 12, maxAmount: 500 }),
167
+ budget: { period: 'month', timeZone: 'Europe/Paris', store: createPostgresToolBudgetStore(pool) },
168
+ emergency: { activateRoles: ['owner', 'support'], releaseRoles: ['owner'] }
169
+ });
170
+
171
+ const run = policy.createRun(); // compteurs d'une conversation / d'une tâche
172
+ const decision = await policy.decide({ tool: 'modifier_element', input: { amount: 40 }, run, actor: { kind: 'model', id: 'assistant' } });
173
+ // { allowed, decision: 'allowed' | 'pending' | 'refused', code, level, input, budget, auditId, ... }
174
+
175
+ const done = await policy.execute({ tool: 'lire_elements', input: {}, run }, (input, { signal }) => lireElements(input, { signal }));
176
+ // N'exécute que si l'appel est autorisé. done.executed, done.result, done.interrupted.
177
+ await policy.recordSpend({ id: 'appel-42', amount: 120 }); // unités entières (centimes), idempotent par id
178
+ ```
179
+
180
+ - **Niveaux** (`TOOL_LEVELS`) : `read` s'exécute ; `controlled` s'exécute sauf au-delà
181
+ de son `overThreshold(input, settings)` ou si le tour a lu un contenu non fiable
182
+ (`run.markUntrusted()` ou `untrusted: true` sur l'appel) : il est alors `pending` ;
183
+ `sensitive` est toujours `pending`. La politique n'exécute jamais un appel en attente :
184
+ l'application le garde et une personne décide.
185
+ - **Codes de refus** (`TOOL_REASONS`) : `emergency_stop`, `disabled`, `unknown_tool`,
186
+ `family_disabled`, `invalid_input`, `budget_exceeded`, `cap_reached` (appels par tour
187
+ ou `maxPerRun` de l'outil), et `settings_unavailable` quand les réglages, l'interrupteur
188
+ ou le budget sont illisibles. Codes d'attente : `sensitive_tool`, `untrusted_context`,
189
+ `over_threshold`. Ordre : arrêt, désactivé, inconnu, famille, entrée, budget, plafonds,
190
+ niveau. Les appels demandés ensemble sont comptés tout de suite : ils ne passent pas
191
+ tous sous un plafond.
192
+ - **Vos mots** : `labels: { levels, decisions, codes }` renomme ce que vous recevez
193
+ (`{ decisions: { pending: 'en_attente' } }`) ; les outils déclarent alors leur niveau
194
+ avec votre mot.
195
+ - **Budget calendaire** (`createCalendarBudget`, utilisable seul) : consommation comptée
196
+ par `'month'` ou `'day'` (ou votre fonction) d'un fuseau horaire (`calendarPeriodKey`),
197
+ plafond et montants en unités entières, jamais en flottants (prenez une unité plus
198
+ petite pour les fractions de centime). `check()` est lu avant chaque appel et teste
199
+ aussi le `estimatedCost` de l'outil ; une consommation tombe dans la période de son
200
+ propre instant : un appel à 23 h 30 le 31 octobre à Paris compte pour octobre là-bas
201
+ et pour novembre en UTC. Magasins : mémoire (`createMemoryToolBudgetStore`),
202
+ PostgreSQL (`createPostgresToolBudgetStore` : une seule requête atomique et
203
+ idempotente, bigint), ou le vôtre `{ getSpent(scope, period), addSpend({ scope,
204
+ period, id, amount, at }) }` (idempotent par id). La portée est `organisationId`
205
+ par défaut. Le plafond est atteint quand `spent >= limit` ; la mesure se faisant après
206
+ l'appel, le dernier appel peut le dépasser.
207
+ - **Arrêt d'urgence** : `halt({ by, reason, organisationId? })` est lu avant chaque
208
+ appel et pendant l'exécution d'un outil. `execute()` donne à l'outil un `AbortSignal`
209
+ qui s'annule aussitôt pour un arrêt dans ce processus, et sous `pollMs` (1 s par défaut)
210
+ pour un arrêt tiré par un autre processus ; l'appel est aussi abandonné si l'outil
211
+ ignore le signal (`interrupted: true`). `activateRoles` le tirent (par défaut : toute
212
+ personne identifiée), `releaseRoles` le lèvent (par défaut : tout humain ; un acteur
213
+ `model` ou `engine` jamais). L'option `governor` fait aussi arrêter les outils par
214
+ l'interrupteur du gouverneur.
215
+ - **Audit** : chaque décision est écrite dans le journal du gouverneur avant d'être
216
+ rendue (`tool_decision` : qui, outil, famille, niveau, décision, motifs, empreinte de
217
+ l'entrée, jamais l'entrée brute), plus `tool_outcome`, `tool_halt`, `tool_resume` et
218
+ leurs refus. Si le journal ne peut pas être écrit, l'appel ne s'exécute pas.
219
+ `onEvent` reçoit les mêmes enregistrements.
220
+
144
221
  ### Approbations (matrice, double approbation, expiration)
145
222
 
146
223
  L'approbation est décidée par la politique, pas par celui qui propose :
@@ -403,6 +480,7 @@ vérifié.
403
480
  ```js
404
481
  postgresConscienceSchema({ prefix: 'astratra_conscience' }) // table <prefix>_records
405
482
  postgresGovernorSchema({ prefix: 'astratra_governor' }) // <prefix>_proposals, _audit, _spend, _controls, _objects, _versions, _findings
483
+ postgresToolBudgetSchema({ prefix: 'astratra_tools' }) // <prefix>_budget_totals, _budget_entries (tool budget, 1.3.0)
406
484
  ```
407
485
 
408
486
  ### Écrire son propre magasin (MongoDB, ...)
package/README.md CHANGED
@@ -135,6 +135,83 @@ by itself (see Approvals and Reversible changes below).
135
135
  resume, register, stage, deploy, promote, rollback, finding) is written to the audit journal before it is returned:
136
136
  `listAudit({ organisationId })`.
137
137
 
138
+ ### Tool policy, calendar budget, tool kill switch (1.3.0)
139
+
140
+ The rest of the governor decides about changes an agent proposes to itself.
141
+ `createToolPolicy` decides about **one call of one tool**, by code, outside any
142
+ model. It knows nothing about what a tool does: families, levels, caps and
143
+ every word it returns come from your configuration.
144
+
145
+ ```js
146
+ const { createToolPolicy, createPostgresGovernorStore, createPostgresToolBudgetStore,
147
+ postgresToolBudgetSchema } = require('@astratra/conscience/governor');
148
+
149
+ await pool.query(postgresToolBudgetSchema()); // once, idempotent
150
+ const policy = createToolPolicy({
151
+ store: createPostgresGovernorStore(pool), // audit journal + kill switch
152
+ tools: [
153
+ { name: 'read_items', family: 'catalogue', level: 'read', maxPerRun: 5 },
154
+ { name: 'update_item', family: 'catalogue', level: 'controlled',
155
+ validate: (input) => Number.isInteger(input?.amount),
156
+ overThreshold: (input, settings) => input.amount > settings.maxAmount },
157
+ { name: 'delete_item', family: 'catalogue', level: 'sensitive' }
158
+ ],
159
+ // Read before EVERY call (a database row, a dashboard...). If it throws, the call is refused.
160
+ settings: async ({ organisationId }) => ({ enabled: true, families: { catalogue: true }, budgetLimit: 15000, maxCallsPerRun: 12, maxAmount: 500 }),
161
+ budget: { period: 'month', timeZone: 'Europe/Paris', store: createPostgresToolBudgetStore(pool) },
162
+ emergency: { activateRoles: ['owner', 'support'], releaseRoles: ['owner'] }
163
+ });
164
+
165
+ const run = policy.createRun(); // counters of one conversation / task
166
+ const decision = await policy.decide({ tool: 'update_item', input: { amount: 40 }, run, actor: { kind: 'model', id: 'assistant' } });
167
+ // { allowed, decision: 'allowed' | 'pending' | 'refused', code, level, input, budget, auditId, ... }
168
+
169
+ const done = await policy.execute({ tool: 'read_items', input: {}, run }, (input, { signal }) => fetchItems(input, { signal }));
170
+ // Runs only when allowed. done.executed, done.result, done.interrupted.
171
+ await policy.recordSpend({ id: 'call-42', amount: 120 }); // whole units (cents), idempotent by id
172
+ ```
173
+
174
+ - **Levels** (`TOOL_LEVELS`): `read` runs; `controlled` runs unless it is over its
175
+ own `overThreshold(input, settings)`, or the run read untrusted content
176
+ (`run.markUntrusted()` or `untrusted: true` on the call), then it is `pending`;
177
+ `sensitive` is always `pending`. The policy never runs a pending call: the
178
+ application keeps it and a person decides.
179
+ - **Refusal codes** (`TOOL_REASONS`): `emergency_stop`, `disabled`,
180
+ `unknown_tool`, `family_disabled`, `invalid_input`, `budget_exceeded`,
181
+ `cap_reached` (calls per run, or `maxPerRun` of the tool), and
182
+ `settings_unavailable` when settings, kill switch or budget cannot be read.
183
+ Pending codes: `sensitive_tool`, `untrusted_context`, `over_threshold`.
184
+ Order: stop, disabled, unknown, family, input, budget, caps, level. Calls asked
185
+ together are counted at once, so they cannot all slip under a cap.
186
+ - **Your words**: `labels: { levels, decisions, codes }` renames what you get
187
+ back (`{ decisions: { pending: 'en_attente' } }`); tools then declare their
188
+ level in your word.
189
+ - **Calendar budget** (`createCalendarBudget`, also usable alone): consumption
190
+ counted per `'month'` or `'day'` (or your own function) of a time zone
191
+ (`calendarPeriodKey`), cap and amounts are whole units, never floats (use a
192
+ smaller unit for fractions of a cent). `check()` runs before each call and
193
+ also tests the tool's `estimatedCost`; a consumption lands in the period of
194
+ its own instant, so a call at 23:30 on 31 October in Paris counts for
195
+ October there and for November in UTC. Stores: memory
196
+ (`createMemoryToolBudgetStore`), PostgreSQL (`createPostgresToolBudgetStore`:
197
+ one atomic, idempotent statement, bigint), or your own `{ getSpent(scope,
198
+ period), addSpend({ scope, period, id, amount, at }) }` (idempotent by id).
199
+ The scope is `organisationId` by default. The cap is reached when
200
+ `spent >= limit`; with the measure after the call, the last call may pass it.
201
+ - **Emergency stop**: `halt({ by, reason, organisationId? })` is read before
202
+ each call and while a tool runs. `execute()` gives the tool an `AbortSignal`
203
+ that aborts at once on a stop in this process, and within `pollMs` (default
204
+ 1 s) on a stop pulled by another process; the call is also abandoned if the
205
+ tool ignores the signal (`interrupted: true`). `activateRoles` pull it
206
+ (default: anyone with an id), `releaseRoles` lift it (default: any human; a
207
+ `model` or `engine` actor never can). A `governor` option makes the governor
208
+ kill switch stop the tools too.
209
+ - **Audit**: every decision is written to the governor journal before it is
210
+ returned (`tool_decision`: who, tool, family, level, decision, reasons, input
211
+ fingerprint, never the raw input), plus `tool_outcome`, `tool_halt`,
212
+ `tool_resume` and their refusals. If the journal cannot be written the call
213
+ does not run. `onEvent` receives the same records.
214
+
138
215
  ### Approvals (matrix, double approval, expiry)
139
216
 
140
217
  Approval is decided by the policy, not by whoever proposes:
@@ -384,6 +461,7 @@ uses parameters only; the table prefix is a checked identifier.
384
461
  ```js
385
462
  postgresConscienceSchema({ prefix: 'astratra_conscience' }) // table <prefix>_records
386
463
  postgresGovernorSchema({ prefix: 'astratra_governor' }) // <prefix>_proposals, _audit, _spend, _controls, _objects, _versions, _findings
464
+ postgresToolBudgetSchema({ prefix: 'astratra_tools' }) // <prefix>_budget_totals, _budget_entries (tool budget, 1.3.0)
387
465
  ```
388
466
 
389
467
  ### Writing your own store (MongoDB, ...)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/conscience",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Documented memory of an AI agent's decisions (outcomes, corrections, lessons with evidence, self-model, lineage, erasure) under a deterministic governor with no language model: constitution, permissions, budgets, isolation, kill switch, human approval.",
5
5
  "engines": {
6
6
  "node": ">=20"
@@ -0,0 +1,101 @@
1
+ 'use strict';
2
+ const { GovernorError, isNonEmptyString } = require('./util');
3
+
4
+ /*
5
+ * Calendar budget: consumption counted per calendar period (day or month) in a
6
+ * given time zone, with a cap in whole units of your choice (cents, tokens...).
7
+ * No floating point money: amounts and caps are safe integers.
8
+ */
9
+
10
+ const PERIODS = Object.freeze(['day', 'month']);
11
+ const formatters = new Map();
12
+
13
+ function formatterFor(timeZone) {
14
+ let formatter = formatters.get(timeZone);
15
+ if (!formatter) {
16
+ try { formatter = new Intl.DateTimeFormat('en-US', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }); } catch (_error) {
17
+ throw new GovernorError('budget_invalid', `Unknown time zone: ${timeZone}.`);
18
+ }
19
+ formatters.set(timeZone, formatter);
20
+ }
21
+ return formatter;
22
+ }
23
+
24
+ /**
25
+ * The calendar period of an instant, in a time zone: "2026-10" (month) or
26
+ * "2026-10-31" (day). `period` may also be a function (instant, timeZone) => key.
27
+ */
28
+ function calendarPeriodKey(at, { period = 'month', timeZone = 'UTC' } = {}) {
29
+ const date = new Date(at instanceof Date ? at.getTime() : at);
30
+ if (Number.isNaN(date.getTime())) throw new GovernorError('budget_invalid', 'The instant of a budget period must be a valid date.');
31
+ if (typeof period === 'function') {
32
+ const key = period(date, timeZone);
33
+ if (!isNonEmptyString(key)) throw new GovernorError('budget_invalid', 'A custom period must return a non-empty string.');
34
+ return key;
35
+ }
36
+ if (!PERIODS.includes(period)) throw new GovernorError('budget_invalid', `period must be ${PERIODS.join(' or ')} or a function.`);
37
+ const parts = Object.fromEntries(formatterFor(timeZone).formatToParts(date).map((part) => [part.type, part.value]));
38
+ return period === 'month' ? `${parts.year}-${parts.month}` : `${parts.year}-${parts.month}-${parts.day}`;
39
+ }
40
+
41
+ const isAmount = (value) => Number.isSafeInteger(value) && value >= 0;
42
+
43
+ /** Budget store kept in memory: lost when the process exits. */
44
+ function createMemoryToolBudgetStore() {
45
+ const totals = new Map();
46
+ const entries = new Set();
47
+ const totalKey = (scope, period) => `${scope}\u0000${period}`;
48
+ return {
49
+ async getSpent(scope, period) { return totals.get(totalKey(scope, period)) ?? 0; },
50
+ /** Idempotent on (scope, id): a replay adds nothing. */
51
+ async addSpend({ scope, period, id, amount }) {
52
+ const entry = `${scope}\u0000${id}`;
53
+ const key = totalKey(scope, period);
54
+ if (entries.has(entry)) return { added: false, spent: totals.get(key) ?? 0 };
55
+ entries.add(entry);
56
+ totals.set(key, (totals.get(key) ?? 0) + amount);
57
+ return { added: true, spent: totals.get(key) };
58
+ }
59
+ };
60
+ }
61
+
62
+ /**
63
+ * Calendar budget over a store { getSpent(scope, period), addSpend({ scope,
64
+ * period, id, amount, at }) }. `limit` is the default cap; a call may pass its own.
65
+ */
66
+ function createCalendarBudget(options = {}) {
67
+ const { period = 'month', timeZone = 'UTC', scope: defaultScope = 'default', limit: defaultLimit } = options;
68
+ const store = options.store ?? createMemoryToolBudgetStore();
69
+ for (const method of ['getSpent', 'addSpend']) {
70
+ if (typeof store[method] !== 'function') throw new GovernorError('budget_invalid', `The budget store is missing ${method}().`);
71
+ }
72
+ if (defaultLimit !== undefined && defaultLimit !== null && !isAmount(defaultLimit)) throw new GovernorError('budget_invalid', 'limit must be an integer >= 0.');
73
+ const now = options.now ?? Date.now;
74
+ calendarPeriodKey(now(), { period, timeZone }); // fails now, not at the first call, on a wrong period or time zone
75
+
76
+ const keyOf = (at) => calendarPeriodKey(at ?? now(), { period, timeZone });
77
+
78
+ /** Where the budget stands, and whether a call of `estimate` units still fits. Read before each call. */
79
+ async function check({ scope = defaultScope, limit = defaultLimit, estimate = 0, at } = {}) {
80
+ if (limit !== undefined && limit !== null && !isAmount(limit)) throw new GovernorError('budget_invalid', 'limit must be an integer >= 0.');
81
+ if (!isAmount(estimate)) throw new GovernorError('budget_invalid', 'estimate must be an integer >= 0.');
82
+ const key = keyOf(at);
83
+ const spent = await store.getSpent(scope, key);
84
+ if (limit === undefined || limit === null) return { allowed: true, exceeded: false, scope, period: key, spent, limit: null, remaining: null };
85
+ return { allowed: spent < limit && spent + estimate <= limit, exceeded: spent >= limit, scope, period: key, spent, limit, remaining: Math.max(0, limit - spent) };
86
+ }
87
+
88
+ /** Counts a consumption in the period of its instant. `id` makes the call safe to repeat. */
89
+ async function record({ scope = defaultScope, amount, id, at } = {}) {
90
+ if (!isAmount(amount)) throw new GovernorError('budget_invalid', 'amount must be an integer >= 0 (whole units, no fractions).');
91
+ if (!isNonEmptyString(id)) throw new GovernorError('budget_invalid', 'A consumption needs a stable id (idempotency).');
92
+ const instant = at ?? now();
93
+ const key = keyOf(instant);
94
+ const result = await store.addSpend({ scope, period: key, id, amount, at: new Date(instant).toISOString() });
95
+ return { added: result.added, scope, period: key, spent: result.spent };
96
+ }
97
+
98
+ return Object.freeze({ check, record, periodKey: keyOf, period: typeof period === 'function' ? 'custom' : period, timeZone });
99
+ }
100
+
101
+ module.exports = { PERIODS, calendarPeriodKey, createMemoryToolBudgetStore, createCalendarBudget, isAmount };
@@ -111,7 +111,7 @@ export interface ChangeProposal {
111
111
 
112
112
  export interface AuditEntry {
113
113
  id: string; at: string; policyVersion: string; organisationId: string | null; proposalId: string | null;
114
- action: 'evaluate' | 'approve' | 'decline' | 'approval_expired' | 'expire' | 'halt' | 'resume' | 'spend' | 'spend_refused' | 'register' | 'stage' | 'deploy' | 'promote' | 'rollback' | 'emergency_revert' | 'finding';
114
+ action: 'evaluate' | 'approve' | 'decline' | 'approval_expired' | 'expire' | 'halt' | 'resume' | 'spend' | 'spend_refused' | 'register' | 'stage' | 'deploy' | 'promote' | 'rollback' | 'emergency_revert' | 'finding' | ToolAuditAction;
115
115
  decision: string; reasons: string[]; actor: Actor | null; [key: string]: unknown;
116
116
  }
117
117
 
@@ -391,3 +391,172 @@ export interface MongoStoreOptions { prefix?: string; client?: MongoSessionClien
391
391
  /** Requires a replica set or sharded cluster for atomic spending. */
392
392
  export function createMongoGovernorStore(db: MongoDatabase, options?: MongoStoreOptions): GovernorStore;
393
393
  export function mongoGovernorIndexes(db: MongoDatabase, options?: { prefix?: string }): Promise<void>;
394
+
395
+ /* ---- Tool policy and calendar budget (generic: families, levels, caps and vocabulary are yours) ---- */
396
+
397
+ export type ToolAuditAction = 'tool_decision' | 'tool_outcome' | 'tool_halt' | 'tool_halt_denied' | 'tool_resume' | 'tool_resume_denied';
398
+ export const TOOL_LEVELS: { readonly READ: 'read'; readonly CONTROLLED: 'controlled'; readonly SENSITIVE: 'sensitive' };
399
+ export const TOOL_DECISIONS: { readonly ALLOWED: 'allowed'; readonly PENDING: 'pending'; readonly REFUSED: 'refused' };
400
+ export const TOOL_REASONS: {
401
+ readonly HALTED: 'emergency_stop'; readonly DISABLED: 'disabled'; readonly UNAVAILABLE: 'settings_unavailable'; readonly UNKNOWN_TOOL: 'unknown_tool';
402
+ readonly FAMILY_DISABLED: 'family_disabled'; readonly INVALID_INPUT: 'invalid_input'; readonly BUDGET: 'budget_exceeded'; readonly CAP: 'cap_reached';
403
+ readonly SENSITIVE: 'sensitive_tool'; readonly UNTRUSTED: 'untrusted_context'; readonly THRESHOLD: 'over_threshold';
404
+ };
405
+ export type ToolLevel = 'read' | 'controlled' | 'sensitive';
406
+ export type ToolDecisionWord = 'allowed' | 'pending' | 'refused';
407
+ export type ToolReasonCode = typeof TOOL_REASONS[keyof typeof TOOL_REASONS];
408
+
409
+ /** An actor of a tool call or of the kill switch. `roles` are checked against emergency.activateRoles / releaseRoles. */
410
+ export interface ToolActor { kind: string; id: string; roles?: string[] }
411
+
412
+ export interface ToolDefinition {
413
+ /** Letters, digits, _ . : - ; starts with a letter. */
414
+ name: string;
415
+ family: string;
416
+ /** One of the level words (the canonical ones, or yours when labels.levels renames them). */
417
+ level: string;
418
+ /** Returns false, { ok: false }, or { ok: true, value } (the value replaces the input). May throw: invalid. */
419
+ validate?(input: any): boolean | { ok: boolean; value?: unknown };
420
+ /** Controlled tools only: true sends the call to a person (an amount over your own threshold, for instance). Throwing counts as true. */
421
+ overThreshold?(input: any, settings: ToolSettings): boolean;
422
+ /** At most this many calls of the tool in one run; the next ones are refused (cap_reached). */
423
+ maxPerRun?: number;
424
+ /** Whole units this call is expected to consume: refused up front when it cannot fit in the budget. */
425
+ estimatedCost?: number;
426
+ /** Stays callable when the budget is exhausted (read-only state, for instance). */
427
+ budgetExempt?: boolean;
428
+ }
429
+
430
+ /** Settings read before EACH call; anything else you put in is handed back to your validate and overThreshold functions. */
431
+ export interface ToolSettings {
432
+ /** false: every call is refused (disabled). */
433
+ enabled?: boolean;
434
+ /** family -> on/off. A family that is not listed is on. */
435
+ families?: Record<string, boolean>;
436
+ /** Cap of the calendar budget, whole units. Overrides the default limit of the budget. */
437
+ budgetLimit?: number | null;
438
+ /** Calls of all tools in one run. */
439
+ maxCallsPerRun?: number | null;
440
+ [key: string]: unknown;
441
+ }
442
+
443
+ export interface ToolRun { calls: number; byTool: Record<string, number>; untrusted: boolean; /** Call after the run read content from outside (a web page, a file...). */ markUntrusted(): void }
444
+
445
+ export interface ToolCall {
446
+ tool: string;
447
+ input?: unknown;
448
+ /** The counters of the run (createRun()). Without it each call is a run of its own. */
449
+ run?: ToolRun;
450
+ actor?: ToolActor | null;
451
+ organisationId?: string | null;
452
+ /** The caller flags this call as made in an untrusted context. */
453
+ untrusted?: boolean;
454
+ /** Budget scope; defaults to organisationId, then "default". */
455
+ budgetScope?: string;
456
+ /** execute() only: the caller's own abort signal. */
457
+ signal?: AbortSignal;
458
+ }
459
+
460
+ export interface ToolDecision {
461
+ allowed: boolean;
462
+ /** 'allowed' | 'pending' | 'refused', or your word. */
463
+ decision: string;
464
+ /** Why it is not allowed (a TOOL_REASONS value, or your word); null when allowed. */
465
+ code: string | null;
466
+ reasons: string[];
467
+ tool: string; family: string | null; level: string | null;
468
+ /** The input after validate(). */
469
+ input: unknown;
470
+ budget: BudgetStanding | null;
471
+ /** Rank of this call in its run. */
472
+ rank: number;
473
+ /** Id of the audit record of this decision. */
474
+ auditId: string;
475
+ }
476
+ export interface ToolExecution<T = unknown> extends ToolDecision { executed: boolean; interrupted: boolean; result?: T }
477
+
478
+ export interface ToolPolicyOptions {
479
+ tools: ToolDefinition[];
480
+ /** When given, every tool's family must be in the list. */
481
+ families?: string[];
482
+ /** Static settings under what settings() returns. */
483
+ defaults?: ToolSettings;
484
+ /** Read before every call. May throw: the call is refused (settings_unavailable). */
485
+ settings?(context: { organisationId: string | null; actor: ToolActor | null }): ToolSettings | Promise<ToolSettings>;
486
+ /** A calendar budget (createCalendarBudget) or its options. */
487
+ budget?: CalendarBudget | CalendarBudgetOptions;
488
+ /** Levels whose calls wait for a person after an untrusted read (default: only the controlled level). */
489
+ untrustedPendingLevels?: string[];
490
+ emergency?: {
491
+ /** Roles allowed to pull the kill switch (default: any actor with an id). */
492
+ activateRoles?: string[];
493
+ /** Roles allowed to release it (default: any human). A model or an engine never can. */
494
+ releaseRoles?: string[];
495
+ };
496
+ /** Rename the words you get back: canonical word -> your word. Tools declare their level in your word. */
497
+ labels?: { levels?: Partial<Record<ToolLevel, string>>; decisions?: Partial<Record<ToolDecisionWord, string>>; codes?: Partial<Record<ToolReasonCode, string>> };
498
+ /** Audit journal and kill switch keys (default: memory). Use the store of your governor. */
499
+ store?: Pick<GovernorStore, 'appendAudit' | 'listAudit' | 'getControl' | 'setControl'>;
500
+ /** A governor whose kill switch also stops the tools. */
501
+ governor?: Governor;
502
+ version?: string;
503
+ /** How often a running tool looks at the kill switch pulled by another process (default 1000, 0 = off). */
504
+ pollMs?: number;
505
+ now?(): number;
506
+ idFactory?(): string;
507
+ onEvent?(event: { type: 'tool_policy' } & AuditEntry): void | Promise<void>;
508
+ }
509
+
510
+ export interface ToolPolicy {
511
+ readonly version: string;
512
+ createRun(): ToolRun;
513
+ /** The decision for one call; audited. Throws only when the journal cannot be written. */
514
+ decide(call: ToolCall): Promise<ToolDecision>;
515
+ /** Decides, then runs fn only when allowed, and cuts it at once on an emergency stop (signal + abandon). */
516
+ execute<T>(call: ToolCall, fn: (input: any, context: { signal: AbortSignal; decision: ToolDecision }) => T | Promise<T>): Promise<ToolExecution<Awaited<T>>>;
517
+ /** Names of the tools to offer the model now (none when stopped or disabled). */
518
+ availableTools(context?: { organisationId?: string | null }): Promise<string[]>;
519
+ listTools(): Array<{ name: string; family: string; level: string; maxPerRun: number | null; estimatedCost: number; budgetExempt: boolean }>;
520
+ halt(options: { by: ToolActor; reason?: string; organisationId?: string }): Promise<unknown>;
521
+ resume(options: { by: ToolActor; organisationId?: string }): Promise<unknown>;
522
+ isHalted(organisationId?: string | null): Promise<boolean>;
523
+ /** Counts what a call really consumed (whole units, idempotent by id), in the period of `at` (default now). */
524
+ recordSpend(spend: { id: string; amount: number; organisationId?: string; scope?: string; at?: number }): Promise<{ added: boolean; scope: string; period: string; spent: number }>;
525
+ budgetStatus(query?: { organisationId?: string; scope?: string; at?: number; estimate?: number }): Promise<BudgetStanding>;
526
+ listAudit: GovernorStore['listAudit'];
527
+ }
528
+ export function createToolPolicy(options: ToolPolicyOptions): ToolPolicy;
529
+
530
+ export interface BudgetStanding {
531
+ /** false when the cap is reached (or the estimate does not fit). */
532
+ allowed: boolean; exceeded: boolean; scope: string; period: string; spent: number; limit: number | null; remaining: number | null;
533
+ }
534
+ /** spent/limit/remaining are whole units of your choice (cents, thousandths of cents, tokens...). No fractions. */
535
+ export interface ToolBudgetStore {
536
+ getSpent(scope: string, period: string): Promise<number>;
537
+ /** Idempotent by (scope, id): a replay adds nothing and returns added: false. */
538
+ addSpend(entry: { scope: string; period: string; id: string; amount: number; at: string }): Promise<{ added: boolean; spent: number }>;
539
+ }
540
+ export interface CalendarBudgetOptions {
541
+ /** 'month' (default), 'day', or a function (instant, timeZone) => key. */
542
+ period?: 'month' | 'day' | ((at: Date, timeZone: string) => string);
543
+ /** IANA time zone (default UTC). */
544
+ timeZone?: string;
545
+ /** Default cap in whole units; absent: no cap. */
546
+ limit?: number | null;
547
+ scope?: string;
548
+ store?: ToolBudgetStore;
549
+ now?(): number;
550
+ }
551
+ export interface CalendarBudget {
552
+ check(query?: { scope?: string; limit?: number | null; estimate?: number; at?: number | Date }): Promise<BudgetStanding>;
553
+ record(spend: { id: string; amount: number; scope?: string; at?: number | Date }): Promise<{ added: boolean; scope: string; period: string; spent: number }>;
554
+ periodKey(at?: number | Date): string;
555
+ readonly period: string; readonly timeZone: string;
556
+ }
557
+ export function createCalendarBudget(options?: CalendarBudgetOptions): CalendarBudget;
558
+ /** "2026-10" (month) or "2026-10-31" (day) of an instant, in a time zone. */
559
+ export function calendarPeriodKey(at: number | Date, options?: { period?: CalendarBudgetOptions['period']; timeZone?: string }): string;
560
+ export function createMemoryToolBudgetStore(): ToolBudgetStore;
561
+ export function createPostgresToolBudgetStore(db: Queryable, options?: { prefix?: string }): ToolBudgetStore;
562
+ export function postgresToolBudgetSchema(options?: { prefix?: string }): string;
@@ -14,8 +14,13 @@ const { bucket } = require('./rollout');
14
14
  const { createRemoteSettings, parseRemoteSettings, remotePolicy, REMOTE_SETTINGS_SCHEMA, DECISION_RESULTS } = require('./remote');
15
15
 
16
16
  const { createMongoGovernorStore, mongoGovernorIndexes } = require('./mongo');
17
+ const { createToolPolicy, TOOL_LEVELS, TOOL_DECISIONS, TOOL_REASONS } = require('./tools');
18
+ const { createCalendarBudget, calendarPeriodKey, createMemoryToolBudgetStore } = require('./calendar');
19
+ const { postgresToolBudgetSchema, createPostgresToolBudgetStore } = require('./toolBudgetPostgres');
17
20
 
18
21
  module.exports = {
22
+ createToolPolicy, TOOL_LEVELS, TOOL_DECISIONS, TOOL_REASONS, createCalendarBudget, calendarPeriodKey, createMemoryToolBudgetStore,
23
+ postgresToolBudgetSchema, createPostgresToolBudgetStore,
19
24
  createMongoGovernorStore, mongoGovernorIndexes,
20
25
  createGovernor, assertGovernorReady, isGovernor, validatePolicy, scopesOf, protectedRulesTouched,
21
26
  createMemoryGovernorStore, createPostgresGovernorStore, postgresGovernorSchema, GovernorError,
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+ const { prefixOf, requireQueryable } = require('./util');
3
+
4
+ const DEFAULT_PREFIX = 'astratra_tools';
5
+ const names = (options) => {
6
+ const p = prefixOf(options, DEFAULT_PREFIX);
7
+ return { totals: `"${p}_budget_totals"`, entries: `"${p}_budget_entries"`, raw: p };
8
+ };
9
+
10
+ /** SQL that creates the tool budget tables. Idempotent: run it at every start or in a migration. */
11
+ function postgresToolBudgetSchema(options) {
12
+ const t = names(options);
13
+ return `CREATE TABLE IF NOT EXISTS ${t.totals} (
14
+ scope text NOT NULL,
15
+ period text NOT NULL,
16
+ spent bigint NOT NULL DEFAULT 0 CHECK (spent >= 0),
17
+ PRIMARY KEY (scope, period)
18
+ );
19
+ CREATE TABLE IF NOT EXISTS ${t.entries} (
20
+ scope text NOT NULL,
21
+ id text NOT NULL,
22
+ period text NOT NULL,
23
+ amount bigint NOT NULL CHECK (amount >= 0),
24
+ at timestamptz NOT NULL,
25
+ PRIMARY KEY (scope, id)
26
+ );`;
27
+ }
28
+
29
+ /**
30
+ * Tool budget store on PostgreSQL. `db` is any `{ query(sql, params) }`. A
31
+ * consumption is added by ONE statement (entry and total together), so it is
32
+ * atomic and idempotent without a transaction. Amounts are bigint integers.
33
+ */
34
+ function createPostgresToolBudgetStore(db, options = {}) {
35
+ requireQueryable(db);
36
+ const t = names(options);
37
+ return {
38
+ async getSpent(scope, period) {
39
+ const row = (await db.query(`SELECT spent::text AS spent FROM ${t.totals} WHERE scope = $1 AND period = $2`, [scope, period])).rows[0];
40
+ return row ? Number(row.spent) : 0;
41
+ },
42
+ async addSpend({ scope, period, id, amount, at }) {
43
+ const row = (await db.query(
44
+ `WITH ins AS (
45
+ INSERT INTO ${t.entries} (scope, id, period, amount, at) VALUES ($1, $2, $3, $4, $5::timestamptz)
46
+ ON CONFLICT (scope, id) DO NOTHING RETURNING amount
47
+ ), upd AS (
48
+ INSERT INTO ${t.totals} (scope, period, spent) SELECT $1, $3, amount FROM ins
49
+ ON CONFLICT (scope, period) DO UPDATE SET spent = ${t.totals}.spent + EXCLUDED.spent RETURNING spent
50
+ )
51
+ SELECT (SELECT count(*) FROM ins)::int AS added,
52
+ coalesce((SELECT spent FROM upd), (SELECT spent FROM ${t.totals} WHERE scope = $1 AND period = $3), 0)::text AS spent`,
53
+ [scope, id, period, amount, at])).rows[0];
54
+ return { added: Number(row.added) > 0, spent: Number(row.spent) };
55
+ }
56
+ };
57
+ }
58
+
59
+ module.exports = { postgresToolBudgetSchema, createPostgresToolBudgetStore };
@@ -0,0 +1,388 @@
1
+ 'use strict';
2
+ const crypto = require('node:crypto');
3
+ const { GovernorError, fingerprintOf, copy, isNonEmptyString } = require('./util');
4
+ const { createMemoryGovernorStore } = require('./stores');
5
+ const { createCalendarBudget, isAmount } = require('./calendar');
6
+
7
+ /*
8
+ * Tool policy: decides, by code and outside any model, whether ONE call of a tool
9
+ * may run. Generic on purpose: families, levels, caps and every word of the
10
+ * vocabulary come from configuration; nothing here knows what a tool does.
11
+ *
12
+ * Order of examination of a call:
13
+ * emergency stop > agent disabled > unknown tool > family disabled > invalid input
14
+ * > calendar budget > caps > level (sensitive, untrusted context, over threshold).
15
+ * Whatever cannot be read (settings, kill switch, budget) refuses: it never lets a call through.
16
+ */
17
+
18
+ const TOOL_LEVELS = Object.freeze({ READ: 'read', CONTROLLED: 'controlled', SENSITIVE: 'sensitive' });
19
+ const TOOL_DECISIONS = Object.freeze({ ALLOWED: 'allowed', PENDING: 'pending', REFUSED: 'refused' });
20
+ const TOOL_REASONS = Object.freeze({
21
+ HALTED: 'emergency_stop',
22
+ DISABLED: 'disabled',
23
+ UNAVAILABLE: 'settings_unavailable',
24
+ UNKNOWN_TOOL: 'unknown_tool',
25
+ FAMILY_DISABLED: 'family_disabled',
26
+ INVALID_INPUT: 'invalid_input',
27
+ BUDGET: 'budget_exceeded',
28
+ CAP: 'cap_reached',
29
+ SENSITIVE: 'sensitive_tool',
30
+ UNTRUSTED: 'untrusted_context',
31
+ THRESHOLD: 'over_threshold'
32
+ });
33
+
34
+ const LEVELS = Object.values(TOOL_LEVELS);
35
+ const DECISIONS = Object.values(TOOL_DECISIONS);
36
+ const CODES = Object.values(TOOL_REASONS);
37
+ const TOOL_NAME = /^[a-zA-Z][a-zA-Z0-9_.:-]{0,127}$/;
38
+ const GLOBAL = '*';
39
+ const NEVER_RELEASE = Object.freeze(['model', 'engine']);
40
+
41
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
42
+ const fail = (message) => { throw new GovernorError('tool_policy_invalid', `Invalid tool policy: ${message}`); };
43
+ const stringList = (value, field) => {
44
+ if (!Array.isArray(value) || !value.length || !value.every(isNonEmptyString)) fail(`${field} must be a non-empty array of strings.`);
45
+ return [...new Set(value)];
46
+ };
47
+
48
+ /** Vocabulary: canonical word -> your word. Only the words you list are renamed. */
49
+ function vocabulary(labels = {}, canonical, field) {
50
+ if (!isObject(labels)) fail(`labels.${field} must be an object.`);
51
+ const toApp = {}; const toCanonical = {};
52
+ for (const word of canonical) {
53
+ const mine = labels[word] ?? word;
54
+ if (!isNonEmptyString(mine)) fail(`labels.${field}.${word} must be a non-empty string.`);
55
+ toApp[word] = mine;
56
+ if (toCanonical[mine] !== undefined) fail(`labels.${field} gives the same word to two entries ("${mine}").`);
57
+ toCanonical[mine] = word;
58
+ }
59
+ for (const word of Object.keys(labels)) if (!canonical.includes(word)) fail(`labels.${field}.${word} is not one of: ${canonical.join(', ')}.`);
60
+ return { toApp, toCanonical };
61
+ }
62
+
63
+ function normalizeSettings(raw) {
64
+ if (!isObject(raw)) throw new GovernorError('settings_invalid', 'Tool settings must be an object.');
65
+ const out = {};
66
+ if (raw.enabled !== undefined) { if (typeof raw.enabled !== 'boolean') throw new GovernorError('settings_invalid', 'enabled must be a boolean.'); out.enabled = raw.enabled; }
67
+ if (raw.families !== undefined) {
68
+ if (!isObject(raw.families) || !Object.values(raw.families).every((value) => typeof value === 'boolean')) throw new GovernorError('settings_invalid', 'families must map a family to a boolean.');
69
+ out.families = { ...raw.families };
70
+ }
71
+ if (raw.budgetLimit !== undefined && raw.budgetLimit !== null) { if (!isAmount(raw.budgetLimit)) throw new GovernorError('settings_invalid', 'budgetLimit must be an integer >= 0.'); out.budgetLimit = raw.budgetLimit; }
72
+ if (raw.maxCallsPerRun !== undefined && raw.maxCallsPerRun !== null) {
73
+ if (!Number.isSafeInteger(raw.maxCallsPerRun) || raw.maxCallsPerRun < 1) throw new GovernorError('settings_invalid', 'maxCallsPerRun must be an integer >= 1.');
74
+ out.maxCallsPerRun = raw.maxCallsPerRun;
75
+ }
76
+ for (const [key, value] of Object.entries(raw)) if (!['enabled', 'families', 'budgetLimit', 'maxCallsPerRun'].includes(key)) out[key] = copy(value);
77
+ return out;
78
+ }
79
+
80
+ function normalizeTool(definition, levelOf, families) {
81
+ if (!isObject(definition)) fail('a tool must be an object.');
82
+ if (!TOOL_NAME.test(definition.name ?? '')) fail(`invalid tool name: ${definition.name}.`);
83
+ const name = definition.name;
84
+ if (!isNonEmptyString(definition.family)) fail(`${name}: family is required.`);
85
+ if (families && !families.includes(definition.family)) fail(`${name}: family "${definition.family}" is not in families.`);
86
+ const level = levelOf.toCanonical[definition.level];
87
+ if (!level) fail(`${name}: level must be one of ${Object.keys(levelOf.toCanonical).join(', ')}.`);
88
+ for (const field of ['validate', 'overThreshold']) if (definition[field] !== undefined && typeof definition[field] !== 'function') fail(`${name}: ${field} must be a function.`);
89
+ if (definition.maxPerRun !== undefined && (!Number.isSafeInteger(definition.maxPerRun) || definition.maxPerRun < 1)) fail(`${name}: maxPerRun must be an integer >= 1.`);
90
+ if (definition.estimatedCost !== undefined && !isAmount(definition.estimatedCost)) fail(`${name}: estimatedCost must be an integer >= 0.`);
91
+ return Object.freeze({
92
+ name, family: definition.family, level, validate: definition.validate ?? null, overThreshold: definition.overThreshold ?? null,
93
+ maxPerRun: definition.maxPerRun ?? null, estimatedCost: definition.estimatedCost ?? 0, budgetExempt: definition.budgetExempt === true
94
+ });
95
+ }
96
+
97
+ const actorOf = (actor) => (isObject(actor)
98
+ ? { kind: String(actor.kind ?? ''), id: String(actor.id ?? ''), roles: Array.isArray(actor.roles) ? actor.roles.map(String) : [] }
99
+ : null);
100
+ const hasRole = (actor, roles) => actor.roles.some((role) => roles.includes(role));
101
+
102
+ /**
103
+ * Builds the tool policy.
104
+ * options: tools, families?, defaults?, settings?, budget?, emergency?, labels?, untrustedPendingLevels?,
105
+ * store?, governor?, version?, pollMs?, now?, idFactory?, onEvent?
106
+ */
107
+ function createToolPolicy(options = {}) {
108
+ if (!isObject(options)) fail('options must be an object.');
109
+ const labels = options.labels ?? {};
110
+ const levelWords = vocabulary(labels.levels, LEVELS, 'levels');
111
+ const decisionWords = vocabulary(labels.decisions, DECISIONS, 'decisions');
112
+ const codeWords = vocabulary(labels.codes, CODES, 'codes');
113
+ const families = options.families === undefined ? null : stringList(options.families, 'families');
114
+ if (!Array.isArray(options.tools) || !options.tools.length) fail('tools must list at least one tool.');
115
+ const tools = new Map();
116
+ for (const definition of options.tools) {
117
+ const tool = normalizeTool(definition, levelWords, families);
118
+ if (tools.has(tool.name)) fail(`tool declared twice: ${tool.name}.`);
119
+ tools.set(tool.name, tool);
120
+ }
121
+ const untrustedLevels = (options.untrustedPendingLevels ?? [levelWords.toApp.controlled]).map((word) => {
122
+ const level = levelWords.toCanonical[word];
123
+ if (!level) fail(`untrustedPendingLevels: unknown level ${word}.`);
124
+ return level;
125
+ });
126
+ const emergency = options.emergency ?? {};
127
+ const activateRoles = emergency.activateRoles === undefined ? null : stringList(emergency.activateRoles, 'emergency.activateRoles');
128
+ const releaseRoles = emergency.releaseRoles === undefined ? null : stringList(emergency.releaseRoles, 'emergency.releaseRoles');
129
+
130
+ const store = options.store ?? createMemoryGovernorStore();
131
+ for (const method of ['appendAudit', 'getControl', 'setControl']) {
132
+ if (typeof store[method] !== 'function') throw new GovernorError('governor_unavailable', `Tool policy store is missing ${method}().`);
133
+ }
134
+ const now = options.now ?? Date.now;
135
+ const newId = options.idFactory ?? (() => crypto.randomUUID());
136
+ const version = options.version ?? '1';
137
+ const pollMs = options.pollMs ?? 1000;
138
+ if (!Number.isSafeInteger(pollMs) || pollMs < 0) fail('pollMs must be an integer >= 0 (0 turns the polling off).');
139
+ const readSettings = options.settings ?? null;
140
+ if (readSettings !== null && typeof readSettings !== 'function') fail('settings must be a function.');
141
+ const defaults = normalizeSettings(options.defaults ?? {});
142
+ const budget = options.budget == null ? null : (typeof options.budget.check === 'function' ? options.budget : createCalendarBudget({ now, ...options.budget }));
143
+ if (budget && typeof budget.record !== 'function') fail('budget must have check() and record().');
144
+ const governor = options.governor ?? null;
145
+ if (governor && typeof governor.isHalted !== 'function') fail('governor must be built by createGovernor().');
146
+
147
+ const active = new Set();
148
+ const iso = () => new Date(now()).toISOString();
149
+
150
+ async function audit(entry) {
151
+ const full = { id: newId(), at: iso(), policyVersion: version, organisationId: null, proposalId: null, reasons: [], actor: null, ...entry };
152
+ await store.appendAudit(full);
153
+ try { await options.onEvent?.({ type: 'tool_policy', ...copy(full) }); } catch (_error) { /* Observers never change a decision. */ }
154
+ return full;
155
+ }
156
+
157
+ async function haltState(organisationId) {
158
+ const global = await store.getControl(`tools-halt:${GLOBAL}`);
159
+ if (global?.halted) return { halted: true, scope: GLOBAL, reason: global.reason ?? null };
160
+ if (organisationId != null) {
161
+ const local = await store.getControl(`tools-halt:${organisationId}`);
162
+ if (local?.halted) return { halted: true, scope: organisationId, reason: local.reason ?? null };
163
+ }
164
+ if (governor && await governor.isHalted(organisationId ?? undefined)) return { halted: true, scope: 'governor', reason: 'governor_halted' };
165
+ return { halted: false };
166
+ }
167
+
168
+ async function currentSettings(call) {
169
+ const raw = readSettings ? await readSettings({ organisationId: call.organisationId ?? null, actor: actorOf(call.actor) }) : {};
170
+ const settings = normalizeSettings(raw ?? {});
171
+ return { ...defaults, ...settings, families: { ...defaults.families, ...settings.families } };
172
+ }
173
+
174
+ function createRun() {
175
+ const run = { calls: 0, byTool: {}, untrusted: false, markUntrusted() { run.untrusted = true; } };
176
+ return run;
177
+ }
178
+
179
+ const refuse = (code, extra = {}) => ({ decision: TOOL_DECISIONS.REFUSED, code, ...extra });
180
+
181
+ /* The verdict for one call, in canonical words. */
182
+ async function judge(call, tool, run, rank, rankOfTool) {
183
+ const organisationId = call.organisationId ?? null;
184
+ let state;
185
+ try { state = await haltState(organisationId); } catch (_error) { return refuse(TOOL_REASONS.UNAVAILABLE); }
186
+ if (state.halted) return refuse(TOOL_REASONS.HALTED, { haltScope: state.scope });
187
+ let settings;
188
+ try { settings = await currentSettings(call); } catch (_error) { return refuse(TOOL_REASONS.UNAVAILABLE); }
189
+ if (settings.enabled === false) return refuse(TOOL_REASONS.DISABLED);
190
+ if (!tool) return refuse(TOOL_REASONS.UNKNOWN_TOOL);
191
+ if (settings.families[tool.family] === false) return refuse(TOOL_REASONS.FAMILY_DISABLED);
192
+
193
+ let input = call.input ?? {};
194
+ if (tool.validate) {
195
+ let verdict;
196
+ try { verdict = tool.validate(input); } catch (_error) { verdict = false; }
197
+ if (verdict === false || (isObject(verdict) && verdict.ok === false)) return refuse(TOOL_REASONS.INVALID_INPUT);
198
+ if (isObject(verdict) && verdict.ok === true && 'value' in verdict) input = verdict.value;
199
+ }
200
+
201
+ let standing = null;
202
+ if (budget && !tool.budgetExempt) {
203
+ try {
204
+ standing = await budget.check({ scope: call.budgetScope ?? organisationId ?? undefined, limit: settings.budgetLimit, estimate: tool.estimatedCost });
205
+ } catch (_error) { return refuse(TOOL_REASONS.UNAVAILABLE, { input }); }
206
+ if (!standing.allowed) return refuse(TOOL_REASONS.BUDGET, { input, budget: standing });
207
+ }
208
+
209
+ if (settings.maxCallsPerRun !== undefined && rank > settings.maxCallsPerRun) return refuse(TOOL_REASONS.CAP, { input, budget: standing });
210
+ if (tool.maxPerRun !== null && rankOfTool > tool.maxPerRun) return refuse(TOOL_REASONS.CAP, { input, budget: standing });
211
+
212
+ const pending = (code) => ({ decision: TOOL_DECISIONS.PENDING, code, input, budget: standing });
213
+ if (tool.level === TOOL_LEVELS.SENSITIVE) return pending(TOOL_REASONS.SENSITIVE);
214
+ /* Content read from outside could carry a hidden instruction: a person looks first. */
215
+ if ((run.untrusted || call.untrusted === true) && untrustedLevels.includes(tool.level)) return pending(TOOL_REASONS.UNTRUSTED);
216
+ if (tool.level === TOOL_LEVELS.CONTROLLED && tool.overThreshold) {
217
+ let over = false;
218
+ try { over = tool.overThreshold(input, settings) === true; } catch (_error) { over = true; }
219
+ if (over) return pending(TOOL_REASONS.THRESHOLD);
220
+ }
221
+ return { decision: TOOL_DECISIONS.ALLOWED, code: null, input, budget: standing };
222
+ }
223
+
224
+ /* Canonical result -> the application's words. */
225
+ function present(result) {
226
+ return {
227
+ ...result,
228
+ decision: decisionWords.toApp[result.decision],
229
+ code: result.code == null ? null : codeWords.toApp[result.code],
230
+ reasons: result.code == null ? [] : [codeWords.toApp[result.code]],
231
+ level: result.level == null ? null : levelWords.toApp[result.level]
232
+ };
233
+ }
234
+
235
+ async function decideCanonical(call) {
236
+ if (!isObject(call)) throw new GovernorError('invalid_call', 'A tool call must be an object { tool, input, ... }.');
237
+ const run = call.run ?? createRun();
238
+ const name = typeof call.tool === 'string' ? call.tool : call.tool?.name;
239
+ const tool = tools.get(name) ?? null;
240
+ /* Counted at once: calls asked together cannot all slip under a cap. */
241
+ run.calls += 1;
242
+ run.byTool[name] = (run.byTool[name] ?? 0) + 1;
243
+ const verdict = await judge(call, tool, run, run.calls, run.byTool[name]);
244
+ const actor = actorOf(call.actor);
245
+ const record = await audit({
246
+ action: 'tool_decision', organisationId: call.organisationId ?? null, actor,
247
+ tool: String(name ?? '').slice(0, 200), family: tool?.family ?? null, level: tool?.level ?? null,
248
+ decision: verdict.decision, reasons: verdict.code ? [verdict.code] : [],
249
+ inputFingerprint: fingerprintOf(call.input ?? null), callRank: run.calls,
250
+ budget: verdict.budget ? { period: verdict.budget.period, spent: verdict.budget.spent, limit: verdict.budget.limit } : null,
251
+ untrusted: run.untrusted || call.untrusted === true
252
+ });
253
+ return {
254
+ allowed: verdict.decision === TOOL_DECISIONS.ALLOWED, decision: verdict.decision, code: verdict.code ?? null,
255
+ tool: record.tool, family: tool?.family ?? null, level: tool?.level ?? null,
256
+ input: verdict.input ?? call.input ?? null, budget: verdict.budget ?? null, rank: run.calls, auditId: record.id
257
+ };
258
+ }
259
+
260
+ /**
261
+ * Decision for ONE call { tool, input, run?, actor?, organisationId?, untrusted?, budgetScope? }.
262
+ * Never throws for a refusal; throws only if the audit journal cannot be written (nothing runs then).
263
+ */
264
+ const decide = async (call) => present(await decideCanonical(call));
265
+
266
+ /** True when the actor may pull the kill switch. */
267
+ function mayHalt(actor) {
268
+ if (!actor || !isNonEmptyString(actor.id)) return false;
269
+ return activateRoles ? hasRole(actor, activateRoles) : true;
270
+ }
271
+ /** True when the actor may release it. A model or an engine never does; without releaseRoles, only a human. */
272
+ function mayResume(actor) {
273
+ if (!actor || !isNonEmptyString(actor.id) || NEVER_RELEASE.includes(actor.kind)) return false;
274
+ return releaseRoles ? hasRole(actor, releaseRoles) : actor.kind === 'human';
275
+ }
276
+
277
+ async function control(halted, { by, reason, organisationId } = {}) {
278
+ const actor = actorOf(by);
279
+ const scope = organisationId == null ? GLOBAL : String(organisationId);
280
+ const action = halted ? 'tool_halt' : 'tool_resume';
281
+ if (!(halted ? mayHalt(actor) : mayResume(actor))) {
282
+ await audit({ action: `${action}_denied`, organisationId: scope === GLOBAL ? null : scope, actor, decision: 'refused', reasons: ['actor_not_allowed'] });
283
+ throw new GovernorError('actor_not_allowed', halted ? 'This actor may not pull the tool kill switch.' : 'This actor may not release the tool kill switch.');
284
+ }
285
+ const value = { halted, by: actor, reason: reason == null ? null : String(reason).slice(0, 2000), at: iso() };
286
+ await store.setControl(`tools-halt:${scope}`, value);
287
+ await audit({ action, organisationId: scope === GLOBAL ? null : scope, actor, decision: halted ? 'halted' : 'running', reasons: halted && value.reason ? [value.reason] : [] });
288
+ if (halted) {
289
+ for (const running of [...active]) if (scope === GLOBAL || running.organisationId === scope) running.interrupt(TOOL_REASONS.HALTED);
290
+ }
291
+ return value;
292
+ }
293
+
294
+ const raceAbort = (promise, signal) => new Promise((resolve, reject) => {
295
+ const onAbort = () => reject(signal.reason);
296
+ if (signal.aborted) { onAbort(); return; }
297
+ signal.addEventListener('abort', onAbort, { once: true });
298
+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));
299
+ });
300
+
301
+ /**
302
+ * Decides, then runs `fn(input, { signal, decision })` only when allowed. The kill switch is read before the
303
+ * call and again while it runs (in-process at once, other processes every pollMs); on a stop the signal aborts
304
+ * and the call is cut, even if the tool ignores the signal. A pending or refused call is never run.
305
+ * Returns { ...decision, executed, result? } or, when cut, a refused decision with interrupted: true.
306
+ */
307
+ async function execute(call, fn) {
308
+ if (typeof fn !== 'function') throw new GovernorError('invalid_call', 'execute needs the function to run.');
309
+ const verdict = await decideCanonical(call);
310
+ if (!verdict.allowed) return { ...present(verdict), executed: false, interrupted: false };
311
+ const controller = new globalThis.AbortController();
312
+ let stopped = false;
313
+ const running = {
314
+ organisationId: call.organisationId ?? null,
315
+ interrupt(code) { if (stopped) return; stopped = true; controller.abort(new GovernorError(code, 'The tool call was cut by the emergency stop.')); }
316
+ };
317
+ active.add(running);
318
+ const outer = call.signal;
319
+ const onOuter = () => controller.abort(outer.reason);
320
+ if (outer) { if (outer.aborted) onOuter(); else outer.addEventListener('abort', onOuter, { once: true }); }
321
+ let timer = null;
322
+ if (pollMs > 0) {
323
+ let reading = false;
324
+ timer = setInterval(async () => {
325
+ if (reading) return;
326
+ reading = true;
327
+ try { if ((await haltState(running.organisationId)).halted) running.interrupt(TOOL_REASONS.HALTED); } catch (_error) { running.interrupt(TOOL_REASONS.HALTED); } finally { reading = false; }
328
+ }, pollMs);
329
+ timer.unref?.();
330
+ }
331
+ const outcome = async (kind, extra = {}) => audit({
332
+ action: 'tool_outcome', organisationId: call.organisationId ?? null, actor: actorOf(call.actor), tool: verdict.tool, family: verdict.family, level: verdict.level,
333
+ decision: kind, reasons: extra.reason ? [extra.reason] : [], decisionAuditId: verdict.auditId
334
+ });
335
+ try {
336
+ /* The stop may have been pulled between the decision and now. */
337
+ if ((await haltState(running.organisationId)).halted) running.interrupt(TOOL_REASONS.HALTED);
338
+ const result = await raceAbort(Promise.resolve().then(() => fn(verdict.input, { signal: controller.signal, decision: present(verdict) })), controller.signal);
339
+ await outcome('ok');
340
+ return { ...present(verdict), executed: true, interrupted: false, result };
341
+ } catch (error) {
342
+ if (stopped) {
343
+ await outcome('interrupted', { reason: TOOL_REASONS.HALTED });
344
+ return { ...present({ ...verdict, allowed: false, decision: TOOL_DECISIONS.REFUSED, code: TOOL_REASONS.HALTED }), executed: false, interrupted: true };
345
+ }
346
+ if (outer?.aborted) { await outcome('aborted'); throw error; }
347
+ await outcome('error', { reason: String(error?.name ?? 'Error').slice(0, 100) });
348
+ throw error;
349
+ } finally {
350
+ if (timer) clearInterval(timer);
351
+ outer?.removeEventListener('abort', onOuter);
352
+ active.delete(running);
353
+ }
354
+ }
355
+
356
+ /** Tools the model may be offered: none when stopped or disabled, else those whose family is on. */
357
+ async function availableTools(call = {}) {
358
+ try {
359
+ if ((await haltState(call.organisationId ?? null)).halted) return [];
360
+ const settings = await currentSettings(call);
361
+ if (settings.enabled === false) return [];
362
+ return [...tools.values()].filter((tool) => settings.families[tool.family] !== false).map((tool) => tool.name);
363
+ } catch (_error) { return []; }
364
+ }
365
+
366
+ const describe = () => [...tools.values()].map((tool) => ({
367
+ name: tool.name, family: tool.family, level: levelWords.toApp[tool.level], maxPerRun: tool.maxPerRun, estimatedCost: tool.estimatedCost, budgetExempt: tool.budgetExempt
368
+ }));
369
+
370
+ return Object.freeze({
371
+ version, createRun, decide, execute, availableTools, listTools: describe,
372
+ halt: (opts) => control(true, opts),
373
+ resume: (opts) => control(false, opts),
374
+ isHalted: async (organisationId) => (await haltState(organisationId ?? null)).halted,
375
+ /** Counts what a call really consumed (idempotent on id). Needs a budget. */
376
+ recordSpend: (spend = {}) => {
377
+ if (!budget) throw new GovernorError('budget_invalid', 'This tool policy has no budget.');
378
+ return budget.record({ ...spend, scope: spend.scope ?? spend.organisationId ?? undefined });
379
+ },
380
+ budgetStatus: (query = {}) => {
381
+ if (!budget) throw new GovernorError('budget_invalid', 'This tool policy has no budget.');
382
+ return budget.check({ ...query, scope: query.scope ?? query.organisationId ?? undefined });
383
+ },
384
+ listAudit: (filter = {}) => store.listAudit(filter)
385
+ });
386
+ }
387
+
388
+ module.exports = { createToolPolicy, TOOL_LEVELS, TOOL_DECISIONS, TOOL_REASONS };