@yanzc/claude-pro 0.6.0 → 0.7.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 +375 -370
- package/package.json +1 -1
- package/src/attach.js +132 -0
- package/src/background.js +424 -0
- package/src/commands.js +75 -35
- package/src/connect.js +79 -0
- package/src/history.js +94 -0
- package/src/host.js +444 -65
- package/src/main.js +35 -6
- package/src/peers.js +290 -215
- package/src/remote.js +50 -15
- package/src/session.js +24 -0
- package/src/supervisor.js +6 -3
- package/src/tools/bash.js +2 -2
- package/src/ui/dialogs.js +48 -0
- package/src/ui/render.js +10 -0
- package/src/ui/repl.js +308 -38
- package/src/ui/vterm.js +62 -0
package/src/commands.js
CHANGED
|
@@ -21,7 +21,7 @@ import { displayPath } from './utils/paths.js';
|
|
|
21
21
|
import { cleanName, machineName } from './peers.js';
|
|
22
22
|
import { rewind, promptAt } from './checkpoints.js';
|
|
23
23
|
import { canRestart, runSelfCheck } from './restart.js';
|
|
24
|
-
import { describeHost } from './host.js';
|
|
24
|
+
import { describeHost, normalizeDir } from './host.js';
|
|
25
25
|
import { qrLines } from './qr.js';
|
|
26
26
|
|
|
27
27
|
const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
@@ -35,6 +35,55 @@ const effortLevels = (modelId, modelInfo = null) => {
|
|
|
35
35
|
return isGpt(modelId) && codexEfforts(modelId).length ? codexEfforts(modelId) : EFFORTS;
|
|
36
36
|
};
|
|
37
37
|
|
|
38
|
+
// What /model offers (and the remote page, see App.remoteOptions): [{value, label, description}] in plain text, the
|
|
39
|
+
// default first. `value` is what /model <value> takes. The gateway's list of models is asked for (4 seconds at
|
|
40
|
+
// most); without an answer gpt-6.1-sol stands for its GPT models.
|
|
41
|
+
export async function modelChoices(cfg) {
|
|
42
|
+
const configured = cfg.configuredModelSpec;
|
|
43
|
+
const opts = [{ value: 'default', label: 'Default', description: `${configured} → ${cfg.resolveModel(configured).id}` }];
|
|
44
|
+
if (cfg.usesCodex) {
|
|
45
|
+
// The models the local Codex install lists.
|
|
46
|
+
for (const m of codexModels({ ...process.env, ...cfg.env }).models.filter((x) => !x.hidden)) opts.push({ value: m.slug, label: m.slug, description: m.contextWindow ? `${formatTokens(m.contextWindow)} context` : '' });
|
|
47
|
+
} else {
|
|
48
|
+
opts.push(...['opus', 'sonnet', 'haiku'].map((a) => ({ value: a, label: a, description: `→ ${cfg.resolveModel(cfg.aliasTarget(a)).label}` })));
|
|
49
|
+
}
|
|
50
|
+
if (cfg.usesGateway) {
|
|
51
|
+
// The other models the gateway serves (Fable, the GPT models, …); without an answer, gpt-6.1-sol.
|
|
52
|
+
const login = readGatewayLogin(cfg.gatewayUrl);
|
|
53
|
+
let served = null;
|
|
54
|
+
try { if (login) served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) }); } catch { /* offline: the fallback below */ }
|
|
55
|
+
const aliased = new Set(['opus', 'sonnet', 'haiku'].map((a) => cfg.resolveModel(cfg.aliasTarget(a)).id));
|
|
56
|
+
for (const m of served?.length ? served : [{ id: 'gpt-6.1-sol' }]) {
|
|
57
|
+
if (aliased.has(m.id)) continue;
|
|
58
|
+
opts.push({ value: m.id, label: m.id, description: isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || '' });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (cfg.provider === 'api' && cfg.env.CLAUDE_CODE_SUBAGENT_MODEL) opts.push({ value: cfg.env.CLAUDE_CODE_SUBAGENT_MODEL, label: cfg.env.CLAUDE_CODE_SUBAGENT_MODEL, description: 'sub-agent model' });
|
|
62
|
+
return opts;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// What /effort offers for the current model: {levels, options: [{value, label, description}]} in plain text (the
|
|
66
|
+
// levels, auto, default).
|
|
67
|
+
export async function effortChoices(cfg) {
|
|
68
|
+
const id = cfg.mainModel.id;
|
|
69
|
+
let info = null;
|
|
70
|
+
if (cfg.usesGateway && isGpt(id)) {
|
|
71
|
+
const login = readGatewayLogin(cfg.gatewayUrl);
|
|
72
|
+
try { if (login) info = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
|
|
73
|
+
}
|
|
74
|
+
const levels = effortLevels(id, info);
|
|
75
|
+
const configured = (cfg.env.CLAUDE_CODE_EFFORT_LEVEL || '').trim().toLowerCase() || 'auto';
|
|
76
|
+
const fallback = defaultEffort(id, cfg);
|
|
77
|
+
return {
|
|
78
|
+
levels,
|
|
79
|
+
options: [
|
|
80
|
+
...levels.map((e) => ({ value: e, label: e, description: '' })),
|
|
81
|
+
{ value: 'auto', label: 'auto', description: fallback ? `model default: ${fallback}` : 'use API default' },
|
|
82
|
+
{ value: 'default', label: 'default', description: `configured: ${configured}` },
|
|
83
|
+
],
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
38
87
|
export function buildCommands(app) {
|
|
39
88
|
const commands = new Map();
|
|
40
89
|
const add = (cmd) => commands.set(cmd.name, cmd);
|
|
@@ -109,6 +158,27 @@ export function buildCommands(app) {
|
|
|
109
158
|
},
|
|
110
159
|
});
|
|
111
160
|
|
|
161
|
+
add({
|
|
162
|
+
name: 'cd',
|
|
163
|
+
argHint: '<directory>',
|
|
164
|
+
argRequired: true,
|
|
165
|
+
description: 'Change the working directory; the conversation goes on there (with that project\'s settings, CLAUDE.md and memory)',
|
|
166
|
+
run(args) {
|
|
167
|
+
const wanted = args.trim().replace(/^(["'])(.*)\1$/, '$2').trim();
|
|
168
|
+
if (!wanted) { out(`Working directory: ${app.cwd} ${c.dim('(/cd <directory> changes it)')}`); return; }
|
|
169
|
+
// absolute, ~ for the home directory, D: for a drive; else from the working directory
|
|
170
|
+
const dir = normalizeDir(wanted) ?? path.resolve(app.cwd, wanted);
|
|
171
|
+
let st = null;
|
|
172
|
+
try { st = fs.statSync(dir); } catch { /* below */ }
|
|
173
|
+
if (!st) { out(c.red(`No such directory: ${dir}`)); return; }
|
|
174
|
+
if (!st.isDirectory()) { out(c.red(`Not a directory: ${dir}`)); return; }
|
|
175
|
+
const same = (a, b) => (process.platform === 'win32' ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b));
|
|
176
|
+
if (same(dir, app.cwd)) { out(`Working directory: ${app.cwd} ${c.dim('(already)')}`); return; }
|
|
177
|
+
const res = app.changeDirectory(dir);
|
|
178
|
+
if (!res.ok) out(c.red(res.message));
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
|
|
112
182
|
add({
|
|
113
183
|
name: 'clear',
|
|
114
184
|
aliases: ['reset', 'new'],
|
|
@@ -224,27 +294,7 @@ export function buildCommands(app) {
|
|
|
224
294
|
const cfg = app.runtime.config;
|
|
225
295
|
let choice = args.trim();
|
|
226
296
|
if (!choice) {
|
|
227
|
-
const
|
|
228
|
-
const opts = [{ label: `Default ${c.dim(`(${configured} → ${cfg.resolveModel(configured).id})`)}`, value: '__default__' }];
|
|
229
|
-
if (cfg.usesCodex) {
|
|
230
|
-
// The models the local Codex install lists.
|
|
231
|
-
for (const m of codexModels({ ...process.env, ...cfg.env }).models.filter((x) => !x.hidden)) opts.push({ label: `${m.slug}${m.contextWindow ? c.dim(` (${formatTokens(m.contextWindow)} context)`) : ''}`, value: m.slug });
|
|
232
|
-
} else {
|
|
233
|
-
opts.push(...['opus', 'sonnet', 'haiku'].map((a) => ({ label: `${a} ${c.dim(`→ ${cfg.resolveModel(cfg.aliasTarget(a)).label}`)}`, value: a })));
|
|
234
|
-
}
|
|
235
|
-
if (cfg.usesGateway) {
|
|
236
|
-
// The other models the gateway serves (Fable, the GPT models, …); without an answer, gpt-6.1-sol.
|
|
237
|
-
const login = readGatewayLogin(cfg.gatewayUrl);
|
|
238
|
-
let served = null;
|
|
239
|
-
try { if (login) served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) }); } catch { /* offline: the fallback below */ }
|
|
240
|
-
const aliased = new Set(['opus', 'sonnet', 'haiku'].map((a) => cfg.resolveModel(cfg.aliasTarget(a)).id));
|
|
241
|
-
for (const m of served?.length ? served : [{ id: 'gpt-6.1-sol' }]) {
|
|
242
|
-
if (aliased.has(m.id)) continue;
|
|
243
|
-
const note = /^gpt-/i.test(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name;
|
|
244
|
-
opts.push({ label: `${m.id}${note ? ` ${c.dim(`(${note})`)}` : ''}`, value: m.id });
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
if (cfg.provider === 'api' && cfg.env.CLAUDE_CODE_SUBAGENT_MODEL) opts.push({ label: `${cfg.env.CLAUDE_CODE_SUBAGENT_MODEL} ${c.dim('(sub-agent model)')}`, value: cfg.env.CLAUDE_CODE_SUBAGENT_MODEL });
|
|
297
|
+
const opts = (await modelChoices(cfg)).map((o) => ({ label: `${o.label}${o.description ? ` ${c.dim(o.description.startsWith('→') ? o.description : `(${o.description})`)}` : ''}`, value: o.value }));
|
|
248
298
|
choice = await app.showDialog(new SelectDialog({ title: 'Select model', question: `Current: ${c.bold(cfg.mainModel.label)}. Any name works too: /model <name>`, options: opts }));
|
|
249
299
|
if (!choice) return;
|
|
250
300
|
}
|
|
@@ -270,15 +320,9 @@ export function buildCommands(app) {
|
|
|
270
320
|
async run(args) {
|
|
271
321
|
const cfg = app.runtime.config;
|
|
272
322
|
const id = cfg.mainModel.id;
|
|
273
|
-
|
|
274
|
-
if (cfg.usesGateway && isGpt(id)) {
|
|
275
|
-
const login = readGatewayLogin(cfg.gatewayUrl);
|
|
276
|
-
try { if (login) modelInfo = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
|
|
277
|
-
}
|
|
278
|
-
const levels = effortLevels(id, modelInfo);
|
|
323
|
+
const { levels, options } = await effortChoices(cfg);
|
|
279
324
|
let choice = args.trim().toLowerCase();
|
|
280
325
|
if (!choice) {
|
|
281
|
-
const configured = (cfg.env.CLAUDE_CODE_EFFORT_LEVEL || '').trim().toLowerCase() || 'auto';
|
|
282
326
|
const fallback = defaultEffort(id, cfg);
|
|
283
327
|
// A level this model does not take goes out as the nearest one it does.
|
|
284
328
|
const sent = effortToSend(cfg, id, cfg.effort);
|
|
@@ -287,11 +331,7 @@ export function buildCommands(app) {
|
|
|
287
331
|
choice = await app.showDialog(new SelectDialog({
|
|
288
332
|
title: `Reasoning effort · ${id}`,
|
|
289
333
|
question: `Current: ${current}`,
|
|
290
|
-
options:
|
|
291
|
-
...levels.map((e) => ({ label: e, value: e })),
|
|
292
|
-
{ label: `auto ${c.dim(fallback ? `(model default: ${fallback})` : '(use API default)')}`, value: 'auto' },
|
|
293
|
-
{ label: `default ${c.dim(`(configured: ${configured})`)}`, value: 'default' },
|
|
294
|
-
],
|
|
334
|
+
options: options.map((o) => ({ label: `${o.label}${o.description ? ` ${c.dim(`(${o.description})`)}` : ''}`, value: o.value })),
|
|
295
335
|
}));
|
|
296
336
|
if (!choice) return;
|
|
297
337
|
}
|
|
@@ -333,7 +373,7 @@ export function buildCommands(app) {
|
|
|
333
373
|
// sessions), and the computer service starts (the web page opens new sessions through it).
|
|
334
374
|
const goOnline = async () => {
|
|
335
375
|
const remote = await app.syncRemote();
|
|
336
|
-
app.ensureHost();
|
|
376
|
+
app.ensureHost({ login: true });
|
|
337
377
|
if (!remote) return;
|
|
338
378
|
out(remote.url
|
|
339
379
|
? `${c.green('⇄')} This session is online at the gateway: ${c.blue(remote.url)} ${c.dim('(/status shows it, with a QR code for a phone)')}`
|
package/src/connect.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// `claude-pro connect <code> [--url U]`: a new computer joins the user's gateway account with the pairing code the
|
|
2
|
+
// web page shows (添加电脑). No login in a browser: the code stands for it. The gateway answers with an API key of
|
|
3
|
+
// this computer's own, which is saved as /login saves one (gateway.json); then the computer service is set up to
|
|
4
|
+
// start at logon and started, so that the page can use this computer at once and after every restart.
|
|
5
|
+
//
|
|
6
|
+
// POST {url}/v1/remote/pair {code, id, machine, host, platform, version, home} (no authentication)
|
|
7
|
+
// 200 {apiKey, computerId, url, account: {name, email}} · 400 配对码无效或已过期 · 429 too many tries
|
|
8
|
+
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import { VERSION, GATEWAY_DEFAULT_URL, loadConfig, settingsFiles, updateSettingsFile } from './config.js';
|
|
11
|
+
import { saveGatewayLogin, normalizeGatewayUrl } from './gateway.js';
|
|
12
|
+
import { machineName } from './peers.js';
|
|
13
|
+
import { computerId, setComputerId, hostEnabled, ensureAutostart, startHostInBackground, hostRunning, readHostState, updateHostState } from './host.js';
|
|
14
|
+
|
|
15
|
+
// The code as typed: 8 letters and digits (I, O, 0 and 1 are not used), maybe with a dash or spaces, in any case.
|
|
16
|
+
export function normalizePairingCode(input) {
|
|
17
|
+
const code = String(input ?? '').toUpperCase().replace(/[\s-]+/g, '');
|
|
18
|
+
return /^[A-Z2-9]{8}$/.test(code) ? code : null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const USAGE = `Usage: claude-pro connect <code> [--url <gateway>]
|
|
22
|
+
|
|
23
|
+
Connects this computer to your gateway account with the pairing code the web page shows (远程控制 → 添加电脑),
|
|
24
|
+
then starts the computer service and sets it to start at logon, so that the page can use this computer.
|
|
25
|
+
--url: the gateway's address (default ${GATEWAY_DEFAULT_URL}, or CLAUDE_PRO_GATEWAY_URL).
|
|
26
|
+
`;
|
|
27
|
+
|
|
28
|
+
export async function connectCommand(args = [], { fetchImpl = globalThis.fetch, out = (s) => process.stdout.write(`${s}\n`), err = (s) => process.stderr.write(`${s}\n`), startService = true } = {}) {
|
|
29
|
+
let url = null;
|
|
30
|
+
const rest = [];
|
|
31
|
+
for (let i = 0; i < args.length; i++) {
|
|
32
|
+
if (args[i] === '--url') url = args[++i];
|
|
33
|
+
else if (args[i].startsWith('--url=')) url = args[i].slice(6);
|
|
34
|
+
else if (args[i] === '-h' || args[i] === '--help') { out(USAGE); return 0; }
|
|
35
|
+
else rest.push(args[i]);
|
|
36
|
+
}
|
|
37
|
+
const code = normalizePairingCode(rest.join(''));
|
|
38
|
+
if (!code) { err(`配对码应是 8 位字母和数字(例如 K7QF-M2XD),不是 "${rest.join(' ')}"\n\n${USAGE}`); return 2; }
|
|
39
|
+
const home = os.homedir();
|
|
40
|
+
const cfg = loadConfig({ cwd: home });
|
|
41
|
+
const base = normalizeGatewayUrl(url || cfg.gatewayUrl);
|
|
42
|
+
let res;
|
|
43
|
+
let data = {};
|
|
44
|
+
try {
|
|
45
|
+
res = await fetchImpl(`${base}/v1/remote/pair`, {
|
|
46
|
+
method: 'POST',
|
|
47
|
+
headers: { 'content-type': 'application/json' },
|
|
48
|
+
body: JSON.stringify({ code, id: computerId(), machine: machineName(cfg.env), host: os.hostname(), platform: process.platform, version: VERSION, home }),
|
|
49
|
+
signal: AbortSignal.timeout(20_000),
|
|
50
|
+
});
|
|
51
|
+
data = await res.json().catch(() => ({}));
|
|
52
|
+
} catch (e) {
|
|
53
|
+
err(`连不上网关 ${base}:${e.message}`);
|
|
54
|
+
return 1;
|
|
55
|
+
}
|
|
56
|
+
if (!res.ok || !data.apiKey) {
|
|
57
|
+
const said = data?.error?.message || (typeof data?.error === 'string' ? data.error : '');
|
|
58
|
+
err(res.status === 429 ? `请求太频繁,请稍后再试${said ? `(${said})` : ''}` : said || `配对失败(HTTP ${res.status})`);
|
|
59
|
+
return 1;
|
|
60
|
+
}
|
|
61
|
+
const gateway = normalizeGatewayUrl(data.url || base);
|
|
62
|
+
saveGatewayLogin({ url: gateway, apiKey: data.apiKey, account: data.account || {} });
|
|
63
|
+
// another gateway than the one configured: the sessions and the service use this one from now on
|
|
64
|
+
if (gateway !== normalizeGatewayUrl(cfg.gatewayUrl)) {
|
|
65
|
+
updateSettingsFile(settingsFiles(home).user, (json) => { json.env = { ...(json.env || {}), CLAUDE_PRO_GATEWAY_URL: gateway }; });
|
|
66
|
+
}
|
|
67
|
+
if (data.computerId && data.computerId !== computerId()) setComputerId(data.computerId);
|
|
68
|
+
const who = data.account?.name || data.account?.email || '你的账户';
|
|
69
|
+
if (!hostEnabled(cfg.env)) {
|
|
70
|
+
out(`已连接到 ${who}。CLAUDE_PRO_HOST=0:电脑服务不会自己启动,用 claude-pro host start 启动它,网页才能使用这台电脑。`);
|
|
71
|
+
return 0;
|
|
72
|
+
}
|
|
73
|
+
updateHostState({ disabled: undefined, autostartDeclined: undefined });
|
|
74
|
+
const auto = ensureAutostart({ force: true, env: cfg.env });
|
|
75
|
+
if (startService && !hostRunning(readHostState())) startHostInBackground();
|
|
76
|
+
// (one that runs already picks the new login up within seconds)
|
|
77
|
+
out(`已连接到 ${who},可以在网页上使用这台电脑了。${auto?.file ? `\n登录后自动启动:${auto.file}` : ''}`);
|
|
78
|
+
return 0;
|
|
79
|
+
}
|
package/src/history.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// The conversations kept on this computer (CONFIG_DIR/projects/<directory>/<id>.jsonl, see session.js), for the web
|
|
2
|
+
// page's history (the computer service's `history` command): newest first, searched by title and first message,
|
|
3
|
+
// a page at a time. A file is read once for as long as it does not change (a session file can be tens of MB): its
|
|
4
|
+
// messages are counted without parsing them, only the first prompt and the meta lines are.
|
|
5
|
+
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { firstUserText, projectDir } from './session.js';
|
|
9
|
+
|
|
10
|
+
const cache = new Map(); // file -> {mtimeMs, size, summary}
|
|
11
|
+
|
|
12
|
+
// {conversationId, cwd, title, firstPrompt, messages, updatedAt} of one session file, or null when it has none.
|
|
13
|
+
export function conversationSummary(file) {
|
|
14
|
+
let st;
|
|
15
|
+
try { st = fs.statSync(file); } catch { return null; }
|
|
16
|
+
const hit = cache.get(file);
|
|
17
|
+
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.summary;
|
|
18
|
+
let text = '';
|
|
19
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { return null; }
|
|
20
|
+
let cwd = null;
|
|
21
|
+
let name = null;
|
|
22
|
+
let topic = null;
|
|
23
|
+
let first = null;
|
|
24
|
+
let messages = 0;
|
|
25
|
+
for (const line of text.split('\n')) {
|
|
26
|
+
if (!line) continue;
|
|
27
|
+
if (line.startsWith('{"type":"message"')) {
|
|
28
|
+
messages++;
|
|
29
|
+
if (!first && line.includes('"role":"user"')) {
|
|
30
|
+
try { first = firstUserText(JSON.parse(line).message) || null; } catch { /* a broken line */ }
|
|
31
|
+
}
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
let e;
|
|
35
|
+
try { e = JSON.parse(line); } catch { continue; }
|
|
36
|
+
if (e.type === 'meta') {
|
|
37
|
+
if (cwd === null && typeof e.cwd === 'string') cwd = e.cwd;
|
|
38
|
+
if ('name' in e) name = typeof e.name === 'string' && e.name.trim() ? e.name : null;
|
|
39
|
+
if (typeof e.topic === 'string' && e.topic.trim()) topic = e.topic;
|
|
40
|
+
} else if (e.type === 'reset' && Array.isArray(e.messages)) {
|
|
41
|
+
messages = e.messages.length;
|
|
42
|
+
} else if (e.type === 'message') {
|
|
43
|
+
messages++;
|
|
44
|
+
if (!first && e.message?.role === 'user') first = firstUserText(e.message) || null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const summary = messages ? {
|
|
48
|
+
conversationId: path.basename(file, '.jsonl'),
|
|
49
|
+
cwd,
|
|
50
|
+
title: name || topic || first || '(no prompt)',
|
|
51
|
+
firstPrompt: first || '',
|
|
52
|
+
messages,
|
|
53
|
+
updatedAt: new Date(st.mtimeMs).toISOString(),
|
|
54
|
+
} : null;
|
|
55
|
+
cache.set(file, { mtimeMs: st.mtimeMs, size: st.size, summary });
|
|
56
|
+
if (cache.size > 5000) cache.delete(cache.keys().next().value);
|
|
57
|
+
return summary;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// {items: [{conversationId, cwd, title, updatedAt, messages, sessionId?}], more}. `cwd`: only that directory's
|
|
61
|
+
// conversations. `before`: older than this time (ISO), for the next page. `open`: conversationId -> the id at the
|
|
62
|
+
// gateway of the session it is open in.
|
|
63
|
+
export function listConversations({ projects, query = '', cwd = null, limit = 50, before = null, open = new Map() } = {}) {
|
|
64
|
+
const max = Math.max(1, Math.min(200, Number(limit) || 50));
|
|
65
|
+
const until = before ? Date.parse(before) : Infinity;
|
|
66
|
+
const q = String(query || '').trim().toLowerCase();
|
|
67
|
+
const dirs = cwd ? [projectDir(cwd)] : (() => {
|
|
68
|
+
try { return fs.readdirSync(projects, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(projects, d.name)); } catch { return []; }
|
|
69
|
+
})();
|
|
70
|
+
const files = [];
|
|
71
|
+
for (const dir of dirs) {
|
|
72
|
+
let names = [];
|
|
73
|
+
try { names = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl')); } catch { continue; }
|
|
74
|
+
for (const f of names) {
|
|
75
|
+
const file = path.join(dir, f);
|
|
76
|
+
try {
|
|
77
|
+
const st = fs.statSync(file);
|
|
78
|
+
if (st.mtimeMs < until) files.push({ file, mtimeMs: st.mtimeMs });
|
|
79
|
+
} catch { /* gone meanwhile */ }
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
files.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
83
|
+
const items = [];
|
|
84
|
+
let more = false;
|
|
85
|
+
for (const { file } of files) {
|
|
86
|
+
const s = conversationSummary(file);
|
|
87
|
+
if (!s) continue;
|
|
88
|
+
if (q && !`${s.title}\n${s.firstPrompt}`.toLowerCase().includes(q)) continue;
|
|
89
|
+
if (items.length === max) { more = true; break; }
|
|
90
|
+
const sessionId = open.get(s.conversationId);
|
|
91
|
+
items.push({ conversationId: s.conversationId, cwd: s.cwd, title: s.title, updatedAt: s.updatedAt, messages: s.messages, ...(sessionId ? { sessionId } : {}) });
|
|
92
|
+
}
|
|
93
|
+
return { items, more };
|
|
94
|
+
}
|