@verax-ai/body 0.6.0 → 0.7.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/dist/alarm-outbox.d.ts +18 -0
- package/dist/alarm-outbox.js +199 -0
- package/dist/alarm-webhook.d.ts +16 -0
- package/dist/alarm-webhook.js +106 -0
- package/dist/approve-cli.js +1 -1
- package/dist/cli.js +14 -0
- package/dist/config.d.ts +31 -0
- package/dist/config.js +66 -1
- package/dist/control-signature.d.ts +1 -0
- package/dist/control-signature.js +15 -3
- package/dist/doctor.js +9 -0
- package/dist/halt.d.ts +28 -9
- package/dist/halt.js +126 -18
- package/dist/incidents.d.ts +67 -0
- package/dist/incidents.js +627 -0
- package/dist/keys.d.ts +18 -1
- package/dist/keys.js +109 -5
- package/dist/main.js +6 -1
- package/dist/memory-reattest-cli.d.ts +9 -0
- package/dist/memory-reattest-cli.js +110 -0
- package/dist/memory-rehead-cli.d.ts +9 -0
- package/dist/memory-rehead-cli.js +65 -0
- package/dist/memory-store.d.ts +157 -0
- package/dist/memory-store.js +917 -0
- package/dist/operator-cli.js +4 -1
- package/dist/operator-handlers.js +29 -8
- package/dist/operator-pairing.d.ts +2 -0
- package/dist/operator-pairing.js +11 -0
- package/dist/reconcile-cli.js +3 -1
- package/dist/server.js +65 -10
- package/dist/tools/memory.d.ts +12 -6
- package/dist/tools/memory.js +80 -124
- package/dist/verify-cli.js +1 -0
- package/dist/watch.js +3 -1
- package/dist/wiring.d.ts +14 -1
- package/dist/wiring.js +84 -14
- package/package.json +3 -3
package/dist/operator-cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { lstatSync } from "node:fs";
|
|
2
2
|
import { resolve } from "node:path";
|
|
3
3
|
import { credentialsPath, credentialsReadable, readCredentials, readCredentialsAt, readRemoved, removeCredential, removedPath, } from "./operator-credentials.js";
|
|
4
|
-
import { beginPairing } from "./operator-pairing.js";
|
|
4
|
+
import { beginPairing, livePairing } from "./operator-pairing.js";
|
|
5
5
|
/**
|
|
6
6
|
* As whom the pairing code is written. An installed body runs as its own
|
|
7
7
|
* account and owns its state directory, and root asking for a code is the
|
|
@@ -111,7 +111,10 @@ export async function runOperator(argv, sys = realSys) {
|
|
|
111
111
|
}
|
|
112
112
|
}
|
|
113
113
|
if (verb === "enroll") {
|
|
114
|
+
const replaced = livePairing(writer.stateDir);
|
|
114
115
|
const { code } = beginPairing(writer.stateDir);
|
|
116
|
+
if (replaced)
|
|
117
|
+
process.stderr.write("the earlier pairing code no longer works\n");
|
|
115
118
|
process.stdout.write(`${code}\n`);
|
|
116
119
|
return 0;
|
|
117
120
|
}
|
|
@@ -4,7 +4,6 @@ import { approvalChallenge, gateApprovalSignature } from "./approval-signature.j
|
|
|
4
4
|
import { gateControlSignature, nextControlChallenge } from "./control-signature.js";
|
|
5
5
|
import { haltBody, readHalt, resumeBody } from "./halt.js";
|
|
6
6
|
import { MAX_BODY_BYTES, readJsonBody, send } from "./http-io.js";
|
|
7
|
-
import { loadOrCreateSigners } from "./keys.js";
|
|
8
7
|
import { readCredentials } from "./operator-credentials.js";
|
|
9
8
|
import { readRpConfig } from "./rp-config.js";
|
|
10
9
|
async function signedDefer(ledger, ref) {
|
|
@@ -68,12 +67,34 @@ export async function handleControl(ctx, what) {
|
|
|
68
67
|
const signature = gated.ok ? gated.signature : undefined;
|
|
69
68
|
const refused = !parsed.ok ? "bad-body" : gated.ok ? undefined : gated.error;
|
|
70
69
|
const by = ctx.subject;
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
70
|
+
if (!resuming) {
|
|
71
|
+
let state;
|
|
72
|
+
try {
|
|
73
|
+
state = {
|
|
74
|
+
...haltBody(stateDir, by, "http", Date.now(), signature),
|
|
75
|
+
...(refused ? { signatureRefused: refused } : {}),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
const message = (err instanceof Error ? err.message : String(err)).replace(/[\r\n]+/g, " ");
|
|
80
|
+
send(res, 500, { error: "halt-failed", reason: message.slice(0, 300) });
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (!readHalt(stateDir).halted) {
|
|
84
|
+
send(res, 500, { error: "halt-failed", reason: "switch-unwritable" });
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
await services.proxy.syncControlRecords();
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
const message = (err instanceof Error ? err.message : String(err)).replace(/[\r\n]+/g, " ");
|
|
92
|
+
process.stderr.write(`verax-proxy: control sync failed: ${terminalText(message)}\n`);
|
|
93
|
+
}
|
|
94
|
+
send(res, 200, state);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const state = resumeBody(stateDir, by, "http", Date.now(), signature, services.keysDir);
|
|
77
98
|
try {
|
|
78
99
|
await services.proxy.syncControlRecords();
|
|
79
100
|
}
|
|
@@ -189,7 +210,7 @@ export async function handleApprove(ctx) {
|
|
|
189
210
|
const approvals = approvalsLogFor(services.ledger);
|
|
190
211
|
const outcome = await approvePending({
|
|
191
212
|
ledger: services.ledger,
|
|
192
|
-
recordSigner:
|
|
213
|
+
recordSigner: services.recordSigner,
|
|
193
214
|
now: () => Date.now(),
|
|
194
215
|
nonce: () => crypto.randomUUID(),
|
|
195
216
|
ref,
|
|
@@ -17,6 +17,8 @@ export declare function hashPairingCode(code: string): string;
|
|
|
17
17
|
export declare function mintPairingCode(): string;
|
|
18
18
|
export declare function writePairing(stateDir: string, record: PairingRecord): void;
|
|
19
19
|
export declare function readPairing(stateDir: string): PairingRecord | null;
|
|
20
|
+
/** A pairing the door would still accept. Enrolling again replaces that code. */
|
|
21
|
+
export declare function livePairing(stateDir: string, nowMs?: number): boolean;
|
|
20
22
|
export declare function beginPairing(stateDir: string, nowMs?: number): {
|
|
21
23
|
code: string;
|
|
22
24
|
};
|
package/dist/operator-pairing.js
CHANGED
|
@@ -32,6 +32,17 @@ export function readPairing(stateDir) {
|
|
|
32
32
|
return null;
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
|
+
/** A pairing the door would still accept. Enrolling again replaces that code. */
|
|
36
|
+
export function livePairing(stateDir, nowMs = Date.now()) {
|
|
37
|
+
const row = readPairing(stateDir);
|
|
38
|
+
if (!row)
|
|
39
|
+
return false;
|
|
40
|
+
if (row.attempts >= PAIRING_MAX_ATTEMPTS)
|
|
41
|
+
return false;
|
|
42
|
+
if (nowMs > row.expiresAtMs)
|
|
43
|
+
return false;
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
35
46
|
export function beginPairing(stateDir, nowMs = Date.now()) {
|
|
36
47
|
const code = mintPairingCode();
|
|
37
48
|
writePairing(stateDir, {
|
package/dist/reconcile-cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import { loadApprovalsFromDir, loadDecisionRefsFromDir, loadEffectsFromDir, loadPolicy, parseCardCsv, parseChannelJsonl, reconcile, } from "@verax-ai/proxy";
|
|
3
|
+
import { loadApprovalsFromDir, loadDecisionRefsFromDir, loadDecisionRequestHashesFromDir, loadEffectsFromDir, loadPolicy, parseCardCsv, parseChannelJsonl, reconcile, } from "@verax-ai/proxy";
|
|
4
4
|
const SNAPSHOT_NAME = /^[0-9a-f]{64}\.json$/;
|
|
5
5
|
// The descriptors come from the parsed policy, never from the stored document: a snapshot is
|
|
6
6
|
// read with unknown keys ignored, and a block the hash does not cover must not decide a match.
|
|
@@ -220,12 +220,14 @@ export function runReconcile(argv, writeErr = (s) => process.stderr.write(s)) {
|
|
|
220
220
|
const channel = card ?? parseChannelJsonl(raw);
|
|
221
221
|
const effects = loadEffectsFromDir(parsed.stateDir);
|
|
222
222
|
const decisionRefs = loadDecisionRefsFromDir(parsed.stateDir);
|
|
223
|
+
const decisionRequestHashes = loadDecisionRequestHashesFromDir(parsed.stateDir);
|
|
223
224
|
const loaded = parsed.channel === "card" ? loadDescriptorsFromDir(parsed.stateDir) : undefined;
|
|
224
225
|
const descriptorsByPayee = loaded?.descriptorsByPayee;
|
|
225
226
|
const report = reconcile(channel, effects, {
|
|
226
227
|
toleranceMs: parsed.toleranceMs,
|
|
227
228
|
window: parsed.window,
|
|
228
229
|
decisionRefs,
|
|
230
|
+
decisionRequestHashes,
|
|
229
231
|
approvals: parsed.channel === "card" ? loadApprovalsFromDir(parsed.stateDir) : undefined,
|
|
230
232
|
skipped: card?.skipped,
|
|
231
233
|
...(descriptorsByPayee && Object.keys(descriptorsByPayee).length > 0
|
package/dist/server.js
CHANGED
|
@@ -6,15 +6,16 @@ import { Server as McpServer } from "@modelcontextprotocol/sdk/server/index.js";
|
|
|
6
6
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
7
7
|
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
8
8
|
import { bodyVersion } from "./body-version.js";
|
|
9
|
+
import { assertAlarmWebhookUrl } from "./alarm-webhook.js";
|
|
9
10
|
import { isLoopbackHost } from "./config.js";
|
|
10
11
|
import { contentLengthOverLimit, MAX_BODY_BYTES, readJsonBody, send } from "./http-io.js";
|
|
11
12
|
import { openOperatorDoor } from "./operator-door.js";
|
|
12
13
|
import { handleApprove, handleApproveChallenge, handleControl } from "./operator-handlers.js";
|
|
13
|
-
import { explain, LedgerDenyUnrecorded, loadApprovalsFromDir, terminalText } from "@verax-ai/proxy";
|
|
14
|
+
import { explain, LedgerDenyUnrecorded, loadApprovalsFromDir, loadDecisionRequestHashesFromDir, sha256Canonical, terminalText, } from "@verax-ai/proxy";
|
|
14
15
|
import { createVerifier, readBearer, resourceMetadataUrl, wwwAuthenticate } from "./auth.js";
|
|
15
16
|
import { bumpMetric, bumpUnauthenticated } from "./metrics.js";
|
|
16
17
|
import { isRevokedJti } from "./revoke.js";
|
|
17
|
-
import { loadOrCreateSigners } from "./keys.js";
|
|
18
|
+
import { loadOrCreateSigners, resolveKeysDir } from "./keys.js";
|
|
18
19
|
import { matchingInputs } from "./inputs-read.js";
|
|
19
20
|
import { readPolicySnapshots } from "./policy-store.js";
|
|
20
21
|
import { readHeartbeat, readInstallHealthNonce, readWitnessPulse } from "./health-extras.js";
|
|
@@ -44,9 +45,10 @@ export const TOOL_META = [
|
|
|
44
45
|
description: "Reads one memory item this tenant stored earlier with memory.put, by its id. " +
|
|
45
46
|
"Use it to recall a fact, a setting or a note before acting on it; nothing is written. " +
|
|
46
47
|
"Like every call it passes the policy gate and leaves a signed decision record; an id that belongs to another tenant is answered with a signed deny. " +
|
|
47
|
-
"Returns the stored item as JSON: {id, body, source, validFromMs, validUntilMs, versionHash}. " +
|
|
48
|
+
"Returns the stored item as JSON: {id, revision, body, source, validFromMs, validUntilMs, versionHash} when it matches the signed memory commit for this tenant. " +
|
|
48
49
|
"Outside the validity window the body is withheld: {stale: true, id, validUntilMs} after it, {notYetValid: true, id, validFromMs} before it. " +
|
|
49
|
-
'An unknown id answers {error: "not-found", id}.'
|
|
50
|
+
'An unknown id answers {error: "not-found", id}. ' +
|
|
51
|
+
'A changed, missing, or uncommitted item answers {error: "memory-integrity-mismatch"|"memory-integrity-missing"|"memory-integrity-unattested"|"memory-integrity-history-unavailable", id} and does not include body or source.',
|
|
50
52
|
inputSchema: {
|
|
51
53
|
type: "object",
|
|
52
54
|
additionalProperties: false,
|
|
@@ -60,8 +62,9 @@ export const TOOL_META = [
|
|
|
60
62
|
name: "memory.put",
|
|
61
63
|
description: "Writes one memory item for this tenant, or replaces the item with the same id, in the body's state directory on this machine. " +
|
|
62
64
|
"Use it to keep a fact for a later memory.get together with where it came from and how long it holds, so a stale fact is not served later. " +
|
|
63
|
-
"The call passes the policy gate and is recorded; the record carries the item's versionHash, a SHA-256 over id, body and validity window. " +
|
|
64
|
-
"
|
|
65
|
+
"The call passes the policy gate and is recorded; the record carries the item's versionHash, a SHA-256 over a v2 envelope of tenant, id, revision, body, source and validity window. " +
|
|
66
|
+
"Each write is a new revision file; the previous file is removed only after a signed commit line is appended. " +
|
|
67
|
+
"Returns {ok: true, id, revision, versionHash}. " +
|
|
65
68
|
'A missing source answers {error: "source-required"}, a missing validUntilMs {error: "validUntilMs-required"}, a malformed id {error: "id-invalid"}.',
|
|
66
69
|
inputSchema: {
|
|
67
70
|
type: "object",
|
|
@@ -181,6 +184,30 @@ export const TOOL_META = [
|
|
|
181
184
|
// authorised until that default. Headers are bounded tighter than the body.
|
|
182
185
|
const REQUEST_TIMEOUT_MS = 30_000;
|
|
183
186
|
const HEADERS_TIMEOUT_MS = 20_000;
|
|
187
|
+
/**
|
|
188
|
+
* Amount, currency and payee on a ledger approval are the arguments only when
|
|
189
|
+
* those arguments still hash to the signed request on the defer. Otherwise
|
|
190
|
+
* the copies are left off and the row is marked unbound.
|
|
191
|
+
*/
|
|
192
|
+
function approvalsForLedger(stateDir) {
|
|
193
|
+
const requestHashes = loadDecisionRequestHashesFromDir(stateDir);
|
|
194
|
+
return loadApprovalsFromDir(stateDir).map((row) => {
|
|
195
|
+
const signed = requestHashes.get(row.ref);
|
|
196
|
+
const rowHash = sha256Canonical({ name: row.subject, arguments: row.args });
|
|
197
|
+
const bound = typeof signed === "string" && signed !== "" && rowHash === signed;
|
|
198
|
+
if (!bound) {
|
|
199
|
+
const { amount: _amount, currency: _currency, payee: _payee, ...rest } = row;
|
|
200
|
+
return { ...rest, bound: false };
|
|
201
|
+
}
|
|
202
|
+
return {
|
|
203
|
+
...row,
|
|
204
|
+
bound: true,
|
|
205
|
+
amount: row.args.amountMinor,
|
|
206
|
+
currency: row.args.currency,
|
|
207
|
+
payee: row.args.payee,
|
|
208
|
+
};
|
|
209
|
+
});
|
|
210
|
+
}
|
|
184
211
|
// Unbounded GET /api/ledger stringified ~690 MB at 200k rows and threw Invalid string length (HTTP 500).
|
|
185
212
|
const DEFAULT_LEDGER_LIMIT = 1000;
|
|
186
213
|
const MAX_LEDGER_LIMIT = 5000;
|
|
@@ -346,11 +373,14 @@ function definitionsForStart(stateDir, definitionsDir, specs) {
|
|
|
346
373
|
return downstream;
|
|
347
374
|
}
|
|
348
375
|
export async function listen(config) {
|
|
349
|
-
|
|
376
|
+
if (config.alarmWebhookUrl)
|
|
377
|
+
assertAlarmWebhookUrl(config.alarmWebhookUrl);
|
|
378
|
+
const keysDir = resolveKeysDir(config.stateDir, config.keysDir);
|
|
379
|
+
const signers = loadOrCreateSigners(config.stateDir, keysDir);
|
|
350
380
|
const bodyPublicKeyPems = [signers.recordSigner.publicKeyPem, signers.effectSigner.publicKeyPem];
|
|
351
381
|
if (config.downstreamFile) {
|
|
352
382
|
try {
|
|
353
|
-
bodyPublicKeyPems.push(readFileSync(join(
|
|
383
|
+
bodyPublicKeyPems.push(readFileSync(join(keysDir, "witness.public.pem"), "utf8"));
|
|
354
384
|
}
|
|
355
385
|
catch (err) {
|
|
356
386
|
if (err.code !== "ENOENT")
|
|
@@ -369,6 +399,10 @@ export async function listen(config) {
|
|
|
369
399
|
policyFile: config.policyFile,
|
|
370
400
|
recordSigner: signers.recordSigner,
|
|
371
401
|
effectSigner: signers.effectSigner,
|
|
402
|
+
keysDir,
|
|
403
|
+
...(config.headDir ? { headDir: config.headDir } : {}),
|
|
404
|
+
...(config.alarmWebhookUrl ? { alarmWebhookUrl: config.alarmWebhookUrl } : {}),
|
|
405
|
+
...(config.alarmRetryMs !== undefined ? { alarmRetryMs: config.alarmRetryMs } : {}),
|
|
372
406
|
...(extraTools.length > 0 ? { extraTools } : {}),
|
|
373
407
|
});
|
|
374
408
|
}
|
|
@@ -386,6 +420,7 @@ export async function listen(config) {
|
|
|
386
420
|
recordBodyStart(config.stateDir, services.ledger.startedAtMs, signers.recordSigner, downstream === undefined ? undefined : { downstream });
|
|
387
421
|
}
|
|
388
422
|
catch (err) {
|
|
423
|
+
await Promise.resolve(services.stopAlarms()).catch(() => undefined);
|
|
389
424
|
services.ledger.close();
|
|
390
425
|
await closeAll(sessions);
|
|
391
426
|
throw err;
|
|
@@ -689,7 +724,7 @@ export async function listen(config) {
|
|
|
689
724
|
policy: { hash: services.policyHash, document: services.policyDocument },
|
|
690
725
|
policies: readPolicySnapshots(config.stateDir, hashes),
|
|
691
726
|
inputs: await matchingInputs(config.stateDir, decisions),
|
|
692
|
-
approvals:
|
|
727
|
+
approvals: approvalsForLedger(config.stateDir),
|
|
693
728
|
more,
|
|
694
729
|
piecesTouched,
|
|
695
730
|
limit,
|
|
@@ -811,6 +846,14 @@ export async function listen(config) {
|
|
|
811
846
|
// That is said on stderr and goes no further: thrown from a close listener
|
|
812
847
|
// it would stop the listeners after it and take the process down, and
|
|
813
848
|
// thrown after a failed start it would replace the reason the start failed.
|
|
849
|
+
const stopAlarms = async () => {
|
|
850
|
+
try {
|
|
851
|
+
await Promise.resolve(services.stopAlarms());
|
|
852
|
+
}
|
|
853
|
+
catch {
|
|
854
|
+
// A stuck retry timer must not hide the ledger close.
|
|
855
|
+
}
|
|
856
|
+
};
|
|
814
857
|
const closeLedger = () => {
|
|
815
858
|
try {
|
|
816
859
|
services.ledger.close();
|
|
@@ -819,11 +862,23 @@ export async function listen(config) {
|
|
|
819
862
|
process.stderr.write(`verax: ledger close: ${terminalText(err instanceof Error ? err.message : "fault")}\n`);
|
|
820
863
|
}
|
|
821
864
|
};
|
|
865
|
+
const rawClose = server.close.bind(server);
|
|
866
|
+
server.close = ((callback) => {
|
|
867
|
+
return rawClose((err) => {
|
|
868
|
+
void stopAlarms()
|
|
869
|
+
.catch(() => undefined)
|
|
870
|
+
.then(() => {
|
|
871
|
+
closeLedger();
|
|
872
|
+
if (callback)
|
|
873
|
+
callback(err);
|
|
874
|
+
});
|
|
875
|
+
});
|
|
876
|
+
});
|
|
822
877
|
server.on("close", () => {
|
|
823
|
-
closeLedger();
|
|
824
878
|
void closeAll(sessions);
|
|
825
879
|
});
|
|
826
880
|
const stopStart = async () => {
|
|
881
|
+
await stopAlarms();
|
|
827
882
|
closeLedger();
|
|
828
883
|
await closeAll(sessions);
|
|
829
884
|
};
|
package/dist/tools/memory.d.ts
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
import { type Principal, type ToolCall, type ToolResult } from "@verax-ai/proxy";
|
|
2
|
+
import { type IntegrityReason, type MemoryStore } from "../memory-store.ts";
|
|
3
|
+
export declare function memoryHistoryUnavailable(stateDir: string, store?: MemoryStore): boolean;
|
|
2
4
|
/** True when `id` exists under a different tenant. Does not read legacy `memory/`. */
|
|
3
|
-
export declare function memoryBelongsToOtherTenant(stateDir: string, id: string, selfKey: string): boolean;
|
|
4
|
-
/** True when this tenant already has `id` under its own memory path. */
|
|
5
|
-
export declare function memoryExistsForTenant(stateDir: string, id: string, principal: Principal): boolean;
|
|
6
|
-
export
|
|
5
|
+
export declare function memoryBelongsToOtherTenant(stateDir: string, id: string, selfKey: string, store?: MemoryStore): boolean;
|
|
6
|
+
/** True when this tenant already has `id` under its own memory path or commit. */
|
|
7
|
+
export declare function memoryExistsForTenant(stateDir: string, id: string, principal: Principal, store?: MemoryStore): boolean;
|
|
8
|
+
export type IntegritySink = (reason: IntegrityReason) => void;
|
|
9
|
+
export declare function readMemoryMeta(stateDir: string, id: string, principal?: Principal, store?: MemoryStore, onIntegrity?: IntegritySink): Promise<{
|
|
7
10
|
versionHash: string;
|
|
8
11
|
validFromMs: number;
|
|
9
12
|
validUntilMs: number;
|
|
10
13
|
} | null>;
|
|
11
|
-
export declare function memoryGet(call: ToolCall, stateDir: string, now: () => number, principal: Principal
|
|
12
|
-
|
|
14
|
+
export declare function memoryGet(call: ToolCall, stateDir: string, now: () => number, principal: Principal, store?: MemoryStore, bound?: ReadonlyArray<{
|
|
15
|
+
id: string;
|
|
16
|
+
versionHash: string;
|
|
17
|
+
}>, onIntegrity?: IntegritySink): Promise<ToolResult>;
|
|
18
|
+
export declare function memoryPut(call: ToolCall, stateDir: string, principal: Principal, putRef?: string, store?: MemoryStore): Promise<ToolResult>;
|
package/dist/tools/memory.js
CHANGED
|
@@ -1,125 +1,101 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { existsSync, readdirSync } from "node:fs";
|
|
3
|
-
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
4
|
-
import { resolve, sep } from "node:path";
|
|
5
|
-
import { canonical } from "@cedulon/core";
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
6
2
|
import { tenantKey } from "@verax-ai/proxy";
|
|
7
3
|
import { memoryQuotaBytes } from "../config.js";
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
}
|
|
4
|
+
import { loadOrCreateSigners } from "../keys.js";
|
|
5
|
+
import { memoryStoreFor } from "../memory-store.js";
|
|
11
6
|
const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
12
|
-
/** One in-process chain per tenant memory directory. The body is one process per state dir. */
|
|
13
|
-
const memoryQuotaChain = new Map();
|
|
14
|
-
function withMemoryQuotaLock(key, fn) {
|
|
15
|
-
const previous = memoryQuotaChain.get(key) ?? Promise.resolve();
|
|
16
|
-
const run = previous.then(fn, fn);
|
|
17
|
-
const settled = run.then(() => undefined, () => undefined);
|
|
18
|
-
memoryQuotaChain.set(key, settled);
|
|
19
|
-
void settled.then(() => {
|
|
20
|
-
if (memoryQuotaChain.get(key) === settled)
|
|
21
|
-
memoryQuotaChain.delete(key);
|
|
22
|
-
});
|
|
23
|
-
return run;
|
|
24
|
-
}
|
|
25
7
|
function jsonResult(value, isError = false) {
|
|
26
8
|
return {
|
|
27
9
|
content: [{ type: "text", text: JSON.stringify(value) }],
|
|
28
10
|
isError,
|
|
29
11
|
};
|
|
30
12
|
}
|
|
31
|
-
function
|
|
32
|
-
|
|
33
|
-
return null;
|
|
34
|
-
const memoryDir = resolve(stateDir, "tenants", tenantKey(principal), "memory");
|
|
35
|
-
const path = resolve(memoryDir, `${id}.json`);
|
|
36
|
-
const prefix = memoryDir.endsWith(sep) ? memoryDir : `${memoryDir}${sep}`;
|
|
37
|
-
if (!path.startsWith(prefix))
|
|
38
|
-
return null;
|
|
39
|
-
return path;
|
|
13
|
+
function integrityResult(reason, id) {
|
|
14
|
+
return jsonResult({ error: reason, id }, true);
|
|
40
15
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
return false;
|
|
45
|
-
const tenantsRoot = resolve(stateDir, "tenants");
|
|
46
|
-
if (!existsSync(tenantsRoot))
|
|
47
|
-
return false;
|
|
48
|
-
let names;
|
|
16
|
+
function storeFor(stateDir, store) {
|
|
17
|
+
if (store)
|
|
18
|
+
return store;
|
|
49
19
|
try {
|
|
50
|
-
|
|
20
|
+
return memoryStoreFor(stateDir);
|
|
51
21
|
}
|
|
52
22
|
catch {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
const path = resolve(tenantsRoot, name, "memory", `${id}.json`);
|
|
59
|
-
const prefix = resolve(tenantsRoot, name, "memory");
|
|
60
|
-
const guarded = prefix.endsWith(sep) ? prefix : `${prefix}${sep}`;
|
|
61
|
-
if (!path.startsWith(guarded))
|
|
62
|
-
continue;
|
|
63
|
-
if (existsSync(path))
|
|
64
|
-
return true;
|
|
23
|
+
const keys = loadOrCreateSigners(stateDir);
|
|
24
|
+
return memoryStoreFor(stateDir, {
|
|
25
|
+
publicKeyPem: keys.recordSigner.publicKeyPem,
|
|
26
|
+
privateKeyPem: keys.recordSigner.privateKeyPem,
|
|
27
|
+
});
|
|
65
28
|
}
|
|
66
|
-
return false;
|
|
67
29
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
30
|
+
export function memoryHistoryUnavailable(stateDir, store) {
|
|
31
|
+
return storeFor(stateDir, store).historyUnavailable;
|
|
32
|
+
}
|
|
33
|
+
/** True when `id` exists under a different tenant. Does not read legacy `memory/`. */
|
|
34
|
+
export function memoryBelongsToOtherTenant(stateDir, id, selfKey, store) {
|
|
35
|
+
if (!ID_RE.test(id))
|
|
36
|
+
return false;
|
|
37
|
+
if (!existsSync(stateDir))
|
|
38
|
+
return false;
|
|
39
|
+
return storeFor(stateDir, store).idVisibleForOtherTenant(id, selfKey);
|
|
40
|
+
}
|
|
41
|
+
/** True when this tenant already has `id` under its own memory path or commit. */
|
|
42
|
+
export function memoryExistsForTenant(stateDir, id, principal, store) {
|
|
43
|
+
if (!ID_RE.test(id))
|
|
72
44
|
return false;
|
|
73
|
-
return
|
|
45
|
+
return storeFor(stateDir, store).idHeldByTenant(id, tenantKey(principal));
|
|
74
46
|
}
|
|
75
|
-
export async function readMemoryMeta(stateDir, id, principal) {
|
|
47
|
+
export async function readMemoryMeta(stateDir, id, principal, store, onIntegrity) {
|
|
76
48
|
if (!principal)
|
|
77
49
|
return null;
|
|
78
|
-
|
|
79
|
-
|
|
50
|
+
if (typeof id !== "string" || !ID_RE.test(id))
|
|
51
|
+
return null;
|
|
52
|
+
const mem = storeFor(stateDir, store);
|
|
53
|
+
const tk = tenantKey(principal);
|
|
54
|
+
const got = await mem.withTenantLock(tk, async () => mem.verifiedRead(tk, id));
|
|
55
|
+
if (got.kind === "integrity") {
|
|
56
|
+
onIntegrity?.(got.reason);
|
|
80
57
|
return null;
|
|
81
|
-
try {
|
|
82
|
-
const item = JSON.parse(await readFile(path, "utf8"));
|
|
83
|
-
const validFromMs = typeof item.validFromMs === "number" ? item.validFromMs : 0;
|
|
84
|
-
const validUntilMs = typeof item.validUntilMs === "number" ? item.validUntilMs : 0;
|
|
85
|
-
const versionHash = typeof item.versionHash === "string"
|
|
86
|
-
? item.versionHash
|
|
87
|
-
: sha256Canonical({ id: item.id, body: item.body, validFromMs, validUntilMs });
|
|
88
|
-
return { versionHash, validFromMs, validUntilMs };
|
|
89
|
-
}
|
|
90
|
-
catch (err) {
|
|
91
|
-
if (err.code === "ENOENT")
|
|
92
|
-
return null;
|
|
93
|
-
throw err;
|
|
94
58
|
}
|
|
59
|
+
if (got.kind !== "ok")
|
|
60
|
+
return null;
|
|
61
|
+
mem.rememberDecisionSnapshot(tenantKey(principal), got.object);
|
|
62
|
+
return {
|
|
63
|
+
versionHash: got.versionHash,
|
|
64
|
+
validFromMs: got.object.validFromMs,
|
|
65
|
+
validUntilMs: got.object.validUntilMs,
|
|
66
|
+
};
|
|
95
67
|
}
|
|
96
|
-
export async function memoryGet(call, stateDir, now, principal) {
|
|
68
|
+
export async function memoryGet(call, stateDir, now, principal, store, bound = [], onIntegrity) {
|
|
97
69
|
const id = call.arguments.id;
|
|
98
70
|
if (typeof id !== "string" || id === "") {
|
|
99
71
|
return jsonResult({ error: "id-required" }, true);
|
|
100
72
|
}
|
|
101
|
-
|
|
102
|
-
if (path === null) {
|
|
73
|
+
if (!ID_RE.test(id)) {
|
|
103
74
|
return jsonResult({ error: "id-invalid" }, true);
|
|
104
75
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
return jsonResult({ stale: true, id: item.id, validUntilMs: item.validUntilMs });
|
|
112
|
-
}
|
|
113
|
-
return jsonResult(item);
|
|
76
|
+
const mem = storeFor(stateDir, store);
|
|
77
|
+
const tk = tenantKey(principal);
|
|
78
|
+
const got = await mem.withTenantLock(tk, async () => mem.verifiedRead(tk, id));
|
|
79
|
+
if (got.kind === "integrity") {
|
|
80
|
+
onIntegrity?.(got.reason);
|
|
81
|
+
return integrityResult(got.reason, id);
|
|
114
82
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
83
|
+
if (got.kind === "not-found")
|
|
84
|
+
return jsonResult({ error: "not-found", id }, true);
|
|
85
|
+
const pinned = bound.find((item) => item.id === id);
|
|
86
|
+
if (pinned && pinned.versionHash !== got.versionHash) {
|
|
87
|
+
return jsonResult({ error: "memory-changed", id }, true);
|
|
120
88
|
}
|
|
89
|
+
const item = got.object;
|
|
90
|
+
if (item.validFromMs > now()) {
|
|
91
|
+
return jsonResult({ notYetValid: true, id: item.id, validFromMs: item.validFromMs });
|
|
92
|
+
}
|
|
93
|
+
if (item.validUntilMs < now()) {
|
|
94
|
+
return jsonResult({ stale: true, id: item.id, validUntilMs: item.validUntilMs });
|
|
95
|
+
}
|
|
96
|
+
return jsonResult(item);
|
|
121
97
|
}
|
|
122
|
-
export async function memoryPut(call, stateDir, principal) {
|
|
98
|
+
export async function memoryPut(call, stateDir, principal, putRef = "", store) {
|
|
123
99
|
const id = call.arguments.id;
|
|
124
100
|
const body = call.arguments.body;
|
|
125
101
|
const source = call.arguments.source;
|
|
@@ -128,8 +104,7 @@ export async function memoryPut(call, stateDir, principal) {
|
|
|
128
104
|
if (typeof id !== "string" || id === "") {
|
|
129
105
|
return jsonResult({ error: "id-required" }, true);
|
|
130
106
|
}
|
|
131
|
-
|
|
132
|
-
if (path === null) {
|
|
107
|
+
if (!ID_RE.test(id)) {
|
|
133
108
|
return jsonResult({ error: "id-invalid" }, true);
|
|
134
109
|
}
|
|
135
110
|
if (source === null || typeof source !== "object" || Array.isArray(source)) {
|
|
@@ -139,41 +114,22 @@ export async function memoryPut(call, stateDir, principal) {
|
|
|
139
114
|
return jsonResult({ error: "validUntilMs-required" }, true);
|
|
140
115
|
}
|
|
141
116
|
const fromMs = typeof validFromMs === "number" ? validFromMs : 0;
|
|
142
|
-
const
|
|
143
|
-
const
|
|
117
|
+
const mem = storeFor(stateDir, store);
|
|
118
|
+
const written = await mem.put({
|
|
119
|
+
tenantKey: tenantKey(principal),
|
|
144
120
|
id,
|
|
145
121
|
body,
|
|
146
122
|
source,
|
|
147
123
|
validFromMs: fromMs,
|
|
148
124
|
validUntilMs,
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const dir = resolve(stateDir, "tenants", tenantKey(principal), "memory");
|
|
152
|
-
const payload = `${JSON.stringify(rec)}\n`;
|
|
153
|
-
return withMemoryQuotaLock(dir, async () => {
|
|
154
|
-
let used = 0;
|
|
155
|
-
try {
|
|
156
|
-
for (const name of await readdir(dir)) {
|
|
157
|
-
const file = resolve(dir, name);
|
|
158
|
-
if (file === path)
|
|
159
|
-
continue;
|
|
160
|
-
const info = await stat(file);
|
|
161
|
-
if (info.isFile())
|
|
162
|
-
used += info.size;
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
catch (err) {
|
|
166
|
-
if (err.code !== "ENOENT")
|
|
167
|
-
throw err;
|
|
168
|
-
}
|
|
169
|
-
if (used + Buffer.byteLength(payload) > memoryQuotaBytes()) {
|
|
170
|
-
return jsonResult({ error: "memory-quota" }, true);
|
|
171
|
-
}
|
|
172
|
-
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
173
|
-
await writeFile(path, payload, {
|
|
174
|
-
encoding: "utf8",
|
|
175
|
-
mode: 0o600,
|
|
176
|
-
});
|
|
177
|
-
return jsonResult({ ok: true, id, versionHash });
|
|
125
|
+
putRef,
|
|
126
|
+
quotaBytes: memoryQuotaBytes(),
|
|
178
127
|
});
|
|
128
|
+
if (!written.ok) {
|
|
129
|
+
if (written.error === "memory-integrity-history-unavailable") {
|
|
130
|
+
return integrityResult(written.error, id);
|
|
131
|
+
}
|
|
132
|
+
return jsonResult({ error: written.error }, true);
|
|
133
|
+
}
|
|
134
|
+
return jsonResult({ ok: true, id: written.id, revision: written.revision, versionHash: written.versionHash });
|
|
179
135
|
}
|
package/dist/verify-cli.js
CHANGED
package/dist/watch.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
3
|
import { setTimeout as delay } from "node:timers/promises";
|
|
4
|
-
import { haltBody } from "./halt.js";
|
|
4
|
+
import { haltBody, readHalt } from "./halt.js";
|
|
5
5
|
import { readHeartbeat } from "./health-extras.js";
|
|
6
6
|
import { isLoopbackHost } from "./config.js";
|
|
7
7
|
const USAGE = "usage: verax watch <stateDir> | --url <https://host/healthz> --token-file <path> [--max-silence 30s] [--once] [--on-silence halt|exec] [--exec <command>]";
|
|
@@ -184,6 +184,8 @@ export async function runWatch(argv, hooks = {}) {
|
|
|
184
184
|
else {
|
|
185
185
|
try {
|
|
186
186
|
haltBody(opts.stateDir, "verax-watch", "cli", now);
|
|
187
|
+
if (!readHalt(opts.stateDir).halted)
|
|
188
|
+
actionResult = "halt-failed";
|
|
187
189
|
}
|
|
188
190
|
catch {
|
|
189
191
|
actionResult = "halt-failed";
|
package/dist/wiring.d.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { createProxy, FileLedger, type EffectSigner, type ExplainOpts, type Policy, type Principal, type RecordSigner, type ToolCall, type ToolResult } from "@verax-ai/proxy";
|
|
2
|
-
|
|
2
|
+
import { type MemoryStore } from "./memory-store.ts";
|
|
3
|
+
export type BoundInput = {
|
|
4
|
+
id: string;
|
|
5
|
+
versionHash: string;
|
|
6
|
+
};
|
|
7
|
+
export type ToolFn = (call: ToolCall, principal: Principal, ref?: string, bound?: ReadonlyArray<BoundInput>) => Promise<ToolResult>;
|
|
3
8
|
export declare const TOOL_NAMES: readonly ["memory.get", "memory.put", "audit.explain", "message.read", "message.send", "spend"];
|
|
4
9
|
export type ExtraTool = {
|
|
5
10
|
name: string;
|
|
@@ -13,6 +18,10 @@ export type BodyServices = {
|
|
|
13
18
|
policyDocument: unknown;
|
|
14
19
|
listTools: () => readonly string[];
|
|
15
20
|
explainOpts: () => Promise<ExplainOpts>;
|
|
21
|
+
recordSigner: RecordSigner;
|
|
22
|
+
memoryStore: MemoryStore;
|
|
23
|
+
stopAlarms: () => Promise<void>;
|
|
24
|
+
keysDir?: string;
|
|
16
25
|
};
|
|
17
26
|
/**
|
|
18
27
|
* Tool functions live in a Map that is not exported. The only way to
|
|
@@ -28,4 +37,8 @@ export declare function createBodyServices(opts: {
|
|
|
28
37
|
now?: () => number;
|
|
29
38
|
nonce?: () => string;
|
|
30
39
|
extraTools?: readonly ExtraTool[];
|
|
40
|
+
keysDir?: string;
|
|
41
|
+
headDir?: string;
|
|
42
|
+
alarmWebhookUrl?: string;
|
|
43
|
+
alarmRetryMs?: number;
|
|
31
44
|
}): BodyServices;
|