@yanzc/claude-pro 0.10.0 → 0.12.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 +66 -35
- package/package.json +1 -1
- package/src/agent.js +16 -6
- package/src/browser/session.js +32 -2
- package/src/commands.js +160 -11
- package/src/config.js +42 -10
- package/src/live.js +148 -0
- package/src/main.js +5 -3
- package/src/peers.js +64 -10
- package/src/providers.js +10 -1
- package/src/remote.js +90 -243
- package/src/runtime.js +36 -11
- package/src/selfcheck.js +3 -3
- package/src/session.js +116 -7
- package/src/supervisor.js +1 -1
- package/src/tools/bash.js +23 -20
- package/src/tools/browser.js +14 -8
- package/src/tools/code.js +18 -11
- package/src/tools/peers.js +6 -5
- package/src/tools/restart.js +1 -1
- package/src/ui/dialogs.js +23 -30
- package/src/ui/editor.js +65 -169
- package/src/ui/repl.js +470 -449
- package/src/ui/screen.js +47 -674
- package/src/updater.js +5 -4
- package/src/utils/shell.js +4 -5
- package/src/web/api.js +787 -0
- package/src/web/app.css +412 -0
- package/src/web/app.js +1850 -0
- package/src/web/data.js +424 -0
- package/src/web/host.js +334 -0
- package/src/web/login.html +66 -0
- package/src/web/page.html +41 -0
- package/src/web/remote-access.js +232 -0
- package/src/web/server.js +459 -0
package/src/web/data.js
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
// What the local web console (see server.js) reads and changes on disk: the conversations of every project, the
|
|
2
|
+
// trash they go to, the running sessions (their peer servers), memory files, and the usage the traces recorded.
|
|
3
|
+
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import http from 'node:http';
|
|
8
|
+
import { CONFIG_DIR, loadConfig } from '../config.js';
|
|
9
|
+
import { SessionStore, firstUserText, archivedSessions } from '../session.js';
|
|
10
|
+
import { transcriptItems } from '../remote.js';
|
|
11
|
+
import { buildTools } from '../tools/index.js';
|
|
12
|
+
import { loadAgents, loadSkills } from '../agents.js';
|
|
13
|
+
import { listPeers } from '../peers.js';
|
|
14
|
+
import { costOf } from '../pricing.js';
|
|
15
|
+
import { stripAnsi } from '../ui/ansi.js';
|
|
16
|
+
|
|
17
|
+
export const projectsRoot = () => path.join(CONFIG_DIR, 'projects');
|
|
18
|
+
export const trashRoot = () => path.join(CONFIG_DIR, 'trash', 'sessions');
|
|
19
|
+
const TRASH_DAYS = 7;
|
|
20
|
+
const ID = /^[\w-]{8,80}$/;
|
|
21
|
+
const DIR = /^[\w.-]{1,250}$/;
|
|
22
|
+
|
|
23
|
+
// ---------------------------------------------------------------- conversations
|
|
24
|
+
|
|
25
|
+
// What the list shows of a conversation file, read without parsing every message (a conversation with screenshots
|
|
26
|
+
// is tens of MB): the messages are counted, only the first prompt and the meta lines are parsed. Kept on disk by
|
|
27
|
+
// file, size and time (cache/web-sessions.json), so that only the files that changed are read again.
|
|
28
|
+
function summarize(file) {
|
|
29
|
+
let count = 0;
|
|
30
|
+
let firstPrompt = null;
|
|
31
|
+
let meta = {};
|
|
32
|
+
let lastAt = 0;
|
|
33
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
34
|
+
let start = 0;
|
|
35
|
+
while (start < text.length) {
|
|
36
|
+
let end = text.indexOf('\n', start);
|
|
37
|
+
if (end < 0) end = text.length;
|
|
38
|
+
const line = text.slice(start, end);
|
|
39
|
+
start = end + 1;
|
|
40
|
+
if (line.startsWith('{"type":"message"')) {
|
|
41
|
+
count++;
|
|
42
|
+
const at = /"at":(\d+)\}\s*$/.exec(line);
|
|
43
|
+
if (at) lastAt = Math.max(lastAt, Number(at[1]));
|
|
44
|
+
if (!firstPrompt && line.includes('"role":"user"')) {
|
|
45
|
+
try { firstPrompt = firstUserText(JSON.parse(line).message); } catch { /* skip */ }
|
|
46
|
+
}
|
|
47
|
+
} else if (line.startsWith('{"type":"reset"')) {
|
|
48
|
+
try {
|
|
49
|
+
const e = JSON.parse(line);
|
|
50
|
+
count = e.messages.length;
|
|
51
|
+
lastAt = Math.max(lastAt, e.at || 0);
|
|
52
|
+
if (!firstPrompt) for (const m of e.messages) if (m.role === 'user' && (firstPrompt = firstUserText(m))) break;
|
|
53
|
+
} catch { /* skip */ }
|
|
54
|
+
} else if (line.startsWith('{"type":"meta"')) {
|
|
55
|
+
try {
|
|
56
|
+
const { systemPrompt, cacheState, ...e } = JSON.parse(line);
|
|
57
|
+
meta = { ...meta, ...e };
|
|
58
|
+
} catch { /* skip */ }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const name = typeof meta.name === 'string' && meta.name.trim() ? meta.name : null;
|
|
62
|
+
const topic = typeof meta.topic === 'string' && meta.topic.trim() ? meta.topic : null;
|
|
63
|
+
return {
|
|
64
|
+
cwd: typeof meta.cwd === 'string' ? meta.cwd : null,
|
|
65
|
+
created: meta.created || null,
|
|
66
|
+
name, topic, firstPrompt, count,
|
|
67
|
+
cost: Number(meta.cost) > 0 ? Number(meta.cost) : 0,
|
|
68
|
+
lastAt,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const cacheFile = () => path.join(CONFIG_DIR, 'cache', 'web-sessions.json');
|
|
73
|
+
let summaries = null; // file -> {mtime, size, data}
|
|
74
|
+
|
|
75
|
+
function readSummaries() {
|
|
76
|
+
if (summaries) return summaries;
|
|
77
|
+
try { summaries = new Map(Object.entries(JSON.parse(fs.readFileSync(cacheFile(), 'utf8')))); } catch { summaries = new Map(); }
|
|
78
|
+
return summaries;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function saveSummaries() {
|
|
82
|
+
try {
|
|
83
|
+
fs.mkdirSync(path.dirname(cacheFile()), { recursive: true });
|
|
84
|
+
const tmp = `${cacheFile()}.${process.pid}.tmp`;
|
|
85
|
+
fs.writeFileSync(tmp, JSON.stringify(Object.fromEntries(summaries)));
|
|
86
|
+
fs.renameSync(tmp, cacheFile());
|
|
87
|
+
} catch { /* read again next time */ }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Every conversation of every project, newest first: {id, dir, file, cwd, title, name, topic, firstPrompt, count,
|
|
91
|
+
// size, mtime, created, cost}.
|
|
92
|
+
export function listAllSessions() {
|
|
93
|
+
const cache = readSummaries();
|
|
94
|
+
const seen = new Set();
|
|
95
|
+
let changed = false;
|
|
96
|
+
const out = [];
|
|
97
|
+
let dirs = [];
|
|
98
|
+
try { dirs = fs.readdirSync(projectsRoot(), { withFileTypes: true }).filter((d) => d.isDirectory()); } catch { return []; }
|
|
99
|
+
for (const d of dirs) {
|
|
100
|
+
const dir = path.join(projectsRoot(), d.name);
|
|
101
|
+
let files = [];
|
|
102
|
+
try { files = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl')); } catch { continue; }
|
|
103
|
+
for (const f of files) {
|
|
104
|
+
const file = path.join(dir, f);
|
|
105
|
+
let st;
|
|
106
|
+
try { st = fs.statSync(file); } catch { continue; }
|
|
107
|
+
seen.add(file);
|
|
108
|
+
let e = cache.get(file);
|
|
109
|
+
if (!e || e.mtime !== st.mtimeMs || e.size !== st.size) {
|
|
110
|
+
try { e = { mtime: st.mtimeMs, size: st.size, data: summarize(file) }; } catch { continue; }
|
|
111
|
+
cache.set(file, e);
|
|
112
|
+
changed = true;
|
|
113
|
+
}
|
|
114
|
+
if (!e.data.count) continue;
|
|
115
|
+
const s = e.data;
|
|
116
|
+
out.push({
|
|
117
|
+
id: f.slice(0, -6), dir: d.name, file, cwd: s.cwd, title: s.name || s.topic || s.firstPrompt || '(no prompt)',
|
|
118
|
+
name: s.name, topic: s.topic, firstPrompt: s.firstPrompt, count: s.count, size: st.size, mtime: st.mtimeMs,
|
|
119
|
+
created: s.created, cost: s.cost,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
for (const file of cache.keys()) if (!seen.has(file)) { cache.delete(file); changed = true; }
|
|
124
|
+
if (changed) saveSummaries();
|
|
125
|
+
const archived = archivedSessions();
|
|
126
|
+
for (const s of out) if (archived[s.id]) s.archived = archived[s.id].at || true;
|
|
127
|
+
return out.sort((a, b) => b.mtime - a.mtime);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function sessionFile(dir, id) {
|
|
131
|
+
if (!DIR.test(dir || '') || !ID.test(id || '')) throw httpError(400, 'bad session reference');
|
|
132
|
+
const file = path.join(projectsRoot(), dir, `${id}.jsonl`);
|
|
133
|
+
if (!fs.existsSync(file)) throw httpError(404, '会话不存在');
|
|
134
|
+
return file;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function httpError(status, message) { return Object.assign(new Error(message), { status }); }
|
|
138
|
+
|
|
139
|
+
// The tools of a project, for the tool calls' headers (their summaries) in a conversation's view.
|
|
140
|
+
const toolsMemo = new Map();
|
|
141
|
+
function toolsFor(cwd) {
|
|
142
|
+
const key = cwd || '';
|
|
143
|
+
if (toolsMemo.has(key)) return toolsMemo.get(key);
|
|
144
|
+
let tools = [];
|
|
145
|
+
try {
|
|
146
|
+
const dir = cwd && fs.existsSync(cwd) ? cwd : os.homedir();
|
|
147
|
+
const config = loadConfig({ cwd: dir });
|
|
148
|
+
tools = buildTools(config, { agents: loadAgents(dir), skills: loadSkills(dir), peers: true });
|
|
149
|
+
} catch { /* headers with the tools' names only */ }
|
|
150
|
+
toolsMemo.set(key, tools);
|
|
151
|
+
return tools;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// A conversation as the console shows it: its items (as the live view has them, images as {k: 'image', n}), with
|
|
155
|
+
// what the list knows of it.
|
|
156
|
+
export function sessionDetail(dir, id) {
|
|
157
|
+
const file = sessionFile(dir, id);
|
|
158
|
+
const loaded = SessionStore.load(file);
|
|
159
|
+
const cwd = summarize(file).cwd;
|
|
160
|
+
const ctx = { cwd: cwd || os.homedir(), projectRoot: cwd || os.homedir() };
|
|
161
|
+
const items = transcriptItems(loaded.messages, { tools: toolsFor(cwd), ctx, cwd: ctx.cwd, limit: Infinity, images: true });
|
|
162
|
+
const st = fs.statSync(file);
|
|
163
|
+
return {
|
|
164
|
+
id, dir, cwd, title: loaded.name || loaded.topic || loaded.title || '(no prompt)', name: loaded.name, topic: loaded.topic,
|
|
165
|
+
count: loaded.messages.length, size: st.size, mtime: st.mtimeMs, cost: loaded.cost, created: loaded.meta.created || null,
|
|
166
|
+
items,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// The n-th image of a conversation's user messages: {mediaType, data (Buffer)} or null.
|
|
171
|
+
export function sessionImage(dir, id, n) {
|
|
172
|
+
const loaded = SessionStore.load(sessionFile(dir, id));
|
|
173
|
+
let i = 0;
|
|
174
|
+
for (const m of loaded.messages) {
|
|
175
|
+
if (m.role !== 'user' || typeof m.content === 'string') continue;
|
|
176
|
+
for (const b of m.content || []) {
|
|
177
|
+
if (b.type !== 'image') continue;
|
|
178
|
+
if (i++ === n) return b.source?.type === 'base64' ? { mediaType: b.source.media_type, data: Buffer.from(b.source.data, 'base64') } : null;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// The whole output of a tool call of a conversation (as the session's own remoteOutput gives it): the result's text,
|
|
185
|
+
// or the file a large one was saved to; at most 1 MB.
|
|
186
|
+
export function sessionToolOutput(dir, id, toolId) {
|
|
187
|
+
const loaded = SessionStore.load(sessionFile(dir, id));
|
|
188
|
+
let result = null;
|
|
189
|
+
for (const m of loaded.messages) {
|
|
190
|
+
if (m.role !== 'user' || !Array.isArray(m.content)) continue;
|
|
191
|
+
for (const b of m.content) if (b.type === 'tool_result' && b.tool_use_id === toolId) result = b;
|
|
192
|
+
}
|
|
193
|
+
if (!result) throw httpError(404, 'no such tool call');
|
|
194
|
+
let text = typeof result.content === 'string' ? result.content
|
|
195
|
+
: (Array.isArray(result.content) ? result.content : []).map((b) => (b.type === 'text' ? b.text : b.type === 'image' ? '[image]' : '')).join('\n');
|
|
196
|
+
const saved = /(?:saved to:?|saved at)\s+(\S+?\.txt)\b/.exec(text)?.[1];
|
|
197
|
+
if (saved && path.resolve(saved).startsWith(projectsRoot() + path.sep) && path.resolve(saved).includes(`${path.sep}tool-results${path.sep}`)) {
|
|
198
|
+
try { text = fs.readFileSync(saved, 'utf8'); } catch { /* the reference is what there is */ }
|
|
199
|
+
}
|
|
200
|
+
const MAX = 1024 * 1024;
|
|
201
|
+
const buf = Buffer.from(text, 'utf8');
|
|
202
|
+
return buf.length > MAX ? { text: buf.subarray(0, MAX).toString('utf8').replace(/\ufffd$/, ''), truncated: true } : { text };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// A conversation as Markdown: what was said, the tool calls as one line each (their results left out).
|
|
206
|
+
export function sessionMarkdown(dir, id) {
|
|
207
|
+
const d = sessionDetail(dir, id);
|
|
208
|
+
const out = [`# ${d.title}`, '', `- 会话 id:${d.id}`, `- 目录:${d.cwd || '未知'}`, `- 消息:${d.count} 条${d.cost ? ` · 花费 $${d.cost.toFixed(4)}` : ''}`, ''];
|
|
209
|
+
for (const it of d.items) {
|
|
210
|
+
if (it.k === 'user') out.push('## 用户', '', it.text, '');
|
|
211
|
+
else if (it.k === 'text') out.push('## claude-pro', '', it.text, '');
|
|
212
|
+
else if (it.k === 'tool') out.push(`> 🔧 ${stripAnsi(it.head || '')}${it.status === 'error' ? '(失败)' : ''}`, '');
|
|
213
|
+
else if (it.k === 'summary') out.push('## 压缩后的摘要', '', it.text, '');
|
|
214
|
+
else if (it.k === 'image') out.push('*[图片]*', '');
|
|
215
|
+
else if (it.k === 'output') {
|
|
216
|
+
const lines = it.lines.map((l) => stripAnsi(l)).join('\n').trim();
|
|
217
|
+
if (lines) out.push('```', lines, '```', '');
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return out.join('\n');
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// /rename for a conversation that is not running: its name, appended as the session does it.
|
|
224
|
+
export function renameSession(dir, id, name) {
|
|
225
|
+
const file = sessionFile(dir, id);
|
|
226
|
+
const clean = String(name ?? '').replace(/\s+/g, ' ').trim().slice(0, 80);
|
|
227
|
+
fs.appendFileSync(file, `${JSON.stringify({ type: 'meta', name: clean || null, at: Date.now() })}\n`);
|
|
228
|
+
return clean;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Deleting moves a conversation (with its trace) into the trash, kept TRASH_DAYS days.
|
|
232
|
+
export function trashSession(dir, id) {
|
|
233
|
+
const file = sessionFile(dir, id);
|
|
234
|
+
const info = summarize(file);
|
|
235
|
+
const stamp = Date.now();
|
|
236
|
+
const base = path.join(trashRoot(), `${stamp}__${dir}__${id}`);
|
|
237
|
+
fs.mkdirSync(base, { recursive: true });
|
|
238
|
+
fs.renameSync(file, path.join(base, `${id}.jsonl`));
|
|
239
|
+
for (const suffix of ['.jsonl', '.jsonl.1']) {
|
|
240
|
+
const trace = path.join(projectsRoot(), dir, 'traces', `${id}${suffix}`);
|
|
241
|
+
try { fs.renameSync(trace, path.join(base, `trace${suffix}`)); } catch { /* none */ }
|
|
242
|
+
}
|
|
243
|
+
fs.writeFileSync(path.join(base, 'info.json'), JSON.stringify({ dir, id, cwd: info.cwd, title: info.name || info.topic || info.firstPrompt || '(no prompt)', count: info.count, deletedAt: stamp }));
|
|
244
|
+
return { trashId: path.basename(base) };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function listTrash() {
|
|
248
|
+
purgeTrash();
|
|
249
|
+
let entries = [];
|
|
250
|
+
try { entries = fs.readdirSync(trashRoot()); } catch { return []; }
|
|
251
|
+
return entries.map((name) => {
|
|
252
|
+
try { return { trashId: name, ...JSON.parse(fs.readFileSync(path.join(trashRoot(), name, 'info.json'), 'utf8')) }; } catch { return null; }
|
|
253
|
+
}).filter(Boolean).sort((a, b) => b.deletedAt - a.deletedAt);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function trashEntry(trashId) {
|
|
257
|
+
if (!/^\d+__[\w.-]+__[\w-]+$/.test(trashId || '')) throw httpError(400, 'bad trash reference');
|
|
258
|
+
const base = path.join(trashRoot(), trashId);
|
|
259
|
+
let info;
|
|
260
|
+
try { info = JSON.parse(fs.readFileSync(path.join(base, 'info.json'), 'utf8')); } catch { throw httpError(404, '回收站里没有它了'); }
|
|
261
|
+
return { base, info };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export function restoreSession(trashId) {
|
|
265
|
+
const { base, info } = trashEntry(trashId);
|
|
266
|
+
const dir = path.join(projectsRoot(), info.dir);
|
|
267
|
+
const target = path.join(dir, `${info.id}.jsonl`);
|
|
268
|
+
if (fs.existsSync(target)) throw httpError(409, '同一个会话已经存在');
|
|
269
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
270
|
+
fs.renameSync(path.join(base, `${info.id}.jsonl`), target);
|
|
271
|
+
for (const suffix of ['.jsonl', '.jsonl.1']) {
|
|
272
|
+
const from = path.join(base, `trace${suffix}`);
|
|
273
|
+
if (!fs.existsSync(from)) continue;
|
|
274
|
+
fs.mkdirSync(path.join(dir, 'traces'), { recursive: true });
|
|
275
|
+
try { fs.renameSync(from, path.join(dir, 'traces', `${info.id}${suffix}`)); } catch { /* left in the trash */ }
|
|
276
|
+
}
|
|
277
|
+
fs.rmSync(base, { recursive: true, force: true });
|
|
278
|
+
return info;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export function purgeTrash({ all = false, trashId = null } = {}) {
|
|
282
|
+
let entries = [];
|
|
283
|
+
try { entries = fs.readdirSync(trashRoot()); } catch { return 0; }
|
|
284
|
+
let n = 0;
|
|
285
|
+
for (const name of entries) {
|
|
286
|
+
const at = Number(name.split('__')[0]);
|
|
287
|
+
if (trashId ? name !== trashId : !(all || !Number.isFinite(at) || Date.now() - at > TRASH_DAYS * 86_400_000)) continue;
|
|
288
|
+
try { fs.rmSync(path.join(trashRoot(), name), { recursive: true, force: true }); n++; } catch { /* next time */ }
|
|
289
|
+
}
|
|
290
|
+
return n;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// ---------------------------------------------------------------- running sessions
|
|
294
|
+
|
|
295
|
+
// GET or POST to a session's peer server (see PeerNode): resolves with {status, body}.
|
|
296
|
+
export function peerRequest(peer, method, route, body = undefined, { timeout = 3000 } = {}) {
|
|
297
|
+
return new Promise((resolve, reject) => {
|
|
298
|
+
const data = body === undefined ? null : JSON.stringify(body);
|
|
299
|
+
const req = http.request({
|
|
300
|
+
host: '127.0.0.1', port: peer.port, path: route, method, timeout,
|
|
301
|
+
headers: { authorization: `Bearer ${peer.token}`, ...(data ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) } : {}) },
|
|
302
|
+
}, (res) => {
|
|
303
|
+
let out = '';
|
|
304
|
+
res.setEncoding('utf8');
|
|
305
|
+
res.on('data', (d) => { out += d; });
|
|
306
|
+
res.on('end', () => {
|
|
307
|
+
let json = null;
|
|
308
|
+
try { json = JSON.parse(out); } catch { /* not JSON */ }
|
|
309
|
+
resolve({ status: res.statusCode, body: json });
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
req.on('timeout', () => req.destroy(new Error('the session did not answer')));
|
|
313
|
+
req.on('error', reject);
|
|
314
|
+
req.end(data);
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// The sessions running on this computer now, each with what it says of itself (GET /status).
|
|
319
|
+
export async function runningSessions() {
|
|
320
|
+
const peers = listPeers();
|
|
321
|
+
return await Promise.all(peers.map(async (p) => {
|
|
322
|
+
let status = {};
|
|
323
|
+
try { status = (await peerRequest(p, 'GET', '/status', undefined, { timeout: 2000 })).body || {}; } catch { /* busy or gone: listed with what its file says */ }
|
|
324
|
+
return { peerId: p.id, name: p.name, cwd: p.cwd, pid: p.pid, startedAt: p.startedAt, status };
|
|
325
|
+
}));
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
export function findPeerById(peerId) {
|
|
329
|
+
const peer = listPeers().find((p) => p.id === peerId);
|
|
330
|
+
if (!peer) throw httpError(404, '这个会话已经不在运行');
|
|
331
|
+
return peer;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// ---------------------------------------------------------------- usage (from the traces)
|
|
335
|
+
|
|
336
|
+
const usageMemo = new Map(); // trace file -> {mtime, size, rows}
|
|
337
|
+
const localDay = (iso) => {
|
|
338
|
+
const d = new Date(iso);
|
|
339
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
function traceRows(file) {
|
|
343
|
+
let st;
|
|
344
|
+
try { st = fs.statSync(file); } catch { return []; }
|
|
345
|
+
const kept = usageMemo.get(file);
|
|
346
|
+
if (kept && kept.mtime === st.mtimeMs && kept.size === st.size) return kept.rows;
|
|
347
|
+
const rows = [];
|
|
348
|
+
let text = '';
|
|
349
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
|
|
350
|
+
for (const line of text.split('\n')) {
|
|
351
|
+
if (!line.includes('"type":"request_end"')) continue;
|
|
352
|
+
let e;
|
|
353
|
+
try { e = JSON.parse(line); } catch { continue; }
|
|
354
|
+
if (!e.ok && !e.output_tokens) continue;
|
|
355
|
+
const usage = { input_tokens: e.input_tokens, output_tokens: e.output_tokens, cache_read_input_tokens: e.cache_read_tokens, cache_creation_input_tokens: e.cache_write_tokens };
|
|
356
|
+
rows.push({ day: localDay(e.time), model: e.model || '?', session: e.session_id, input: e.input_tokens || 0, output: e.output_tokens || 0, cacheRead: e.cache_read_tokens || 0, cacheWrite: e.cache_write_tokens || 0, cost: costOf(e.model, usage) });
|
|
357
|
+
}
|
|
358
|
+
usageMemo.set(file, { mtime: st.mtimeMs, size: st.size, rows });
|
|
359
|
+
return rows;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// Tokens and (where the model has a price here) cost by day, model and project, from every project's traces; and
|
|
363
|
+
// each conversation's own total (its meta), which covers what the traces do not price.
|
|
364
|
+
export function usageReport({ days = 30 } = {}) {
|
|
365
|
+
const since = localDay(new Date(Date.now() - (days - 1) * 86_400_000).toISOString());
|
|
366
|
+
const byDay = new Map();
|
|
367
|
+
const byModel = new Map();
|
|
368
|
+
const byProject = new Map();
|
|
369
|
+
const add = (map, key, r) => {
|
|
370
|
+
const e = map.get(key) || { key, requests: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, unpriced: 0 };
|
|
371
|
+
e.requests++;
|
|
372
|
+
e.input += r.input; e.output += r.output; e.cacheRead += r.cacheRead; e.cacheWrite += r.cacheWrite;
|
|
373
|
+
if (r.cost == null) e.unpriced++; else e.cost += r.cost;
|
|
374
|
+
map.set(key, e);
|
|
375
|
+
};
|
|
376
|
+
const sessions = listAllSessions();
|
|
377
|
+
const cwdOfDir = new Map(sessions.filter((s) => s.cwd).map((s) => [s.dir, s.cwd]));
|
|
378
|
+
let dirs = [];
|
|
379
|
+
try { dirs = fs.readdirSync(projectsRoot(), { withFileTypes: true }).filter((d) => d.isDirectory()); } catch { /* none */ }
|
|
380
|
+
for (const d of dirs) {
|
|
381
|
+
const traces = path.join(projectsRoot(), d.name, 'traces');
|
|
382
|
+
let files = [];
|
|
383
|
+
try { files = fs.readdirSync(traces).filter((f) => /\.jsonl(\.\d+)?$/.test(f)); } catch { continue; }
|
|
384
|
+
for (const f of files) {
|
|
385
|
+
for (const r of traceRows(path.join(traces, f))) {
|
|
386
|
+
if (r.day < since) continue;
|
|
387
|
+
add(byDay, r.day, r);
|
|
388
|
+
add(byModel, r.model, r);
|
|
389
|
+
add(byProject, cwdOfDir.get(d.name) || d.name, r);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
const dayList = [];
|
|
394
|
+
for (let i = days - 1; i >= 0; i--) {
|
|
395
|
+
const key = localDay(new Date(Date.now() - i * 86_400_000).toISOString());
|
|
396
|
+
dayList.push(byDay.get(key) || { key, requests: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, unpriced: 0 });
|
|
397
|
+
}
|
|
398
|
+
const sortCost = (a, b) => b.cost - a.cost || b.requests - a.requests;
|
|
399
|
+
return {
|
|
400
|
+
days: dayList,
|
|
401
|
+
models: [...byModel.values()].sort(sortCost),
|
|
402
|
+
projects: [...byProject.values()].sort(sortCost),
|
|
403
|
+
sessions: sessions.filter((s) => s.cost > 0).sort((a, b) => b.cost - a.cost).slice(0, 30)
|
|
404
|
+
.map(({ id, dir, cwd, title, cost, mtime }) => ({ id, dir, cwd, title, cost, mtime })),
|
|
405
|
+
totalSessionCost: sessions.reduce((sum, s) => sum + s.cost, 0),
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// ---------------------------------------------------------------- disk
|
|
410
|
+
|
|
411
|
+
export function dirSize(dir) {
|
|
412
|
+
let total = 0;
|
|
413
|
+
const walk = (d) => {
|
|
414
|
+
let entries = [];
|
|
415
|
+
try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch { return; }
|
|
416
|
+
for (const e of entries) {
|
|
417
|
+
const p = path.join(d, e.name);
|
|
418
|
+
if (e.isDirectory()) walk(p);
|
|
419
|
+
else { try { total += fs.statSync(p).size; } catch { /* gone */ } }
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
walk(dir);
|
|
423
|
+
return total;
|
|
424
|
+
}
|