@hype/clod 1.3.1 → 1.4.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/README.md +27 -11
- package/dist/git.js +170 -0
- package/dist/harnesses/claude.js +445 -0
- package/dist/harnesses/index.js +27 -0
- package/dist/harnesses/omp.js +477 -0
- package/dist/index.js +7 -3
- package/dist/list.js +37 -17
- package/dist/proc.js +51 -0
- package/dist/sessions.js +5 -352
- package/dist/ui.js +91 -39
- package/package.json +8 -6
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
import { open, readdir, readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { basename, dirname, join } from 'node:path';
|
|
4
|
+
import { reflogBranches } from '../git.js';
|
|
5
|
+
import { ompLeases, terminalProcesses } from '../proc.js';
|
|
6
|
+
import { modelKey, throughputOf } from '../sessions.js';
|
|
7
|
+
import { trashPaths } from '../trash.js';
|
|
8
|
+
// omp honors PI_CODING_AGENT_DIR for its whole agent tree, sessions and
|
|
9
|
+
// history.db included.
|
|
10
|
+
export const agentDir = () => process.env.PI_CODING_AGENT_DIR || join(homedir(), '.omp', 'agent');
|
|
11
|
+
const sessionsDir = () => join(agentDir(), 'sessions');
|
|
12
|
+
const text = (content) => typeof content === 'string'
|
|
13
|
+
? content
|
|
14
|
+
: Array.isArray(content)
|
|
15
|
+
? content
|
|
16
|
+
.filter((b) => b.type === 'text')
|
|
17
|
+
.map((b) => b.text ?? '')
|
|
18
|
+
.join('')
|
|
19
|
+
: '';
|
|
20
|
+
// omp's resolveSessionLeafId: the last entry's captured leaf, falling back to the
|
|
21
|
+
// newest entry that selects itself when that leaf no longer exists.
|
|
22
|
+
export function activeBranch(nodes) {
|
|
23
|
+
const byId = new Map(nodes.map((n) => [n.id, n]));
|
|
24
|
+
const last = nodes.at(-1);
|
|
25
|
+
let leaf = last ? last.leafId : null;
|
|
26
|
+
if (leaf !== null && !byId.has(leaf)) {
|
|
27
|
+
leaf = null;
|
|
28
|
+
for (let i = nodes.length - 1; i >= 0; i--) {
|
|
29
|
+
if (nodes[i].leafId === nodes[i].id) {
|
|
30
|
+
leaf = nodes[i].id;
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const branch = new Set();
|
|
36
|
+
for (let n = leaf ? byId.get(leaf) : undefined; n && !branch.has(n.id);) {
|
|
37
|
+
branch.add(n.id);
|
|
38
|
+
n = n.parentId ? byId.get(n.parentId) : undefined;
|
|
39
|
+
}
|
|
40
|
+
return branch;
|
|
41
|
+
}
|
|
42
|
+
function addUsage(acc, model, u) {
|
|
43
|
+
const key = modelKey(model) ?? model ?? 'unknown';
|
|
44
|
+
acc[key] ??= { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
45
|
+
acc[key].input += u.input || 0;
|
|
46
|
+
acc[key].output += u.output || 0;
|
|
47
|
+
acc[key].cacheRead += u.cacheRead || 0;
|
|
48
|
+
acc[key].cacheWrite += u.cacheWrite || 0;
|
|
49
|
+
}
|
|
50
|
+
// omp's generated titles lead with a Nerd Font icon from the Private Use Areas.
|
|
51
|
+
// clod drops it: it sorts ahead of every letter and reads as noise in a list.
|
|
52
|
+
export const stripIcon = (title) => title.replace(/^[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]+\s*/u, '');
|
|
53
|
+
// Everything clod shows from one transcript. Tool results are most of the bytes
|
|
54
|
+
// and carry nothing clod shows, so they only get their tree links read.
|
|
55
|
+
async function readTranscript(filePath) {
|
|
56
|
+
const raw = await readFile(filePath, 'utf8');
|
|
57
|
+
const lines = raw.split('\n');
|
|
58
|
+
let title = null;
|
|
59
|
+
let aiTitle = null;
|
|
60
|
+
let header = null;
|
|
61
|
+
let lastTimestamp = null;
|
|
62
|
+
let importedFrom = null;
|
|
63
|
+
const nodes = [];
|
|
64
|
+
const turns = [];
|
|
65
|
+
const models = {};
|
|
66
|
+
let lastLine = lines.length - 1;
|
|
67
|
+
while (lastLine > 0 && !lines[lastLine])
|
|
68
|
+
lastLine--;
|
|
69
|
+
for (let i = 0; i < lines.length; i++) {
|
|
70
|
+
const line = lines[i];
|
|
71
|
+
if (!line)
|
|
72
|
+
continue;
|
|
73
|
+
const head = line.slice(0, 400);
|
|
74
|
+
// the last entry is parsed whole, since it may carry the active leaf
|
|
75
|
+
if (i !== lastLine && head.includes('"role":"toolResult"')) {
|
|
76
|
+
const id = /"id":"([^"]+)"/.exec(head)?.[1];
|
|
77
|
+
if (id) {
|
|
78
|
+
const parentId = /"parentId":"([^"]+)"/.exec(head)?.[1] ?? null;
|
|
79
|
+
nodes.push({ id, parentId, leafId: id });
|
|
80
|
+
lastTimestamp = /"timestamp":"([^"]+)"/.exec(head)?.[1] ?? lastTimestamp;
|
|
81
|
+
}
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
let r;
|
|
85
|
+
try {
|
|
86
|
+
r = JSON.parse(line);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (i === 0 && r.type === 'title') {
|
|
92
|
+
// source "user" is a rename, "auto" (or none, from older omp) is generated
|
|
93
|
+
const shown = r.title ? stripIcon(r.title) : '';
|
|
94
|
+
if (shown) {
|
|
95
|
+
if (r.source === 'user')
|
|
96
|
+
title = shown;
|
|
97
|
+
else
|
|
98
|
+
aiTitle = shown;
|
|
99
|
+
}
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (r.type === 'session') {
|
|
103
|
+
header ??= r;
|
|
104
|
+
const shown = r.title ? stripIcon(r.title) : '';
|
|
105
|
+
if (shown && !title && !aiTitle) {
|
|
106
|
+
if (r.titleSource === 'user')
|
|
107
|
+
title = shown;
|
|
108
|
+
else
|
|
109
|
+
aiTitle = shown;
|
|
110
|
+
}
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (r.timestamp)
|
|
114
|
+
lastTimestamp = r.timestamp;
|
|
115
|
+
if (r.id) {
|
|
116
|
+
nodes.push({
|
|
117
|
+
id: r.id,
|
|
118
|
+
parentId: r.parentId ?? null,
|
|
119
|
+
leafId: r.activeLeafId !== undefined ? r.activeLeafId : r.id
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
if (r.type === 'custom' && r.customType === 'foreign_session_import' && r.data?.sourcePath) {
|
|
123
|
+
importedFrom = r.data.sourcePath;
|
|
124
|
+
}
|
|
125
|
+
// background model calls (title generation) would skew usage against Claude's
|
|
126
|
+
if (r.type === 'model_usage' && r.usage && r.purpose !== 'title')
|
|
127
|
+
addUsage(models, r.model, r.usage);
|
|
128
|
+
if (r.type !== 'message' || !r.id)
|
|
129
|
+
continue;
|
|
130
|
+
const m = r.message;
|
|
131
|
+
if (m?.role === 'assistant') {
|
|
132
|
+
if (m.usage)
|
|
133
|
+
addUsage(models, m.model, m.usage);
|
|
134
|
+
turns.push({
|
|
135
|
+
id: r.id,
|
|
136
|
+
role: 'assistant',
|
|
137
|
+
text: text(m.content).trim(),
|
|
138
|
+
timestamp: r.timestamp,
|
|
139
|
+
ctx: m.contextSnapshot?.promptTokens ?? null
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
else if (m?.role === 'user') {
|
|
143
|
+
turns.push({
|
|
144
|
+
id: r.id,
|
|
145
|
+
role: 'user',
|
|
146
|
+
text: text(m.content),
|
|
147
|
+
timestamp: r.timestamp,
|
|
148
|
+
ctx: null
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return { title, aiTitle, header, lastTimestamp, importedFrom, nodes, turns, models };
|
|
153
|
+
}
|
|
154
|
+
// omp drops gitBranch on --from-claude, so an import reads it off the original.
|
|
155
|
+
async function importedBranch(sourcePath) {
|
|
156
|
+
try {
|
|
157
|
+
const raw = await readFile(sourcePath, 'utf8');
|
|
158
|
+
let branch = null;
|
|
159
|
+
for (const m of raw.matchAll(/"gitBranch":"([^"]*)"/g))
|
|
160
|
+
if (m[1] && m[1] !== 'HEAD')
|
|
161
|
+
branch = m[1];
|
|
162
|
+
return branch;
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
// omp records no git branch, so it comes from the cwd repo's reflog, read once
|
|
169
|
+
// per repo per listing.
|
|
170
|
+
let branchOf = reflogBranches();
|
|
171
|
+
export async function parseSession(filePath, fileStats) {
|
|
172
|
+
try {
|
|
173
|
+
const t = await readTranscript(filePath);
|
|
174
|
+
const cwd = t.header?.cwd;
|
|
175
|
+
if (!cwd)
|
|
176
|
+
return null;
|
|
177
|
+
const branch = activeBranch(t.nodes);
|
|
178
|
+
const onBranch = t.turns.filter((x) => branch.has(x.id));
|
|
179
|
+
const users = onBranch.filter((x) => x.role === 'user');
|
|
180
|
+
const lastCtx = [...onBranch].reverse().find((x) => x.ctx !== null);
|
|
181
|
+
const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
182
|
+
for (const k in t.models) {
|
|
183
|
+
totals.input += t.models[k].input;
|
|
184
|
+
totals.output += t.models[k].output;
|
|
185
|
+
totals.cacheRead += t.models[k].cacheRead;
|
|
186
|
+
totals.cacheWrite += t.models[k].cacheWrite;
|
|
187
|
+
}
|
|
188
|
+
const lastTimestamp = t.lastTimestamp ? new Date(t.lastTimestamp).getTime() : fileStats.mtimeMs;
|
|
189
|
+
const gitBranch = (t.importedFrom ? await importedBranch(t.importedFrom) : null) ??
|
|
190
|
+
(await branchOf(cwd, lastTimestamp));
|
|
191
|
+
return {
|
|
192
|
+
harness: 'omp',
|
|
193
|
+
sessionId: t.header?.id ?? basename(filePath, '.jsonl').split('_').at(-1),
|
|
194
|
+
title: t.title,
|
|
195
|
+
aiTitle: t.aiTitle,
|
|
196
|
+
cwd,
|
|
197
|
+
gitBranch,
|
|
198
|
+
firstUserMessage: users.find((u) => u.text.trim())?.text.trim() ?? null,
|
|
199
|
+
lastUserMessage: users.at(-1)?.text ?? null,
|
|
200
|
+
contextTokens: lastCtx?.ctx ?? null,
|
|
201
|
+
models: t.models,
|
|
202
|
+
totals,
|
|
203
|
+
throughput: throughputOf(totals),
|
|
204
|
+
searchText: t.turns
|
|
205
|
+
.map((x) => x.text)
|
|
206
|
+
.join(' ')
|
|
207
|
+
.toLowerCase(),
|
|
208
|
+
mtime: fileStats.mtimeMs,
|
|
209
|
+
lastTimestamp,
|
|
210
|
+
filePath
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
export async function getSessionMessages(filePath) {
|
|
218
|
+
try {
|
|
219
|
+
const t = await readTranscript(filePath);
|
|
220
|
+
const branch = activeBranch(t.nodes);
|
|
221
|
+
return t.turns
|
|
222
|
+
.filter((x) => branch.has(x.id) && (x.role === 'user' || x.text))
|
|
223
|
+
.map((x) => ({ role: x.role, text: x.text, timestamp: x.timestamp }));
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
return [];
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
// <agentDir>/sessions/<cwd-slug>/<ISO>_<id>.jsonl. Deeper .jsonl files are
|
|
230
|
+
// subagent transcripts inside a session's artifact directory.
|
|
231
|
+
export async function listSessionFiles() {
|
|
232
|
+
branchOf = reflogBranches();
|
|
233
|
+
let slugs;
|
|
234
|
+
try {
|
|
235
|
+
slugs = await readdir(sessionsDir());
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
return [];
|
|
239
|
+
}
|
|
240
|
+
const files = (await Promise.all(slugs.map(async (slug) => {
|
|
241
|
+
const dir = join(sessionsDir(), slug);
|
|
242
|
+
try {
|
|
243
|
+
return (await readdir(dir)).filter((f) => f.endsWith('.jsonl')).map((f) => join(dir, f));
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
return [];
|
|
247
|
+
}
|
|
248
|
+
}))).flat();
|
|
249
|
+
const stats = await Promise.all(files.map(async (filePath) => {
|
|
250
|
+
try {
|
|
251
|
+
return { harness: 'omp', filePath, stats: await stat(filePath) };
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
}));
|
|
257
|
+
return stats.filter((s) => s !== null);
|
|
258
|
+
}
|
|
259
|
+
const realProbes = { leases: ompLeases, terminals: terminalProcesses };
|
|
260
|
+
// An interactive omp, not one of its workers or a one-shot subcommand.
|
|
261
|
+
function isInteractiveOmp(command) {
|
|
262
|
+
const [bin, sub] = command.split(/\s+/);
|
|
263
|
+
return basename(bin) === 'omp' && !command.includes('__omp_worker') && sub !== 'session';
|
|
264
|
+
}
|
|
265
|
+
// Transcripts an interactive omp has open. omp rewrites terminal-sessions/<tty>
|
|
266
|
+
// whenever a terminal creates, switches, or resumes a session, so a breadcrumb
|
|
267
|
+
// names the open one while an omp runs on that tty. Breadcrumbs outlive omp,
|
|
268
|
+
// and ones named for a multiplexer pane or terminal app have no tty to check.
|
|
269
|
+
async function openFiles(probes) {
|
|
270
|
+
const ttys = new Set((await probes.terminals())
|
|
271
|
+
.filter((p) => isInteractiveOmp(p.command))
|
|
272
|
+
.map((p) => p.tty.replace(/\//g, '-')));
|
|
273
|
+
const dir = join(agentDir(), 'terminal-sessions');
|
|
274
|
+
const open = new Set();
|
|
275
|
+
let names;
|
|
276
|
+
try {
|
|
277
|
+
names = await readdir(dir);
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
return open;
|
|
281
|
+
}
|
|
282
|
+
for (const name of names.filter((n) => ttys.has(n))) {
|
|
283
|
+
try {
|
|
284
|
+
const file = (await readFile(join(dir, name), 'utf8')).split('\n')[1]?.trim();
|
|
285
|
+
if (file)
|
|
286
|
+
open.add(file);
|
|
287
|
+
}
|
|
288
|
+
catch { }
|
|
289
|
+
}
|
|
290
|
+
return open;
|
|
291
|
+
}
|
|
292
|
+
// Sessions a running omp would write back over: held while it writes, or open
|
|
293
|
+
// in a terminal while it idles, which holds no lease. null when the lease probe
|
|
294
|
+
// failed, so a caller about to write can refuse rather than guess.
|
|
295
|
+
export async function liveSessionIds(sessions, probes = realProbes) {
|
|
296
|
+
const [held, files] = await Promise.all([
|
|
297
|
+
probes.leases(sessions.map((s) => s.sessionId)),
|
|
298
|
+
openFiles(probes)
|
|
299
|
+
]);
|
|
300
|
+
if (held === null)
|
|
301
|
+
return null;
|
|
302
|
+
for (const s of sessions)
|
|
303
|
+
if (files.has(s.filePath))
|
|
304
|
+
held.add(s.sessionId);
|
|
305
|
+
return held;
|
|
306
|
+
}
|
|
307
|
+
// For the list's mark: a failed probe marks nothing.
|
|
308
|
+
export const listLive = async (sessions, probes = realProbes) => (await liveSessionIds(sessions, probes)) ?? new Set();
|
|
309
|
+
async function refuseLive(session, probes) {
|
|
310
|
+
const live = await liveSessionIds([session], probes);
|
|
311
|
+
if (live === null)
|
|
312
|
+
throw new Error('could not check whether omp has the session open');
|
|
313
|
+
if (live.has(session.sessionId))
|
|
314
|
+
throw new Error('session is open in omp');
|
|
315
|
+
}
|
|
316
|
+
// Node 22 prints an ExperimentalWarning for node:sqlite, which would land on
|
|
317
|
+
// the TUI. Node 24 prints none.
|
|
318
|
+
export function quietSqlite(emit) {
|
|
319
|
+
return ((warning, ...rest) => {
|
|
320
|
+
const text = typeof warning === 'string' ? warning : warning.message;
|
|
321
|
+
if (text.includes('SQLite'))
|
|
322
|
+
return;
|
|
323
|
+
return emit.call(process, warning, ...rest);
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
// omp's index of titles and recaps, opened only when it exists: opening a
|
|
327
|
+
// missing path would create one omp never made.
|
|
328
|
+
export async function openHistory() {
|
|
329
|
+
const path = join(agentDir(), 'history.db');
|
|
330
|
+
try {
|
|
331
|
+
await stat(path);
|
|
332
|
+
}
|
|
333
|
+
catch {
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
const emit = process.emitWarning;
|
|
337
|
+
process.emitWarning = quietSqlite(emit);
|
|
338
|
+
let sqlite;
|
|
339
|
+
try {
|
|
340
|
+
sqlite = await import('node:sqlite');
|
|
341
|
+
}
|
|
342
|
+
finally {
|
|
343
|
+
process.emitWarning = emit;
|
|
344
|
+
}
|
|
345
|
+
const db = new sqlite.DatabaseSync(path);
|
|
346
|
+
return {
|
|
347
|
+
run: (sql, ...params) => {
|
|
348
|
+
db.prepare(sql).run(...params);
|
|
349
|
+
},
|
|
350
|
+
close: () => db.close()
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
// The index is a cache omp's picker rebuilds from transcripts, so a busy or
|
|
354
|
+
// odd database never fails the rename or delete that already landed.
|
|
355
|
+
async function updateHistory(openDb, statements) {
|
|
356
|
+
let db = null;
|
|
357
|
+
try {
|
|
358
|
+
db = await openDb();
|
|
359
|
+
}
|
|
360
|
+
catch { }
|
|
361
|
+
if (!db)
|
|
362
|
+
return;
|
|
363
|
+
// a short wait: the TUI blocks on it, and the index is only a cache
|
|
364
|
+
for (const [sql, ...params] of [
|
|
365
|
+
['PRAGMA busy_timeout = 250'],
|
|
366
|
+
...statements
|
|
367
|
+
]) {
|
|
368
|
+
try {
|
|
369
|
+
db.run(sql, ...params);
|
|
370
|
+
}
|
|
371
|
+
catch { }
|
|
372
|
+
}
|
|
373
|
+
db.close();
|
|
374
|
+
}
|
|
375
|
+
// ─── Rename ──────────────────────────────────────────────────────────────────
|
|
376
|
+
const SLOT_BYTES = 256;
|
|
377
|
+
const slotLine = (title, updatedAt, pad) => `${JSON.stringify({ type: 'title', v: 1, title, source: 'user', updatedAt, pad })}\n`;
|
|
378
|
+
// omp's serializeTitleSlot: the longest code-point prefix of the title that
|
|
379
|
+
// fits, padded with spaces to exactly 256 bytes.
|
|
380
|
+
export function serializeSlot(title, updatedAt) {
|
|
381
|
+
const points = [...title];
|
|
382
|
+
// a 256-byte slot holds far fewer than 256 code points
|
|
383
|
+
let n = Math.min(points.length, SLOT_BYTES);
|
|
384
|
+
while (n > 0 &&
|
|
385
|
+
Buffer.byteLength(slotLine(points.slice(0, n).join(''), updatedAt, '')) > SLOT_BYTES)
|
|
386
|
+
n--;
|
|
387
|
+
const fit = points.slice(0, n).join('');
|
|
388
|
+
return slotLine(fit, updatedAt, ' '.repeat(SLOT_BYTES - Buffer.byteLength(slotLine(fit, updatedAt, ''))));
|
|
389
|
+
}
|
|
390
|
+
// omp's #cleanTitle
|
|
391
|
+
export const cleanTitle = (title) => title
|
|
392
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it strips
|
|
393
|
+
.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')
|
|
394
|
+
.replace(/\s+/g, ' ')
|
|
395
|
+
.trim();
|
|
396
|
+
// Rename as omp's own picker does: the slot on line 1 rewritten in place at the
|
|
397
|
+
// same length, plus the title index. No title_change record, which would fork
|
|
398
|
+
// the tree under an omp that has the file open, and no file rename, since omp
|
|
399
|
+
// keys sessions by the id in the filename.
|
|
400
|
+
export async function renameSession(session, title, { probes = realProbes, openDb = openHistory } = {}) {
|
|
401
|
+
const clean = cleanTitle(title);
|
|
402
|
+
if (!clean)
|
|
403
|
+
throw new Error('title is empty');
|
|
404
|
+
await refuseLive(session, probes);
|
|
405
|
+
let stored = clean;
|
|
406
|
+
const fh = await open(session.filePath, 'r+');
|
|
407
|
+
try {
|
|
408
|
+
const head = Buffer.alloc(SLOT_BYTES);
|
|
409
|
+
const { bytesRead } = await fh.read(head, 0, SLOT_BYTES, 0);
|
|
410
|
+
let slot = null;
|
|
411
|
+
try {
|
|
412
|
+
if (bytesRead === SLOT_BYTES && head[SLOT_BYTES - 1] === 10)
|
|
413
|
+
slot = JSON.parse(head.toString('utf8'));
|
|
414
|
+
}
|
|
415
|
+
catch { }
|
|
416
|
+
if (slot?.type !== 'title' || slot.v !== 1)
|
|
417
|
+
throw new Error('no title slot, resume it in omp to rename');
|
|
418
|
+
const line = serializeSlot(clean, new Date().toISOString());
|
|
419
|
+
stored = JSON.parse(line).title;
|
|
420
|
+
await fh.write(Buffer.from(line), 0, SLOT_BYTES, 0);
|
|
421
|
+
}
|
|
422
|
+
finally {
|
|
423
|
+
await fh.close();
|
|
424
|
+
}
|
|
425
|
+
await updateHistory(openDb, [
|
|
426
|
+
[
|
|
427
|
+
"INSERT INTO session_titles (session_id, title, updated_at) VALUES (?, ?, CAST(strftime('%s','now') AS INTEGER)) ON CONFLICT(session_id) DO UPDATE SET title = excluded.title, updated_at = excluded.updated_at",
|
|
428
|
+
session.sessionId,
|
|
429
|
+
stored
|
|
430
|
+
]
|
|
431
|
+
]);
|
|
432
|
+
return stored;
|
|
433
|
+
}
|
|
434
|
+
// ─── Delete ──────────────────────────────────────────────────────────────────
|
|
435
|
+
// Delete as omp's picker does (the transcript, its artifact directory, and
|
|
436
|
+
// rewrite leftovers), trashed rather than unlinked, refused while omp has it
|
|
437
|
+
// open since a live omp writes the whole file back. Lock sidecars stay, as omp
|
|
438
|
+
// leaves them. The title and recap rows go too, as omp gc drops them. Prompt
|
|
439
|
+
// history stays: it is deduped across sessions and feeds a full-text index.
|
|
440
|
+
export async function deleteSession(session, { trashFn = trashPaths, probes = realProbes, openDb = openHistory } = {}) {
|
|
441
|
+
await refuseLive(session, probes);
|
|
442
|
+
const file = session.filePath;
|
|
443
|
+
const stem = basename(file, '.jsonl');
|
|
444
|
+
const candidates = [file, join(dirname(file), stem)];
|
|
445
|
+
try {
|
|
446
|
+
for (const name of await readdir(dirname(file)))
|
|
447
|
+
if (name.startsWith(`${stem}.jsonl.`) && name.endsWith('.bak'))
|
|
448
|
+
candidates.push(join(dirname(file), name));
|
|
449
|
+
}
|
|
450
|
+
catch { }
|
|
451
|
+
const toTrash = [];
|
|
452
|
+
for (const p of candidates) {
|
|
453
|
+
try {
|
|
454
|
+
await stat(p);
|
|
455
|
+
toTrash.push(p);
|
|
456
|
+
}
|
|
457
|
+
catch { }
|
|
458
|
+
}
|
|
459
|
+
await trashFn(toTrash);
|
|
460
|
+
await updateHistory(openDb, [
|
|
461
|
+
['DELETE FROM session_titles WHERE session_id = ?', session.sessionId],
|
|
462
|
+
['DELETE FROM session_recaps WHERE session_id = ?', session.sessionId]
|
|
463
|
+
]);
|
|
464
|
+
}
|
|
465
|
+
export const omp = {
|
|
466
|
+
id: 'omp',
|
|
467
|
+
name: 'omp',
|
|
468
|
+
mark: 'π',
|
|
469
|
+
listFiles: listSessionFiles,
|
|
470
|
+
parse: (f) => parseSession(f.filePath, f.stats),
|
|
471
|
+
messages: (s) => getSessionMessages(s.filePath),
|
|
472
|
+
// the full id: omp resolves a prefix too, but its lease probe does not
|
|
473
|
+
resume: (s) => ({ command: 'omp', args: ['--resume', s.sessionId] }),
|
|
474
|
+
liveIds: (sessions) => listLive(sessions),
|
|
475
|
+
rename: (s, title) => renameSession(s, title),
|
|
476
|
+
delete: (s) => deleteSession(s)
|
|
477
|
+
};
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { join } from 'node:path';
|
|
2
3
|
import { helpText, parseArgs, readPackage } from './cli.js';
|
|
3
4
|
import { loadConfig } from './config.js';
|
|
4
|
-
import { listSessionFiles, parseSessions } from './
|
|
5
|
+
import { harnessOf, listSessionFiles, parseSessions } from './harnesses/index.js';
|
|
6
|
+
import { agentDir } from './harnesses/omp.js';
|
|
7
|
+
import { shortPath } from './sessions.js';
|
|
5
8
|
const action = parseArgs(process.argv.slice(2));
|
|
6
9
|
if (action === 'help') {
|
|
7
10
|
console.log(helpText(await readPackage()));
|
|
@@ -15,7 +18,7 @@ if (action === 'version') {
|
|
|
15
18
|
const FIRST_BATCH = 40;
|
|
16
19
|
const files = await listSessionFiles();
|
|
17
20
|
if (files.length === 0) {
|
|
18
|
-
console.log(
|
|
21
|
+
console.log(`No sessions found in ~/.claude/projects or ${shortPath(join(agentDir(), 'sessions'))}`);
|
|
19
22
|
process.exit(0);
|
|
20
23
|
}
|
|
21
24
|
// Start parsing before the react/ink import so the two overlap.
|
|
@@ -45,7 +48,8 @@ process.stdout.write('\x1b[?1049l'); // restore normal screen
|
|
|
45
48
|
const target = resume.target;
|
|
46
49
|
if (target) {
|
|
47
50
|
const { spawnSync } = await import('node:child_process');
|
|
48
|
-
|
|
51
|
+
const { command, args } = harnessOf(target).resume(target);
|
|
52
|
+
spawnSync(command, args, {
|
|
49
53
|
stdio: 'inherit',
|
|
50
54
|
cwd: target.cwd
|
|
51
55
|
});
|
package/dist/list.js
CHANGED
|
@@ -1,28 +1,48 @@
|
|
|
1
|
+
import stringWidth from 'string-width';
|
|
1
2
|
import { fmtTokens, relativeTime, shortPath } from './sessions.js';
|
|
2
3
|
// items[i] is always a session here: callers skip headers before calling.
|
|
3
4
|
const sessionIdAt = (items, i) => items[i].session.sessionId;
|
|
4
5
|
// below these widths a column is hidden rather than truncated into noise
|
|
5
6
|
export const BRANCH_MIN = 8;
|
|
6
7
|
export const DIR_MIN = 10;
|
|
7
|
-
export
|
|
8
|
-
|
|
8
|
+
export const GUTTER = 3;
|
|
9
|
+
// Columns are terminal cells, as ink measures them: an emoji or CJK character
|
|
10
|
+
// takes two, omp's Nerd Font title icons one.
|
|
11
|
+
export const width = (str) => stringWidth(str);
|
|
12
|
+
// The longest prefix that fits in n cells, whole characters only.
|
|
13
|
+
function slice(str, n) {
|
|
14
|
+
let out = '';
|
|
15
|
+
let w = 0;
|
|
16
|
+
for (const ch of str) {
|
|
17
|
+
const cw = stringWidth(ch);
|
|
18
|
+
if (w + cw > n)
|
|
19
|
+
break;
|
|
20
|
+
out += ch;
|
|
21
|
+
w += cw;
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
9
24
|
}
|
|
10
25
|
export function truncate(str, max) {
|
|
11
26
|
if (!str)
|
|
12
27
|
return '';
|
|
13
|
-
return str
|
|
28
|
+
return width(str) > max ? `${slice(str, max - 1)}…` : str;
|
|
14
29
|
}
|
|
15
30
|
export function pad(str, len) {
|
|
16
|
-
|
|
31
|
+
const cut = width(str) > len ? slice(str, len) : str;
|
|
32
|
+
return cut + ' '.repeat(len - width(cut));
|
|
17
33
|
}
|
|
18
34
|
export function padLeft(str, len) {
|
|
19
|
-
|
|
35
|
+
const cut = width(str) > len ? slice(str, len) : str;
|
|
36
|
+
return ' '.repeat(len - width(cut)) + cut;
|
|
20
37
|
}
|
|
38
|
+
// named: the user's /rename, auto: the tool's generated title, prompt: neither
|
|
21
39
|
export function displayTitle(session) {
|
|
22
40
|
if (session.title)
|
|
23
|
-
return { text: session.title,
|
|
41
|
+
return { text: session.title, kind: 'named' };
|
|
42
|
+
if (session.aiTitle)
|
|
43
|
+
return { text: session.aiTitle, kind: 'auto' };
|
|
24
44
|
const prompt = session.firstUserMessage?.replace(/\s+/g, ' ').trim();
|
|
25
|
-
return { text: prompt || 'Untitled',
|
|
45
|
+
return { text: prompt || 'Untitled', kind: 'prompt' };
|
|
26
46
|
}
|
|
27
47
|
// subsequence fuzzy match: query chars must appear in order, case-insensitive
|
|
28
48
|
export function fuzzyMatch(query, target) {
|
|
@@ -40,8 +60,8 @@ export function fuzzyMatch(query, target) {
|
|
|
40
60
|
// Title matches fuzzy (it's short); content matches by substring (fuzzy over a
|
|
41
61
|
// long blob hits everything).
|
|
42
62
|
export function sessionMatches(query, session) {
|
|
43
|
-
const { text,
|
|
44
|
-
if ((
|
|
63
|
+
const { text, kind } = displayTitle(session);
|
|
64
|
+
if ((kind !== 'prompt' || text === 'Untitled') && fuzzyMatch(query, text))
|
|
45
65
|
return true;
|
|
46
66
|
return session.searchText ? session.searchText.includes(query.toLowerCase()) : false;
|
|
47
67
|
}
|
|
@@ -55,27 +75,27 @@ export function computeRowLayout(opts) {
|
|
|
55
75
|
const pathStr = shortPath(session.cwd);
|
|
56
76
|
const naturalBranch = session.gitBranch ?? null;
|
|
57
77
|
const showDir = sortMode !== 'directory';
|
|
58
|
-
// flex = space for title + branch + dir after the
|
|
59
|
-
// (used/ctx/time + three 2-space gaps).
|
|
60
|
-
const { text: fullTitle,
|
|
61
|
-
const flex = termWidth -
|
|
62
|
-
const claim =
|
|
78
|
+
// flex = space for title + branch + dir after the 3-column gutter (cursor,
|
|
79
|
+
// harness mark, space) and the fixed right block (used/ctx/time + three 2-space gaps).
|
|
80
|
+
const { text: fullTitle, kind } = displayTitle(session);
|
|
81
|
+
const flex = termWidth - GUTTER - usedWidth - ctxWidth - timeWidth - 6;
|
|
82
|
+
const claim = kind === 'prompt' ? Math.min(width(fullTitle), Math.floor(flex / 2)) : width(fullTitle);
|
|
63
83
|
let avail = flex - claim;
|
|
64
84
|
let dirWidth = 0;
|
|
65
85
|
if (showDir && avail >= DIR_MIN + 2) {
|
|
66
|
-
dirWidth = Math.min(pathStr
|
|
86
|
+
dirWidth = Math.min(width(pathStr), avail - 2);
|
|
67
87
|
avail -= dirWidth + 2;
|
|
68
88
|
}
|
|
69
89
|
let branchWidth = 0;
|
|
70
90
|
if (naturalBranch && avail >= BRANCH_MIN + 2) {
|
|
71
|
-
branchWidth = Math.min(naturalBranch
|
|
91
|
+
branchWidth = Math.min(width(naturalBranch), avail - 2);
|
|
72
92
|
avail -= branchWidth + 2;
|
|
73
93
|
}
|
|
74
94
|
// title absorbs the leftover as padding so the right block stays aligned
|
|
75
95
|
const titleWidth = Math.max(1, flex - (dirWidth ? dirWidth + 2 : 0) - (branchWidth ? branchWidth + 2 : 0));
|
|
76
96
|
return {
|
|
77
97
|
title: pad(truncate(fullTitle, titleWidth), titleWidth),
|
|
78
|
-
|
|
98
|
+
titleKind: kind,
|
|
79
99
|
branchCol: branchWidth > 0 ? truncate(naturalBranch, branchWidth) : null,
|
|
80
100
|
dirCol: dirWidth > 0 ? truncate(pathStr, dirWidth) : null,
|
|
81
101
|
usedCol: padLeft(usedStr(session), usedWidth),
|
package/dist/proc.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
// Start time of a live process in ps's lstart format, read the way Claude Code
|
|
4
|
+
// reads its own procStart (C locale, UTC, 1s timeout). Isolated so isSessionLive
|
|
5
|
+
// can take a fake in tests and this adapter stays out of the coverage gate.
|
|
6
|
+
export async function processStartedAt(pid) {
|
|
7
|
+
try {
|
|
8
|
+
const { stdout } = await promisify(execFile)('ps', ['-o', 'lstart=', '-p', String(pid)], {
|
|
9
|
+
env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
|
|
10
|
+
timeout: 1000
|
|
11
|
+
});
|
|
12
|
+
return stdout.trim() || null;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
// Session ids a running omp holds the ownership lease on, from omp's own probe,
|
|
19
|
+
// which takes no lease itself. Ids must be full: a prefix silently matches none.
|
|
20
|
+
// An empty set when omp is not installed, null when the probe fails.
|
|
21
|
+
export async function ompLeases(ids) {
|
|
22
|
+
if (ids.length === 0)
|
|
23
|
+
return new Set();
|
|
24
|
+
try {
|
|
25
|
+
const { stdout } = await promisify(execFile)('omp', ['session', 'lease', '--json', '--', ...ids], {
|
|
26
|
+
timeout: 5000
|
|
27
|
+
});
|
|
28
|
+
return new Set(JSON.parse(stdout).held ?? []);
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
return err.code === 'ENOENT' ? new Set() : null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// Every process with a controlling terminal, as `ps` names the terminal.
|
|
35
|
+
export async function terminalProcesses() {
|
|
36
|
+
try {
|
|
37
|
+
const { stdout } = await promisify(execFile)('ps', ['-axo', 'tty=,command='], {
|
|
38
|
+
env: { ...process.env, LC_ALL: 'C' },
|
|
39
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
40
|
+
timeout: 2000
|
|
41
|
+
});
|
|
42
|
+
return stdout
|
|
43
|
+
.split('\n')
|
|
44
|
+
.map((l) => /^\s*(\S+)\s+(.*)$/.exec(l))
|
|
45
|
+
.filter((m) => m !== null && !/^\?+$/.test(m[1]))
|
|
46
|
+
.map((m) => ({ tty: m[1], command: m[2] }));
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
}
|