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/screen.mjs
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// src/screen.mjs — the terminal, with no library: Node's raw mode and keypress events (readline.emitKeypressEvents), the
|
|
2
|
+
// alternate screen, the cursor hidden and wrapping at the last column off, each frame written whole; and the terminal
|
|
3
|
+
// restored on every way out (src/main.mjs calls restore() for q, Ctrl-C, SIGTERM, SIGHUP, SIGINT and an uncaught error,
|
|
4
|
+
// and once more as the process exits). A terminal left raw is the one failure a reader must never have.
|
|
5
|
+
//
|
|
6
|
+
// What it writes is its own escape sequences (ENTER, LEAVE, a cursor position per line and the line erased whole, SGR
|
|
7
|
+
// styles) and the text of the lines, each segment passed through visible() once more on its way out, so that no
|
|
8
|
+
// control character, whatever its source, reaches the terminal as one. Each row is erased before it is written: a
|
|
9
|
+
// terminal that draws a cluster narrower than it is counted here (an emoji and VS16, one column by wcwidth) ends the
|
|
10
|
+
// row early, and nothing of the frame before may stay after it (R.F6). Each row's segments are put in the order the
|
|
11
|
+
// right-to-left mode writes them (text.mjs displayOrder, R1): laid out by the reader, or as stored for a terminal that
|
|
12
|
+
// lays bidirectional text out itself. A row laid out by the reader that holds right-to-left text is written inside a
|
|
13
|
+
// left-to-right override, LRO after its first grapheme cluster that takes a column and PDF at its end (Y1, round 6; Z3,
|
|
14
|
+
// round 7: after a first cluster that takes none, it was at the row's first column), so that a terminal that
|
|
15
|
+
// lays text out itself keeps the reader's order: measured on four terminals (S378, CONTROLS.md), the two take no column
|
|
16
|
+
// in Alacritty 0.17.0, Konsole 26.08.3, tmux 3.6 and VS Code 1.146.0's terminal (xterm.js) there, and Konsole applies an
|
|
17
|
+
// override from a row's second column on; at its first column an LRO is not applied by Konsole, dropped by tmux and
|
|
18
|
+
// given a column by xterm.js, which gives an isolate (LRI, RLI, PDI) a column anywhere; so nothing else is written.
|
|
19
|
+
import readline from 'node:readline';
|
|
20
|
+
import { AL, AN, R, classOf } from './bidi.mjs';
|
|
21
|
+
import { clusterWidth, clusters, displayOrder, visible } from './text.mjs';
|
|
22
|
+
|
|
23
|
+
/** The alternate screen, the cursor hidden, no wrapping at the last column (so a cluster a terminal draws wider than it
|
|
24
|
+
* is counted here cannot scroll the screen), and bracketed paste: the terminal marks a paste, so that its text is
|
|
25
|
+
* read as text, never as keys (R.F8). */
|
|
26
|
+
export const ENTER = '\x1b[?1049h\x1b[?25l\x1b[?7l\x1b[?2004h';
|
|
27
|
+
/** Back: bracketed paste off, styles reset, wrapping on, the cursor shown, the main screen. */
|
|
28
|
+
export const LEAVE = '\x1b[?2004l\x1b[0m\x1b[?7h\x1b[?25h\x1b[?1049l';
|
|
29
|
+
const SGR = Object.freeze({ head: '1', dim: '2', sel: '7', bad: '31', addr: '36' });
|
|
30
|
+
/** The styles that are colours, left out under NO_COLOR; bold, faint and reverse are not colours. */
|
|
31
|
+
const COLOURS = new Set(['bad', 'addr']);
|
|
32
|
+
|
|
33
|
+
/** Colour unless NO_COLOR is set to anything but the empty string (no-color.org). */
|
|
34
|
+
export const colourFrom = (env) => !(typeof env.NO_COLOR === 'string' && env.NO_COLOR !== '');
|
|
35
|
+
|
|
36
|
+
/** One segment's text as it is written: visible, on one line. */
|
|
37
|
+
const safe = (s) => visible(s).replace(/\n/g, '\\n').replace(/\t/g, '\\t');
|
|
38
|
+
|
|
39
|
+
/** The left-to-right override (U+202D) and the pop that ends it (U+202C), written around a row laid out by the reader
|
|
40
|
+
* that holds right-to-left text (Y1): the only bidirectional controls the reader writes (a transcript's are escapes). */
|
|
41
|
+
export const LRO = '\u202d', PDF = '\u202c';
|
|
42
|
+
/** A text with no character that could be right to left (every R, AL and AN code point is at U+0590 or above). */
|
|
43
|
+
const NO_RTL = /^[\u0000-\u058f]*$/;
|
|
44
|
+
/** Whether a row's text holds a character a terminal that lays text out itself would lay out right to left or reorder
|
|
45
|
+
* around: one of class R, AL or AN (an Arabic number among neutrals is reordered too, and the reader has laid it out). */
|
|
46
|
+
export function holdsRtl(text) {
|
|
47
|
+
if (NO_RTL.test(text)) return false;
|
|
48
|
+
for (const ch of text) { const c = classOf(ch.codePointAt(0)); if (c === R || c === AL || c === AN) return true; }
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Where the first grapheme cluster of `text` that takes a column ends (Z3, round 7: after a first cluster that takes
|
|
53
|
+
* none, ZWSP or a lone mark, the LRO was in the row's first column), or -1 when none takes a column. */
|
|
54
|
+
function firstColumnEnd(text) {
|
|
55
|
+
let at = 0;
|
|
56
|
+
for (const c of clusters(text)) { at += c.length; if (clusterWidth(c) > 0) return at; }
|
|
57
|
+
return -1;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The bytes of one whole frame: each line at its row, the row erased whole first, then the line, styled; its segments in
|
|
61
|
+
* the order the right-to-left mode `rtl` writes them ("reader" or "terminal"); in "reader", a row that holds
|
|
62
|
+
* right-to-left text inside LRO (after its first grapheme cluster that takes a column) and PDF (last). */
|
|
63
|
+
export function frameBytes(lines, { cols, rows, colour = true, rtl = 'reader' }) {
|
|
64
|
+
let out = '';
|
|
65
|
+
for (let i = 0; i < rows; i++) {
|
|
66
|
+
const row = displayOrder(lines[i] ?? [], rtl);
|
|
67
|
+
out += `\x1b[${i + 1};1H\x1b[2K`;
|
|
68
|
+
// segments of one style next to each other are written as one
|
|
69
|
+
const merged = [];
|
|
70
|
+
for (const s of row) { const last = merged[merged.length - 1]; if (last && (last.style ?? null) === (s.style ?? null)) last.text += s.text; else merged.push({ text: s.text, style: s.style ?? null }); }
|
|
71
|
+
const texts = merged.map((s) => safe(s.text));
|
|
72
|
+
// laid out by the reader and holding right-to-left text: LRO right after the row's first grapheme cluster that takes
|
|
73
|
+
// a column (where it ends, in whichever segment that is, a mark on its character kept with it; never in the row's
|
|
74
|
+
// first column, where the terminals measured drop it, give it a column or do not apply it: Z3, round 7), PDF last; a
|
|
75
|
+
// row with no cluster that takes a column has nothing a terminal could reorder, and neither
|
|
76
|
+
let end = '';
|
|
77
|
+
if (rtl === 'reader') {
|
|
78
|
+
const whole = texts.join('');
|
|
79
|
+
const first = holdsRtl(whole) ? firstColumnEnd(whole) : -1;
|
|
80
|
+
if (first > 0) {
|
|
81
|
+
for (let k = 0, at = 0; k < texts.length; at += texts[k++].length) {
|
|
82
|
+
if (at < first && first <= at + texts[k].length) { texts[k] = texts[k].slice(0, first - at) + LRO + texts[k].slice(first - at); break; }
|
|
83
|
+
}
|
|
84
|
+
end = PDF;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
merged.forEach((s, k) => {
|
|
88
|
+
const code = s.style && (colour || !COLOURS.has(s.style)) ? SGR[s.style] : undefined;
|
|
89
|
+
out += code ? `\x1b[${code}m${texts[k]}\x1b[0m` : texts[k];
|
|
90
|
+
});
|
|
91
|
+
out += end;
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Take the terminal: raw mode, keypress events on `input`, the alternate screen. onKey(str, key) for each key;
|
|
98
|
+
* onResize() when the window's size changes; `rtl` the right-to-left mode. Returns { draw(lines, cols, rows), restore(),
|
|
99
|
+
* size() }; restore() may be called any number of times, and from any way out; restore({ modes: false }) writes the
|
|
100
|
+
* leave sequence and leaves the terminal's modes as they are (another process has set them since: R3).
|
|
101
|
+
*/
|
|
102
|
+
export function openScreen({ input, output, colour = true, rtl = 'reader', onKey, onResize }) {
|
|
103
|
+
let open = true, dead = false;
|
|
104
|
+
const write = (s) => { if (dead) return; try { output.write(s); } catch { dead = true; } };
|
|
105
|
+
const onError = () => { dead = true; };
|
|
106
|
+
output.on('error', onError);
|
|
107
|
+
readline.emitKeypressEvents(input, { escapeCodeTimeout: 50 });
|
|
108
|
+
input.setRawMode(true);
|
|
109
|
+
input.on('keypress', onKey);
|
|
110
|
+
output.on('resize', onResize);
|
|
111
|
+
input.resume();
|
|
112
|
+
write(ENTER);
|
|
113
|
+
return {
|
|
114
|
+
get open() { return open; },
|
|
115
|
+
size: () => ({ cols: output.columns || 80, rows: output.rows || 24 }),
|
|
116
|
+
draw(lines, cols, rows) { if (open) write(frameBytes(lines, { cols, rows, colour, rtl })); },
|
|
117
|
+
restore({ modes = true } = {}) {
|
|
118
|
+
if (!open) return;
|
|
119
|
+
open = false;
|
|
120
|
+
input.off('keypress', onKey);
|
|
121
|
+
output.off('resize', onResize);
|
|
122
|
+
write(LEAVE);
|
|
123
|
+
if (modes) { try { input.setRawMode(false); } catch {} }
|
|
124
|
+
try { input.pause(); } catch {}
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
package/src/sources.mjs
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// src/sources.mjs — where the reader's rows come from: a folder of project folders (the engine: the projects by ltms's
|
|
2
|
+
// walk, a project's sessions by `ltms index`, search by `ltms search`, an address's transcript by its prefix), or one
|
|
3
|
+
// transcript. Either way a session is read in this process (src/reading.mjs), and the error class of each failed call
|
|
4
|
+
// comes from `ltms skeleton`, so the lines the screen draws are the lines an agent reads from the same commands.
|
|
5
|
+
import { lstatSync } from 'node:fs';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { Engine, childEnv, runLtms } from './engine.mjs';
|
|
9
|
+
import { classify, walk } from './layout.mjs';
|
|
10
|
+
import { readTranscript } from './reading.mjs';
|
|
11
|
+
import { prefixOf } from './view.mjs';
|
|
12
|
+
|
|
13
|
+
/** The failed calls' error classes, as `ltms skeleton` prints them for the transcript at `abs`: a Map from each call of
|
|
14
|
+
* `view` (its item) to its `ek`. Calls are matched by turn, address, result's address, ok and result length (two calls
|
|
15
|
+
* of one record share an address), in the order both give them. */
|
|
16
|
+
export async function errorClasses(abs, view, run = runLtms) {
|
|
17
|
+
const r = await run(['skeleton', '--', abs]);
|
|
18
|
+
const lists = new Map();
|
|
19
|
+
const key = (ta, a, rr, ok, n) => JSON.stringify([ta, a, rr, ok, n]);
|
|
20
|
+
for (const l of r.lines) {
|
|
21
|
+
if (l.k !== 'call') continue;
|
|
22
|
+
const k = key(l.ta, l.a, l.r, l.ok, l.n);
|
|
23
|
+
if (!lists.has(k)) lists.set(k, []);
|
|
24
|
+
lists.get(k).push(l.ek ?? null);
|
|
25
|
+
}
|
|
26
|
+
const out = new Map();
|
|
27
|
+
for (const t of view.turns) for (const x of t.items) {
|
|
28
|
+
if (x.kind !== 'call') continue;
|
|
29
|
+
const list = lists.get(key(t.ta, x.a, x.r, x.ok, x.n));
|
|
30
|
+
if (list?.length) out.set(x, list.shift());
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Whether the transcript read as `doc` is still the file at its path, unchanged (its size and time). */
|
|
36
|
+
export function unchanged(doc) {
|
|
37
|
+
try { const st = lstatSync(doc.abs); return st.isFile() && st.size === doc.size && st.mtimeMs === doc.mtimeMs; } catch { return false; }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A path with the home folder written as ~. */
|
|
41
|
+
export function shownPath(p) { const h = homedir(); return h && (p === h || p.startsWith(`${h}${path.sep}`)) ? `~${p.slice(h.length)}` : p; }
|
|
42
|
+
|
|
43
|
+
/** The projects folder given (or Claude Code's), read through the engine. `only`: the one project shown, when the
|
|
44
|
+
* folder given was a project's own. `again`: the command that was run (src/start.mjs's againOf), which a refusal of a
|
|
45
|
+
* transcript too large names; `heapLimit`: the limit its size rule reads by (the runtime's when not given). */
|
|
46
|
+
export class RootSource {
|
|
47
|
+
constructor({ root, only = null, env = childEnv(process.env), engine = null, again = undefined, heapLimit = undefined }) {
|
|
48
|
+
this.kind = 'root';
|
|
49
|
+
this.engine = engine ?? new Engine({ root, env });
|
|
50
|
+
this.only = only;
|
|
51
|
+
this.env = env;
|
|
52
|
+
this.reading = { again, heapLimit };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
get rootShown() { return this.engine.rootShown(); }
|
|
56
|
+
|
|
57
|
+
/** The project folders, newest first, each with the count of the transcripts `ltms index` would read in it (ltms's
|
|
58
|
+
* walk: any depth, but a session's own folder, the set-aside copies and a pin store). */
|
|
59
|
+
projects() {
|
|
60
|
+
const p = this.engine.projects();
|
|
61
|
+
const list = p.projects.filter((x) => this.only === null || x.name === this.only).map((x) => {
|
|
62
|
+
if (x.unreadable) return { name: x.name, transcripts: null, newest: null, unreadable: x.unreadable };
|
|
63
|
+
let transcripts = null, cut = false;
|
|
64
|
+
try {
|
|
65
|
+
const w = walk(path.join(p.root, x.name)), cls = classify(w);
|
|
66
|
+
transcripts = [...cls.values()].filter((c) => c === 'read').length;
|
|
67
|
+
cut = w.cut;
|
|
68
|
+
} catch {}
|
|
69
|
+
return { name: x.name, transcripts, cut, newest: x.newest };
|
|
70
|
+
});
|
|
71
|
+
return { rootShown: p.rootShown, state: p.state, projects: list, links: p.links };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A project's sessions, as `ltms index` lists them, newest first; `fresh`: read again, not answered from the list kept
|
|
75
|
+
* (r, Y2). */
|
|
76
|
+
sessions(project, { fresh = false } = {}) { return this.engine.index(project, { fresh }); }
|
|
77
|
+
|
|
78
|
+
/** One transcript of a project, read here. */
|
|
79
|
+
open(project, file) { return { project, file, ...readTranscript(this.engine.sessionFile(project, file).abs, this.reading) }; }
|
|
80
|
+
|
|
81
|
+
unchanged(doc) { return unchanged(doc); }
|
|
82
|
+
|
|
83
|
+
errorClasses(doc) { return errorClasses(doc.abs, doc.view, (args) => runLtms(args, { env: this.env })); }
|
|
84
|
+
|
|
85
|
+
/** `ltms search` over one project, or every project (null). */
|
|
86
|
+
search({ project, q, skip = 0, max = 100 }) { return this.engine.searchFor({ project, q, skip, max }); }
|
|
87
|
+
|
|
88
|
+
/** The transcripts whose address prefix is `prefix`, the project `prefer` first: [{ project, file }]. */
|
|
89
|
+
resolve(prefix, { prefer = null } = {}) {
|
|
90
|
+
return this.engine.resolve(null, prefix, { prefer }).then((found) => found.filter((f) => this.only === null || f.project === this.only));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A path as the screen shows it: the home folder as ~. */
|
|
94
|
+
shown(p) { return this.engine.shown(p); }
|
|
95
|
+
|
|
96
|
+
dispose() { this.engine.dispose(); }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** One transcript, given by its path; `again` and `heapLimit` as RootSource's. */
|
|
100
|
+
export class FileSource {
|
|
101
|
+
constructor({ file, env = childEnv(process.env), again = undefined, heapLimit = undefined }) {
|
|
102
|
+
this.kind = 'file';
|
|
103
|
+
this.file = file;
|
|
104
|
+
this.name = path.basename(file);
|
|
105
|
+
this.prefix = prefixOf(this.name);
|
|
106
|
+
this.env = env;
|
|
107
|
+
this.running = null;
|
|
108
|
+
this.reading = { again, heapLimit };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
open() { return { project: null, file: this.name, ...readTranscript(this.file, this.reading) }; }
|
|
112
|
+
|
|
113
|
+
unchanged(doc) { return unchanged(doc); }
|
|
114
|
+
|
|
115
|
+
errorClasses(doc) { return errorClasses(doc.abs, doc.view, (args) => runLtms(args, { env: this.env })); }
|
|
116
|
+
|
|
117
|
+
/** `ltms search` over this one file, shaped as the engine shapes a search over a folder. */
|
|
118
|
+
async search({ q, skip = 0, max = 100 }) {
|
|
119
|
+
this.running?.abort();
|
|
120
|
+
const ac = new AbortController();
|
|
121
|
+
this.running = ac;
|
|
122
|
+
const r = await runLtms(['search', '--no-cache', '--max', String(max), '--skip', String(skip), '--', q, this.file], { env: this.env, signal: ac.signal });
|
|
123
|
+
if (this.running === ac) this.running = null;
|
|
124
|
+
const files = r.lines.filter((l) => l.k === 'file').map((l) => ({ f: l.f, p: l.p, last: l.last ?? null, project: null, file: this.name, copies: [], others: [], copyOf: null }));
|
|
125
|
+
return { q, project: null, skip, max, coverage: r.lines.find((l) => l.k === 'coverage') ?? null, files, hits: r.lines.filter((l) => l.k === 'hit'), folded: { files: 0, turns: 0 }, stderr: r.stderr.trim(), code: r.code, ms: r.ms };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** This file, when `prefix` is its address prefix. */
|
|
129
|
+
async resolve(prefix) { return prefix === this.prefix ? [{ project: null, file: this.name }] : []; }
|
|
130
|
+
|
|
131
|
+
shown(p) { return shownPath(p); }
|
|
132
|
+
|
|
133
|
+
dispose() { this.running?.abort(); }
|
|
134
|
+
}
|
package/src/start.mjs
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// src/start.mjs — what the reader opens, from its command line, and what it refuses before it reads anything.
|
|
2
|
+
//
|
|
3
|
+
// ltms-reader the projects under ~/.claude/projects (or $CLAUDE_CONFIG_DIR/projects)
|
|
4
|
+
// ltms-reader <projects folder> another folder of project folders
|
|
5
|
+
// ltms-reader <file.jsonl> one transcript
|
|
6
|
+
//
|
|
7
|
+
// It shows transcripts on a terminal's screen and nowhere else, so it is refused at once when stdin or stdout is not a
|
|
8
|
+
// terminal: ltms is the command for lines (to read, or to pipe). A folder whose top holds transcripts and whose folders
|
|
9
|
+
// hold none at theirs is one project's own folder (given where its parent was meant): it is opened as that project.
|
|
10
|
+
import { lstatSync, readdirSync, realpathSync, statSync } from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
|
|
13
|
+
export const USAGE = `usage: ltms-reader the projects under ~/.claude/projects (or $CLAUDE_CONFIG_DIR/projects)
|
|
14
|
+
ltms-reader <projects folder> another folder of project folders
|
|
15
|
+
ltms-reader <file.jsonl> one transcript
|
|
16
|
+
|
|
17
|
+
A full-screen reader of your Claude Code sessions, on this terminal's alternate screen: the projects, a project's
|
|
18
|
+
sessions, a session's turns, a turn's tool calls, a record's text. Read-only, local, no network.
|
|
19
|
+
Keys: arrows, PgUp PgDn, Home End move; Enter opens; Esc goes back; / searches; : opens an address; r reads a list
|
|
20
|
+
again (Projects, a project's Sessions); ? the keys; q quits.
|
|
21
|
+
For lines to read or to pipe, ltms is the command (npx long-term-memory-structure).
|
|
22
|
+
|
|
23
|
+
Right to left (Hebrew, Arabic): in every terminal the reader lays out each line itself, by the Unicode Bidirectional
|
|
24
|
+
Algorithm, and writes a line that holds right-to-left text inside a left-to-right override (U+202D after its first
|
|
25
|
+
character that takes a column, U+202C at its end), so that a terminal that lays text out itself keeps that order.
|
|
26
|
+
Measured on four terminals: Alacritty, Konsole, tmux and VS Code's terminal; no other was. To choose:
|
|
27
|
+
LTMS_READER_BIDI=reader the reader lays it out (the default)
|
|
28
|
+
LTMS_READER_BIDI=terminal as stored, with no override (for a terminal that lays text out itself)
|
|
29
|
+
`;
|
|
30
|
+
|
|
31
|
+
/** The arguments: { help } | { version } | { path } (null for none) | { usage: what is wrong }. */
|
|
32
|
+
export function parseArgs(argv) {
|
|
33
|
+
const rest = [];
|
|
34
|
+
let ended = false;
|
|
35
|
+
for (const a of argv) {
|
|
36
|
+
if (!ended && a === '--') { ended = true; continue; }
|
|
37
|
+
if (!ended && (a === '--help' || a === '-h')) return { help: true };
|
|
38
|
+
if (!ended && (a === '--version' || a === '-v')) return { version: true };
|
|
39
|
+
if (!ended && a.startsWith('-') && a !== '-') return { usage: `no option ${JSON.stringify(a)}` };
|
|
40
|
+
rest.push(a);
|
|
41
|
+
}
|
|
42
|
+
if (rest.length > 1) return { usage: `one folder or one file, not ${rest.length} arguments` };
|
|
43
|
+
return { path: rest[0] ?? null };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** One word for a POSIX shell: as it is when it holds nothing a shell reads specially, else in single quotes. */
|
|
47
|
+
const shellWord = (s) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
|
|
48
|
+
|
|
49
|
+
/** The command that runs the reader again on what it was given (`arg`, as typed; null for none), for a message that
|
|
50
|
+
* tells the person how to read something with more memory: without the path, it would open another folder. */
|
|
51
|
+
export function againOf(arg) {
|
|
52
|
+
if (arg === null || arg === undefined) return 'npx ltms-reader';
|
|
53
|
+
return `npx ltms-reader ${arg.startsWith('-') ? '-- ' : ''}${shellWord(arg)}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Why the reader does not run on these streams, or null when stdin and stdout are both terminals. */
|
|
57
|
+
export function notTerminal(stdin, stdout) {
|
|
58
|
+
const inTty = stdin?.isTTY === true, outTty = stdout?.isTTY === true;
|
|
59
|
+
if (inTty && outTty) return null;
|
|
60
|
+
const which = !inTty && !outTty ? 'stdin and stdout are not terminals' : !outTty ? 'stdout is not a terminal' : 'stdin is not a terminal';
|
|
61
|
+
// the commands are written as npx runs them, so that they run as they are written: installing ltms-reader does not put
|
|
62
|
+
// ltms on the PATH (R.F13)
|
|
63
|
+
return `ltms-reader: ${which}, so nothing was read.
|
|
64
|
+
ltms-reader shows transcripts on a terminal's screen only: none of their text goes to a pipe, a file or a log.
|
|
65
|
+
For lines to read or to pipe, ltms is the command, from the package ltms-reader is built on.
|
|
66
|
+
npm install -g long-term-memory-structure puts ltms on the PATH; npx runs it without that:
|
|
67
|
+
npx long-term-memory-structure index <projects folder>/<project> the sessions, newest first
|
|
68
|
+
npx long-term-memory-structure search '<words>' <folder> the turns that hold the words, by address
|
|
69
|
+
npx long-term-memory-structure skeleton <file.jsonl> a session's turns and tool calls, with addresses
|
|
70
|
+
`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const isJsonl = (name) => name.endsWith('.jsonl');
|
|
74
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
75
|
+
|
|
76
|
+
/** Whether a folder is one project's own: transcripts at its top, and none at the top of any folder in it that is not
|
|
77
|
+
* a session's own (named by a UUID, or as a transcript beside it). */
|
|
78
|
+
function isProjectFolder(dir) {
|
|
79
|
+
let entries;
|
|
80
|
+
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return false; }
|
|
81
|
+
const files = new Set(entries.filter((e) => e.isFile() && isJsonl(e.name)).map((e) => e.name));
|
|
82
|
+
if (!files.size) return false;
|
|
83
|
+
for (const e of entries) {
|
|
84
|
+
if (!e.isDirectory() || UUID.test(e.name) || files.has(`${e.name}.jsonl`)) continue;
|
|
85
|
+
try { if (readdirSync(path.join(dir, e.name), { withFileTypes: true }).some((f) => f.isFile() && isJsonl(f.name))) return false; } catch {}
|
|
86
|
+
}
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* What to open: { kind: 'root', root, from } (a folder of project folders; from: 'argument', 'CLAUDE_CONFIG_DIR' or
|
|
92
|
+
* 'default'), { kind: 'root', root, project } (one project's own folder, under root), { kind: 'file', file } (one
|
|
93
|
+
* transcript, its real path), or { refused: why }.
|
|
94
|
+
*/
|
|
95
|
+
export function startOf(arg, { env = process.env, home }) {
|
|
96
|
+
if (arg === null) {
|
|
97
|
+
const conf = typeof env.CLAUDE_CONFIG_DIR === 'string' && env.CLAUDE_CONFIG_DIR !== '' ? env.CLAUDE_CONFIG_DIR : null;
|
|
98
|
+
const root = conf ? path.resolve(conf, 'projects') : path.join(home, '.claude', 'projects');
|
|
99
|
+
let st = null;
|
|
100
|
+
try { st = statSync(root); } catch {}
|
|
101
|
+
if (!st?.isDirectory()) return { refused: `no folder at ${root}: ${conf ? 'CLAUDE_CONFIG_DIR names' : 'Claude Code keeps'} its projects there${conf ? '' : ' (CLAUDE_CONFIG_DIR moves them)'}. Give a folder of project folders, or one transcript (a .jsonl file).` };
|
|
102
|
+
return { kind: 'root', root, from: conf ? 'CLAUDE_CONFIG_DIR' : 'default' };
|
|
103
|
+
}
|
|
104
|
+
const abs = path.resolve(arg);
|
|
105
|
+
let st;
|
|
106
|
+
try { st = statSync(abs); } catch (e) {
|
|
107
|
+
let link = false;
|
|
108
|
+
try { link = lstatSync(abs).isSymbolicLink(); } catch {}
|
|
109
|
+
return { refused: link ? `${arg} is a symbolic link to nothing` : `no file or folder at ${arg}` };
|
|
110
|
+
}
|
|
111
|
+
if (st.isDirectory()) {
|
|
112
|
+
if (isProjectFolder(abs)) {
|
|
113
|
+
const real = realpathSync(abs);
|
|
114
|
+
return { kind: 'root', root: path.dirname(real), project: path.basename(real), from: 'argument' };
|
|
115
|
+
}
|
|
116
|
+
return { kind: 'root', root: abs, from: 'argument' };
|
|
117
|
+
}
|
|
118
|
+
if (st.isFile()) {
|
|
119
|
+
if (!isJsonl(abs)) return { refused: `${arg} is not a transcript: a transcript is a .jsonl file` };
|
|
120
|
+
return { kind: 'file', file: realpathSync(abs) };
|
|
121
|
+
}
|
|
122
|
+
return { refused: `${arg} is neither a folder nor a regular file` };
|
|
123
|
+
}
|