tabherd 0.0.0-stage → 0.6.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.
Files changed (67) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/LICENSE +674 -0
  3. package/README.md +540 -2
  4. package/launcher/npm.js +9 -0
  5. package/lib/agents.js +324 -0
  6. package/lib/codex-client.js +306 -0
  7. package/lib/codex-rollout.js +251 -0
  8. package/lib/codex.js +424 -0
  9. package/lib/comfy.js +479 -0
  10. package/lib/completed.js +55 -0
  11. package/lib/copilot.js +359 -0
  12. package/lib/cursor.js +516 -0
  13. package/lib/dismissed.js +30 -0
  14. package/lib/filters.js +120 -0
  15. package/lib/groups.js +144 -0
  16. package/lib/history.js +253 -0
  17. package/lib/llamacpp.js +159 -0
  18. package/lib/lmstudio.js +134 -0
  19. package/lib/localai.js +291 -0
  20. package/lib/memory.js +55 -0
  21. package/lib/ollama.js +124 -0
  22. package/lib/open-dashboard.js +39 -0
  23. package/lib/opencode.js +371 -0
  24. package/lib/repos.js +81 -0
  25. package/lib/saved.js +33 -0
  26. package/lib/secrets.js +196 -0
  27. package/lib/session-id.js +9 -0
  28. package/lib/settings.js +231 -0
  29. package/lib/store.js +44 -0
  30. package/lib/terminals/index.js +62 -0
  31. package/lib/terminals/kitty.js +126 -0
  32. package/lib/terminals/linux.js +310 -0
  33. package/lib/terminals/macos.js +468 -0
  34. package/lib/terminals/tmux.js +89 -0
  35. package/lib/terminals/unix-driver.js +172 -0
  36. package/lib/terminals/unix.js +204 -0
  37. package/lib/terminals/unsupported.js +22 -0
  38. package/lib/terminals/wezterm.js +103 -0
  39. package/lib/terminals/windows-close.ps1 +125 -0
  40. package/lib/terminals/windows-focus.ps1 +235 -0
  41. package/lib/terminals/windows-pick-folder.ps1 +57 -0
  42. package/lib/terminals/windows-titles.js +124 -0
  43. package/lib/terminals/windows-titles.ps1 +95 -0
  44. package/lib/terminals/windows.js +166 -0
  45. package/lib/ticket-refs.js +184 -0
  46. package/lib/tickets.js +437 -0
  47. package/lib/todos.js +166 -0
  48. package/lib/trackers.js +541 -0
  49. package/lib/transcript.js +314 -0
  50. package/lib/updates.js +186 -0
  51. package/package.json +44 -4
  52. package/public/app.js +4077 -0
  53. package/public/favicon.svg +1 -0
  54. package/public/icons/tabherd-128.png +0 -0
  55. package/public/icons/tabherd-16.png +0 -0
  56. package/public/icons/tabherd-20.png +0 -0
  57. package/public/icons/tabherd-24.png +0 -0
  58. package/public/icons/tabherd-256.png +0 -0
  59. package/public/icons/tabherd-32.png +0 -0
  60. package/public/icons/tabherd-40.png +0 -0
  61. package/public/icons/tabherd-48.png +0 -0
  62. package/public/icons/tabherd-512.png +0 -0
  63. package/public/icons/tabherd-64.png +0 -0
  64. package/public/index.html +655 -0
  65. package/public/lang/es.js +742 -0
  66. package/public/style.css +1443 -0
  67. package/server.js +814 -0
package/lib/cursor.js ADDED
@@ -0,0 +1,516 @@
1
+ 'use strict';
2
+
3
+ // Cursor CLI's sessions (cursor-agent), as cards like Claude's. Each chat has
4
+ // a folder, <config>/chats/<hash of its folder>/<chat ID>/, where <config> is
5
+ // CURSOR_CONFIG_DIR, else $XDG_CONFIG_HOME/cursor, else ~/.cursor. Its
6
+ // meta.json gives the chat's folder, its title once it has one, and when it
7
+ // began and changed. Its transcript,
8
+ // <data>/projects/<folder as a name>/agent-transcripts/<ID>/<ID>.jsonl, where
9
+ // <data> is CURSOR_DATA_DIR or ~/.cursor, has what was asked and answered as
10
+ // the turn goes, and a line where each turn ended.
11
+ //
12
+ // Cursor records no process for a chat, so each window is matched to its
13
+ // chat by its tab's title, which Cursor sets to the chat's title, or by the
14
+ // chat begun in it since it started. With Cursor's status indicators on
15
+ // (/status-indicators), the title also says whether it's working, waiting for
16
+ // you or ready. Without them, the transcript says whether a turn is running,
17
+ // but not that it's waiting on an approval.
18
+
19
+ const fs = require('fs');
20
+ const os = require('os');
21
+ const path = require('path');
22
+ const { execFile } = require('child_process');
23
+ const { Transcript, clip } = require('./transcript');
24
+ const terminals = require('./terminals');
25
+
26
+ const IS_WIN = process.platform === 'win32';
27
+ const setting = (name) => (process.env[name] || '').trim();
28
+ const CONFIG_DIR = setting('CURSOR_CONFIG_DIR') || (setting('XDG_CONFIG_HOME') ? path.join(setting('XDG_CONFIG_HOME'), 'cursor') : path.join(os.homedir(), '.cursor'));
29
+ const CHATS_DIR = path.join(CONFIG_DIR, 'chats');
30
+ const PROJECTS_DIR = path.join(setting('CURSOR_DATA_DIR') || path.join(os.homedir(), '.cursor'), 'projects');
31
+ const WINDOWS_REFRESH_MS = 3000;
32
+ const CHATS_REFRESH_MS = 3000;
33
+ const SEARCH_AGAIN_MS = 10000;
34
+ // A chat begun this soon before its window's process was seen to start is
35
+ // still that window's: the two clocks are read separately.
36
+ const START_SLACK_MS = 2000;
37
+ const NO_SUBAGENTS = { running: [], finished: [], finishedTotal: 0 };
38
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
39
+ // cursor-agent runs as the Node its install brought, on
40
+ // .../cursor-agent/versions/<version>/index.js, then its own arguments.
41
+ const ENTRY = /cursor-agent[\\/]versions[\\/]([^\\/"\s]+)[\\/]index\.js"?(.*)$/i;
42
+ // Its commands that aren't a window with a chat in it, and the flags that
43
+ // run without one.
44
+ const NOT_A_SESSION = new Set(
45
+ 'login logout mcp plugin worker worker-server status whoami models team bedrock about update upgrade create-chat generate-rule rule help'.split(' '),
46
+ );
47
+ const NO_WINDOW = new Set(['-p', '--print', '-v', '--version', '-h', '--help', '--list-models']);
48
+ // What Cursor calls a window or chat with no title yet, maybe with its
49
+ // worktree after it.
50
+ const UNTITLED = /^(Cursor Agent|New Agent)( \(.*\))?$/;
51
+ // The state at the end of a tab's title, with the status indicators on: the
52
+ // chat's title, " - ", an emoji, and the state ("⏳ Working ...", "✅ Ready").
53
+ const STATE_IN_TITLE =
54
+ / - (?:\S+ )?(Moving to cloud|Loading conversation|Reconnecting|Running shell command|Planning|Working[ .·]*|Queued|Waiting for you|Waiting for confirmation|Reviewing changes|Ready)$/u;
55
+
56
+ // ---- windows ------------------------------------------------------------------
57
+
58
+ function run(cmd, args) {
59
+ return new Promise((resolve) => {
60
+ execFile(cmd, args, { windowsHide: true, timeout: 15000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => resolve(err && !stdout ? null : String(stdout)));
61
+ });
62
+ }
63
+
64
+ // Whether cursor-agent's arguments are a window with a chat in it.
65
+ function isSessionWindow(args) {
66
+ if (args.some((a) => NO_WINDOW.has(a))) return false;
67
+ const first = args.find((a) => !a.startsWith('-'));
68
+ return !first || !NOT_A_SESSION.has(first);
69
+ }
70
+
71
+ // The chat a window was started on, from its command line.
72
+ function resumeArg(args) {
73
+ const at = args.indexOf('--resume');
74
+ const id = at >= 0 ? args[at + 1] : args.find((a) => a.startsWith('--resume='))?.slice(9);
75
+ return id && UUID.test(id) ? id : null;
76
+ }
77
+
78
+ // What a process's command line says, if it's cursor-agent in a window: its
79
+ // version, and the chat and model it was started on.
80
+ function windowFrom(commandLine) {
81
+ const m = String(commandLine || '').match(ENTRY);
82
+ if (!m) return null;
83
+ const args = m[2].trim().split(/\s+/).filter(Boolean);
84
+ if (!isSessionWindow(args)) return null;
85
+ const model = args[args.indexOf('--model') + 1];
86
+ return { version: m[1], resume: resumeArg(args), model: args.includes('--model') && model && !model.startsWith('-') ? model : null };
87
+ }
88
+
89
+ // How long ps says a process has run, [[dd-]hh:]mm:ss, in ms.
90
+ function elapsed(text) {
91
+ const m = String(text).match(/^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/);
92
+ return m ? (((Number(m[1] || 0) * 24 + Number(m[2] || 0)) * 60 + Number(m[3])) * 60 + Number(m[4])) * 1000 : null;
93
+ }
94
+
95
+ // The cursor-agent processes in windows: [{ pid, memBytes, startedAt, version, resume, model }].
96
+ async function findWindows() {
97
+ const found = [];
98
+ const add = (pid, memBytes, startedAt, commandLine) => {
99
+ const w = windowFrom(commandLine);
100
+ if (w) found.push({ pid, memBytes, startedAt, ...w });
101
+ };
102
+ if (IS_WIN) {
103
+ const script =
104
+ `Get-CimInstance Win32_Process -Filter "Name like 'node%' and CommandLine like '%cursor-agent%'" | ForEach-Object { ` +
105
+ `'{0}|{1}|{2}|{3}' -f $_.ProcessId, $_.WorkingSetSize, ([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds(), $_.CommandLine }`;
106
+ const out = await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script]);
107
+ if (out === null) return null;
108
+ for (const line of out.split(/\r?\n/)) {
109
+ const [pid, ws, start, ...cmd] = line.trim().split('|');
110
+ if (pid) add(Number(pid), Number(ws) || null, Number(start) || null, cmd.join('|'));
111
+ }
112
+ } else {
113
+ const out = await run('ps', ['-A', '-o', 'pid=,rss=,etime=,args=']);
114
+ if (out === null) return null;
115
+ const now = Date.now();
116
+ for (const line of out.split('\n')) {
117
+ const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/);
118
+ const ran = m && elapsed(m[3]);
119
+ if (m) add(Number(m[1]), Number(m[2]) * 1024, ran === null ? null : now - ran, m[4]);
120
+ }
121
+ }
122
+ return found;
123
+ }
124
+
125
+ let windows = [];
126
+ let windowsAt = 0;
127
+ let windowsPending = null;
128
+
129
+ function refreshWindows() {
130
+ if (windowsPending || Date.now() - windowsAt < WINDOWS_REFRESH_MS) return;
131
+ windowsPending = findWindows().then((found) => {
132
+ if (found) {
133
+ windows = found;
134
+ windowsAt = Date.now();
135
+ }
136
+ windowsPending = null;
137
+ });
138
+ }
139
+
140
+ // What a tab's title shows: the chat's title, '' while it has none, and the
141
+ // state Cursor's status indicators add, if they're on.
142
+ function readTitle(tab) {
143
+ const t = String(tab || '').trim();
144
+ const m = t.match(STATE_IN_TITLE);
145
+ const name = (m ? t.slice(0, m.index) : t).trim();
146
+ return { name: UNTITLED.test(name) ? '' : name, state: m ? m[1].replace(/[ .·]+$/, '') : null };
147
+ }
148
+
149
+ // Whether a tab's title shows that chat: its title, maybe with its worktree after it.
150
+ const shows = (name, chat) => Boolean(name && chat.title && (name === chat.title || name.startsWith(`${chat.title} (`)));
151
+
152
+ // Each window's chat: the one it was started on, else the one whose title its
153
+ // tab shows, if no other chat has that title, else the newest begun since the
154
+ // window started, as a new chat has no title until its first prompt.
155
+ function matchWindows(chats, wins, titleFor = terminals.titleFor) {
156
+ const byPid = new Map();
157
+ const taken = new Set();
158
+ const take = (w, c) => {
159
+ byPid.set(w.pid, c);
160
+ taken.add(c.id);
161
+ };
162
+ for (const w of wins) {
163
+ const c = w.resume && chats.find((x) => x.id === w.resume);
164
+ if (c) take(w, c);
165
+ }
166
+ const titles = new Map();
167
+ for (const c of chats) if (c.title) titles.set(c.title, (titles.get(c.title) || 0) + 1);
168
+ const shown = new Map(wins.map((w) => [w.pid, readTitle(titleFor(w.pid)).name]));
169
+ for (const w of wins) {
170
+ if (byPid.has(w.pid)) continue;
171
+ const matches = chats.filter((c) => !taken.has(c.id) && shows(shown.get(w.pid), c));
172
+ if (matches.length === 1 && titles.get(matches[0].title) === 1) take(w, matches[0]);
173
+ }
174
+ // The latest window first, so each takes the chats begun since it started,
175
+ // and an earlier one those before.
176
+ const rank = (name, c) => (shows(name, c) ? 0 : c.title ? 2 : 1);
177
+ for (const w of wins.filter((x) => !byPid.has(x.pid) && x.startedAt).sort((a, b) => b.startedAt - a.startedAt)) {
178
+ const name = shown.get(w.pid);
179
+ const since = chats
180
+ .filter((c) => !taken.has(c.id) && c.createdAt >= w.startedAt - START_SLACK_MS)
181
+ .sort((a, b) => rank(name, a) - rank(name, b) || b.createdAt - a.createdAt);
182
+ if (since[0]) take(w, since[0]);
183
+ }
184
+ return byPid;
185
+ }
186
+
187
+ // ---- chats ------------------------------------------------------------------------
188
+
189
+ function chatFrom(id, file) {
190
+ try {
191
+ const m = JSON.parse(fs.readFileSync(file, 'utf8'));
192
+ if (!m || typeof m !== 'object' || m.isSubagent) return null;
193
+ const title = typeof m.title === 'string' ? m.title.trim() : '';
194
+ return {
195
+ id,
196
+ title: title && !UNTITLED.test(title) ? title : null,
197
+ cwd: typeof m.cwd === 'string' && m.cwd ? m.cwd : null,
198
+ createdAt: Number(m.createdAtMs) || null,
199
+ updatedAt: Number(m.updatedAtMs) || null,
200
+ hasConversation: m.hasConversation === true,
201
+ };
202
+ } catch {
203
+ return null;
204
+ }
205
+ }
206
+
207
+ const listDir = (dir) => {
208
+ try {
209
+ return fs.readdirSync(dir);
210
+ } catch {
211
+ return [];
212
+ }
213
+ };
214
+
215
+ // Every chat's meta.json, read again only once it's changed.
216
+ const metas = new Map();
217
+
218
+ function readChats() {
219
+ const chats = [];
220
+ const seen = new Set();
221
+ for (const hash of listDir(CHATS_DIR)) {
222
+ for (const id of listDir(path.join(CHATS_DIR, hash))) {
223
+ if (!UUID.test(id)) continue;
224
+ const file = path.join(CHATS_DIR, hash, id, 'meta.json');
225
+ let mtime;
226
+ try {
227
+ mtime = fs.statSync(file).mtimeMs;
228
+ } catch {
229
+ continue;
230
+ }
231
+ seen.add(file);
232
+ let m = metas.get(file);
233
+ if (!m || m.mtime !== mtime) {
234
+ m = { mtime, chat: chatFrom(id, file) };
235
+ // One caught while it's being written is read again next time.
236
+ if (m.chat) metas.set(file, m);
237
+ else metas.delete(file);
238
+ }
239
+ if (m.chat) chats.push(m.chat);
240
+ }
241
+ }
242
+ for (const file of metas.keys()) if (!seen.has(file)) metas.delete(file);
243
+ return chats;
244
+ }
245
+
246
+ let chats = [];
247
+ let chatsAt = 0;
248
+
249
+ function refreshChats(now = Date.now()) {
250
+ if (now - chatsAt < CHATS_REFRESH_MS) return;
251
+ chatsAt = now;
252
+ chats = readChats();
253
+ }
254
+
255
+ // A folder as Cursor names its project folder: "C:\work\app" -> "C-work-app".
256
+ const folderName = (dir) =>
257
+ String(dir)
258
+ .replace(/[^a-zA-Z0-9]/g, '-')
259
+ .replace(/-+/g, '-')
260
+ .replace(/^-+|-+$/g, '');
261
+
262
+ const transcriptPaths = new Map();
263
+ const searchedAt = new Map();
264
+
265
+ // A chat's transcript: in its folder's project folder, else in any project
266
+ // folder, as a chat started with --workspace has that one's. A new chat has
267
+ // none until its first prompt.
268
+ function findTranscript(chat, now = Date.now()) {
269
+ const cached = transcriptPaths.get(chat.id);
270
+ if (cached && fs.existsSync(cached)) return cached;
271
+ const inProject = (dir) => [path.join(PROJECTS_DIR, dir, 'agent-transcripts', chat.id, `${chat.id}.jsonl`), path.join(PROJECTS_DIR, dir, 'agent-transcripts', `${chat.id}.jsonl`)];
272
+ let found = chat.cwd ? inProject(folderName(chat.cwd)).find((f) => fs.existsSync(f)) : null;
273
+ if (!found && now - (searchedAt.get(chat.id) || 0) >= SEARCH_AGAIN_MS) {
274
+ searchedAt.set(chat.id, now);
275
+ for (const dir of listDir(PROJECTS_DIR)) {
276
+ found = inProject(dir).find((f) => fs.existsSync(f));
277
+ if (found) break;
278
+ }
279
+ }
280
+ if (found) transcriptPaths.set(chat.id, found);
281
+ return found || null;
282
+ }
283
+
284
+ // The prompt in a user line: what's in <user_query>, without the
285
+ // <timestamp> Cursor adds, and when that says it was sent.
286
+ function promptIn(text) {
287
+ const t = String(text || '');
288
+ const query = t.match(/<user_query>([\s\S]*?)<\/user_query>/);
289
+ const prompt = (query ? query[1] : t.replace(/<timestamp>[\s\S]*?<\/timestamp>/, '')).trim();
290
+ if (!prompt || (!query && prompt.startsWith('<'))) return null;
291
+ return { text: prompt, at: sentAt(t.match(/<timestamp>([\s\S]*?)<\/timestamp>/)?.[1]) };
292
+ }
293
+
294
+ const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
295
+
296
+ // "Wednesday, Nov 25, 2026, 7:47 PM (UTC-5)", to the minute, in ms.
297
+ function sentAt(text) {
298
+ const m = String(text || '').match(/([A-Za-z]{3})[a-z]* (\d{1,2}), (\d{4}),? (\d{1,2}):(\d{2})\s*(AM|PM)?\s*\(UTC(?:([+-])(\d{1,2})(?::?(\d{2}))?)?\)/i);
299
+ const month = m ? MONTHS.indexOf(m[1].toLowerCase()) : -1;
300
+ if (month < 0) return null;
301
+ let hour = Number(m[4]) % (m[6] ? 12 : 24);
302
+ if (m[6]?.toUpperCase() === 'PM') hour += 12;
303
+ const offset = (m[7] === '-' ? -1 : 1) * (Number(m[8] || 0) * 60 + Number(m[9] || 0));
304
+ return Date.UTC(Number(m[3]), month, Number(m[2]), hour, Number(m[5])) - offset * 60000;
305
+ }
306
+
307
+ // What a tool call is about: its command, else its file, search or address.
308
+ function describe(input) {
309
+ const a = input && typeof input === 'object' ? input : {};
310
+ const text = a.command || a.path || a.file_path || a.target_file || a.pattern || a.query || a.url || Object.values(a).find((v) => typeof v === 'string' && v.length < 200) || '';
311
+ const t = String(text).replace(/\s+/g, ' ').trim();
312
+ return t.length > 160 ? `${t.slice(0, 159)}…` : t;
313
+ }
314
+
315
+ // A transcript, read a few new bytes at a time like a Claude one, into the
316
+ // same summary, plus whether a turn is running and how the last one ended.
317
+ // Its lines have no times, so a reply is given the time the file was written,
318
+ // read just before its new lines are.
319
+ class CursorLog extends Transcript {
320
+ reset() {
321
+ super.reset();
322
+ Object.assign(this.s, { turnOpen: false, lastTurn: null });
323
+ }
324
+
325
+ update() {
326
+ try {
327
+ this.writtenAt = fs.statSync(this.file).mtimeMs;
328
+ } catch {
329
+ return false;
330
+ }
331
+ return super.update();
332
+ }
333
+
334
+ line(line) {
335
+ if (!line) return;
336
+ let e;
337
+ try {
338
+ e = JSON.parse(line);
339
+ } catch {
340
+ return;
341
+ }
342
+ const s = this.s;
343
+ if (e.type === 'turn_ended') {
344
+ s.turnOpen = false;
345
+ s.lastTurn = typeof e.status === 'string' ? e.status : null;
346
+ s.tools.clear();
347
+ return;
348
+ }
349
+ const content = Array.isArray(e.message?.content) ? e.message.content : [];
350
+ const text = content
351
+ .filter((c) => c?.type === 'text' && typeof c.text === 'string')
352
+ .map((c) => c.text)
353
+ .join('\n')
354
+ .trim();
355
+ if (e.role === 'user') {
356
+ const prompt = promptIn(text);
357
+ if (!prompt) return;
358
+ s.tools.clear();
359
+ s.turnOpen = true;
360
+ s.lastTurn = null;
361
+ s.lastPrompt = { text: clip(prompt.text), at: prompt.at ?? this.writtenAt };
362
+ s.firstPrompt = s.firstPrompt || s.lastPrompt;
363
+ s.prompts++;
364
+ this.noteTickets(prompt.text, 'prompt');
365
+ } else if (e.role === 'assistant') {
366
+ // A step's tool calls are done once the next step is written.
367
+ s.tools.clear();
368
+ content.forEach((c, i) => {
369
+ if (c?.type === 'tool_use') s.tools.set(i, { name: c.name || 'Tool', detail: describe(c.input), at: null });
370
+ });
371
+ if (text) {
372
+ s.lastReply = { text: clip(text), at: this.writtenAt };
373
+ this.noteTickets(text, 'reply');
374
+ }
375
+ }
376
+ }
377
+
378
+ summary() {
379
+ const s = this.s;
380
+ return { ...super.summary(), contextLimit: 0, contextTokens: 0, turnOpen: s.turnOpen, lastTurn: s.lastTurn };
381
+ }
382
+ }
383
+
384
+ const logs = new Map();
385
+
386
+ function readLog(file, used) {
387
+ let log = logs.get(file);
388
+ if (!log) {
389
+ log = new CursorLog(file);
390
+ logs.set(file, log);
391
+ }
392
+ used.add(file);
393
+ return log.update() ? log.summary() : null;
394
+ }
395
+
396
+ // What an approval is for, from the tool call the turn stopped on.
397
+ function approvalFor(s) {
398
+ const tool = s?.tools?.[s.tools.length - 1];
399
+ if (!tool) return 'Approval';
400
+ if (/^(shell|bash|terminal)/i.test(tool.name) && tool.detail) return `Approval: run ${tool.detail}`;
401
+ return `Approval: ${[tool.name, tool.detail].filter(Boolean).join(' ')}`;
402
+ }
403
+
404
+ // A chat's state: from its tab's title, if the status indicators are on,
405
+ // else from its transcript, where a turn with no end is still running. A
406
+ // turn that failed needs you too.
407
+ function stateOf(state, s) {
408
+ if (state === 'Waiting for confirmation') return { status: 'waiting', waitingFor: approvalFor(s) };
409
+ if (state === 'Waiting for you') return { status: 'waiting', waitingFor: 'Your answer' };
410
+ if (state && state !== 'Ready') return { status: 'busy', waitingFor: null };
411
+ if (!state && s?.turnOpen) return { status: 'busy', waitingFor: null };
412
+ if (s?.lastTurn === 'error') return { status: 'waiting', waitingFor: 'Its last turn failed' };
413
+ return { status: 'idle', waitingFor: null };
414
+ }
415
+
416
+ // When each chat's state began, as first seen.
417
+ const since = new Map();
418
+
419
+ // The cards for these chats and windows, as the page shows sessions.
420
+ function agentsFrom(allChats, wins, { titleFor = terminals.titleFor, now = Date.now() } = {}) {
421
+ const byPid = matchWindows(allChats, wins, titleFor);
422
+ const used = new Set();
423
+ const agents = [];
424
+ for (const w of wins) {
425
+ const chat = byPid.get(w.pid);
426
+ if (!chat) continue;
427
+ const file = findTranscript(chat, now);
428
+ const s = file ? readLog(file, used) : null;
429
+ const st = stateOf(readTitle(titleFor(w.pid)).state, s);
430
+ const key = `${st.status}:${st.waitingFor}`;
431
+ if (since.get(chat.id)?.key !== key) since.set(chat.id, { key, at: now });
432
+ agents.push({
433
+ ...(s || {}),
434
+ app: 'cursor',
435
+ id: chat.id,
436
+ pid: w.pid,
437
+ title: chat.title,
438
+ name: chat.title || path.basename(chat.cwd || '') || 'Cursor',
439
+ cwd: chat.cwd,
440
+ kind: 'interactive',
441
+ entrypoint: 'cli',
442
+ version: w.version || null,
443
+ model: w.model || null,
444
+ modelName: w.model || null,
445
+ status: st.status,
446
+ waitingFor: st.waitingFor,
447
+ statusSince: since.get(chat.id).at,
448
+ startedAt: chat.createdAt || w.startedAt || null,
449
+ memBytes: w.memBytes ?? null,
450
+ terminalTitle: null,
451
+ tools: st.status === 'idle' ? [] : s?.tools || [],
452
+ subagents: NO_SUBAGENTS,
453
+ });
454
+ }
455
+ for (const f of logs.keys()) if (!used.has(f)) logs.delete(f);
456
+ const live = new Set(agents.map((a) => a.id));
457
+ for (const id of since.keys()) if (!live.has(id)) since.delete(id);
458
+ return agents;
459
+ }
460
+
461
+ // Cursor's cards, and the windows whose tab titles the next snapshot needs.
462
+ // Its chats are only read while one of its windows is open.
463
+ function snapshot(now = Date.now()) {
464
+ refreshWindows();
465
+ if (!windows.length) return { agents: [], windowPids: [] };
466
+ refreshChats(now);
467
+ return { agents: agentsFrom(chats, windows, { now }), windowPids: windows.map((w) => w.pid) };
468
+ }
469
+
470
+ // ---- driving sessions ------------------------------------------------------------
471
+
472
+ // The command a new tab runs: cursor-agent, allowing commands it doesn't deny
473
+ // if Settings says to skip permission prompts, resuming a chat if given one.
474
+ // A chat is kept with its folder, so it's resumed from there.
475
+ function command({ skipPermissions = false, resume = null } = {}) {
476
+ const parts = ['cursor-agent'];
477
+ if (skipPermissions) parts.push('--force');
478
+ if (resume && UUID.test(resume)) parts.push('--resume', resume);
479
+ return parts.join(' ');
480
+ }
481
+
482
+ // ---- history -----------------------------------------------------------------------
483
+
484
+ // Chats with a transcript changed since `floor`: [{ id, file, mtime, chat }].
485
+ async function sessionFiles(floor) {
486
+ const found = [];
487
+ for (const chat of readChats()) {
488
+ if (!chat.hasConversation || !chat.cwd || (chat.updatedAt || 0) < floor) continue;
489
+ const file = findTranscript(chat);
490
+ if (!file) continue;
491
+ try {
492
+ const mtime = (await fs.promises.stat(file)).mtimeMs;
493
+ if (mtime >= floor) found.push({ id: chat.id, file, mtime, chat });
494
+ } catch {}
495
+ }
496
+ return found;
497
+ }
498
+
499
+ module.exports = {
500
+ snapshot,
501
+ agentsFrom,
502
+ matchWindows,
503
+ readTitle,
504
+ windowFrom,
505
+ isSessionWindow,
506
+ elapsed,
507
+ promptIn,
508
+ sentAt,
509
+ stateOf,
510
+ command,
511
+ sessionFiles,
512
+ folderName,
513
+ CursorLog,
514
+ CHATS_DIR,
515
+ PROJECTS_DIR,
516
+ };
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+
3
+ const store = require('./store');
4
+
5
+ // Failed jobs, chats and downloads cleared from the dashboard, by card ID, so
6
+ // they stay cleared after a restart and in every browser. Saved as
7
+ // dismissed.json; the latest 500 are kept, which outlasts the day a failure
8
+ // is shown for.
9
+
10
+ const MAX = 500;
11
+
12
+ function load() {
13
+ const saved = store.read('dismissed', null);
14
+ const list = Array.isArray(saved?.ids) ? saved.ids.filter((x) => typeof x?.id === 'string' && x.id.length <= 300) : [];
15
+ return new Map(list.map((x) => [x.id, Number(x.at) || 0]));
16
+ }
17
+
18
+ let ids = load();
19
+
20
+ function add(id, now = Date.now()) {
21
+ const next = new Map(ids);
22
+ next.set(id, now);
23
+ const kept = [...next].sort((a, b) => b[1] - a[1]).slice(0, MAX);
24
+ store.write('dismissed', { ids: kept.map(([i, at]) => ({ id: i, at })) });
25
+ ids = new Map(kept);
26
+ }
27
+
28
+ const has = (id) => ids.has(id);
29
+
30
+ module.exports = { add, has };
package/lib/filters.js ADDED
@@ -0,0 +1,120 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const store = require('./store');
5
+
6
+ // The filter tabs across the top of the dashboard, after All, which is always
7
+ // there. Each shows the cards that match everything it names: their status,
8
+ // their app, their group, their tickets' status, and words in their name or
9
+ // folder. A list left empty matches any. To-do cards show only under the
10
+ // filters that ask for them. Until they're changed, the tabs are the four the
11
+ // dashboard always had, and Ticket done, which shows once there's a tracker.
12
+
13
+ // Status groups, with Shell running apart from the rest of Working.
14
+ const STATUSES = ['needs', 'working', 'shell', 'idle'];
15
+ // A card's tickets' status, in the dashboard's groups for them, or none. A
16
+ // card with several goes by its least finished: closed counts as finished,
17
+ // without being done.
18
+ const TICKETS = ['todo', 'progress', 'done', 'closed', 'none'];
19
+ // filters.json's version. Version 1 had no Shell running of its own, and
20
+ // version 2 no tickets.
21
+ const VERSION = 3;
22
+ const APPS = ['claude', 'codex', 'copilot', 'opencode', 'cursor', 'comfy', 'localai', 'ollama', 'lmstudio', 'llamacpp'];
23
+ const MAX_FILTERS = 12;
24
+ const MAX_GROUPS = 20;
25
+ const NAME_MAX = 24;
26
+ const TEXT_MAX = 100;
27
+ const ID = /^[A-Za-z0-9_-]{1,40}$/;
28
+
29
+ // A session whose work its tickets say is finished, which may be ready to close.
30
+ const TICKET_DONE = { id: 'ticket-done', name: 'Ticket done', statuses: [], apps: [], groups: [], tickets: ['done', 'closed'], todos: false, text: '' };
31
+
32
+ const DEFAULTS = [
33
+ { id: 'todo', name: 'Todo', statuses: ['needs', 'idle'], apps: [], groups: [], tickets: [], todos: true, text: '' },
34
+ { id: 'needs', name: 'Needs you', statuses: ['needs'], apps: [], groups: [], tickets: [], todos: false, text: '' },
35
+ { id: 'working', name: 'Working', statuses: ['working', 'shell'], apps: [], groups: [], tickets: [], todos: false, text: '' },
36
+ { id: 'idle', name: 'Idle', statuses: ['idle'], apps: [], groups: [], tickets: [], todos: false, text: '' },
37
+ TICKET_DONE,
38
+ ];
39
+
40
+ // Each of `given` that's one of `allowed`, once, in the order given.
41
+ const pick = (given, allowed) => [...new Set((Array.isArray(given) ? given : []).filter((x) => allowed(x)))];
42
+
43
+ // A filter as given, cleaned, or a reason it can't be saved.
44
+ function cleanFilter(f) {
45
+ if (!f || typeof f !== 'object') return { error: 'Not a filter.' };
46
+ const name = typeof f.name === 'string' ? f.name.replace(/\s+/g, ' ').trim() : '';
47
+ if (!name) return { error: 'A filter needs a name.' };
48
+ if (name.length > NAME_MAX) return { error: `Keep filter names to ${NAME_MAX} characters.` };
49
+ if (name.toLowerCase() === 'all') return { error: 'All is already there.' };
50
+ const text = typeof f.text === 'string' ? f.text.replace(/\s+/g, ' ').trim() : '';
51
+ if (text.length > TEXT_MAX) return { error: `Keep the words to ${TEXT_MAX} characters.` };
52
+ const groups = pick(f.groups, (g) => typeof g === 'string' && ID.test(g));
53
+ if (groups.length > MAX_GROUPS + 1) return { error: 'Too many groups.' };
54
+ return {
55
+ filter: {
56
+ id: typeof f.id === 'string' && ID.test(f.id) ? f.id : crypto.randomUUID(),
57
+ name,
58
+ statuses: pick(f.statuses, (s) => STATUSES.includes(s)),
59
+ apps: pick(f.apps, (a) => APPS.includes(a)),
60
+ groups,
61
+ tickets: pick(f.tickets, (s) => TICKETS.includes(s)),
62
+ todos: f.todos === true,
63
+ text,
64
+ },
65
+ };
66
+ }
67
+
68
+ // Filters saved before Shell running could be picked on its own counted it as
69
+ // Working, so one that picks Working picks it too. Ticket done is added once,
70
+ // to the filters saved before it, if there's room and none has its name; once
71
+ // they're saved again, deleting it keeps it gone.
72
+ function upgrade(saved) {
73
+ let list = saved.filters;
74
+ if (!(saved.version >= 2)) {
75
+ list = list.map((f) =>
76
+ Array.isArray(f?.statuses) && f.statuses.includes('working') && !f.statuses.includes('shell') ? { ...f, statuses: [...f.statuses, 'shell'] } : f,
77
+ );
78
+ }
79
+ const named = (f) => f?.id === TICKET_DONE.id || (typeof f?.name === 'string' && f.name.trim().toLowerCase() === TICKET_DONE.name.toLowerCase());
80
+ if (!(saved.version >= 3) && list.length < MAX_FILTERS && !list.some(named)) list = [...list, TICKET_DONE];
81
+ return list;
82
+ }
83
+
84
+ function load() {
85
+ const saved = store.read('filters', null);
86
+ if (!Array.isArray(saved?.filters)) return DEFAULTS;
87
+ const filters = [];
88
+ for (const f of upgrade(saved)) {
89
+ const { filter } = cleanFilter(f);
90
+ if (filter && filters.length < MAX_FILTERS && !filters.some((x) => x.id === filter.id)) filters.push(filter);
91
+ }
92
+ return filters;
93
+ }
94
+
95
+ let state = load();
96
+
97
+ const list = () => state;
98
+
99
+ // Replaces every filter, in the order given, as the page saves them.
100
+ function setFilters(given) {
101
+ if (!Array.isArray(given)) return { ok: false, error: 'Expected a list of filters.' };
102
+ if (given.length > MAX_FILTERS) return { ok: false, error: `Up to ${MAX_FILTERS} filters, besides All.` };
103
+ const filters = [];
104
+ for (const f of given) {
105
+ const { filter, error } = cleanFilter(f);
106
+ if (error) return { ok: false, error };
107
+ if (filters.some((x) => x.id === filter.id)) return { ok: false, error: 'Two filters have the same ID.' };
108
+ if (filters.some((x) => x.name.toLowerCase() === filter.name.toLowerCase())) return { ok: false, error: `There's already a filter called ${filter.name}.` };
109
+ filters.push(filter);
110
+ }
111
+ try {
112
+ store.write('filters', { version: VERSION, filters });
113
+ } catch (err) {
114
+ return { ok: false, error: `Couldn't save the filters: ${err.message}` };
115
+ }
116
+ state = filters;
117
+ return { ok: true, filters };
118
+ }
119
+
120
+ module.exports = { list, setFilters, cleanFilter, upgrade, DEFAULTS, MAX_FILTERS };