@astratra/conscience 1.3.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
@@ -178,7 +178,9 @@ await policy.recordSpend({ id: 'appel-42', amount: 120 }); // unités entières
178
178
  ```
179
179
 
180
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
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
182
184
  (`run.markUntrusted()` ou `untrusted: true` sur l'appel) : il est alors `pending` ;
183
185
  `sensitive` est toujours `pending`. La politique n'exécute jamais un appel en attente :
184
186
  l'application le garde et une personne décide.
@@ -203,7 +205,11 @@ await policy.recordSpend({ id: 'appel-42', amount: 120 }); // unités entières
203
205
  idempotente, bigint), ou le vôtre `{ getSpent(scope, period), addSpend({ scope,
204
206
  period, id, amount, at }) }` (idempotent par id). La portée est `organisationId`
205
207
  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.
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.
207
213
  - **Arrêt d'urgence** : `halt({ by, reason, organisationId? })` est lu avant chaque
208
214
  appel et pendant l'exécution d'un outil. `execute()` donne à l'outil un `AbortSignal`
209
215
  qui s'annule aussitôt pour un arrêt dans ce processus, et sous `pollMs` (1 s par défaut)
@@ -211,7 +217,11 @@ await policy.recordSpend({ id: 'appel-42', amount: 120 }); // unités entières
211
217
  ignore le signal (`interrupted: true`). `activateRoles` le tirent (par défaut : toute
212
218
  personne identifiée), `releaseRoles` le lèvent (par défaut : tout humain ; un acteur
213
219
  `model` ou `engine` jamais). L'option `governor` fait aussi arrêter les outils par
214
- l'interrupteur du gouverneur.
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.
215
225
  - **Audit** : chaque décision est écrite dans le journal du gouverneur avant d'être
216
226
  rendue (`tool_decision` : qui, outil, famille, niveau, décision, motifs, empreinte de
217
227
  l'entrée, jamais l'entrée brute), plus `tool_outcome`, `tool_halt`, `tool_resume` et
package/README.md CHANGED
@@ -172,7 +172,9 @@ await policy.recordSpend({ id: 'call-42', amount: 120 }); // whole units (cents)
172
172
  ```
173
173
 
174
174
  - **Levels** (`TOOL_LEVELS`): `read` runs; `controlled` runs unless it is over its
175
- own `overThreshold(input, settings)`, or the run read untrusted content
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
176
178
  (`run.markUntrusted()` or `untrusted: true` on the call), then it is `pending`;
177
179
  `sensitive` is always `pending`. The policy never runs a pending call: the
178
180
  application keeps it and a person decides.
@@ -198,6 +200,10 @@ await policy.recordSpend({ id: 'call-42', amount: 120 }); // whole units (cents)
198
200
  period), addSpend({ scope, period, id, amount, at }) }` (idempotent by id).
199
201
  The scope is `organisationId` by default. The cap is reached when
200
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.
201
207
  - **Emergency stop**: `halt({ by, reason, organisationId? })` is read before
202
208
  each call and while a tool runs. `execute()` gives the tool an `AbortSignal`
203
209
  that aborts at once on a stop in this process, and within `pollMs` (default
@@ -205,7 +211,11 @@ await policy.recordSpend({ id: 'call-42', amount: 120 }); // whole units (cents)
205
211
  tool ignores the signal (`interrupted: true`). `activateRoles` pull it
206
212
  (default: anyone with an id), `releaseRoles` lift it (default: any human; a
207
213
  `model` or `engine` actor never can). A `governor` option makes the governor
208
- kill switch stop the tools too.
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.
209
219
  - **Audit**: every decision is written to the governor journal before it is
210
220
  returned (`tool_decision`: who, tool, family, level, decision, reasons, input
211
221
  fingerprint, never the raw input), plus `tool_outcome`, `tool_halt`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/conscience",
3
- "version": "1.3.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"
@@ -62,13 +62,16 @@ function createMemoryToolBudgetStore() {
62
62
  /**
63
63
  * Calendar budget over a store { getSpent(scope, period), addSpend({ scope,
64
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.
65
66
  */
66
67
  function createCalendarBudget(options = {}) {
67
68
  const { period = 'month', timeZone = 'UTC', scope: defaultScope = 'default', limit: defaultLimit } = options;
68
69
  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
- }
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().');
72
75
  if (defaultLimit !== undefined && defaultLimit !== null && !isAmount(defaultLimit)) throw new GovernorError('budget_invalid', 'limit must be an integer >= 0.');
73
76
  const now = options.now ?? Date.now;
74
77
  calendarPeriodKey(now(), { period, timeZone }); // fails now, not at the first call, on a wrong period or time zone
@@ -87,6 +90,7 @@ function createCalendarBudget(options = {}) {
87
90
 
88
91
  /** Counts a consumption in the period of its instant. `id` makes the call safe to repeat. */
89
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.');
90
94
  if (!isAmount(amount)) throw new GovernorError('budget_invalid', 'amount must be an integer >= 0 (whole units, no fractions).');
91
95
  if (!isNonEmptyString(id)) throw new GovernorError('budget_invalid', 'A consumption needs a stable id (idempotency).');
92
96
  const instant = at ?? now();
@@ -95,7 +99,7 @@ function createCalendarBudget(options = {}) {
95
99
  return { added: result.added, scope, period: key, spent: result.spent };
96
100
  }
97
101
 
98
- return Object.freeze({ check, record, periodKey: keyOf, period: typeof period === 'function' ? 'custom' : period, timeZone });
102
+ return Object.freeze({ check, record, readOnly, periodKey: keyOf, period: typeof period === 'function' ? 'custom' : period, timeZone });
99
103
  }
100
104
 
101
105
  module.exports = { PERIODS, calendarPeriodKey, createMemoryToolBudgetStore, createCalendarBudget, isAmount };
@@ -416,9 +416,10 @@ export interface ToolDefinition {
416
416
  /** One of the level words (the canonical ones, or yours when labels.levels renames them). */
417
417
  level: string;
418
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;
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>;
422
423
  /** At most this many calls of the tool in one run; the next ones are refused (cap_reached). */
423
424
  maxPerRun?: number;
424
425
  /** Whole units this call is expected to consume: refused up front when it cannot fit in the budget. */
@@ -499,6 +500,10 @@ export interface ToolPolicyOptions {
499
500
  store?: Pick<GovernorStore, 'appendAudit' | 'listAudit' | 'getControl' | 'setControl'>;
500
501
  /** A governor whose kill switch also stops the tools. */
501
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>);
502
507
  version?: string;
503
508
  /** How often a running tool looks at the kill switch pulled by another process (default 1000, 0 = off). */
504
509
  pollMs?: number;
@@ -534,8 +539,9 @@ export interface BudgetStanding {
534
539
  /** spent/limit/remaining are whole units of your choice (cents, thousandths of cents, tokens...). No fractions. */
535
540
  export interface ToolBudgetStore {
536
541
  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 }>;
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 }>;
539
545
  }
540
546
  export interface CalendarBudgetOptions {
541
547
  /** 'month' (default), 'day', or a function (instant, timeZone) => key. */
@@ -546,6 +552,8 @@ export interface CalendarBudgetOptions {
546
552
  limit?: number | null;
547
553
  scope?: string;
548
554
  store?: ToolBudgetStore;
555
+ /** Asserts the store has no addSpend() (a store with getSpent() only is read-only anyway). */
556
+ readOnly?: boolean;
549
557
  now?(): number;
550
558
  }
551
559
  export interface CalendarBudget {
@@ -553,6 +561,8 @@ export interface CalendarBudget {
553
561
  record(spend: { id: string; amount: number; scope?: string; at?: number | Date }): Promise<{ added: boolean; scope: string; period: string; spent: number }>;
554
562
  periodKey(at?: number | Date): string;
555
563
  readonly period: string; readonly timeZone: string;
564
+ /** true when the store has getSpent() only. */
565
+ readonly readOnly: boolean;
556
566
  }
557
567
  export function createCalendarBudget(options?: CalendarBudgetOptions): CalendarBudget;
558
568
  /** "2026-10" (month) or "2026-10-31" (day) of an instant, in a time zone. */
@@ -102,7 +102,7 @@ const hasRole = (actor, roles) => actor.roles.some((role) => roles.includes(role
102
102
  /**
103
103
  * Builds the tool policy.
104
104
  * options: tools, families?, defaults?, settings?, budget?, emergency?, labels?, untrustedPendingLevels?,
105
- * store?, governor?, version?, pollMs?, now?, idFactory?, onEvent?
105
+ * store?, governor?, isHalted?, version?, pollMs?, now?, idFactory?, onEvent?
106
106
  */
107
107
  function createToolPolicy(options = {}) {
108
108
  if (!isObject(options)) fail('options must be an object.');
@@ -143,6 +143,10 @@ function createToolPolicy(options = {}) {
143
143
  if (budget && typeof budget.record !== 'function') fail('budget must have check() and record().');
144
144
  const governor = options.governor ?? null;
145
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.');
146
150
 
147
151
  const active = new Set();
148
152
  const iso = () => new Date(now()).toISOString();
@@ -162,6 +166,11 @@ function createToolPolicy(options = {}) {
162
166
  if (local?.halted) return { halted: true, scope: organisationId, reason: local.reason ?? null };
163
167
  }
164
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
+ }
165
174
  return { halted: false };
166
175
  }
167
176
 
@@ -193,7 +202,7 @@ function createToolPolicy(options = {}) {
193
202
  let input = call.input ?? {};
194
203
  if (tool.validate) {
195
204
  let verdict;
196
- try { verdict = tool.validate(input); } catch (_error) { verdict = false; }
205
+ try { verdict = await tool.validate(input); } catch (_error) { verdict = false; }
197
206
  if (verdict === false || (isObject(verdict) && verdict.ok === false)) return refuse(TOOL_REASONS.INVALID_INPUT);
198
207
  if (isObject(verdict) && verdict.ok === true && 'value' in verdict) input = verdict.value;
199
208
  }
@@ -215,7 +224,8 @@ function createToolPolicy(options = {}) {
215
224
  if ((run.untrusted || call.untrusted === true) && untrustedLevels.includes(tool.level)) return pending(TOOL_REASONS.UNTRUSTED);
216
225
  if (tool.level === TOOL_LEVELS.CONTROLLED && tool.overThreshold) {
217
226
  let over = false;
218
- try { over = tool.overThreshold(input, settings) === true; } catch (_error) { over = true; }
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; }
219
229
  if (over) return pending(TOOL_REASONS.THRESHOLD);
220
230
  }
221
231
  return { decision: TOOL_DECISIONS.ALLOWED, code: null, input, budget: standing };