worktrust 0.11.9 → 0.11.11
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/CHANGELOG.md +43 -0
- package/LICENSE +3 -0
- package/README.md +18 -12
- package/cli-look.mjs +192 -0
- package/cli-menu-remote.mjs +31 -7
- package/cli-menu.mjs +28 -14
- package/engine-release.json +1 -1
- package/log-session.mjs +6 -169
- package/package-release.json +1 -1
- package/package.json +3 -1
- package/remote-adapter-claude-code.mjs +30 -4
- package/remote-adapter-codex.mjs +49 -6
- package/remote-adapter-opencode.mjs +63 -10
- package/remote-adapter-terminal.mjs +4 -3
- package/remote-cli.mjs +22 -44
- package/remote-connections.mjs +55 -1
- package/remote-daemon.mjs +5 -2
- package/remote-inventory.mjs +12 -2
- package/remote-pairing.mjs +42 -4
- package/remote-protocol.mjs +119 -20
- package/remote-qr.mjs +40 -15
- package/remote-run.mjs +7 -5
- package/remote-sessions.mjs +15 -15
- package/remote-steering.mjs +60 -0
- package/remote-store.mjs +10 -0
- package/session-readers.mjs +212 -0
- package/transcript-readers.mjs +5 -5
- package/worktrust.mjs +57 -19
package/remote-qr.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* A QR CODE FOR THE TERMINAL, WITHOUT A DEPENDENCY (2026-11-07; owner: pairing by scanning the computer's screen with the
|
|
3
|
-
* WorkTrust app). ISO/IEC 18004: byte mode, error correction level M, the smallest version 1 to 40 that holds the data,
|
|
3
|
+
* WorkTrust app). ISO/IEC 18004: byte mode, error correction level M (or L), the smallest version 1 to 40 that holds the data,
|
|
4
4
|
* the mask with the lowest penalty, format and version information. `qrMatrix(text)` gives the modules (true = dark);
|
|
5
5
|
* `renderQr(matrix)` draws them with half-block characters, two module rows per line, black on an explicitly white
|
|
6
6
|
* background with a four-module white quiet zone, so it scans in a light or a dark terminal.
|
|
@@ -16,8 +16,20 @@ const EC_M = [null,
|
|
|
16
16
|
[26, 17, 42], [28, 17, 46], [28, 4, 47, 14, 48], [28, 6, 45, 14, 46], [28, 8, 47, 13, 48], [28, 19, 46, 4, 47], [28, 22, 45, 3, 46], [28, 3, 45, 23, 46], [28, 21, 45, 7, 46], [28, 19, 47, 10, 48],
|
|
17
17
|
[28, 2, 46, 29, 47], [28, 10, 46, 23, 47], [28, 14, 46, 21, 47], [28, 14, 46, 23, 47], [28, 12, 47, 26, 48], [28, 6, 47, 34, 48], [28, 29, 46, 14, 47], [28, 13, 46, 32, 47], [28, 40, 47, 7, 48], [28, 18, 47, 31, 48]];
|
|
18
18
|
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
// Level L, the same shape (ISO/IEC 18004 table 9). A code on a screen is not scuffed like a print: L (7% recovery, M is 15%)
|
|
20
|
+
// holds the same link in fewer modules (owner, 2026-11-14: "make the QR more compact"). Every version's total of codewords
|
|
21
|
+
// is the same as M's; scripts/test-remote-claude-events.mjs holds that for all forty.
|
|
22
|
+
const EC_L = [null,
|
|
23
|
+
[7, 1, 19], [10, 1, 34], [15, 1, 55], [20, 1, 80], [26, 1, 108], [18, 2, 68], [20, 2, 78], [24, 2, 97], [30, 2, 116], [18, 2, 68, 2, 69],
|
|
24
|
+
[20, 4, 81], [24, 2, 92, 2, 93], [26, 4, 107], [30, 3, 115, 1, 116], [22, 5, 87, 1, 88], [24, 5, 98, 1, 99], [28, 1, 107, 5, 108], [30, 5, 120, 1, 121], [28, 3, 113, 4, 114], [28, 3, 107, 5, 108],
|
|
25
|
+
[28, 4, 116, 4, 117], [28, 2, 111, 7, 112], [30, 4, 121, 5, 122], [30, 6, 117, 4, 118], [26, 8, 106, 4, 107], [28, 10, 114, 2, 115], [30, 8, 122, 4, 123], [30, 3, 117, 10, 118], [30, 7, 116, 7, 117], [30, 5, 115, 10, 116],
|
|
26
|
+
[30, 13, 115, 3, 116], [30, 17, 115], [30, 17, 115, 1, 116], [30, 13, 115, 6, 116], [30, 12, 121, 7, 122], [30, 6, 121, 14, 122], [30, 17, 122, 4, 123], [30, 4, 122, 18, 123], [30, 20, 117, 4, 118], [30, 19, 118, 6, 119]];
|
|
27
|
+
const TABLES = { L: EC_L, M: EC_M };
|
|
28
|
+
/** The format information's two level bits (L 01, M 00). */
|
|
29
|
+
const LEVEL_BITS = { L: 0b01, M: 0b00 };
|
|
30
|
+
|
|
31
|
+
export const blocksOf = (v, level = "M") => { const [ec, n1, d1, n2 = 0, d2 = 0] = TABLES[level][v]; return { ec, groups: [[n1, d1], [n2, d2]].filter(([n]) => n > 0) }; };
|
|
32
|
+
const dataCodewords = (v, level = "M") => blocksOf(v, level).groups.reduce((s, [n, d]) => s + n * d, 0);
|
|
21
33
|
|
|
22
34
|
// GF(256) with the QR polynomial x^8 + x^4 + x^3 + x^2 + 1.
|
|
23
35
|
const EXP = new Uint8Array(512), LOG = new Uint8Array(256);
|
|
@@ -44,12 +56,12 @@ export function reedSolomon(data, degree) {
|
|
|
44
56
|
return rem;
|
|
45
57
|
}
|
|
46
58
|
|
|
47
|
-
function codewords(bytes) {
|
|
59
|
+
function codewords(bytes, level = "M") {
|
|
48
60
|
let version = 1;
|
|
49
61
|
const need = (v) => 4 + (v < 10 ? 8 : 16) + bytes.length * 8;
|
|
50
|
-
while (version <= 40 && need(version) > dataCodewords(version) * 8) version += 1;
|
|
62
|
+
while (version <= 40 && need(version) > dataCodewords(version, level) * 8) version += 1;
|
|
51
63
|
if (version > 40) throw new RangeError("too much data for one QR code");
|
|
52
|
-
const capacity = dataCodewords(version) * 8, bits = [];
|
|
64
|
+
const capacity = dataCodewords(version, level) * 8, bits = [];
|
|
53
65
|
const put = (value, length) => { for (let i = length - 1; i >= 0; i -= 1) bits.push((value >>> i) & 1); };
|
|
54
66
|
put(0b0100, 4);
|
|
55
67
|
put(bytes.length, version < 10 ? 8 : 16);
|
|
@@ -59,7 +71,7 @@ function codewords(bytes) {
|
|
|
59
71
|
for (let pad = 0; bits.length < capacity; pad += 1) put(pad % 2 ? 0x11 : 0xec, 8);
|
|
60
72
|
const data = [];
|
|
61
73
|
for (let i = 0; i < bits.length; i += 8) data.push(bits.slice(i, i + 8).reduce((a, b) => (a << 1) | b, 0));
|
|
62
|
-
const { ec, groups } = blocksOf(version), blocks = [];
|
|
74
|
+
const { ec, groups } = blocksOf(version, level), blocks = [];
|
|
63
75
|
let at = 0;
|
|
64
76
|
for (const [n, d] of groups) for (let i = 0; i < n; i += 1) { const block = data.slice(at, at + d); at += d; blocks.push({ data: block, ec: reedSolomon(block, ec) }); }
|
|
65
77
|
const out = [], longest = Math.max(...blocks.map((b) => b.data.length));
|
|
@@ -79,7 +91,7 @@ export function alignmentCenters(version) {
|
|
|
79
91
|
}
|
|
80
92
|
|
|
81
93
|
const bch = (value, poly, bitsOfPoly) => { let v = value << (bitsOfPoly - 1); while (31 - Math.clz32(v) >= bitsOfPoly - 1) v ^= poly << (31 - Math.clz32(v) - (bitsOfPoly - 1)); return v; };
|
|
82
|
-
export const formatBits = (mask) => { const data = (
|
|
94
|
+
export const formatBits = (mask, level = "M") => { const data = (LEVEL_BITS[level] << 3) | mask; return ((data << 10) | bch(data, 0x537, 11)) ^ 0x5412; };
|
|
83
95
|
export const versionBits = (version) => (version << 12) | bch(version, 0x1f25, 13);
|
|
84
96
|
|
|
85
97
|
export const MASKS = [(r, c) => (r + c) % 2 === 0, (r) => r % 2 === 0, (r, c) => c % 3 === 0, (r, c) => (r + c) % 3 === 0,
|
|
@@ -110,7 +122,7 @@ function base(version) {
|
|
|
110
122
|
return { size, m, fixed };
|
|
111
123
|
}
|
|
112
124
|
|
|
113
|
-
function place(version, words, mask) {
|
|
125
|
+
function place(version, words, mask, level = "M") {
|
|
114
126
|
const { size, m, fixed } = base(version);
|
|
115
127
|
let bit = 0;
|
|
116
128
|
const total = words.length * 8, take = () => (bit < total ? (words[bit >> 3] >>> (7 - (bit++ & 7))) & 1 : 0);
|
|
@@ -121,7 +133,7 @@ function place(version, words, mask) {
|
|
|
121
133
|
for (const c of [col, col - 1]) if (!fixed[r][c]) m[r][c] = (take() === 1) !== MASKS[mask](r, c);
|
|
122
134
|
}
|
|
123
135
|
}
|
|
124
|
-
const f = formatBits(mask);
|
|
136
|
+
const f = formatBits(mask, level);
|
|
125
137
|
for (let i = 0; i < 15; i += 1) {
|
|
126
138
|
const dark = ((f >> i) & 1) === 1;
|
|
127
139
|
if (i < 6) m[i][8] = dark; else if (i < 8) m[i + 1][8] = dark; else m[size - 15 + i][8] = dark;
|
|
@@ -153,17 +165,19 @@ export function penalty(m) {
|
|
|
153
165
|
}
|
|
154
166
|
|
|
155
167
|
/** The modules of the QR code for `text` (UTF-8 bytes), `mask` chosen by penalty unless given. */
|
|
156
|
-
export function qrMatrix(text, forcedMask = null) {
|
|
157
|
-
const { version, out } = codewords(new TextEncoder().encode(text));
|
|
158
|
-
if (forcedMask !== null) return { version, mask: forcedMask, modules: place(version, out, forcedMask) };
|
|
168
|
+
export function qrMatrix(text, forcedMask = null, level = "M") {
|
|
169
|
+
const { version, out } = codewords(new TextEncoder().encode(text), level);
|
|
170
|
+
if (forcedMask !== null) return { version, mask: forcedMask, modules: place(version, out, forcedMask, level) };
|
|
159
171
|
let best = null;
|
|
160
|
-
for (let mask = 0; mask < 8; mask += 1) { const modules = place(version, out, mask), score = penalty(modules); if (!best || score < best.score) best = { version, mask, modules, score }; }
|
|
172
|
+
for (let mask = 0; mask < 8; mask += 1) { const modules = place(version, out, mask, level), score = penalty(modules); if (!best || score < best.score) best = { version, mask, modules, score }; }
|
|
161
173
|
return { version: best.version, mask: best.mask, modules: best.modules };
|
|
162
174
|
}
|
|
163
175
|
|
|
176
|
+
/** The quiet zone, in modules, around every code the CLI draws (the standard's four; its ground is drawn white). */
|
|
177
|
+
export const QUIET = 4;
|
|
164
178
|
/** Half blocks, black on white, a four-module quiet zone. `color` false gives the plain characters (dark = block). */
|
|
165
179
|
export function renderQr(modules, { color = true } = {}) {
|
|
166
|
-
const quiet =
|
|
180
|
+
const quiet = QUIET, size = modules.length + quiet * 2;
|
|
167
181
|
const dark = (r, c) => { const rr = r - quiet, cc = c - quiet; return rr >= 0 && cc >= 0 && rr < modules.length && cc < modules.length && modules[rr][cc]; };
|
|
168
182
|
const lines = [];
|
|
169
183
|
for (let r = 0; r < size; r += 2) {
|
|
@@ -173,3 +187,14 @@ export function renderQr(modules, { color = true } = {}) {
|
|
|
173
187
|
}
|
|
174
188
|
return lines.join("\n");
|
|
175
189
|
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* EVERY QR THE CLI DRAWS GOES THROUGH HERE (owner, 2026-11-14: "make the QR more compact"): the approval, the pairing and the
|
|
193
|
+
* one-scan code alike, level L, half blocks (two module rows per terminal line), the white quiet zone, so a version-10 code
|
|
194
|
+
* is 33 lines by 65 columns and fits an 80-column terminal. `color` as renderQr: the ground drawn white on a terminal with
|
|
195
|
+
* colours, the plain characters otherwise (a pipe, NO_COLOR). check-remote-cli and cli-01110-cases hold that no other path
|
|
196
|
+
* draws one.
|
|
197
|
+
*/
|
|
198
|
+
export function terminalQr(text, { color = true } = {}) {
|
|
199
|
+
return renderQr(qrMatrix(text, null, "L").modules, { color });
|
|
200
|
+
}
|
package/remote-run.mjs
CHANGED
|
@@ -15,7 +15,7 @@ import { fileURLToPath } from "node:url";
|
|
|
15
15
|
import * as P from "./remote-protocol.mjs";
|
|
16
16
|
import { loadPreviewGrants, loadRoots } from "./remote-store.mjs";
|
|
17
17
|
import { sessionProjects } from "./remote-projects.mjs";
|
|
18
|
-
import { ensureRemoteDir, issuerKeys, loadDeskMarks, loadIdentity, loadKeys, loadPipelineReviews, loadProjects, loadSettings, readJson, remotePath, random, saveIdentity } from "./remote-store.mjs";
|
|
18
|
+
import { ensureRemoteDir, gatewayOf, issuerKeys, loadDeskMarks, loadIdentity, loadKeys, loadPipelineReviews, loadProjects, loadSettings, readJson, remotePath, random, saveIdentity } from "./remote-store.mjs";
|
|
19
19
|
import { openJournal } from "./remote-journal.mjs";
|
|
20
20
|
import { inventory as listAgents, offered } from "./remote-inventory.mjs";
|
|
21
21
|
|
|
@@ -105,9 +105,11 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
|
|
|
105
105
|
const settings = loadSettings(), identity = loadIdentity(), keys = loadKeys();
|
|
106
106
|
if (!settings.enabled) throw new Error("remote is off on this computer: run `worktrust remote app` (or `remote web`)");
|
|
107
107
|
if (!identity || !keys) throw new Error("this computer is not paired for remote: run `worktrust remote app` (or `remote web`)");
|
|
108
|
-
|
|
108
|
+
// A computer saved with `gateway: null` (0.11.8 and 0.11.9 saved that when none was given) uses WorkTrust's relay: no new
|
|
109
|
+
// approval is needed (owner, 2026-11-14: on by default).
|
|
110
|
+
const gateway = gatewayOf(settings);
|
|
109
111
|
if (!webSocketAvailable()) throw new Error(`remote needs Node 22.4 or later (this is ${process.versions.node})`);
|
|
110
|
-
const keysOf = issuerKeys(
|
|
112
|
+
const keysOf = issuerKeys(gateway);
|
|
111
113
|
const claims = P.verifyBinding(identity.binding, { issuerKeys: keysOf, now: Date.now(), kind: "computer", deviceId: identity.device_id });
|
|
112
114
|
if (!claims.ok) throw new Error(`this computer's binding does not verify (${claims.code}): run \`worktrust remote app\` (or \`remote web\`) again`);
|
|
113
115
|
if (claims.value.exp * 1000 - Date.now() < 7 * 86400_000 && identity.origin) {
|
|
@@ -176,9 +178,9 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
|
|
|
176
178
|
// The production gateway admits a computer on a five-minute assertion from the issuer, asked fresh for every challenge.
|
|
177
179
|
const { requestAssertion } = await import("./remote-pairing.mjs");
|
|
178
180
|
const authorize = () => (identity.origin ? requestAssertion({ origin: identity.origin, deviceId: identity.device_id, secret: keys.secret }) : Promise.resolve(null));
|
|
179
|
-
transport = connectGateway({ url:
|
|
181
|
+
transport = connectGateway({ url: gateway, identity, signingSecret: keys.secret.ed25519, log, authorize, onFrame: (f) => { dispatchFrame(f).catch((e) => log("frame_failed", { name: e?.name ?? "Error" })); },
|
|
180
182
|
onState: (state, info) => { log("gateway", { state, ...info }); if (state === "ready") registerCode(true); } });
|
|
181
|
-
say(` WorkTrust remote is running for ${identity.device_id} (gateway ${new URL(
|
|
183
|
+
say(` WorkTrust remote is running for ${identity.device_id} (gateway ${new URL(gateway).host}). Ctrl+C stops it.`);
|
|
182
184
|
let stopping = false;
|
|
183
185
|
const stop = async (code = 0) => {
|
|
184
186
|
if (stopping) return;
|
package/remote-sessions.mjs
CHANGED
|
@@ -17,13 +17,13 @@ import { allowedModes, startChoice } from "./remote-settings.mjs";
|
|
|
17
17
|
import { claudeArgs, isClaudeSessionId, removeQuietly, startClaude, writeMcpConfig } from "./remote-adapter-claude-code.mjs";
|
|
18
18
|
import { backgroundJobs, emptyClaudeState, endClaudeRun, mapClaudeLine } from "./remote-claude-events.mjs";
|
|
19
19
|
import { collectChanges, snapshotChanges } from "./remote-changes.mjs";
|
|
20
|
-
import { isCodexThreadId, startCodex, writeBridgeSession } from "./remote-adapter-codex.mjs";
|
|
20
|
+
import { codexDeskGrants, isCodexThreadId, startCodex, writeBridgeSession } from "./remote-adapter-codex.mjs";
|
|
21
21
|
import { emptyCodexState, mapCodexMessage, unwrapShell } from "./remote-codex-events.mjs";
|
|
22
22
|
import { isOpenCodeSessionId, mintOpenCodeSessionId } from "./remote-adapter-opencode.mjs";
|
|
23
23
|
import { emptyOpenCodeState } from "./remote-opencode-events.mjs";
|
|
24
24
|
import { spawnOpenCode } from "./remote-opencode-session.mjs";
|
|
25
25
|
import { createCoalescer } from "./remote-coalesce.mjs";
|
|
26
|
-
import { accept, announceQueue, claudeReplay, codexLanded, dropWaiting, interruptedEnd, interruptOf, steerLive, steerModeOf } from "./remote-steering.mjs";
|
|
26
|
+
import { accept, announceQueue, claudeReplay, codexLanded, dropWaiting, interruptedEnd, interruptOf, modelRefusal, steerLive, steerModeOf, switchModel } from "./remote-steering.mjs";
|
|
27
27
|
import { classifyAction } from "./remote-policy.mjs";
|
|
28
28
|
import { activeRows, listSessions, statusReport } from "./remote-session-list.mjs";
|
|
29
29
|
|
|
@@ -46,10 +46,12 @@ export function createSessions(ctx) {
|
|
|
46
46
|
};
|
|
47
47
|
const mark = (s) => s.agent_ref && appendSteered({ v: 1, steered: "remote", adapter: s.adapter, agent_session_ref: s.agent_ref, remote_session_id: s.session_id, project_id: s.project_id, how: s.how, first_steered_at: s.first, last_steered_at: ctx.now() });
|
|
48
48
|
const advance = (s, kind) => { if (s.command_id) ctx.journal.advance(s.command_id, { kind }, ctx.now()); };
|
|
49
|
+
const deskGranted = (adapter, projectPath) => adapter === "codex" && codexDeskGrants({ env: ctx.agentEnv(), projectPath }).length > 0; // read at each start
|
|
49
50
|
|
|
50
51
|
function nextTurn(s) {
|
|
51
52
|
// A Claude Code steer not yet read may become a turn of its own: the next prompt waits until it was (P3-7).
|
|
52
|
-
if (s.turnOpen || s.queue.length === 0 || !s.run?.alive() || (s.adapter !== "codex" && s.steers.length > 0)) return;
|
|
53
|
+
if (s.switching || s.turnOpen || s.queue.length === 0 || !s.run?.alive() || (s.adapter !== "codex" && s.steers.length > 0)) return;
|
|
54
|
+
if (s.queue[0].model !== undefined && s.queue[0].model !== s.model && switchModel(ctx, s, s.queue[0].model, { respawn: () => spawnAgent(s, s.agent_ref), resumeTurns: () => nextTurn(s) }) === "later") return;
|
|
53
55
|
const item = s.queue.shift();
|
|
54
56
|
s.waiting = item;
|
|
55
57
|
s.turnOpen = true;
|
|
@@ -173,7 +175,7 @@ export function createSessions(ctx) {
|
|
|
173
175
|
if (!s.stopping) taskEnded(s, "failed"); // an agent that exits before its task's turn ended did not do the task
|
|
174
176
|
s.turnOpen = false;
|
|
175
177
|
s.run = null;
|
|
176
|
-
dropWaiting(ctx, s); // a revived session never runs words sent to the agent that died
|
|
178
|
+
if (!s.switching) dropWaiting(ctx, s); // a revived session never runs words sent to the agent that died (a model switch's restart keeps them)
|
|
177
179
|
ctx.onActivity?.();
|
|
178
180
|
}
|
|
179
181
|
|
|
@@ -189,8 +191,7 @@ export function createSessions(ctx) {
|
|
|
189
191
|
onThread: (id) => { s.agent_ref = id; mark(s); ctx.journal.recordSession({ session_id: s.session_id, agent_session_ref: id }); },
|
|
190
192
|
approve: async (tool, input) => (await ctx.approvals.request(s, tool, input))?.behavior === "allow" });
|
|
191
193
|
ctx.journal.recordSession({ session_id: s.session_id, pid: s.run.pid ?? null });
|
|
192
|
-
s.ledgerTimer = setInterval(() => { if (s.turnOpen) mark(s); }, LEDGER_EVERY_MS);
|
|
193
|
-
s.ledgerTimer.unref?.();
|
|
194
|
+
s.ledgerTimer = setInterval(() => { if (s.turnOpen) mark(s); }, LEDGER_EVERY_MS); s.ledgerTimer.unref?.();
|
|
194
195
|
}
|
|
195
196
|
|
|
196
197
|
function spawnAgent(s, resume) {
|
|
@@ -203,8 +204,7 @@ export function createSessions(ctx) {
|
|
|
203
204
|
mark(s); // the ledger names the session before the agent writes a line
|
|
204
205
|
s.run = startClaude({ file: ctx.inventory().files["claude-code"], cwd: s.projectPath, env: ctx.agentEnv(), args, onLine: (line) => onLine(s, line), onExit: (how) => onExit(s, how) });
|
|
205
206
|
ctx.journal.recordSession({ session_id: s.session_id, pid: s.run.pid ?? null, agent_session_ref: s.agent_ref }); // a later daemon ends it if this one dies (P2-b)
|
|
206
|
-
s.ledgerTimer = setInterval(() => { if (s.turnOpen) mark(s); }, LEDGER_EVERY_MS);
|
|
207
|
-
s.ledgerTimer.unref?.();
|
|
207
|
+
s.ledgerTimer = setInterval(() => { if (s.turnOpen) mark(s); }, LEDGER_EVERY_MS); s.ledgerTimer.unref?.();
|
|
208
208
|
}
|
|
209
209
|
|
|
210
210
|
function start(env, payload) {
|
|
@@ -215,8 +215,8 @@ export function createSessions(ctx) {
|
|
|
215
215
|
if (!project) return "not_found";
|
|
216
216
|
const refused = P.checkStart(payload, adapterOf(ctx.inventory(), payload.adapter)); if (refused) return refused;
|
|
217
217
|
const choice = startChoice(payload, project.project_id, ctx.inventory(), ctx.settings(), known); if (typeof choice === "string") return choice;
|
|
218
|
-
if (!AGENT_ID[payload.adapter]) return "unsupported";
|
|
219
|
-
if (payload.
|
|
218
|
+
if (!AGENT_ID[payload.adapter] || (payload.resume !== null && !AGENT_ID[payload.adapter](payload.resume))) return "unsupported";
|
|
219
|
+
if (deskGranted(payload.adapter, project.path)) return "not_allowed"; // S0: Codex's own allow rules cannot be denied per session
|
|
220
220
|
const s = { session_id: env.session_id, project_id: project.project_id, projectPath: project.path, adapter: payload.adapter, model: payload.model, mode: payload.permission_mode,
|
|
221
221
|
agent_ref: payload.resume ?? (payload.adapter === "codex" ? null : payload.adapter === "opencode" ? mintOpenCodeSessionId(ctx.now(), ctx.random) : randomUUID()), how: "started", first: ctx.now(), queue: [], state: FRESH_STATE[payload.adapter](),
|
|
222
222
|
coalesce: createCoalescer({ now: ctx.now }), attention: null, command_id: null, waiting: null, turnOpen: false, run: null, steers: [], interrupting: false, ownTurn: null, task: env.task === true, tokens: P.NO_TOKENS, subagents: new Map(), turnStartedAt: null, name: payload.name ?? null, active: 0, countedTurn: null,
|
|
@@ -234,11 +234,11 @@ export function createSessions(ctx) {
|
|
|
234
234
|
/** A known session whose agent is gone (a daemon restart) resumes by the agent's own id. */
|
|
235
235
|
function revive(sessionId) {
|
|
236
236
|
let s = live.get(sessionId);
|
|
237
|
-
if (s?.run) return s;
|
|
237
|
+
if (s?.run || s?.switching) return s; // a model switch restarts it on its own
|
|
238
238
|
const saved = s ?? ctx.journal.session(sessionId);
|
|
239
239
|
if (!saved || saved.closed) return null;
|
|
240
240
|
const known = ctx.projects(), project = known.find((p) => p.project_id === saved.project_id), ref = s?.agent_ref ?? saved.agent_session_ref;
|
|
241
|
-
if (!project || !AGENT_ID[saved.adapter]?.(ref)) return null;
|
|
241
|
+
if (!project || !AGENT_ID[saved.adapter]?.(ref) || deskGranted(saved.adapter, project.path)) return null;
|
|
242
242
|
const agentMode = s?.agentMode ?? saved.agent_mode ?? null; // within today's ceiling, or it stays down (0.11.7)
|
|
243
243
|
if (agentMode && !allowedModes(ctx.settings()).includes(agentMode)) return null;
|
|
244
244
|
const extras = (s?.extraIds ?? saved.extra_project_ids ?? []).map((id) => known.find((p) => p.project_id === id)).filter(Boolean);
|
|
@@ -246,8 +246,7 @@ export function createSessions(ctx) {
|
|
|
246
246
|
s = s ?? { session_id: sessionId, project_id: saved.project_id, projectPath: project.path, adapter: saved.adapter, model: saved.model ?? null, mode: saved.mode ?? "ask", agent_ref: ref, how: "started", first: ctx.now(), queue: [], state: FRESH_STATE[saved.adapter](),
|
|
247
247
|
coalesce: createCoalescer({ now: ctx.now }), attention: null, command_id: null, waiting: null, turnOpen: false, run: null, steers: [], interrupting: false, ownTurn: null, task: false, tokens: P.NO_TOKENS, subagents: new Map(), turnStartedAt: null, name: saved.name ?? null, active: saved.active_ms ?? null, countedTurn: null,
|
|
248
248
|
agentMode, effort: saved.effort ?? null, extraIds: extras.map((p) => p.project_id), extraPaths: extras.map((p) => p.path) };
|
|
249
|
-
live.set(sessionId, s);
|
|
250
|
-
spawnAgent(s, s.agent_ref);
|
|
249
|
+
live.set(sessionId, s); spawnAgent(s, s.agent_ref);
|
|
251
250
|
return s;
|
|
252
251
|
}
|
|
253
252
|
|
|
@@ -275,7 +274,8 @@ export function createSessions(ctx) {
|
|
|
275
274
|
const report = adapterOf(ctx.inventory(), s.adapter);
|
|
276
275
|
const named = ctx.attachments ? ctx.attachments.referenceText(s.session_id, payload.attachments) : payload.attachments?.length ? null : ""; // null: refused, never ""
|
|
277
276
|
if (named === null) return "not_found"; // a file it names is not here whole: never a prompt without its file
|
|
278
|
-
const
|
|
277
|
+
const refusedModel = payload.model === undefined ? null : modelRefusal(ctx, s, payload.model); if (refusedModel) return refusedModel;
|
|
278
|
+
const item = { text: payload.text + named, command_id, received_at: ctx.now(), ...(payload.model !== undefined ? { model: payload.model } : {}) };
|
|
279
279
|
if (type === "agent.steer" && steerModeOf(report) === "none") return "unsupported";
|
|
280
280
|
mark(s);
|
|
281
281
|
if (type === "agent.steer" && s.turnOpen && steerModeOf(report) === "live" && (await steerLive(ctx, s, item))) return null;
|
package/remote-steering.mjs
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* Pure helpers over a session record `s`; the sessions module owns the agent processes.
|
|
16
16
|
*/
|
|
17
17
|
import * as P from "./remote-protocol.mjs";
|
|
18
|
+
import { agentOptionsOf } from "./remote-inventory.mjs";
|
|
18
19
|
|
|
19
20
|
/** Tell the phone where each waiting command stands, once per change of place. */
|
|
20
21
|
export function announceQueue(ctx, s, reason = "turn_running") {
|
|
@@ -95,3 +96,62 @@ export function interruptedEnd(ctx, s, event) {
|
|
|
95
96
|
/** What the adapter reports for words sent mid-turn (the phone offers only this). */
|
|
96
97
|
export const steerModeOf = (report) => (report ? P.steerOffered(report.capabilities) : "none");
|
|
97
98
|
export const interruptOf = (report) => Boolean(report && P.interruptOffered(report.capabilities));
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* ANOTHER MODEL OF THE SAME AGENT INSIDE A SESSION (release 33; owner, 2026-11-13: option A; docs/remote-agents/PROTOCOL.md
|
|
102
|
+
* "A model is chosen per session"). An agent.prompt may carry `model`: one of the session's OWN adapter's listed models,
|
|
103
|
+
* for that turn and the turns after it. Another agent is never a model (the payload names no adapter): it is a new chat,
|
|
104
|
+
* with no hand-over. Verified per adapter from the adapters themselves (2026-11-14):
|
|
105
|
+
*
|
|
106
|
+
* Claude Code its own resume with another model flag: the idle process ends and starts again with
|
|
107
|
+
* `--resume <its own session id> --model <model>` (claudeArgs takes both; `--model` is "Model for the current
|
|
108
|
+
* session" in 2.1.322's help). NOT run against a live model here: the restart is proven on a fake Claude Code.
|
|
109
|
+
* Codex `turn/start` carries `model`: "Override the model for this turn and subsequent turns" (the app-server's own
|
|
110
|
+
* JSON schema, `codex app-server generate-json-schema`, 0.154.0); the thread and its process stay.
|
|
111
|
+
* OpenCode one process per run, `--session <id> --model <p/m>`: the next run takes the new model. NOT VERIFIED on a
|
|
112
|
+
* real install (OpenCode is not on the build machine), as the adapter itself says.
|
|
113
|
+
* terminal no switch: nothing is typed into a terminal session that the phone composed (a `/model` would be one).
|
|
114
|
+
*
|
|
115
|
+
* modelRefusal(ctx, s, model) on receipt: null, or why the prompt is refused (it then runs nothing)
|
|
116
|
+
* switchModel(ctx, s, model, o) at the turn's start: "now" (switched in place) or "later" (Claude Code restarts;
|
|
117
|
+
* o.respawn() then o.resumeTurns() run when its process is gone)
|
|
118
|
+
*
|
|
119
|
+
* The check is the protocol's own (checkModelSwitch) against the computer's CURRENT report and its own options, never the
|
|
120
|
+
* phone's: a model the agent did not list, or a switch for an adapter whose options do not say `model_switch`, is refused.
|
|
121
|
+
*/
|
|
122
|
+
/** → null when the session may continue on `model`, else the reject reason (unsupported, unknown_model). */
|
|
123
|
+
export function modelRefusal(ctx, s, model) {
|
|
124
|
+
const inv = ctx.inventory();
|
|
125
|
+
const report = P.reportFor(inv.reports, s.adapter, "structured");
|
|
126
|
+
const options = agentOptionsOf(inv).find((o) => o.adapter === s.adapter && o.mode === "structured") ?? null;
|
|
127
|
+
return P.checkModelSwitch(model, report, options);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Switch the session to `model` before its next turn. Codex and OpenCode take it in place (`run.setModel`). Claude Code's
|
|
132
|
+
* process is idle here (a turn starts only when none is open), so it ends and comes back on its own session id with the new
|
|
133
|
+
* model; the queue is held aside meanwhile and nothing waiting is dropped (`s.switching`, remote-sessions.mjs onExit).
|
|
134
|
+
*/
|
|
135
|
+
export function switchModel(ctx, s, model, o) {
|
|
136
|
+
const record = () => { s.model = model; ctx.journal.recordSession({ session_id: s.session_id, model }); ctx.onSessionsChanged?.(); };
|
|
137
|
+
if (typeof s.run?.setModel === "function") { s.run.setModel(model); record(); return "now"; }
|
|
138
|
+
if (s.adapter !== "claude-code") throw new Error("this adapter has no model switch"); // modelRefusal kept it out
|
|
139
|
+
s.switching = true;
|
|
140
|
+
s.stopping = true;
|
|
141
|
+
const held = s.queue.splice(0);
|
|
142
|
+
(async () => {
|
|
143
|
+
try {
|
|
144
|
+
await s.run?.stop();
|
|
145
|
+
s.stopping = false;
|
|
146
|
+
record();
|
|
147
|
+
o.respawn(); // spawnAgent(s, s.agent_ref): the ledger names the session first, then --resume <id> --model <model>
|
|
148
|
+
} catch {
|
|
149
|
+
s.stopping = false;
|
|
150
|
+
}
|
|
151
|
+
s.queue.unshift(...held, ...s.queue.splice(0)); // what arrived during the restart waits behind what was held
|
|
152
|
+
s.switching = false;
|
|
153
|
+
if (!s.run) dropWaiting(ctx, s); // the agent did not come back: what waited is cancelled, never left hanging
|
|
154
|
+
o.resumeTurns();
|
|
155
|
+
})();
|
|
156
|
+
return "later";
|
|
157
|
+
}
|
package/remote-store.mjs
CHANGED
|
@@ -72,6 +72,16 @@ export const saveIdentity = (identity) => writeJson("identity.json", identity);
|
|
|
72
72
|
// modes_allowed (0.11.7, owner 2026-11-12): the CEILING of agent modes a phone may start, set here only (`worktrust remote
|
|
73
73
|
// modes allow|deny edit|auto`); manual and plan always. admin (0.11.7): RESERVED for managing this computer from the app or
|
|
74
74
|
// the web with a server-signed proof (part B); on by default, honoured by nothing yet (remote-settings.mjs).
|
|
75
|
+
/**
|
|
76
|
+
* WORKTRUST'S PRODUCTION RELAY, ON BY DEFAULT FOR EVERYONE (owner, 2026-11-14: "it must be ON by default for everyone, also
|
|
77
|
+
* without Premium; the subscription comes later"; CLI 0.11.10). A computer's saved `gateway: null` means THIS default, read
|
|
78
|
+
* where it is used, so a later change of the default moves every computer that never chose one; `--gateway` and
|
|
79
|
+
* WORKTRUST_REMOTE_GATEWAY at `remote app` still choose another (the dev relay, tests), and that choice is saved.
|
|
80
|
+
* GATEWAY.md step 9 (a crypto review and a penetration test) is still open: the owner chose the default before it.
|
|
81
|
+
*/
|
|
82
|
+
export const PRODUCTION_GATEWAY = "wss://remote.worktrust.io";
|
|
83
|
+
/** The relay this computer uses: its own saved choice, else WorkTrust's. */
|
|
84
|
+
export const gatewayOf = (settings) => settings?.gateway ?? PRODUCTION_GATEWAY;
|
|
75
85
|
export const DEFAULT_SETTINGS = Object.freeze({ v: 1, enabled: false, paused: null, gateway: null, default_adapter: "claude-code", default_model: null, agent_path: null, codex: false, opencode: false, terminal: false, allow_endorse: false, modes_allowed: Object.freeze(["manual", "plan"]), admin: true });
|
|
76
86
|
export const loadSettings = () => ({ ...DEFAULT_SETTINGS, ...(readJson("settings.json") ?? {}) });
|
|
77
87
|
export const saveSettings = (settings) => writeJson("settings.json", { ...DEFAULT_SETTINGS, ...settings });
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE SESSION READERS: where each AI app keeps its sessions on this computer, and how a session file is read (CLI 0.11.10,
|
|
3
|
+
* split from log-session.mjs unchanged, so the hook and `npx worktrust look` find and read sessions by ONE set of rules).
|
|
4
|
+
*
|
|
5
|
+
* Two halves. READING: a transcript read in 8 MB chunks, line by line, never whole; a read that fails is counted
|
|
6
|
+
* (READ_FAILURES), never silent; a resumed read checks the file is still the one it read (edgesOf). FINDING: every session
|
|
7
|
+
* of every AI app the readers know (Claude Code transcripts, Codex rollouts, Antigravity conversations and the database
|
|
8
|
+
* clients of session-databases.mjs), an excluded project skipped before a file is opened.
|
|
9
|
+
*
|
|
10
|
+
* The per-app parsing stays in transcript-readers.mjs and session-databases.mjs; this module takes their functions as
|
|
11
|
+
* arguments (transcriptLines, sessionFinders), so a copy without one of them still reads Claude Code, as before. Nothing
|
|
12
|
+
* here writes a file or opens a connection: it reads, counts and yields.
|
|
13
|
+
*/
|
|
14
|
+
import { closeSync, existsSync, fstatSync, openSync, readdirSync, readSync, statSync } from "node:fs";
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
|
|
19
|
+
// ── reading a session file ──
|
|
20
|
+
/**
|
|
21
|
+
* A FILE'S LINES, READ IN CHUNKS (0.10.32). A whole-file `readFileSync(file, "utf8")` throws past the longest string Node
|
|
22
|
+
* makes (about 512 MB), and that throw was read as "this file cannot be read": the owner's VS Code session passed it on
|
|
23
|
+
* 2026-10-18 (797 MB by 10-28) and from then on measured no day at all, live or re-measured. Read 8 MB at a time, one
|
|
24
|
+
* line at a time; re-iterable (each pass opens the file again); null only when the file cannot be opened.
|
|
25
|
+
*/
|
|
26
|
+
const CHUNK_BYTES = 8 << 20;
|
|
27
|
+
/**
|
|
28
|
+
* The read buffer for one file, sized to what is left of it (CLI 0.11.11; docs/OPEN.md "Rust was measured and not taken"):
|
|
29
|
+
* 8 MB allocated for every file cost about 3.4 s over 10,000 small rollouts. At least 64 KiB, so a file that grows while
|
|
30
|
+
* it is read (a live transcript) still reads in sensible steps; at most CHUNK_BYTES; CHUNK_BYTES when fstat fails.
|
|
31
|
+
*/
|
|
32
|
+
function readBufferFor(fd, from = 0) {
|
|
33
|
+
let left = CHUNK_BYTES;
|
|
34
|
+
try { left = fstatSync(fd).size - from + 1; } catch { left = CHUNK_BYTES; }
|
|
35
|
+
return Buffer.allocUnsafe(Math.min(CHUNK_BYTES, Math.max(64 << 10, left)));
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* A READ THAT FAILS IS COUNTED, NEVER SILENT (0.10.32): a transcript that exists and cannot be opened or read to its end
|
|
39
|
+
* is one failure. The run keeps the count in sessions.json (`npx worktrust status` says it) and tells WorkTrust the
|
|
40
|
+
* count alone, never which file or what was in it (reportUnreadable).
|
|
41
|
+
*/
|
|
42
|
+
const READ_FAILURES = { n: 0 };
|
|
43
|
+
/** The bytes this run read from transcripts (the resume's own measure, below): said on stderr under WORKTRUST_HOOK_DEBUG, never sent. */
|
|
44
|
+
const READ_BYTES = { n: 0 };
|
|
45
|
+
/**
|
|
46
|
+
* What a resume trusts of the bytes it does not read again: eight 4 KB samples before the offset, the first and the last of
|
|
47
|
+
* them at its edges and six spread evenly between, hashed with the offset (32 KB read, whatever the file's length).
|
|
48
|
+
*/
|
|
49
|
+
const EDGE_BYTES = 4096, EDGE_SAMPLES = 8;
|
|
50
|
+
const edgesOf = (fd, end) => {
|
|
51
|
+
const hash = createHash("sha256").update(`worktrust-read-position|${end}|`), buffer = Buffer.allocUnsafe(EDGE_BYTES);
|
|
52
|
+
const starts = end <= EDGE_BYTES ? [0] : [...new Set(Array.from({ length: EDGE_SAMPLES }, (_, k) => Math.floor((k * (end - EDGE_BYTES)) / (EDGE_SAMPLES - 1))))];
|
|
53
|
+
for (const from of starts) {
|
|
54
|
+
const want = Math.min(EDGE_BYTES, end - from);
|
|
55
|
+
let got = 0;
|
|
56
|
+
while (got < want) { const n = readSync(fd, buffer, got, want - got, from + got); if (n <= 0) break; got += n; }
|
|
57
|
+
READ_BYTES.n += got;
|
|
58
|
+
hash.update(buffer.subarray(0, got));
|
|
59
|
+
}
|
|
60
|
+
return hash.digest("base64url").slice(0, 22);
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* The lines from byte `from` (a line boundary), split on the newline BYTE, which no UTF-8 sequence holds, and decoded line by
|
|
64
|
+
* line. `at`, when given, says where each yielded line starts (`at.line`) and, read through the same descriptor the lines came
|
|
65
|
+
* from: the file's identity (`at.dev`, `at.ino`), the offset after its last newline (`at.end`, set before an unterminated last
|
|
66
|
+
* line is yielded) and the hash of its edges before that offset (`at.hash`). `at.failed` is a read that failed (counted, as
|
|
67
|
+
* always); `at.moved` a file that is not the one `expect` names (another identity, shorter than its offset, other bytes at its
|
|
68
|
+
* edges): nothing is yielded and nothing counted, and the caller reads it whole.
|
|
69
|
+
*/
|
|
70
|
+
function* chunkedLines(file, from = 0, at = null, expect = null) {
|
|
71
|
+
let fd;
|
|
72
|
+
try { fd = openSync(file, "r"); } catch { READ_FAILURES.n += 1; if (at) at.failed = true; return; }
|
|
73
|
+
try {
|
|
74
|
+
if (at || expect) {
|
|
75
|
+
let stat; try { stat = fstatSync(fd); } catch { READ_FAILURES.n += 1; if (at) at.failed = true; return; }
|
|
76
|
+
if (at) { at.dev = String(stat.dev); at.ino = String(stat.ino); }
|
|
77
|
+
if (expect) {
|
|
78
|
+
let same = false;
|
|
79
|
+
try { same = String(stat.dev) === expect.dev && String(stat.ino) === expect.ino && stat.size >= expect.end && expect.end >= from && (expect.end === 0 ? expect.hash === null : edgesOf(fd, expect.end) === expect.hash); } catch { same = false; }
|
|
80
|
+
if (!same) { if (at) at.moved = true; return; }
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const buffer = readBufferFor(fd, from);
|
|
84
|
+
let pending = [], position = from, lineStart = from;
|
|
85
|
+
for (;;) {
|
|
86
|
+
let n;
|
|
87
|
+
try { n = readSync(fd, buffer, 0, buffer.length, position); } catch { READ_FAILURES.n += 1; if (at) at.failed = true; return; }
|
|
88
|
+
if (n <= 0) break;
|
|
89
|
+
READ_BYTES.n += n;
|
|
90
|
+
const chunk = buffer.subarray(0, n);
|
|
91
|
+
let start = 0;
|
|
92
|
+
for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, start)) {
|
|
93
|
+
const text = pending.length > 0 ? Buffer.concat([...pending, chunk.subarray(start, nl)]).toString("utf8") : chunk.toString("utf8", start, nl);
|
|
94
|
+
pending = [];
|
|
95
|
+
if (at) at.line = lineStart;
|
|
96
|
+
lineStart = position + nl + 1; start = nl + 1;
|
|
97
|
+
yield text;
|
|
98
|
+
}
|
|
99
|
+
if (start < n) pending.push(Buffer.from(chunk.subarray(start)));
|
|
100
|
+
position += n;
|
|
101
|
+
}
|
|
102
|
+
if (at) { at.end = lineStart; try { at.hash = lineStart > 0 ? edgesOf(fd, lineStart) : null; } catch { READ_FAILURES.n += 1; at.failed = true; } }
|
|
103
|
+
const rest = pending.length > 0 ? Buffer.concat(pending).toString("utf8") : "";
|
|
104
|
+
if (rest) { if (at) at.line = lineStart; yield rest; }
|
|
105
|
+
} finally { closeSync(fd); }
|
|
106
|
+
}
|
|
107
|
+
/** A Claude Code transcript's lines as objects from byte `from`, `at` and `expect` as chunkedLines takes them. */
|
|
108
|
+
function* claudeLinesFrom(file, from, at, expect) { for (const raw of chunkedLines(file, from, at, expect)) { if (!raw.trim()) continue; let line; try { line = JSON.parse(raw); } catch { continue; } yield line; } }
|
|
109
|
+
const fileLines = (file) => {
|
|
110
|
+
try { closeSync(openSync(file, "r")); } catch (error) { if (error?.code !== "ENOENT") READ_FAILURES.n += 1; return null; }
|
|
111
|
+
return { [Symbol.iterator]: () => chunkedLines(file) };
|
|
112
|
+
};
|
|
113
|
+
export { READ_FAILURES, READ_BYTES, chunkedLines, claudeLinesFrom, fileLines };
|
|
114
|
+
|
|
115
|
+
/** The line reader for any client's session, given the per-client readers (transcript-readers.mjs, session-databases.mjs). */
|
|
116
|
+
export function transcriptLines({ DATABASE_SESSION, databaseLines, CODEX_ROLLOUT, codexLines, ANTIGRAVITY_TRANSCRIPT, antigravityIdOf, antigravityLines, antigravityContext }) {
|
|
117
|
+
/** A transcript's lines as objects, whichever client wrote it; null when the file cannot be read. A Claude Code transcript is parsed lazily, as it is read. */
|
|
118
|
+
const parsedLines = (file) => {
|
|
119
|
+
if (DATABASE_SESSION.test(file)) return databaseLines(file);
|
|
120
|
+
const lines = fileLines(file);
|
|
121
|
+
if (!lines) return null;
|
|
122
|
+
if (CODEX_ROLLOUT.test(file)) return [...codexLines(lines)];
|
|
123
|
+
if (ANTIGRAVITY_TRANSCRIPT.test(file)) { const id = antigravityIdOf(file); return [...antigravityLines(lines, { id, ...antigravityContext(id) })]; }
|
|
124
|
+
return { *[Symbol.iterator]() { for (const raw of lines) { if (!raw.trim()) continue; try { yield JSON.parse(raw); } catch { /* a torn line */ } } } };
|
|
125
|
+
};
|
|
126
|
+
return parsedLines;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ── finding each AI app's sessions ──
|
|
130
|
+
/**
|
|
131
|
+
* The finders, given the hook's arguments (`value`: a test names its own roots), its project modes (`excluded`) and the
|
|
132
|
+
* per-client readers. Returns the roots and the walks the hook and `look` share.
|
|
133
|
+
*/
|
|
134
|
+
export function sessionFinders({ value, excluded, DATABASE_CLIENTS, codexRolloutFiles, codexCwd, codexIdOf, antigravityRoots, antigravityTranscripts, antigravityContext, databaseSessions }) {
|
|
135
|
+
/** The roots this machine's transcripts live under; a test names its own. */
|
|
136
|
+
const claudeRoot = () => value("transcript-root") ?? join(homedir(), ".claude", "projects");
|
|
137
|
+
const codexRoot = () => { const given = value("codex-root"); if (given) return given.replace(/^~(?=\/|$)/, homedir()); return value("transcript-root") ? null : join(homedir(), ".codex", "sessions"); };
|
|
138
|
+
/** Every Codex rollout and Antigravity conversation on this machine, an excluded project's threads skipped by their working directory. */
|
|
139
|
+
function* codexRollouts() {
|
|
140
|
+
const root = codexRoot();
|
|
141
|
+
for (const file of root ? codexRolloutFiles(root) : []) {
|
|
142
|
+
const cwd = codexCwd(file);
|
|
143
|
+
if (cwd && excluded(cwd)) continue;
|
|
144
|
+
yield { id: `codex:${codexIdOf(file)}`, file };
|
|
145
|
+
}
|
|
146
|
+
yield* antigravityConversations();
|
|
147
|
+
yield* databaseConversations();
|
|
148
|
+
}
|
|
149
|
+
/** The attended sessions of the clients that keep a database (session-databases.mjs); an excluded folder skipped. */
|
|
150
|
+
function* databaseConversations() {
|
|
151
|
+
const given = Object.fromEntries(DATABASE_CLIENTS.map((client) => [client, value(`${client}-root`)]).filter(([, root]) => root));
|
|
152
|
+
for (const { client, sessionId, file, cwd, writtenAt } of databaseSessions(given, Boolean(value("transcript-root")))) {
|
|
153
|
+
if (!(cwd && excluded(cwd))) yield { id: `${client}:${sessionId}`, file, writtenAt };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/** Antigravity beside Codex: one transcript per conversation, its folder known only from the Stop hook. */
|
|
157
|
+
function* antigravityConversations() {
|
|
158
|
+
const given = value("antigravity-root");
|
|
159
|
+
for (const { conversationId, file } of antigravityTranscripts(given || !value("transcript-root") ? antigravityRoots(given) : [])) {
|
|
160
|
+
const { cwd } = antigravityContext(conversationId);
|
|
161
|
+
if (!(cwd && excluded(cwd))) yield { id: `antigravity:${conversationId}`, file };
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Every transcript this machine holds, excluded projects skipped before a file is opened. */
|
|
166
|
+
function* allTranscripts() {
|
|
167
|
+
const root = claudeRoot();
|
|
168
|
+
if (existsSync(root)) for (const dir of readdirSync(root)) {
|
|
169
|
+
if (excluded(dir)) continue;
|
|
170
|
+
let files;
|
|
171
|
+
try { files = readdirSync(join(root, dir)); } catch { continue; }
|
|
172
|
+
for (const file of files) if (file.endsWith(".jsonl")) yield { id: file.replace(/\.jsonl$/, ""), file: join(root, dir, file) };
|
|
173
|
+
}
|
|
174
|
+
yield* codexRollouts();
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* EVERY TRANSCRIPT, with what it was last written. The two filters that used to live here decided
|
|
179
|
+
* the wrong thing at the wrong level:
|
|
180
|
+
*
|
|
181
|
+
* - "idle 30 minutes" skipped the file being typed into, and with it every earlier day of a
|
|
182
|
+
* session that has been open for a fortnight. Whether a DAY is finished is a fact about the day.
|
|
183
|
+
* - "not older than 48 hours" skipped the machine that was closed for four months, which is
|
|
184
|
+
* exactly the person whose work needs collecting when they come back.
|
|
185
|
+
*
|
|
186
|
+
* The caller opens a file only when it has been written since the watermark says we last read it,
|
|
187
|
+
* so a sweep over a hundred transcripts costs a hundred `stat` calls and nothing more.
|
|
188
|
+
*/
|
|
189
|
+
function* candidates() {
|
|
190
|
+
for (const rollout of codexRollouts()) {
|
|
191
|
+
if (rollout.writtenAt) { yield rollout; continue; } // a database session knows its own last moment
|
|
192
|
+
let stat; try { stat = statSync(rollout.file); } catch { continue; }
|
|
193
|
+
yield { ...rollout, writtenAt: stat.mtimeMs };
|
|
194
|
+
}
|
|
195
|
+
const root = claudeRoot();
|
|
196
|
+
if (!existsSync(root)) return;
|
|
197
|
+
for (const dir of readdirSync(root)) {
|
|
198
|
+
if (excluded(dir)) continue;
|
|
199
|
+
const path = join(root, dir);
|
|
200
|
+
let files;
|
|
201
|
+
try { files = readdirSync(path); } catch { continue; }
|
|
202
|
+
for (const file of files) {
|
|
203
|
+
if (!file.endsWith(".jsonl")) continue;
|
|
204
|
+
const full = join(path, file);
|
|
205
|
+
let stat;
|
|
206
|
+
try { stat = statSync(full); } catch { continue; }
|
|
207
|
+
yield { id: file.replace(/\.jsonl$/, ""), file: full, writtenAt: stat.mtimeMs };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return { claudeRoot, codexRoot, codexRollouts, databaseConversations, antigravityConversations, allTranscripts, candidates };
|
|
212
|
+
}
|
package/transcript-readers.mjs
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* counter's named rules and the hook's measure(), whose payloads are fixed allowlists of numbers,
|
|
14
14
|
* dates and enum values (log-session.mjs, "WHAT CANNOT LEAVE").
|
|
15
15
|
*/
|
|
16
|
-
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
|
16
|
+
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
|
17
17
|
import { createHash } from "node:crypto";
|
|
18
18
|
import { spawnSync } from "node:child_process";
|
|
19
19
|
import { homedir } from "node:os";
|
|
@@ -252,16 +252,16 @@ export function* codexLines(records) {
|
|
|
252
252
|
*/
|
|
253
253
|
const EFFORT_LEVELS = new Set(["low", "medium", "high", "xhigh", "max"]);
|
|
254
254
|
/**
|
|
255
|
-
* A FILE'S LINES, 8 MB AT A TIME (0.10.32
|
|
256
|
-
*
|
|
257
|
-
* Null when the file cannot be opened; a read that fails halfway ends
|
|
255
|
+
* A FILE'S LINES, 8 MB AT A TIME (0.10.32; a buffer sized to the file, 64 KiB to 8 MB, since 0.11.11): a whole-file read
|
|
256
|
+
* throws past Node's longest string (about 512 MB), which is how the owner's Claude Code session went unmeasured from
|
|
257
|
+
* 2026-10-18; a rollout is read the same way. Null when the file cannot be opened; a read that fails halfway ends there.
|
|
258
258
|
*/
|
|
259
259
|
export function streamedLines(file) {
|
|
260
260
|
try { closeSync(openSync(file, "r")); } catch { return null; }
|
|
261
261
|
return { *[Symbol.iterator]() {
|
|
262
262
|
let fd; try { fd = openSync(file, "r"); } catch { return; }
|
|
263
263
|
try {
|
|
264
|
-
const decoder = new StringDecoder("utf8"), buffer = Buffer.allocUnsafe(8 << 20);
|
|
264
|
+
const decoder = new StringDecoder("utf8"), buffer = Buffer.allocUnsafe(Math.min(8 << 20, Math.max(64 << 10, (() => { try { return fstatSync(fd).size + 1; } catch { return 8 << 20; } })())));
|
|
265
265
|
let rest = "";
|
|
266
266
|
for (;;) {
|
|
267
267
|
let n; try { n = readSync(fd, buffer, 0, buffer.length, null); } catch { return; }
|