@yanzc/claude-pro 0.7.8 → 0.9.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/src/history.js DELETED
@@ -1,163 +0,0 @@
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
- }
95
-
96
- // A conversation's id as it may be used in a path: what SessionStore makes (a UUID), letters, digits, - and _ in
97
- // any case. Anything else (a dot, a slash: "../x") is refused before it gets near a path.
98
- export const CONVERSATION_ID = /^[A-Za-z0-9_-]{8,64}$/;
99
-
100
- // Delete what this computer keeps of the conversation `id` (the web page's "delete"): its session file (in every
101
- // project it is in: /cd moves it), the tool results saved for it (the outputs too long for the conversation, named
102
- // after its tool calls or referred to by path in it) and its checkpoints (the file snapshots of /rewind, tagged
103
- // with the conversation they belong to). What belongs to the project stays: its memory, CLAUDE.md, the input
104
- // history, the checkpoints of other conversations. `extra`: more files to delete (a background session's log).
105
- // Returns {files, bytes}; throws when there is no such conversation.
106
- export function deleteConversation({ projects, id, extra = [] }) {
107
- if (!CONVERSATION_ID.test(String(id || ''))) throw new Error('对话 id 不对');
108
- let dirs = [];
109
- try { dirs = fs.readdirSync(projects, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(projects, d.name)); } catch { /* none */ }
110
- const sessionFiles = dirs.map((d) => path.join(d, `${id}.jsonl`)).filter((f) => fs.existsSync(f));
111
- if (!sessionFiles.length) throw new Error('这台电脑上没有这段对话');
112
- // the tool results it saved: <tool call id>.txt (persistLargeOutput) and bash-<time>-<random>.txt (the Bash tool)
113
- const names = new Set();
114
- for (const file of sessionFiles) {
115
- let text = '';
116
- try { text = fs.readFileSync(file, 'utf8'); } catch { continue; }
117
- for (const m of text.matchAll(/"(?:tool_use_id|id)":"([^"]{1,200})"/g)) names.add(`${m[1].replace(/[^\w-]/g, '_')}.txt`);
118
- for (const m of text.matchAll(/bash-\d+-[a-z0-9]+\.txt/g)) names.add(m[0]);
119
- }
120
- const doomed = [...sessionFiles, ...extra];
121
- const rewrites = []; // checkpoint indexes that keep other conversations' entries
122
- for (const dir of dirs) {
123
- const results = path.join(dir, 'tool-results');
124
- for (const name of names) {
125
- const f = path.join(results, name);
126
- if (fs.existsSync(f)) doomed.push(f);
127
- }
128
- let runs = [];
129
- try { runs = fs.readdirSync(path.join(dir, 'checkpoints')); } catch { continue; }
130
- for (const run of runs) {
131
- const runDir = path.join(dir, 'checkpoints', run);
132
- let entries;
133
- try { entries = JSON.parse(fs.readFileSync(path.join(runDir, 'index.json'), 'utf8')); } catch { continue; }
134
- if (!Array.isArray(entries) || !entries.some((e) => e?.conversation === id)) continue;
135
- const kept = entries.filter((e) => e?.conversation !== id);
136
- for (const e of entries) {
137
- if (e?.conversation !== id) continue;
138
- for (const f of e.files || []) if (f?.snap && /^[\w-]+$/.test(f.snap)) doomed.push(path.join(runDir, f.snap));
139
- }
140
- if (kept.length) rewrites.push({ file: path.join(runDir, 'index.json'), entries: kept });
141
- else doomed.push(path.join(runDir, 'index.json'), runDir);
142
- }
143
- }
144
- let files = 0;
145
- let bytes = 0;
146
- const failed = [];
147
- for (const f of doomed) {
148
- try {
149
- const st = fs.statSync(f);
150
- if (st.isDirectory()) { fs.rmSync(f, { recursive: true, force: true }); continue; }
151
- fs.rmSync(f);
152
- files++;
153
- bytes += st.size;
154
- } catch (e) {
155
- if (e.code !== 'ENOENT') failed.push(`${path.basename(f)}: ${e.code || e.message}`);
156
- }
157
- }
158
- for (const r of rewrites) {
159
- try { fs.writeFileSync(r.file, JSON.stringify(r.entries, null, 1)); } catch (e) { failed.push(`${r.file}: ${e.code || e.message}`); }
160
- }
161
- if (sessionFiles.some((f) => fs.existsSync(f))) throw new Error(`删除失败:${failed.join(';') || '会话文件还在'}`);
162
- return { files, bytes, ...(failed.length ? { failed } : {}) };
163
- }