claude-rpc 1.7.4 → 1.8.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 +5 -4
- package/SECURITY.md +20 -0
- package/package.json +1 -1
- package/src/cli.js +3 -1
- package/src/commands.js +1 -0
- package/src/config-edit.js +59 -0
- package/src/server/assets/dashboard.html +1 -0
- package/src/server/assets/settings.client.js +422 -0
- package/src/server/assets/settings.css +145 -0
- package/src/server/assets/settings.html +176 -0
- package/src/server/index.js +67 -16
- package/src/server/page.js +17 -3
- package/src/server/routes.js +16 -0
- package/src/server/settings.js +234 -0
- package/src/version.js +1 -1
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
// Settings API for the local dashboard's /settings page — the config editor,
|
|
2
|
+
// daemon controls and per-project privacy that used to live in a separate
|
|
3
|
+
// Electron app. Everything here runs in-process against the same modules the
|
|
4
|
+
// CLI uses, so the page and `claude-rpc start|stop|private` can't disagree.
|
|
5
|
+
//
|
|
6
|
+
// Routes (registered in routes.js):
|
|
7
|
+
// GET /api/settings effective config + daemon status + template vars
|
|
8
|
+
// POST /api/settings { base, edited } → write only what changed
|
|
9
|
+
// POST /api/daemon { action: start|stop|restart }
|
|
10
|
+
// GET /api/log tail of daemon.log
|
|
11
|
+
// GET /api/workspaces known project dirs + their visibility
|
|
12
|
+
// POST /api/workspaces { cwd, level }
|
|
13
|
+
//
|
|
14
|
+
// The write routes are guarded in index.js (same-origin + JSON body), since a
|
|
15
|
+
// localhost server is reachable from any page the user has open.
|
|
16
|
+
|
|
17
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
18
|
+
import { basename, resolve as resolvePath } from 'node:path';
|
|
19
|
+
import { CONFIG_PATH, LOG_PATH, SCAN_CACHE_PATH } from '../paths.js';
|
|
20
|
+
import { DEFAULT_CONFIG } from '../default-config.js';
|
|
21
|
+
import { loadConfig, mergeConfig } from '../config.js';
|
|
22
|
+
import { applyEdits } from '../config-edit.js';
|
|
23
|
+
import { writeFileAtomic } from '../atomic-rename.js';
|
|
24
|
+
import { daemonAlive, spawnDaemonDetached } from '../ensure-daemon.js';
|
|
25
|
+
import { ipcStateFromLog, bridgeFromLog, classifyClientId } from '../doctor.js';
|
|
26
|
+
import { readActiveState } from '../state.js';
|
|
27
|
+
import { findLiveSessions, readAggregate } from '../scanner.js';
|
|
28
|
+
import { buildVars, applyIdle } from '../format.js';
|
|
29
|
+
import { readUsageCache } from '../usage.js';
|
|
30
|
+
import { listVisibility, setCwdVisibility } from '../privacy.js';
|
|
31
|
+
import { VERSION } from '../version.js';
|
|
32
|
+
|
|
33
|
+
// Every status the card can render, in the order the page lists them.
|
|
34
|
+
export const STATUSES = ['working', 'thinking', 'compacting', 'shipped', 'notification', 'idle'];
|
|
35
|
+
const VIS_LEVELS = ['public', 'name-only', 'hidden'];
|
|
36
|
+
const MAX_CONFIG_BYTES = 256 * 1024;
|
|
37
|
+
|
|
38
|
+
// Write routes change the user's config and start/stop their daemon, and a
|
|
39
|
+
// localhost server is reachable from every page open in the browser. Two
|
|
40
|
+
// checks keep other sites out:
|
|
41
|
+
// - Origin, when sent (browsers always send it on POST), must be this exact
|
|
42
|
+
// host:port — not merely "some localhost page".
|
|
43
|
+
// - The body must be application/json. A cross-site form can't send that
|
|
44
|
+
// without a CORS preflight, which this server never answers.
|
|
45
|
+
export function writeAllowed(headers) {
|
|
46
|
+
const type = String(headers['content-type'] || '').split(';')[0].trim().toLowerCase();
|
|
47
|
+
if (type !== 'application/json') return false;
|
|
48
|
+
const origin = headers.origin;
|
|
49
|
+
if (origin === undefined) return true; // non-browser client (curl, tests)
|
|
50
|
+
try { return new URL(origin).host === headers.host; } catch { return false; }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
54
|
+
|
|
55
|
+
function tailLog(lines = 80) {
|
|
56
|
+
try {
|
|
57
|
+
if (!existsSync(LOG_PATH)) return '';
|
|
58
|
+
return readFileSync(LOG_PATH, 'utf8').split('\n').slice(-lines).join('\n').trimEnd();
|
|
59
|
+
} catch { return ''; }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// running/pid from the pid file; ipc ('up'|'down'|'unknown') and the client
|
|
63
|
+
// kind from the log tail — the same reading `claude-rpc doctor` reports.
|
|
64
|
+
export function daemonStatus() {
|
|
65
|
+
const pid = daemonAlive();
|
|
66
|
+
if (!pid) return { running: false, pid: null, ipc: 'down', client: null };
|
|
67
|
+
const log = tailLog(200);
|
|
68
|
+
return { running: true, pid, ipc: ipcStateFromLog(log), client: bridgeFromLog(log) };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Live template variables, for the card preview and the {variable} picker.
|
|
72
|
+
function liveVars(config) {
|
|
73
|
+
try {
|
|
74
|
+
let state = readActiveState();
|
|
75
|
+
state.liveSessions = findLiveSessions({ thresholdMs: 90_000 });
|
|
76
|
+
state = applyIdle(state, config);
|
|
77
|
+
state.usage = readUsageCache();
|
|
78
|
+
return buildVars(state, config, readAggregate() || {});
|
|
79
|
+
} catch { return {}; }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function getSettings() {
|
|
83
|
+
const config = loadConfig();
|
|
84
|
+
const live = liveVars(config);
|
|
85
|
+
return {
|
|
86
|
+
version: VERSION,
|
|
87
|
+
configPath: CONFIG_PATH,
|
|
88
|
+
config,
|
|
89
|
+
statuses: STATUSES,
|
|
90
|
+
daemon: daemonStatus(),
|
|
91
|
+
vars: Object.keys(live).sort(),
|
|
92
|
+
live,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// The file as it is on disk right now. A missing file is an empty config; an
|
|
97
|
+
// unreadable or half-written one throws, because overwriting it would lose
|
|
98
|
+
// whatever is in it.
|
|
99
|
+
function readRawConfig(path) {
|
|
100
|
+
let text;
|
|
101
|
+
try { text = readFileSync(path, 'utf8'); }
|
|
102
|
+
catch (e) {
|
|
103
|
+
if (e.code === 'ENOENT') return {};
|
|
104
|
+
throw new Error(`couldn't read ${path} (${e.message})`, { cause: e });
|
|
105
|
+
}
|
|
106
|
+
let raw;
|
|
107
|
+
try { raw = JSON.parse(text); }
|
|
108
|
+
catch (e) { throw new Error(`${path} isn't valid JSON (${e.message}) — fix or delete it first`, { cause: e }); }
|
|
109
|
+
if (!isPlainObject(raw)) throw new Error(`${path} isn't a JSON object`);
|
|
110
|
+
return raw;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Reject edits that would leave the daemon unable to render anything. Kept
|
|
114
|
+
// short on purpose: the daemon already tolerates odd values by falling back
|
|
115
|
+
// to defaults, so this only catches what would silently break the card.
|
|
116
|
+
export function validateConfig(merged) {
|
|
117
|
+
if (classifyClientId(merged.clientId) !== 'ok') {
|
|
118
|
+
return 'Discord application ID must be the 17–21 digit number from the Discord developer portal';
|
|
119
|
+
}
|
|
120
|
+
for (const b of merged.presence?.buttons || []) {
|
|
121
|
+
if (!b || typeof b.label !== 'string' || !/^https?:\/\//i.test(b.url || '')) {
|
|
122
|
+
return 'Each button needs a label and an http(s) link';
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if ((merged.presence?.buttons || []).length > 2) return 'Discord shows at most 2 buttons';
|
|
126
|
+
for (const k of ['updateIntervalMs', 'rotationIntervalMs', 'idleThresholdSec', 'staleSessionMin', 'shippedFrameSec']) {
|
|
127
|
+
const v = merged[k];
|
|
128
|
+
if (v !== undefined && v !== null && !(typeof v === 'number' && Number.isFinite(v) && v >= 0)) {
|
|
129
|
+
return `${k} must be a number, 0 or more`;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// { base, edited } → writes only the keys that differ between them onto the
|
|
136
|
+
// file as it is on disk now. Returns { ok, config } or { error }.
|
|
137
|
+
// `path` is overridable for tests only.
|
|
138
|
+
export function saveSettings(body, { path = CONFIG_PATH } = {}) {
|
|
139
|
+
const { base, edited } = body || {};
|
|
140
|
+
if (!isPlainObject(base) || !isPlainObject(edited)) return { error: 'Nothing to save' };
|
|
141
|
+
let raw;
|
|
142
|
+
try { raw = readRawConfig(path); } catch (e) { return { error: `Not saved: ${e.message}` }; }
|
|
143
|
+
const next = applyEdits(raw, base, edited);
|
|
144
|
+
const problem = validateConfig(mergeConfig(DEFAULT_CONFIG, next));
|
|
145
|
+
if (problem) return { error: problem };
|
|
146
|
+
const text = JSON.stringify(next, null, 2) + '\n';
|
|
147
|
+
if (Buffer.byteLength(text) > MAX_CONFIG_BYTES) return { error: 'Config is too large to save' };
|
|
148
|
+
try { writeFileAtomic(path, text); }
|
|
149
|
+
catch (e) { return { error: `Not saved: ${e.message}` }; }
|
|
150
|
+
return { ok: true, config: loadConfig({ path }) };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
154
|
+
|
|
155
|
+
// Poll until the daemon's liveness matches `want` (true = up), or time out.
|
|
156
|
+
async function waitDaemon(want, timeoutMs) {
|
|
157
|
+
const deadline = Date.now() + timeoutMs;
|
|
158
|
+
for (;;) {
|
|
159
|
+
if (!!daemonAlive() === want) return true;
|
|
160
|
+
if (Date.now() >= deadline) return false;
|
|
161
|
+
await sleep(100);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function signal(pid, sig) {
|
|
166
|
+
try { process.kill(pid, sig); return true; } catch { return false; }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function stop() {
|
|
170
|
+
const pid = daemonAlive();
|
|
171
|
+
if (!pid) return true;
|
|
172
|
+
signal(pid, 'SIGTERM');
|
|
173
|
+
if (await waitDaemon(false, 3000)) return true;
|
|
174
|
+
// Wedged: it ignored SIGTERM for 3s. Don't leave the user with a daemon
|
|
175
|
+
// they asked to stop.
|
|
176
|
+
signal(pid, 'SIGKILL');
|
|
177
|
+
return waitDaemon(false, 1500);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function start() {
|
|
181
|
+
if (daemonAlive()) return true;
|
|
182
|
+
const child = spawnDaemonDetached();
|
|
183
|
+
if (!child || !child.pid) return false;
|
|
184
|
+
// A detached spawn can die a millisecond later (bad path, startup throw), so
|
|
185
|
+
// confirm through the pid file the daemon claims early in startup.
|
|
186
|
+
return waitDaemon(true, 3000);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export async function daemonAction(action) {
|
|
190
|
+
let ok;
|
|
191
|
+
if (action === 'start') ok = await start();
|
|
192
|
+
else if (action === 'stop') ok = await stop();
|
|
193
|
+
else if (action === 'restart') ok = (await stop()) && (await start());
|
|
194
|
+
else return { error: 'unknown action' };
|
|
195
|
+
const daemon = daemonStatus();
|
|
196
|
+
if (ok) return { ok: true, daemon };
|
|
197
|
+
const what = action === 'stop' ? "The daemon didn't stop" : "The daemon didn't come up";
|
|
198
|
+
return { error: `${what} — see the log below`, daemon };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function getLog() {
|
|
202
|
+
return { path: LOG_PATH, content: tailLog(80) };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Project directories the scanner has seen, newest activity first. Read from
|
|
206
|
+
// the scan cache (each transcript summary carries its cwd) rather than
|
|
207
|
+
// re-walking ~/.claude/projects. Subagent transcripts share their parent's cwd
|
|
208
|
+
// and collapse into it.
|
|
209
|
+
export function listWorkspaces() {
|
|
210
|
+
const seen = new Map(); // resolved cwd → { name, cwd, lastTs }
|
|
211
|
+
try {
|
|
212
|
+
const cache = JSON.parse(readFileSync(SCAN_CACHE_PATH, 'utf8'));
|
|
213
|
+
for (const f of Object.values(cache.files || {})) {
|
|
214
|
+
if (!f || typeof f.cwd !== 'string' || !f.cwd) continue;
|
|
215
|
+
const cwd = resolvePath(f.cwd);
|
|
216
|
+
const lastTs = Number(f.lastTs) || 0;
|
|
217
|
+
const prev = seen.get(cwd);
|
|
218
|
+
if (!prev || lastTs > prev.lastTs) seen.set(cwd, { name: basename(cwd) || cwd, cwd, lastTs });
|
|
219
|
+
}
|
|
220
|
+
} catch { /* no scan yet — empty list */ }
|
|
221
|
+
return {
|
|
222
|
+
workspaces: [...seen.values()].sort((a, b) => b.lastTs - a.lastTs),
|
|
223
|
+
visibility: listVisibility(),
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// level: public | name-only | hidden; anything else clears the override.
|
|
228
|
+
export function setWorkspaceVisibility(body) {
|
|
229
|
+
const cwd = body && typeof body.cwd === 'string' && body.cwd ? body.cwd : null;
|
|
230
|
+
if (!cwd) return { error: 'no project given' };
|
|
231
|
+
const level = VIS_LEVELS.includes(body.level) ? body.level : null;
|
|
232
|
+
try { return { ok: true, visibility: setCwdVisibility(cwd, level) }; }
|
|
233
|
+
catch (e) { return { error: e.message }; }
|
|
234
|
+
}
|