ltms-reader 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +136 -0
- package/LICENSE +21 -0
- package/LICENSE-UNICODE +49 -0
- package/README.md +284 -2
- package/bin/ltms-reader.mjs +16 -0
- package/package.json +32 -4
- package/src/app.mjs +415 -0
- package/src/bidi-table.mjs +354 -0
- package/src/bidi.mjs +251 -0
- package/src/engine.mjs +505 -0
- package/src/guard.mjs +116 -0
- package/src/helper.mjs +127 -0
- package/src/layout.mjs +181 -0
- package/src/lines.mjs +18 -0
- package/src/main.mjs +133 -0
- package/src/reading.mjs +165 -0
- package/src/screen-process.mjs +6 -0
- package/src/screen.mjs +127 -0
- package/src/sources.mjs +134 -0
- package/src/start.mjs +123 -0
- package/src/text.mjs +712 -0
- package/src/view.mjs +337 -0
- package/src/views.mjs +518 -0
- package/src/width-table.mjs +101 -0
package/src/engine.mjs
ADDED
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
// src/engine.mjs — everything the extension knows how to read, with no editor in it (so it is tested as it is):
|
|
2
|
+
// the projects under the root, a project's sessions (`ltms index`), a session's turns and any record in it (the helper,
|
|
3
|
+
// on ltms's library), and search (`ltms search`). `index` and `search` run ltms's own CLI (#ltms/cli, which the host
|
|
4
|
+
// package maps: ltms-reader to its dependency's, the extension to its vendored copy's), so the lines the page draws are
|
|
5
|
+
// the lines an agent reads from the same command.
|
|
6
|
+
//
|
|
7
|
+
// Names come from the page; paths never do. A project is a directory name the root lists; a transcript is its path in
|
|
8
|
+
// that project ('/'-separated), any regular .jsonl at any depth that ltms's own walk would read (src/layout.mjs). Every
|
|
9
|
+
// one is checked here against the disk, without following a symbolic link (ltms follows none under a directory either).
|
|
10
|
+
//
|
|
11
|
+
// Copies: a project can hold one session in several files (a mirror of pinned sessions kept inside it lists each pinned
|
|
12
|
+
// session again). Files with the same name and the same bytes (sha256, computed in the reading process and kept by
|
|
13
|
+
// device, inode, size and time) are one transcript: one row, one target for an address, its hits shown once, and the
|
|
14
|
+
// others named as its copies. Same name, other bytes: other versions, each kept, each naming the others.
|
|
15
|
+
import { spawn } from 'node:child_process';
|
|
16
|
+
import { lstatSync, readdirSync, realpathSync } from 'node:fs';
|
|
17
|
+
import { open as openFile } from 'node:fs/promises';
|
|
18
|
+
import { createRequire } from 'node:module';
|
|
19
|
+
import { homedir } from 'node:os';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { fileURLToPath } from 'node:url';
|
|
22
|
+
import { onLines } from './lines.mjs';
|
|
23
|
+
import { prefixOf } from './view.mjs';
|
|
24
|
+
import { agentsOf, byPlace, classify, identifies, parentOf, transcriptAt, walk } from './layout.mjs';
|
|
25
|
+
|
|
26
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
27
|
+
/** ltms's CLI, resolved from the package this file sits in (its package.json "imports" maps #ltms/cli). */
|
|
28
|
+
export const CLI = createRequire(import.meta.url).resolve('#ltms/cli');
|
|
29
|
+
export const HELPER = path.join(HERE, 'helper.mjs');
|
|
30
|
+
|
|
31
|
+
/** The environment a child gets: what a Node program needs to find home, temp, locale and Claude Code's configuration,
|
|
32
|
+
* nothing else of the editor's, and the switch that makes the editor's binary run as Node. */
|
|
33
|
+
const PASS = ['HOME', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH', 'APPDATA', 'LOCALAPPDATA', 'SystemRoot', 'windir', 'TEMP', 'TMP', 'TMPDIR', 'PATH', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TZ', 'CLAUDE_CONFIG_DIR'];
|
|
34
|
+
export function childEnv(from = process.env, extra = {}) {
|
|
35
|
+
const env = {};
|
|
36
|
+
for (const k of PASS) if (typeof from[k] === 'string') env[k] = from[k];
|
|
37
|
+
return { ...env, ...extra, ELECTRON_RUN_AS_NODE: '1' };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export class Refusal extends Error { constructor(kind, message) { super(message); this.kind = kind; } }
|
|
41
|
+
|
|
42
|
+
/** A list read in less than this is read again when anything under its folder changed; a slower one is kept, and the
|
|
43
|
+
* page is told what changed (ms). */
|
|
44
|
+
export const AUTO_MS = 3000;
|
|
45
|
+
/** How long one walk of a project serves the requests of one action (ms). */
|
|
46
|
+
export const WALK_MS = 3000;
|
|
47
|
+
|
|
48
|
+
/** What changed between two snapshots (path → size:time): null when nothing did; else the counts and the first paths. */
|
|
49
|
+
export function changes(before, now) {
|
|
50
|
+
const changed = [], added = [], removed = [];
|
|
51
|
+
for (const [rel, sig] of now) { const b = before.get(rel); if (b === undefined) added.push(rel); else if (b !== sig) changed.push(rel); }
|
|
52
|
+
for (const rel of before.keys()) if (!now.has(rel)) removed.push(rel);
|
|
53
|
+
const count = changed.length + added.length + removed.length;
|
|
54
|
+
return count ? { count, changed: changed.slice(0, 20), added: added.slice(0, 20), removed: removed.slice(0, 20), counts: { changed: changed.length, added: added.length, removed: removed.length } } : null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const PLAIN = /^[^/\\\0]+$/;
|
|
58
|
+
const baseName = (rel) => rel.slice(rel.lastIndexOf('/') + 1);
|
|
59
|
+
const isName = (s) => typeof s === 'string' && s !== '.' && s !== '..' && PLAIN.test(s) && s.length <= 255;
|
|
60
|
+
const kindOf = (p) => { try { const s = lstatSync(p); return s.isSymbolicLink() ? 'link' : s.isDirectory() ? 'dir' : s.isFile() ? 'file' : 'other'; } catch { return 'none'; } };
|
|
61
|
+
|
|
62
|
+
/** Run ltms's CLI and collect its JSON lines. Never through a shell: the query is one argument. */
|
|
63
|
+
export function runLtms(args, { runtime = process.execPath, env = childEnv(), signal, maxStdout = 256 * 1024 * 1024, maxStderr = 64 * 1024 } = {}) {
|
|
64
|
+
return new Promise((resolve, reject) => {
|
|
65
|
+
const t0 = Date.now();
|
|
66
|
+
const child = spawn(runtime, [CLI, ...args], { env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
67
|
+
const lines = [];
|
|
68
|
+
let size = 0, stderr = '', bad = 0, over = false;
|
|
69
|
+
const onAbort = () => child.kill();
|
|
70
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
71
|
+
onLines(child.stdout, (l) => {
|
|
72
|
+
size += l.length + 1;
|
|
73
|
+
if (size > maxStdout) { if (!over) { over = true; child.kill(); } return; }
|
|
74
|
+
if (l === '') return;
|
|
75
|
+
try { lines.push(JSON.parse(l)); } catch { bad++; }
|
|
76
|
+
});
|
|
77
|
+
child.stderr.setEncoding('utf8');
|
|
78
|
+
child.stderr.on('data', (d) => { if (stderr.length < maxStderr) stderr += d.slice(0, maxStderr - stderr.length); });
|
|
79
|
+
child.on('error', (e) => { signal?.removeEventListener('abort', onAbort); reject(new Refusal('no-runtime', `could not start ltms with ${runtime} (${e.code ?? e.message})`)); });
|
|
80
|
+
child.on('close', (code, sig) => {
|
|
81
|
+
signal?.removeEventListener('abort', onAbort);
|
|
82
|
+
if (signal?.aborted) return reject(new Refusal('cancelled', 'cancelled'));
|
|
83
|
+
if (over) return reject(new Refusal('too-large', `ltms printed more than ${Math.round(maxStdout / 1048576)} MB; ask for fewer at a time`));
|
|
84
|
+
if (bad) return reject(new Refusal('bad-output', `ltms printed ${bad} line(s) that are not JSON`));
|
|
85
|
+
resolve({ code, signal: sig, lines, stderr, ms: Date.now() - t0 });
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** One long-lived helper process (src/helper.mjs), started on the first request and again after it exits. */
|
|
91
|
+
export class HelperClient {
|
|
92
|
+
constructor({ runtime = process.execPath, env = childEnv(), idleMs = 600_000, timeoutMs = 300_000, log = () => {} } = {}) {
|
|
93
|
+
Object.assign(this, { runtime, env: { ...env, LTMS_GUI_IDLE_MS: String(idleMs) }, timeoutMs, log });
|
|
94
|
+
this.child = null; this.next = 1; this.pending = new Map();
|
|
95
|
+
}
|
|
96
|
+
start() {
|
|
97
|
+
const child = spawn(this.runtime, [HELPER], { env: this.env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
|
|
98
|
+
this.child = child;
|
|
99
|
+
onLines(child.stdout, (l) => {
|
|
100
|
+
let m; try { m = JSON.parse(l); } catch { this.log(`helper: a line that is not JSON (${l.length} characters)`); return; }
|
|
101
|
+
const p = this.pending.get(m.id);
|
|
102
|
+
if (!p) return;
|
|
103
|
+
this.pending.delete(m.id);
|
|
104
|
+
if (m.ok) p.resolve(m.result); else p.reject(new Refusal(m.error?.kind ?? 'internal', m.error?.message ?? 'the helper refused'));
|
|
105
|
+
});
|
|
106
|
+
child.stderr.setEncoding('utf8');
|
|
107
|
+
child.stderr.on('data', (d) => this.log(`helper stderr: ${String(d).slice(0, 2000).trimEnd()}`));
|
|
108
|
+
const gone = (why) => {
|
|
109
|
+
if (this.child === child) this.child = null;
|
|
110
|
+
for (const [, p] of this.pending) p.reject(new Refusal('helper-exit', `the reading process ended (${why}) before it answered`));
|
|
111
|
+
this.pending.clear();
|
|
112
|
+
};
|
|
113
|
+
child.on('error', (e) => gone(`could not start: ${e.code ?? e.message}`));
|
|
114
|
+
child.on('exit', (code, sig) => gone(sig ? `signal ${sig}` : `exit ${code}`));
|
|
115
|
+
child.stdin.on('error', () => {});
|
|
116
|
+
}
|
|
117
|
+
request(op, args) {
|
|
118
|
+
if (!this.child) this.start();
|
|
119
|
+
const id = this.next++;
|
|
120
|
+
return new Promise((resolve, reject) => {
|
|
121
|
+
// a request with no answer in time ends with a refusal that names the file, and the reading process is started again
|
|
122
|
+
const timer = setTimeout(() => {
|
|
123
|
+
if (!this.pending.delete(id)) return;
|
|
124
|
+
reject(new Refusal('timeout', `the reading process gave no answer in ${Math.round(this.timeoutMs / 1000)} s${args?.name ? ` for ${args.name}` : ''}; it was restarted, so asking again starts afresh`));
|
|
125
|
+
this.dispose();
|
|
126
|
+
}, this.timeoutMs);
|
|
127
|
+
timer.unref?.();
|
|
128
|
+
this.pending.set(id, { resolve: (v) => { clearTimeout(timer); resolve(v); }, reject: (e) => { clearTimeout(timer); reject(e); } });
|
|
129
|
+
this.child.stdin.write(`${JSON.stringify({ id, op, ...args })}\n`);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
dispose() { const c = this.child; this.child = null; c?.kill(); }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export class Engine {
|
|
136
|
+
/** root: the folder holding the projects (Claude Code's <config>/projects). */
|
|
137
|
+
constructor({ root, runtime = process.execPath, env = childEnv(), idleMs = 600_000, timeoutMs = 300_000, log = () => {} }) {
|
|
138
|
+
Object.assign(this, { given: path.resolve(root), runtime, env, log });
|
|
139
|
+
this.root = this.given;
|
|
140
|
+
this.rootState(); // resolved now, so a session asked for before the projects is checked against the real folder
|
|
141
|
+
this.helper = new HelperClient({ runtime, env, idleMs, timeoutMs, log });
|
|
142
|
+
this.indexCache = new Map();
|
|
143
|
+
this.digests = new Map();
|
|
144
|
+
this.walks = new Map();
|
|
145
|
+
this.indexRun = null;
|
|
146
|
+
this.search = null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The root itself may be a symbolic link (a projects folder moved to another disk): it is the user's own setting or
|
|
150
|
+
* Claude Code's configuration, so it is resolved, once it exists. Nothing below it is followed. */
|
|
151
|
+
rootState() {
|
|
152
|
+
if (this.root === this.given) try { const real = realpathSync(this.given); if (kindOf(real) === 'dir') this.root = real; } catch {}
|
|
153
|
+
return kindOf(this.root);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The root as the page shows it: the home folder written as ~, so a picture of the page does not show the user's
|
|
157
|
+
* name in a path. */
|
|
158
|
+
rootShown() { const h = homedir(), g = this.given; return h && (g === h || g.startsWith(`${h}${path.sep}`)) ? `~${g.slice(h.length)}` : g; }
|
|
159
|
+
|
|
160
|
+
/** The project folders under the root, newest file first: each with its count of transcript (.jsonl) files at its top
|
|
161
|
+
* (ltms index says which of them are sessions). A folder that cannot be listed is kept, marked, and the rest go on;
|
|
162
|
+
* symbolic links are counted, not entered. */
|
|
163
|
+
projects() {
|
|
164
|
+
const state = this.rootState();
|
|
165
|
+
if (state !== 'dir') return { root: this.root, rootShown: this.rootShown(), state, projects: [], links: 0 };
|
|
166
|
+
const projects = [];
|
|
167
|
+
let links = 0;
|
|
168
|
+
for (const e of readdirSync(this.root, { withFileTypes: true })) {
|
|
169
|
+
if (e.isSymbolicLink()) { links++; continue; }
|
|
170
|
+
if (!e.isDirectory() || !isName(e.name)) continue;
|
|
171
|
+
let files = 0, newest = 0, newestFile = null;
|
|
172
|
+
try {
|
|
173
|
+
for (const f of readdirSync(path.join(this.root, e.name), { withFileTypes: true })) {
|
|
174
|
+
if (!f.isFile() || !f.name.endsWith('.jsonl')) continue;
|
|
175
|
+
files++;
|
|
176
|
+
try { const m = lstatSync(path.join(this.root, e.name, f.name)).mtimeMs; if (m > newest) { newest = m; newestFile = f.name; } } catch {}
|
|
177
|
+
}
|
|
178
|
+
} catch (err) { projects.push({ name: e.name, files: null, newest: null, unreadable: err?.code ?? 'unreadable' }); continue; }
|
|
179
|
+
projects.push({ name: e.name, files, newest: newest || null, newestFile });
|
|
180
|
+
}
|
|
181
|
+
projects.sort((a, b) => (b.newest ?? 0) - (a.newest ?? 0) || a.name.localeCompare(b.name));
|
|
182
|
+
return { root: this.root, rootShown: this.rootShown(), state, projects, links };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** A path as the page shows it: the home folder written as ~. */
|
|
186
|
+
shown(p) { const h = homedir(); return h && (p === h || p.startsWith(`${h}${path.sep}`)) ? `~${p.slice(h.length)}` : p; }
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Each project's working directory (A.F16: the folder's name is the path with every other character written as -,
|
|
190
|
+
* which cannot be read back): the cwd its newest transcript's first records hold, read from that file's first 64 KB
|
|
191
|
+
* only, without blocking the editor's process; with ~ for home; null when no complete line there says it. The projects
|
|
192
|
+
* as projects() listed them (names, newest files).
|
|
193
|
+
*/
|
|
194
|
+
async projectPaths(list) {
|
|
195
|
+
const out = {};
|
|
196
|
+
for (const p of list) {
|
|
197
|
+
out[p.name] = null;
|
|
198
|
+
if (!p.newestFile) continue;
|
|
199
|
+
let fh;
|
|
200
|
+
try {
|
|
201
|
+
const file = this.sessionFile(p.name, p.newestFile).abs;
|
|
202
|
+
fh = await openFile(file, 'r');
|
|
203
|
+
const buf = Buffer.alloc(64 * 1024), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
|
|
204
|
+
const text = buf.subarray(0, bytesRead).toString('utf8'), lines = text.split('\n');
|
|
205
|
+
if (bytesRead === buf.length) lines.pop(); // the last line may be cut: only whole lines are read
|
|
206
|
+
for (const l of lines) {
|
|
207
|
+
let r; try { r = JSON.parse(l); } catch { continue; }
|
|
208
|
+
if (typeof r?.cwd === 'string' && r.cwd.length > 0 && r.cwd.length <= 4096) { out[p.name] = this.shown(r.cwd); break; }
|
|
209
|
+
}
|
|
210
|
+
} catch {} finally { await fh?.close().catch(() => {}); }
|
|
211
|
+
}
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
projectDir(project) {
|
|
216
|
+
if (!isName(project)) throw new Refusal('bad-name', `${JSON.stringify(project)} is not a project folder's name`);
|
|
217
|
+
const dir = path.join(this.root, project), k = kindOf(dir);
|
|
218
|
+
if (k !== 'dir') throw new Refusal('no-project', k === 'link' ? `${project} is a symbolic link under ${this.root}; it is not entered` : `no project folder ${project} under ${this.root}`);
|
|
219
|
+
return dir;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** A transcript of the project, by its path in it: any regular .jsonl at any depth that ltms's walk reads, every
|
|
223
|
+
* folder on the way a real one (src/layout.mjs). */
|
|
224
|
+
sessionFile(project, file) {
|
|
225
|
+
const dir = this.projectDir(project);
|
|
226
|
+
const r = transcriptAt(dir, file);
|
|
227
|
+
if (r.refused) throw new Refusal(r.refused, r.refused === 'bad-name' ? r.why : `${project}: ${r.why}`);
|
|
228
|
+
return r;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** The sha256 of a transcript (the reading process computes it), kept by device, inode, size and time. */
|
|
232
|
+
async digestOf(project, file) {
|
|
233
|
+
const { abs } = this.sessionFile(project, file);
|
|
234
|
+
let st; try { st = lstatSync(abs); } catch { throw new Refusal('no-session', `${project}: no file ${file}`); }
|
|
235
|
+
const key = `${st.dev}:${st.ino}:${st.size}:${st.mtimeMs}`;
|
|
236
|
+
const hit = this.digests.get(key);
|
|
237
|
+
if (hit) return hit;
|
|
238
|
+
const d = await this.helper.request('digest', { file: abs, dir: path.dirname(abs), name: path.basename(abs) });
|
|
239
|
+
// kept only if the file did not change while it was read
|
|
240
|
+
if (d.size === st.size && d.mtimeMs === st.mtimeMs) this.digests.set(key, d.sha256);
|
|
241
|
+
return d.sha256;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* The transcripts among `files` (paths in one project) that are one transcript: same name and same bytes. Returns a Map
|
|
246
|
+
* from each file with a same-named sibling among `files` to { rep, copies, others }: rep is the copy shown (the fewest
|
|
247
|
+
* folders, then by path: Claude Code's own place first), copies the identical ones besides it, others the files of the
|
|
248
|
+
* same name whose bytes differ (each its own row, naming the rest). A file whose name no other shares is not in the Map,
|
|
249
|
+
* nor one whose name does not stand for one transcript (layout.mjs identifies: a workflow's journal.jsonl is in every run).
|
|
250
|
+
*/
|
|
251
|
+
async groupsOf(project, files) {
|
|
252
|
+
const byName = new Map();
|
|
253
|
+
for (const f of files) { const n = f.slice(f.lastIndexOf('/') + 1); if (!identifies(n)) continue; if (!byName.has(n)) byName.set(n, []); byName.get(n).push(f); }
|
|
254
|
+
const out = new Map();
|
|
255
|
+
for (const same of byName.values()) {
|
|
256
|
+
if (same.length < 2) continue;
|
|
257
|
+
const contents = new Map(); // size, then sha256 when two share a size → files
|
|
258
|
+
const bySize = new Map();
|
|
259
|
+
for (const f of same) {
|
|
260
|
+
let size = null;
|
|
261
|
+
try { size = lstatSync(this.sessionFile(project, f).abs).size; } catch {}
|
|
262
|
+
const k = String(size);
|
|
263
|
+
if (!bySize.has(k)) bySize.set(k, []);
|
|
264
|
+
bySize.get(k).push(f);
|
|
265
|
+
}
|
|
266
|
+
for (const [size, fs] of bySize) {
|
|
267
|
+
if (fs.length === 1 || size === 'null') { for (const f of fs) contents.set(`${size}:${f}`, [f]); continue; }
|
|
268
|
+
for (const f of fs) {
|
|
269
|
+
let sha; try { sha = await this.digestOf(project, f); } catch { sha = `unreadable:${f}`; }
|
|
270
|
+
const k = `${size}:${sha}`;
|
|
271
|
+
if (!contents.has(k)) contents.set(k, []);
|
|
272
|
+
contents.get(k).push(f);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const groups = [...contents.values()].map((g) => g.sort(byPlace));
|
|
276
|
+
const reps = groups.map((g) => g[0]);
|
|
277
|
+
for (const g of groups) {
|
|
278
|
+
const entry = { rep: g[0], copies: g.slice(1), others: reps.filter((r) => r !== g[0]).sort(byPlace) };
|
|
279
|
+
for (const f of g) out.set(f, entry);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return out;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** What is there now under a project's folder, as far as it can change what `ltms index` prints (a list read before is
|
|
286
|
+
* compared with it): a file it reads by its size and time; a file it counts and does not read (in a session's own
|
|
287
|
+
* folder, a set-aside copy) by its presence; a symbolic link, a file whose name is not UTF-8, a folder holding PINS.log
|
|
288
|
+
* by their presence; nothing under such a folder (it is not entered). */
|
|
289
|
+
snapshot(dir) {
|
|
290
|
+
const w = walk(dir), cls = classify(w), sig = new Map();
|
|
291
|
+
for (const f of w.files) { const c = cls.get(f.rel); if (c === 'read') sig.set(f.rel, `${f.size}:${f.mtimeMs}`); else if (c !== 'pinned') sig.set(f.rel, c); }
|
|
292
|
+
for (const r of w.linkRels) sig.set(r, 'link');
|
|
293
|
+
for (const r of w.lossy) sig.set(r, 'lossy');
|
|
294
|
+
for (const r of w.pinStores) sig.set(`${r}/PINS.log`, 'pins');
|
|
295
|
+
return { w, sig, byRel: new Map(w.files.map((f) => [f.rel, f])) };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** A walk of a project, kept for WALK_MS: the several walks one action needs (its copies, an address, a search's
|
|
299
|
+
* folding) share one, in the editor's own process. The list's change test never uses it. */
|
|
300
|
+
walkOf(dir) {
|
|
301
|
+
const hit = this.walks.get(dir);
|
|
302
|
+
if (hit && Date.now() - hit.at < WALK_MS) return hit.w;
|
|
303
|
+
const w = walk(dir);
|
|
304
|
+
this.walks.set(dir, { at: Date.now(), w });
|
|
305
|
+
return w;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* A project's sessions, as `ltms index` lists them, newest first; each line gains `file`, its path in the project, and
|
|
310
|
+
* the lines of identical copies are folded into the one shown (copies, others: groupsOf). The list read last is kept:
|
|
311
|
+
* asked again, it is answered at once when nothing under the folder changed; when something did, it is read again if
|
|
312
|
+
* that run took less than AUTO_MS, else answered at once with what changed (`changed`), for the page to offer a new
|
|
313
|
+
* reading (our own project: 34 s a run, and the session being written changes it every few seconds). fresh: read again.
|
|
314
|
+
*/
|
|
315
|
+
async index(project, { fresh = false } = {}) {
|
|
316
|
+
const dir = this.projectDir(project);
|
|
317
|
+
const now = this.snapshot(dir);
|
|
318
|
+
const kept = this.indexCache.get(dir);
|
|
319
|
+
if (kept && !fresh) {
|
|
320
|
+
const changed = changes(kept.sig, now.sig);
|
|
321
|
+
if (!changed) return kept.value;
|
|
322
|
+
if (kept.value.ms + kept.value.copiesMs >= AUTO_MS) return { ...kept.value, changed: { ...changed, since: kept.value.at } };
|
|
323
|
+
}
|
|
324
|
+
// one run per folder at a time; a run for another folder is stopped (the page shows one project). A run reading this
|
|
325
|
+
// folder already is joined; what changed since it started is said with its list; asked to read again (fresh) after a
|
|
326
|
+
// change it has not seen, a new run replaces it
|
|
327
|
+
const going = this.indexRun?.dir === dir ? this.indexRun : null;
|
|
328
|
+
if (going) {
|
|
329
|
+
const since = changes(going.sig, now.sig);
|
|
330
|
+
if (!since) return going.promise;
|
|
331
|
+
if (!fresh) return going.promise.then((v) => ({ ...v, changed: { ...since, since: v.at } }));
|
|
332
|
+
}
|
|
333
|
+
this.indexRun?.ac.abort();
|
|
334
|
+
const ac = new AbortController(), run = { dir, ac, sig: now.sig, promise: null };
|
|
335
|
+
run.promise = this.indexOnce(project, dir, now, ac.signal).finally(() => { if (this.indexRun === run) this.indexRun = null; });
|
|
336
|
+
this.indexRun = run;
|
|
337
|
+
return run.promise;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
async indexOnce(project, dir, now, signal) {
|
|
341
|
+
const at = Date.now();
|
|
342
|
+
const r = await runLtms(['index', '--max', '0', '--', dir], { runtime: this.runtime, env: this.env, signal });
|
|
343
|
+
const coverage = r.lines.find((l) => l.k === 'coverage') ?? null;
|
|
344
|
+
// a run that ended without its coverage line (killed, out of memory) is a failure, said, and never kept
|
|
345
|
+
if (!coverage || r.signal) throw new Refusal('index-failed', `ltms index ended ${r.signal ? `by signal ${r.signal}` : `with exit ${r.code}`} before its coverage line${r.stderr.trim() ? `: ${this.tidy(r.stderr.trim().split('\n').pop().slice(0, 300))}` : ''}`);
|
|
346
|
+
const lines = [];
|
|
347
|
+
for (const l of r.lines) {
|
|
348
|
+
if (l.k !== 'session') continue;
|
|
349
|
+
const rel = path.relative(dir, String(l.path));
|
|
350
|
+
if (rel.startsWith('..') || path.isAbsolute(rel)) { this.log(`index: a session outside ${dir} was left out`); continue; }
|
|
351
|
+
lines.push({ ...l, file: rel.split(path.sep).join('/') });
|
|
352
|
+
}
|
|
353
|
+
const t0 = Date.now();
|
|
354
|
+
// the groups take in the files of the same names that ltms does not list (in a session's own folder, with no turn):
|
|
355
|
+
// a row names every copy the session view names (B15)
|
|
356
|
+
const listed = new Set(lines.map((l) => l.file)), named = new Set(lines.map((l) => l.file.slice(l.file.lastIndexOf('/') + 1)));
|
|
357
|
+
const extra = now.w.files.map((f) => f.rel).filter((r) => !listed.has(r) && named.has(r.slice(r.lastIndexOf('/') + 1)));
|
|
358
|
+
const groups = await this.groupsOf(project, [...listed, ...extra]);
|
|
359
|
+
const lineOf = new Map(lines.map((l) => [l.file, l]));
|
|
360
|
+
// A1: the bytes are compared after ltms read the files, and a file can change during a run: a copy's line is folded
|
|
361
|
+
// only when ltms printed the same as for the copy shown in every field read from the transcript's bytes (not its
|
|
362
|
+
// path, nor its agents, which ltms counts in each copy's own folder: the session's head links every copy); else it
|
|
363
|
+
// stays, marked
|
|
364
|
+
const sameAs = (a, b) => { const k = ({ path: _p, file: _f, agents: _a, ...rest }) => JSON.stringify(rest); return !!a && !!b && k(a) === k(b); };
|
|
365
|
+
const sessions = [];
|
|
366
|
+
let copies = 0, copyBytes = 0;
|
|
367
|
+
for (const l of lines) {
|
|
368
|
+
const g = groups.get(l.file);
|
|
369
|
+
if (g && g.rep !== l.file && g.copies.includes(l.file)) {
|
|
370
|
+
if (sameAs(lineOf.get(g.rep), l)) { copies++; copyBytes += now.byRel.get(l.file)?.size ?? 0; continue; }
|
|
371
|
+
sessions.push({ ...l, copies: [g.rep, ...g.copies].filter((f) => f !== l.file), others: g.others, copyOf: g.rep, readDiffers: lineOf.has(g.rep) });
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
sessions.push({ ...l, copies: g?.copies ?? [], others: g?.others ?? [] });
|
|
375
|
+
}
|
|
376
|
+
const value = { project, coverage, sessions, copies: { files: copies, bytes: copyBytes }, stderr: this.tidy(r.stderr.trim()), code: r.code, ms: r.ms, copiesMs: Date.now() - t0, at, changed: null };
|
|
377
|
+
this.indexCache.set(dir, { sig: now.sig, value, lines: lineOf });
|
|
378
|
+
return value;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** B3: what ltms index printed for this file in the list read last, if it printed a line for it; else undefined. */
|
|
382
|
+
ltmsLine(project, file) { try { return this.indexCache.get(this.projectDir(project))?.lines?.get(file); } catch { return undefined; } }
|
|
383
|
+
|
|
384
|
+
/** The agent transcripts of a session: every agent-*.jsonl at any depth of its own folder, as ltms index counts them
|
|
385
|
+
* ({ agents: [{ file, name, group, bytes, mtime }], known }). */
|
|
386
|
+
agents(project, file) { this.sessionFile(project, file); return agentsOf(this.projectDir(project), file); }
|
|
387
|
+
|
|
388
|
+
/** For an agent's transcript, the session whose own folder holds it (its path), or null. */
|
|
389
|
+
parent(project, file) { this.sessionFile(project, file); return parentOf(this.projectDir(project), file); }
|
|
390
|
+
|
|
391
|
+
/** The other files of the project with this transcript's name: { copies (identical), others (other bytes) }. */
|
|
392
|
+
async copiesOf(project, file) {
|
|
393
|
+
this.sessionFile(project, file);
|
|
394
|
+
const name = file.slice(file.lastIndexOf('/') + 1);
|
|
395
|
+
const same = this.walkOf(this.projectDir(project)).files.map((f) => f.rel).filter((r) => r.slice(r.lastIndexOf('/') + 1) === name);
|
|
396
|
+
if (!same.includes(file)) same.push(file);
|
|
397
|
+
const g = (await this.groupsOf(project, same)).get(file);
|
|
398
|
+
return g ? { shown: g.rep, copies: [g.rep, ...g.copies].filter((f) => f !== file), others: g.others } : { shown: file, copies: [], others: [] };
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** The transcripts whose address prefix is `prefix` (ltms's prefixOf of the file's name), in one project or in every
|
|
402
|
+
* project (null), at any depth; identical copies come back once (the copy Claude Code keeps first), naming the rest. */
|
|
403
|
+
async resolve(project, prefix, { prefer = null } = {}) {
|
|
404
|
+
if (typeof prefix !== 'string' || !/^(?:agent-[0-9A-Za-z._-]{1,8}|[0-9A-Za-z._-]{1,8})$/.test(prefix)) throw new Refusal('bad-name', `${JSON.stringify(prefix)} is not an address prefix (the first 8 characters of a session's file name, or agent- and the first 8 of an agent's id)`);
|
|
405
|
+
// over every project, the one the page shows is looked in first, and alone when it holds the prefix (A7)
|
|
406
|
+
if (project === null && typeof prefer === 'string') { let here = []; try { here = await this.resolve(prefer, prefix); } catch {} if (here.length) return here; }
|
|
407
|
+
const names = project === null ? this.projects().projects.filter((p) => !p.unreadable).map((p) => p.name) : [project];
|
|
408
|
+
const found = [];
|
|
409
|
+
for (const name of names) {
|
|
410
|
+
let dir; try { dir = this.projectDir(name); } catch { continue; }
|
|
411
|
+
const hits = this.walkOf(dir).files.map((f) => f.rel).filter((r) => prefixOf(r.slice(r.lastIndexOf('/') + 1)) === prefix);
|
|
412
|
+
if (!hits.length) continue;
|
|
413
|
+
const groups = await this.groupsOf(name, hits);
|
|
414
|
+
for (const f of hits.filter((h) => !groups.has(h) || groups.get(h).rep === h).sort(byPlace)) {
|
|
415
|
+
const g = groups.get(f);
|
|
416
|
+
found.push({ project: name, file: f, copies: g?.copies ?? [], others: g?.others ?? [] });
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
return found;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** What a search over one project (or every project, null: the whole folder, as ltms walks it) would read: its
|
|
423
|
+
* transcripts' count and bytes. */
|
|
424
|
+
scope(project) {
|
|
425
|
+
const dir = project === null ? (this.rootState() === 'dir' ? this.root : null) : this.projectDir(project);
|
|
426
|
+
let files = 0, bytes = 0;
|
|
427
|
+
let cut = false;
|
|
428
|
+
if (dir) { const w = this.walkOf(dir); cut = w.cut; for (const f of w.files) { files++; bytes += f.size; } }
|
|
429
|
+
return { files, bytes, cut };
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// the reading process gets the folder the file must be in, and opens the file without following a link
|
|
433
|
+
session(project, file) { const { abs, name } = this.sessionFile(project, file); return this.helper.request('session', { file: abs, dir: path.dirname(abs), name }); }
|
|
434
|
+
turn(project, file, ta) { const { abs, name } = this.sessionFile(project, file); return this.helper.request('turn', { file: abs, dir: path.dirname(abs), name, ta }); }
|
|
435
|
+
record(project, file, line, whole = false) { const { abs, name } = this.sessionFile(project, file); return this.helper.request('record', { file: abs, dir: path.dirname(abs), name, line, whole }); }
|
|
436
|
+
window(project, file, line, field, at) { const { abs, name } = this.sessionFile(project, file); return this.helper.request('window', { file: abs, dir: path.dirname(abs), name, line, field, at }); }
|
|
437
|
+
|
|
438
|
+
/** `ltms search` over one project, or over every project (project null). A new search cancels the one running. */
|
|
439
|
+
async searchFor({ project = null, q, skip = 0, max = 50, substring = false, kinds = null }) {
|
|
440
|
+
if (typeof q !== 'string' || q.trim() === '' || q.length > 2000 || q.includes('\0')) throw new Refusal('bad-query', 'a query is one to 2,000 characters of text');
|
|
441
|
+
if (!Number.isSafeInteger(skip) || skip < 0 || !Number.isSafeInteger(max) || max < 1 || max > 500) throw new Refusal('bad-query', 'skip is 0 or more, and max 1 to 500');
|
|
442
|
+
if (kinds !== null && !(Array.isArray(kinds) && kinds.length && kinds.every((k) => typeof k === 'string' && /^[a-z]+$/.test(k)))) throw new Refusal('bad-query', 'kinds are names of the kinds of text');
|
|
443
|
+
const dir = project === null ? this.root : this.projectDir(project);
|
|
444
|
+
if (project === null && this.rootState() !== 'dir') throw new Refusal('no-root', `no folder at ${this.root}`);
|
|
445
|
+
this.search?.abort();
|
|
446
|
+
const ac = new AbortController();
|
|
447
|
+
this.search = ac;
|
|
448
|
+
const args = ['search', '--max', String(max), '--skip', String(skip), ...(substring ? ['--substring'] : []), ...(kinds ? ['--kind', kinds.join(',')] : []), '--', q, dir];
|
|
449
|
+
const r = await runLtms(args, { runtime: this.runtime, env: this.env, signal: ac.signal });
|
|
450
|
+
if (this.search === ac) this.search = null;
|
|
451
|
+
const files = new Map();
|
|
452
|
+
for (const l of r.lines) {
|
|
453
|
+
if (l.k !== 'file') continue;
|
|
454
|
+
const rel = path.relative(this.root, String(l.path)).split(path.sep);
|
|
455
|
+
if (rel[0] === '..' || path.isAbsolute(rel.join('/')) || rel.length < 2) { this.log(`search: a file outside the root was left out (${l.path})`); continue; }
|
|
456
|
+
files.set(l.f, { f: l.f, p: l.p, last: l.last ?? null, project: rel[0], file: rel.slice(1).join('/'), copies: [], others: [], copyOf: null });
|
|
457
|
+
}
|
|
458
|
+
// identical copies (one name, the same bytes, in one project) hold the same hits. On this page, each group's copies
|
|
459
|
+
// are folded under the first of them present (by place); that one is marked as a copy when the copy shown first is not
|
|
460
|
+
// on this page. A1: a copy is folded only when each of its hits on this page is one the kept copy has here too (the
|
|
461
|
+
// bytes are compared after ltms read them, and a file can change during a run); else it stays, marked.
|
|
462
|
+
const folded = new Set();
|
|
463
|
+
const hitsOf = new Map();
|
|
464
|
+
for (const l of r.lines) if (l.k === 'hit') { if (!hitsOf.has(l.f)) hitsOf.set(l.f, []); hitsOf.get(l.f).push(JSON.stringify({ ta: l.ta, ch: l.ch, at: l.at })); }
|
|
465
|
+
const byProject = new Map();
|
|
466
|
+
for (const f of files.values()) { if (!byProject.has(f.project)) byProject.set(f.project, []); byProject.get(f.project).push(f); }
|
|
467
|
+
for (const [proj, fs] of byProject) {
|
|
468
|
+
let dir; try { dir = this.projectDir(proj); } catch { continue; }
|
|
469
|
+
const want = new Set(fs.map((f) => baseName(f.file))), names = new Map();
|
|
470
|
+
for (const w of this.walkOf(dir).files) { const n = baseName(w.rel); if (want.has(n)) { if (!names.has(n)) names.set(n, []); names.get(n).push(w.rel); } }
|
|
471
|
+
const shared = [...names.values()].filter((v) => v.length > 1).flat();
|
|
472
|
+
if (!shared.length) continue;
|
|
473
|
+
const groups = await this.groupsOf(proj, shared);
|
|
474
|
+
const present = new Map(); // a group's rep → its files on this page, by place
|
|
475
|
+
for (const f of fs) { const g = groups.get(f.file); if (!g) continue; f.others = g.others; if (!present.has(g.rep)) present.set(g.rep, []); present.get(g.rep).push(f); }
|
|
476
|
+
for (const [repName, here] of present) {
|
|
477
|
+
here.sort((a, b) => byPlace(a.file, b.file));
|
|
478
|
+
const keep = here[0], kept = new Set(hitsOf.get(keep.f) ?? []);
|
|
479
|
+
const g = groups.get(keep.file);
|
|
480
|
+
keep.copies = [g.rep, ...g.copies].filter((x) => x !== keep.file);
|
|
481
|
+
if (keep.file !== repName) keep.copyOf = repName;
|
|
482
|
+
for (const f of here.slice(1)) {
|
|
483
|
+
f.copies = [g.rep, ...g.copies].filter((x) => x !== f.file);
|
|
484
|
+
if ((hitsOf.get(f.f) ?? []).every((h) => kept.has(h))) { files.delete(f.f); folded.add(f.f); }
|
|
485
|
+
else { f.copyOf = repName; f.readDiffers = true; }
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
const hitLines = r.lines.filter((l) => l.k === 'hit');
|
|
490
|
+
return {
|
|
491
|
+
q, project, skip, max, substring, kinds,
|
|
492
|
+
coverage: r.lines.find((l) => l.k === 'coverage') ?? null,
|
|
493
|
+
files: [...files.values()],
|
|
494
|
+
hits: hitLines.filter((l) => files.has(l.f)),
|
|
495
|
+
folded: { files: folded.size, turns: hitLines.filter((l) => folded.has(l.f)).length },
|
|
496
|
+
stderr: this.tidy(r.stderr.trim()), code: r.code, ms: r.ms,
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** What ltms printed, with the projects folder written as the page shows it (~ for home). */
|
|
501
|
+
tidy(text) { const shown = this.rootShown(); return [this.root, this.given].reduce((t, p) => (p && p !== shown ? t.split(p).join(shown) : t), text); }
|
|
502
|
+
|
|
503
|
+
cancelSearch() { this.search?.abort(); this.search = null; }
|
|
504
|
+
dispose() { this.cancelSearch(); this.indexRun?.ac.abort(); this.indexRun = null; this.helper.dispose(); }
|
|
505
|
+
}
|
package/src/guard.mjs
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// src/guard.mjs — the reader's screen runs in a child process of the command (src/screen-process.mjs), on the same
|
|
2
|
+
// terminal, and the command waits for it. Every way out the screen knows of (q, Ctrl-C, SIGTERM, SIGHUP, SIGINT, an
|
|
3
|
+
// uncaught error) restores the terminal in that process (src/main.mjs). A way out it cannot know of ends it without the
|
|
4
|
+
// restore: V8's heap running out aborts the process (SIGABRT), and so does any other fatal error; SIGKILL ends it. Then
|
|
5
|
+
// this process writes the leave sequence, and Node puts the terminal's mode back as this process exits, to what it was
|
|
6
|
+
// when this process started (measured, R.F1: in a pseudo-terminal, a child that took raw mode and the alternate screen,
|
|
7
|
+
// then ran out of heap, left stty -g changed when it ran alone, and as it was before when it ran under a parent that
|
|
8
|
+
// wrote the leave sequence and exited; Node's own exit restores the terminal modes of its stdin, stdout and stderr).
|
|
9
|
+
//
|
|
10
|
+
// A signal sent to this process (SIGINT, SIGTERM, SIGHUP) is passed on to the screen's, whose own way out it is; this
|
|
11
|
+
// process then ends with the screen's exit code. What the screen's process writes to stderr is kept (its last 64 KB)
|
|
12
|
+
// and written after it ends: its own error report comes after its own restore, as before, and V8's report of a heap
|
|
13
|
+
// run out comes after this restore, on the main screen, instead of on the alternate screen that the restore takes away.
|
|
14
|
+
// The screen's process uses this process's Node, its flags (process.execArgv) and its environment (NODE_OPTIONS too).
|
|
15
|
+
//
|
|
16
|
+
// An error in this process itself (thrown and not caught, or a promise rejected with nothing to catch it: a module
|
|
17
|
+
// loaded through NODE_OPTIONS or --import that throws, say) ends the screen by its own way out, SIGTERM, on which the
|
|
18
|
+
// screen's process restores the terminal and exits; this process waits for that (STOP_WAIT at most; then SIGKILL, and
|
|
19
|
+
// the leave sequence is written here), writes what the screen's process wrote to stderr, then its own report, after the
|
|
20
|
+
// restore, by the error's kind and place, not its message (src/main.mjs errorReport), and ends with 1. N1 (S377): Node's
|
|
21
|
+
// own report of such an error, its message with it, was written on the alternate screen while the frame was up, and the
|
|
22
|
+
// screen's own report went to a pipe no one read. Everything this process writes to stderr is made visible.
|
|
23
|
+
//
|
|
24
|
+
// Nothing runs in this process when SIGKILL ends it: the screen's process learns of it by an IPC channel this process
|
|
25
|
+
// opens to it, which the kernel closes when this process is gone, and then restores the terminal and ends
|
|
26
|
+
// (src/main.mjs). N5 (S377): it lived on, raw, until the terminal hung up. Measured: the channel's disconnect, and the
|
|
27
|
+
// end of a socketpair on fd 3, each reached a child 3 to 4 ms after its parent's SIGKILL, on Node 26.13.1 and 20.20.2,
|
|
28
|
+
// and neither kept an idle child running once unref'd; the channel needs no flag to say it is there (process.channel).
|
|
29
|
+
import { spawn } from 'node:child_process';
|
|
30
|
+
import { writeSync } from 'node:fs';
|
|
31
|
+
import { constants } from 'node:os';
|
|
32
|
+
import path from 'node:path';
|
|
33
|
+
import { fileURLToPath } from 'node:url';
|
|
34
|
+
import { getHeapStatistics } from 'node:v8';
|
|
35
|
+
import { errorReport } from './main.mjs';
|
|
36
|
+
import { LEAVE } from './screen.mjs';
|
|
37
|
+
import { againOf, parseArgs } from './start.mjs';
|
|
38
|
+
import { visible } from './text.mjs';
|
|
39
|
+
|
|
40
|
+
export const SCREEN_PROCESS = path.join(path.dirname(fileURLToPath(import.meta.url)), 'screen-process.mjs');
|
|
41
|
+
/** The end of the screen process's stderr kept to be written after it ends. */
|
|
42
|
+
const KEEP = 64 * 1024;
|
|
43
|
+
const MB = 1024 * 1024;
|
|
44
|
+
const FORWARDED = ['SIGINT', 'SIGTERM', 'SIGHUP'];
|
|
45
|
+
/** How long the screen's process is given to end by its own way out (SIGTERM) when this process has failed itself. */
|
|
46
|
+
export const STOP_WAIT = 2000;
|
|
47
|
+
|
|
48
|
+
/** What this process says when the screen's process ended by a signal: the signal, the restore, and, when what it wrote
|
|
49
|
+
* says V8's heap ran out, the setting that gives it more (twice this process's heap limit, the same flags as the
|
|
50
|
+
* screen's process had). */
|
|
51
|
+
export function endedBy(signal, said, argv, heapLimit = getHeapStatistics().heap_size_limit) {
|
|
52
|
+
const heap = /heap out of memory/.test(said);
|
|
53
|
+
const more = Math.ceil((2 * heapLimit) / MB / 256) * 256;
|
|
54
|
+
return `ltms-reader: the screen's process ended by ${signal}, without restoring the terminal; this command restored it.${heap ? ` Node's heap ran out, as it says above: to give it more memory, NODE_OPTIONS=--max-old-space-size=${more} ${againOf(parseArgs(argv).path ?? null)}` : ''}\n`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Run the screen (src/main.mjs's main, in src/screen-process.mjs) in a child process on this terminal, with `argv`;
|
|
59
|
+
* resolves to the exit code this command ends with: the screen's own, or 128 + the signal's number when a signal ended
|
|
60
|
+
* it, after the restore; 1 when this process failed itself (its uncaughtException or unhandledRejection, on `proc`).
|
|
61
|
+
* `out` and `err` write to this process's stdout and stderr; `proc` receives the signals passed on and this process's
|
|
62
|
+
* own errors; the rest are parameters so that a test can run it with a screen of its own (onChild: given the child
|
|
63
|
+
* process; stopWait: STOP_WAIT).
|
|
64
|
+
*/
|
|
65
|
+
export function guard(argv, { execPath = process.execPath, execArgv = process.execArgv, env = process.env, proc = process, entry = SCREEN_PROCESS, out = (s) => writeSync(1, s), err = (s) => writeSync(2, s), onChild = null, stopWait = STOP_WAIT } = {}) {
|
|
66
|
+
return new Promise((resolve) => {
|
|
67
|
+
let child;
|
|
68
|
+
try { child = spawn(execPath, [...execArgv, entry, ...argv], { stdio: ['inherit', 'inherit', 'pipe', 'ipc'], env }); }
|
|
69
|
+
catch (e) { try { err(`ltms-reader: the screen's process could not start (${visible(e?.code ?? e?.name ?? 'error')}); nothing was read\n`); } catch {} resolve(1); return; }
|
|
70
|
+
onChild?.(child);
|
|
71
|
+
let said = '';
|
|
72
|
+
child.stderr.setEncoding('utf8');
|
|
73
|
+
child.stderr.on('data', (d) => { said = (said + d).slice(-KEEP); });
|
|
74
|
+
const pass = Object.fromEntries(FORWARDED.map((sig) => [sig, () => { try { child.kill(sig); } catch {} }]));
|
|
75
|
+
for (const sig of FORWARDED) proc.on(sig, pass[sig]);
|
|
76
|
+
// an error of this process's own: the first is kept, and the screen's process is ended by its own way out
|
|
77
|
+
let failed = null, stopping = null;
|
|
78
|
+
const fail = (e) => {
|
|
79
|
+
if (failed) return;
|
|
80
|
+
failed = { e, killed: false };
|
|
81
|
+
try { child.kill('SIGTERM'); } catch {}
|
|
82
|
+
stopping = setTimeout(() => { failed.killed = true; try { child.kill('SIGKILL'); } catch {} }, stopWait);
|
|
83
|
+
};
|
|
84
|
+
proc.on('uncaughtException', fail);
|
|
85
|
+
proc.on('unhandledRejection', fail);
|
|
86
|
+
let started = true;
|
|
87
|
+
child.on('error', (e) => {
|
|
88
|
+
// it could not start (it has no pid): the terminal was never taken; a signal that could not be sent is not that
|
|
89
|
+
if (child.pid !== undefined) return;
|
|
90
|
+
started = false;
|
|
91
|
+
try { err(`ltms-reader: the screen's process could not start (${visible(e?.code ?? e?.name ?? 'error')}); nothing was read\n`); } catch {}
|
|
92
|
+
});
|
|
93
|
+
child.on('close', (code, signal) => {
|
|
94
|
+
clearTimeout(stopping);
|
|
95
|
+
for (const sig of FORWARDED) proc.off(sig, pass[sig]);
|
|
96
|
+
proc.off('uncaughtException', fail);
|
|
97
|
+
proc.off('unhandledRejection', fail);
|
|
98
|
+
const own = () => { if (failed) { try { err(errorReport(failed.e, "the command's process")); } catch {} } };
|
|
99
|
+
if (!started) { own(); resolve(1); return; }
|
|
100
|
+
if (signal) { try { out(LEAVE); } catch {} }
|
|
101
|
+
if (said) { try { err(visible(said)); } catch {} }
|
|
102
|
+
if (failed) {
|
|
103
|
+
if (signal) { try { err(failed.killed && signal === 'SIGKILL' ? `ltms-reader: the screen's process did not end within ${stopWait} ms of SIGTERM; this command ended it (SIGKILL) and restored the terminal.\n` : visible(endedBy(signal, said, argv))); } catch {} }
|
|
104
|
+
own();
|
|
105
|
+
resolve(1);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (signal) {
|
|
109
|
+
try { err(visible(endedBy(signal, said, argv))); } catch {}
|
|
110
|
+
resolve(128 + (constants.signals[signal] ?? 0));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
resolve(code ?? 1);
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
}
|