@verax-ai/body 0.6.1 → 0.8.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.
@@ -20,7 +20,8 @@
20
20
  import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
21
21
  import { rmSync } from "node:fs";
22
22
  import { createServer } from "node:http";
23
- import { loadApprovalsFromDir, terminalText } from "@verax-ai/proxy";
23
+ import { approvalDispatchArgs, loadApprovalsFromDir, terminalText } from "@verax-ai/proxy";
24
+ import { boundOnDisk } from "./approval-bound.js";
24
25
  import { asAssertion } from "./approval-signature.js";
25
26
  import { readBearer } from "./auth.js";
26
27
  import { heldSpend } from "./held-spend.js";
@@ -410,15 +411,18 @@ export async function openOperatorDoor(opts) {
410
411
  }
411
412
  if (url.pathname === "/api/waiting") {
412
413
  const at = now();
414
+ // A row edited on disk is not listed: what the phone shows is what
415
+ // the signed defer names, and that is what an approval sends.
416
+ const isBound = boundOnDisk(stateDir);
413
417
  const waiting = loadApprovalsFromDir(stateDir)
414
- .filter((row) => row.status === "pending" && row.expiresAtMs > at)
418
+ .filter((row) => row.status === "pending" && row.expiresAtMs > at && isBound(row))
415
419
  .map((row) => {
416
420
  const spend = heldSpend(row);
417
421
  return {
418
422
  ref: row.ref,
419
423
  requestHash: row.requestHash,
420
424
  tool: row.subject,
421
- args: row.args,
425
+ args: approvalDispatchArgs(row),
422
426
  agent: row.brain,
423
427
  rule: row.ruleText,
424
428
  ...(row.createdAtMs !== undefined ? { createdAtMs: row.createdAtMs } : {}),
@@ -1,10 +1,10 @@
1
1
  import { decisionRecordHash } from "@cedulon/core";
2
2
  import { approvalsLogFor, approvePending, createApprovalBudgetGuard, loadApprovalsFromDir, terminalText } from "@verax-ai/proxy";
3
+ import { boundOnDisk } from "./approval-bound.js";
3
4
  import { approvalChallenge, gateApprovalSignature } from "./approval-signature.js";
4
5
  import { gateControlSignature, nextControlChallenge } from "./control-signature.js";
5
6
  import { haltBody, readHalt, resumeBody } from "./halt.js";
6
7
  import { MAX_BODY_BYTES, readJsonBody, send } from "./http-io.js";
7
- import { loadOrCreateSigners } from "./keys.js";
8
8
  import { readCredentials } from "./operator-credentials.js";
9
9
  import { readRpConfig } from "./rp-config.js";
10
10
  async function signedDefer(ledger, ref) {
@@ -68,12 +68,34 @@ export async function handleControl(ctx, what) {
68
68
  const signature = gated.ok ? gated.signature : undefined;
69
69
  const refused = !parsed.ok ? "bad-body" : gated.ok ? undefined : gated.error;
70
70
  const by = ctx.subject;
71
- const state = resuming
72
- ? resumeBody(stateDir, by, "http", Date.now(), signature)
73
- : {
74
- ...haltBody(stateDir, by, "http", Date.now(), signature),
75
- ...(refused ? { signatureRefused: refused } : {}),
76
- };
71
+ if (!resuming) {
72
+ let state;
73
+ try {
74
+ state = {
75
+ ...haltBody(stateDir, by, "http", Date.now(), signature),
76
+ ...(refused ? { signatureRefused: refused } : {}),
77
+ };
78
+ }
79
+ catch (err) {
80
+ const message = (err instanceof Error ? err.message : String(err)).replace(/[\r\n]+/g, " ");
81
+ send(res, 500, { error: "halt-failed", reason: message.slice(0, 300) });
82
+ return;
83
+ }
84
+ if (!readHalt(stateDir).halted) {
85
+ send(res, 500, { error: "halt-failed", reason: "switch-unwritable" });
86
+ return;
87
+ }
88
+ try {
89
+ await services.proxy.syncControlRecords();
90
+ }
91
+ catch (err) {
92
+ const message = (err instanceof Error ? err.message : String(err)).replace(/[\r\n]+/g, " ");
93
+ process.stderr.write(`verax-proxy: control sync failed: ${terminalText(message)}\n`);
94
+ }
95
+ send(res, 200, state);
96
+ return;
97
+ }
98
+ const state = resumeBody(stateDir, by, "http", Date.now(), signature, services.keysDir);
77
99
  try {
78
100
  await services.proxy.syncControlRecords();
79
101
  }
@@ -149,6 +171,12 @@ export async function handleApprove(ctx) {
149
171
  send(res, 409, { error: "stale", requestHash: waiting.requestHash });
150
172
  return;
151
173
  }
174
+ // The row on disk is what the phone showed; the body approves its own copy.
175
+ // A row the signed defer does not name is not approved.
176
+ if (!boundOnDisk(stateDir)(waiting)) {
177
+ send(res, 409, { error: "row-unbound" });
178
+ return;
179
+ }
152
180
  const deferRecord = await signedDefer(services.ledger, ref);
153
181
  if (!deferRecord) {
154
182
  send(res, 404, { error: "unknown-ref" });
@@ -189,7 +217,7 @@ export async function handleApprove(ctx) {
189
217
  const approvals = approvalsLogFor(services.ledger);
190
218
  const outcome = await approvePending({
191
219
  ledger: services.ledger,
192
- recordSigner: loadOrCreateSigners(stateDir).recordSigner,
220
+ recordSigner: services.recordSigner,
193
221
  now: () => Date.now(),
194
222
  nonce: () => crypto.randomUUID(),
195
223
  ref,
@@ -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, loadDecisionRequestHashesFromDir, loadEffectsFromDir, loadPolicy, parseCardCsv, parseChannelJsonl, reconcile, } from "@verax-ai/proxy";
3
+ import { loadApprovalsFromDir, loadDecisionRefsFromDir, loadDecisionRequestHashesFromDir, loadSignedForwardedHashesFromDir, 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.
@@ -221,6 +221,7 @@ export function runReconcile(argv, writeErr = (s) => process.stderr.write(s)) {
221
221
  const effects = loadEffectsFromDir(parsed.stateDir);
222
222
  const decisionRefs = loadDecisionRefsFromDir(parsed.stateDir);
223
223
  const decisionRequestHashes = loadDecisionRequestHashesFromDir(parsed.stateDir);
224
+ const decisionForwardedHashes = loadSignedForwardedHashesFromDir(parsed.stateDir);
224
225
  const loaded = parsed.channel === "card" ? loadDescriptorsFromDir(parsed.stateDir) : undefined;
225
226
  const descriptorsByPayee = loaded?.descriptorsByPayee;
226
227
  const report = reconcile(channel, effects, {
@@ -228,6 +229,7 @@ export function runReconcile(argv, writeErr = (s) => process.stderr.write(s)) {
228
229
  window: parsed.window,
229
230
  decisionRefs,
230
231
  decisionRequestHashes,
232
+ decisionForwardedHashes,
231
233
  approvals: parsed.channel === "card" ? loadApprovalsFromDir(parsed.stateDir) : undefined,
232
234
  skipped: card?.skipped,
233
235
  ...(descriptorsByPayee && Object.keys(descriptorsByPayee).length > 0
package/dist/server.js CHANGED
@@ -6,15 +6,17 @@ 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, loadDecisionRequestHashesFromDir, sha256Canonical, terminalText, } from "@verax-ai/proxy";
14
+ import { boundOnDisk } from "./approval-bound.js";
15
+ import { approvalDispatchArgs, explain, LedgerDenyUnrecorded, loadApprovalsFromDir, terminalText, } from "@verax-ai/proxy";
14
16
  import { createVerifier, readBearer, resourceMetadataUrl, wwwAuthenticate } from "./auth.js";
15
17
  import { bumpMetric, bumpUnauthenticated } from "./metrics.js";
16
18
  import { isRevokedJti } from "./revoke.js";
17
- import { loadOrCreateSigners } from "./keys.js";
19
+ import { loadOrCreateSigners, resolveKeysDir } from "./keys.js";
18
20
  import { matchingInputs } from "./inputs-read.js";
19
21
  import { readPolicySnapshots } from "./policy-store.js";
20
22
  import { readHeartbeat, readInstallHealthNonce, readWitnessPulse } from "./health-extras.js";
@@ -44,9 +46,10 @@ export const TOOL_META = [
44
46
  description: "Reads one memory item this tenant stored earlier with memory.put, by its id. " +
45
47
  "Use it to recall a fact, a setting or a note before acting on it; nothing is written. " +
46
48
  "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}. " +
49
+ "Returns the stored item as JSON: {id, revision, body, source, validFromMs, validUntilMs, versionHash} when it matches the signed memory commit for this tenant. " +
48
50
  "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}.',
51
+ 'An unknown id answers {error: "not-found", id}. ' +
52
+ '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
53
  inputSchema: {
51
54
  type: "object",
52
55
  additionalProperties: false,
@@ -60,8 +63,9 @@ export const TOOL_META = [
60
63
  name: "memory.put",
61
64
  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
65
  "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
- "Returns {ok: true, id, versionHash}. " +
66
+ "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. " +
67
+ "Each write is a new revision file; the previous file is removed only after a signed commit line is appended. " +
68
+ "Returns {ok: true, id, revision, versionHash}. " +
65
69
  'A missing source answers {error: "source-required"}, a missing validUntilMs {error: "validUntilMs-required"}, a malformed id {error: "id-invalid"}.',
66
70
  inputSchema: {
67
71
  type: "object",
@@ -187,21 +191,21 @@ const HEADERS_TIMEOUT_MS = 20_000;
187
191
  * the copies are left off and the row is marked unbound.
188
192
  */
189
193
  function approvalsForLedger(stateDir) {
190
- const requestHashes = loadDecisionRequestHashesFromDir(stateDir);
194
+ const isBound = boundOnDisk(stateDir);
191
195
  return loadApprovalsFromDir(stateDir).map((row) => {
192
- const signed = requestHashes.get(row.ref);
193
- const rowHash = sha256Canonical({ name: row.subject, arguments: row.args });
194
- const bound = typeof signed === "string" && signed !== "" && rowHash === signed;
196
+ const bound = isBound(row);
197
+ const shown = approvalDispatchArgs(row);
195
198
  if (!bound) {
196
199
  const { amount: _amount, currency: _currency, payee: _payee, ...rest } = row;
197
- return { ...rest, bound: false };
200
+ return { ...rest, bound: false, args: shown };
198
201
  }
199
202
  return {
200
203
  ...row,
201
204
  bound: true,
202
- amount: row.args.amountMinor,
203
- currency: row.args.currency,
204
- payee: row.args.payee,
205
+ args: shown,
206
+ amount: shown.amountMinor,
207
+ currency: shown.currency,
208
+ payee: shown.payee,
205
209
  };
206
210
  });
207
211
  }
@@ -370,11 +374,14 @@ function definitionsForStart(stateDir, definitionsDir, specs) {
370
374
  return downstream;
371
375
  }
372
376
  export async function listen(config) {
373
- const signers = loadOrCreateSigners(config.stateDir);
377
+ if (config.alarmWebhookUrl)
378
+ assertAlarmWebhookUrl(config.alarmWebhookUrl);
379
+ const keysDir = resolveKeysDir(config.stateDir, config.keysDir);
380
+ const signers = loadOrCreateSigners(config.stateDir, keysDir);
374
381
  const bodyPublicKeyPems = [signers.recordSigner.publicKeyPem, signers.effectSigner.publicKeyPem];
375
382
  if (config.downstreamFile) {
376
383
  try {
377
- bodyPublicKeyPems.push(readFileSync(join(config.stateDir, "keys", "witness.public.pem"), "utf8"));
384
+ bodyPublicKeyPems.push(readFileSync(join(keysDir, "witness.public.pem"), "utf8"));
378
385
  }
379
386
  catch (err) {
380
387
  if (err.code !== "ENOENT")
@@ -393,6 +400,10 @@ export async function listen(config) {
393
400
  policyFile: config.policyFile,
394
401
  recordSigner: signers.recordSigner,
395
402
  effectSigner: signers.effectSigner,
403
+ keysDir,
404
+ ...(config.headDir ? { headDir: config.headDir } : {}),
405
+ ...(config.alarmWebhookUrl ? { alarmWebhookUrl: config.alarmWebhookUrl } : {}),
406
+ ...(config.alarmRetryMs !== undefined ? { alarmRetryMs: config.alarmRetryMs } : {}),
396
407
  ...(extraTools.length > 0 ? { extraTools } : {}),
397
408
  });
398
409
  }
@@ -410,6 +421,7 @@ export async function listen(config) {
410
421
  recordBodyStart(config.stateDir, services.ledger.startedAtMs, signers.recordSigner, downstream === undefined ? undefined : { downstream });
411
422
  }
412
423
  catch (err) {
424
+ await Promise.resolve(services.stopAlarms()).catch(() => undefined);
413
425
  services.ledger.close();
414
426
  await closeAll(sessions);
415
427
  throw err;
@@ -835,6 +847,14 @@ export async function listen(config) {
835
847
  // That is said on stderr and goes no further: thrown from a close listener
836
848
  // it would stop the listeners after it and take the process down, and
837
849
  // thrown after a failed start it would replace the reason the start failed.
850
+ const stopAlarms = async () => {
851
+ try {
852
+ await Promise.resolve(services.stopAlarms());
853
+ }
854
+ catch {
855
+ // A stuck retry timer must not hide the ledger close.
856
+ }
857
+ };
838
858
  const closeLedger = () => {
839
859
  try {
840
860
  services.ledger.close();
@@ -843,11 +863,23 @@ export async function listen(config) {
843
863
  process.stderr.write(`verax: ledger close: ${terminalText(err instanceof Error ? err.message : "fault")}\n`);
844
864
  }
845
865
  };
866
+ const rawClose = server.close.bind(server);
867
+ server.close = ((callback) => {
868
+ return rawClose((err) => {
869
+ void stopAlarms()
870
+ .catch(() => undefined)
871
+ .then(() => {
872
+ closeLedger();
873
+ if (callback)
874
+ callback(err);
875
+ });
876
+ });
877
+ });
846
878
  server.on("close", () => {
847
- closeLedger();
848
879
  void closeAll(sessions);
849
880
  });
850
881
  const stopStart = async () => {
882
+ await stopAlarms();
851
883
  closeLedger();
852
884
  await closeAll(sessions);
853
885
  };
@@ -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 declare function readMemoryMeta(stateDir: string, id: string, principal?: Principal): Promise<{
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): Promise<ToolResult>;
12
- export declare function memoryPut(call: ToolCall, stateDir: string, principal: Principal): Promise<ToolResult>;
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>;
@@ -1,125 +1,101 @@
1
- import { createHash } from "node:crypto";
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
- function sha256Canonical(value) {
9
- return createHash("sha256").update(canonical(value), "utf8").digest("hex");
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 resolveMemoryPath(stateDir, id, principal) {
32
- if (!ID_RE.test(id))
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
- /** True when `id` exists under a different tenant. Does not read legacy `memory/`. */
42
- export function memoryBelongsToOtherTenant(stateDir, id, selfKey) {
43
- if (!ID_RE.test(id))
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
- names = readdirSync(tenantsRoot);
20
+ return memoryStoreFor(stateDir);
51
21
  }
52
22
  catch {
53
- return false;
54
- }
55
- for (const name of names) {
56
- if (name === selfKey)
57
- continue;
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
- /** True when this tenant already has `id` under its own memory path. */
69
- export function memoryExistsForTenant(stateDir, id, principal) {
70
- const path = resolveMemoryPath(stateDir, id, principal);
71
- if (path === null)
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 existsSync(path);
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
- const path = resolveMemoryPath(stateDir, id, principal);
79
- if (path === null)
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
- const path = resolveMemoryPath(stateDir, id, principal);
102
- if (path === null) {
73
+ if (!ID_RE.test(id)) {
103
74
  return jsonResult({ error: "id-invalid" }, true);
104
75
  }
105
- try {
106
- const item = JSON.parse(await readFile(path, "utf8"));
107
- if (typeof item.validFromMs === "number" && item.validFromMs > now()) {
108
- return jsonResult({ notYetValid: true, id: item.id, validFromMs: item.validFromMs });
109
- }
110
- if (typeof item.validUntilMs === "number" && item.validUntilMs < now()) {
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
- catch (err) {
116
- if (err.code === "ENOENT") {
117
- return jsonResult({ error: "not-found", id }, true);
118
- }
119
- throw err;
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
- const path = resolveMemoryPath(stateDir, id, principal);
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 versionHash = sha256Canonical({ id, body, validFromMs: fromMs, validUntilMs });
143
- const rec = {
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
- versionHash,
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
  }
@@ -104,6 +104,7 @@ const CONTROL_NOT_CHECKED = {
104
104
  unsignedHttp: 0,
105
105
  cli: 0,
106
106
  file: 0,
107
+ integrity: 0,
107
108
  line: "control signatures not checked",
108
109
  trustSource: "none",
109
110
  trustNote: "control signatures were not checked",
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
- export type ToolFn = (call: ToolCall, principal: Principal, ref?: string) => Promise<ToolResult>;
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;