wrkpanel 0.0.0-stage → 0.3.1

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.
@@ -0,0 +1,379 @@
1
+ import { open, readdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { StringDecoder } from 'node:string_decoder';
4
+ import { db, transaction } from './db.js';
5
+ const MAX_SESSIONS_PER_LINK = 50;
6
+ const MAX_TITLE = 200;
7
+ const CHUNK = 1024 * 1024;
8
+ const TOOL_RE = /^Artifact(Data|Comments)?$|^mcp__.*(artifact|claude_docs)/i;
9
+ const DOCS_RE = /claude_docs/i;
10
+ const URL_RE = /^https?:\/\/claude\.ai\/(code\/)?artifact\/([A-Za-z0-9_-]{6,64})(?=$|[/?#])/;
11
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12
+ /** claude.ai/artifact/X or claude.ai/code/artifact/X, without query, hash or trailing path. */
13
+ export function canonicalUrl(input) {
14
+ if (typeof input !== 'string')
15
+ return undefined;
16
+ const m = input.match(URL_RE);
17
+ return m ? `https://claude.ai/${m[1] ?? ''}artifact/${m[2]}` : undefined;
18
+ }
19
+ function uuidOf(input) {
20
+ return typeof input === 'string' && UUID_RE.test(input) ? input.toLowerCase() : undefined;
21
+ }
22
+ /** A code/artifact/<uuid> URL names the uuid itself. */
23
+ function uuidOfUrl(url) {
24
+ const m = url?.match(/\/code\/artifact\/([^/]+)$/);
25
+ return m ? uuidOf(m[1]) : undefined;
26
+ }
27
+ function cleanTitle(input) {
28
+ if (typeof input !== 'string')
29
+ return undefined;
30
+ const t = input.replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, MAX_TITLE);
31
+ return t || undefined;
32
+ }
33
+ function obj(v) {
34
+ return typeof v === 'object' && v !== null && !Array.isArray(v) ? v : undefined;
35
+ }
36
+ function resultText(content) {
37
+ if (typeof content === 'string')
38
+ return content;
39
+ if (!Array.isArray(content))
40
+ return '';
41
+ return content.map((c) => (typeof obj(c)?.text === 'string' ? obj(c).text : '')).join('\n');
42
+ }
43
+ /** A JSON string literal's body (`a\"b`) back to text. */
44
+ function unescapeJson(s) {
45
+ try {
46
+ return JSON.parse(`"${s}"`);
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ }
52
+ /**
53
+ * The link one finished tool call points at, or null. `result` is the entry's `toolUseResult`,
54
+ * `text` the tool_result's text.
55
+ */
56
+ export function linkOf(use, result, text, at) {
57
+ const input = use.input;
58
+ if (use.name === 'Artifact' && (input.action === 'quickstart' || (input.action === 'list' && !input.url)))
59
+ return null;
60
+ const r = obj(result);
61
+ const read = obj(r?.read);
62
+ const fileRead = obj(r?.file_read);
63
+ let url = canonicalUrl(input.url) ?? canonicalUrl(r?.url) ?? canonicalUrl(read?.url) ?? canonicalUrl(fileRead?.url) ?? canonicalUrl(obj(r?.written)?.url);
64
+ let uuid = uuidOf(r?.artifact_id) ?? uuidOf(obj(r?.artifactRead)?.slug);
65
+ let title = cleanTitle(r?.title) ?? cleanTitle(read?.title) ?? cleanTitle(fileRead?.title);
66
+ if (DOCS_RE.test(use.name)) {
67
+ // Docs results are JSON text; the doc's link is in `frame`, its name in `value.name` (a read) or
68
+ // in the create call's input.
69
+ const container = obj(input.container);
70
+ const ref = obj(input.ref);
71
+ const docId = container?.id ?? (ref?.object === 'project' ? ref.id : undefined); // short id or uuid
72
+ url ??= canonicalUrl(text.match(/"artifactUrl":"(https:\/\/claude\.ai\/[^"]+)"/)?.[1]);
73
+ uuid ??= uuidOf(text.match(/"frame":\{"slug":"([0-9a-f-]{36})"/)?.[1]) ?? uuidOf(docId);
74
+ title ??= cleanTitle(obj(container?.create)?.name);
75
+ const name = text.match(/"value":\{"name":"((?:[^"\\]|\\.)*)"/)?.[1];
76
+ title ??= name === undefined ? undefined : cleanTitle(unescapeJson(name));
77
+ if (!url && !uuid && typeof docId === 'string')
78
+ url = canonicalUrl(`https://claude.ai/artifact/${docId}`); // by its short id
79
+ }
80
+ uuid ??= uuidOfUrl(url);
81
+ if (!url && !uuid)
82
+ return null;
83
+ const deleted = use.name === 'Artifact' && input.action === 'delete' && input.path === undefined;
84
+ return { url, uuid, title, at, ...(deleted ? { deleted } : {}) };
85
+ }
86
+ const scans = new Map();
87
+ function newScan() {
88
+ return { offset: 0, decoder: new StringDecoder('utf8'), carry: '', pending: new Map() };
89
+ }
90
+ function handleLine(line, scan, out) {
91
+ // Most lines are other tools' output: only parse the ones that can matter.
92
+ if (!/rtifact|Claude_Docs/.test(line) && ![...scan.pending.keys()].some((id) => line.includes(id)))
93
+ return;
94
+ let entry;
95
+ try {
96
+ entry = JSON.parse(line);
97
+ }
98
+ catch {
99
+ return;
100
+ }
101
+ const content = entry.message?.content;
102
+ if (!Array.isArray(content))
103
+ return;
104
+ if (entry.type === 'assistant') {
105
+ for (const b of content) {
106
+ const block = obj(b);
107
+ if (block?.type !== 'tool_use' || typeof block.id !== 'string' || typeof block.name !== 'string')
108
+ continue;
109
+ if (TOOL_RE.test(block.name))
110
+ scan.pending.set(block.id, { name: block.name, input: obj(block.input) ?? {} });
111
+ }
112
+ }
113
+ else if (entry.type === 'user') {
114
+ for (const b of content) {
115
+ const block = obj(b);
116
+ if (block?.type !== 'tool_result' || typeof block.tool_use_id !== 'string')
117
+ continue;
118
+ const use = scan.pending.get(block.tool_use_id);
119
+ if (!use)
120
+ continue;
121
+ scan.pending.delete(block.tool_use_id);
122
+ if (block.is_error === true)
123
+ continue;
124
+ const t = Date.parse(typeof entry.timestamp === 'string' ? entry.timestamp : '');
125
+ const found = linkOf(use, entry.toolUseResult, resultText(block.content), Number.isFinite(t) ? t : Date.now());
126
+ if (found)
127
+ out.push(found);
128
+ }
129
+ }
130
+ }
131
+ /** Links in the part of `path` not read yet. A missing file gives nothing; a shrunk one is read again. */
132
+ async function scanFile(path) {
133
+ let scan = scans.get(path) ?? newScan();
134
+ scans.set(path, scan);
135
+ const out = [];
136
+ let fh;
137
+ try {
138
+ fh = await open(path, 'r');
139
+ }
140
+ catch {
141
+ return out;
142
+ }
143
+ try {
144
+ const size = (await fh.stat()).size;
145
+ if (size < scan.offset) {
146
+ scan = newScan(); // replaced or truncated
147
+ scans.set(path, scan);
148
+ }
149
+ const buf = Buffer.alloc(Math.min(CHUNK, Math.max(1, size - scan.offset)));
150
+ while (scan.offset < size) {
151
+ const { bytesRead } = await fh.read(buf, 0, Math.min(buf.length, size - scan.offset), scan.offset);
152
+ if (!bytesRead)
153
+ break;
154
+ scan.offset += bytesRead;
155
+ const lines = (scan.carry + scan.decoder.write(buf.subarray(0, bytesRead))).split('\n');
156
+ scan.carry = lines.pop() ?? '';
157
+ for (const line of lines)
158
+ handleLine(line, scan, out);
159
+ }
160
+ }
161
+ finally {
162
+ await fh.close();
163
+ }
164
+ return out;
165
+ }
166
+ /** A transcript and its subagents' transcripts (`<transcript>/subagents/*.jsonl`). */
167
+ async function transcriptFiles(transcript) {
168
+ const files = [transcript];
169
+ const dir = join(transcript.replace(/\.jsonl$/, ''), 'subagents');
170
+ try {
171
+ for (const f of await readdir(dir))
172
+ if (f.endsWith('.jsonl'))
173
+ files.push(join(dir, f));
174
+ }
175
+ catch {
176
+ /* no subagents */
177
+ }
178
+ return files;
179
+ }
180
+ // ---------- the store ----------
181
+ /** Every row, loaded once; record() changes it in place and save() writes it back. */
182
+ let cache = null;
183
+ function strings(json) {
184
+ try {
185
+ const v = JSON.parse(json);
186
+ return Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [];
187
+ }
188
+ catch {
189
+ return [];
190
+ }
191
+ }
192
+ function load() {
193
+ if (cache)
194
+ return cache;
195
+ const rows = db().prepare('SELECT url, uuid, title, first, last, cwds, sessions, deleted FROM artifacts').all();
196
+ cache = rows.map((r) => ({
197
+ url: r.url,
198
+ ...(r.uuid ? { uuid: r.uuid } : {}),
199
+ title: r.title,
200
+ first: r.first,
201
+ last: r.last,
202
+ cwds: strings(r.cwds),
203
+ sessions: strings(r.sessions),
204
+ ...(r.deleted ? { deleted: true } : {}),
205
+ }));
206
+ return cache;
207
+ }
208
+ /** Write the whole list: rows for links merged away are deleted. One transaction. */
209
+ function save(links) {
210
+ transaction(() => {
211
+ const d = db();
212
+ const upsert = d.prepare(`INSERT INTO artifacts (url, uuid, title, first, last, cwds, sessions, deleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
213
+ ON CONFLICT(url) DO UPDATE SET uuid = excluded.uuid, title = excluded.title, first = excluded.first,
214
+ last = excluded.last, cwds = excluded.cwds, sessions = excluded.sessions, deleted = excluded.deleted`);
215
+ const keep = new Set();
216
+ for (const a of links) {
217
+ keep.add(a.url);
218
+ upsert.run(a.url, a.uuid ?? null, a.title, a.first, a.last, JSON.stringify(a.cwds), JSON.stringify(a.sessions), a.deleted ? 1 : 0);
219
+ }
220
+ const del = d.prepare('DELETE FROM artifacts WHERE url = ?');
221
+ for (const { url } of d.prepare('SELECT url FROM artifacts').all())
222
+ if (!keep.has(url))
223
+ del.run(url);
224
+ });
225
+ }
226
+ function addUnique(list, value, max = Infinity) {
227
+ if (list.includes(value))
228
+ return false;
229
+ list.push(value);
230
+ if (list.length > max)
231
+ list.splice(0, list.length - max);
232
+ return true;
233
+ }
234
+ /** Fold `b` into `a` (the same artifact under two URLs). */
235
+ function merge(a, b) {
236
+ a.uuid ??= b.uuid;
237
+ if (b.title && (!a.title || b.last > a.last))
238
+ a.title = b.title;
239
+ a.first = Math.min(a.first, b.first);
240
+ a.last = Math.max(a.last, b.last);
241
+ for (const c of b.cwds)
242
+ addUnique(a.cwds, c);
243
+ for (const s of b.sessions)
244
+ addUnique(a.sessions, s, MAX_SESSIONS_PER_LINK);
245
+ if (b.deleted)
246
+ a.deleted = true;
247
+ }
248
+ /** Add links found in a session's transcript. Returns whether anything changed. */
249
+ export function record(links, found, sessionKey, cwd) {
250
+ let changed = false;
251
+ for (const f of found) {
252
+ let a = (f.url && links.find((x) => x.url === f.url)) || (f.uuid && links.find((x) => x.uuid === f.uuid)) || undefined;
253
+ if (!a) {
254
+ if (!f.url)
255
+ continue; // a uuid we have no link for yet (a doc edit before any result named its URL)
256
+ a = { url: f.url, ...(f.uuid ? { uuid: f.uuid } : {}), title: '', first: f.at, last: f.at, cwds: [], sessions: [] };
257
+ links.push(a);
258
+ changed = true;
259
+ }
260
+ if (f.uuid && !a.uuid) {
261
+ a.uuid = f.uuid;
262
+ changed = true;
263
+ }
264
+ // This result ties a URL to a uuid that another record holds: they are one artifact.
265
+ const twin = f.uuid ? links.find((x) => x !== a && (x.uuid === f.uuid || (f.url && x.url === f.url))) : undefined;
266
+ if (twin) {
267
+ merge(a, twin);
268
+ links.splice(links.indexOf(twin), 1);
269
+ changed = true;
270
+ }
271
+ // Show the short claude.ai/artifact/<id> form once a result names it.
272
+ if (f.url && a.url !== f.url && !f.url.includes('/code/') && !links.some((x) => x.url === f.url)) {
273
+ a.url = f.url;
274
+ changed = true;
275
+ }
276
+ if (f.title && f.title !== a.title && (!a.title || f.at >= a.last)) {
277
+ a.title = f.title;
278
+ changed = true;
279
+ }
280
+ if (f.at < a.first) {
281
+ a.first = f.at;
282
+ changed = true;
283
+ }
284
+ if (f.at > a.last) {
285
+ a.last = f.at;
286
+ changed = true;
287
+ }
288
+ if (f.deleted && !a.deleted) {
289
+ a.deleted = true;
290
+ changed = true;
291
+ }
292
+ if (cwd && addUnique(a.cwds, cwd))
293
+ changed = true;
294
+ if (addUnique(a.sessions, sessionKey, MAX_SESSIONS_PER_LINK))
295
+ changed = true;
296
+ }
297
+ return changed;
298
+ }
299
+ /** One sync at a time: scans and store writes never interleave. */
300
+ let queue = Promise.resolve();
301
+ function serial(fn) {
302
+ const run = queue.then(fn, fn);
303
+ queue = run.catch(() => { });
304
+ return run;
305
+ }
306
+ async function syncLocked(targets) {
307
+ const links = load();
308
+ let changed = false;
309
+ for (const t of targets) {
310
+ for (const transcript of t.transcripts) {
311
+ for (const file of await transcriptFiles(transcript)) {
312
+ if (record(links, await scanFile(file), t.uid, t.cwd))
313
+ changed = true;
314
+ }
315
+ }
316
+ }
317
+ if (changed)
318
+ save(links);
319
+ }
320
+ /** Read new transcript lines of these sessions and keep the links found. */
321
+ export function syncSessions(targets) {
322
+ return serial(() => syncLocked(targets));
323
+ }
324
+ /**
325
+ * Like syncSessions for every live session, then forget the read positions of transcripts no live
326
+ * session uses any more (an ended session got its final sync when it ended).
327
+ */
328
+ export function syncAll(targets) {
329
+ return serial(async () => {
330
+ await syncLocked(targets);
331
+ const used = new Set(targets.flatMap((t) => t.transcripts));
332
+ for (const path of scans.keys()) {
333
+ const main = path.replace(/\/subagents\/[^/]+\.jsonl$/, '.jsonl');
334
+ if (!used.has(main))
335
+ scans.delete(path);
336
+ }
337
+ });
338
+ }
339
+ /**
340
+ * A live session from before session records got its uid: its links, kept under the old
341
+ * `<tmux id>@<created>` key, now point at the record instead.
342
+ */
343
+ export function rekey(oldKey, uid) {
344
+ return serial(async () => {
345
+ const links = load();
346
+ let changed = false;
347
+ for (const a of links) {
348
+ const i = a.sessions.indexOf(oldKey);
349
+ if (i < 0)
350
+ continue;
351
+ if (a.sessions.includes(uid))
352
+ a.sessions.splice(i, 1);
353
+ else
354
+ a.sessions[i] = uid;
355
+ changed = true;
356
+ }
357
+ if (changed)
358
+ save(links);
359
+ });
360
+ }
361
+ function view(a) {
362
+ return { url: a.url, title: a.title, first: a.first, last: a.last, cwds: a.cwds };
363
+ }
364
+ /** All artifacts, latest first. The page groups them under projects by `cwds`. */
365
+ export function listArtifacts() {
366
+ return load()
367
+ .filter((a) => !a.deleted)
368
+ .sort((a, b) => b.last - a.last)
369
+ .map(view);
370
+ }
371
+ /** The artifacts one session record touched, latest first. */
372
+ export function artifactsOf(uid) {
373
+ if (!uid)
374
+ return [];
375
+ return load()
376
+ .filter((a) => !a.deleted && a.sessions.includes(uid))
377
+ .sort((a, b) => b.last - a.last)
378
+ .map(view);
379
+ }
@@ -0,0 +1,99 @@
1
+ import { homedir } from 'node:os';
2
+ import * as pty from 'node-pty';
3
+ import { sessionExists, tmuxBaseArgs, tmuxEnv, tmuxPath } from './tmux.js';
4
+ /** Every live attach pty, so shutdown can detach them all. */
5
+ const live = new Set();
6
+ export function killAllAttach() {
7
+ for (const p of live) {
8
+ try {
9
+ p.kill();
10
+ }
11
+ catch {
12
+ /* already gone */
13
+ }
14
+ }
15
+ live.clear();
16
+ }
17
+ function clamp(n, lo, hi, dflt) {
18
+ const v = Math.floor(Number(n));
19
+ return Number.isFinite(v) ? Math.min(hi, Math.max(lo, v)) : dflt;
20
+ }
21
+ function sendJson(ws, msg) {
22
+ if (ws.readyState === ws.OPEN)
23
+ ws.send(JSON.stringify(msg));
24
+ }
25
+ /**
26
+ * Bridge one browser view to one tmux session.
27
+ *
28
+ * Wire protocol:
29
+ * browser -> server text {t:"in", d:string} | {t:"resize", cols, rows}
30
+ * server -> browser binary raw terminal output (UTF-8)
31
+ * text {t:"ended"} session is gone (terminated or Claude exited)
32
+ * {t:"detached"} attach client exited but the session still runs
33
+ *
34
+ * Closing the socket kills only this attach client; tmux detaches and Claude keeps running.
35
+ */
36
+ export async function bridge(ws, id, colsIn, rowsIn) {
37
+ if (!(await sessionExists(id))) {
38
+ sendJson(ws, { t: 'ended' });
39
+ ws.close(1000, 'ended');
40
+ return;
41
+ }
42
+ const cols = clamp(colsIn, 2, 1000, 120);
43
+ const rows = clamp(rowsIn, 2, 500, 40);
44
+ const p = pty.spawn(tmuxPath(), [...tmuxBaseArgs(), 'attach-session', '-t', `=${id}`], {
45
+ name: 'xterm-256color',
46
+ cols,
47
+ rows,
48
+ cwd: homedir(),
49
+ env: tmuxEnv(),
50
+ });
51
+ live.add(p);
52
+ let socketClosed = false;
53
+ p.onData((d) => {
54
+ if (ws.readyState === ws.OPEN)
55
+ ws.send(Buffer.from(d, 'utf8'), { binary: true });
56
+ });
57
+ p.onExit(async () => {
58
+ live.delete(p);
59
+ if (socketClosed)
60
+ return;
61
+ const stillThere = await sessionExists(id);
62
+ sendJson(ws, { t: stillThere ? 'detached' : 'ended' });
63
+ ws.close(1000, stillThere ? 'detached' : 'ended');
64
+ });
65
+ ws.on('message', (raw, isBinary) => {
66
+ if (isBinary)
67
+ return;
68
+ let msg;
69
+ try {
70
+ msg = JSON.parse(raw.toString());
71
+ }
72
+ catch {
73
+ return;
74
+ }
75
+ if (msg.t === 'in' && typeof msg.d === 'string') {
76
+ p.write(msg.d);
77
+ }
78
+ else if (msg.t === 'resize') {
79
+ try {
80
+ p.resize(clamp(msg.cols, 2, 1000, cols), clamp(msg.rows, 2, 500, rows));
81
+ }
82
+ catch {
83
+ /* pty already exited */
84
+ }
85
+ }
86
+ });
87
+ ws.on('close', () => {
88
+ socketClosed = true;
89
+ if (live.has(p)) {
90
+ live.delete(p);
91
+ try {
92
+ p.kill(); // SIGHUP -> tmux client detaches; session keeps running
93
+ }
94
+ catch {
95
+ /* already gone */
96
+ }
97
+ }
98
+ });
99
+ }
@@ -0,0 +1,43 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ /** Project root, whether running from server/*.ts (tsx) or dist/server/*.js (built). */
6
+ function findRoot() {
7
+ let dir = dirname(fileURLToPath(import.meta.url));
8
+ for (let i = 0; i < 4; i++) {
9
+ if (existsSync(join(dir, 'package.json')))
10
+ return dir;
11
+ dir = resolve(dir, '..');
12
+ }
13
+ throw new Error('wrkpanel: could not find project root (package.json)');
14
+ }
15
+ export const ROOT = findRoot();
16
+ export const PORT = Number(process.env.WRKPANEL_PORT ?? 8855);
17
+ export const HOST = '127.0.0.1';
18
+ /** tmux socket name. Override only for testing, so a test server never touches your real sessions. */
19
+ export const SOCKET = process.env.WRKPANEL_SOCKET || 'wrkpanel';
20
+ export const TMUX_CONF = join(ROOT, 'tmux.conf');
21
+ /** Claude Code hooks passed to every session with `claude --settings`; they report status to /api/hooks. Its status line reports plan usage to /api/usage. */
22
+ export const HOOKS_FILE = join(ROOT, 'claude-hooks.json');
23
+ /** Where wrkpanel keeps its own data (projects, todos, session records, artifact links). Override for testing, like WRKPANEL_SOCKET. */
24
+ export const DATA_DIR = process.env.WRKPANEL_DATA || join(homedir(), '.config', 'wrkpanel');
25
+ export const DB_FILE = join(DATA_DIR, 'wrkpanel.db');
26
+ /** The JSON files used before SQLite: imported into DB_FILE once (db.ts), then never read. */
27
+ export const PROJECTS_FILE = join(DATA_DIR, 'projects.json');
28
+ export const TODOS_FILE = join(DATA_DIR, 'todos.json');
29
+ export const ARTIFACTS_FILE = join(DATA_DIR, 'artifacts.json');
30
+ export const WEB_DIR = join(ROOT, 'dist', 'web');
31
+ /** `--dev`: Vite serves the page on :5173 (allowed as an origin); the server serves no static files. */
32
+ export const DEV = process.argv.includes('--dev');
33
+ export const DEV_PORT = 5173;
34
+ /** Session ids are always `wp-` + slug. Anything else from the browser is rejected. */
35
+ export const ID_RE = /^wp-[a-z0-9-]{1,40}$/;
36
+ /** A session record's uid (`s-<hex>`, see sessions.ts). */
37
+ export const UID_RE = /^s-[A-Za-z0-9-]{1,40}$/;
38
+ export const ENV_ID = 'WRKPANEL_ID';
39
+ /** Base URL the hooks post to, set in each session's environment. */
40
+ export const ENV_URL = 'WRKPANEL_URL';
41
+ /** Your own status-line command, run by wrkpanel's status line after it reports plan usage (usage.ts). */
42
+ export const ENV_STATUSLINE = 'WRKPANEL_STATUSLINE';
43
+ export const SELF_URL = `http://${HOST}:${PORT}`;