@verax-ai/body 0.4.6 → 0.4.7
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/cli.js +17 -0
- package/dist/doctor.js +3 -3
- package/dist/health-extras.d.ts +3 -0
- package/dist/health-extras.js +3 -0
- package/dist/heartbeat.d.ts +21 -0
- package/dist/heartbeat.js +64 -0
- package/dist/no-bypass-scan.js +2 -2
- package/dist/server.js +24 -5
- package/dist/verify-cli.d.ts +2 -1
- package/dist/verify-cli.js +9 -5
- package/dist/watch.d.ts +19 -0
- package/dist/watch.js +220 -0
- package/package.json +3 -3
package/dist/cli.js
CHANGED
|
@@ -16,6 +16,7 @@ import { runReconcile } from "./reconcile-cli.js";
|
|
|
16
16
|
import { runVerify } from "./verify-cli.js";
|
|
17
17
|
import { runUnlock } from "./unlock.js";
|
|
18
18
|
import { runWitness } from "./witness.js";
|
|
19
|
+
import { runWatch } from "./watch.js";
|
|
19
20
|
const HELP = `verax - the body an agent asks before it acts, and the ledger it answers from.
|
|
20
21
|
|
|
21
22
|
Usage: verax <command> [options]
|
|
@@ -54,6 +55,9 @@ Usage: verax <command> [options]
|
|
|
54
55
|
register each checkpoint's hash with a transparency service
|
|
55
56
|
someone else runs and keep its receipt for verify --anchor-key
|
|
56
57
|
witness <stateDir> run the witness alongside a body
|
|
58
|
+
watch <stateDir> [--max-silence 30s] [--once] [--on-silence halt|exec] [--exec <command>]
|
|
59
|
+
halt on silence; --url <https://host/healthz> --token-file <path>
|
|
60
|
+
reports remotely (remote halt is out of scope)
|
|
57
61
|
halt <stateDir> stop the body from allowing anything further
|
|
58
62
|
resume <stateDir> lift a halt; who and when go to halt-history.jsonl
|
|
59
63
|
unlock [--force] <stateDir> clear a stale ledger lock
|
|
@@ -168,6 +172,19 @@ async function dispatchCli(argv, stdout, stderr, env) {
|
|
|
168
172
|
}
|
|
169
173
|
return runHalt(stateDir, (s) => stderr.write(s));
|
|
170
174
|
}
|
|
175
|
+
if (argv[0] === "watch") {
|
|
176
|
+
const controller = new AbortController();
|
|
177
|
+
const stop = () => controller.abort();
|
|
178
|
+
process.once("SIGINT", stop);
|
|
179
|
+
process.once("SIGTERM", stop);
|
|
180
|
+
try {
|
|
181
|
+
return await runWatch(argv.slice(1), { stdout, stderr, env, signal: controller.signal });
|
|
182
|
+
}
|
|
183
|
+
finally {
|
|
184
|
+
process.removeListener("SIGINT", stop);
|
|
185
|
+
process.removeListener("SIGTERM", stop);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
171
188
|
if (argv[0] === "resume") {
|
|
172
189
|
const stateDir = argv[1];
|
|
173
190
|
if (!stateDir) {
|
package/dist/doctor.js
CHANGED
|
@@ -464,12 +464,12 @@ function evidenceChecks(stateDir, env) {
|
|
|
464
464
|
hb = null;
|
|
465
465
|
}
|
|
466
466
|
}
|
|
467
|
-
if (srcLines > 0 || hb) {
|
|
467
|
+
if (srcLines > 0 || hb || existsSync(hbPath)) {
|
|
468
468
|
if (!hb || typeof hb.atMs !== "number") {
|
|
469
469
|
checks.push({
|
|
470
470
|
id: "heartbeat",
|
|
471
471
|
level: "fail",
|
|
472
|
-
detail: "
|
|
472
|
+
detail: "no readable heartbeat; the body looks stopped or its pulse cannot be written",
|
|
473
473
|
});
|
|
474
474
|
}
|
|
475
475
|
else if (!Number.isFinite(hb.atMs) || hb.atMs > Date.now() + HEARTBEAT_FUTURE_SKEW_MS) {
|
|
@@ -483,7 +483,7 @@ function evidenceChecks(stateDir, env) {
|
|
|
483
483
|
checks.push({
|
|
484
484
|
id: "heartbeat",
|
|
485
485
|
level: "fail",
|
|
486
|
-
detail: `heartbeat is silent; last pulse ${hb.atMs} lastDecisionN ${String(hb.lastDecisionN ?? "?")}`,
|
|
486
|
+
detail: `heartbeat is silent; body stopped or pulse unavailable; last pulse ${hb.atMs} lastDecisionN ${String(hb.lastDecisionN ?? "?")}`,
|
|
487
487
|
});
|
|
488
488
|
}
|
|
489
489
|
else {
|
package/dist/health-extras.d.ts
CHANGED
|
@@ -4,6 +4,9 @@ export declare const INSTALL_HEALTH_NONCE = "install-health-nonce";
|
|
|
4
4
|
export declare function readInstallHealthNonce(stateDir: string): string | null;
|
|
5
5
|
export type HealthHeartbeat = {
|
|
6
6
|
atMs: number;
|
|
7
|
+
pid?: number;
|
|
8
|
+
startedAtMs?: number;
|
|
9
|
+
beat?: "timer" | "row";
|
|
7
10
|
lastDecisionN: number;
|
|
8
11
|
lastEffectN: number;
|
|
9
12
|
};
|
package/dist/health-extras.js
CHANGED
|
@@ -24,6 +24,9 @@ export function readHeartbeat(stateDir) {
|
|
|
24
24
|
return null;
|
|
25
25
|
return {
|
|
26
26
|
atMs: raw.atMs,
|
|
27
|
+
...(typeof raw.pid === "number" ? { pid: raw.pid } : {}),
|
|
28
|
+
...(typeof raw.startedAtMs === "number" ? { startedAtMs: raw.startedAtMs } : {}),
|
|
29
|
+
...(raw.beat === "timer" || raw.beat === "row" ? { beat: raw.beat } : {}),
|
|
27
30
|
lastDecisionN: typeof raw.lastDecisionN === "number" ? raw.lastDecisionN : 0,
|
|
28
31
|
lastEffectN: typeof raw.lastEffectN === "number" ? raw.lastEffectN : 0,
|
|
29
32
|
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { FileLedger } from "@verax-ai/proxy";
|
|
2
|
+
export type StartRow = {
|
|
3
|
+
action: "start";
|
|
4
|
+
atMs: number;
|
|
5
|
+
prevBeatAtMs: number | null;
|
|
6
|
+
gapMs: number | null;
|
|
7
|
+
pid: number;
|
|
8
|
+
};
|
|
9
|
+
export declare function heartbeatEveryMs(env?: NodeJS.ProcessEnv): number;
|
|
10
|
+
/** Separate from halt history: starts are unsigned observations, not controls. */
|
|
11
|
+
export declare function recordBodyStart(stateDir: string, atMs: number): void;
|
|
12
|
+
export declare function startHeartbeat(ledger: FileLedger): () => void;
|
|
13
|
+
export type StartSummary = {
|
|
14
|
+
count: number;
|
|
15
|
+
largestGapMs: number | null;
|
|
16
|
+
missingPreviousBeat: number[];
|
|
17
|
+
unsigned: true;
|
|
18
|
+
warnings: string[];
|
|
19
|
+
};
|
|
20
|
+
export declare function readStartSummary(stateDir: string): StartSummary;
|
|
21
|
+
export declare function renderStarts(summary: StartSummary): string;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { appendFileSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { readHeartbeat } from "./health-extras.js";
|
|
4
|
+
export function heartbeatEveryMs(env = process.env) {
|
|
5
|
+
const n = Number(env.VERAX_HEARTBEAT_EVERY_MS ?? "10000");
|
|
6
|
+
return Number.isFinite(n) && n > 0 ? Math.min(2_147_483_647, Math.max(1000, Math.floor(n))) : 10_000;
|
|
7
|
+
}
|
|
8
|
+
/** Separate from halt history: starts are unsigned observations, not controls. */
|
|
9
|
+
export function recordBodyStart(stateDir, atMs) {
|
|
10
|
+
const prevBeatAtMs = readHeartbeat(stateDir)?.atMs ?? null;
|
|
11
|
+
const row = { action: "start", atMs, prevBeatAtMs, gapMs: prevBeatAtMs === null ? null : atMs - prevBeatAtMs, pid: process.pid };
|
|
12
|
+
appendFileSync(join(stateDir, "starts.jsonl"), `${JSON.stringify(row)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
13
|
+
}
|
|
14
|
+
export function startHeartbeat(ledger) {
|
|
15
|
+
ledger.pulseHeartbeat("timer");
|
|
16
|
+
const timer = setInterval(() => {
|
|
17
|
+
try {
|
|
18
|
+
ledger.pulseHeartbeat("timer");
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// A failed write must leave the old timestamp for the watcher to detect.
|
|
22
|
+
process.stderr.write("verax-heartbeat: pulse could not be written\n");
|
|
23
|
+
}
|
|
24
|
+
}, heartbeatEveryMs());
|
|
25
|
+
timer.unref();
|
|
26
|
+
return () => clearInterval(timer);
|
|
27
|
+
}
|
|
28
|
+
export function readStartSummary(stateDir) {
|
|
29
|
+
const result = { count: 0, largestGapMs: null, missingPreviousBeat: [], unsigned: true, warnings: [] };
|
|
30
|
+
let raw;
|
|
31
|
+
try {
|
|
32
|
+
raw = readFileSync(join(stateDir, "starts.jsonl"), "utf8");
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
if (err.code !== "ENOENT")
|
|
36
|
+
result.warnings.push("starts.jsonl could not be read");
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
for (const [i, line] of raw.split("\n").entries()) {
|
|
40
|
+
if (line.trim() === "")
|
|
41
|
+
continue;
|
|
42
|
+
try {
|
|
43
|
+
const row = JSON.parse(line);
|
|
44
|
+
if (!row || row.action !== "start" || !Number.isFinite(row.atMs) || !Number.isInteger(row.pid)
|
|
45
|
+
|| !(row.prevBeatAtMs === null || Number.isFinite(row.prevBeatAtMs))
|
|
46
|
+
|| !(row.gapMs === null || Number.isFinite(row.gapMs))
|
|
47
|
+
|| (row.prevBeatAtMs === null) !== (row.gapMs === null))
|
|
48
|
+
throw new Error("start row shape");
|
|
49
|
+
result.count += 1;
|
|
50
|
+
if (row.prevBeatAtMs === null)
|
|
51
|
+
result.missingPreviousBeat.push(row.atMs);
|
|
52
|
+
if (row.gapMs !== null)
|
|
53
|
+
result.largestGapMs = result.largestGapMs === null ? row.gapMs : Math.max(result.largestGapMs, row.gapMs);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
result.warnings.push(`starts.jsonl line ${i + 1} is unreadable`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
61
|
+
export function renderStarts(summary) {
|
|
62
|
+
return `starts ${summary.count}; largest gap ${summary.largestGapMs === null ? "none" : `${summary.largestGapMs} ms`}; previous beat missing at ${summary.missingPreviousBeat.join(", ") || "none"}; unsigned (not verified)`
|
|
63
|
+
+ summary.warnings.map((warning) => `\nwarning ${warning}`).join("");
|
|
64
|
+
}
|
package/dist/no-bypass-scan.js
CHANGED
|
@@ -53,8 +53,8 @@ export function scanNoBypass(base = pkgRoot, extra = []) {
|
|
|
53
53
|
continue;
|
|
54
54
|
const wiring = rel === "src/wiring.ts";
|
|
55
55
|
// Desktop supervises issuer/body/panel. Install copies the body under another
|
|
56
|
-
// account.
|
|
57
|
-
const desktop = rel === "src/desktop.ts" || rel === "src/install.ts";
|
|
56
|
+
// account. Watch runs an operator's isolation command. None is a tool-call path.
|
|
57
|
+
const desktop = rel === "src/desktop.ts" || rel === "src/install.ts" || rel === "src/watch.ts";
|
|
58
58
|
// The downstream spike attaches one stdio MCP server. Not a tool-call path.
|
|
59
59
|
const downstream = rel === "src/downstream.ts";
|
|
60
60
|
const originalLines = text.split(/\r?\n/);
|
package/dist/server.js
CHANGED
|
@@ -21,6 +21,7 @@ import { readHeartbeat, readInstallHealthNonce, readWitnessPulse } from "./healt
|
|
|
21
21
|
import { agentsWindow } from "./agents.js";
|
|
22
22
|
import { gateControlSignature, nextControlChallenge } from "./control-signature.js";
|
|
23
23
|
import { haltBody, readHalt, resumeBody } from "./halt.js";
|
|
24
|
+
import { recordBodyStart, startHeartbeat } from "./heartbeat.js";
|
|
24
25
|
import { inventoryHealth, readInventoryFile } from "./inventory-file.js";
|
|
25
26
|
import { createBodyServices, TOOL_NAMES } from "./wiring.js";
|
|
26
27
|
import { openDownstream, parseDownstreamDocument, } from "./downstream.js";
|
|
@@ -169,7 +170,7 @@ export const TOOL_META = [
|
|
|
169
170
|
},
|
|
170
171
|
reference: {
|
|
171
172
|
type: "string",
|
|
172
|
-
description: "Your own reference for this payment, such as an invoice or order id. Recorded with the authorization and
|
|
173
|
+
description: "Your own reference for this payment, such as an invoice or order id. Recorded with the authorization; verax reconcile does not read it, and matches a card statement row by a verax:<ref> in its description, amount, currency and time.",
|
|
173
174
|
},
|
|
174
175
|
_ref: REF_PARAM,
|
|
175
176
|
},
|
|
@@ -382,6 +383,15 @@ export async function listen(config) {
|
|
|
382
383
|
await closeAll(sessions);
|
|
383
384
|
throw err;
|
|
384
385
|
}
|
|
386
|
+
try {
|
|
387
|
+
// This must precede syncControlRecords: those records pulse too.
|
|
388
|
+
recordBodyStart(config.stateDir, services.ledger.startedAtMs);
|
|
389
|
+
}
|
|
390
|
+
catch (err) {
|
|
391
|
+
services.ledger.close();
|
|
392
|
+
await closeAll(sessions);
|
|
393
|
+
throw err;
|
|
394
|
+
}
|
|
385
395
|
try {
|
|
386
396
|
await services.proxy.syncControlRecords();
|
|
387
397
|
}
|
|
@@ -969,14 +979,21 @@ export async function listen(config) {
|
|
|
969
979
|
});
|
|
970
980
|
server.requestTimeout = REQUEST_TIMEOUT_MS;
|
|
971
981
|
server.headersTimeout = HEADERS_TIMEOUT_MS;
|
|
972
|
-
await new Promise((resolve, reject) => {
|
|
973
|
-
server.once("error", reject);
|
|
974
|
-
server.listen(config.bindPort, config.bindHost, () => resolve());
|
|
975
|
-
});
|
|
976
982
|
server.on("close", () => {
|
|
977
983
|
services.ledger.close();
|
|
978
984
|
void closeAll(sessions);
|
|
979
985
|
});
|
|
986
|
+
try {
|
|
987
|
+
await new Promise((resolve, reject) => {
|
|
988
|
+
server.once("error", reject);
|
|
989
|
+
server.listen(config.bindPort, config.bindHost, () => resolve());
|
|
990
|
+
});
|
|
991
|
+
}
|
|
992
|
+
catch (err) {
|
|
993
|
+
services.ledger.close();
|
|
994
|
+
await closeAll(sessions);
|
|
995
|
+
throw err;
|
|
996
|
+
}
|
|
980
997
|
const bound = server.address();
|
|
981
998
|
if (!bound || typeof bound === "string") {
|
|
982
999
|
await new Promise((resolve) => server.close(() => resolve()));
|
|
@@ -984,6 +1001,8 @@ export async function listen(config) {
|
|
|
984
1001
|
}
|
|
985
1002
|
try {
|
|
986
1003
|
services.ledger.recordListenPort(bound.port);
|
|
1004
|
+
const stopHeartbeat = startHeartbeat(services.ledger);
|
|
1005
|
+
server.once("close", stopHeartbeat);
|
|
987
1006
|
}
|
|
988
1007
|
catch (err) {
|
|
989
1008
|
await new Promise((resolve) => server.close(() => resolve()));
|
package/dist/verify-cli.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type VerifyResult } from "@verax-ai/proxy";
|
|
2
2
|
import { type ApprovalSignatureReport } from "./approval-signature.ts";
|
|
3
3
|
import { type ControlSignatureReport } from "./control-signature.ts";
|
|
4
|
+
import { type StartSummary } from "./heartbeat.ts";
|
|
4
5
|
export declare const EX_VERIFY_FAILED = 1;
|
|
5
|
-
export declare function renderVerify(r: VerifyResult, approval?: ApprovalSignatureReport, control?: ControlSignatureReport): string;
|
|
6
|
+
export declare function renderVerify(r: VerifyResult, approval?: ApprovalSignatureReport, control?: ControlSignatureReport, starts?: StartSummary): string;
|
|
6
7
|
export declare function runVerify(argv: readonly string[], out?: (s: string) => void): Promise<number>;
|
package/dist/verify-cli.js
CHANGED
|
@@ -21,6 +21,7 @@ import { verifyLedger } from "@verax-ai/proxy";
|
|
|
21
21
|
import { verifyApprovalSignatures } from "./approval-signature.js";
|
|
22
22
|
import { verifyControlSignatures } from "./control-signature.js";
|
|
23
23
|
import { directoryAccess, unreadableSentence } from "./install.js";
|
|
24
|
+
import { readStartSummary, renderStarts } from "./heartbeat.js";
|
|
24
25
|
export const EX_VERIFY_FAILED = 1;
|
|
25
26
|
function usage() {
|
|
26
27
|
return [
|
|
@@ -88,7 +89,7 @@ const CONTROL_NOT_CHECKED = {
|
|
|
88
89
|
trustSource: "none",
|
|
89
90
|
trustNote: "control signatures were not checked",
|
|
90
91
|
};
|
|
91
|
-
export function renderVerify(r, approval = APPROVAL_NOT_CHECKED, control = CONTROL_NOT_CHECKED) {
|
|
92
|
+
export function renderVerify(r, approval = APPROVAL_NOT_CHECKED, control = CONTROL_NOT_CHECKED, starts) {
|
|
92
93
|
const lines = [];
|
|
93
94
|
lines.push(`ledger ${r.directory}`);
|
|
94
95
|
lines.push(`decisions ${r.decisions}`);
|
|
@@ -151,6 +152,8 @@ export function renderVerify(r, approval = APPROVAL_NOT_CHECKED, control = CONTR
|
|
|
151
152
|
lines.push(` ${approval.trustNote}`);
|
|
152
153
|
// Halt and resume signatures are checked under the same operator key.
|
|
153
154
|
lines.push(control.line);
|
|
155
|
+
if (starts)
|
|
156
|
+
lines.push(renderStarts(starts));
|
|
154
157
|
if (r.problems.length > 0) {
|
|
155
158
|
lines.push("");
|
|
156
159
|
lines.push("problems:");
|
|
@@ -295,8 +298,9 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
|
|
|
295
298
|
anchors: { line: "anchors: not checked", receipts: 0, verified: 0, checked: false },
|
|
296
299
|
problems: [problem],
|
|
297
300
|
};
|
|
298
|
-
const
|
|
299
|
-
|
|
301
|
+
const starts = readStartSummary(dir);
|
|
302
|
+
const failedReport = { ...failed, approvalSignatures: APPROVAL_NOT_CHECKED, controlSignatures: CONTROL_NOT_CHECKED, starts };
|
|
303
|
+
out(json ? JSON.stringify(failedReport, null, 2) : renderVerify(failed, APPROVAL_NOT_CHECKED, CONTROL_NOT_CHECKED, starts));
|
|
300
304
|
return EX_VERIFY_FAILED;
|
|
301
305
|
}
|
|
302
306
|
let approval;
|
|
@@ -331,7 +335,7 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
|
|
|
331
335
|
problems: [...result.problems, `control signatures: ${control.signedFailed} did not verify`],
|
|
332
336
|
};
|
|
333
337
|
}
|
|
334
|
-
const reported = { ...result, approvalSignatures: approval, controlSignatures: control };
|
|
335
|
-
out(json ? JSON.stringify(reported, null, 2) : renderVerify(reported, approval, control));
|
|
338
|
+
const reported = { ...result, approvalSignatures: approval, controlSignatures: control, starts: readStartSummary(dir) };
|
|
339
|
+
out(json ? JSON.stringify(reported, null, 2) : renderVerify(reported, approval, control, reported.starts));
|
|
336
340
|
return reported.ok ? 0 : EX_VERIFY_FAILED;
|
|
337
341
|
}
|
package/dist/watch.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type ChildProcess, type SpawnOptions } from "node:child_process";
|
|
2
|
+
export type WatchHooks = {
|
|
3
|
+
stdout?: {
|
|
4
|
+
write(s: string): unknown;
|
|
5
|
+
};
|
|
6
|
+
stderr?: {
|
|
7
|
+
write(s: string): unknown;
|
|
8
|
+
};
|
|
9
|
+
env?: NodeJS.ProcessEnv;
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
now?: () => number;
|
|
12
|
+
sleep?: (ms: number) => Promise<void>;
|
|
13
|
+
fetch?: typeof fetch;
|
|
14
|
+
spawn?: (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess;
|
|
15
|
+
};
|
|
16
|
+
/** Split operator-supplied argv; no expansion, pipes, redirects or shell. */
|
|
17
|
+
export declare function commandArgv(text: string): string[];
|
|
18
|
+
export declare function silenceReason(atMs: unknown, now: number, maxSilenceMs: number): string | null;
|
|
19
|
+
export declare function runWatch(argv: readonly string[], hooks?: WatchHooks): Promise<number>;
|
package/dist/watch.js
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
4
|
+
import { haltBody } from "./halt.js";
|
|
5
|
+
import { readHeartbeat } from "./health-extras.js";
|
|
6
|
+
import { isLoopbackHost } from "./config.js";
|
|
7
|
+
const USAGE = "usage: verax watch <stateDir> | --url <https://host/healthz> --token-file <path> [--max-silence 30s] [--once] [--on-silence halt|exec] [--exec <command>]";
|
|
8
|
+
/** Split operator-supplied argv; no expansion, pipes, redirects or shell. */
|
|
9
|
+
export function commandArgv(text) {
|
|
10
|
+
const args = [];
|
|
11
|
+
let word = "", quote = "", started = false;
|
|
12
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
13
|
+
const ch = text[i];
|
|
14
|
+
if (ch === "\0" || ch === "\n" || ch === "\r")
|
|
15
|
+
throw new Error("invalid command");
|
|
16
|
+
if (ch === "\\" && (text[i + 1] === quote || text[i + 1] === "\\" || (!quote && /[\s"']/.test(text[i + 1] ?? "")))) {
|
|
17
|
+
word += text[++i];
|
|
18
|
+
started = true;
|
|
19
|
+
}
|
|
20
|
+
else if (quote) {
|
|
21
|
+
if (ch === quote)
|
|
22
|
+
quote = "";
|
|
23
|
+
else
|
|
24
|
+
word += ch;
|
|
25
|
+
}
|
|
26
|
+
else if (ch === '"' || ch === "'") {
|
|
27
|
+
quote = ch;
|
|
28
|
+
started = true;
|
|
29
|
+
}
|
|
30
|
+
else if (/\s/.test(ch)) {
|
|
31
|
+
if (started) {
|
|
32
|
+
args.push(word);
|
|
33
|
+
word = "";
|
|
34
|
+
started = false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
word += ch;
|
|
39
|
+
started = true;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (quote)
|
|
43
|
+
throw new Error("unclosed command quote");
|
|
44
|
+
if (started)
|
|
45
|
+
args.push(word);
|
|
46
|
+
if (!args[0])
|
|
47
|
+
throw new Error("empty command");
|
|
48
|
+
return args;
|
|
49
|
+
}
|
|
50
|
+
function options(argv) {
|
|
51
|
+
const result = { maxSilenceMs: 30_000, once: false, action: "halt" };
|
|
52
|
+
const seen = new Set();
|
|
53
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
54
|
+
const arg = argv[i];
|
|
55
|
+
if (!arg.startsWith("-")) {
|
|
56
|
+
if (result.stateDir)
|
|
57
|
+
throw new Error("one state directory required");
|
|
58
|
+
result.stateDir = arg;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (seen.has(arg))
|
|
62
|
+
throw new Error("duplicate option");
|
|
63
|
+
seen.add(arg);
|
|
64
|
+
if (arg === "--once") {
|
|
65
|
+
result.once = true;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (!["--url", "--token-file", "--max-silence", "--on-silence", "--exec"].includes(arg))
|
|
69
|
+
throw new Error("unknown option");
|
|
70
|
+
const value = argv[++i];
|
|
71
|
+
if (!value || value.startsWith("--"))
|
|
72
|
+
throw new Error("missing option value");
|
|
73
|
+
if (arg === "--url")
|
|
74
|
+
result.url = value;
|
|
75
|
+
if (arg === "--token-file")
|
|
76
|
+
result.tokenFile = value;
|
|
77
|
+
if (arg === "--exec")
|
|
78
|
+
result.command = commandArgv(value);
|
|
79
|
+
if (arg === "--on-silence") {
|
|
80
|
+
if (value !== "halt" && value !== "exec")
|
|
81
|
+
throw new Error("invalid silence action");
|
|
82
|
+
result.action = value;
|
|
83
|
+
}
|
|
84
|
+
if (arg === "--max-silence") {
|
|
85
|
+
const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(value);
|
|
86
|
+
if (!match)
|
|
87
|
+
throw new Error("duration needs ms, s, m or h");
|
|
88
|
+
result.maxSilenceMs = Number(match[1]) * ({ ms: 1, s: 1000, m: 60_000, h: 3_600_000 }[match[2]]);
|
|
89
|
+
if (!Number.isFinite(result.maxSilenceMs) || result.maxSilenceMs < 1 || result.maxSilenceMs / 3 > 2_147_483_647)
|
|
90
|
+
throw new Error("duration out of range");
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (Boolean(result.stateDir) === Boolean(result.url))
|
|
94
|
+
throw new Error("choose local or URL mode");
|
|
95
|
+
if (result.url) {
|
|
96
|
+
const url = new URL(result.url);
|
|
97
|
+
if (url.username || url.password || url.hash || url.search || url.pathname !== "/healthz"
|
|
98
|
+
|| !(url.protocol === "https:" || (url.protocol === "http:" && isLoopbackHost(url.hostname))))
|
|
99
|
+
throw new Error("HTTPS required except on loopback; use /healthz without credentials");
|
|
100
|
+
if (!result.tokenFile)
|
|
101
|
+
throw new Error("token file required");
|
|
102
|
+
}
|
|
103
|
+
else if (result.tokenFile)
|
|
104
|
+
throw new Error("token file requires URL mode");
|
|
105
|
+
if ((result.action === "exec") !== Boolean(result.command))
|
|
106
|
+
throw new Error("exec action requires --exec command");
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
109
|
+
export function silenceReason(atMs, now, maxSilenceMs) {
|
|
110
|
+
if (typeof atMs !== "number" || !Number.isFinite(atMs))
|
|
111
|
+
return "heartbeat-unreadable";
|
|
112
|
+
if (atMs > now + 60_000)
|
|
113
|
+
return "heartbeat-in-future";
|
|
114
|
+
if (now - atMs > maxSilenceMs)
|
|
115
|
+
return "heartbeat-stale";
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
async function remoteBeat(opts, hooks) {
|
|
119
|
+
try {
|
|
120
|
+
const token = readFileSync(opts.tokenFile, "utf8").trim();
|
|
121
|
+
if (!token || /[\r\n]/.test(token))
|
|
122
|
+
return undefined;
|
|
123
|
+
const timeout = AbortSignal.timeout(Math.max(1, Math.min(10_000, Math.floor(opts.maxSilenceMs / 3))));
|
|
124
|
+
const signal = hooks.signal ? AbortSignal.any([hooks.signal, timeout]) : timeout;
|
|
125
|
+
const response = await (hooks.fetch ?? fetch)(opts.url, { headers: { authorization: `Bearer ${token}` }, redirect: "error", signal });
|
|
126
|
+
if (!response.ok)
|
|
127
|
+
return undefined;
|
|
128
|
+
const body = await response.json();
|
|
129
|
+
return body?.heartbeat?.atMs;
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
// Do not print transport errors: a header or token may be embedded in them.
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
async function execute(opts, reason, hooks) {
|
|
137
|
+
return new Promise((resolve) => {
|
|
138
|
+
try {
|
|
139
|
+
const child = (hooks.spawn ?? spawn)(opts.command[0], opts.command.slice(1), {
|
|
140
|
+
shell: false,
|
|
141
|
+
windowsHide: true,
|
|
142
|
+
stdio: ["ignore", "ignore", "inherit"],
|
|
143
|
+
env: { ...(hooks.env ?? process.env), VERAX_WATCH_REASON: reason },
|
|
144
|
+
});
|
|
145
|
+
child.once("error", () => resolve(false));
|
|
146
|
+
child.once("close", (code) => resolve(code === 0));
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
resolve(false);
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
export async function runWatch(argv, hooks = {}) {
|
|
154
|
+
const stdout = hooks.stdout ?? process.stdout;
|
|
155
|
+
const stderr = hooks.stderr ?? process.stderr;
|
|
156
|
+
if (argv.length === 1 && (argv[0] === "--help" || argv[0] === "-h")) {
|
|
157
|
+
stdout.write(`${USAGE}\n`);
|
|
158
|
+
return 0;
|
|
159
|
+
}
|
|
160
|
+
let opts;
|
|
161
|
+
try {
|
|
162
|
+
opts = options(argv);
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
stderr.write(`${USAGE}\n`);
|
|
166
|
+
return 2;
|
|
167
|
+
}
|
|
168
|
+
let silent = false;
|
|
169
|
+
while (!hooks.signal?.aborted) {
|
|
170
|
+
const atMs = opts.url ? await remoteBeat(opts, hooks) : readHeartbeat(opts.stateDir)?.atMs;
|
|
171
|
+
if (hooks.signal?.aborted)
|
|
172
|
+
break;
|
|
173
|
+
const now = (hooks.now ?? Date.now)();
|
|
174
|
+
const reason = silenceReason(atMs, now, opts.maxSilenceMs);
|
|
175
|
+
if (reason && !silent) {
|
|
176
|
+
silent = true;
|
|
177
|
+
let actionResult = "halted";
|
|
178
|
+
if (opts.action === "exec") {
|
|
179
|
+
actionResult = await execute(opts, reason, hooks) ? "exec-ok" : "exec-failed";
|
|
180
|
+
}
|
|
181
|
+
else if (opts.url) {
|
|
182
|
+
actionResult = "remote halt is out of scope";
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
try {
|
|
186
|
+
haltBody(opts.stateDir, "verax-watch", "cli", now);
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
actionResult = "halt-failed";
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
stdout.write(`${JSON.stringify({ event: "silence", atMs: now, reason, action: opts.action, actionResult })}\n`);
|
|
193
|
+
if (actionResult === "halt-failed") {
|
|
194
|
+
stderr.write("verax-watch: could not persist halt\n");
|
|
195
|
+
return 3;
|
|
196
|
+
}
|
|
197
|
+
if (opts.url && opts.action === "halt")
|
|
198
|
+
return 3;
|
|
199
|
+
}
|
|
200
|
+
else if (!reason && silent) {
|
|
201
|
+
silent = false;
|
|
202
|
+
stdout.write(`${JSON.stringify({ event: "recovery", atMs: now })}\n`);
|
|
203
|
+
// Recovery never removes the halt; only an operator resumes the body.
|
|
204
|
+
}
|
|
205
|
+
if (opts.once)
|
|
206
|
+
return reason ? 3 : 0;
|
|
207
|
+
try {
|
|
208
|
+
const ms = Math.max(1, Math.floor(opts.maxSilenceMs / 3));
|
|
209
|
+
if (hooks.sleep)
|
|
210
|
+
await hooks.sleep(ms);
|
|
211
|
+
else
|
|
212
|
+
await delay(ms, undefined, hooks.signal ? { signal: hooks.signal } : {});
|
|
213
|
+
}
|
|
214
|
+
catch (err) {
|
|
215
|
+
if (!hooks.signal?.aborted)
|
|
216
|
+
throw err;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return 0;
|
|
220
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@verax-ai/body",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.7",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -26,8 +26,8 @@
|
|
|
26
26
|
"@cedulon/cose": "0.13.1",
|
|
27
27
|
"@cedulon/effect-extract": "0.13.1",
|
|
28
28
|
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
29
|
-
"@verax-ai/inventory": "^0.4.
|
|
30
|
-
"@verax-ai/proxy": "^0.4.
|
|
29
|
+
"@verax-ai/inventory": "^0.4.7",
|
|
30
|
+
"@verax-ai/proxy": "^0.4.7",
|
|
31
31
|
"jose": "^6.2.11"
|
|
32
32
|
},
|
|
33
33
|
"description": "VERAX body: an MCP server that decides, records and proves what an agent did.",
|