worktrust 0.10.23 → 0.10.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -0
- package/SECURITY.md +24 -4
- package/engine-release.json +1 -1
- package/history-outbox.mjs +93 -0
- package/log-session.mjs +66 -108
- package/package-integrity.mjs +83 -6
- package/package-release.json +1 -1
- package/package.json +3 -2
- package/preserve-lines.mjs +2 -1
- package/preserve.mjs +7 -9
- package/runtime-install.mjs +48 -6
- package/setup-mcp.mjs +20 -18
- package/worktrust-launch.mjs +90 -8
- package/worktrust.mjs +73 -43
package/worktrust.mjs
CHANGED
|
@@ -32,9 +32,7 @@
|
|
|
32
32
|
* WHAT RUNS. From the npm package, everything that runs is in the package: this file,
|
|
33
33
|
* `setup-mcp.mjs` (gives every AI app here the WorkTrust door), `log-session.mjs` (the session hook)
|
|
34
34
|
* and `count-behaviour.mjs` (the local counter, pinned: never replaced from the network), with
|
|
35
|
-
* `transcript-readers.mjs` (how Codex and Antigravity logs are read, imported by the last two).
|
|
36
|
-
* is downloaded. Run as a single file from WorkTrust's site instead, it fetches those from that
|
|
37
|
-
* same site, and says so before it asks.
|
|
35
|
+
* `transcript-readers.mjs` (how Codex and Antigravity logs are read, imported by the last two). Individual support scripts are never downloaded or executed outside the complete release.
|
|
38
36
|
* HOW THE ACCOUNT IS DECIDED. By default this terminal listens on 127.0.0.1 for one answer and holds
|
|
39
37
|
* a PKCE secret. Your browser opens WorkTrust, you approve this computer there (signed in, second
|
|
40
38
|
* factor), and the browser is sent back to 127.0.0.1 with a one-time code that only this terminal,
|
|
@@ -63,27 +61,29 @@
|
|
|
63
61
|
* No dependencies: Node 18 or later.
|
|
64
62
|
*/
|
|
65
63
|
import { execFileSync, spawn } from "node:child_process";
|
|
66
|
-
import { createHash, generateKeyPairSync, randomBytes, sign } from "node:crypto";
|
|
64
|
+
import { createHash, createPublicKey, generateKeyPairSync, randomBytes, sign } from "node:crypto";
|
|
67
65
|
import { createServer } from "node:http";
|
|
68
66
|
import { chmodSync, closeSync, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
|
|
69
67
|
import { homedir, hostname, platform } from "node:os";
|
|
70
|
-
import { dirname, join } from "node:path";
|
|
68
|
+
import { dirname, join, basename } from "node:path";
|
|
71
69
|
import { createInterface } from "node:readline/promises";
|
|
72
70
|
import { createInterface as lines } from "node:readline";
|
|
73
71
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
74
72
|
|
|
73
|
+
const { moduleArgs, moduleExecutable, readPrivateFile, writePrivateFile } = await import("./package-integrity.mjs").catch(() => ({}));
|
|
74
|
+
|
|
75
75
|
const args = process.argv.slice(2);
|
|
76
76
|
const VALUED = ["--name", "--origin", "--url", "--export", "--from-folder"];
|
|
77
77
|
const command = args.includes("--help") ? "help" : args.includes("--version") ? "version" : args.find((arg, at) => !arg.startsWith("--") && !(at > 0 && VALUED.includes(args[at - 1]))) ?? "default";
|
|
78
78
|
const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
|
|
79
79
|
const has = (name) => args.includes(`--${name}`);
|
|
80
80
|
/** This CLI's version, said to the door so the app can tell which computer runs an old one (check-cli-package holds it equal to package.json). */
|
|
81
|
-
const CLI_VERSION = "0.10.
|
|
81
|
+
const CLI_VERSION = "0.10.25";
|
|
82
82
|
const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.worktrust.io").replace(/\/$/, "");
|
|
83
83
|
const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
|
|
84
84
|
const HOME_DIR = join(homedir(), ".worktrust");
|
|
85
85
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
86
|
-
const SCRIPTS = ["setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "runtime-install.mjs", "orchestration-contract.mjs", "orchestration-evidence.mjs", "orchestration-report.mjs", "claude-mod.mjs", "package-integrity.mjs", "worktrust-launch.mjs"];
|
|
86
|
+
const SCRIPTS = ["history-outbox.mjs", "setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "runtime-install.mjs", "orchestration-contract.mjs", "orchestration-evidence.mjs", "orchestration-report.mjs", "claude-mod.mjs", "package-integrity.mjs", "worktrust-launch.mjs"];
|
|
87
87
|
/** The modules the scripts import by name from beside them; a download keeps that name. */
|
|
88
88
|
const IMPORTED = new Set(["transcript-readers.mjs", "session-databases.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "runtime-install.mjs", "orchestration-contract.mjs", "orchestration-evidence.mjs", "orchestration-report.mjs"]);
|
|
89
89
|
const downloaded = (name) => (IMPORTED.has(name) ? name : `${name}.download.mjs`);
|
|
@@ -125,16 +125,24 @@ async function post(path, body) {
|
|
|
125
125
|
return { status: response.status, json: await response.json().catch(() => ({})) };
|
|
126
126
|
}
|
|
127
127
|
|
|
128
|
-
/**
|
|
128
|
+
/** Every helper belongs to this complete release. No loose-file download fallback. */
|
|
129
129
|
async function scripts() {
|
|
130
130
|
if (BUNDLED) return Object.fromEntries(SCRIPTS.map((name) => [name, join(HERE, name)]));
|
|
131
131
|
fail("Use the complete official npm/Python package or preservation kit. Individual scripts are not downloaded or executed without release verification.");
|
|
132
132
|
}
|
|
133
133
|
|
|
134
|
+
/** Stable across bearer renewal, distinct across account/device replacement. Never sent to the server. */
|
|
135
|
+
function historyQueueScope(token) {
|
|
136
|
+
const key = keyStore.load();
|
|
137
|
+
if (!key || key.token !== token || !key.accountRef || !key.device) return "";
|
|
138
|
+
try { return createHash("sha256").update(`${key.accountRef}\0${createPublicKey(key.device).export({ format: "jwk" }).x}`).digest("hex"); }
|
|
139
|
+
catch { return ""; }
|
|
140
|
+
}
|
|
141
|
+
|
|
134
142
|
/** Run a script; its output is shown, or collected for the plan. The key travels in the environment only. */
|
|
135
143
|
function run(path, scriptArgs, token, collect = false, extraEnv = {}) {
|
|
136
144
|
return new Promise((resolve) => {
|
|
137
|
-
const child = spawn(
|
|
145
|
+
const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, basename(path), scriptArgs)], { stdio: collect ? ["ignore", "pipe", "pipe"] : "inherit", env: { ...process.env, WORKTRUST_MCP_URL: MCP, WORKTRUST_MCP_TOKEN: token, WORKTRUST_NODE: NODE, WORKTRUST_NODE_ARGS: JSON.stringify(NODE_ARGS), WORKTRUST_CLI_VERSION: CLI_VERSION, WORKTRUST_HISTORY_SCOPE: historyQueueScope(token), ...extraEnv } });
|
|
138
146
|
let out = "";
|
|
139
147
|
child.stdout?.on("data", (chunk) => { out += chunk; });
|
|
140
148
|
child.stderr?.on("data", (chunk) => { out += chunk; });
|
|
@@ -213,6 +221,7 @@ async function pairByBrowser(host, extra) {
|
|
|
213
221
|
server.close();
|
|
214
222
|
if (!code) fail("no approval arrived in time. Run `worktrust connect` again.");
|
|
215
223
|
const exchange = await post("/api/cli/token", { device_code: secret, code, code_verifier: verifier }).catch(() => null);
|
|
224
|
+
if (exchange?.json?.error === "device_limit") fail("Five devices are already connected. In WorkTrust Sources, disconnect a device, then connect again. Earlier measurements are kept.");
|
|
216
225
|
if (!exchange || exchange.status !== 200 || !exchange.json.token) fail(`the approval could not be exchanged (${exchange?.json?.error ?? "no answer"}). Run \`worktrust connect\` again.`);
|
|
217
226
|
say(` ✓ Approved as "${exchange.json.label}"${exchange.json.account ? ` for the WorkTrust account ${exchange.json.account}` : ""}`);
|
|
218
227
|
if (exchange.json.account) say(" Not your account? Run `npx worktrust disconnect` now and revoke it in WorkTrust.");
|
|
@@ -247,6 +256,7 @@ async function pairByCode(host, extra) {
|
|
|
247
256
|
if (answer.json.account) say(" Not your account? Run `npx worktrust disconnect` now and revoke it in WorkTrust.");
|
|
248
257
|
return paired(answer.json);
|
|
249
258
|
}
|
|
259
|
+
if (answer.json.error === "device_limit") fail("Five devices are already connected. In WorkTrust Sources, disconnect a device, then connect again. Earlier measurements are kept.");
|
|
250
260
|
if (answer.json.error === "slow_down") wait += 2000;
|
|
251
261
|
else if (answer.json.error === "expired_token") fail("the code expired. Run `worktrust connect` again.");
|
|
252
262
|
else if (answer.json.error === "invalid_grant") fail("this pairing was already used. Run `worktrust connect` again.");
|
|
@@ -262,7 +272,7 @@ async function pairByCode(host, extra) {
|
|
|
262
272
|
let NODE = process.env.WORKTRUST_BUNDLED_RUNTIME_DIR ? process.execPath : (process.env.PATH ?? "").split(OS === "windows" ? ";" : ":").map((dir) => join(dir, OS === "windows" ? "node.exe" : "node")).find((path) => existsSync(path)) ?? process.execPath;
|
|
263
273
|
const KEY_FILE = join(HOME_DIR, "key.json");
|
|
264
274
|
const STABLE_FILE = join(HOME_DIR, "worktrust.mjs");
|
|
265
|
-
let STABLE =
|
|
275
|
+
let STABLE = join(HERE, "worktrust-launch.mjs"), runtimePrepared = false, NODE_ARGS = [];
|
|
266
276
|
const RENEW_EVERY_MS = 7 * 24 * 3600_000;
|
|
267
277
|
const KEY_PLACE = "~/.worktrust/key.json (only you can read it)";
|
|
268
278
|
const ensureHome = () => { mkdirSync(HOME_DIR, { recursive: true, mode: 0o700 }); try { chmodSync(HOME_DIR, 0o700); } catch { /* Windows */ } };
|
|
@@ -270,6 +280,10 @@ const ensureHome = () => { mkdirSync(HOME_DIR, { recursive: true, mode: 0o700 })
|
|
|
270
280
|
/** A tool-runner cache is disposable. Install the whole verified runtime/engine before changing wiring. */
|
|
271
281
|
async function prepareBundledRuntime() {
|
|
272
282
|
if (runtimePrepared) return;
|
|
283
|
+
const installedLauncher = join(dirname(HERE), "worktrust-launch.py");
|
|
284
|
+
if (moduleExecutable(HERE) !== process.execPath) {
|
|
285
|
+
NODE = process.env.WORKTRUST_BUNDLED_PYTHON; NODE_ARGS = ["-I"]; STABLE = installedLauncher; runtimePrepared = true; return;
|
|
286
|
+
}
|
|
273
287
|
if (!process.env.WORKTRUST_BUNDLED_RUNTIME_DIR) {
|
|
274
288
|
if (existsSync(join(HERE, "package-release.json"))) {
|
|
275
289
|
if (existsSync(HOME_DIR) && (!lstatSync(HOME_DIR).isDirectory() || lstatSync(HOME_DIR).isSymbolicLink())) fail("the WorkTrust directory must be a directory, not a symlink.");
|
|
@@ -281,11 +295,11 @@ async function prepareBundledRuntime() {
|
|
|
281
295
|
if (existsSync(HOME_DIR) && (!lstatSync(HOME_DIR).isDirectory() || lstatSync(HOME_DIR).isSymbolicLink())) fail("the WorkTrust directory must be a directory, not a symlink.");
|
|
282
296
|
ensureHome();
|
|
283
297
|
const installed = installRuntime(process.env.WORKTRUST_BUNDLED_RUNTIME_DIR, HERE, HOME_DIR, ["worktrust.mjs", ...SCRIPTS, "preserve.mjs", "preserve-lines.mjs", "preserve-summary.mjs"]);
|
|
284
|
-
NODE = installed.executable; STABLE = installed.bridge; runtimePrepared = true;
|
|
298
|
+
NODE = installed.executable; NODE_ARGS = installed.args; STABLE = installed.bridge; runtimePrepared = true;
|
|
285
299
|
}
|
|
286
300
|
function saveStableEntry() {
|
|
287
|
-
const temporary = `${
|
|
288
|
-
try { writeFileSync(temporary,
|
|
301
|
+
const target = join(HOME_DIR, "installed-release.json"), temporary = `${target}.${randomBytes(8).toString("hex")}.tmp`;
|
|
302
|
+
try { writeFileSync(temporary, JSON.stringify({ version: CLI_VERSION }), { flag: "wx", mode: 0o600 }); renameSync(temporary, target); }
|
|
289
303
|
finally { try { rmSync(temporary); } catch { /* already renamed */ } }
|
|
290
304
|
}
|
|
291
305
|
|
|
@@ -299,14 +313,16 @@ function saveStableEntry() {
|
|
|
299
313
|
const keyStore = {
|
|
300
314
|
/** Written whole or not at all: a temporary file renamed over the old one. */
|
|
301
315
|
save(entry) {
|
|
302
|
-
|
|
303
|
-
const temporary = `${KEY_FILE}.${process.pid}.tmp`;
|
|
304
|
-
writeFileSync(temporary, Buffer.from(JSON.stringify(entry)).toString("base64"), { mode: 0o600 });
|
|
305
|
-
try { chmodSync(temporary, 0o600); } catch { /* Windows */ }
|
|
306
|
-
renameSync(temporary, KEY_FILE);
|
|
316
|
+
writePrivateFile(KEY_FILE, Buffer.from(JSON.stringify(entry)).toString("base64"));
|
|
307
317
|
},
|
|
308
318
|
load() {
|
|
309
|
-
|
|
319
|
+
const bytes = readPrivateFile(KEY_FILE);
|
|
320
|
+
if (bytes === null) return null;
|
|
321
|
+
try {
|
|
322
|
+
const entry = JSON.parse(Buffer.from(bytes, "base64").toString("utf8"));
|
|
323
|
+
if (!entry || Array.isArray(entry) || typeof entry !== "object" || typeof entry.token !== "string" || !entry.token) throw Error();
|
|
324
|
+
return entry;
|
|
325
|
+
} catch { throw Error("KEY_FILE_INVALID"); }
|
|
310
326
|
},
|
|
311
327
|
erase() { try { rmSync(KEY_FILE); } catch { /* gone */ } },
|
|
312
328
|
};
|
|
@@ -356,7 +372,7 @@ function proof(device, url, body) {
|
|
|
356
372
|
async function accepted(url, token, device) {
|
|
357
373
|
try {
|
|
358
374
|
const body = JSON.stringify({ jsonrpc: "2.0", id: 0, method: "tools/list" });
|
|
359
|
-
const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${token}`, "user-agent":
|
|
375
|
+
const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${token}`, "user-agent": `worktrust-bridge worktrust-cli/${CLI_VERSION}`, ...proof(device, url, body) }, body, redirect: "error", signal: AbortSignal.timeout(5000) });
|
|
360
376
|
if (response.status === 401 || response.status === 403) return false;
|
|
361
377
|
if (response.status !== 200) return null;
|
|
362
378
|
const answer = await response.json();
|
|
@@ -457,7 +473,7 @@ function sweepAtMostHourly() {
|
|
|
457
473
|
const stamp = join(HOME_DIR, "bridge-swept-at");
|
|
458
474
|
try { if (Date.now() - Number(readFileSync(stamp, "utf8")) < 3_600_000) return; } catch { /* never swept here */ }
|
|
459
475
|
try { mkdirSync(HOME_DIR, { recursive: true }); writeFileSync(stamp, String(Date.now())); } catch { return; }
|
|
460
|
-
try { spawn(
|
|
476
|
+
try { spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "worktrust.mjs", ["hook"])], { detached: true, stdio: "ignore" }).unref(); } catch { /* the next start sweeps */ }
|
|
461
477
|
}
|
|
462
478
|
|
|
463
479
|
async function bridge() {
|
|
@@ -500,7 +516,7 @@ async function hook() {
|
|
|
500
516
|
if (has("hermes") || has("goose")) return sessionEnd();
|
|
501
517
|
const key = await freshKey();
|
|
502
518
|
if (!key) return;
|
|
503
|
-
const child = spawn(
|
|
519
|
+
const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "log-session.mjs", args.filter((arg) => arg !== "hook"))], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, WORKTRUST_CLI_VERSION: CLI_VERSION, WORKTRUST_HISTORY_SCOPE: historyQueueScope(key.token), ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } }); // 0.10.20: the hook names the version that started it, beside each line
|
|
504
520
|
process.exitCode = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", (code) => resolve(code ?? 1)); });
|
|
505
521
|
}
|
|
506
522
|
|
|
@@ -523,7 +539,7 @@ async function antigravityStop() {
|
|
|
523
539
|
process.stdin.on("end", () => { clearTimeout(timer); resolve(text); });
|
|
524
540
|
process.stdin.on("error", () => { clearTimeout(timer); resolve(text); });
|
|
525
541
|
});
|
|
526
|
-
try { spawn(
|
|
542
|
+
try { spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "worktrust.mjs", ["hook", "--antigravity"])], { detached: true, stdio: "ignore", env: { ...process.env, WORKTRUST_HOOK_INPUT: input.slice(0, 65536) } }).unref(); } catch { /* the next run sweeps it */ }
|
|
527
543
|
process.stdin.pause(); return;
|
|
528
544
|
}
|
|
529
545
|
|
|
@@ -537,7 +553,7 @@ async function antigravityStop() {
|
|
|
537
553
|
async function sessionEnd() {
|
|
538
554
|
writeSync(1, "{}\n");
|
|
539
555
|
if (!process.stdin.isTTY) await new Promise((resolve) => { const timer = setTimeout(resolve, 2000); process.stdin.on("data", () => {}); process.stdin.on("end", () => { clearTimeout(timer); resolve(); }); process.stdin.on("error", () => { clearTimeout(timer); resolve(); }); });
|
|
540
|
-
try { spawn(
|
|
556
|
+
try { spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "worktrust.mjs", ["hook"])], { detached: true, stdio: "ignore" }).unref(); } catch { /* the next run sweeps it */ }
|
|
541
557
|
process.stdin.pause(); return;
|
|
542
558
|
}
|
|
543
559
|
|
|
@@ -573,15 +589,16 @@ async function update() {
|
|
|
573
589
|
// Out first, then in: an app that held a key of its own (a hand-made entry) moves onto the bridge.
|
|
574
590
|
await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token, true);
|
|
575
591
|
if ((await run(paths["setup-mcp.mjs"], ["--write", "--bridge", STABLE], key.token)).code !== 0) fail("coupling the AI apps failed; the output above says where.");
|
|
576
|
-
const hookArgs = ["--install",
|
|
592
|
+
const hookArgs = ["--install", "--via", STABLE];
|
|
577
593
|
if ((await run(paths["log-session.mjs"], hookArgs, key.token, false)).code !== 0) fail("installing the session hook failed; the output above says where.");
|
|
578
594
|
// Codex installed since, or a No said at connect: the one question, asked again (or "already set").
|
|
579
595
|
await offerCodex();
|
|
580
596
|
await offerAntigravity();
|
|
597
|
+
const reported = await accepted(key.url, key.token, key.device);
|
|
598
|
+
say(reported === true ? ` ✓ WorkTrust received CLI version ${CLI_VERSION}.` : " ! Installed locally. WorkTrust could not confirm the version yet; it will be reported on the next connection.");
|
|
581
599
|
await offerRebuild(previousVersion, paths, key);
|
|
582
600
|
say();
|
|
583
|
-
say(" Done. Quit your AI apps completely and open them again
|
|
584
|
-
say(" under Sources → CLI once one of them has spoken. A key an app held by hand still works until you end it there.");
|
|
601
|
+
say(" Done. Quit your AI apps completely and open them again to use the updated CLI.");
|
|
585
602
|
}
|
|
586
603
|
|
|
587
604
|
async function connect() {
|
|
@@ -600,7 +617,6 @@ async function connect() {
|
|
|
600
617
|
if (!has("replace") && !(await ask("Couple it again?", false))) { say(" Stopped. Nothing was changed: this computer stays coupled as it is."); return; }
|
|
601
618
|
say();
|
|
602
619
|
}
|
|
603
|
-
if (!BUNDLED) say(` The three scripts that do the work are downloaded from ${ORIGIN} first. From npm they come in the package.\n`);
|
|
604
620
|
const paths = await scripts();
|
|
605
621
|
const direct = has("direct");
|
|
606
622
|
const plan = await run(paths["setup-mcp.mjs"], direct ? [] : ["--bridge", STABLE], PLACEHOLDER, true);
|
|
@@ -612,7 +628,7 @@ async function connect() {
|
|
|
612
628
|
if (foundApps.length === 0) say(" (no AI app found here yet; run connect again after installing one)");
|
|
613
629
|
if (!direct) say(` 3. The key is kept in ${KEY_PLACE}, works only on this computer (every call is signed) and is renewed every week.`);
|
|
614
630
|
say(` ${direct ? 3 : 4}. The session hook is installed:`);
|
|
615
|
-
say(
|
|
631
|
+
say(" + The hook and counter from the checked release, retained outside the package-manager cache");
|
|
616
632
|
say(` + ${join(homedir(), ".claude", "settings.json")} → SessionStart, SessionEnd and PreCompact run it`);
|
|
617
633
|
say();
|
|
618
634
|
say(" Sent to WorkTrust afterwards: durations, token counts, model names, a layer keyword, counts,");
|
|
@@ -650,7 +666,7 @@ async function connect() {
|
|
|
650
666
|
// A NEW COUPLING SENDS NOTHING FROM BEFORE IT (log-session THE FLOORS): `--from-now` for a first coupling and a change
|
|
651
667
|
// of account; the same account coupled again keeps its watermarks. A change of account also closes the history offer.
|
|
652
668
|
const floors = !previous || switched ? ["--from-now", ...(switched ? ["--history-floor", "now"] : [])] : [];
|
|
653
|
-
const hookArgs = ["--install", ...floors,
|
|
669
|
+
const hookArgs = ["--install", ...floors, "--via", STABLE, ...(direct ? ["--direct"] : [])];
|
|
654
670
|
if ((await run(paths["log-session.mjs"], hookArgs, token, false, { WORKTRUST_CODEX_OFFER: "1" })).code !== 0) fail("installing the session hook failed; the output above says where.");
|
|
655
671
|
await offerCodex();
|
|
656
672
|
await offerAntigravity();
|
|
@@ -691,7 +707,7 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
|
|
|
691
707
|
if (!has("history") && !(rebuild ? await ask("Send them (re-measured; this computer's earlier lines for these days are replaced, a day is counted once)?", false) : await ask("Send these as history (hours and tokens per day; never text)?", false))) { historyDone(false); say(" Not sent. Send them later with: npx worktrust"); return; }
|
|
692
708
|
// Marked unfinished before the first batch leaves (0.10.9): a send stopped halfway (Ctrl+C, a closed lid) is finished by the next run.
|
|
693
709
|
historyDone(false);
|
|
694
|
-
const sent = await run(paths["log-session.mjs"], ["--history", ...(rebuild ? ["--rebuild"] : [])], token, true, env);
|
|
710
|
+
const sent = await run(paths["log-session.mjs"], ["--history", ...(rebuild ? ["--rebuild"] : []), ...(has("retry-review") ? ["--retry-review"] : [])], token, true, env);
|
|
695
711
|
historyDone(sent.code === 0);
|
|
696
712
|
// WHAT ACTUALLY HAPPENED, FROM THE DOOR'S RECEIPTS (owner, 2026-10-10): a re-measure in which nothing changed must not say
|
|
697
713
|
// "replaced". The hook sums the receipts of every batch and prints one line; without it (an older hook) the sentence stays neutral.
|
|
@@ -701,13 +717,15 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
|
|
|
701
717
|
: n(did.replaced) > 0 ? `${n(did.replaced)} of this computer's earlier lines were replaced (withdrawn and kept, never deleted)${n(did.new) > 0 ? `, ${n(did.new)} new` : ""}${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}.`
|
|
702
718
|
: n(did.new) === 0 ? `Nothing changed: the same measurement${n(did.filled) > 0 ? `; ${n(did.filled)} lines gained what was missing (the stack, the tools seen, a layer)` : ""}; ${n(did.alreadyHeld)} lines already held.`
|
|
703
719
|
: `${n(did.new)} new lines${n(did.filled) > 0 ? `, ${n(did.filled)} lines gained what was missing` : ""}; ${n(did.alreadyHeld)} already held.`;
|
|
704
|
-
if (
|
|
705
|
-
|
|
720
|
+
if (Number(did?.delivery?.review) > 0) say(` ${did.delivery.review} lines are waiting for review. Earlier measurements remain unchanged. Reconnecting or repeating the import does not approve them.`);
|
|
721
|
+
if (Number(did?.delivery?.waiting) > 0) say(" Pending batches remain on this computer. Run npx worktrust history --resume after the upload limit or connection recovers.");
|
|
722
|
+
if (rebuild && !Number(did?.delivery?.review) && !Number(did?.delivery?.waiting)) say(sent.code === 0 ? ` ✓ Re-measured. ${outcome}` : " Not all of it arrived. Run npx worktrust again: it finishes what did not arrive, a day already rebuilt is counted once.");
|
|
723
|
+
else if (!rebuild) say(sent.code === 0 ? " ✓ Sent as history. Activity is recorded with its origin; independent verification and passport publication are separate. A day WorkTrust already holds is kept once." : " Not all of it arrived. Run npx worktrust history again: a line already received is kept once.");
|
|
706
724
|
if (did && Number(did.measuredSeconds) > 0) say(` Measured by WorkTrust: ${(Number(did.measuredSeconds) / 3600).toFixed(1)} h for what this send stored${n(did.corrected) > 0 ? ` (${n(did.corrected)} lines corrected: a figure sent beside the timeline differed)` : ""}.`);
|
|
707
725
|
}
|
|
708
726
|
|
|
709
727
|
/** The version stamped in the stable copy in ~/.worktrust, the CLI this computer ran before an update; null without one. */
|
|
710
|
-
const stableVersion = () => { try { return /const CLI_VERSION = "([^"]+)";/.exec(readFileSync(STABLE_FILE, "utf8"))?.[1] ?? null; } catch { return null; } };
|
|
728
|
+
const stableVersion = () => { try { const installed = JSON.parse(readFileSync(join(HOME_DIR, "installed-release.json"), "utf8")); if (/^\d+\.\d+\.\d+$/.test(installed.version)) return installed.version; } catch { /* older registration */ } try { return /const CLI_VERSION = "([^"]+)";/.exec(readFileSync(STABLE_FILE, "utf8"))?.[1] ?? null; } catch { return null; } };
|
|
711
729
|
|
|
712
730
|
/**
|
|
713
731
|
* OFFERED ONCE, BY `update`, IN PLAIN WORDS (owner, 2026-10-07): when the computer's earlier lines were made by an earlier CLI
|
|
@@ -763,6 +781,11 @@ async function again() {
|
|
|
763
781
|
async function history() {
|
|
764
782
|
const key = await freshKey();
|
|
765
783
|
if (!key) fail("this computer is not coupled through the key file. Run npx worktrust first.");
|
|
784
|
+
if (has("resume")) {
|
|
785
|
+
if (!has("dry-run") && !has("history") && !(await ask("Resume previously approved metadata uploads? Lines held for review stay held.", false))) return;
|
|
786
|
+
const paths = await scripts(), sent = await run(paths["log-session.mjs"], ["--history", "--resume", ...(has("dry-run") ? ["--dry-run"] : []), ...(has("retry-review") ? ["--retry-review"] : [])], key.token, true, { WORKTRUST_MCP_URL: key.url, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) });
|
|
787
|
+
say(sent.out.trim()); process.exitCode = sent.code; return;
|
|
788
|
+
}
|
|
766
789
|
if (has("from-archive")) return offerArchive(await scripts(), key);
|
|
767
790
|
if (has("export")) { if (!flag("export") || flag("export").startsWith("--")) fail("--export needs the export's path: the zip, its folder, conversations.json, a conversations-000.zip part, or the manifest"); await offerExport(await scripts(), key, flag("export")); return; }
|
|
768
791
|
if (has("from-folder")) { if (!flag("from-folder") || flag("from-folder").startsWith("--")) fail("--from-folder needs the copied folder's path"); await offerFolder(await scripts(), key, flag("from-folder")); return; }
|
|
@@ -919,9 +942,9 @@ function writeCodex(rows) {
|
|
|
919
942
|
async function offerCodex() {
|
|
920
943
|
if (!existsSync(join(homedir(), ".codex"))) { if (command === "codex") say(" Codex is not on this computer (no ~/.codex)."); return; }
|
|
921
944
|
const viaBridge = existsSync(STABLE);
|
|
922
|
-
const hookFile =
|
|
945
|
+
const hookFile = STABLE;
|
|
923
946
|
if (!existsSync(hookFile)) { say(" Couple this computer first: npx worktrust"); return; }
|
|
924
|
-
const desired = () => `notify = [${(viaBridge ? [NODE, STABLE, "hook", "--codex-notify"] : [NODE, hookFile, "--codex-notify"]).map((part) => JSON.stringify(part)).join(", ")}]`;
|
|
947
|
+
const desired = () => `notify = [${(viaBridge ? [NODE, ...NODE_ARGS, STABLE, "hook", "--codex-notify"] : [NODE, ...NODE_ARGS, hookFile, "--codex-notify"]).map((part) => JSON.stringify(part)).join(", ")}]`;
|
|
925
948
|
let want = desired();
|
|
926
949
|
const found = codexNotify();
|
|
927
950
|
say();
|
|
@@ -968,7 +991,7 @@ function writeAgyHooks(hooks) {
|
|
|
968
991
|
async function offerAntigravity() {
|
|
969
992
|
if (!antigravityHere()) { if (command === "antigravity") say(" Antigravity is not on this computer (no ~/.gemini/config or ~/.gemini/antigravity*)."); return; }
|
|
970
993
|
if (!existsSync(STABLE)) { say(" Couple this computer first: npx worktrust"); return; }
|
|
971
|
-
const desired = () => ({ enabled: true, Stop: [{ type: "command", command: `"${NODE}" "${STABLE}" hook --antigravity-stop`, timeout: 10 }] });
|
|
994
|
+
const desired = () => ({ enabled: true, Stop: [{ type: "command", command: `"${NODE}" ${NODE_ARGS.map(arg => JSON.stringify(arg)).join(" ")}${NODE_ARGS.length ? " " : ""}"${STABLE}" hook --antigravity-stop`, timeout: 10 }] });
|
|
972
995
|
let want = desired();
|
|
973
996
|
const hooks = agyHooks();
|
|
974
997
|
say();
|
|
@@ -1024,7 +1047,7 @@ async function disconnect() {
|
|
|
1024
1047
|
previousNote.save(keyStore.load());
|
|
1025
1048
|
keyStore.erase();
|
|
1026
1049
|
// Everything of ours on this computer goes; the folder too, when nothing else is left in it.
|
|
1027
|
-
for (const name of [
|
|
1050
|
+
for (const name of [STABLE_FILE, ...SCRIPTS.map((script) => join(HOME_DIR, downloaded(script))), join(HOME_DIR, "pinned")]) { try { rmSync(name); } catch { /* gone */ } }
|
|
1028
1051
|
try { rmSync(HOME_DIR, { recursive: false }); } catch { /* not empty, or gone */ }
|
|
1029
1052
|
say();
|
|
1030
1053
|
say(" Done. Revoke the key in WorkTrust to finish.");
|
|
@@ -1084,12 +1107,12 @@ async function status() {
|
|
|
1084
1107
|
say(key ? ` Key: in ${KEY_PLACE}, ${key.device ? "bound to this computer, " : ""}last renewed ${String(key.renewedAt ?? "").slice(0, 10) || "never"}` : " Key: not on this computer (or written into the apps' settings with --direct)");
|
|
1085
1108
|
if (key) say(key.account ? ` Account: ${key.account}${key.coupledAt ? `, coupled ${String(key.coupledAt).slice(0, 10)}` : ""}` : " Account: not recorded (coupled by an older version; `npx worktrust connect` records it)");
|
|
1086
1109
|
let hook = false;
|
|
1087
|
-
try { hook = /log-session|worktrust
|
|
1110
|
+
try { hook = /log-session|worktrust(?:-launch)?\.(?:mjs|py)\\?" hook/.test(readFileSync(join(homedir(), ".claude", "settings.json"), "utf8")); } catch { /* none */ }
|
|
1088
1111
|
say(hook ? " Session hook: installed" : " Session hook: not installed");
|
|
1089
1112
|
if (existsSync(join(homedir(), ".codex"))) { const notify = codexNotify().text ?? ""; say(isOurNotify(notify) ? " Codex: wakes the session hook" : " Codex: does not wake the session hook (npx worktrust update asks)"); }
|
|
1090
|
-
if (existsSync(join(homedir(), ".hermes"))) { let text = ""; try { text = readFileSync(join(homedir(), ".hermes", "config.yaml"), "utf8"); } catch { /* none */ } say(/worktrust
|
|
1113
|
+
if (existsSync(join(homedir(), ".hermes"))) { let text = ""; try { text = readFileSync(join(homedir(), ".hermes", "config.yaml"), "utf8"); } catch { /* none */ } say(/worktrust(?:-launch)?\.(?:mjs|py)\\?" hook --hermes/.test(text) ? " Hermes Agent: wakes the session hook" : " Hermes Agent: does not wake the session hook (npx worktrust update writes it)"); }
|
|
1091
1114
|
if (antigravityHere()) say(agyHooks()?.worktrust ? " Antigravity: wakes the session hook" : " Antigravity: does not wake the session hook (npx worktrust update asks)");
|
|
1092
|
-
say(
|
|
1115
|
+
say(" Counter: from this release, checked by the official launcher");
|
|
1093
1116
|
await measuredHere();
|
|
1094
1117
|
}
|
|
1095
1118
|
|
|
@@ -1098,7 +1121,7 @@ async function status() {
|
|
|
1098
1121
|
* with each stretch (kinds and counts, never text). Read here by the hook beside this file; nothing is sent to show it.
|
|
1099
1122
|
*/
|
|
1100
1123
|
async function measuredHere() {
|
|
1101
|
-
const hook =
|
|
1124
|
+
const hook = join(HERE, "log-session.mjs");
|
|
1102
1125
|
if (!hook) return;
|
|
1103
1126
|
// Through the CLI's one way of starting a script (never a synchronous child: check-computer-pairing), with no door to send to.
|
|
1104
1127
|
const read = await run(hook, ["--evidence-summary"], "", true, { WORKTRUST_MCP_URL: "", WORKTRUST_HOOK_INPUT: "" });
|
|
@@ -1132,7 +1155,7 @@ function claudeKeepsDays() {
|
|
|
1132
1155
|
async function preserve() {
|
|
1133
1156
|
const script = join(HERE, "preserve.mjs");
|
|
1134
1157
|
if (!existsSync(script)) fail("preserve runs from the package: npx worktrust@latest preserve");
|
|
1135
|
-
const child = spawn(
|
|
1158
|
+
const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "preserve.mjs", args.filter((arg) => arg !== "preserve"))], { stdio: "inherit", env: { ...process.env, WORKTRUST_COLLECTOR: `worktrust-cli/${CLI_VERSION}` } });
|
|
1136
1159
|
process.exitCode = await new Promise((resolve) => child.on("exit", (code) => resolve(code ?? 1)));
|
|
1137
1160
|
}
|
|
1138
1161
|
|
|
@@ -1150,6 +1173,8 @@ function help() {
|
|
|
1150
1173
|
say(" --replace yes in advance to coupling a computer that is already coupled");
|
|
1151
1174
|
say(" worktrust update this computer onto the newest CLI: same key, no new pairing");
|
|
1152
1175
|
say(" worktrust history send this computer's earlier sessions as history (asks first)");
|
|
1176
|
+
say(" --resume retry saved metadata batches, even if source files are gone (asks first)");
|
|
1177
|
+
say(" --retry-review explicitly retry held batches after support resolves their review");
|
|
1153
1178
|
say(" --rebuild re-measure them with the current rules; WorkTrust replaces this computer's earlier lines,");
|
|
1154
1179
|
say(" day by day, never counting a day twice (shows the plan per AI app, asks first; --dry-run: the plan only)");
|
|
1155
1180
|
say(" --from-archive [dir] send what your archive (preserve --archive) holds of sessions your AI apps already deleted,");
|
|
@@ -1181,6 +1206,7 @@ function help() {
|
|
|
1181
1206
|
// before anything is read or written, --yes included. The hook and the MCP bridge are started by the agent's client
|
|
1182
1207
|
// itself and stay as they are; `status` only reads.
|
|
1183
1208
|
async function main() {
|
|
1209
|
+
if (!moduleArgs || !moduleExecutable) fail("Use the complete WorkTrust package from npm/PyPI or the signed preservation kit; individual scripts cannot run.");
|
|
1184
1210
|
if (Number(process.versions.node.split(".")[0]) < 18) fail("needs Node 18 or later (fetch is built in from 18).");
|
|
1185
1211
|
const AGENT_ENV = ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CODEX_SANDBOX", "CODEX_CI", "GEMINI_CLI", "CURSOR_AGENT", "OPENCODE", "CLINE_ACTIVE", "AIDER_CHAT", "ANTIGRAVITY_AGENT", "WINDSURF_AGENT"];
|
|
1186
1212
|
const PERSON_ONLY = new Set(["default", "connect", "update", "history", "disconnect", "preserve", "codex", "antigravity", "sources", "web", "import", "orchestration", "mod"]);
|
|
@@ -1215,6 +1241,10 @@ async function relayToNewest() {
|
|
|
1215
1241
|
}
|
|
1216
1242
|
if (await relayToNewest()) return;
|
|
1217
1243
|
|
|
1244
|
+
if (!["version", "help", "preserve"].includes(command)) {
|
|
1245
|
+
try { keyStore.load(); }
|
|
1246
|
+
catch { fail("The local WorkTrust key file is unsafe or damaged. Upload stopped. Restore the private key file from your own backup, or reconnect using an official release."); }
|
|
1247
|
+
}
|
|
1218
1248
|
if (command === "version") say(CLI_VERSION);
|
|
1219
1249
|
else if (command === "default") { if (keyStore.load()) await again(); else await connect(); }
|
|
1220
1250
|
else if (command === "mcp") await bridge();
|