llmtop 0.1.3 → 0.1.5
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 +20 -4
- package/bin/llmtop.mjs +34 -6
- package/package.json +1 -1
- package/src/api.mjs +6 -1
- package/src/db.mjs +5 -2
- package/src/process.mjs +205 -14
- package/src/providers/codex.mjs +121 -19
- package/src/serve.mjs +20 -10
- package/src/update.mjs +59 -5
package/README.md
CHANGED
|
@@ -24,10 +24,10 @@
|
|
|
24
24
|
|
|
25
25
|
```bash
|
|
26
26
|
npm install -g llmtop
|
|
27
|
-
llmtop
|
|
27
|
+
llmtop start # Run in background (survives closing the terminal); llmtop stop to end
|
|
28
28
|
```
|
|
29
29
|
|
|
30
|
-
Or run without installing
|
|
30
|
+
Or run in the foreground with `llmtop serve`, or without installing via `npx llmtop serve`. Open <http://localhost:4310>.
|
|
31
31
|
|
|
32
32
|
- **Local-only:** Binds `127.0.0.1` only; zero telemetry, zero background network requests (only `llmtop update` contacts npmjs when invoked), zero runtime npm dependencies.
|
|
33
33
|
- **Zero setup:** Automatically reads `~/.claude/projects`, `~/.codex/sessions`, and `~/.gemini/antigravity-cli`, skipping absent tools.
|
|
@@ -90,19 +90,35 @@ Or run without installing: `npx llmtop serve`. Open <http://localhost:4310>.
|
|
|
90
90
|
CLI and dashboard totals stay identical for the same window and filters (`--json` supported on listing commands).
|
|
91
91
|
|
|
92
92
|
```bash
|
|
93
|
-
llmtop
|
|
93
|
+
llmtop start [--port n] # Start dashboard in background (log ~/.config/llmtop/data/serve.log)
|
|
94
|
+
llmtop serve [--port n] [--daemon] # Dashboard at http://localhost:4310 (--daemon detaches like start)
|
|
94
95
|
llmtop stop # Stop the running dashboard server
|
|
95
96
|
llmtop scan # Archive new transcript lines into usage.db
|
|
96
97
|
llmtop usage [--days n | --since d --until d] [--by day|model|provider|effort|project|session|hour|tool|skill|subagent]
|
|
97
98
|
[--provider name] [--project name] [--model family] [--effort level] [--json]
|
|
98
99
|
llmtop prices [--json] # Verify prices.md against host cost records
|
|
99
100
|
llmtop show <session>:<line> # Print one archived record
|
|
100
|
-
llmtop update [--check] [--json]
|
|
101
|
+
llmtop update [--check] [--json] [--force] # Check npmjs or upgrade to the latest release
|
|
101
102
|
llmtop uninstall [--purge] [--dry-run] [--yes]
|
|
102
103
|
# Stop llmtop and remove the global installation
|
|
103
104
|
llmtop --help | --version
|
|
104
105
|
```
|
|
105
106
|
|
|
107
|
+
## Update & Uninstall
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
llmtop update --check # Check npmjs for a newer release (supports --json)
|
|
111
|
+
llmtop update # Upgrade the global installation to the latest release
|
|
112
|
+
llmtop stop # Stop a running llmtop serve process
|
|
113
|
+
llmtop uninstall --dry-run # Preview what uninstall will stop, remove, or keep
|
|
114
|
+
llmtop uninstall # Stop llmtop and remove the global package (keeps ~/.config/llmtop)
|
|
115
|
+
llmtop uninstall --purge # Also remove ~/.config/llmtop (config, archive, and usage.db)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
- **`llmtop start`** (or `llmtop serve --daemon`) detaches the dashboard from the terminal and writes logs to `~/.config/llmtop/data/serve.log` (using `systemd-run --user` on systemd Linux so closing the terminal will not stop it). Run `llmtop stop` to end it.
|
|
119
|
+
- **`llmtop update`** queries `registry.npmjs.org` only when invoked (never in the background), detects your global package manager (`npm`, `pnpm`, `yarn`, or `bun`), automatically stops a running background daemon (`llmtop start` / `--daemon`) before upgrading and restarts it on the new version, and warns if a foreground `llmtop serve` is running so you can restart it afterward. From a local Git checkout or `npx`, it prints manual steps unless `--force` is passed.
|
|
120
|
+
- **`llmtop uninstall`** stops running `llmtop serve` processes, removes the global package, and asks for confirmation in interactive terminals (pass `--yes` or `-y` in scripts). By default it keeps `~/.config/llmtop`; add `--purge` to delete local config, archive, and SQLite data. Original provider transcripts (`~/.claude`, `~/.codex`, `~/.gemini/antigravity-cli`) are never touched.
|
|
121
|
+
|
|
106
122
|
## Configuration
|
|
107
123
|
|
|
108
124
|
Optional settings live in `~/.config/llmtop/config.json` (see [llmtop.config.example.json](https://github.com/nguyencanhtrung/llmtop/blob/main/llmtop.config.example.json)). Override paths with `XDG_CONFIG_HOME`, `LLMTOP_CONFIG`, or `LLMTOP_DATA`. Token rates come from [prices.md](https://github.com/nguyencanhtrung/llmtop/blob/main/prices.md).
|
package/bin/llmtop.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { join } from "node:path";
|
|
|
4
4
|
import { defaultConfigDir, defaultConfigPath, loadConfig, ROOT } from "../src/config.mjs";
|
|
5
5
|
import { localTime } from "../src/format.mjs";
|
|
6
6
|
import { pricesCommand } from "../src/prices-command.mjs";
|
|
7
|
-
import { stopCommand, writeServerState } from "../src/process.mjs";
|
|
7
|
+
import { startCommand, stopCommand, writeServerState } from "../src/process.mjs";
|
|
8
8
|
import { scan, scanReport } from "../src/scan.mjs";
|
|
9
9
|
import { serve } from "../src/serve.mjs";
|
|
10
10
|
import { show } from "../src/show.mjs";
|
|
@@ -21,7 +21,8 @@ const USAGE = `usage: llmtop <command> [options]
|
|
|
21
21
|
usage [--days n | --since d --until d] [--by day|model|provider|effort|project|session|hour|tool|skill|subagent]
|
|
22
22
|
[--provider name] [--project name] [--model family] [--effort level]
|
|
23
23
|
prices the price table checked against the host's cost records
|
|
24
|
-
serve [--port n]
|
|
24
|
+
serve [--port n] [--daemon] the built dashboard on http://localhost:<port>
|
|
25
|
+
start [--port n] start the dashboard in the background
|
|
25
26
|
stop stop the running llmtop serve process
|
|
26
27
|
update [--check] [--force] check npmjs or upgrade llmtop to the latest version
|
|
27
28
|
uninstall [--purge] [--dry-run] [--yes]
|
|
@@ -46,6 +47,14 @@ function loadConfigOrDefault() {
|
|
|
46
47
|
}
|
|
47
48
|
}
|
|
48
49
|
|
|
50
|
+
function parsePort(options, config) {
|
|
51
|
+
const port = options.port === undefined ? config.port : Number(options.port);
|
|
52
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
53
|
+
throw new UsageError(`--port needs a port number, got ${options.port}`);
|
|
54
|
+
}
|
|
55
|
+
return port;
|
|
56
|
+
}
|
|
57
|
+
|
|
49
58
|
const COMMANDS = {
|
|
50
59
|
async scan({ config, out }) {
|
|
51
60
|
const t = await scan(config);
|
|
@@ -57,11 +66,22 @@ const COMMANDS = {
|
|
|
57
66
|
},
|
|
58
67
|
usage: usageCommand,
|
|
59
68
|
async serve({ config, options, out }) {
|
|
60
|
-
const port = options
|
|
61
|
-
if (
|
|
69
|
+
const port = parsePort(options, config);
|
|
70
|
+
if (options.daemon) {
|
|
71
|
+
return startCommand({ config, options: { ...options, port }, out });
|
|
72
|
+
}
|
|
73
|
+
if (process.env.LLMTOP_DAEMON === "1") {
|
|
74
|
+
process.on("SIGHUP", () => {});
|
|
75
|
+
}
|
|
62
76
|
const at = localTime(config.timeZone);
|
|
63
77
|
const server = await serve(config, { port, onScan: (t) => reportScan(t, out, `${at(new Date().toISOString())} `) });
|
|
64
|
-
const cleanup = writeServerState(config, {
|
|
78
|
+
const cleanup = writeServerState(config, {
|
|
79
|
+
pid: process.pid,
|
|
80
|
+
port: server.address().port,
|
|
81
|
+
version: VERSION,
|
|
82
|
+
token: process.env.LLMTOP_DAEMON_TOKEN,
|
|
83
|
+
daemon: process.env.LLMTOP_DAEMON === "1",
|
|
84
|
+
});
|
|
65
85
|
server.once("close", cleanup);
|
|
66
86
|
let closing = false;
|
|
67
87
|
const shutdown = () => {
|
|
@@ -75,6 +95,10 @@ const COMMANDS = {
|
|
|
75
95
|
process.once("SIGTERM", shutdown);
|
|
76
96
|
out.write(`dashboard at http://localhost:${server.address().port}: its Refresh button scans again, Ctrl+C to stop\n`);
|
|
77
97
|
},
|
|
98
|
+
async start({ config, options, out }) {
|
|
99
|
+
const port = parsePort(options, config);
|
|
100
|
+
return startCommand({ config, options: { ...options, port }, out });
|
|
101
|
+
},
|
|
78
102
|
prices: pricesCommand,
|
|
79
103
|
stop: stopCommand,
|
|
80
104
|
update: updateCommand,
|
|
@@ -82,7 +106,7 @@ const COMMANDS = {
|
|
|
82
106
|
};
|
|
83
107
|
|
|
84
108
|
// Options are --name value or --flag; FLAGS lists the ones without a value.
|
|
85
|
-
const FLAGS = new Set(["json", "check", "force", "purge", "dry-run", "yes"]);
|
|
109
|
+
const FLAGS = new Set(["json", "check", "force", "purge", "dry-run", "yes", "daemon"]);
|
|
86
110
|
const LENIENT_CONFIG_COMMANDS = new Set(["stop", "update", "uninstall"]);
|
|
87
111
|
function parseArgs(argv) {
|
|
88
112
|
const positional = [];
|
|
@@ -93,6 +117,10 @@ function parseArgs(argv) {
|
|
|
93
117
|
options.yes = true;
|
|
94
118
|
continue;
|
|
95
119
|
}
|
|
120
|
+
if (arg === "-d") {
|
|
121
|
+
options.daemon = true;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
96
124
|
if (!arg.startsWith("--")) {
|
|
97
125
|
positional.push(arg);
|
|
98
126
|
continue;
|
package/package.json
CHANGED
package/src/api.mjs
CHANGED
|
@@ -28,7 +28,12 @@ export function createApi(config, { onScan = () => {}, routes: extra = {} } = {}
|
|
|
28
28
|
},
|
|
29
29
|
};
|
|
30
30
|
return (req, res) => {
|
|
31
|
-
|
|
31
|
+
let path;
|
|
32
|
+
try {
|
|
33
|
+
path = new URL(req.url, "http://localhost").pathname;
|
|
34
|
+
} catch {
|
|
35
|
+
return Promise.resolve(false);
|
|
36
|
+
}
|
|
32
37
|
if (!path.startsWith("/api/")) return Promise.resolve(false);
|
|
33
38
|
if (req.method === "GET" && path === "/api/scan/progress") {
|
|
34
39
|
res.writeHead(200, JSON_TYPE).end(JSON.stringify(progress));
|
package/src/db.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { dirname } from "node:path";
|
|
|
3
3
|
import { DatabaseSync } from "node:sqlite";
|
|
4
4
|
|
|
5
5
|
// Bump when the schema changes: the database is then rebuilt from the archive.
|
|
6
|
-
export const SCHEMA_VERSION =
|
|
6
|
+
export const SCHEMA_VERSION = 14;
|
|
7
7
|
|
|
8
8
|
const SCHEMA = `
|
|
9
9
|
CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT);
|
|
@@ -43,7 +43,8 @@ CREATE INDEX skills_session ON skills(session_id);
|
|
|
43
43
|
CREATE INDEX skills_file ON skills(file_id);
|
|
44
44
|
CREATE TABLE subagents(agent_id TEXT PRIMARY KEY, session_id TEXT, type TEXT, tool_use_id TEXT);
|
|
45
45
|
CREATE TABLE file_meta(file_id INTEGER PRIMARY KEY, parent_session_id TEXT, subagent_type TEXT, tool_use_id TEXT,
|
|
46
|
-
api_ms INTEGER, tool_ms INTEGER, lines_added INTEGER, lines_removed INTEGER, repo_url TEXT, target_paths TEXT
|
|
46
|
+
api_ms INTEGER, tool_ms INTEGER, lines_added INTEGER, lines_removed INTEGER, repo_url TEXT, target_paths TEXT,
|
|
47
|
+
parser_state TEXT);
|
|
47
48
|
CREATE TABLE compactions(uuid TEXT PRIMARY KEY, file_id INTEGER, line INTEGER, session_id TEXT, agent_id TEXT, ts TEXT,
|
|
48
49
|
trigger TEXT, pre_tokens INTEGER, post_tokens INTEGER, duration_ms INTEGER);
|
|
49
50
|
CREATE INDEX compactions_session ON compactions(session_id);
|
|
@@ -73,6 +74,8 @@ function configureDb(db) {
|
|
|
73
74
|
function upgradeInPlace(db) {
|
|
74
75
|
const cols = db.prepare("PRAGMA table_info(files)").all();
|
|
75
76
|
if (!cols.some((c) => c.name === "ctime_ms")) db.exec("ALTER TABLE files ADD COLUMN ctime_ms REAL");
|
|
77
|
+
const fmCols = db.prepare("PRAGMA table_info(file_meta)").all();
|
|
78
|
+
if (!fmCols.some((c) => c.name === "parser_state")) db.exec("ALTER TABLE file_meta ADD COLUMN parser_state TEXT");
|
|
76
79
|
db.exec(`
|
|
77
80
|
CREATE INDEX IF NOT EXISTS requests_file ON requests(file_id);
|
|
78
81
|
CREATE INDEX IF NOT EXISTS tool_calls_file ON tool_calls(file_id);
|
package/src/process.mjs
CHANGED
|
@@ -1,18 +1,24 @@
|
|
|
1
|
-
import { spawnSync } from "node:child_process";
|
|
2
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
import { ROOT } from "./config.mjs";
|
|
1
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { defaultConfigDir, ROOT } from "./config.mjs";
|
|
5
5
|
|
|
6
6
|
export function serverStatePath(config) {
|
|
7
7
|
return join(config.data, "serve.json");
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
+
export function serverLogPath(config) {
|
|
11
|
+
return join(config.data, "serve.log");
|
|
12
|
+
}
|
|
13
|
+
|
|
10
14
|
// Writes serve.json atomically and returns a cleanup callback that removes it only if the PID still matches.
|
|
11
|
-
export function writeServerState(config, { pid = process.pid, port, version }) {
|
|
15
|
+
export function writeServerState(config, { pid = process.pid, port, version, token, daemon = false }) {
|
|
12
16
|
const path = serverStatePath(config);
|
|
13
17
|
mkdirSync(config.data, { recursive: true });
|
|
14
18
|
const tmp = join(config.data, `.serve.${pid}.${process.hrtime.bigint()}.tmp`);
|
|
15
|
-
const
|
|
19
|
+
const body = { pid, port, startedAt: new Date().toISOString(), version, daemon: Boolean(daemon) };
|
|
20
|
+
if (token !== undefined) body.token = token;
|
|
21
|
+
const payload = JSON.stringify(body, null, 2);
|
|
16
22
|
writeFileSync(tmp, `${payload}\n`);
|
|
17
23
|
renameSync(tmp, path);
|
|
18
24
|
return () => {
|
|
@@ -88,16 +94,44 @@ function parsePortFromCommand(command) {
|
|
|
88
94
|
return match ? Number(match[1]) : null;
|
|
89
95
|
}
|
|
90
96
|
|
|
97
|
+
function readProcEnv(pid, readFile = readFileSync) {
|
|
98
|
+
try {
|
|
99
|
+
const raw = readFile(`/proc/${pid}/environ`, "utf8");
|
|
100
|
+
const env = {};
|
|
101
|
+
for (const entry of raw.split("\0")) {
|
|
102
|
+
const idx = entry.indexOf("=");
|
|
103
|
+
if (idx > 0) env[entry.slice(0, idx)] = entry.slice(idx + 1);
|
|
104
|
+
}
|
|
105
|
+
return env;
|
|
106
|
+
} catch {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function belongsToConfig(pid, config, env, readFile) {
|
|
112
|
+
const procEnv = readProcEnv(pid, readFile);
|
|
113
|
+
if (!procEnv) return true;
|
|
114
|
+
if (procEnv.LLMTOP_DATA && resolve(procEnv.LLMTOP_DATA) !== resolve(config.data)) return false;
|
|
115
|
+
if (procEnv.LLMTOP_CONFIG && config.configPath && resolve(procEnv.LLMTOP_CONFIG) !== resolve(config.configPath)) return false;
|
|
116
|
+
if (procEnv.XDG_CONFIG_HOME !== env.XDG_CONFIG_HOME) return false;
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
|
|
91
120
|
export function findRunningServers(config, deps = {}) {
|
|
92
121
|
const {
|
|
93
|
-
listProcesses
|
|
122
|
+
listProcesses,
|
|
94
123
|
isAlive = isPidAlive,
|
|
95
124
|
selfPid = process.pid,
|
|
96
125
|
root = ROOT,
|
|
126
|
+
env = process.env,
|
|
97
127
|
exists = existsSync,
|
|
98
128
|
readFile = readFileSync,
|
|
99
129
|
} = deps;
|
|
100
|
-
const
|
|
130
|
+
const defaultDataDir = resolve(join(defaultConfigDir(env), "data"));
|
|
131
|
+
const isDefaultData = resolve(config.data) === defaultDataDir;
|
|
132
|
+
const isRepoData = resolve(config.data) === resolve(join(root, "data"));
|
|
133
|
+
const scanProcesses = deps.includeProcessScan ?? (Boolean(listProcesses) || isDefaultData);
|
|
134
|
+
const osList = (listProcesses ?? listOsProcesses)();
|
|
101
135
|
const osByPid = new Map(osList.map((p) => [p.pid, p]));
|
|
102
136
|
const byPid = new Map();
|
|
103
137
|
let staleState = false;
|
|
@@ -110,7 +144,7 @@ export function findRunningServers(config, deps = {}) {
|
|
|
110
144
|
const osEntry = osByPid.get(state.pid);
|
|
111
145
|
const matchesOs = osList.length === 0 || (osEntry && isLlmtopServeCommand(osEntry.command));
|
|
112
146
|
if (isAlive(state.pid) && matchesOs) {
|
|
113
|
-
byPid.set(state.pid, { pid: state.pid, port: state.port ?? null, source: "state" });
|
|
147
|
+
byPid.set(state.pid, { pid: state.pid, port: state.port ?? null, source: "state", daemon: Boolean(state.daemon) });
|
|
114
148
|
} else {
|
|
115
149
|
staleState = true;
|
|
116
150
|
}
|
|
@@ -121,7 +155,7 @@ export function findRunningServers(config, deps = {}) {
|
|
|
121
155
|
}
|
|
122
156
|
|
|
123
157
|
const pidFile = join(root, "data", "serve.pid");
|
|
124
|
-
if (exists(pidFile)) {
|
|
158
|
+
if (isRepoData && exists(pidFile)) {
|
|
125
159
|
try {
|
|
126
160
|
const pid = Number(readFile(pidFile, "utf8").trim());
|
|
127
161
|
if (Number.isInteger(pid) && pid > 0 && pid !== selfPid && isAlive(pid)) {
|
|
@@ -129,7 +163,7 @@ export function findRunningServers(config, deps = {}) {
|
|
|
129
163
|
if (osEntry && isLlmtopServeCommand(osEntry.command)) {
|
|
130
164
|
const existing = byPid.get(pid);
|
|
131
165
|
if (existing) existing.pidFile = pidFile;
|
|
132
|
-
else byPid.set(pid, { pid, port: parsePortFromCommand(osEntry.command), source: "pidfile", pidFile });
|
|
166
|
+
else byPid.set(pid, { pid, port: parsePortFromCommand(osEntry.command), source: "pidfile", pidFile, daemon: false });
|
|
133
167
|
}
|
|
134
168
|
}
|
|
135
169
|
} catch {
|
|
@@ -137,9 +171,12 @@ export function findRunningServers(config, deps = {}) {
|
|
|
137
171
|
}
|
|
138
172
|
}
|
|
139
173
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
174
|
+
if (scanProcesses) {
|
|
175
|
+
for (const proc of osList) {
|
|
176
|
+
if (proc.pid === selfPid || byPid.has(proc.pid) || !isLlmtopServeCommand(proc.command)) continue;
|
|
177
|
+
if (!listProcesses && !belongsToConfig(proc.pid, config, env, readFile)) continue;
|
|
178
|
+
byPid.set(proc.pid, { pid: proc.pid, port: parsePortFromCommand(proc.command), source: "process", daemon: false });
|
|
179
|
+
}
|
|
143
180
|
}
|
|
144
181
|
|
|
145
182
|
return { servers: [...byPid.values()].sort((a, b) => a.pid - b.pid), staleState };
|
|
@@ -235,3 +272,157 @@ export async function stopCommand({ config, out, err = process.stderr, deps = {}
|
|
|
235
272
|
}
|
|
236
273
|
return 0;
|
|
237
274
|
}
|
|
275
|
+
|
|
276
|
+
const FORWARDED_DAEMON_ENV = [
|
|
277
|
+
"HOME",
|
|
278
|
+
"PATH",
|
|
279
|
+
"USER",
|
|
280
|
+
"TZ",
|
|
281
|
+
"XDG_CONFIG_HOME",
|
|
282
|
+
"LLMTOP_CONFIG",
|
|
283
|
+
"LLMTOP_DATA",
|
|
284
|
+
"NODE_OPTIONS",
|
|
285
|
+
];
|
|
286
|
+
|
|
287
|
+
export function canUseSystemdUser({ platform = process.platform, spawn: spawnCmd = spawnSync, env = process.env } = {}) {
|
|
288
|
+
if (platform !== "linux" || env.LLMTOP_NO_SYSTEMD === "1") return false;
|
|
289
|
+
try {
|
|
290
|
+
const version = spawnCmd("systemd-run", ["--version"], { encoding: "utf8", stdio: "pipe" });
|
|
291
|
+
if (version.status !== 0) return false;
|
|
292
|
+
const mgr = spawnCmd("systemctl", ["--user", "show-environment"], { encoding: "utf8", stdio: "pipe" });
|
|
293
|
+
return mgr.status === 0;
|
|
294
|
+
} catch {
|
|
295
|
+
return false;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function readAppendedLog(logPath, startOffset, exists, readFile) {
|
|
300
|
+
if (!exists(logPath)) return "";
|
|
301
|
+
try {
|
|
302
|
+
const buf = readFile(logPath);
|
|
303
|
+
return buf.subarray(startOffset).toString("utf8").trim();
|
|
304
|
+
} catch {
|
|
305
|
+
return "";
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export async function startBackgroundServer(config, { port, deps = {} } = {}) {
|
|
310
|
+
const {
|
|
311
|
+
env = process.env,
|
|
312
|
+
platform = process.platform,
|
|
313
|
+
root = ROOT,
|
|
314
|
+
binPath = join(ROOT, "bin", "llmtop.mjs"),
|
|
315
|
+
execPath = process.execPath,
|
|
316
|
+
spawn: spawnChild = spawn,
|
|
317
|
+
spawnSync: spawnCmd = spawnSync,
|
|
318
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
319
|
+
timeoutMs = 5000,
|
|
320
|
+
isAlive = isPidAlive,
|
|
321
|
+
exists = existsSync,
|
|
322
|
+
readFile = readFileSync,
|
|
323
|
+
stat = statSync,
|
|
324
|
+
mkdir = mkdirSync,
|
|
325
|
+
unlink = unlinkSync,
|
|
326
|
+
open = openSync,
|
|
327
|
+
close = closeSync,
|
|
328
|
+
canUseSystemd = canUseSystemdUser,
|
|
329
|
+
} = deps;
|
|
330
|
+
|
|
331
|
+
const { servers, staleState } = findRunningServers(config, { ...deps, root, isAlive, exists, readFile });
|
|
332
|
+
if (servers.length > 0) {
|
|
333
|
+
return { ok: false, alreadyRunning: true, server: servers[0] };
|
|
334
|
+
}
|
|
335
|
+
if (staleState) {
|
|
336
|
+
try {
|
|
337
|
+
unlink(serverStatePath(config));
|
|
338
|
+
} catch {
|
|
339
|
+
// Ignore already-deleted stale state file.
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
mkdir(config.data, { recursive: true });
|
|
344
|
+
const logPath = serverLogPath(config);
|
|
345
|
+
const startOffset = exists(logPath) ? stat(logPath).size : 0;
|
|
346
|
+
const token = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
|
347
|
+
const childArgs = [binPath, "serve", ...(port !== undefined ? ["--port", String(port)] : [])];
|
|
348
|
+
|
|
349
|
+
let mode = null;
|
|
350
|
+
let unit = null;
|
|
351
|
+
let child = null;
|
|
352
|
+
|
|
353
|
+
if (canUseSystemd({ platform, spawn: spawnCmd, env })) {
|
|
354
|
+
unit = `llmtop-serve-${Date.now()}-${process.pid}`;
|
|
355
|
+
const setenvArgs = [];
|
|
356
|
+
for (const key of FORWARDED_DAEMON_ENV) {
|
|
357
|
+
if (env[key] !== undefined) setenvArgs.push(`--setenv=${key}=${env[key]}`);
|
|
358
|
+
}
|
|
359
|
+
setenvArgs.push("--setenv=LLMTOP_DAEMON=1", `--setenv=LLMTOP_DAEMON_TOKEN=${token}`);
|
|
360
|
+
const systemdArgs = [
|
|
361
|
+
"--user",
|
|
362
|
+
"--collect",
|
|
363
|
+
"--no-block",
|
|
364
|
+
`--unit=${unit}`,
|
|
365
|
+
"--description=llmtop local dashboard",
|
|
366
|
+
`--property=WorkingDirectory=${config.data}`,
|
|
367
|
+
`--property=StandardOutput=append:${logPath}`,
|
|
368
|
+
`--property=StandardError=append:${logPath}`,
|
|
369
|
+
...setenvArgs,
|
|
370
|
+
execPath,
|
|
371
|
+
...childArgs,
|
|
372
|
+
];
|
|
373
|
+
const res = spawnCmd("systemd-run", systemdArgs, { encoding: "utf8", stdio: "pipe" });
|
|
374
|
+
if (res.status === 0) mode = "systemd";
|
|
375
|
+
else unit = null;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
if (!mode) {
|
|
379
|
+
const logFd = open(logPath, "a");
|
|
380
|
+
try {
|
|
381
|
+
child = spawnChild(execPath, childArgs, {
|
|
382
|
+
detached: true,
|
|
383
|
+
stdio: ["ignore", logFd, logFd],
|
|
384
|
+
env: { ...env, LLMTOP_DAEMON: "1", LLMTOP_DAEMON_TOKEN: token },
|
|
385
|
+
});
|
|
386
|
+
} finally {
|
|
387
|
+
close(logFd);
|
|
388
|
+
}
|
|
389
|
+
child.unref();
|
|
390
|
+
mode = "detached";
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const deadline = Date.now() + timeoutMs;
|
|
394
|
+
while (Date.now() < deadline) {
|
|
395
|
+
const state = readServerState(config, { exists, readFile });
|
|
396
|
+
if (state && state.token === token && isAlive(state.pid)) {
|
|
397
|
+
return { ok: true, pid: state.pid, port: state.port, logPath, mode, unit };
|
|
398
|
+
}
|
|
399
|
+
if (mode === "detached" && child?.exitCode !== null) break;
|
|
400
|
+
if (mode === "systemd") {
|
|
401
|
+
const appended = readAppendedLog(logPath, startOffset, exists, readFile);
|
|
402
|
+
if (/^error:/m.test(appended)) break;
|
|
403
|
+
}
|
|
404
|
+
await sleep(50);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const appended = readAppendedLog(logPath, startOffset, exists, readFile);
|
|
408
|
+
return {
|
|
409
|
+
ok: false,
|
|
410
|
+
error: appended || "timed out waiting for llmtop serve to start",
|
|
411
|
+
logPath,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
export async function startCommand({ config, options = {}, out, err = process.stderr, deps = {} }) {
|
|
416
|
+
const res = await startBackgroundServer(config, { port: options.port, deps });
|
|
417
|
+
if (res.alreadyRunning) {
|
|
418
|
+
const where = res.server.port ? `, http://localhost:${res.server.port}` : "";
|
|
419
|
+
err.write(`llmtop serve is already running (pid ${res.server.pid}${where}); run \`llmtop stop\` first\n`);
|
|
420
|
+
return 1;
|
|
421
|
+
}
|
|
422
|
+
if (!res.ok) {
|
|
423
|
+
err.write(`${res.error}\n`);
|
|
424
|
+
return 1;
|
|
425
|
+
}
|
|
426
|
+
out.write(`dashboard at http://localhost:${res.port} in the background (pid ${res.pid}, log ${res.logPath}); run \`llmtop stop\` to stop\n`);
|
|
427
|
+
return 0;
|
|
428
|
+
}
|
package/src/providers/codex.mjs
CHANGED
|
@@ -222,6 +222,18 @@ function extractDollarSkills(text) {
|
|
|
222
222
|
return [...seen];
|
|
223
223
|
}
|
|
224
224
|
|
|
225
|
+
const str = (v) => (typeof v === "string" && v ? v : null);
|
|
226
|
+
const modelOf = (v) => str(v) ?? str(v?.model);
|
|
227
|
+
function parseParserState(raw) {
|
|
228
|
+
if (!raw) return null;
|
|
229
|
+
try {
|
|
230
|
+
const o = JSON.parse(raw);
|
|
231
|
+
return o && typeof o === "object" ? o : null;
|
|
232
|
+
} catch {
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
225
237
|
export function createIngester(db, timeZone) {
|
|
226
238
|
const zone = zoner(timeZone);
|
|
227
239
|
const q = {
|
|
@@ -241,12 +253,17 @@ export function createIngester(db, timeZone) {
|
|
|
241
253
|
subagent_type = COALESCE(excluded.subagent_type, file_meta.subagent_type),
|
|
242
254
|
tool_use_id = COALESCE(excluded.tool_use_id, file_meta.tool_use_id),
|
|
243
255
|
repo_url = COALESCE(excluded.repo_url, file_meta.repo_url)`),
|
|
244
|
-
getStats: db.prepare("SELECT api_ms, tool_ms, lines_added, lines_removed, target_paths FROM file_meta WHERE file_id = ?"),
|
|
256
|
+
getStats: db.prepare("SELECT api_ms, tool_ms, lines_added, lines_removed, target_paths, parser_state FROM file_meta WHERE file_id = ?"),
|
|
245
257
|
upsertStats: db.prepare(`INSERT INTO file_meta(file_id, api_ms, tool_ms, lines_added, lines_removed) VALUES (?, ?, ?, ?, ?)
|
|
246
258
|
ON CONFLICT(file_id) DO UPDATE SET api_ms = excluded.api_ms, tool_ms = excluded.tool_ms,
|
|
247
259
|
lines_added = excluded.lines_added, lines_removed = excluded.lines_removed`),
|
|
248
260
|
upsertTargetPaths: db.prepare(`INSERT INTO file_meta(file_id, target_paths) VALUES (?, ?)
|
|
249
261
|
ON CONFLICT(file_id) DO UPDATE SET target_paths = excluded.target_paths`),
|
|
262
|
+
upsertParserState: db.prepare(`INSERT INTO file_meta(file_id, parser_state) VALUES (?, ?)
|
|
263
|
+
ON CONFLICT(file_id) DO UPDATE SET parser_state = excluded.parser_state`),
|
|
264
|
+
backfillReqModel: db.prepare("UPDATE requests SET model = ?, family = ? WHERE file_id = ? AND model = 'unknown'"),
|
|
265
|
+
backfillCallModel: db.prepare("UPDATE tool_calls SET model = ? WHERE file_id = ? AND model IS NULL"),
|
|
266
|
+
backfillReqEffort: db.prepare("UPDATE requests SET effort = ? WHERE file_id = ? AND effort IS NULL"),
|
|
250
267
|
};
|
|
251
268
|
const stateByFile = new Map();
|
|
252
269
|
|
|
@@ -261,17 +278,25 @@ export function createIngester(db, timeZone) {
|
|
|
261
278
|
let st = stateByFile.get(file.id);
|
|
262
279
|
if (!st) {
|
|
263
280
|
const prevStats = file.lines > 0 ? q.getStats.get(file.id) : null;
|
|
281
|
+
const ps = parseParserState(prevStats?.parser_state);
|
|
264
282
|
st = {
|
|
265
283
|
launchCwd: file.cwd ?? null,
|
|
266
|
-
cwd: file.cwd ?? null,
|
|
267
|
-
model:
|
|
284
|
+
cwd: str(ps?.cwd) ?? file.cwd ?? null,
|
|
285
|
+
model: str(ps?.model) ?? null,
|
|
286
|
+
effort: str(ps?.effort) ?? null,
|
|
287
|
+
sawTokenRec: Boolean(ps?.sawTokenRec),
|
|
288
|
+
lastTotal: str(ps?.lastTotal) ?? null,
|
|
289
|
+
lastCompactionLine: typeof ps?.lastCompactionLine === "number" ? ps.lastCompactionLine : -999,
|
|
268
290
|
callStart: new Map(), callSkills: new Map(),
|
|
269
291
|
turnStartMs: null, turnToolMs: 0, openApiMs: 0, lastWaitFromMs: null,
|
|
270
292
|
completedApiMs: prevStats?.api_ms ?? 0, toolMs: prevStats?.tool_ms ?? 0,
|
|
271
293
|
baseAdded: prevStats?.lines_added ?? 0, baseRemoved: prevStats?.lines_removed ?? 0,
|
|
272
|
-
sawFileChange:
|
|
294
|
+
sawFileChange: Boolean(ps?.sawFileChange),
|
|
295
|
+
fcAdded: 0, fcRemoved: 0, patchAdded: 0, patchRemoved: 0,
|
|
273
296
|
paths: createPathTracker(prevStats?.target_paths ?? null),
|
|
274
|
-
|
|
297
|
+
hadUnknownModel: Boolean(ps?.hadUnknownModel),
|
|
298
|
+
hadNullEffort: Boolean(ps?.hadNullEffort),
|
|
299
|
+
statsDirty: false, pathsDirty: false, stateDirty: false,
|
|
275
300
|
};
|
|
276
301
|
stateByFile.set(file.id, st);
|
|
277
302
|
}
|
|
@@ -286,6 +311,34 @@ export function createIngester(db, timeZone) {
|
|
|
286
311
|
let cwd = p.cwd ?? null;
|
|
287
312
|
let added = 0;
|
|
288
313
|
|
|
314
|
+
const setModel = (raw) => {
|
|
315
|
+
const next = modelOf(raw);
|
|
316
|
+
if (!next) return;
|
|
317
|
+
if (!st.model && st.hadUnknownModel) {
|
|
318
|
+
q.backfillReqModel.run(next, familyOf(next), file.id);
|
|
319
|
+
q.backfillCallModel.run(next, file.id);
|
|
320
|
+
st.hadUnknownModel = false;
|
|
321
|
+
st.stateDirty = true;
|
|
322
|
+
}
|
|
323
|
+
if (st.model !== next) {
|
|
324
|
+
st.model = next;
|
|
325
|
+
st.stateDirty = true;
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
const setEffort = (raw) => {
|
|
329
|
+
const next = str(raw);
|
|
330
|
+
if (!next) return;
|
|
331
|
+
if (!st.effort && st.hadNullEffort) {
|
|
332
|
+
q.backfillReqEffort.run(next, file.id);
|
|
333
|
+
st.hadNullEffort = false;
|
|
334
|
+
st.stateDirty = true;
|
|
335
|
+
}
|
|
336
|
+
if (st.effort !== next) {
|
|
337
|
+
st.effort = next;
|
|
338
|
+
st.stateDirty = true;
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
|
|
289
342
|
const consumeOpenWait = () => {
|
|
290
343
|
if (tsMs !== null && st.lastWaitFromMs !== null) {
|
|
291
344
|
const dt = tsMs - st.lastWaitFromMs;
|
|
@@ -310,6 +363,14 @@ export function createIngester(db, timeZone) {
|
|
|
310
363
|
const output = u.output_tokens ?? 0;
|
|
311
364
|
const thinking = u.reasoning_output_tokens ?? 0;
|
|
312
365
|
if (!input && !output && !cacheRead && !cacheWrite) return false;
|
|
366
|
+
if (!st.model && !st.hadUnknownModel) {
|
|
367
|
+
st.hadUnknownModel = true;
|
|
368
|
+
st.stateDirty = true;
|
|
369
|
+
}
|
|
370
|
+
if (!st.effort && !st.hadNullEffort) {
|
|
371
|
+
st.hadNullEffort = true;
|
|
372
|
+
st.stateDirty = true;
|
|
373
|
+
}
|
|
313
374
|
const model = st.model ?? "unknown";
|
|
314
375
|
const { day, hour } = zone(ts);
|
|
315
376
|
q.record.run(`codex:${ownId}:${line}`, file.id, line, rec.type, ts);
|
|
@@ -321,40 +382,52 @@ export function createIngester(db, timeZone) {
|
|
|
321
382
|
if (rec.type === "session_meta") {
|
|
322
383
|
if (p.cwd) {
|
|
323
384
|
st.launchCwd ??= p.cwd;
|
|
324
|
-
st.cwd
|
|
385
|
+
if (st.cwd !== p.cwd) {
|
|
386
|
+
st.cwd = p.cwd;
|
|
387
|
+
st.stateDirty = true;
|
|
388
|
+
}
|
|
325
389
|
}
|
|
326
390
|
const subType = subagentTypeOf(p.source);
|
|
327
391
|
const metaSub = p.parent_thread_id || subType ? (subType ?? "subagent") : null;
|
|
328
392
|
const repoUrl = p.git?.repository_url ?? null;
|
|
329
393
|
if (metaSub || repoUrl) q.fileMeta.run(file.id, p.parent_thread_id ?? null, metaSub, null, repoUrl);
|
|
330
|
-
|
|
394
|
+
setModel(p.model);
|
|
331
395
|
} else if (rec.type === "turn_context") {
|
|
332
396
|
if (p.cwd) {
|
|
333
397
|
st.launchCwd ??= p.cwd;
|
|
334
|
-
st.cwd
|
|
398
|
+
if (st.cwd !== p.cwd) {
|
|
399
|
+
st.cwd = p.cwd;
|
|
400
|
+
st.stateDirty = true;
|
|
401
|
+
}
|
|
335
402
|
if (p.cwd !== st.launchCwd && st.paths.add(p.cwd, { write: false })) st.pathsDirty = true;
|
|
336
403
|
}
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
if (eff) st.effort = eff;
|
|
404
|
+
setModel(p.model ?? p.collaboration_mode?.settings?.model);
|
|
405
|
+
setEffort(p.effort ?? p.collaboration_mode?.settings?.reasoning_effort);
|
|
340
406
|
} else if (rec.type === "world_state") {
|
|
341
|
-
|
|
342
|
-
|
|
407
|
+
setModel(modelOf(p.state?.model) ?? modelOf(p.state?.collaboration_mode?.model) ?? modelOf(p.state?.collaboration_mode?.settings?.model));
|
|
408
|
+
setEffort(p.state?.effort ?? p.state?.reasoning_effort ?? p.state?.collaboration_mode?.settings?.reasoning_effort);
|
|
343
409
|
} else if (rec.type === "token_usage_record") {
|
|
344
410
|
consumeOpenWait();
|
|
345
|
-
st.sawTokenRec
|
|
411
|
+
if (!st.sawTokenRec) {
|
|
412
|
+
st.sawTokenRec = true;
|
|
413
|
+
st.stateDirty = true;
|
|
414
|
+
}
|
|
346
415
|
const msgId = `codex:${p.response_id || `${ownId}:${line}`}`;
|
|
347
416
|
if (recordUsage(msgId, p.usage)) added = 1;
|
|
348
417
|
} else if (rec.type === "compacted") {
|
|
418
|
+
if (!st.model) setModel(p.resume_metadata?.previous_turn_settings?.model);
|
|
419
|
+
if (!st.effort) setEffort(p.resume_metadata?.previous_turn_settings?.reasoning_effort ?? p.resume_metadata?.previous_turn_settings?.effort);
|
|
349
420
|
if (line - st.lastCompactionLine > 5) {
|
|
350
421
|
st.lastCompactionLine = line;
|
|
422
|
+
st.stateDirty = true;
|
|
351
423
|
q.record.run(`codex:${ownId}:${line}`, file.id, line, rec.type, ts);
|
|
352
424
|
q.compaction.run(`codex:${ownId}:${line}`, file.id, line, session, agent, ts, "auto", null, null, null);
|
|
353
425
|
added = 1;
|
|
354
426
|
}
|
|
355
427
|
} else if (rec.type === "response_item") {
|
|
356
|
-
if (p.type === "configuration_update"
|
|
357
|
-
|
|
428
|
+
if (p.type === "configuration_update") {
|
|
429
|
+
setModel(p.model);
|
|
430
|
+
setEffort(p.reasoning?.effort ?? p.effort);
|
|
358
431
|
} else if (p.type === "message" && p.role === "user") {
|
|
359
432
|
const msg = userMessageText(p.content);
|
|
360
433
|
if (msg) {
|
|
@@ -373,6 +446,10 @@ export function createIngester(db, timeZone) {
|
|
|
373
446
|
consumeOpenWait();
|
|
374
447
|
} else if (p.type === "function_call" || p.type === "custom_tool_call") {
|
|
375
448
|
consumeOpenWait();
|
|
449
|
+
if (!st.model && !st.hadUnknownModel) {
|
|
450
|
+
st.hadUnknownModel = true;
|
|
451
|
+
st.stateDirty = true;
|
|
452
|
+
}
|
|
376
453
|
q.record.run(`codex:${ownId}:${line}`, file.id, line, p.type, ts);
|
|
377
454
|
q.call.run(`codex:${p.call_id || `${ownId}:${line}`}`, file.id, line, session, agent, ts, p.name ?? "unknown", st.model ?? null);
|
|
378
455
|
if (tsMs !== null && p.call_id) st.callStart.set(p.call_id, tsMs);
|
|
@@ -434,13 +511,18 @@ export function createIngester(db, timeZone) {
|
|
|
434
511
|
} else if (p.type === "compaction") {
|
|
435
512
|
if (line - st.lastCompactionLine > 5) {
|
|
436
513
|
st.lastCompactionLine = line;
|
|
514
|
+
st.stateDirty = true;
|
|
437
515
|
q.record.run(`codex:${ownId}:${line}`, file.id, line, p.type, ts);
|
|
438
516
|
q.compaction.run(`codex:${ownId}:${line}`, file.id, line, session, agent, ts, "auto", null, null, null);
|
|
439
517
|
added = 1;
|
|
440
518
|
}
|
|
441
519
|
}
|
|
442
520
|
} else if (rec.type === "event_msg") {
|
|
443
|
-
if (p.type === "
|
|
521
|
+
if (p.type === "thread_settings_applied") {
|
|
522
|
+
const tsSettings = p.thread_settings;
|
|
523
|
+
setModel(tsSettings?.model ?? tsSettings?.collaboration_mode?.settings?.model);
|
|
524
|
+
setEffort(tsSettings?.reasoning_effort ?? tsSettings?.effort ?? tsSettings?.collaboration_mode?.settings?.reasoning_effort);
|
|
525
|
+
} else if (p.type === "task_started" || p.type === "turn_started") {
|
|
444
526
|
if (tsMs !== null) {
|
|
445
527
|
st.turnStartMs = tsMs;
|
|
446
528
|
st.turnToolMs = 0;
|
|
@@ -486,7 +568,10 @@ export function createIngester(db, timeZone) {
|
|
|
486
568
|
st.fcRemoved += d.removed;
|
|
487
569
|
}
|
|
488
570
|
}
|
|
489
|
-
st.sawFileChange
|
|
571
|
+
if (!st.sawFileChange) {
|
|
572
|
+
st.sawFileChange = true;
|
|
573
|
+
st.stateDirty = true;
|
|
574
|
+
}
|
|
490
575
|
st.statsDirty = true;
|
|
491
576
|
}
|
|
492
577
|
} else if (p.type === "token_count" && !st.sawTokenRec && p.info?.last_token_usage) {
|
|
@@ -494,7 +579,10 @@ export function createIngester(db, timeZone) {
|
|
|
494
579
|
const tot = p.info.total_token_usage;
|
|
495
580
|
const totKey = tot ? `${tot.total_tokens}|${tot.input_tokens}|${tot.output_tokens}|${tot.cached_input_tokens}` : null;
|
|
496
581
|
if (!totKey || totKey !== st.lastTotal) {
|
|
497
|
-
st.lastTotal
|
|
582
|
+
if (st.lastTotal !== totKey) {
|
|
583
|
+
st.lastTotal = totKey;
|
|
584
|
+
st.stateDirty = true;
|
|
585
|
+
}
|
|
498
586
|
if (recordUsage(`codex:${ownId}:${line}`, p.info.last_token_usage)) added = 1;
|
|
499
587
|
}
|
|
500
588
|
}
|
|
@@ -519,6 +607,20 @@ export function createIngester(db, timeZone) {
|
|
|
519
607
|
const json = st.paths.toJSON();
|
|
520
608
|
if (json) q.upsertTargetPaths.run(fileId, json);
|
|
521
609
|
}
|
|
610
|
+
if (st.stateDirty) {
|
|
611
|
+
st.stateDirty = false;
|
|
612
|
+
q.upsertParserState.run(fileId, JSON.stringify({
|
|
613
|
+
cwd: st.cwd,
|
|
614
|
+
model: st.model,
|
|
615
|
+
effort: st.effort,
|
|
616
|
+
sawTokenRec: st.sawTokenRec,
|
|
617
|
+
lastTotal: st.lastTotal,
|
|
618
|
+
lastCompactionLine: st.lastCompactionLine,
|
|
619
|
+
sawFileChange: st.sawFileChange,
|
|
620
|
+
hadUnknownModel: st.hadUnknownModel,
|
|
621
|
+
hadNullEffort: st.hadNullEffort,
|
|
622
|
+
}));
|
|
623
|
+
}
|
|
522
624
|
};
|
|
523
625
|
ingestLine.reset = (fileId) => { stateByFile.delete(fileId); };
|
|
524
626
|
return ingestLine;
|
package/src/serve.mjs
CHANGED
|
@@ -23,18 +23,28 @@ const TEXT = { "content-type": "text/plain; charset=utf-8" };
|
|
|
23
23
|
export function serve(config, { port, onScan = () => {}, dist = DIST, routes }) {
|
|
24
24
|
const api = createApi(config, { onScan, routes });
|
|
25
25
|
const server = createServer(async (req, res) => {
|
|
26
|
-
if (await api(req, res)) return;
|
|
27
|
-
if (req.method !== "GET") return res.writeHead(405, TEXT).end("method not allowed\n");
|
|
28
|
-
const path = normalize(decodeURIComponent(new URL(req.url, "http://localhost").pathname));
|
|
29
|
-
const file = join(dist, path);
|
|
30
|
-
const asset = file.startsWith(dist + sep) && extname(path) ? file : join(dist, "index.html");
|
|
31
26
|
try {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
27
|
+
if (await api(req, res)) return;
|
|
28
|
+
if (req.method !== "GET") return res.writeHead(405, TEXT).end("method not allowed\n");
|
|
29
|
+
let path;
|
|
30
|
+
try {
|
|
31
|
+
path = normalize(decodeURIComponent(new URL(req.url, "http://localhost").pathname));
|
|
32
|
+
} catch {
|
|
33
|
+
return res.writeHead(400, TEXT).end("bad request\n");
|
|
34
|
+
}
|
|
35
|
+
const file = join(dist, path);
|
|
36
|
+
const asset = file.startsWith(dist + sep) && extname(path) ? file : join(dist, "index.html");
|
|
37
|
+
try {
|
|
38
|
+
const body = await readFile(asset);
|
|
39
|
+
const cacheControl = asset.startsWith(join(dist, "assets") + sep) ? "max-age=31536000, immutable" : "no-store";
|
|
40
|
+
res.writeHead(200, { "content-type": TYPES[extname(asset)] ?? "application/octet-stream", "cache-control": cacheControl }).end(body);
|
|
41
|
+
} catch {
|
|
42
|
+
if (asset.endsWith("index.html")) res.writeHead(503, TEXT).end("the dashboard is not built: run npm run build, or npm run dev\n");
|
|
43
|
+
else res.writeHead(404, TEXT).end("not found\n");
|
|
44
|
+
}
|
|
35
45
|
} catch {
|
|
36
|
-
if (
|
|
37
|
-
else res.
|
|
46
|
+
if (!res.headersSent) res.writeHead(500, TEXT).end("internal server error\n");
|
|
47
|
+
else if (!res.writableEnded) res.end();
|
|
38
48
|
}
|
|
39
49
|
});
|
|
40
50
|
return new Promise((resolve, reject) => {
|
package/src/update.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
1
2
|
import { readFileSync } from "node:fs";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { ROOT } from "./config.mjs";
|
|
4
5
|
import { detectInstallMode, runPackageManager } from "./install.mjs";
|
|
5
|
-
import { findRunningServers } from "./process.mjs";
|
|
6
|
+
import { findRunningServers, stopRunningServers } from "./process.mjs";
|
|
6
7
|
|
|
7
8
|
const VERSION = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")).version;
|
|
8
9
|
|
|
@@ -80,6 +81,20 @@ export async function fetchLatestVersion({
|
|
|
80
81
|
return data.version.trim();
|
|
81
82
|
}
|
|
82
83
|
|
|
84
|
+
export function restartInstalledDaemon({ port, env = process.env, platform = process.platform, spawn = spawnSync } = {}) {
|
|
85
|
+
const args = ["start", ...(port ? ["--port", String(port)] : [])];
|
|
86
|
+
let res = spawn("llmtop", args, { encoding: "utf8", stdio: "pipe", env, shell: platform === "win32" });
|
|
87
|
+
if (res.error?.code === "ENOENT") {
|
|
88
|
+
res = spawn(process.execPath, [join(ROOT, "bin", "llmtop.mjs"), ...args], { encoding: "utf8", stdio: "pipe", env });
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
ok: !res.error && res.status === 0,
|
|
92
|
+
stdout: res.stdout ?? "",
|
|
93
|
+
stderr: res.stderr ?? "",
|
|
94
|
+
error: res.error?.message ?? "",
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
83
98
|
export async function updateCommand({ config, options = {}, out, err = process.stderr, deps = {} }) {
|
|
84
99
|
const current = deps.currentVersion ?? VERSION;
|
|
85
100
|
const env = deps.env ?? process.env;
|
|
@@ -120,6 +135,27 @@ export async function updateCommand({ config, options = {}, out, err = process.s
|
|
|
120
135
|
}
|
|
121
136
|
}
|
|
122
137
|
|
|
138
|
+
const findServers = deps.findRunningServers ?? findRunningServers;
|
|
139
|
+
const stopServers = deps.stopRunningServers ?? stopRunningServers;
|
|
140
|
+
const restartDaemon = deps.restartDaemon ?? restartInstalledDaemon;
|
|
141
|
+
|
|
142
|
+
const before = findServers(config);
|
|
143
|
+
const daemons = before.servers.filter((s) => s.daemon);
|
|
144
|
+
let restartPort;
|
|
145
|
+
|
|
146
|
+
if (daemons.length > 0) {
|
|
147
|
+
restartPort = daemons[0].port;
|
|
148
|
+
const stopped = await stopServers(config);
|
|
149
|
+
if (stopped.failed.length > 0) {
|
|
150
|
+
for (const f of stopped.failed) {
|
|
151
|
+
err.write(`error: could not stop background llmtop serve (pid ${f.pid}) before upgrade: ${f.error}\n`);
|
|
152
|
+
}
|
|
153
|
+
return 1;
|
|
154
|
+
}
|
|
155
|
+
const details = stopped.stopped.map((s) => `pid ${s.pid}`).join(", ");
|
|
156
|
+
out.write(`stopped background llmtop serve before upgrade (${details})\n`);
|
|
157
|
+
}
|
|
158
|
+
|
|
123
159
|
const pm = install.packageManager || "npm";
|
|
124
160
|
const res = (deps.runPackageManager ?? runPackageManager)(pm, "install", `llmtop@${latest}`);
|
|
125
161
|
if (!res.ok) {
|
|
@@ -127,14 +163,32 @@ export async function updateCommand({ config, options = {}, out, err = process.s
|
|
|
127
163
|
if (res.permissionDenied) {
|
|
128
164
|
err.write(`hint: try running \`sudo ${res.command}\`\n`);
|
|
129
165
|
}
|
|
166
|
+
if (daemons.length > 0) {
|
|
167
|
+
const restored = restartDaemon({ port: restartPort, env });
|
|
168
|
+
if (restored.ok) {
|
|
169
|
+
out.write(`${restored.stdout.trim() || "restarted previous background llmtop serve"}\n`);
|
|
170
|
+
} else {
|
|
171
|
+
err.write(`warning: failed to restore background server: ${restored.stderr.trim() || restored.error}; run \`llmtop start\` manually\n`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
130
174
|
return 1;
|
|
131
175
|
}
|
|
132
176
|
|
|
133
177
|
out.write(`updated llmtop ${current} -> ${latest}\n`);
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
178
|
+
if (daemons.length > 0) {
|
|
179
|
+
const restarted = restartDaemon({ port: restartPort, env });
|
|
180
|
+
if (restarted.ok) {
|
|
181
|
+
out.write(`${restarted.stdout.trim() || "restarted background llmtop serve"}\n`);
|
|
182
|
+
} else {
|
|
183
|
+
err.write(`warning: updated to ${latest} but failed to restart background server: ${restarted.stderr.trim() || restarted.error}; run \`llmtop start\` manually\n`);
|
|
184
|
+
return 1;
|
|
185
|
+
}
|
|
186
|
+
} else {
|
|
187
|
+
const { servers } = findServers(config);
|
|
188
|
+
if (servers.length > 0) {
|
|
189
|
+
const details = servers.map((s) => `pid ${s.pid}${s.port ? ` on port ${s.port}` : ""}`).join(", ");
|
|
190
|
+
out.write(`note: llmtop serve is still running (${details}); run \`llmtop stop\` and \`llmtop start\` (or \`llmtop serve\`) to use ${latest}.\n`);
|
|
191
|
+
}
|
|
138
192
|
}
|
|
139
193
|
return 0;
|
|
140
194
|
}
|