@astratra/conscience 1.2.0 → 1.4.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,93 @@ 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, { organisationId, actor })` (synchrone ou
182
+ asynchrone : le seuil peut être lu dans votre base ; une erreur ou un rejet compte
183
+ comme un dépassement) ou si le tour a lu un contenu non fiable
184
+ (`run.markUntrusted()` ou `untrusted: true` sur l'appel) : il est alors `pending` ;
185
+ `sensitive` est toujours `pending`. La politique n'exécute jamais un appel en attente :
186
+ l'application le garde et une personne décide.
187
+ - **Codes de refus** (`TOOL_REASONS`) : `emergency_stop`, `disabled`, `unknown_tool`,
188
+ `family_disabled`, `invalid_input`, `budget_exceeded`, `cap_reached` (appels par tour
189
+ ou `maxPerRun` de l'outil), et `settings_unavailable` quand les réglages, l'interrupteur
190
+ ou le budget sont illisibles. Codes d'attente : `sensitive_tool`, `untrusted_context`,
191
+ `over_threshold`. Ordre : arrêt, désactivé, inconnu, famille, entrée, budget, plafonds,
192
+ niveau. Les appels demandés ensemble sont comptés tout de suite : ils ne passent pas
193
+ tous sous un plafond.
194
+ - **Vos mots** : `labels: { levels, decisions, codes }` renomme ce que vous recevez
195
+ (`{ decisions: { pending: 'en_attente' } }`) ; les outils déclarent alors leur niveau
196
+ avec votre mot.
197
+ - **Budget calendaire** (`createCalendarBudget`, utilisable seul) : consommation comptée
198
+ par `'month'` ou `'day'` (ou votre fonction) d'un fuseau horaire (`calendarPeriodKey`),
199
+ plafond et montants en unités entières, jamais en flottants (prenez une unité plus
200
+ petite pour les fractions de centime). `check()` est lu avant chaque appel et teste
201
+ aussi le `estimatedCost` de l'outil ; une consommation tombe dans la période de son
202
+ propre instant : un appel à 23 h 30 le 31 octobre à Paris compte pour octobre là-bas
203
+ et pour novembre en UTC. Magasins : mémoire (`createMemoryToolBudgetStore`),
204
+ PostgreSQL (`createPostgresToolBudgetStore` : une seule requête atomique et
205
+ idempotente, bigint), ou le vôtre `{ getSpent(scope, period), addSpend({ scope,
206
+ period, id, amount, at }) }` (idempotent par id). La portée est `organisationId`
207
+ par défaut. Le plafond est atteint quand `spent >= limit` ; la mesure se faisant après
208
+ l'appel, le dernier appel peut le dépasser. **Lecture seule (1.4.0)** : un magasin qui
209
+ n'a que `getSpent()` lit une consommation déjà comptée ailleurs (votre propre table de
210
+ coûts) ; le budget ne fait alors que la vérifier avant chaque appel, `budget.readOnly`
211
+ vaut `true`, et `record()` / `recordSpend()` lèvent `budget_read_only`. `readOnly: true`
212
+ l'affirme.
213
+ - **Arrêt d'urgence** : `halt({ by, reason, organisationId? })` est lu avant chaque
214
+ appel et pendant l'exécution d'un outil. `execute()` donne à l'outil un `AbortSignal`
215
+ qui s'annule aussitôt pour un arrêt dans ce processus, et sous `pollMs` (1 s par défaut)
216
+ pour un arrêt tiré par un autre processus ; l'appel est aussi abandonné si l'outil
217
+ ignore le signal (`interrupted: true`). `activateRoles` le tirent (par défaut : toute
218
+ personne identifiée), `releaseRoles` le lèvent (par défaut : tout humain ; un acteur
219
+ `model` ou `engine` jamais). L'option `governor` fait aussi arrêter les outils par
220
+ l'interrupteur du gouverneur. **`isHalted` (1.4.0)** : un arrêt d'urgence tenu par
221
+ votre application (une colonne de ses réglages), booléen ou fonction
222
+ `(organisationId) => boolean`, synchrone ou asynchrone, lu avant chaque appel et
223
+ relu pendant l'exécution d'un outil ; tout autre résultat, ou une erreur, refuse
224
+ l'appel (`settings_unavailable`). `validate` peut aussi être asynchrone.
225
+ - **Audit** : chaque décision est écrite dans le journal du gouverneur avant d'être
226
+ rendue (`tool_decision` : qui, outil, famille, niveau, décision, motifs, empreinte de
227
+ l'entrée, jamais l'entrée brute), plus `tool_outcome`, `tool_halt`, `tool_resume` et
228
+ leurs refus. Si le journal ne peut pas être écrit, l'appel ne s'exécute pas.
229
+ `onEvent` reçoit les mêmes enregistrements.
230
+
144
231
  ### Approbations (matrice, double approbation, expiration)
145
232
 
146
233
  L'approbation est décidée par la politique, pas par celui qui propose :
@@ -403,6 +490,7 @@ vérifié.
403
490
  ```js
404
491
  postgresConscienceSchema({ prefix: 'astratra_conscience' }) // table <prefix>_records
405
492
  postgresGovernorSchema({ prefix: 'astratra_governor' }) // <prefix>_proposals, _audit, _spend, _controls, _objects, _versions, _findings
493
+ postgresToolBudgetSchema({ prefix: 'astratra_tools' }) // <prefix>_budget_totals, _budget_entries (tool budget, 1.3.0)
406
494
  ```
407
495
 
408
496
  ### Écrire son propre magasin (MongoDB, ...)
package/README.md CHANGED
@@ -135,6 +135,93 @@ 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, { organisationId, actor })` (sync or
176
+ async, so a cap can be read from your database; a throw or a rejection
177
+ counts as over), or the run read untrusted content
178
+ (`run.markUntrusted()` or `untrusted: true` on the call), then it is `pending`;
179
+ `sensitive` is always `pending`. The policy never runs a pending call: the
180
+ application keeps it and a person decides.
181
+ - **Refusal codes** (`TOOL_REASONS`): `emergency_stop`, `disabled`,
182
+ `unknown_tool`, `family_disabled`, `invalid_input`, `budget_exceeded`,
183
+ `cap_reached` (calls per run, or `maxPerRun` of the tool), and
184
+ `settings_unavailable` when settings, kill switch or budget cannot be read.
185
+ Pending codes: `sensitive_tool`, `untrusted_context`, `over_threshold`.
186
+ Order: stop, disabled, unknown, family, input, budget, caps, level. Calls asked
187
+ together are counted at once, so they cannot all slip under a cap.
188
+ - **Your words**: `labels: { levels, decisions, codes }` renames what you get
189
+ back (`{ decisions: { pending: 'en_attente' } }`); tools then declare their
190
+ level in your word.
191
+ - **Calendar budget** (`createCalendarBudget`, also usable alone): consumption
192
+ counted per `'month'` or `'day'` (or your own function) of a time zone
193
+ (`calendarPeriodKey`), cap and amounts are whole units, never floats (use a
194
+ smaller unit for fractions of a cent). `check()` runs before each call and
195
+ also tests the tool's `estimatedCost`; a consumption lands in the period of
196
+ its own instant, so a call at 23:30 on 31 October in Paris counts for
197
+ October there and for November in UTC. Stores: memory
198
+ (`createMemoryToolBudgetStore`), PostgreSQL (`createPostgresToolBudgetStore`:
199
+ one atomic, idempotent statement, bigint), or your own `{ getSpent(scope,
200
+ period), addSpend({ scope, period, id, amount, at }) }` (idempotent by id).
201
+ The scope is `organisationId` by default. The cap is reached when
202
+ `spent >= limit`; with the measure after the call, the last call may pass it.
203
+ **Read-only (1.4.0)**: a store with `getSpent()` only reads a consumption you
204
+ already count elsewhere (your own table of costs); the budget then only
205
+ checks it before each call, `budget.readOnly` is `true`, and `record()` /
206
+ `recordSpend()` throw `budget_read_only`. `readOnly: true` asserts it.
207
+ - **Emergency stop**: `halt({ by, reason, organisationId? })` is read before
208
+ each call and while a tool runs. `execute()` gives the tool an `AbortSignal`
209
+ that aborts at once on a stop in this process, and within `pollMs` (default
210
+ 1 s) on a stop pulled by another process; the call is also abandoned if the
211
+ tool ignores the signal (`interrupted: true`). `activateRoles` pull it
212
+ (default: anyone with an id), `releaseRoles` lift it (default: any human; a
213
+ `model` or `engine` actor never can). A `governor` option makes the governor
214
+ kill switch stop the tools too. **`isHalted` (1.4.0)**: an emergency stop kept
215
+ by your application (a column of its settings), a boolean or a function
216
+ `(organisationId) => boolean`, sync or async, read before each call and
217
+ polled while a tool runs; anything but a boolean, or a throw, refuses the
218
+ call (`settings_unavailable`). `validate` may be async too.
219
+ - **Audit**: every decision is written to the governor journal before it is
220
+ returned (`tool_decision`: who, tool, family, level, decision, reasons, input
221
+ fingerprint, never the raw input), plus `tool_outcome`, `tool_halt`,
222
+ `tool_resume` and their refusals. If the journal cannot be written the call
223
+ does not run. `onEvent` receives the same records.
224
+
138
225
  ### Approvals (matrix, double approval, expiry)
139
226
 
140
227
  Approval is decided by the policy, not by whoever proposes:
@@ -384,6 +471,7 @@ uses parameters only; the table prefix is a checked identifier.
384
471
  ```js
385
472
  postgresConscienceSchema({ prefix: 'astratra_conscience' }) // table <prefix>_records
386
473
  postgresGovernorSchema({ prefix: 'astratra_governor' }) // <prefix>_proposals, _audit, _spend, _controls, _objects, _versions, _findings
474
+ postgresToolBudgetSchema({ prefix: 'astratra_tools' }) // <prefix>_budget_totals, _budget_entries (tool budget, 1.3.0)
387
475
  ```
388
476
 
389
477
  ### 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.4.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,105 @@
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
+ * A store with getSpent() only is a supported case: the budget reads a consumption kept elsewhere.
66
+ */
67
+ function createCalendarBudget(options = {}) {
68
+ const { period = 'month', timeZone = 'UTC', scope: defaultScope = 'default', limit: defaultLimit } = options;
69
+ const store = options.store ?? createMemoryToolBudgetStore();
70
+ if (typeof store.getSpent !== 'function') throw new GovernorError('budget_invalid', 'The budget store is missing getSpent().');
71
+ /* A store with getSpent() only is read-only: the consumption is counted elsewhere (your own table of costs),
72
+ the budget only reads it before each call. record() then refuses with budget_read_only. */
73
+ const readOnly = typeof store.addSpend !== 'function';
74
+ if (!readOnly && options.readOnly === true) throw new GovernorError('budget_invalid', 'readOnly: true but the store has addSpend().');
75
+ if (defaultLimit !== undefined && defaultLimit !== null && !isAmount(defaultLimit)) throw new GovernorError('budget_invalid', 'limit must be an integer >= 0.');
76
+ const now = options.now ?? Date.now;
77
+ calendarPeriodKey(now(), { period, timeZone }); // fails now, not at the first call, on a wrong period or time zone
78
+
79
+ const keyOf = (at) => calendarPeriodKey(at ?? now(), { period, timeZone });
80
+
81
+ /** Where the budget stands, and whether a call of `estimate` units still fits. Read before each call. */
82
+ async function check({ scope = defaultScope, limit = defaultLimit, estimate = 0, at } = {}) {
83
+ if (limit !== undefined && limit !== null && !isAmount(limit)) throw new GovernorError('budget_invalid', 'limit must be an integer >= 0.');
84
+ if (!isAmount(estimate)) throw new GovernorError('budget_invalid', 'estimate must be an integer >= 0.');
85
+ const key = keyOf(at);
86
+ const spent = await store.getSpent(scope, key);
87
+ if (limit === undefined || limit === null) return { allowed: true, exceeded: false, scope, period: key, spent, limit: null, remaining: null };
88
+ return { allowed: spent < limit && spent + estimate <= limit, exceeded: spent >= limit, scope, period: key, spent, limit, remaining: Math.max(0, limit - spent) };
89
+ }
90
+
91
+ /** Counts a consumption in the period of its instant. `id` makes the call safe to repeat. */
92
+ async function record({ scope = defaultScope, amount, id, at } = {}) {
93
+ if (readOnly) throw new GovernorError('budget_read_only', 'This budget reads a consumption counted elsewhere: record it in your own store.');
94
+ if (!isAmount(amount)) throw new GovernorError('budget_invalid', 'amount must be an integer >= 0 (whole units, no fractions).');
95
+ if (!isNonEmptyString(id)) throw new GovernorError('budget_invalid', 'A consumption needs a stable id (idempotency).');
96
+ const instant = at ?? now();
97
+ const key = keyOf(instant);
98
+ const result = await store.addSpend({ scope, period: key, id, amount, at: new Date(instant).toISOString() });
99
+ return { added: result.added, scope, period: key, spent: result.spent };
100
+ }
101
+
102
+ return Object.freeze({ check, record, readOnly, periodKey: keyOf, period: typeof period === 'function' ? 'custom' : period, timeZone });
103
+ }
104
+
105
+ 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,182 @@ 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 } | Promise<boolean | { ok: boolean; value?: unknown }>;
420
+ /** Controlled tools only: true sends the call to a person (an amount over your own threshold, for instance).
421
+ * May be async (a cap read from your database); throwing or rejecting counts as true. */
422
+ overThreshold?(input: any, settings: ToolSettings, context: { organisationId: string | null; actor: ToolActor }): boolean | Promise<boolean>;
423
+ /** At most this many calls of the tool in one run; the next ones are refused (cap_reached). */
424
+ maxPerRun?: number;
425
+ /** Whole units this call is expected to consume: refused up front when it cannot fit in the budget. */
426
+ estimatedCost?: number;
427
+ /** Stays callable when the budget is exhausted (read-only state, for instance). */
428
+ budgetExempt?: boolean;
429
+ }
430
+
431
+ /** Settings read before EACH call; anything else you put in is handed back to your validate and overThreshold functions. */
432
+ export interface ToolSettings {
433
+ /** false: every call is refused (disabled). */
434
+ enabled?: boolean;
435
+ /** family -> on/off. A family that is not listed is on. */
436
+ families?: Record<string, boolean>;
437
+ /** Cap of the calendar budget, whole units. Overrides the default limit of the budget. */
438
+ budgetLimit?: number | null;
439
+ /** Calls of all tools in one run. */
440
+ maxCallsPerRun?: number | null;
441
+ [key: string]: unknown;
442
+ }
443
+
444
+ 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 }
445
+
446
+ export interface ToolCall {
447
+ tool: string;
448
+ input?: unknown;
449
+ /** The counters of the run (createRun()). Without it each call is a run of its own. */
450
+ run?: ToolRun;
451
+ actor?: ToolActor | null;
452
+ organisationId?: string | null;
453
+ /** The caller flags this call as made in an untrusted context. */
454
+ untrusted?: boolean;
455
+ /** Budget scope; defaults to organisationId, then "default". */
456
+ budgetScope?: string;
457
+ /** execute() only: the caller's own abort signal. */
458
+ signal?: AbortSignal;
459
+ }
460
+
461
+ export interface ToolDecision {
462
+ allowed: boolean;
463
+ /** 'allowed' | 'pending' | 'refused', or your word. */
464
+ decision: string;
465
+ /** Why it is not allowed (a TOOL_REASONS value, or your word); null when allowed. */
466
+ code: string | null;
467
+ reasons: string[];
468
+ tool: string; family: string | null; level: string | null;
469
+ /** The input after validate(). */
470
+ input: unknown;
471
+ budget: BudgetStanding | null;
472
+ /** Rank of this call in its run. */
473
+ rank: number;
474
+ /** Id of the audit record of this decision. */
475
+ auditId: string;
476
+ }
477
+ export interface ToolExecution<T = unknown> extends ToolDecision { executed: boolean; interrupted: boolean; result?: T }
478
+
479
+ export interface ToolPolicyOptions {
480
+ tools: ToolDefinition[];
481
+ /** When given, every tool's family must be in the list. */
482
+ families?: string[];
483
+ /** Static settings under what settings() returns. */
484
+ defaults?: ToolSettings;
485
+ /** Read before every call. May throw: the call is refused (settings_unavailable). */
486
+ settings?(context: { organisationId: string | null; actor: ToolActor | null }): ToolSettings | Promise<ToolSettings>;
487
+ /** A calendar budget (createCalendarBudget) or its options. */
488
+ budget?: CalendarBudget | CalendarBudgetOptions;
489
+ /** Levels whose calls wait for a person after an untrusted read (default: only the controlled level). */
490
+ untrustedPendingLevels?: string[];
491
+ emergency?: {
492
+ /** Roles allowed to pull the kill switch (default: any actor with an id). */
493
+ activateRoles?: string[];
494
+ /** Roles allowed to release it (default: any human). A model or an engine never can. */
495
+ releaseRoles?: string[];
496
+ };
497
+ /** Rename the words you get back: canonical word -> your word. Tools declare their level in your word. */
498
+ labels?: { levels?: Partial<Record<ToolLevel, string>>; decisions?: Partial<Record<ToolDecisionWord, string>>; codes?: Partial<Record<ToolReasonCode, string>> };
499
+ /** Audit journal and kill switch keys (default: memory). Use the store of your governor. */
500
+ store?: Pick<GovernorStore, 'appendAudit' | 'listAudit' | 'getControl' | 'setControl'>;
501
+ /** A governor whose kill switch also stops the tools. */
502
+ governor?: Governor;
503
+ /** An emergency stop kept by your application (a column of your settings): a boolean, or a function
504
+ * (organisationId) => boolean, sync or async, read before each call and polled while a tool runs.
505
+ * Anything but a boolean, or a throw, refuses the call (settings_unavailable). */
506
+ isHalted?: boolean | ((organisationId: string | undefined) => boolean | Promise<boolean>);
507
+ version?: string;
508
+ /** How often a running tool looks at the kill switch pulled by another process (default 1000, 0 = off). */
509
+ pollMs?: number;
510
+ now?(): number;
511
+ idFactory?(): string;
512
+ onEvent?(event: { type: 'tool_policy' } & AuditEntry): void | Promise<void>;
513
+ }
514
+
515
+ export interface ToolPolicy {
516
+ readonly version: string;
517
+ createRun(): ToolRun;
518
+ /** The decision for one call; audited. Throws only when the journal cannot be written. */
519
+ decide(call: ToolCall): Promise<ToolDecision>;
520
+ /** Decides, then runs fn only when allowed, and cuts it at once on an emergency stop (signal + abandon). */
521
+ execute<T>(call: ToolCall, fn: (input: any, context: { signal: AbortSignal; decision: ToolDecision }) => T | Promise<T>): Promise<ToolExecution<Awaited<T>>>;
522
+ /** Names of the tools to offer the model now (none when stopped or disabled). */
523
+ availableTools(context?: { organisationId?: string | null }): Promise<string[]>;
524
+ listTools(): Array<{ name: string; family: string; level: string; maxPerRun: number | null; estimatedCost: number; budgetExempt: boolean }>;
525
+ halt(options: { by: ToolActor; reason?: string; organisationId?: string }): Promise<unknown>;
526
+ resume(options: { by: ToolActor; organisationId?: string }): Promise<unknown>;
527
+ isHalted(organisationId?: string | null): Promise<boolean>;
528
+ /** Counts what a call really consumed (whole units, idempotent by id), in the period of `at` (default now). */
529
+ recordSpend(spend: { id: string; amount: number; organisationId?: string; scope?: string; at?: number }): Promise<{ added: boolean; scope: string; period: string; spent: number }>;
530
+ budgetStatus(query?: { organisationId?: string; scope?: string; at?: number; estimate?: number }): Promise<BudgetStanding>;
531
+ listAudit: GovernorStore['listAudit'];
532
+ }
533
+ export function createToolPolicy(options: ToolPolicyOptions): ToolPolicy;
534
+
535
+ export interface BudgetStanding {
536
+ /** false when the cap is reached (or the estimate does not fit). */
537
+ allowed: boolean; exceeded: boolean; scope: string; period: string; spent: number; limit: number | null; remaining: number | null;
538
+ }
539
+ /** spent/limit/remaining are whole units of your choice (cents, thousandths of cents, tokens...). No fractions. */
540
+ export interface ToolBudgetStore {
541
+ getSpent(scope: string, period: string): Promise<number>;
542
+ /** Idempotent by (scope, id): a replay adds nothing and returns added: false.
543
+ * Absent: the budget is read-only (the consumption is counted elsewhere; record() throws budget_read_only). */
544
+ addSpend?(entry: { scope: string; period: string; id: string; amount: number; at: string }): Promise<{ added: boolean; spent: number }>;
545
+ }
546
+ export interface CalendarBudgetOptions {
547
+ /** 'month' (default), 'day', or a function (instant, timeZone) => key. */
548
+ period?: 'month' | 'day' | ((at: Date, timeZone: string) => string);
549
+ /** IANA time zone (default UTC). */
550
+ timeZone?: string;
551
+ /** Default cap in whole units; absent: no cap. */
552
+ limit?: number | null;
553
+ scope?: string;
554
+ store?: ToolBudgetStore;
555
+ /** Asserts the store has no addSpend() (a store with getSpent() only is read-only anyway). */
556
+ readOnly?: boolean;
557
+ now?(): number;
558
+ }
559
+ export interface CalendarBudget {
560
+ check(query?: { scope?: string; limit?: number | null; estimate?: number; at?: number | Date }): Promise<BudgetStanding>;
561
+ record(spend: { id: string; amount: number; scope?: string; at?: number | Date }): Promise<{ added: boolean; scope: string; period: string; spent: number }>;
562
+ periodKey(at?: number | Date): string;
563
+ readonly period: string; readonly timeZone: string;
564
+ /** true when the store has getSpent() only. */
565
+ readonly readOnly: boolean;
566
+ }
567
+ export function createCalendarBudget(options?: CalendarBudgetOptions): CalendarBudget;
568
+ /** "2026-10" (month) or "2026-10-31" (day) of an instant, in a time zone. */
569
+ export function calendarPeriodKey(at: number | Date, options?: { period?: CalendarBudgetOptions['period']; timeZone?: string }): string;
570
+ export function createMemoryToolBudgetStore(): ToolBudgetStore;
571
+ export function createPostgresToolBudgetStore(db: Queryable, options?: { prefix?: string }): ToolBudgetStore;
572
+ 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,398 @@
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?, isHalted?, 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
+ /* An emergency stop kept by the application (a column of its settings): a boolean, or a function
147
+ (organisationId) => boolean, sync or async, read before each call and while a tool runs. */
148
+ const appHalted = options.isHalted ?? null;
149
+ if (appHalted !== null && typeof appHalted !== 'boolean' && typeof appHalted !== 'function') fail('isHalted must be a boolean or a function.');
150
+
151
+ const active = new Set();
152
+ const iso = () => new Date(now()).toISOString();
153
+
154
+ async function audit(entry) {
155
+ const full = { id: newId(), at: iso(), policyVersion: version, organisationId: null, proposalId: null, reasons: [], actor: null, ...entry };
156
+ await store.appendAudit(full);
157
+ try { await options.onEvent?.({ type: 'tool_policy', ...copy(full) }); } catch (_error) { /* Observers never change a decision. */ }
158
+ return full;
159
+ }
160
+
161
+ async function haltState(organisationId) {
162
+ const global = await store.getControl(`tools-halt:${GLOBAL}`);
163
+ if (global?.halted) return { halted: true, scope: GLOBAL, reason: global.reason ?? null };
164
+ if (organisationId != null) {
165
+ const local = await store.getControl(`tools-halt:${organisationId}`);
166
+ if (local?.halted) return { halted: true, scope: organisationId, reason: local.reason ?? null };
167
+ }
168
+ if (governor && await governor.isHalted(organisationId ?? undefined)) return { halted: true, scope: 'governor', reason: 'governor_halted' };
169
+ if (appHalted !== null) {
170
+ const value = typeof appHalted === 'function' ? await appHalted(organisationId ?? undefined) : appHalted;
171
+ if (typeof value !== 'boolean') throw new GovernorError('governor_unavailable', 'isHalted() must give a boolean.'); // Read as a failure: refuses.
172
+ if (value) return { halted: true, scope: 'application', reason: 'application_halted' };
173
+ }
174
+ return { halted: false };
175
+ }
176
+
177
+ async function currentSettings(call) {
178
+ const raw = readSettings ? await readSettings({ organisationId: call.organisationId ?? null, actor: actorOf(call.actor) }) : {};
179
+ const settings = normalizeSettings(raw ?? {});
180
+ return { ...defaults, ...settings, families: { ...defaults.families, ...settings.families } };
181
+ }
182
+
183
+ function createRun() {
184
+ const run = { calls: 0, byTool: {}, untrusted: false, markUntrusted() { run.untrusted = true; } };
185
+ return run;
186
+ }
187
+
188
+ const refuse = (code, extra = {}) => ({ decision: TOOL_DECISIONS.REFUSED, code, ...extra });
189
+
190
+ /* The verdict for one call, in canonical words. */
191
+ async function judge(call, tool, run, rank, rankOfTool) {
192
+ const organisationId = call.organisationId ?? null;
193
+ let state;
194
+ try { state = await haltState(organisationId); } catch (_error) { return refuse(TOOL_REASONS.UNAVAILABLE); }
195
+ if (state.halted) return refuse(TOOL_REASONS.HALTED, { haltScope: state.scope });
196
+ let settings;
197
+ try { settings = await currentSettings(call); } catch (_error) { return refuse(TOOL_REASONS.UNAVAILABLE); }
198
+ if (settings.enabled === false) return refuse(TOOL_REASONS.DISABLED);
199
+ if (!tool) return refuse(TOOL_REASONS.UNKNOWN_TOOL);
200
+ if (settings.families[tool.family] === false) return refuse(TOOL_REASONS.FAMILY_DISABLED);
201
+
202
+ let input = call.input ?? {};
203
+ if (tool.validate) {
204
+ let verdict;
205
+ try { verdict = await tool.validate(input); } catch (_error) { verdict = false; }
206
+ if (verdict === false || (isObject(verdict) && verdict.ok === false)) return refuse(TOOL_REASONS.INVALID_INPUT);
207
+ if (isObject(verdict) && verdict.ok === true && 'value' in verdict) input = verdict.value;
208
+ }
209
+
210
+ let standing = null;
211
+ if (budget && !tool.budgetExempt) {
212
+ try {
213
+ standing = await budget.check({ scope: call.budgetScope ?? organisationId ?? undefined, limit: settings.budgetLimit, estimate: tool.estimatedCost });
214
+ } catch (_error) { return refuse(TOOL_REASONS.UNAVAILABLE, { input }); }
215
+ if (!standing.allowed) return refuse(TOOL_REASONS.BUDGET, { input, budget: standing });
216
+ }
217
+
218
+ if (settings.maxCallsPerRun !== undefined && rank > settings.maxCallsPerRun) return refuse(TOOL_REASONS.CAP, { input, budget: standing });
219
+ if (tool.maxPerRun !== null && rankOfTool > tool.maxPerRun) return refuse(TOOL_REASONS.CAP, { input, budget: standing });
220
+
221
+ const pending = (code) => ({ decision: TOOL_DECISIONS.PENDING, code, input, budget: standing });
222
+ if (tool.level === TOOL_LEVELS.SENSITIVE) return pending(TOOL_REASONS.SENSITIVE);
223
+ /* Content read from outside could carry a hidden instruction: a person looks first. */
224
+ if ((run.untrusted || call.untrusted === true) && untrustedLevels.includes(tool.level)) return pending(TOOL_REASONS.UNTRUSTED);
225
+ if (tool.level === TOOL_LEVELS.CONTROLLED && tool.overThreshold) {
226
+ let over = false;
227
+ // May be async (a cap read from the database). A failure or a timeout puts the call in front of a person.
228
+ try { over = (await tool.overThreshold(input, settings, { organisationId, actor: actorOf(call.actor) })) === true; } catch (_error) { over = true; }
229
+ if (over) return pending(TOOL_REASONS.THRESHOLD);
230
+ }
231
+ return { decision: TOOL_DECISIONS.ALLOWED, code: null, input, budget: standing };
232
+ }
233
+
234
+ /* Canonical result -> the application's words. */
235
+ function present(result) {
236
+ return {
237
+ ...result,
238
+ decision: decisionWords.toApp[result.decision],
239
+ code: result.code == null ? null : codeWords.toApp[result.code],
240
+ reasons: result.code == null ? [] : [codeWords.toApp[result.code]],
241
+ level: result.level == null ? null : levelWords.toApp[result.level]
242
+ };
243
+ }
244
+
245
+ async function decideCanonical(call) {
246
+ if (!isObject(call)) throw new GovernorError('invalid_call', 'A tool call must be an object { tool, input, ... }.');
247
+ const run = call.run ?? createRun();
248
+ const name = typeof call.tool === 'string' ? call.tool : call.tool?.name;
249
+ const tool = tools.get(name) ?? null;
250
+ /* Counted at once: calls asked together cannot all slip under a cap. */
251
+ run.calls += 1;
252
+ run.byTool[name] = (run.byTool[name] ?? 0) + 1;
253
+ const verdict = await judge(call, tool, run, run.calls, run.byTool[name]);
254
+ const actor = actorOf(call.actor);
255
+ const record = await audit({
256
+ action: 'tool_decision', organisationId: call.organisationId ?? null, actor,
257
+ tool: String(name ?? '').slice(0, 200), family: tool?.family ?? null, level: tool?.level ?? null,
258
+ decision: verdict.decision, reasons: verdict.code ? [verdict.code] : [],
259
+ inputFingerprint: fingerprintOf(call.input ?? null), callRank: run.calls,
260
+ budget: verdict.budget ? { period: verdict.budget.period, spent: verdict.budget.spent, limit: verdict.budget.limit } : null,
261
+ untrusted: run.untrusted || call.untrusted === true
262
+ });
263
+ return {
264
+ allowed: verdict.decision === TOOL_DECISIONS.ALLOWED, decision: verdict.decision, code: verdict.code ?? null,
265
+ tool: record.tool, family: tool?.family ?? null, level: tool?.level ?? null,
266
+ input: verdict.input ?? call.input ?? null, budget: verdict.budget ?? null, rank: run.calls, auditId: record.id
267
+ };
268
+ }
269
+
270
+ /**
271
+ * Decision for ONE call { tool, input, run?, actor?, organisationId?, untrusted?, budgetScope? }.
272
+ * Never throws for a refusal; throws only if the audit journal cannot be written (nothing runs then).
273
+ */
274
+ const decide = async (call) => present(await decideCanonical(call));
275
+
276
+ /** True when the actor may pull the kill switch. */
277
+ function mayHalt(actor) {
278
+ if (!actor || !isNonEmptyString(actor.id)) return false;
279
+ return activateRoles ? hasRole(actor, activateRoles) : true;
280
+ }
281
+ /** True when the actor may release it. A model or an engine never does; without releaseRoles, only a human. */
282
+ function mayResume(actor) {
283
+ if (!actor || !isNonEmptyString(actor.id) || NEVER_RELEASE.includes(actor.kind)) return false;
284
+ return releaseRoles ? hasRole(actor, releaseRoles) : actor.kind === 'human';
285
+ }
286
+
287
+ async function control(halted, { by, reason, organisationId } = {}) {
288
+ const actor = actorOf(by);
289
+ const scope = organisationId == null ? GLOBAL : String(organisationId);
290
+ const action = halted ? 'tool_halt' : 'tool_resume';
291
+ if (!(halted ? mayHalt(actor) : mayResume(actor))) {
292
+ await audit({ action: `${action}_denied`, organisationId: scope === GLOBAL ? null : scope, actor, decision: 'refused', reasons: ['actor_not_allowed'] });
293
+ 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.');
294
+ }
295
+ const value = { halted, by: actor, reason: reason == null ? null : String(reason).slice(0, 2000), at: iso() };
296
+ await store.setControl(`tools-halt:${scope}`, value);
297
+ await audit({ action, organisationId: scope === GLOBAL ? null : scope, actor, decision: halted ? 'halted' : 'running', reasons: halted && value.reason ? [value.reason] : [] });
298
+ if (halted) {
299
+ for (const running of [...active]) if (scope === GLOBAL || running.organisationId === scope) running.interrupt(TOOL_REASONS.HALTED);
300
+ }
301
+ return value;
302
+ }
303
+
304
+ const raceAbort = (promise, signal) => new Promise((resolve, reject) => {
305
+ const onAbort = () => reject(signal.reason);
306
+ if (signal.aborted) { onAbort(); return; }
307
+ signal.addEventListener('abort', onAbort, { once: true });
308
+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));
309
+ });
310
+
311
+ /**
312
+ * Decides, then runs `fn(input, { signal, decision })` only when allowed. The kill switch is read before the
313
+ * call and again while it runs (in-process at once, other processes every pollMs); on a stop the signal aborts
314
+ * and the call is cut, even if the tool ignores the signal. A pending or refused call is never run.
315
+ * Returns { ...decision, executed, result? } or, when cut, a refused decision with interrupted: true.
316
+ */
317
+ async function execute(call, fn) {
318
+ if (typeof fn !== 'function') throw new GovernorError('invalid_call', 'execute needs the function to run.');
319
+ const verdict = await decideCanonical(call);
320
+ if (!verdict.allowed) return { ...present(verdict), executed: false, interrupted: false };
321
+ const controller = new globalThis.AbortController();
322
+ let stopped = false;
323
+ const running = {
324
+ organisationId: call.organisationId ?? null,
325
+ interrupt(code) { if (stopped) return; stopped = true; controller.abort(new GovernorError(code, 'The tool call was cut by the emergency stop.')); }
326
+ };
327
+ active.add(running);
328
+ const outer = call.signal;
329
+ const onOuter = () => controller.abort(outer.reason);
330
+ if (outer) { if (outer.aborted) onOuter(); else outer.addEventListener('abort', onOuter, { once: true }); }
331
+ let timer = null;
332
+ if (pollMs > 0) {
333
+ let reading = false;
334
+ timer = setInterval(async () => {
335
+ if (reading) return;
336
+ reading = true;
337
+ try { if ((await haltState(running.organisationId)).halted) running.interrupt(TOOL_REASONS.HALTED); } catch (_error) { running.interrupt(TOOL_REASONS.HALTED); } finally { reading = false; }
338
+ }, pollMs);
339
+ timer.unref?.();
340
+ }
341
+ const outcome = async (kind, extra = {}) => audit({
342
+ action: 'tool_outcome', organisationId: call.organisationId ?? null, actor: actorOf(call.actor), tool: verdict.tool, family: verdict.family, level: verdict.level,
343
+ decision: kind, reasons: extra.reason ? [extra.reason] : [], decisionAuditId: verdict.auditId
344
+ });
345
+ try {
346
+ /* The stop may have been pulled between the decision and now. */
347
+ if ((await haltState(running.organisationId)).halted) running.interrupt(TOOL_REASONS.HALTED);
348
+ const result = await raceAbort(Promise.resolve().then(() => fn(verdict.input, { signal: controller.signal, decision: present(verdict) })), controller.signal);
349
+ await outcome('ok');
350
+ return { ...present(verdict), executed: true, interrupted: false, result };
351
+ } catch (error) {
352
+ if (stopped) {
353
+ await outcome('interrupted', { reason: TOOL_REASONS.HALTED });
354
+ return { ...present({ ...verdict, allowed: false, decision: TOOL_DECISIONS.REFUSED, code: TOOL_REASONS.HALTED }), executed: false, interrupted: true };
355
+ }
356
+ if (outer?.aborted) { await outcome('aborted'); throw error; }
357
+ await outcome('error', { reason: String(error?.name ?? 'Error').slice(0, 100) });
358
+ throw error;
359
+ } finally {
360
+ if (timer) clearInterval(timer);
361
+ outer?.removeEventListener('abort', onOuter);
362
+ active.delete(running);
363
+ }
364
+ }
365
+
366
+ /** Tools the model may be offered: none when stopped or disabled, else those whose family is on. */
367
+ async function availableTools(call = {}) {
368
+ try {
369
+ if ((await haltState(call.organisationId ?? null)).halted) return [];
370
+ const settings = await currentSettings(call);
371
+ if (settings.enabled === false) return [];
372
+ return [...tools.values()].filter((tool) => settings.families[tool.family] !== false).map((tool) => tool.name);
373
+ } catch (_error) { return []; }
374
+ }
375
+
376
+ const describe = () => [...tools.values()].map((tool) => ({
377
+ name: tool.name, family: tool.family, level: levelWords.toApp[tool.level], maxPerRun: tool.maxPerRun, estimatedCost: tool.estimatedCost, budgetExempt: tool.budgetExempt
378
+ }));
379
+
380
+ return Object.freeze({
381
+ version, createRun, decide, execute, availableTools, listTools: describe,
382
+ halt: (opts) => control(true, opts),
383
+ resume: (opts) => control(false, opts),
384
+ isHalted: async (organisationId) => (await haltState(organisationId ?? null)).halted,
385
+ /** Counts what a call really consumed (idempotent on id). Needs a budget. */
386
+ recordSpend: (spend = {}) => {
387
+ if (!budget) throw new GovernorError('budget_invalid', 'This tool policy has no budget.');
388
+ return budget.record({ ...spend, scope: spend.scope ?? spend.organisationId ?? undefined });
389
+ },
390
+ budgetStatus: (query = {}) => {
391
+ if (!budget) throw new GovernorError('budget_invalid', 'This tool policy has no budget.');
392
+ return budget.check({ ...query, scope: query.scope ?? query.organisationId ?? undefined });
393
+ },
394
+ listAudit: (filter = {}) => store.listAudit(filter)
395
+ });
396
+ }
397
+
398
+ module.exports = { createToolPolicy, TOOL_LEVELS, TOOL_DECISIONS, TOOL_REASONS };