hmcp-core 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -3
- package/dist/approvals.d.ts +508 -0
- package/dist/approvals.js +1445 -0
- package/dist/argpath.d.ts +75 -0
- package/dist/argpath.js +189 -0
- package/dist/audit.d.ts +289 -0
- package/dist/audit.js +512 -0
- package/dist/canonical.d.ts +78 -0
- package/dist/canonical.js +146 -0
- package/dist/classify-held.d.ts +47 -0
- package/dist/classify-held.js +60 -0
- package/dist/classify-name.d.ts +55 -0
- package/dist/classify-name.js +255 -0
- package/dist/decide.d.ts +168 -0
- package/dist/decide.js +518 -0
- package/dist/egress.d.ts +123 -0
- package/dist/egress.js +544 -0
- package/dist/enforce.d.ts +78 -0
- package/dist/enforce.js +231 -0
- package/dist/exposure-apply.d.ts +51 -0
- package/dist/exposure-apply.js +69 -0
- package/dist/exposure.d.ts +81 -0
- package/dist/exposure.js +65 -0
- package/dist/file-lock.d.ts +70 -0
- package/dist/file-lock.js +165 -0
- package/dist/glob.d.ts +11 -0
- package/dist/glob.js +55 -0
- package/dist/grants.d.ts +204 -0
- package/dist/grants.js +372 -0
- package/dist/http-util.d.ts +52 -0
- package/dist/http-util.js +81 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +36 -0
- package/dist/inventory.d.ts +100 -0
- package/dist/inventory.js +88 -0
- package/dist/ip.d.ts +15 -0
- package/dist/ip.js +186 -0
- package/dist/jwt.d.ts +57 -0
- package/dist/jwt.js +199 -0
- package/dist/live-state.d.ts +76 -0
- package/dist/live-state.js +57 -0
- package/dist/migrate.d.ts +22 -0
- package/dist/migrate.js +318 -0
- package/dist/pins.d.ts +119 -0
- package/dist/pins.js +125 -0
- package/dist/policy-batch.d.ts +89 -0
- package/dist/policy-batch.js +340 -0
- package/dist/policy-source.d.ts +161 -0
- package/dist/policy-source.js +299 -0
- package/dist/policy-write.d.ts +627 -0
- package/dist/policy-write.js +1697 -0
- package/dist/policy.d.ts +456 -0
- package/dist/policy.js +448 -0
- package/dist/redact.d.ts +65 -0
- package/dist/redact.js +191 -0
- package/dist/registry.d.ts +41 -0
- package/dist/registry.js +121 -0
- package/dist/remember-defaults.d.ts +9 -0
- package/dist/remember-defaults.js +9 -0
- package/dist/remember.d.ts +91 -0
- package/dist/remember.js +371 -0
- package/dist/resolve.d.ts +22 -0
- package/dist/resolve.js +34 -0
- package/dist/runtime-state.d.ts +65 -0
- package/dist/runtime-state.js +35 -0
- package/dist/secrets.d.ts +159 -0
- package/dist/secrets.js +361 -0
- package/dist/tenant.d.ts +83 -0
- package/dist/tenant.js +182 -0
- package/dist/unicode.d.ts +40 -0
- package/dist/unicode.js +103 -0
- package/dist/within-host.d.ts +33 -0
- package/dist/within-host.js +91 -0
- package/dist/within-real.d.ts +7 -0
- package/dist/within-real.js +28 -0
- package/package.json +33 -4
|
@@ -0,0 +1,1445 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import { chmodSync, existsSync, mkdirSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { randomBytes } from "node:crypto";
|
|
5
|
+
import { BINDING_VERSION, callBindings } from "./canonical.js";
|
|
6
|
+
import { UNCLASSIFIED_RULE } from "./decide.js";
|
|
7
|
+
import { redactArgs } from "./redact.js";
|
|
8
|
+
import { EffectSchema, expandPath } from "./policy.js";
|
|
9
|
+
import { GRANTS_SCHEMA, grantBoundsArgs, grantMatches, newGrantId } from "./grants.js";
|
|
10
|
+
import { EXPOSURE_SCHEMA } from "./exposure.js";
|
|
11
|
+
import { migrate } from "./migrate.js";
|
|
12
|
+
import { RUNTIME_STATE_SCHEMA, RUNTIME_STATE_TTL_MS } from "./runtime-state.js";
|
|
13
|
+
import { GATEWAY_PINNER, TOOL_CHANGE_SCHEMA, TOOL_PIN_SCHEMA } from "./pins.js";
|
|
14
|
+
import { REMEMBER_DEFAULT_USES } from "./remember-defaults.js";
|
|
15
|
+
import { LIVE_STATE_SQL, LIVE_STATE_STALE_MS, liveStateFresh } from "./live-state.js";
|
|
16
|
+
import { TOOL_INVENTORY_SCHEMA } from "./inventory.js";
|
|
17
|
+
function parseContract(text) {
|
|
18
|
+
if (!text)
|
|
19
|
+
return null;
|
|
20
|
+
try {
|
|
21
|
+
const parsed = JSON.parse(text);
|
|
22
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function encodeViolations(violations) {
|
|
29
|
+
return violations && violations.length > 0 ? JSON.stringify(violations) : null;
|
|
30
|
+
}
|
|
31
|
+
/** Decodes the recorded violations. An unreadable value reads as none. */
|
|
32
|
+
export function approvalViolations(row) {
|
|
33
|
+
if (!row.violations)
|
|
34
|
+
return [];
|
|
35
|
+
try {
|
|
36
|
+
const parsed = JSON.parse(row.violations);
|
|
37
|
+
return Array.isArray(parsed) ? parsed.filter((v) => typeof v === "string") : [];
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const SCHEMA = `
|
|
44
|
+
CREATE TABLE IF NOT EXISTS approvals (
|
|
45
|
+
id TEXT PRIMARY KEY,
|
|
46
|
+
component TEXT NOT NULL DEFAULT '',
|
|
47
|
+
tenant TEXT NOT NULL DEFAULT '',
|
|
48
|
+
created_at INTEGER NOT NULL,
|
|
49
|
+
expires_at INTEGER NOT NULL,
|
|
50
|
+
tool TEXT NOT NULL,
|
|
51
|
+
effect TEXT,
|
|
52
|
+
binding_hash TEXT NOT NULL,
|
|
53
|
+
args_redacted TEXT NOT NULL,
|
|
54
|
+
reason TEXT NOT NULL,
|
|
55
|
+
actor TEXT NOT NULL,
|
|
56
|
+
session TEXT NOT NULL,
|
|
57
|
+
state TEXT NOT NULL,
|
|
58
|
+
decided_at INTEGER,
|
|
59
|
+
decided_by TEXT,
|
|
60
|
+
decision_note TEXT,
|
|
61
|
+
violations TEXT,
|
|
62
|
+
rule_id TEXT,
|
|
63
|
+
policy_digest TEXT,
|
|
64
|
+
-- 1 for a row written before the framing changed. Never defaulted into a new
|
|
65
|
+
-- row: the inserts below set it explicitly.
|
|
66
|
+
binding_version INTEGER NOT NULL DEFAULT 1,
|
|
67
|
+
-- JSON array of argument paths that broke a bound; NULL when not recorded.
|
|
68
|
+
held_args TEXT
|
|
69
|
+
);
|
|
70
|
+
CREATE INDEX IF NOT EXISTS approvals_binding ON approvals (component, tenant, binding_hash, state);
|
|
71
|
+
CREATE INDEX IF NOT EXISTS approvals_state ON approvals (component, tenant, state, created_at);
|
|
72
|
+
`;
|
|
73
|
+
export function newApprovalId() {
|
|
74
|
+
return `apr_${randomBytes(6).toString("hex")}`;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Durable store for approval requests and grants. Backed by the built-in
|
|
78
|
+
* `node:sqlite` so there is no native dependency to compile, and so an
|
|
79
|
+
* out-of-band CLI in a separate process can see what a server is waiting on.
|
|
80
|
+
*/
|
|
81
|
+
/**
|
|
82
|
+
* Durable store for approval requests and grants. Backed by the built-in
|
|
83
|
+
* `node:sqlite` so there is no native dependency to compile, and so an
|
|
84
|
+
* out-of-band CLI in a separate process can see what a server is waiting on.
|
|
85
|
+
*
|
|
86
|
+
* One database holds rows for many servers and many tenants: the default
|
|
87
|
+
* `store_path` is shared, and a hosted gateway serves every tenant from one
|
|
88
|
+
* process. So almost nothing a caller wants to do belongs on this class.
|
|
89
|
+
* `scoped()` hands back the view that does, bound to one component and one
|
|
90
|
+
* tenant, and that is where every query a call path makes now lives.
|
|
91
|
+
*
|
|
92
|
+
* What stays here is the handle, the lifecycle, and the three operations that
|
|
93
|
+
* are legitimately about the whole file: the expiry janitor, an unfiltered
|
|
94
|
+
* read for an operator, and the list of scopes present. Each of those is named
|
|
95
|
+
* so that reaching for it is a decision rather than an accident — which is the
|
|
96
|
+
* point of having moved the rest out, and the reason none of the moved methods
|
|
97
|
+
* were left behind as delegates.
|
|
98
|
+
*/
|
|
99
|
+
/** How long to wait for another process before giving up on a locked database. */
|
|
100
|
+
const BUSY_TIMEOUT_MS = 5000;
|
|
101
|
+
/**
|
|
102
|
+
* Puts the database in WAL mode, which is what lets a gateway and the console
|
|
103
|
+
* use one file at the same time.
|
|
104
|
+
*
|
|
105
|
+
* This is three lines of care around one pragma, and each line is a failure
|
|
106
|
+
* that was reachable from a cold start:
|
|
107
|
+
*
|
|
108
|
+
* - **Skip the switch when it is already WAL.** Converting takes an
|
|
109
|
+
* *exclusive* lock on the database; staying in WAL needs no lock at all.
|
|
110
|
+
* Since the mode is persistent, only the process that creates the file
|
|
111
|
+
* ever needs to convert it, so checking first removes the contention
|
|
112
|
+
* entirely for every process after the first -- which is every process, in
|
|
113
|
+
* practice.
|
|
114
|
+
*
|
|
115
|
+
* - **Retry while another process holds the file.** A `busy_timeout` makes
|
|
116
|
+
* SQLite wait out a *reader*, but it does not cover a conversion blocked
|
|
117
|
+
* by another connection's write lock: that fails immediately, timeout or
|
|
118
|
+
* not. The retry is what makes two processes creating the database at the
|
|
119
|
+
* same moment work rather than work most of the time.
|
|
120
|
+
*
|
|
121
|
+
* - **Say what happened if it still fails.** `database is locked` thrown
|
|
122
|
+
* from a constructor tells an operator nothing about which file, which
|
|
123
|
+
* process, or what to do.
|
|
124
|
+
*
|
|
125
|
+
* WAL is not optional here. Falling back to the default journal would let the
|
|
126
|
+
* store open while quietly serializing the console against every running
|
|
127
|
+
* gateway, so a failure to convert is reported rather than absorbed.
|
|
128
|
+
*/
|
|
129
|
+
function enableWal(db, path, budgetMs) {
|
|
130
|
+
if (journalMode(db) === "wal")
|
|
131
|
+
return;
|
|
132
|
+
const deadline = Date.now() + budgetMs;
|
|
133
|
+
let lastError;
|
|
134
|
+
for (;;) {
|
|
135
|
+
try {
|
|
136
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
catch (err) {
|
|
140
|
+
lastError = err;
|
|
141
|
+
/*
|
|
142
|
+
* A file whose first bytes are not a SQLite header will never become
|
|
143
|
+
* one. Retrying spends the whole budget and then reports contention,
|
|
144
|
+
* which is the one explanation that is certainly wrong -- and sends
|
|
145
|
+
* whoever typed the path hunting for a process that does not exist.
|
|
146
|
+
*/
|
|
147
|
+
if (notADatabase(lastError))
|
|
148
|
+
throw new NotADatabase(describeNotADatabase(path));
|
|
149
|
+
// Another process may have converted it while we were failing to.
|
|
150
|
+
if (journalMode(db) === "wal")
|
|
151
|
+
return;
|
|
152
|
+
if (Date.now() >= deadline)
|
|
153
|
+
break;
|
|
154
|
+
sleepSync(25);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
throw new Error(`could not put the approvals database at ${path} into WAL mode within ${budgetMs}ms: ` +
|
|
158
|
+
`${lastError?.message ?? "unknown error"}. Another process is holding it; if none is running, ` +
|
|
159
|
+
`check for a stale lock beside that file.`);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* A store path that holds something other than a SQLite database.
|
|
163
|
+
*
|
|
164
|
+
* Its own class so a caller can report it as a message rather than a stack
|
|
165
|
+
* trace: it is a mistyped path, not a fault in the program.
|
|
166
|
+
*/
|
|
167
|
+
export class NotADatabase extends Error {
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* True when SQLite is saying the file is not a database.
|
|
171
|
+
*
|
|
172
|
+
* Matched on the code where the binding provides one and on the message
|
|
173
|
+
* otherwise, because the message is the only signal `node:sqlite` has carried
|
|
174
|
+
* in some versions and a wrong guess here reinstates the five-second wait.
|
|
175
|
+
*/
|
|
176
|
+
function notADatabase(err) {
|
|
177
|
+
const code = err.code;
|
|
178
|
+
if (typeof code === "string" && code.includes("SQLITE_NOTADB"))
|
|
179
|
+
return true;
|
|
180
|
+
return /not a database|file is encrypted/i.test(err.message);
|
|
181
|
+
}
|
|
182
|
+
function describeNotADatabase(path) {
|
|
183
|
+
return (`${path} is not a SQLite database. Nothing was changed. SQLite reads the first bytes of a ` +
|
|
184
|
+
`file to recognise one, and these are something else -- so this is a path that points at the ` +
|
|
185
|
+
`wrong file rather than a store that needs repairing. Check the path, or point --store at the ` +
|
|
186
|
+
`database your gateway is using (by default ~/.hmcp/approvals.sqlite).`);
|
|
187
|
+
}
|
|
188
|
+
function journalMode(db) {
|
|
189
|
+
try {
|
|
190
|
+
const row = db.prepare("PRAGMA journal_mode").get();
|
|
191
|
+
return String(row?.journal_mode ?? "").toLowerCase();
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
return "";
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Blocks this thread. Deliberately, and only here: opening the store is
|
|
199
|
+
* synchronous by the time anything calls it, so there is no event loop to
|
|
200
|
+
* yield to and a timer would not help. `Atomics.wait` sleeps without burning
|
|
201
|
+
* the CPU the way a spin loop would.
|
|
202
|
+
*/
|
|
203
|
+
function sleepSync(ms) {
|
|
204
|
+
const shared = new Int32Array(new SharedArrayBuffer(4));
|
|
205
|
+
Atomics.wait(shared, 0, 0, ms);
|
|
206
|
+
}
|
|
207
|
+
export class ApprovalStore {
|
|
208
|
+
db;
|
|
209
|
+
path;
|
|
210
|
+
constructor(path, cwd = process.cwd(), options = {}) {
|
|
211
|
+
const busyTimeoutMs = options.busyTimeoutMs ?? BUSY_TIMEOUT_MS;
|
|
212
|
+
this.path = path === ":memory:" ? path : expandPath(path, cwd);
|
|
213
|
+
/*
|
|
214
|
+
* Private to its owner, like the audit log beside it. This file holds the
|
|
215
|
+
* redacted arguments of every held call and what reviewers typed about
|
|
216
|
+
* them. Only on creation: an existing file's mode is someone's decision,
|
|
217
|
+
* and a store deliberately shared between accounts must keep working.
|
|
218
|
+
* SQLite gives the -wal and -shm files the mode of the database itself.
|
|
219
|
+
*/
|
|
220
|
+
const created = this.path !== ":memory:" && !existsSync(this.path);
|
|
221
|
+
if (this.path !== ":memory:")
|
|
222
|
+
mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
|
|
223
|
+
this.db = new DatabaseSync(this.path);
|
|
224
|
+
if (created) {
|
|
225
|
+
try {
|
|
226
|
+
chmodSync(this.path, 0o600);
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
/* a filesystem without modes; nothing to tighten */
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
/*
|
|
233
|
+
* The busy timeout is set before anything that can take a lock, including
|
|
234
|
+
* the journal-mode switch below. A `PRAGMA busy_timeout` applies only from
|
|
235
|
+
* the moment it is set, so a statement issued ahead of it gets no timeout
|
|
236
|
+
* at all -- which is the difference between waiting for another process
|
|
237
|
+
* and failing in front of the user.
|
|
238
|
+
*/
|
|
239
|
+
this.db.exec(`PRAGMA busy_timeout = ${busyTimeoutMs}`);
|
|
240
|
+
enableWal(this.db, this.path, busyTimeoutMs);
|
|
241
|
+
// After the pragmas, so a migration runs with WAL and the busy timeout
|
|
242
|
+
// already in force: it takes the write lock, and a second process opening
|
|
243
|
+
// the same file concurrently waits rather than failing.
|
|
244
|
+
migrate(this.db, (db) => {
|
|
245
|
+
db.exec(SCHEMA);
|
|
246
|
+
db.exec(GRANTS_SCHEMA);
|
|
247
|
+
db.exec(EXPOSURE_SCHEMA);
|
|
248
|
+
db.exec(RUNTIME_STATE_SCHEMA);
|
|
249
|
+
db.exec(TOOL_INVENTORY_SCHEMA);
|
|
250
|
+
db.exec(TOOL_PIN_SCHEMA);
|
|
251
|
+
db.exec(TOOL_CHANGE_SCHEMA);
|
|
252
|
+
});
|
|
253
|
+
/*
|
|
254
|
+
* Outside the versioned migrations on purpose. These two tables hold
|
|
255
|
+
* nothing but what running processes say about themselves right now, so a
|
|
256
|
+
* database that lacks them has lost nothing, and `IF NOT EXISTS` on every
|
|
257
|
+
* open is the whole upgrade. Bumping the schema version for them would
|
|
258
|
+
* make every older build refuse to open the shared store -- a console and
|
|
259
|
+
* a gateway from different releases could no longer run side by side --
|
|
260
|
+
* for tables neither of them depends on.
|
|
261
|
+
*/
|
|
262
|
+
this.db.exec(LIVE_STATE_SQL);
|
|
263
|
+
this.db.exec(LIVE_REQUEST_SEEN_SQL);
|
|
264
|
+
}
|
|
265
|
+
close() {
|
|
266
|
+
this.db.close();
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* The view a call path works through: every query below is filtered to one
|
|
270
|
+
* component and one tenant, by the database rather than by the caller
|
|
271
|
+
* remembering to.
|
|
272
|
+
*/
|
|
273
|
+
scoped(scope) {
|
|
274
|
+
return new ScopedApprovals(this.db, scope);
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Marks every past-due pending or granted row expired, across every scope.
|
|
278
|
+
*
|
|
279
|
+
* Deliberately unscoped: expiry is a property of the clock, not of who owns
|
|
280
|
+
* the row, and a tenant whose server never runs again should not keep a
|
|
281
|
+
* stale "pending" row for ever because nobody swept their scope.
|
|
282
|
+
*/
|
|
283
|
+
expireStale(now = Date.now()) {
|
|
284
|
+
const stmt = this.db.prepare("UPDATE approvals SET state = 'expired' WHERE expires_at <= ? AND state IN ('pending','granted')");
|
|
285
|
+
return Number(stmt.run(now).changes);
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Every waiting request in the file, whoever it belongs to.
|
|
289
|
+
*
|
|
290
|
+
* For an operator looking at the database as a database — draining rows left
|
|
291
|
+
* by a server that no longer exists, or the ones a pre-scoping version wrote
|
|
292
|
+
* under ("",""). Not for a call path: `scoped(...).listPending()` is.
|
|
293
|
+
*/
|
|
294
|
+
listPendingAll(limit = 50) {
|
|
295
|
+
this.expireStale();
|
|
296
|
+
return this.db
|
|
297
|
+
.prepare("SELECT * FROM approvals WHERE state = 'pending' ORDER BY created_at ASC LIMIT ?")
|
|
298
|
+
.all(limit)
|
|
299
|
+
.map((r) => ({ ...r }));
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Every request in the file, decided or not, newest first.
|
|
303
|
+
*
|
|
304
|
+
* The operator counterpart to `scoped(...).list()`. An `hmcp` at a terminal
|
|
305
|
+
* has a policy file and a database path and no idea which component it is
|
|
306
|
+
* standing in front of, so scoping it by default would mean scoping it to a
|
|
307
|
+
* guess. It shows the scope on each row instead.
|
|
308
|
+
*/
|
|
309
|
+
listAll(limit = 50) {
|
|
310
|
+
return this.db
|
|
311
|
+
.prepare("SELECT * FROM approvals ORDER BY created_at DESC LIMIT ?")
|
|
312
|
+
.all(limit)
|
|
313
|
+
.map((r) => ({ ...r }));
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* One request by id, whatever scope it is in.
|
|
317
|
+
*
|
|
318
|
+
* Safe to be unscoped because the id is the primary key, so there is nothing
|
|
319
|
+
* to confuse it with, and because anyone who can call this already has the
|
|
320
|
+
* database file open — scoping an operator tool against someone holding the
|
|
321
|
+
* file would be theatre. The enforcement path never uses it; it has
|
|
322
|
+
* `scoped(...).get()`, which cannot reach another tenant's row.
|
|
323
|
+
*/
|
|
324
|
+
getAny(id) {
|
|
325
|
+
const row = this.db.prepare("SELECT * FROM approvals WHERE id = ?").get(id);
|
|
326
|
+
return row ? { ...row } : undefined;
|
|
327
|
+
}
|
|
328
|
+
/** An operator's decision on any parked request, by id. */
|
|
329
|
+
decideAny(id, state, by, note = "") {
|
|
330
|
+
this.expireStale();
|
|
331
|
+
const changes = Number(this.db
|
|
332
|
+
.prepare(`UPDATE approvals SET state = ?, decided_at = ?, decided_by = ?, decision_note = ?
|
|
333
|
+
WHERE id = ? AND state = 'pending'`)
|
|
334
|
+
.run(state, Date.now(), by, note, id).changes);
|
|
335
|
+
return changes > 0 ? this.getAny(id) : undefined;
|
|
336
|
+
}
|
|
337
|
+
/** Which (component, tenant) pairs have rows here, for an operator view. */
|
|
338
|
+
listScopes() {
|
|
339
|
+
return this.db
|
|
340
|
+
.prepare(`SELECT component, tenant FROM approvals
|
|
341
|
+
UNION
|
|
342
|
+
SELECT component, tenant FROM standing_grants
|
|
343
|
+
UNION
|
|
344
|
+
SELECT component, tenant FROM tool_exposure
|
|
345
|
+
ORDER BY component, tenant`)
|
|
346
|
+
.all()
|
|
347
|
+
.map((r) => ({ ...r }));
|
|
348
|
+
}
|
|
349
|
+
// ---- runtime state ---------------------------------------------------
|
|
350
|
+
//
|
|
351
|
+
// Not scoped, and not an oversight: these columns describe an operating
|
|
352
|
+
// system process -- its pid, when it started, when it last checked in, and
|
|
353
|
+
// the digest of the policy it parsed. One hosted process serves every
|
|
354
|
+
// tenant, so there is one row per component and a tenant column would be
|
|
355
|
+
// the wrong axis.
|
|
356
|
+
/**
|
|
357
|
+
* Announces which policy this process is enforcing, replacing any row from a
|
|
358
|
+
* previous run of the same server.
|
|
359
|
+
*
|
|
360
|
+
* One row per component, not per process: two servers sharing a component
|
|
361
|
+
* would be two answers to a question that has one, and the last to start is
|
|
362
|
+
* the better guess. The digest is what the reader actually needs — `pid` and
|
|
363
|
+
* `started_at` are there to make a stale row legible rather than merely wrong.
|
|
364
|
+
*/
|
|
365
|
+
recordRuntimeState(row) {
|
|
366
|
+
const seen = row.last_seen ?? Date.now();
|
|
367
|
+
this.db
|
|
368
|
+
.prepare(`INSERT INTO runtime_state (component, pid, started_at, last_seen, policy_digest, policy_path)
|
|
369
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
370
|
+
ON CONFLICT(component) DO UPDATE SET
|
|
371
|
+
pid = excluded.pid,
|
|
372
|
+
started_at = excluded.started_at,
|
|
373
|
+
last_seen = excluded.last_seen,
|
|
374
|
+
policy_digest = excluded.policy_digest,
|
|
375
|
+
policy_path = excluded.policy_path`)
|
|
376
|
+
.run(row.component, row.pid, row.started_at, seen, row.policy_digest, row.policy_path);
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Marks this server still alive, without touching what it reported.
|
|
380
|
+
*
|
|
381
|
+
* Scoped to the pid that wrote the row so a process that has been superseded
|
|
382
|
+
* cannot keep a live successor's row looking like its own. A row gone stale
|
|
383
|
+
* (its writer stopped beating, so it has exited) is taken over instead:
|
|
384
|
+
* with two app processes on one toolbox, the second one's row replaces the
|
|
385
|
+
* first's, and when the second exits the first must not look dead for good.
|
|
386
|
+
*/
|
|
387
|
+
touchRuntimeState(component, pid, now = Date.now(),
|
|
388
|
+
/** The survivor's own policy, written on a takeover so the row doesn't claim the stopped process's (R2 N6). */
|
|
389
|
+
own) {
|
|
390
|
+
const touched = this.db
|
|
391
|
+
.prepare("UPDATE runtime_state SET last_seen = ? WHERE component = ? AND pid = ?")
|
|
392
|
+
.run(now, component, pid);
|
|
393
|
+
if (Number(touched.changes) > 0)
|
|
394
|
+
return;
|
|
395
|
+
if (own) {
|
|
396
|
+
this.db
|
|
397
|
+
.prepare("UPDATE runtime_state SET pid = ?, last_seen = ?, policy_digest = ?, policy_path = ? WHERE component = ? AND last_seen < ?")
|
|
398
|
+
.run(pid, now, own.policy_digest, own.policy_path, component, now - RUNTIME_STATE_TTL_MS);
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
this.db
|
|
402
|
+
.prepare("UPDATE runtime_state SET pid = ?, last_seen = ? WHERE component = ? AND last_seen < ?")
|
|
403
|
+
.run(pid, now, component, now - RUNTIME_STATE_TTL_MS);
|
|
404
|
+
}
|
|
405
|
+
runtimeState(component) {
|
|
406
|
+
const row = this.db.prepare("SELECT * FROM runtime_state WHERE component = ?").get(component);
|
|
407
|
+
return row ? { ...row } : undefined;
|
|
408
|
+
}
|
|
409
|
+
// ---- tool pins -------------------------------------------------------
|
|
410
|
+
//
|
|
411
|
+
// What each upstream advertised the last time this gateway looked, so a
|
|
412
|
+
// tool that was honest yesterday and is not today can be noticed. Keyed by
|
|
413
|
+
// component, like the inventory: two gateways may front different servers
|
|
414
|
+
// under one tool name, and neither should speak for the other.
|
|
415
|
+
/**
|
|
416
|
+
* Compares a tool's advertised contract against the pin, and records it.
|
|
417
|
+
*
|
|
418
|
+
* Records in every case, including a change: the point is to notice the
|
|
419
|
+
* change once and keep going, not to report it on every start forever. The
|
|
420
|
+
* finding is in the audit log, which is where a record that must not be
|
|
421
|
+
* overwritten belongs.
|
|
422
|
+
*/
|
|
423
|
+
pinTool(component, tool, digest, by = "gateway", now = Date.now(), contract,
|
|
424
|
+
/**
|
|
425
|
+
* Whether a change moves the pin to what was just seen.
|
|
426
|
+
*
|
|
427
|
+
* True where the change is only being reported: the finding is in the
|
|
428
|
+
* audit log, which cannot be overwritten, and repeating it on every start
|
|
429
|
+
* forever is a warning nobody reads.
|
|
430
|
+
*
|
|
431
|
+
* False where something is being withheld until a person accepts it. A
|
|
432
|
+
* pin that advanced on detection would mean the tool was quarantined for
|
|
433
|
+
* the life of one process and served by the next -- and that merely
|
|
434
|
+
* looking at it, with any command that connects, cleared a quarantine
|
|
435
|
+
* nobody had reviewed.
|
|
436
|
+
*/
|
|
437
|
+
advance = true) {
|
|
438
|
+
const row = this.db
|
|
439
|
+
.prepare("SELECT digest, contract, pinned_at, pinned_by FROM tool_pins WHERE component = ? AND tool = ?")
|
|
440
|
+
.get(component, tool);
|
|
441
|
+
if (row?.digest === digest)
|
|
442
|
+
return { kind: "unchanged" };
|
|
443
|
+
const known = row?.digest !== undefined;
|
|
444
|
+
if (known && !advance) {
|
|
445
|
+
let pending;
|
|
446
|
+
if (row.contract) {
|
|
447
|
+
try {
|
|
448
|
+
pending = JSON.parse(row.contract);
|
|
449
|
+
}
|
|
450
|
+
catch {
|
|
451
|
+
pending = undefined;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
return {
|
|
455
|
+
kind: "changed",
|
|
456
|
+
was: row.digest,
|
|
457
|
+
wasContract: pending,
|
|
458
|
+
pinnedAt: row.pinned_at ?? 0,
|
|
459
|
+
pinnedBy: row.pinned_by ?? "unknown"
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
this.db
|
|
463
|
+
.prepare(`INSERT INTO tool_pins (component, tool, digest, contract, pinned_at, pinned_by)
|
|
464
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
465
|
+
ON CONFLICT (component, tool) DO UPDATE SET digest = excluded.digest,
|
|
466
|
+
contract = excluded.contract,
|
|
467
|
+
pinned_at = excluded.pinned_at,
|
|
468
|
+
pinned_by = excluded.pinned_by`)
|
|
469
|
+
.run(component, tool, digest, contract ? JSON.stringify(contract) : null, now, by);
|
|
470
|
+
if (row?.digest === undefined)
|
|
471
|
+
return { kind: "first-seen" };
|
|
472
|
+
/*
|
|
473
|
+
* A pin written by an older build, or one whose stored contract cannot be
|
|
474
|
+
* read, still reports the change. Only the description of *what* changed
|
|
475
|
+
* is lost, and saying so is better than implying this knows.
|
|
476
|
+
*/
|
|
477
|
+
let wasContract;
|
|
478
|
+
if (row.contract) {
|
|
479
|
+
try {
|
|
480
|
+
wasContract = JSON.parse(row.contract);
|
|
481
|
+
}
|
|
482
|
+
catch {
|
|
483
|
+
wasContract = undefined;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return {
|
|
487
|
+
kind: "changed",
|
|
488
|
+
was: row.digest,
|
|
489
|
+
wasContract,
|
|
490
|
+
pinnedAt: row.pinned_at ?? 0,
|
|
491
|
+
pinnedBy: row.pinned_by ?? "unknown"
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Accepts what a tool advertises now as the pin, attributed to a person.
|
|
496
|
+
*
|
|
497
|
+
* Without this the only way to stop a reported change being reported is to
|
|
498
|
+
* let the gateway record it silently, which would mean a reviewer could
|
|
499
|
+
* never say "yes, I looked at that, it is fine" in a way that is written
|
|
500
|
+
* down. Returns whether anything was written.
|
|
501
|
+
*/
|
|
502
|
+
acceptPin(component, tool, digest, by, now = Date.now(), contract) {
|
|
503
|
+
/*
|
|
504
|
+
* A pin already at this digest is left exactly as it is -- who pinned it
|
|
505
|
+
* and when -- unless a gateway has reported a change to this very digest.
|
|
506
|
+
* That is `on_tool_change: warn`: the gateway has already moved the pin to
|
|
507
|
+
* the new digest as it reported it, so the digests match, and the
|
|
508
|
+
* acceptance must still be written, or the pin stays attributed to the
|
|
509
|
+
* gateway as though nobody had looked. Otherwise `pin accept --all` would
|
|
510
|
+
* rewrite every pin that had not changed as the operator's.
|
|
511
|
+
*/
|
|
512
|
+
const row = this.db
|
|
513
|
+
.prepare("SELECT digest FROM tool_pins WHERE component = ? AND tool = ?")
|
|
514
|
+
.get(component, tool);
|
|
515
|
+
if (row?.digest === digest) {
|
|
516
|
+
const reported = this.db
|
|
517
|
+
.prepare("SELECT 1 FROM tool_changes WHERE component = ? AND tool = ? AND digest = ?")
|
|
518
|
+
.get(component, tool, digest);
|
|
519
|
+
if (!reported)
|
|
520
|
+
return false;
|
|
521
|
+
}
|
|
522
|
+
this.db
|
|
523
|
+
.prepare(`INSERT INTO tool_pins (component, tool, digest, contract, pinned_at, pinned_by)
|
|
524
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
525
|
+
ON CONFLICT (component, tool) DO UPDATE SET digest = excluded.digest,
|
|
526
|
+
contract = excluded.contract,
|
|
527
|
+
pinned_at = excluded.pinned_at,
|
|
528
|
+
pinned_by = excluded.pinned_by`)
|
|
529
|
+
.run(component, tool, digest, contract ? JSON.stringify(contract) : null, now, by);
|
|
530
|
+
return true;
|
|
531
|
+
}
|
|
532
|
+
/** One pin in full, so a caller can put it back exactly as it was. */
|
|
533
|
+
getPin(component, tool) {
|
|
534
|
+
const row = this.db
|
|
535
|
+
.prepare("SELECT digest, contract, pinned_at, pinned_by FROM tool_pins WHERE component = ? AND tool = ?")
|
|
536
|
+
.get(component, tool);
|
|
537
|
+
if (!row)
|
|
538
|
+
return undefined;
|
|
539
|
+
return {
|
|
540
|
+
digest: row.digest,
|
|
541
|
+
contract: parseContract(row.contract) ?? undefined,
|
|
542
|
+
pinnedAt: row.pinned_at,
|
|
543
|
+
pinnedBy: row.pinned_by
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* Replaces the changed contracts this component is holding with the ones it
|
|
548
|
+
* holds now.
|
|
549
|
+
*
|
|
550
|
+
* Delete-then-insert in one transaction, like the inventory beside it: a
|
|
551
|
+
* change that is no longer pending -- accepted, or the upstream went back --
|
|
552
|
+
* has to disappear rather than linger as something to review.
|
|
553
|
+
*/
|
|
554
|
+
publishToolChanges(component, pid, changes, now = Date.now()) {
|
|
555
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
556
|
+
try {
|
|
557
|
+
this.db.prepare("DELETE FROM tool_changes WHERE component = ?").run(component);
|
|
558
|
+
const insert = this.db.prepare(`INSERT INTO tool_changes
|
|
559
|
+
(component, tool, pid, digest, contract, was_digest, was_contract,
|
|
560
|
+
pinned_at, pinned_by, withheld, detected_at)
|
|
561
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
562
|
+
for (const change of changes) {
|
|
563
|
+
insert.run(component, change.tool, pid, change.digest, JSON.stringify(change.contract), change.was, change.wasContract ? JSON.stringify(change.wasContract) : null, change.pinnedAt, change.pinnedBy, change.withheld ? 1 : 0, now);
|
|
564
|
+
}
|
|
565
|
+
this.db.exec("COMMIT");
|
|
566
|
+
}
|
|
567
|
+
catch (err) {
|
|
568
|
+
this.db.exec("ROLLBACK");
|
|
569
|
+
throw err;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* The changes this component published that nobody has accepted yet.
|
|
574
|
+
*
|
|
575
|
+
* A row is settled once a person has pinned the digest it describes. The
|
|
576
|
+
* gateway only re-checks its pins when its tool list is rebuilt, so between
|
|
577
|
+
* an acceptance and the next rebuild it may republish a change that has
|
|
578
|
+
* already been accepted; reading through the pin is what keeps that from
|
|
579
|
+
* reappearing as work to do. A pin the gateway moved itself (under `warn`)
|
|
580
|
+
* does not settle anything: nobody looked at it.
|
|
581
|
+
*/
|
|
582
|
+
toolChanges(component) {
|
|
583
|
+
const rows = this.db
|
|
584
|
+
.prepare(`SELECT c.* FROM tool_changes c
|
|
585
|
+
LEFT JOIN tool_pins p ON p.component = c.component AND p.tool = c.tool
|
|
586
|
+
WHERE c.component = ?
|
|
587
|
+
AND NOT (p.digest IS NOT NULL AND p.digest = c.digest AND p.pinned_by <> ?)
|
|
588
|
+
ORDER BY c.tool`)
|
|
589
|
+
.all(component, GATEWAY_PINNER);
|
|
590
|
+
const out = [];
|
|
591
|
+
for (const row of rows) {
|
|
592
|
+
const contract = parseContract(row["contract"]);
|
|
593
|
+
// A row whose contract cannot be read cannot be reviewed or accepted.
|
|
594
|
+
if (!contract)
|
|
595
|
+
continue;
|
|
596
|
+
out.push({
|
|
597
|
+
component: row["component"],
|
|
598
|
+
tool: row["tool"],
|
|
599
|
+
pid: Number(row["pid"]),
|
|
600
|
+
digest: row["digest"],
|
|
601
|
+
contract,
|
|
602
|
+
wasDigest: row["was_digest"],
|
|
603
|
+
wasContract: parseContract(row["was_contract"]),
|
|
604
|
+
pinnedAt: Number(row["pinned_at"]),
|
|
605
|
+
pinnedBy: row["pinned_by"],
|
|
606
|
+
withheld: Number(row["withheld"]) === 1,
|
|
607
|
+
detectedAt: Number(row["detected_at"])
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
return out;
|
|
611
|
+
}
|
|
612
|
+
/** Drops one published change, once it has been dealt with. */
|
|
613
|
+
clearToolChange(component, tool) {
|
|
614
|
+
this.db.prepare("DELETE FROM tool_changes WHERE component = ? AND tool = ?").run(component, tool);
|
|
615
|
+
}
|
|
616
|
+
/** Every pin this component holds, for a reader that wants to show them. */
|
|
617
|
+
listPins(component) {
|
|
618
|
+
return this.db
|
|
619
|
+
.prepare("SELECT tool, digest, pinned_at, pinned_by FROM tool_pins WHERE component = ? ORDER BY tool")
|
|
620
|
+
.all(component).map((r) => ({ tool: r.tool, digest: r.digest, pinnedAt: r.pinned_at, pinnedBy: r.pinned_by }));
|
|
621
|
+
}
|
|
622
|
+
// ---- tool inventory --------------------------------------------------
|
|
623
|
+
//
|
|
624
|
+
// Also keyed by component rather than tenant, and for the same reason: a
|
|
625
|
+
// gateway's upstreams offer one set of tools to every tenant it serves.
|
|
626
|
+
/**
|
|
627
|
+
* Replaces everything this component publishes with what it is serving now.
|
|
628
|
+
*
|
|
629
|
+
* Delete-then-insert in one transaction, so a tool an upstream stopped
|
|
630
|
+
* offering disappears rather than lingering as a row a reader would present
|
|
631
|
+
* as current. A partial write is the one outcome worth ruling out: half a
|
|
632
|
+
* tool list is indistinguishable from a gateway that genuinely narrowed.
|
|
633
|
+
*/
|
|
634
|
+
publishInventory(component, pid, tools, now = Date.now()) {
|
|
635
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
636
|
+
try {
|
|
637
|
+
this.db.prepare("DELETE FROM tool_inventory WHERE component = ?").run(component);
|
|
638
|
+
const insert = this.db.prepare(`INSERT INTO tool_inventory
|
|
639
|
+
(component, tool, pid, upstream, effect, effect_source, description,
|
|
640
|
+
raw_description, input_schema, hidden, injection, discovered_at)
|
|
641
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
642
|
+
for (const tool of tools) {
|
|
643
|
+
insert.run(component, tool.tool, pid, tool.upstream, tool.effect ?? null, tool.effectSource, tool.description, tool.rawDescription, JSON.stringify(tool.inputSchema ?? { type: "object" }), tool.hidden ? 1 : 0, tool.injection && tool.injection.length > 0 ? JSON.stringify(tool.injection) : null, now);
|
|
644
|
+
}
|
|
645
|
+
this.db.exec("COMMIT");
|
|
646
|
+
}
|
|
647
|
+
catch (err) {
|
|
648
|
+
this.db.exec("ROLLBACK");
|
|
649
|
+
throw err;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* What this component last published.
|
|
654
|
+
*
|
|
655
|
+
* Unfiltered by pid on purpose: a caller that cares which process wrote these
|
|
656
|
+
* rows has to compare them against `runtimeState(component)` anyway, and
|
|
657
|
+
* silently returning nothing would be indistinguishable from a gateway that
|
|
658
|
+
* has never run. `inventoryPid` is the cheap form of that question.
|
|
659
|
+
*/
|
|
660
|
+
inventory(component) {
|
|
661
|
+
return this.db
|
|
662
|
+
.prepare("SELECT * FROM tool_inventory WHERE component = ? ORDER BY tool")
|
|
663
|
+
.all(component)
|
|
664
|
+
.map((row) => ({ ...row }));
|
|
665
|
+
}
|
|
666
|
+
/** Which process wrote the rows this component published, if any. */
|
|
667
|
+
inventoryPid(component) {
|
|
668
|
+
const row = this.db.prepare("SELECT pid FROM tool_inventory WHERE component = ? LIMIT 1").get(component);
|
|
669
|
+
return row?.pid;
|
|
670
|
+
}
|
|
671
|
+
// ---- live state ------------------------------------------------------
|
|
672
|
+
//
|
|
673
|
+
// What each running gateway process says about its servers, and the
|
|
674
|
+
// console's requests back to it. One row per process, not per component:
|
|
675
|
+
// several AI apps can each run a gateway for the same gateway.yaml, and
|
|
676
|
+
// "connected" in one of them says nothing about the others.
|
|
677
|
+
/** Publish this process's view, replacing its previous row. Called on the heartbeat. */
|
|
678
|
+
writeLiveState(row) {
|
|
679
|
+
this.db
|
|
680
|
+
.prepare(`INSERT INTO live_config_state (component, pid, config_digest, applied_at, refusal, upstreams, heartbeat_at)
|
|
681
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
682
|
+
ON CONFLICT(component, pid) DO UPDATE SET
|
|
683
|
+
config_digest = excluded.config_digest,
|
|
684
|
+
applied_at = excluded.applied_at,
|
|
685
|
+
refusal = excluded.refusal,
|
|
686
|
+
upstreams = excluded.upstreams,
|
|
687
|
+
heartbeat_at = excluded.heartbeat_at`)
|
|
688
|
+
.run(row.component, row.pid, row.config_digest, row.applied_at, row.refusal, JSON.stringify(row.upstreams), row.heartbeat_at);
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Every live process's view of one component, newest heartbeat first.
|
|
692
|
+
*
|
|
693
|
+
* A row whose heartbeat is older than `LIVE_STATE_STALE_MS` belongs to a
|
|
694
|
+
* process that is gone -- killed, or its AI app quit -- and is deleted here
|
|
695
|
+
* rather than shown, so "connected" is never reported by a process that no
|
|
696
|
+
* longer exists.
|
|
697
|
+
*/
|
|
698
|
+
readLiveState(component, now = Date.now()) {
|
|
699
|
+
const rows = this.db
|
|
700
|
+
.prepare("SELECT * FROM live_config_state WHERE component = ? ORDER BY heartbeat_at DESC")
|
|
701
|
+
.all(component);
|
|
702
|
+
const fresh = [];
|
|
703
|
+
const remove = this.db.prepare("DELETE FROM live_config_state WHERE component = ? AND pid = ? AND heartbeat_at = ?");
|
|
704
|
+
for (const raw of rows) {
|
|
705
|
+
const row = toLiveRow(raw);
|
|
706
|
+
if (row && liveStateFresh(row, now)) {
|
|
707
|
+
fresh.push(row);
|
|
708
|
+
}
|
|
709
|
+
else {
|
|
710
|
+
// Matched on the heartbeat too, so a process that beat between the
|
|
711
|
+
// read and this delete keeps its new row.
|
|
712
|
+
remove.run(component, Number(raw["pid"]), String(raw["heartbeat_at"]));
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
return fresh;
|
|
716
|
+
}
|
|
717
|
+
/** Remove this process's row, on a clean shutdown. */
|
|
718
|
+
clearLiveState(component, pid) {
|
|
719
|
+
this.db.prepare("DELETE FROM live_config_state WHERE component = ? AND pid = ?").run(component, pid);
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* Ask the running gateways for a component to do something now -- today,
|
|
723
|
+
* retry one server rather than wait for its backoff. A request already
|
|
724
|
+
* waiting for the same server is returned instead of queuing a second one,
|
|
725
|
+
* so a person clicking "Try again" twice causes one retry.
|
|
726
|
+
*/
|
|
727
|
+
requestLive(component, upstream, kind, now = new Date()) {
|
|
728
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
729
|
+
try {
|
|
730
|
+
// A request past its time would be returned and then dropped unacted on.
|
|
731
|
+
this.db
|
|
732
|
+
.prepare("DELETE FROM live_requests WHERE component = ? AND upstream = ? AND kind = ? AND created_at < ?")
|
|
733
|
+
.run(component, upstream, kind, new Date(now.getTime() - LIVE_REQUEST_TTL_MS).toISOString());
|
|
734
|
+
const existing = this.db
|
|
735
|
+
.prepare("SELECT * FROM live_requests WHERE component = ? AND upstream = ? AND kind = ? ORDER BY id LIMIT 1")
|
|
736
|
+
.get(component, upstream, kind);
|
|
737
|
+
let row = existing;
|
|
738
|
+
if (!row) {
|
|
739
|
+
row = this.db
|
|
740
|
+
.prepare("INSERT INTO live_requests (component, upstream, kind, created_at) VALUES (?, ?, ?, ?) RETURNING *")
|
|
741
|
+
.get(component, upstream, kind, now.toISOString());
|
|
742
|
+
}
|
|
743
|
+
this.db.exec("COMMIT");
|
|
744
|
+
return toLiveRequest(row);
|
|
745
|
+
}
|
|
746
|
+
catch (err) {
|
|
747
|
+
this.db.exec("ROLLBACK");
|
|
748
|
+
throw err;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* The requests for a component that this process has not acted on yet.
|
|
753
|
+
*
|
|
754
|
+
* Every live process sees each request once. Several AI apps can each run a
|
|
755
|
+
* gateway for the same toolbox, and a server can be connected in one and
|
|
756
|
+
* failed in another; if the first to poll took the request away, the
|
|
757
|
+
* process where it actually failed might never retry. So each taker marks a
|
|
758
|
+
* request seen for its pid, and a request is deleted once every live
|
|
759
|
+
* process (and this one) has seen it, or once it is older than the stale
|
|
760
|
+
* window -- a retry nobody picked up in time is no longer what the person
|
|
761
|
+
* asked for. All in one write transaction, so two processes polling at once
|
|
762
|
+
* cannot both miss the delete or both take the same request twice.
|
|
763
|
+
*/
|
|
764
|
+
takeLiveRequests(component, pid, now = Date.now()) {
|
|
765
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
766
|
+
try {
|
|
767
|
+
const rows = this.db
|
|
768
|
+
.prepare("SELECT * FROM live_requests WHERE component = ? ORDER BY id")
|
|
769
|
+
.all(component);
|
|
770
|
+
const livePids = new Set([pid]);
|
|
771
|
+
for (const raw of this.db
|
|
772
|
+
.prepare("SELECT pid, heartbeat_at FROM live_config_state WHERE component = ?")
|
|
773
|
+
.all(component)) {
|
|
774
|
+
if (liveStateFresh(raw, now))
|
|
775
|
+
livePids.add(Number(raw.pid));
|
|
776
|
+
}
|
|
777
|
+
const seenBy = this.db.prepare("SELECT pid FROM live_request_seen WHERE request_id = ?");
|
|
778
|
+
const markSeen = this.db.prepare("INSERT OR IGNORE INTO live_request_seen (request_id, pid) VALUES (?, ?)");
|
|
779
|
+
const remove = this.db.prepare("DELETE FROM live_requests WHERE id = ?");
|
|
780
|
+
const forget = this.db.prepare("DELETE FROM live_request_seen WHERE request_id = ?");
|
|
781
|
+
const taken = [];
|
|
782
|
+
for (const raw of rows) {
|
|
783
|
+
const request = toLiveRequest(raw);
|
|
784
|
+
const expired = !(now - Date.parse(request.created_at) <= LIVE_REQUEST_TTL_MS);
|
|
785
|
+
const seen = new Set(seenBy.all(request.id).map((r) => Number(r.pid)));
|
|
786
|
+
if (!expired && !seen.has(pid)) {
|
|
787
|
+
markSeen.run(request.id, pid);
|
|
788
|
+
seen.add(pid);
|
|
789
|
+
taken.push(request);
|
|
790
|
+
}
|
|
791
|
+
if (expired || [...livePids].every((p) => seen.has(p))) {
|
|
792
|
+
remove.run(request.id);
|
|
793
|
+
forget.run(request.id);
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
this.db.exec("COMMIT");
|
|
797
|
+
return taken;
|
|
798
|
+
}
|
|
799
|
+
catch (err) {
|
|
800
|
+
this.db.exec("ROLLBACK");
|
|
801
|
+
throw err;
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
/** How long a "Try again" waits for every live process to act on it. */
|
|
806
|
+
const LIVE_REQUEST_TTL_MS = LIVE_STATE_STALE_MS * 6;
|
|
807
|
+
/**
|
|
808
|
+
* Which processes have acted on which request. Kept beside `LIVE_STATE_SQL`
|
|
809
|
+
* and created the same way (`IF NOT EXISTS` on every open, no schema bump),
|
|
810
|
+
* for the same reason: it holds only what running processes are doing now.
|
|
811
|
+
*/
|
|
812
|
+
const LIVE_REQUEST_SEEN_SQL = `
|
|
813
|
+
CREATE TABLE IF NOT EXISTS live_request_seen (
|
|
814
|
+
request_id INTEGER NOT NULL,
|
|
815
|
+
pid INTEGER NOT NULL,
|
|
816
|
+
PRIMARY KEY (request_id, pid)
|
|
817
|
+
);
|
|
818
|
+
`;
|
|
819
|
+
function toLiveRow(raw) {
|
|
820
|
+
let upstreams;
|
|
821
|
+
try {
|
|
822
|
+
const parsed = JSON.parse(String(raw["upstreams"]));
|
|
823
|
+
if (!Array.isArray(parsed))
|
|
824
|
+
return null;
|
|
825
|
+
upstreams = parsed;
|
|
826
|
+
}
|
|
827
|
+
catch {
|
|
828
|
+
// A row nobody can read is treated like a dead process's: dropped.
|
|
829
|
+
return null;
|
|
830
|
+
}
|
|
831
|
+
return {
|
|
832
|
+
component: String(raw["component"]),
|
|
833
|
+
pid: Number(raw["pid"]),
|
|
834
|
+
config_digest: String(raw["config_digest"]),
|
|
835
|
+
applied_at: String(raw["applied_at"]),
|
|
836
|
+
refusal: raw["refusal"] === null || raw["refusal"] === undefined ? null : String(raw["refusal"]),
|
|
837
|
+
upstreams,
|
|
838
|
+
heartbeat_at: String(raw["heartbeat_at"])
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
function toLiveRequest(raw) {
|
|
842
|
+
return {
|
|
843
|
+
id: Number(raw["id"]),
|
|
844
|
+
component: String(raw["component"]),
|
|
845
|
+
upstream: String(raw["upstream"]),
|
|
846
|
+
kind: raw["kind"],
|
|
847
|
+
created_at: String(raw["created_at"])
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* One component's rows, for one tenant.
|
|
852
|
+
*
|
|
853
|
+
* Every statement here carries `component = ? AND tenant = ?`. That is the
|
|
854
|
+
* whole of the isolation, and it is deliberately in the SQL rather than folded
|
|
855
|
+
* into `binding_hash` or enforced by a convention: a `WHERE` clause can be
|
|
856
|
+
* read, grepped and tested, and a caller that forgets the scope cannot compile
|
|
857
|
+
* rather than quietly matching everything.
|
|
858
|
+
*
|
|
859
|
+
* Two bugs this closes, both of which were live whenever a database was shared
|
|
860
|
+
* — which is the default. `consume` matched on `binding_hash` alone, and the
|
|
861
|
+
* hash covers only the tool name and arguments, so one tenant's granted
|
|
862
|
+
* approval released another tenant's identical call. `consumeGrant` matched on
|
|
863
|
+
* tool, effect and arguments, so one tenant's standing grant released another
|
|
864
|
+
* tenant's call and charged the use to the wrong grant.
|
|
865
|
+
*/
|
|
866
|
+
export class ScopedApprovals {
|
|
867
|
+
db;
|
|
868
|
+
scope;
|
|
869
|
+
constructor(db, scope) {
|
|
870
|
+
this.db = db;
|
|
871
|
+
this.scope = scope;
|
|
872
|
+
}
|
|
873
|
+
get where() {
|
|
874
|
+
return [this.scope.component, this.scope.tenant];
|
|
875
|
+
}
|
|
876
|
+
/** Expiry is global; it is re-exposed here so scoped reads can sweep first. */
|
|
877
|
+
expireStale(now = Date.now()) {
|
|
878
|
+
this.db
|
|
879
|
+
.prepare("UPDATE approvals SET state = 'expired' WHERE expires_at <= ? AND state IN ('pending','granted')")
|
|
880
|
+
.run(now);
|
|
881
|
+
}
|
|
882
|
+
insertPending(row) {
|
|
883
|
+
this.db
|
|
884
|
+
.prepare(`INSERT INTO approvals (id, component, tenant, created_at, expires_at, tool, effect,
|
|
885
|
+
binding_hash, args_redacted, reason, actor, session, state,
|
|
886
|
+
violations, rule_id, policy_digest, binding_version, held_args)
|
|
887
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?, ?)`)
|
|
888
|
+
.run(row.id, ...this.where, row.created_at, row.expires_at, row.tool, row.effect, row.binding_hash, row.args_redacted, row.reason, row.actor, row.session, encodeViolations(row.violations), row.rule_id ?? null, row.policy_digest ?? null, BINDING_VERSION, JSON.stringify(row.held_args ?? []));
|
|
889
|
+
return this.get(row.id);
|
|
890
|
+
}
|
|
891
|
+
/** Records an already-decided grant, e.g. one obtained via elicitation. */
|
|
892
|
+
insertGranted(row, decidedBy, note = "", state = "granted") {
|
|
893
|
+
this.db
|
|
894
|
+
.prepare(`INSERT INTO approvals (id, component, tenant, created_at, expires_at, tool, effect,
|
|
895
|
+
binding_hash, args_redacted, reason, actor, session, state, decided_at, decided_by, decision_note,
|
|
896
|
+
violations, rule_id, policy_digest, binding_version, held_args)
|
|
897
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
898
|
+
.run(row.id, ...this.where, row.created_at, row.expires_at, row.tool, row.effect, row.binding_hash, row.args_redacted, row.reason, row.actor, row.session, state, Date.now(), decidedBy, note, encodeViolations(row.violations), row.rule_id ?? null, row.policy_digest ?? null, BINDING_VERSION, JSON.stringify(row.held_args ?? []));
|
|
899
|
+
return this.get(row.id);
|
|
900
|
+
}
|
|
901
|
+
get(id) {
|
|
902
|
+
const row = this.db
|
|
903
|
+
.prepare("SELECT * FROM approvals WHERE id = ? AND component = ? AND tenant = ?")
|
|
904
|
+
.get(id, ...this.where);
|
|
905
|
+
return row ? { ...row } : undefined;
|
|
906
|
+
}
|
|
907
|
+
listPending(limit = 50) {
|
|
908
|
+
this.expireStale();
|
|
909
|
+
return this.db
|
|
910
|
+
.prepare(`SELECT * FROM approvals WHERE component = ? AND tenant = ? AND state = 'pending'
|
|
911
|
+
ORDER BY created_at ASC LIMIT ?`)
|
|
912
|
+
.all(...this.where, limit)
|
|
913
|
+
.map((r) => ({ ...r }));
|
|
914
|
+
}
|
|
915
|
+
list(limit = 50) {
|
|
916
|
+
return this.db
|
|
917
|
+
.prepare(`SELECT * FROM approvals WHERE component = ? AND tenant = ?
|
|
918
|
+
ORDER BY created_at DESC LIMIT ?`)
|
|
919
|
+
.all(...this.where, limit)
|
|
920
|
+
.map((r) => ({ ...r }));
|
|
921
|
+
}
|
|
922
|
+
/**
|
|
923
|
+
* The most recent "no" a person gave to this exact call since `since`, if
|
|
924
|
+
* any. A refusal the AI is never told about just turns into a new,
|
|
925
|
+
* identical question on its next try, so the broker answers that try
|
|
926
|
+
* itself for a while after a no.
|
|
927
|
+
*/
|
|
928
|
+
findRecentlyDenied(binding, since) {
|
|
929
|
+
const row = this.db
|
|
930
|
+
.prepare(`SELECT * FROM approvals
|
|
931
|
+
WHERE component = ? AND tenant = ? AND binding_version = ${BINDING_VERSION} AND binding_hash = ?
|
|
932
|
+
AND state = 'denied' AND decided_at >= ?
|
|
933
|
+
ORDER BY decided_at DESC LIMIT 1`)
|
|
934
|
+
.get(...this.where, binding, since);
|
|
935
|
+
return row ? { ...row } : undefined;
|
|
936
|
+
}
|
|
937
|
+
/**
|
|
938
|
+
* The request already waiting on a human for this exact call, if there is
|
|
939
|
+
* one. Current framing only: a pending row is always written under it.
|
|
940
|
+
*/
|
|
941
|
+
findPending(binding, now = Date.now()) {
|
|
942
|
+
const row = this.db
|
|
943
|
+
.prepare(`SELECT * FROM approvals
|
|
944
|
+
WHERE component = ? AND tenant = ? AND binding_version = ${BINDING_VERSION} AND binding_hash = ?
|
|
945
|
+
AND state = 'pending' AND expires_at > ?
|
|
946
|
+
ORDER BY created_at ASC LIMIT 1`)
|
|
947
|
+
.get(...this.where, binding, now);
|
|
948
|
+
return row ? { ...row } : undefined;
|
|
949
|
+
}
|
|
950
|
+
/** Human decision on a parked request. */
|
|
951
|
+
decide(id, state, by, note = "") {
|
|
952
|
+
this.expireStale();
|
|
953
|
+
const changes = Number(this.db
|
|
954
|
+
.prepare(`UPDATE approvals SET state = ?, decided_at = ?, decided_by = ?, decision_note = ?
|
|
955
|
+
WHERE id = ? AND component = ? AND tenant = ? AND state = 'pending'`)
|
|
956
|
+
.run(state, Date.now(), by, note, id, ...this.where).changes);
|
|
957
|
+
return changes > 0 ? this.get(id) : undefined;
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Atomically finds and consumes a usable grant for this exact call. The
|
|
961
|
+
* binding hash covers the tool name and every argument, so a grant issued for
|
|
962
|
+
* one set of arguments cannot release a different one — and the scope filter
|
|
963
|
+
* is what stops an identical call in another tenant from redeeming it.
|
|
964
|
+
*/
|
|
965
|
+
/**
|
|
966
|
+
* Redeems a grant for this exact call.
|
|
967
|
+
*
|
|
968
|
+
* `bindings` carries one digest per framing `bindingHash` has used, and each
|
|
969
|
+
* is matched only against rows stamped with that framing. Pairing them in the
|
|
970
|
+
* `WHERE` rather than matching on either digest is what keeps the older
|
|
971
|
+
* scheme from releasing a row written under the newer one -- and it keeps the
|
|
972
|
+
* whole transition readable in one SQL clause, which is the same reason the
|
|
973
|
+
* tenant filter lives here rather than inside the hash.
|
|
974
|
+
*
|
|
975
|
+
* The legacy arm exists so an approval a human had already granted when this
|
|
976
|
+
* build was deployed still releases the retry it was granted for. It matches
|
|
977
|
+
* nothing once those rows expire.
|
|
978
|
+
*/
|
|
979
|
+
consume(binding, singleUse, now = Date.now()) {
|
|
980
|
+
this.expireStale(now);
|
|
981
|
+
const bindings = typeof binding === "string" ? { current: binding, legacy: binding } : binding;
|
|
982
|
+
const candidate = this.db
|
|
983
|
+
.prepare(`SELECT * FROM approvals
|
|
984
|
+
WHERE component = ? AND tenant = ?
|
|
985
|
+
AND ( (binding_version >= ${BINDING_VERSION} AND binding_hash = ?)
|
|
986
|
+
OR (binding_version < ${BINDING_VERSION} AND binding_hash = ?) )
|
|
987
|
+
AND state = 'granted' AND expires_at > ?
|
|
988
|
+
ORDER BY created_at ASC LIMIT 1`)
|
|
989
|
+
.get(...this.where, bindings.current, bindings.legacy, now);
|
|
990
|
+
if (!candidate)
|
|
991
|
+
return undefined;
|
|
992
|
+
const row = { ...candidate };
|
|
993
|
+
if (!singleUse)
|
|
994
|
+
return row;
|
|
995
|
+
const changes = Number(this.db
|
|
996
|
+
.prepare("UPDATE approvals SET state = 'used' WHERE id = ? AND state = 'granted'")
|
|
997
|
+
.run(row.id).changes);
|
|
998
|
+
// Lost the race to another consumer; treat as not granted rather than
|
|
999
|
+
// letting two calls through on one approval.
|
|
1000
|
+
return changes > 0 ? { ...row, state: "used" } : undefined;
|
|
1001
|
+
}
|
|
1002
|
+
/**
|
|
1003
|
+
* `decide` with the "why not" the CLI and the console both need. `decide`
|
|
1004
|
+
* returns `undefined` for a missing row and for an already-decided one alike;
|
|
1005
|
+
* a reviewer needs to be told which it was.
|
|
1006
|
+
*/
|
|
1007
|
+
decideChecked(id, state, by, note = "") {
|
|
1008
|
+
this.expireStale();
|
|
1009
|
+
const existing = this.get(id);
|
|
1010
|
+
if (!existing)
|
|
1011
|
+
return { ok: false, error: `no approval request with id ${id}` };
|
|
1012
|
+
if (existing.state !== "pending") {
|
|
1013
|
+
return { ok: false, error: `approval ${id} is already ${existing.state} and cannot be decided again` };
|
|
1014
|
+
}
|
|
1015
|
+
const row = this.decide(id, state, by, note);
|
|
1016
|
+
// Lost a race with another reviewer between the check and the update.
|
|
1017
|
+
if (!row)
|
|
1018
|
+
return { ok: false, error: `approval ${id} was decided by someone else first` };
|
|
1019
|
+
return { ok: true, row };
|
|
1020
|
+
}
|
|
1021
|
+
// ---- standing grants -------------------------------------------------
|
|
1022
|
+
createGrant(draft, now = Date.now()) {
|
|
1023
|
+
const id = newGrantId();
|
|
1024
|
+
this.db
|
|
1025
|
+
.prepare(`INSERT INTO standing_grants (id, component, tenant, created_at, expires_at, tool_match,
|
|
1026
|
+
effect, constraints, max_uses, uses, reason, created_by, state, closed)
|
|
1027
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, 'active', ?)`)
|
|
1028
|
+
.run(id, ...this.where, now, draft.expires_at, draft.tool_match, draft.effect ?? null, JSON.stringify(draft.constraints ?? {}), draft.max_uses ?? null, draft.reason, draft.created_by, draft.closed ? 1 : 0);
|
|
1029
|
+
return this.getGrant(id);
|
|
1030
|
+
}
|
|
1031
|
+
getGrant(id) {
|
|
1032
|
+
const row = this.db
|
|
1033
|
+
.prepare("SELECT * FROM standing_grants WHERE id = ? AND component = ? AND tenant = ?")
|
|
1034
|
+
.get(id, ...this.where);
|
|
1035
|
+
return row ? { ...row } : undefined;
|
|
1036
|
+
}
|
|
1037
|
+
listGrants(options = {}) {
|
|
1038
|
+
this.expireStaleGrants();
|
|
1039
|
+
const limit = options.limit ?? 100;
|
|
1040
|
+
const sql = options.activeOnly
|
|
1041
|
+
? `SELECT * FROM standing_grants WHERE component = ? AND tenant = ? AND state = 'active'
|
|
1042
|
+
ORDER BY created_at DESC LIMIT ?`
|
|
1043
|
+
: `SELECT * FROM standing_grants WHERE component = ? AND tenant = ?
|
|
1044
|
+
ORDER BY created_at DESC LIMIT ?`;
|
|
1045
|
+
return this.db
|
|
1046
|
+
.prepare(sql)
|
|
1047
|
+
.all(...this.where, limit)
|
|
1048
|
+
.map((r) => ({ ...r }));
|
|
1049
|
+
}
|
|
1050
|
+
/** Marks past-due grants expired. Lazy, like `expireStale` for approvals. */
|
|
1051
|
+
expireStaleGrants(now = Date.now()) {
|
|
1052
|
+
return Number(this.db
|
|
1053
|
+
.prepare(`UPDATE standing_grants SET state = 'expired'
|
|
1054
|
+
WHERE component = ? AND tenant = ? AND expires_at <= ? AND state = 'active'`)
|
|
1055
|
+
.run(...this.where, now).changes);
|
|
1056
|
+
}
|
|
1057
|
+
revokeGrant(id, by, now = Date.now()) {
|
|
1058
|
+
const changes = Number(this.db
|
|
1059
|
+
.prepare(`UPDATE standing_grants SET state = 'revoked', revoked_at = ?, revoked_by = ?
|
|
1060
|
+
WHERE id = ? AND component = ? AND tenant = ? AND state = 'active'`)
|
|
1061
|
+
.run(now, by, id, ...this.where).changes);
|
|
1062
|
+
return changes > 0 ? this.getGrant(id) : undefined;
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* Finds the oldest live grant covering this call and charges one use to it.
|
|
1066
|
+
*
|
|
1067
|
+
* Returns undefined when nothing covers the call, which is the signal to fall
|
|
1068
|
+
* through to ordinary approval. A grant that matches the tool but whose
|
|
1069
|
+
* argument constraints reject the arguments is simply not a match: it must not
|
|
1070
|
+
* become a denial.
|
|
1071
|
+
*/
|
|
1072
|
+
consumeGrant(tool, effect, args, now = Date.now(),
|
|
1073
|
+
/** Arguments that broke a rule's bound, when that is why the call is held. */
|
|
1074
|
+
heldArgs = []) {
|
|
1075
|
+
this.expireStaleGrants(now);
|
|
1076
|
+
const candidates = this.db
|
|
1077
|
+
.prepare(`SELECT * FROM standing_grants
|
|
1078
|
+
WHERE component = ? AND tenant = ? AND state = 'active' AND expires_at > ?
|
|
1079
|
+
ORDER BY created_at ASC`)
|
|
1080
|
+
.all(...this.where, now)
|
|
1081
|
+
.map((r) => ({ ...r }));
|
|
1082
|
+
for (const candidate of candidates) {
|
|
1083
|
+
if (!grantMatches(candidate, tool, effect, args).matches)
|
|
1084
|
+
continue;
|
|
1085
|
+
/*
|
|
1086
|
+
* A call held because it broke a rule's bound is the one the rule's
|
|
1087
|
+
* author wanted a person to look at. A grant made to stop being asked
|
|
1088
|
+
* about ordinary calls must not also wave that one through, so it
|
|
1089
|
+
* releases it only when the grant itself bounds the argument in
|
|
1090
|
+
* question -- which is its author saying how far past the rule they
|
|
1091
|
+
* meant to go. Not a match rather than a refusal, like any other grant
|
|
1092
|
+
* that does not cover a call: it falls through to a human.
|
|
1093
|
+
*/
|
|
1094
|
+
if (heldArgs.length > 0 && !grantBoundsArgs(candidate, args, heldArgs))
|
|
1095
|
+
continue;
|
|
1096
|
+
// Charge the use and exhaust the grant in one statement, guarded so two
|
|
1097
|
+
// concurrent calls cannot both take the last use.
|
|
1098
|
+
const changes = Number(this.db
|
|
1099
|
+
.prepare(`UPDATE standing_grants
|
|
1100
|
+
SET uses = uses + 1,
|
|
1101
|
+
state = CASE WHEN max_uses IS NOT NULL AND uses + 1 >= max_uses THEN 'exhausted' ELSE 'active' END
|
|
1102
|
+
WHERE id = ? AND state = 'active' AND (max_uses IS NULL OR uses < max_uses)`)
|
|
1103
|
+
.run(candidate.id).changes);
|
|
1104
|
+
// Lost the race, or it was exhausted between the select and the update.
|
|
1105
|
+
// Try the next candidate rather than failing a call a later grant covers.
|
|
1106
|
+
if (changes > 0)
|
|
1107
|
+
return this.getGrant(candidate.id);
|
|
1108
|
+
}
|
|
1109
|
+
return undefined;
|
|
1110
|
+
}
|
|
1111
|
+
// ---- exposure overrides ----------------------------------------------
|
|
1112
|
+
/**
|
|
1113
|
+
* Switches one tool off, for this component and this tenant.
|
|
1114
|
+
*
|
|
1115
|
+
* Idempotent, and it only ever subtracts: there is no corresponding row that
|
|
1116
|
+
* can make a call reachable. `set_at` and `set_by` are refreshed on a repeat
|
|
1117
|
+
* so the audit trail and the console both show who last asserted it.
|
|
1118
|
+
*/
|
|
1119
|
+
disableTool(tool, by, reason = "") {
|
|
1120
|
+
this.db
|
|
1121
|
+
.prepare(`INSERT INTO tool_exposure (component, tenant, tool, reason, set_at, set_by)
|
|
1122
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
1123
|
+
ON CONFLICT(component, tenant, tool) DO UPDATE SET
|
|
1124
|
+
reason = excluded.reason, set_at = excluded.set_at, set_by = excluded.set_by`)
|
|
1125
|
+
.run(...this.where, tool, reason, Date.now(), by);
|
|
1126
|
+
return this.toolExposure(tool);
|
|
1127
|
+
}
|
|
1128
|
+
/** Clears the override, handing the question back to policy. */
|
|
1129
|
+
enableTool(tool) {
|
|
1130
|
+
const existing = this.toolExposure(tool);
|
|
1131
|
+
if (!existing)
|
|
1132
|
+
return undefined;
|
|
1133
|
+
this.db
|
|
1134
|
+
.prepare("DELETE FROM tool_exposure WHERE component = ? AND tenant = ? AND tool = ?")
|
|
1135
|
+
.run(...this.where, tool);
|
|
1136
|
+
return existing;
|
|
1137
|
+
}
|
|
1138
|
+
toolExposure(tool) {
|
|
1139
|
+
const row = this.db
|
|
1140
|
+
.prepare("SELECT * FROM tool_exposure WHERE component = ? AND tenant = ? AND tool = ?")
|
|
1141
|
+
.get(...this.where, tool);
|
|
1142
|
+
return row ? { ...row } : undefined;
|
|
1143
|
+
}
|
|
1144
|
+
/** Every tool switched off in this scope, newest first. */
|
|
1145
|
+
listDisabledTools() {
|
|
1146
|
+
return this.db
|
|
1147
|
+
.prepare(`SELECT * FROM tool_exposure WHERE component = ? AND tenant = ?
|
|
1148
|
+
ORDER BY set_at DESC`)
|
|
1149
|
+
.all(...this.where)
|
|
1150
|
+
.map((r) => ({ ...r }));
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
/** What the prompt offers for how long to remember an approval, and what each means. */
|
|
1154
|
+
const REMEMBER_CHOICES = {
|
|
1155
|
+
"10 minutes": 10 * 60,
|
|
1156
|
+
"1 hour": 60 * 60,
|
|
1157
|
+
"8 hours": 8 * 60 * 60
|
|
1158
|
+
};
|
|
1159
|
+
/**
|
|
1160
|
+
* Runs the approval flow for a single call: reuse an existing grant, else ask
|
|
1161
|
+
* the host interactively, else park the request for out-of-band review.
|
|
1162
|
+
*/
|
|
1163
|
+
export class ApprovalBroker {
|
|
1164
|
+
config;
|
|
1165
|
+
store;
|
|
1166
|
+
elicit;
|
|
1167
|
+
redactKeys;
|
|
1168
|
+
classify;
|
|
1169
|
+
remember;
|
|
1170
|
+
now;
|
|
1171
|
+
constructor(options) {
|
|
1172
|
+
this.config = options.config;
|
|
1173
|
+
this.store = options.store;
|
|
1174
|
+
this.elicit = options.elicit;
|
|
1175
|
+
this.redactKeys = options.redactKeys ?? [];
|
|
1176
|
+
this.classify = options.classify;
|
|
1177
|
+
this.remember = options.remember;
|
|
1178
|
+
this.now = options.now ?? Date.now;
|
|
1179
|
+
}
|
|
1180
|
+
async request(req) {
|
|
1181
|
+
const bindings = callBindings(req.tool, req.args);
|
|
1182
|
+
const binding = bindings.current;
|
|
1183
|
+
const now = this.now();
|
|
1184
|
+
// 1. A grant already issued for this exact call. Both framings are offered
|
|
1185
|
+
// so an approval granted before this build was deployed still releases
|
|
1186
|
+
// the retry it was granted for; only the current one is ever written.
|
|
1187
|
+
const cached = this.store.consume(bindings, this.config.single_use, now);
|
|
1188
|
+
if (cached) {
|
|
1189
|
+
return { granted: true, approvalId: cached.id, via: "cached" };
|
|
1190
|
+
}
|
|
1191
|
+
const base = {
|
|
1192
|
+
id: newApprovalId(),
|
|
1193
|
+
created_at: now,
|
|
1194
|
+
expires_at: now + this.config.ttl_seconds * 1000,
|
|
1195
|
+
tool: req.tool,
|
|
1196
|
+
effect: req.effect,
|
|
1197
|
+
binding_hash: binding,
|
|
1198
|
+
args_redacted: JSON.stringify(redactArgs(req.args, this.redactKeys)),
|
|
1199
|
+
reason: req.reason,
|
|
1200
|
+
actor: req.actor,
|
|
1201
|
+
session: req.session,
|
|
1202
|
+
...(req.violations && req.violations.length > 0 ? { violations: req.violations } : {}),
|
|
1203
|
+
...(req.heldArgs && req.heldArgs.length > 0 ? { held_args: req.heldArgs } : {}),
|
|
1204
|
+
...(req.ruleId ? { rule_id: req.ruleId } : {}),
|
|
1205
|
+
...(req.policyDigest ? { policy_digest: req.policyDigest } : {})
|
|
1206
|
+
};
|
|
1207
|
+
// 2. A standing grant covering this class of call. Recorded as an already
|
|
1208
|
+
// consumed approval so the exact arguments still appear in the history and
|
|
1209
|
+
// cannot be replayed through the binding-hash path above.
|
|
1210
|
+
const grant = this.store.consumeGrant(req.tool, req.effect, req.args, now, req.heldArgs);
|
|
1211
|
+
if (grant) {
|
|
1212
|
+
const row = this.store.insertGranted(base, `standing-grant:${grant.id}`, grant.reason, "used");
|
|
1213
|
+
return { granted: true, approvalId: row.id, via: "standing", grantId: grant.id };
|
|
1214
|
+
}
|
|
1215
|
+
if (this.config.mode === "deny") {
|
|
1216
|
+
return {
|
|
1217
|
+
granted: false,
|
|
1218
|
+
approvalId: null,
|
|
1219
|
+
reason: "policy requires approval for this call and approvals are disabled"
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
// 2b. A person already said no to this exact call a moment ago. Asking
|
|
1223
|
+
// again would put the same question back in front of them for every
|
|
1224
|
+
// retry, and the AI would never learn it was refused.
|
|
1225
|
+
const refused = this.store.findRecentlyDenied(binding, now - DENY_REMEMBER_MS);
|
|
1226
|
+
if (refused)
|
|
1227
|
+
return personSaidNo(refused.id);
|
|
1228
|
+
// 3. Ask the host, when it can ask a human.
|
|
1229
|
+
if ((this.config.mode === "elicit" || this.config.mode === "both") && this.elicit) {
|
|
1230
|
+
/*
|
|
1231
|
+
* A call held only because nothing says what the tool does is the one
|
|
1232
|
+
* hold a reviewer can end for good, so the prompt offers to: one more
|
|
1233
|
+
* field, optional, asked only when there is somewhere to record the
|
|
1234
|
+
* answer.
|
|
1235
|
+
*/
|
|
1236
|
+
const canClassify = req.ruleId === UNCLASSIFIED_RULE && this.classify !== undefined;
|
|
1237
|
+
/*
|
|
1238
|
+
* "And allow calls like this for a while." Offered for a read or a
|
|
1239
|
+
* write. Not for a tool nothing has classified, which has to be
|
|
1240
|
+
* classified first, and not for a destructive one, which stays in front
|
|
1241
|
+
* of a person every time.
|
|
1242
|
+
*/
|
|
1243
|
+
const canRemember = this.remember !== undefined && (req.effect === "read" || req.effect === "write");
|
|
1244
|
+
try {
|
|
1245
|
+
const result = await this.elicit({
|
|
1246
|
+
message: renderPrompt(req, this.redactKeys, canClassify),
|
|
1247
|
+
requestedSchema: {
|
|
1248
|
+
type: "object",
|
|
1249
|
+
properties: {
|
|
1250
|
+
approve: {
|
|
1251
|
+
type: "boolean",
|
|
1252
|
+
title: "Approve this call?",
|
|
1253
|
+
description: `Allow ${req.tool} to run with exactly these arguments.`
|
|
1254
|
+
},
|
|
1255
|
+
...(canClassify
|
|
1256
|
+
? {
|
|
1257
|
+
classify: {
|
|
1258
|
+
type: "string",
|
|
1259
|
+
title: "What does this tool do? (optional)",
|
|
1260
|
+
description: "Records it in policy, so the tool stops being treated as unknown. " +
|
|
1261
|
+
"Calls to it will still ask.",
|
|
1262
|
+
enum: ["read", "write", "destructive"]
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
: {}),
|
|
1266
|
+
...(canRemember
|
|
1267
|
+
? {
|
|
1268
|
+
remember: {
|
|
1269
|
+
type: "string",
|
|
1270
|
+
title: "Also allow calls like this one? (optional)",
|
|
1271
|
+
description: `Pre-approves ${req.tool} for the time chosen, for up to ${REMEMBER_DEFAULT_USES} calls, ` +
|
|
1272
|
+
(req.violations && req.violations.length > 0
|
|
1273
|
+
? "inside the policy's bounds and no further past them than this call. "
|
|
1274
|
+
: "inside whatever bounds policy sets on it. ") +
|
|
1275
|
+
"You can take it back in the hardened-mcp console, under Pre-approvals.",
|
|
1276
|
+
enum: Object.keys(REMEMBER_CHOICES)
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
: {}),
|
|
1280
|
+
note: { type: "string", title: "Note", description: "Recorded in the audit log." }
|
|
1281
|
+
},
|
|
1282
|
+
required: ["approve"]
|
|
1283
|
+
}
|
|
1284
|
+
});
|
|
1285
|
+
if (result.action === "accept" && result.content?.["approve"] === true) {
|
|
1286
|
+
let note = typeof result.content["note"] === "string" ? result.content["note"] : "";
|
|
1287
|
+
const effect = EffectSchema.safeParse(result.content["classify"]);
|
|
1288
|
+
if (canClassify && effect.success) {
|
|
1289
|
+
try {
|
|
1290
|
+
const ruleId = await this.classify(req.tool, effect.data);
|
|
1291
|
+
note = `${note}${note ? " " : ""}[classified as ${effect.data}: rule ${ruleId}]`;
|
|
1292
|
+
}
|
|
1293
|
+
catch (err) {
|
|
1294
|
+
// The reviewer said yes to this call. Failing to write a rule is
|
|
1295
|
+
// a separate problem and must not turn their yes into a no.
|
|
1296
|
+
note = `${note}${note ? " " : ""}[could not classify as ${effect.data}: ${err.message}]`;
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
const ttl = REMEMBER_CHOICES[String(result.content["remember"])];
|
|
1300
|
+
if (canRemember && ttl !== undefined) {
|
|
1301
|
+
try {
|
|
1302
|
+
const grantId = await this.remember(req, ttl, base.id);
|
|
1303
|
+
note = `${note}${note ? " " : ""}[remembered as ${grantId} for ${result.content["remember"]}]`;
|
|
1304
|
+
}
|
|
1305
|
+
catch (err) {
|
|
1306
|
+
// As with classifying: the yes to this call stands on its own.
|
|
1307
|
+
note = `${note}${note ? " " : ""}[could not remember: ${err.message}]`;
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
// Recorded as already consumed: the grant exists for the audit trail,
|
|
1311
|
+
// not to be redeemed a second time.
|
|
1312
|
+
const row = this.store.insertGranted(base, "elicitation", note, this.config.single_use ? "used" : "granted");
|
|
1313
|
+
return { granted: true, approvalId: row.id, via: "elicit" };
|
|
1314
|
+
}
|
|
1315
|
+
if (result.action === "accept") {
|
|
1316
|
+
this.store.insertGranted(base, "elicitation", "explicitly declined by reviewer", "denied");
|
|
1317
|
+
return personSaidNo(base.id);
|
|
1318
|
+
}
|
|
1319
|
+
return {
|
|
1320
|
+
granted: false,
|
|
1321
|
+
approvalId: null,
|
|
1322
|
+
reason: result.action === "cancel" ? "the approval prompt was cancelled" : "the host declined to prompt"
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
catch (err) {
|
|
1326
|
+
// The host advertised elicitation but could not deliver. Fall through to
|
|
1327
|
+
// the CLI path if it is available rather than failing open.
|
|
1328
|
+
if (this.config.mode === "elicit") {
|
|
1329
|
+
return {
|
|
1330
|
+
granted: false,
|
|
1331
|
+
approvalId: null,
|
|
1332
|
+
reason: `approval prompt failed: ${err.message}`
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
if (this.config.mode === "elicit") {
|
|
1338
|
+
return {
|
|
1339
|
+
granted: false,
|
|
1340
|
+
approvalId: null,
|
|
1341
|
+
reason: "this call needs approval but the connected client does not support elicitation"
|
|
1342
|
+
};
|
|
1343
|
+
}
|
|
1344
|
+
// 4. Park it for out-of-band review -- once. An agent told "approval
|
|
1345
|
+
// required" retries, and a second row for the same call is the same
|
|
1346
|
+
// question asked twice: it clutters the reviewer's queue and lets a
|
|
1347
|
+
// retry loop grow the database. The open request is handed back.
|
|
1348
|
+
const open = this.store.findPending(binding, now);
|
|
1349
|
+
const row = open ?? this.store.insertPending(base);
|
|
1350
|
+
// 5. Hold the call open for a little while, so a person who answers in
|
|
1351
|
+
// the console straight away lets it run without the AI having to try
|
|
1352
|
+
// again.
|
|
1353
|
+
if (this.config.wait_seconds > 0) {
|
|
1354
|
+
const decided = await this.waitForDecision(row.id, now + this.config.wait_seconds * 1000);
|
|
1355
|
+
if (decided === "granted") {
|
|
1356
|
+
const released = this.store.consume(bindings, this.config.single_use, this.now());
|
|
1357
|
+
if (released)
|
|
1358
|
+
return { granted: true, approvalId: released.id, via: "cli" };
|
|
1359
|
+
}
|
|
1360
|
+
else if (decided === "denied") {
|
|
1361
|
+
return personSaidNo(row.id);
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
const minutes = Math.max(1, Math.round(this.config.ttl_seconds / 60));
|
|
1365
|
+
return {
|
|
1366
|
+
granted: false,
|
|
1367
|
+
approvalId: row.id,
|
|
1368
|
+
parked: open ? "existing" : "new",
|
|
1369
|
+
reason: `this ${req.effect ?? "unclassified"} call requires human approval`,
|
|
1370
|
+
instructions: `This request is waiting for the person to approve it. Tell them, in plain words, that it is waiting ` +
|
|
1371
|
+
`for them in the hardened-mcp console, under "Waiting for you", where they can approve it or say no. ` +
|
|
1372
|
+
`Once they have approved it, try this same call again with exactly the same arguments, within ` +
|
|
1373
|
+
`${minutes} minute${minutes === 1 ? "" : "s"}. Do not ask them to type any commands: nothing needs to be ` +
|
|
1374
|
+
`run in a terminal. (Request ${row.id}.)`
|
|
1375
|
+
};
|
|
1376
|
+
}
|
|
1377
|
+
/** Polls the store until the request is decided or `deadline` passes. */
|
|
1378
|
+
async waitForDecision(id, deadline) {
|
|
1379
|
+
for (;;) {
|
|
1380
|
+
const state = this.store.get(id)?.state;
|
|
1381
|
+
if (state === "granted" || state === "used")
|
|
1382
|
+
return "granted";
|
|
1383
|
+
if (state === "denied")
|
|
1384
|
+
return "denied";
|
|
1385
|
+
if (state !== "pending")
|
|
1386
|
+
return null;
|
|
1387
|
+
const left = deadline - this.now();
|
|
1388
|
+
if (left <= 0)
|
|
1389
|
+
return null;
|
|
1390
|
+
await new Promise((r) => setTimeout(r, Math.min(WAIT_POLL_MS, left)));
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
/** How long a person's "no" to an exact call is remembered and told to the AI. */
|
|
1395
|
+
export const DENY_REMEMBER_MS = 5 * 60 * 1000;
|
|
1396
|
+
const WAIT_POLL_MS = 250;
|
|
1397
|
+
function personSaidNo(approvalId) {
|
|
1398
|
+
return {
|
|
1399
|
+
granted: false,
|
|
1400
|
+
approvalId,
|
|
1401
|
+
refusedByPerson: true,
|
|
1402
|
+
reason: "the person said no to this exact request",
|
|
1403
|
+
instructions: "The person looked at this exact request and said no. Do not try it again: for the next 5 minutes this " +
|
|
1404
|
+
"exact request is refused without asking them. Tell them it was not done, and ask what they would like " +
|
|
1405
|
+
"to do instead."
|
|
1406
|
+
};
|
|
1407
|
+
}
|
|
1408
|
+
function renderPrompt(req, redactKeys = [], canClassify = false) {
|
|
1409
|
+
// The same key list the stored row is redacted with. The prompt leaves this
|
|
1410
|
+
// process for the MCP host, so it is the last place a value the operator
|
|
1411
|
+
// asked to keep out of the record should appear in full.
|
|
1412
|
+
const args = JSON.stringify(redactArgs(req.args, redactKeys), null, 2);
|
|
1413
|
+
const lines = [
|
|
1414
|
+
`Approve a ${req.effect ?? "unclassified"} operation?`,
|
|
1415
|
+
"",
|
|
1416
|
+
`Tool: ${req.tool}`,
|
|
1417
|
+
req.target ? `Target: ${req.target}` : null,
|
|
1418
|
+
`Policy: ${req.reason}`,
|
|
1419
|
+
/*
|
|
1420
|
+
* The one hold that is nobody's decision -- it is the absence of one. A
|
|
1421
|
+
* reviewer approving these one at a time should be told that the asking
|
|
1422
|
+
* can be ended, and where. Said only for this rule, so every other prompt
|
|
1423
|
+
* is unchanged.
|
|
1424
|
+
*/
|
|
1425
|
+
...(req.ruleId === UNCLASSIFIED_RULE
|
|
1426
|
+
? [
|
|
1427
|
+
"",
|
|
1428
|
+
"Nothing classifies this tool, so you are asked about every call to it.",
|
|
1429
|
+
canClassify
|
|
1430
|
+
? "To settle that, say what it does below, or on the Tools page in the hardened-mcp console."
|
|
1431
|
+
: "To settle that, say what it does on the Tools page in the hardened-mcp console."
|
|
1432
|
+
]
|
|
1433
|
+
: []),
|
|
1434
|
+
// Which bound was exceeded and by how much. The arguments below are
|
|
1435
|
+
// redacted and truncated, so for a call held by a bound this may be the
|
|
1436
|
+
// only place the reviewer sees the value the decision is actually about.
|
|
1437
|
+
...(req.violations && req.violations.length > 0
|
|
1438
|
+
? ["", "Outside these bounds:", ...req.violations.map((v) => ` - ${v}`)]
|
|
1439
|
+
: []),
|
|
1440
|
+
"",
|
|
1441
|
+
"Arguments:",
|
|
1442
|
+
args.length > 2000 ? `${args.slice(0, 2000)}\n…(truncated)` : args
|
|
1443
|
+
];
|
|
1444
|
+
return lines.filter((l) => l !== null).join("\n");
|
|
1445
|
+
}
|