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.
- package/CHANGELOG.md +166 -0
- package/LICENSE +674 -0
- package/README.md +540 -2
- package/launcher/npm.js +9 -0
- package/lib/agents.js +324 -0
- package/lib/codex-client.js +306 -0
- package/lib/codex-rollout.js +251 -0
- package/lib/codex.js +424 -0
- package/lib/comfy.js +479 -0
- package/lib/completed.js +55 -0
- package/lib/copilot.js +359 -0
- package/lib/cursor.js +516 -0
- package/lib/dismissed.js +30 -0
- package/lib/filters.js +120 -0
- package/lib/groups.js +144 -0
- package/lib/history.js +253 -0
- package/lib/llamacpp.js +159 -0
- package/lib/lmstudio.js +134 -0
- package/lib/localai.js +291 -0
- package/lib/memory.js +55 -0
- package/lib/ollama.js +124 -0
- package/lib/open-dashboard.js +39 -0
- package/lib/opencode.js +371 -0
- package/lib/repos.js +81 -0
- package/lib/saved.js +33 -0
- package/lib/secrets.js +196 -0
- package/lib/session-id.js +9 -0
- package/lib/settings.js +231 -0
- package/lib/store.js +44 -0
- package/lib/terminals/index.js +62 -0
- package/lib/terminals/kitty.js +126 -0
- package/lib/terminals/linux.js +310 -0
- package/lib/terminals/macos.js +468 -0
- package/lib/terminals/tmux.js +89 -0
- package/lib/terminals/unix-driver.js +172 -0
- package/lib/terminals/unix.js +204 -0
- package/lib/terminals/unsupported.js +22 -0
- package/lib/terminals/wezterm.js +103 -0
- package/lib/terminals/windows-close.ps1 +125 -0
- package/lib/terminals/windows-focus.ps1 +235 -0
- package/lib/terminals/windows-pick-folder.ps1 +57 -0
- package/lib/terminals/windows-titles.js +124 -0
- package/lib/terminals/windows-titles.ps1 +95 -0
- package/lib/terminals/windows.js +166 -0
- package/lib/ticket-refs.js +184 -0
- package/lib/tickets.js +437 -0
- package/lib/todos.js +166 -0
- package/lib/trackers.js +541 -0
- package/lib/transcript.js +314 -0
- package/lib/updates.js +186 -0
- package/package.json +44 -4
- package/public/app.js +4077 -0
- package/public/favicon.svg +1 -0
- package/public/icons/tabherd-128.png +0 -0
- package/public/icons/tabherd-16.png +0 -0
- package/public/icons/tabherd-20.png +0 -0
- package/public/icons/tabherd-24.png +0 -0
- package/public/icons/tabherd-256.png +0 -0
- package/public/icons/tabherd-32.png +0 -0
- package/public/icons/tabherd-40.png +0 -0
- package/public/icons/tabherd-48.png +0 -0
- package/public/icons/tabherd-512.png +0 -0
- package/public/icons/tabherd-64.png +0 -0
- package/public/index.html +655 -0
- package/public/lang/es.js +742 -0
- package/public/style.css +1443 -0
- package/server.js +814 -0
package/lib/agents.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { execFile } = require('child_process');
|
|
7
|
+
const { Transcript } = require('./transcript');
|
|
8
|
+
const terminals = require('./terminals');
|
|
9
|
+
const codex = require('./codex');
|
|
10
|
+
const comfy = require('./comfy');
|
|
11
|
+
const localai = require('./localai');
|
|
12
|
+
const copilot = require('./copilot');
|
|
13
|
+
const opencode = require('./opencode');
|
|
14
|
+
const cursor = require('./cursor');
|
|
15
|
+
const ollama = require('./ollama');
|
|
16
|
+
const lmstudio = require('./lmstudio');
|
|
17
|
+
const llamacpp = require('./llamacpp');
|
|
18
|
+
const memory = require('./memory');
|
|
19
|
+
const { version } = require('../package.json');
|
|
20
|
+
|
|
21
|
+
const CLAUDE_DIR = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
|
|
22
|
+
const SESSIONS_DIR = path.join(CLAUDE_DIR, 'sessions');
|
|
23
|
+
const PROJECTS_DIR = path.join(CLAUDE_DIR, 'projects');
|
|
24
|
+
const IS_WIN = process.platform === 'win32';
|
|
25
|
+
const PROC_REFRESH_MS = 10000;
|
|
26
|
+
const FINISHED_SUBAGENTS = 5;
|
|
27
|
+
const PROCESS_NAMES = /^(claude|node|bun)(\.exe)?$/i;
|
|
28
|
+
const NO_SUBAGENTS = { running: [], finished: [], finishedTotal: 0 };
|
|
29
|
+
|
|
30
|
+
const transcripts = new Map();
|
|
31
|
+
const transcriptPaths = new Map();
|
|
32
|
+
let procInfo = new Map();
|
|
33
|
+
let procInfoAt = 0;
|
|
34
|
+
let procInfoPending = null;
|
|
35
|
+
|
|
36
|
+
// Each running Claude Code session registers itself as sessions/<pid>.json.
|
|
37
|
+
// The <pid>.<hash>.key files beside them hold secrets and are never opened.
|
|
38
|
+
// A file caught while it's being rewritten keeps its last reading, so the
|
|
39
|
+
// session doesn't drop off the dashboard for a moment and look finished.
|
|
40
|
+
const lastRead = new Map();
|
|
41
|
+
|
|
42
|
+
function readRegistry() {
|
|
43
|
+
let names;
|
|
44
|
+
try {
|
|
45
|
+
names = fs.readdirSync(SESSIONS_DIR);
|
|
46
|
+
} catch {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
const records = [];
|
|
50
|
+
const seen = new Set();
|
|
51
|
+
for (const name of names) {
|
|
52
|
+
if (!/^\d+\.json$/.test(name)) continue;
|
|
53
|
+
seen.add(name);
|
|
54
|
+
let rec = null;
|
|
55
|
+
try {
|
|
56
|
+
rec = JSON.parse(fs.readFileSync(path.join(SESSIONS_DIR, name), 'utf8'));
|
|
57
|
+
lastRead.set(name, rec);
|
|
58
|
+
} catch {
|
|
59
|
+
rec = lastRead.get(name) || null;
|
|
60
|
+
}
|
|
61
|
+
if (rec && Number.isInteger(rec.pid) && rec.pid > 0) records.push(rec);
|
|
62
|
+
}
|
|
63
|
+
for (const name of lastRead.keys()) if (!seen.has(name)) lastRead.delete(name);
|
|
64
|
+
return records;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Run headless, with `claude -p` (entrypoint sdk-cli) or the Agent SDK, so
|
|
68
|
+
// there's no window to go to or type into. Claude registers these as
|
|
69
|
+
// interactive too.
|
|
70
|
+
const isBackground = (rec) => /^sdk-/.test(rec.entrypoint || '');
|
|
71
|
+
|
|
72
|
+
function isRunning(pid) {
|
|
73
|
+
try {
|
|
74
|
+
process.kill(pid, 0);
|
|
75
|
+
return true;
|
|
76
|
+
} catch (err) {
|
|
77
|
+
return err.code === 'EPERM';
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function run(cmd, args) {
|
|
82
|
+
return new Promise((resolve) => {
|
|
83
|
+
execFile(cmd, args, { windowsHide: true, timeout: 15000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) =>
|
|
84
|
+
resolve(err && !stdout ? null : String(stdout)),
|
|
85
|
+
);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Name, start time and memory for the given PIDs. On Windows the start time is
|
|
90
|
+
// a FILETIME, the same unit Claude Code records as procStart.
|
|
91
|
+
async function queryProcesses(pids) {
|
|
92
|
+
const info = new Map();
|
|
93
|
+
if (!pids.length) return info;
|
|
94
|
+
if (IS_WIN) {
|
|
95
|
+
const script =
|
|
96
|
+
`Get-Process -Id ${pids.join(',')} -ErrorAction SilentlyContinue | ForEach-Object { ` +
|
|
97
|
+
`'{0}|{1}|{2}|{3}' -f $_.Id, $_.ProcessName, $(try { $_.StartTime.ToFileTimeUtc() } catch { '' }), $_.WorkingSet64 }`;
|
|
98
|
+
const out = await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script]);
|
|
99
|
+
if (out === null) return null;
|
|
100
|
+
for (const line of out.split(/\r?\n/)) {
|
|
101
|
+
const [pid, name, start, ws] = line.trim().split('|');
|
|
102
|
+
if (!pid) continue;
|
|
103
|
+
info.set(Number(pid), { name, start: start ? Number(start) : null, memBytes: Number(ws) || null });
|
|
104
|
+
}
|
|
105
|
+
} else {
|
|
106
|
+
const out = await run('ps', ['-o', 'pid=,rss=,comm=', '-p', pids.join(',')]);
|
|
107
|
+
if (out === null) return null;
|
|
108
|
+
for (const line of out.split('\n')) {
|
|
109
|
+
const m = line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);
|
|
110
|
+
if (m) info.set(Number(m[1]), { name: path.basename(m[3]), start: null, memBytes: Number(m[2]) * 1024 });
|
|
111
|
+
}
|
|
112
|
+
// Node 24 on Linux names its main thread MainThread, and ps gives that as
|
|
113
|
+
// the process's name. The program it was started as says what it is.
|
|
114
|
+
const unnamed = [...info].filter(([, p]) => !PROCESS_NAMES.test(p.name)).map(([pid]) => pid);
|
|
115
|
+
if (unnamed.length) {
|
|
116
|
+
const args = (await run('ps', ['-o', 'pid=,args=', '-p', unnamed.join(',')])) || '';
|
|
117
|
+
for (const line of args.split('\n')) {
|
|
118
|
+
const m = line.trim().match(/^(\d+)\s+(\S+)/);
|
|
119
|
+
const name = m ? path.basename(m[2]) : '';
|
|
120
|
+
if (PROCESS_NAMES.test(name)) info.get(Number(m[1])).name = name;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return info;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function refreshProcInfo(pids) {
|
|
128
|
+
const known = pids.every((pid) => procInfo.has(pid));
|
|
129
|
+
if (known && Date.now() - procInfoAt < PROC_REFRESH_MS) return;
|
|
130
|
+
if (!procInfoPending) {
|
|
131
|
+
procInfoPending = queryProcesses(pids).then((info) => {
|
|
132
|
+
if (info) {
|
|
133
|
+
procInfo = info;
|
|
134
|
+
procInfoAt = Date.now();
|
|
135
|
+
}
|
|
136
|
+
procInfoPending = null;
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
// New PIDs must be checked before they are shown; memory refreshes can lag.
|
|
140
|
+
if (!known) await procInfoPending;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// A registry file outlives a crashed session, and Windows reuses PIDs, so a
|
|
144
|
+
// live PID only counts when the process is Claude and started when the file says.
|
|
145
|
+
function isSameProcess(rec) {
|
|
146
|
+
const p = procInfo.get(rec.pid);
|
|
147
|
+
if (!p) return true;
|
|
148
|
+
if (!PROCESS_NAMES.test(p.name)) return false;
|
|
149
|
+
const recorded = Number(rec.procStartFt ?? rec.procStart);
|
|
150
|
+
if (!IS_WIN || !p.start || !Number.isFinite(recorded)) return true;
|
|
151
|
+
return Math.abs(p.start - recorded) < 2e7;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function findTranscript(rec) {
|
|
155
|
+
if (!rec.sessionId || !rec.cwd) return null;
|
|
156
|
+
const cached = transcriptPaths.get(rec.sessionId);
|
|
157
|
+
if (cached && fs.existsSync(cached)) return cached;
|
|
158
|
+
const file = `${rec.sessionId}.jsonl`;
|
|
159
|
+
const direct = path.join(PROJECTS_DIR, rec.cwd.replace(/[^a-zA-Z0-9]/g, '-'), file);
|
|
160
|
+
let found = fs.existsSync(direct) ? direct : null;
|
|
161
|
+
if (!found) {
|
|
162
|
+
// Very long paths are shortened when they become folder names, so search.
|
|
163
|
+
try {
|
|
164
|
+
for (const dir of fs.readdirSync(PROJECTS_DIR)) {
|
|
165
|
+
const candidate = path.join(PROJECTS_DIR, dir, file);
|
|
166
|
+
if (fs.existsSync(candidate)) {
|
|
167
|
+
found = candidate;
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
} catch {}
|
|
172
|
+
}
|
|
173
|
+
if (found) transcriptPaths.set(rec.sessionId, found);
|
|
174
|
+
return found;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function readTranscript(file, used) {
|
|
178
|
+
let t = transcripts.get(file);
|
|
179
|
+
if (!t) {
|
|
180
|
+
t = new Transcript(file);
|
|
181
|
+
transcripts.set(file, t);
|
|
182
|
+
}
|
|
183
|
+
used.add(file);
|
|
184
|
+
return t.update() ? t.summary() : null;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function readSubagents(transcriptFile, rec, used) {
|
|
188
|
+
const dir = path.join(path.dirname(transcriptFile), rec.sessionId, 'subagents');
|
|
189
|
+
let names;
|
|
190
|
+
try {
|
|
191
|
+
names = fs.readdirSync(dir);
|
|
192
|
+
} catch {
|
|
193
|
+
return NO_SUBAGENTS;
|
|
194
|
+
}
|
|
195
|
+
const running = [];
|
|
196
|
+
const finished = [];
|
|
197
|
+
for (const name of names) {
|
|
198
|
+
if (!name.endsWith('.meta.json')) continue;
|
|
199
|
+
const id = name.slice(0, -'.meta.json'.length);
|
|
200
|
+
const jsonl = path.join(dir, `${id}.jsonl`);
|
|
201
|
+
let meta;
|
|
202
|
+
let mtime;
|
|
203
|
+
try {
|
|
204
|
+
meta = JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8'));
|
|
205
|
+
mtime = fs.statSync(jsonl).mtimeMs;
|
|
206
|
+
} catch {
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
const agent = {
|
|
210
|
+
id: id.replace(/^agent-/, ''),
|
|
211
|
+
type: meta.agentType || 'agent',
|
|
212
|
+
description: meta.description || '',
|
|
213
|
+
background: meta.requestShape === 'background',
|
|
214
|
+
updatedAt: mtime,
|
|
215
|
+
};
|
|
216
|
+
// A subagent left unfinished by an earlier run of a resumed session is not running.
|
|
217
|
+
if (!meta.finished && mtime >= (rec.startedAt || 0)) {
|
|
218
|
+
const s = readTranscript(jsonl, used);
|
|
219
|
+
running.push({
|
|
220
|
+
...agent,
|
|
221
|
+
status: 'running',
|
|
222
|
+
startedAt: s?.firstPrompt?.at || null,
|
|
223
|
+
tools: s?.tools || [],
|
|
224
|
+
lastReply: s?.lastReply || null,
|
|
225
|
+
outputTokens: s?.outputTokens || 0,
|
|
226
|
+
});
|
|
227
|
+
} else {
|
|
228
|
+
finished.push({ ...agent, status: meta.finished ? 'done' : 'stopped' });
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
finished.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
232
|
+
return {
|
|
233
|
+
running: running.sort((a, b) => b.updatedAt - a.updatedAt),
|
|
234
|
+
finished: finished.slice(0, FINISHED_SUBAGENTS),
|
|
235
|
+
finishedTotal: finished.length,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async function snapshot() {
|
|
240
|
+
const records = readRegistry().filter((rec) => isRunning(rec.pid));
|
|
241
|
+
await refreshProcInfo(records.map((rec) => rec.pid));
|
|
242
|
+
const used = new Set();
|
|
243
|
+
const agents = [];
|
|
244
|
+
for (const rec of records) {
|
|
245
|
+
if (!isSameProcess(rec)) continue;
|
|
246
|
+
const file = findTranscript(rec);
|
|
247
|
+
const t = file ? readTranscript(file, used) : null;
|
|
248
|
+
agents.push({
|
|
249
|
+
app: 'claude',
|
|
250
|
+
id: rec.sessionId,
|
|
251
|
+
pid: rec.pid,
|
|
252
|
+
name: rec.name || path.basename(rec.cwd || '') || `pid ${rec.pid}`,
|
|
253
|
+
cwd: rec.cwd,
|
|
254
|
+
kind: rec.kind,
|
|
255
|
+
entrypoint: rec.entrypoint,
|
|
256
|
+
background: isBackground(rec),
|
|
257
|
+
version: rec.version,
|
|
258
|
+
status: rec.status || 'unknown',
|
|
259
|
+
waitingFor: rec.waitingFor || null,
|
|
260
|
+
detail: typeof rec.detail === 'string' ? rec.detail : null,
|
|
261
|
+
statusSince: rec.statusUpdatedAt || rec.updatedAt || rec.startedAt,
|
|
262
|
+
startedAt: rec.startedAt,
|
|
263
|
+
memBytes: procInfo.get(rec.pid)?.memBytes ?? null,
|
|
264
|
+
terminalTitle: terminals.titleFor(rec.pid),
|
|
265
|
+
...(t || {}),
|
|
266
|
+
subagents: file ? readSubagents(file, rec, used) : NO_SUBAGENTS,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
for (const file of transcripts.keys()) if (!used.has(file)) transcripts.delete(file);
|
|
270
|
+
// Codex's windows have their titles read too: that's how each is matched
|
|
271
|
+
// to its session.
|
|
272
|
+
const fromCodex = codex.snapshot();
|
|
273
|
+
agents.push(...fromCodex.agents);
|
|
274
|
+
// GitHub Copilot's sessions, from the CLI and VS Code.
|
|
275
|
+
const fromCopilot = copilot.snapshot();
|
|
276
|
+
agents.push(...fromCopilot.agents);
|
|
277
|
+
// OpenCode's sessions, from its background service. Its windows' titles
|
|
278
|
+
// are read too: that's how each is matched to its session.
|
|
279
|
+
const fromOpenCode = opencode.snapshot();
|
|
280
|
+
agents.push(...fromOpenCode.agents);
|
|
281
|
+
// Cursor CLI's chats, matched to their windows by their tabs' titles too.
|
|
282
|
+
const fromCursor = cursor.snapshot();
|
|
283
|
+
agents.push(...fromCursor.agents);
|
|
284
|
+
// ComfyUI's jobs, and Comfy Desktop's windows, whose titles give the
|
|
285
|
+
// running job's progress.
|
|
286
|
+
const fromComfy = comfy.snapshot();
|
|
287
|
+
agents.push(...fromComfy.items);
|
|
288
|
+
// LocalAI's loaded models, the ones working, downloads, agent chats and
|
|
289
|
+
// agent jobs.
|
|
290
|
+
agents.push(...localai.snapshot());
|
|
291
|
+
// Ollama's, LM Studio's and llama.cpp's loaded models.
|
|
292
|
+
agents.push(...ollama.snapshot(), ...lmstudio.snapshot(), ...llamacpp.snapshot());
|
|
293
|
+
terminals.refreshTitles([
|
|
294
|
+
...agents.filter((a) => a.app === 'claude' && !a.background && (!a.kind || a.kind === 'interactive')).map((a) => a.pid),
|
|
295
|
+
...fromCodex.windowPids,
|
|
296
|
+
...fromOpenCode.windowPids,
|
|
297
|
+
...fromCursor.windowPids,
|
|
298
|
+
...fromCopilot.agents.filter((a) => a.entrypoint === 'cli').map((a) => a.pid),
|
|
299
|
+
...fromComfy.windowPids,
|
|
300
|
+
]);
|
|
301
|
+
// How each ComfyUI job that just finished ended, and its output, for the
|
|
302
|
+
// notification its leaving brings.
|
|
303
|
+
return {
|
|
304
|
+
now: Date.now(),
|
|
305
|
+
host: os.hostname(),
|
|
306
|
+
// The version running, under the computer's name in the header.
|
|
307
|
+
version,
|
|
308
|
+
home: os.homedir(),
|
|
309
|
+
platform: process.platform,
|
|
310
|
+
agents,
|
|
311
|
+
finished: fromComfy.finished,
|
|
312
|
+
// RAM and graphics memory, for the card at the top.
|
|
313
|
+
memory: memory.snapshot(),
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async function findAgent(sessionId) {
|
|
318
|
+
const snap = await snapshot();
|
|
319
|
+
return snap.agents.find((a) => a.id === sessionId) || null;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const sessionFile = (pid) => path.join(SESSIONS_DIR, `${pid}.json`);
|
|
323
|
+
|
|
324
|
+
module.exports = { snapshot, findAgent, sessionFile, PROJECTS_DIR };
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Codex runs its sessions ("threads") in one background service per
|
|
4
|
+
// CODEX_HOME, and the `codex` in a terminal is a window onto it. The service
|
|
5
|
+
// answers on a local socket, speaking JSON-RPC over a WebSocket, and
|
|
6
|
+
// `codex app-server proxy` relays that socket over its stdin and stdout, the
|
|
7
|
+
// same way on every system. This keeps one proxy running while the service
|
|
8
|
+
// does, and keeps a list of the sessions it has loaded and their status, which
|
|
9
|
+
// it pushes to every connection as it changes. It only reads: it starts,
|
|
10
|
+
// resumes and answers nothing, and Codex sends approval requests to the
|
|
11
|
+
// windows showing a session, not to a connection like this one.
|
|
12
|
+
|
|
13
|
+
const fs = require('fs');
|
|
14
|
+
const os = require('os');
|
|
15
|
+
const path = require('path');
|
|
16
|
+
const crypto = require('crypto');
|
|
17
|
+
const { spawn } = require('child_process');
|
|
18
|
+
|
|
19
|
+
const CODEX_HOME = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
|
|
20
|
+
const IS_WIN = process.platform === 'win32';
|
|
21
|
+
const RETRY_MS = [2000, 5000, 15000, 30000, 60000];
|
|
22
|
+
const RESYNC_MS = 30000;
|
|
23
|
+
const REQUEST_MS = 10000;
|
|
24
|
+
|
|
25
|
+
// ---- WebSocket frames ----------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
// A text frame from the client, which must be masked.
|
|
28
|
+
function encodeFrame(text, opcode = 1) {
|
|
29
|
+
const payload = Buffer.from(text);
|
|
30
|
+
const mask = crypto.randomBytes(4);
|
|
31
|
+
let head;
|
|
32
|
+
if (payload.length < 126) {
|
|
33
|
+
head = Buffer.from([0x80 | opcode, 0x80 | payload.length]);
|
|
34
|
+
} else if (payload.length < 65536) {
|
|
35
|
+
head = Buffer.alloc(4);
|
|
36
|
+
head.writeUInt16BE(payload.length, 2);
|
|
37
|
+
head[1] = 0x80 | 126;
|
|
38
|
+
} else {
|
|
39
|
+
head = Buffer.alloc(10);
|
|
40
|
+
head.writeBigUInt64BE(BigInt(payload.length), 2);
|
|
41
|
+
head[1] = 0x80 | 127;
|
|
42
|
+
}
|
|
43
|
+
head[0] = 0x80 | opcode;
|
|
44
|
+
const body = Buffer.allocUnsafe(payload.length);
|
|
45
|
+
for (let i = 0; i < payload.length; i++) body[i] = payload[i] ^ mask[i & 3];
|
|
46
|
+
return Buffer.concat([head, mask, body]);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Whole frames from the front of `buf`: { frames: [{ opcode, fin, data }], rest }.
|
|
50
|
+
function decodeFrames(buf) {
|
|
51
|
+
const frames = [];
|
|
52
|
+
for (;;) {
|
|
53
|
+
if (buf.length < 2) break;
|
|
54
|
+
let len = buf[1] & 0x7f;
|
|
55
|
+
let off = 2;
|
|
56
|
+
if (len === 126) {
|
|
57
|
+
if (buf.length < 4) break;
|
|
58
|
+
len = buf.readUInt16BE(2);
|
|
59
|
+
off = 4;
|
|
60
|
+
} else if (len === 127) {
|
|
61
|
+
if (buf.length < 10) break;
|
|
62
|
+
len = Number(buf.readBigUInt64BE(2));
|
|
63
|
+
off = 10;
|
|
64
|
+
}
|
|
65
|
+
const masked = Boolean(buf[1] & 0x80);
|
|
66
|
+
const mask = masked ? buf.subarray(off, off + 4) : null;
|
|
67
|
+
if (masked) off += 4;
|
|
68
|
+
if (buf.length < off + len) break;
|
|
69
|
+
let data = buf.subarray(off, off + len);
|
|
70
|
+
if (mask) data = Buffer.from(data.map((b, i) => b ^ mask[i & 3]));
|
|
71
|
+
frames.push({ opcode: buf[0] & 0x0f, fin: Boolean(buf[0] & 0x80), data });
|
|
72
|
+
buf = buf.subarray(off + len);
|
|
73
|
+
}
|
|
74
|
+
return { frames, rest: buf };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ---- the service ---------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
function isRunning(pid) {
|
|
80
|
+
try {
|
|
81
|
+
process.kill(pid, 0);
|
|
82
|
+
return true;
|
|
83
|
+
} catch (err) {
|
|
84
|
+
return err.code === 'EPERM';
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Whether Codex's background service is running for this CODEX_HOME. The
|
|
89
|
+
// proxy only connects to a running one, so Tabherd never starts it.
|
|
90
|
+
function serviceRunning(home = CODEX_HOME) {
|
|
91
|
+
for (const name of ['daemon.pid', 'app-server.pid']) {
|
|
92
|
+
try {
|
|
93
|
+
const { pid } = JSON.parse(fs.readFileSync(path.join(home, 'app-server-daemon', name), 'utf8'));
|
|
94
|
+
if (Number.isInteger(pid) && pid > 0 && isRunning(pid)) return true;
|
|
95
|
+
} catch {}
|
|
96
|
+
}
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// The service's own copy of Codex, so the proxy is the same version, else
|
|
101
|
+
// `codex` from the PATH.
|
|
102
|
+
function codexCommand(home = CODEX_HOME) {
|
|
103
|
+
const own = path.join(home, 'packages', 'app-server-daemon', 'current', 'bin', IS_WIN ? 'codex.exe' : 'codex');
|
|
104
|
+
return fs.existsSync(own) ? own : 'codex';
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// The status Codex reports, as the dashboard's: waiting on an approval or an
|
|
108
|
+
// answer, working, or idle at the prompt.
|
|
109
|
+
function mapStatus(status) {
|
|
110
|
+
const flags = status?.activeFlags || [];
|
|
111
|
+
switch (status?.type) {
|
|
112
|
+
case 'active':
|
|
113
|
+
if (flags.includes('waitingOnApproval')) return { status: 'waiting', waitingFor: 'Approval' };
|
|
114
|
+
if (flags.includes('waitingOnUserInput')) return { status: 'waiting', waitingFor: 'Your answer' };
|
|
115
|
+
return { status: 'busy', waitingFor: null };
|
|
116
|
+
case 'idle':
|
|
117
|
+
return { status: 'idle', waitingFor: null };
|
|
118
|
+
case 'systemError':
|
|
119
|
+
return { status: 'idle', waitingFor: null, detail: 'Codex reported an error' };
|
|
120
|
+
default:
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
class CodexClient {
|
|
126
|
+
constructor({ home = CODEX_HOME, spawnProxy } = {}) {
|
|
127
|
+
this.home = home;
|
|
128
|
+
this.spawnProxy = spawnProxy || (() => spawn(codexCommand(home), ['app-server', 'proxy'], { stdio: 'pipe', windowsHide: true }));
|
|
129
|
+
this.threads = new Map();
|
|
130
|
+
this.proc = null;
|
|
131
|
+
this.ready = false;
|
|
132
|
+
this.failures = 0;
|
|
133
|
+
this.retryAt = 0;
|
|
134
|
+
this.nextId = 1;
|
|
135
|
+
this.pending = new Map();
|
|
136
|
+
this.message = [];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Called with each snapshot: connects when the service is running, and
|
|
140
|
+
// returns the sessions it has loaded.
|
|
141
|
+
poll() {
|
|
142
|
+
if (!this.proc && Date.now() >= this.retryAt && serviceRunning(this.home)) this.connect();
|
|
143
|
+
return [...this.threads.values()];
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
connect() {
|
|
147
|
+
let proc;
|
|
148
|
+
try {
|
|
149
|
+
proc = this.spawnProxy();
|
|
150
|
+
} catch {
|
|
151
|
+
return this.lost();
|
|
152
|
+
}
|
|
153
|
+
this.proc = proc;
|
|
154
|
+
// Nor does the proxy keep Node running by itself.
|
|
155
|
+
proc.unref?.();
|
|
156
|
+
for (const s of [proc.stdin, proc.stdout, proc.stderr]) s?.unref?.();
|
|
157
|
+
let buf = Buffer.alloc(0);
|
|
158
|
+
let upgraded = false;
|
|
159
|
+
proc.on('error', () => this.lost(proc));
|
|
160
|
+
proc.on('exit', () => this.lost(proc));
|
|
161
|
+
proc.stdin.on('error', () => {});
|
|
162
|
+
proc.stderr?.resume();
|
|
163
|
+
proc.stdout.on('data', (chunk) => {
|
|
164
|
+
buf = Buffer.concat([buf, chunk]);
|
|
165
|
+
if (!upgraded) {
|
|
166
|
+
const end = buf.indexOf('\r\n\r\n');
|
|
167
|
+
if (end < 0) return;
|
|
168
|
+
if (!/^HTTP\/1\.1 101/.test(buf.subarray(0, end).toString())) return proc.kill();
|
|
169
|
+
upgraded = true;
|
|
170
|
+
buf = buf.subarray(end + 4);
|
|
171
|
+
this.start().catch(() => proc.kill());
|
|
172
|
+
}
|
|
173
|
+
const { frames, rest } = decodeFrames(buf);
|
|
174
|
+
buf = rest;
|
|
175
|
+
for (const f of frames) this.frame(f);
|
|
176
|
+
});
|
|
177
|
+
const key = crypto.randomBytes(16).toString('base64');
|
|
178
|
+
proc.stdin.write(
|
|
179
|
+
`GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${key}\r\nSec-WebSocket-Version: 13\r\n\r\n`,
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// The proxy ended, or never started: forget the sessions and try again later.
|
|
184
|
+
lost(proc) {
|
|
185
|
+
if (proc && proc !== this.proc) return;
|
|
186
|
+
clearInterval(this.resync);
|
|
187
|
+
for (const { reject } of this.pending.values()) reject(new Error('Codex connection closed'));
|
|
188
|
+
this.pending.clear();
|
|
189
|
+
this.threads.clear();
|
|
190
|
+
this.proc = null;
|
|
191
|
+
this.ready = false;
|
|
192
|
+
this.retryAt = Date.now() + RETRY_MS[Math.min(this.failures++, RETRY_MS.length - 1)];
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
close() {
|
|
196
|
+
const proc = this.proc;
|
|
197
|
+
this.lost(proc);
|
|
198
|
+
proc?.kill();
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
send(msg) {
|
|
202
|
+
this.proc?.stdin.write(encodeFrame(JSON.stringify(msg)));
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
request(method, params) {
|
|
206
|
+
return new Promise((resolve, reject) => {
|
|
207
|
+
const id = this.nextId++;
|
|
208
|
+
const timer = setTimeout(() => {
|
|
209
|
+
this.pending.delete(id);
|
|
210
|
+
reject(new Error(`${method} timed out`));
|
|
211
|
+
}, REQUEST_MS);
|
|
212
|
+
this.pending.set(id, {
|
|
213
|
+
resolve: (v) => (clearTimeout(timer), resolve(v)),
|
|
214
|
+
reject: (e) => (clearTimeout(timer), reject(e)),
|
|
215
|
+
});
|
|
216
|
+
this.send({ id, method, params });
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
frame({ opcode, fin, data }) {
|
|
221
|
+
if (opcode === 9) return this.proc?.stdin.write(encodeFrame(data, 0xa));
|
|
222
|
+
if (opcode === 8) return this.proc?.kill();
|
|
223
|
+
if (opcode !== 1 && opcode !== 0) return;
|
|
224
|
+
this.message.push(data);
|
|
225
|
+
if (!fin) return;
|
|
226
|
+
const text = Buffer.concat(this.message).toString('utf8');
|
|
227
|
+
this.message = [];
|
|
228
|
+
let m;
|
|
229
|
+
try {
|
|
230
|
+
m = JSON.parse(text);
|
|
231
|
+
} catch {
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
// Requests from the service, such as approvals, are for the windows
|
|
235
|
+
// showing the session. Answering one here could approve something.
|
|
236
|
+
if (m.method && m.id !== undefined) return;
|
|
237
|
+
if (m.method) return this.notify(m.method, m.params || {});
|
|
238
|
+
const waiter = this.pending.get(m.id);
|
|
239
|
+
if (!waiter) return;
|
|
240
|
+
this.pending.delete(m.id);
|
|
241
|
+
if (m.error) waiter.reject(new Error(m.error.message || 'Codex error'));
|
|
242
|
+
else waiter.resolve(m.result);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async start() {
|
|
246
|
+
await this.request('initialize', { clientInfo: { name: 'tabherd', title: 'Tabherd', version: require('../package.json').version } });
|
|
247
|
+
this.send({ method: 'initialized' });
|
|
248
|
+
this.failures = 0;
|
|
249
|
+
await this.sync();
|
|
250
|
+
// The open sessions are known from here on.
|
|
251
|
+
this.ready = true;
|
|
252
|
+
this.resync = setInterval(() => this.sync().catch(() => {}), RESYNC_MS);
|
|
253
|
+
this.resync.unref?.();
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Every loaded session, read again: catches anything a notification missed.
|
|
257
|
+
async sync() {
|
|
258
|
+
const ids = [];
|
|
259
|
+
let cursor = null;
|
|
260
|
+
do {
|
|
261
|
+
const page = await this.request('thread/loaded/list', cursor ? { cursor } : {});
|
|
262
|
+
ids.push(...(page?.data || []));
|
|
263
|
+
cursor = page?.nextCursor || null;
|
|
264
|
+
} while (cursor);
|
|
265
|
+
for (const id of this.threads.keys()) if (!ids.includes(id)) this.threads.delete(id);
|
|
266
|
+
for (const id of ids) await this.read(id);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async read(id) {
|
|
270
|
+
try {
|
|
271
|
+
const r = await this.request('thread/read', { threadId: id });
|
|
272
|
+
if (r?.thread) this.update(r.thread);
|
|
273
|
+
} catch {}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
update(t, statusChanged) {
|
|
277
|
+
const old = this.threads.get(t.id);
|
|
278
|
+
const at = statusChanged || (old && JSON.stringify(old.status) !== JSON.stringify(t.status)) ? Date.now() : null;
|
|
279
|
+
this.threads.set(t.id, {
|
|
280
|
+
...old,
|
|
281
|
+
...t,
|
|
282
|
+
statusSince: at || old?.statusSince || (t.updatedAt ? t.updatedAt * 1000 : Date.now()),
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
notify(method, p) {
|
|
287
|
+
const t = this.threads.get(p.threadId);
|
|
288
|
+
switch (method) {
|
|
289
|
+
case 'thread/started':
|
|
290
|
+
if (p.thread?.id) this.update(p.thread);
|
|
291
|
+
break;
|
|
292
|
+
case 'thread/status/changed':
|
|
293
|
+
if (t) this.update({ ...t, status: p.status }, true);
|
|
294
|
+
else if (p.threadId) this.read(p.threadId);
|
|
295
|
+
break;
|
|
296
|
+
case 'thread/name/updated':
|
|
297
|
+
if (t) this.threads.set(t.id, { ...t, name: p.threadName ?? null });
|
|
298
|
+
break;
|
|
299
|
+
case 'thread/closed':
|
|
300
|
+
this.threads.delete(p.threadId);
|
|
301
|
+
break;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
module.exports = { CodexClient, encodeFrame, decodeFrames, mapStatus, serviceRunning, codexCommand, CODEX_HOME };
|