tabherd 0.0.1 → 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 +538 -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 +35 -7
- 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/placeholder.js +0 -3
package/lib/opencode.js
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
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 terminals = require('./terminals');
|
|
8
|
+
const refs = require('./ticket-refs');
|
|
9
|
+
|
|
10
|
+
// OpenCode's sessions as cards. OpenCode 2 runs one background service that
|
|
11
|
+
// all its windows use. Its address and password are in
|
|
12
|
+
// <state>/opencode/service.json, where <state> is XDG_STATE_HOME or
|
|
13
|
+
// ~/.local/state, as OpenCode has it on every system. A session has a card
|
|
14
|
+
// while a window shows it, found by the tab's title ("OC | <session title>"),
|
|
15
|
+
// and while it's working or waiting on you without one.
|
|
16
|
+
|
|
17
|
+
const IS_WIN = process.platform === 'win32';
|
|
18
|
+
const REFRESH_MS = 2000;
|
|
19
|
+
const REQUEST_MS = 3000;
|
|
20
|
+
const WINDOWS_REFRESH_MS = 3000;
|
|
21
|
+
const SESSIONS_LISTED = 50;
|
|
22
|
+
const MESSAGES_READ = 30;
|
|
23
|
+
const NO_SUBAGENTS = { running: [], finished: [], finishedTotal: 0 };
|
|
24
|
+
// OpenCode's commands that aren't a window with a session in it.
|
|
25
|
+
const NOT_A_SESSION = new Set([
|
|
26
|
+
'upgrade',
|
|
27
|
+
'update',
|
|
28
|
+
'uninstall',
|
|
29
|
+
'acp',
|
|
30
|
+
'api',
|
|
31
|
+
'debug',
|
|
32
|
+
'auth',
|
|
33
|
+
'mcp',
|
|
34
|
+
'plugin',
|
|
35
|
+
'models',
|
|
36
|
+
'stats',
|
|
37
|
+
'run',
|
|
38
|
+
'session',
|
|
39
|
+
'service',
|
|
40
|
+
'reload',
|
|
41
|
+
'machine',
|
|
42
|
+
'pair',
|
|
43
|
+
'serve',
|
|
44
|
+
]);
|
|
45
|
+
// A session's ID, as OpenCode makes them: safe in a command line as it is.
|
|
46
|
+
const SESSION_ID = /^ses_[A-Za-z0-9]{10,60}$/;
|
|
47
|
+
|
|
48
|
+
const stateFile = () => path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'), 'opencode', 'service.json');
|
|
49
|
+
|
|
50
|
+
// The background service, if it's said where it is. Only one on this
|
|
51
|
+
// computer is used, as the password goes with every request.
|
|
52
|
+
function readService() {
|
|
53
|
+
try {
|
|
54
|
+
const s = JSON.parse(fs.readFileSync(stateFile(), 'utf8'));
|
|
55
|
+
if (typeof s.url !== 'string' || typeof s.password !== 'string' || !s.password) return null;
|
|
56
|
+
const u = new URL(s.url);
|
|
57
|
+
if (u.protocol !== 'http:' || !['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname)) return null;
|
|
58
|
+
return { url: s.url.replace(/\/+$/, ''), auth: `Basic ${Buffer.from(`opencode:${s.password}`).toString('base64')}` };
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function request(service, route, { method = 'GET', body } = {}) {
|
|
65
|
+
const res = await fetch(service.url + route, {
|
|
66
|
+
method,
|
|
67
|
+
headers: { Authorization: service.auth, Accept: 'application/json', ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
|
68
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
69
|
+
signal: AbortSignal.timeout(REQUEST_MS),
|
|
70
|
+
redirect: 'error',
|
|
71
|
+
});
|
|
72
|
+
if (!res.ok) {
|
|
73
|
+
const err = new Error(`OpenCode answered ${res.status}`);
|
|
74
|
+
err.status = res.status;
|
|
75
|
+
throw err;
|
|
76
|
+
}
|
|
77
|
+
return res.json().catch(() => ({}));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const list = (answer) => (Array.isArray(answer?.data) ? answer.data : Array.isArray(answer) ? answer : []);
|
|
81
|
+
|
|
82
|
+
// ---- windows ------------------------------------------------------------------
|
|
83
|
+
|
|
84
|
+
function run(cmd, args) {
|
|
85
|
+
return new Promise((resolve) => {
|
|
86
|
+
execFile(cmd, args, { windowsHide: true, timeout: 15000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => resolve(err && !stdout ? null : String(stdout)));
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Whether a process is OpenCode in a terminal: `opencode`, or its minimal
|
|
91
|
+
// interface, running no other command. A folder to start in is fine.
|
|
92
|
+
function isSessionWindow(name, args) {
|
|
93
|
+
if (!/^opencode(\.exe)?$/i.test(name)) return false;
|
|
94
|
+
const first = args.find((a) => !a.startsWith('-'));
|
|
95
|
+
return !first || !NOT_A_SESSION.has(first);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// The session a window was started on, from its command line.
|
|
99
|
+
function sessionArg(args) {
|
|
100
|
+
const at = args.findIndex((a) => a === '--session' || a === '-s');
|
|
101
|
+
const id = at >= 0 ? args[at + 1] : args.find((a) => a.startsWith('--session='))?.slice(10);
|
|
102
|
+
return id && SESSION_ID.test(id) ? id : null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// The `opencode` processes running in terminals: [{ pid, memBytes, session }].
|
|
106
|
+
async function findWindows() {
|
|
107
|
+
const found = [];
|
|
108
|
+
const add = (pid, name, memBytes, args) => {
|
|
109
|
+
if (isSessionWindow(name, args)) found.push({ pid, memBytes, session: sessionArg(args) });
|
|
110
|
+
};
|
|
111
|
+
if (IS_WIN) {
|
|
112
|
+
const script =
|
|
113
|
+
`Get-CimInstance Win32_Process -Filter "Name like 'opencode%'" | ForEach-Object { ` +
|
|
114
|
+
`'{0}|{1}|{2}|{3}' -f $_.ProcessId, $_.Name, $_.WorkingSetSize, $_.CommandLine }`;
|
|
115
|
+
const out = await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script]);
|
|
116
|
+
if (out === null) return null;
|
|
117
|
+
for (const line of out.split(/\r?\n/)) {
|
|
118
|
+
const [pid, name, ws, ...cmd] = line.trim().split('|');
|
|
119
|
+
if (!pid) continue;
|
|
120
|
+
add(Number(pid), name, Number(ws) || null, cmd.join('|').replace(/^\s*("[^"]*"|\S+)\s*/, '').split(/\s+/).filter(Boolean));
|
|
121
|
+
}
|
|
122
|
+
} else {
|
|
123
|
+
const out = await run('ps', ['-A', '-o', 'pid=,rss=,args=']);
|
|
124
|
+
if (out === null) return null;
|
|
125
|
+
for (const line of out.split('\n')) {
|
|
126
|
+
const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)\s*(.*)$/);
|
|
127
|
+
if (m) add(Number(m[1]), path.basename(m[3]), Number(m[2]) * 1024, m[4].split(/\s+/).filter(Boolean));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return found;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
let windows = [];
|
|
134
|
+
let windowsAt = 0;
|
|
135
|
+
let windowsPending = null;
|
|
136
|
+
|
|
137
|
+
function refreshWindows() {
|
|
138
|
+
if (windowsPending || Date.now() - windowsAt < WINDOWS_REFRESH_MS) return;
|
|
139
|
+
windowsPending = findWindows().then((found) => {
|
|
140
|
+
if (found) {
|
|
141
|
+
windows = found;
|
|
142
|
+
windowsAt = Date.now();
|
|
143
|
+
}
|
|
144
|
+
windowsPending = null;
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// The session title in a tab's: "OC | Fix the login" → "Fix the login".
|
|
149
|
+
const titleIn = (tab) =>
|
|
150
|
+
String(tab || '')
|
|
151
|
+
.replace(/^[^\p{L}\p{N}]*OC\s*\|\s*/u, '')
|
|
152
|
+
.trim();
|
|
153
|
+
|
|
154
|
+
// Each session's window: the one started on it, else the one whose tab
|
|
155
|
+
// shows its title, if only one does and no other session has that title.
|
|
156
|
+
function matchWindows(sessions, wins, titleFor = terminals.titleFor) {
|
|
157
|
+
const bySession = new Map();
|
|
158
|
+
const free = new Map(wins.map((w) => [w.pid, w]));
|
|
159
|
+
for (const w of wins) {
|
|
160
|
+
if (w.session && sessions.some((s) => s.id === w.session)) {
|
|
161
|
+
bySession.set(w.session, w);
|
|
162
|
+
free.delete(w.pid);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const named = new Map();
|
|
166
|
+
for (const s of sessions) if (s.title && !bySession.has(s.id)) named.set(s.title, (named.get(s.title) || 0) + 1);
|
|
167
|
+
for (const s of sessions) {
|
|
168
|
+
if (bySession.has(s.id) || !s.title || named.get(s.title) > 1) continue;
|
|
169
|
+
const matches = [...free.values()].filter((w) => {
|
|
170
|
+
const shown = titleIn(titleFor(w.pid));
|
|
171
|
+
return shown === s.title || (shown.endsWith('…') && s.title.startsWith(shown.slice(0, -1)));
|
|
172
|
+
});
|
|
173
|
+
if (matches.length !== 1) continue;
|
|
174
|
+
bySession.set(s.id, matches[0]);
|
|
175
|
+
free.delete(matches[0].pid);
|
|
176
|
+
}
|
|
177
|
+
return bySession;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ---- what each session is doing ----------------------------------------------------
|
|
181
|
+
|
|
182
|
+
// The latest prompt and reply, from messages newest first.
|
|
183
|
+
function lastTurn(messages) {
|
|
184
|
+
const user = messages.find((m) => m?.type === 'user' && typeof m.text === 'string' && m.text.trim());
|
|
185
|
+
const reply = messages.find((m) => m?.type === 'assistant' && (m.content || []).some((c) => c?.type === 'text' && c.text?.trim()));
|
|
186
|
+
const text = reply
|
|
187
|
+
? reply.content
|
|
188
|
+
.filter((c) => c?.type === 'text')
|
|
189
|
+
.map((c) => c.text)
|
|
190
|
+
.join('\n')
|
|
191
|
+
.trim()
|
|
192
|
+
: '';
|
|
193
|
+
// The tickets they claim, give up or (in prompts) link, oldest first.
|
|
194
|
+
const ticketRefs = [];
|
|
195
|
+
for (const m of [...messages].reverse()) {
|
|
196
|
+
if (m?.type === 'user' && typeof m.text === 'string') ticketRefs.push(...refs.find(m.text, 'prompt'));
|
|
197
|
+
else if (m?.type === 'assistant') for (const c of m.content || []) if (c?.type === 'text' && typeof c.text === 'string') ticketRefs.push(...refs.find(c.text, 'reply'));
|
|
198
|
+
}
|
|
199
|
+
return {
|
|
200
|
+
lastPrompt: user ? { text: user.text.trim().slice(0, 4000), at: user.time?.created || null } : null,
|
|
201
|
+
lastReply: reply ? { text: text.slice(0, 8000), at: reply.time?.completed || reply.time?.created || null } : null,
|
|
202
|
+
prompts: messages.filter((m) => m?.type === 'user').length,
|
|
203
|
+
ticketRefs,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Needs you while it asks permission or a question, working while a turn
|
|
208
|
+
// runs, idle otherwise. A turn that failed needs you too.
|
|
209
|
+
function statusOf(s, { running, asks = [], forms = [] }) {
|
|
210
|
+
const ask = asks[0];
|
|
211
|
+
if (ask) {
|
|
212
|
+
const what = ask.resources?.length ? `${ask.action}: ${ask.resources.join(', ')}` : ask.action;
|
|
213
|
+
return { status: 'waiting', waitingFor: String(ask.message || `Permission to ${what || 'go on'}`).slice(0, 300), since: `ask:${ask.id}` };
|
|
214
|
+
}
|
|
215
|
+
const form = forms[0];
|
|
216
|
+
if (form) return { status: 'waiting', waitingFor: String(form.title || 'It has a question for you').slice(0, 300), since: `form:${form.id}` };
|
|
217
|
+
if (running) return { status: 'busy', waitingFor: null, detail: running.type && running.type !== 'running' ? running.type : null, at: s.time?.busy };
|
|
218
|
+
if (s.outcome === 'failed' || s.outcome === 'error') return { status: 'waiting', waitingFor: 'Its last turn failed', at: s.time?.idle };
|
|
219
|
+
return { status: 'idle', waitingFor: null, at: s.time?.idle || s.time?.updated };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
let state = null;
|
|
223
|
+
let refreshing = null;
|
|
224
|
+
let refreshedAt = 0;
|
|
225
|
+
// Each session's latest prompt and reply, by ID, with the update they're from.
|
|
226
|
+
const turns = new Map();
|
|
227
|
+
// When each question or permission request was first seen.
|
|
228
|
+
const firstSeen = new Map();
|
|
229
|
+
|
|
230
|
+
async function refresh() {
|
|
231
|
+
const service = readService();
|
|
232
|
+
if (!service) {
|
|
233
|
+
state = null;
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const [active, listed] = await Promise.all([request(service, '/api/session/active'), request(service, `/api/session?limit=${SESSIONS_LISTED}`)]);
|
|
237
|
+
const running = active?.data && typeof active.data === 'object' ? active.data : {};
|
|
238
|
+
const sessions = list(listed).filter((s) => s?.id && SESSION_ID.test(s.id) && !s.parentID);
|
|
239
|
+
// A running session older than the list, or one a window was started on,
|
|
240
|
+
// is fetched by itself.
|
|
241
|
+
for (const id of new Set([...Object.keys(running), ...windows.map((w) => w.session).filter(Boolean)])) {
|
|
242
|
+
if (SESSION_ID.test(id) && !sessions.some((s) => s.id === id)) {
|
|
243
|
+
const one = await request(service, `/api/session/${id}`).catch(() => null);
|
|
244
|
+
if (one?.data?.id) sessions.push(one.data);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const byWindow = matchWindows(sessions, windows);
|
|
248
|
+
const shown = sessions.filter((s) => byWindow.has(s.id) || running[s.id]);
|
|
249
|
+
const asks = new Map();
|
|
250
|
+
const forms = new Map();
|
|
251
|
+
await Promise.all(
|
|
252
|
+
shown.map(async (s) => {
|
|
253
|
+
const [a, f] = await Promise.all([
|
|
254
|
+
request(service, `/api/session/${s.id}/permission`).catch(() => null),
|
|
255
|
+
request(service, `/api/session/${s.id}/form`).catch(() => null),
|
|
256
|
+
]);
|
|
257
|
+
asks.set(s.id, list(a));
|
|
258
|
+
forms.set(s.id, list(f));
|
|
259
|
+
const updated = s.time?.updated || 0;
|
|
260
|
+
if (turns.get(s.id)?.updated !== updated) {
|
|
261
|
+
const messages = await request(service, `/api/session/${s.id}/message?limit=${MESSAGES_READ}`).catch(() => null);
|
|
262
|
+
if (messages) turns.set(s.id, { updated, ...lastTurn(list(messages)) });
|
|
263
|
+
}
|
|
264
|
+
}),
|
|
265
|
+
);
|
|
266
|
+
for (const id of turns.keys()) if (!shown.some((s) => s.id === id)) turns.delete(id);
|
|
267
|
+
state = { sessions: shown, running, asks, forms, byWindow, turns };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function poll() {
|
|
271
|
+
if (refreshing || Date.now() - refreshedAt < REFRESH_MS) return;
|
|
272
|
+
refreshing = refresh()
|
|
273
|
+
.catch(() => {
|
|
274
|
+
// Not running is the usual case, and shows nothing.
|
|
275
|
+
state = null;
|
|
276
|
+
})
|
|
277
|
+
.finally(() => {
|
|
278
|
+
refreshing = null;
|
|
279
|
+
refreshedAt = Date.now();
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function seenSince(key, now) {
|
|
284
|
+
if (!firstSeen.has(key)) firstSeen.set(key, now);
|
|
285
|
+
return firstSeen.get(key);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// The cards for a state, as the page shows sessions.
|
|
289
|
+
function agentsFrom(s, { now = Date.now() } = {}) {
|
|
290
|
+
if (!s) return [];
|
|
291
|
+
const keys = new Set();
|
|
292
|
+
const agents = s.sessions.map((session) => {
|
|
293
|
+
const win = s.byWindow.get(session.id) || null;
|
|
294
|
+
const st = statusOf(session, { running: s.running[session.id], asks: s.asks.get(session.id), forms: s.forms.get(session.id) });
|
|
295
|
+
if (st.since) keys.add(st.since);
|
|
296
|
+
const turn = s.turns?.get(session.id) || {};
|
|
297
|
+
const dir = session.location?.directory || null;
|
|
298
|
+
return {
|
|
299
|
+
app: 'opencode',
|
|
300
|
+
id: session.id,
|
|
301
|
+
pid: win?.pid ?? null,
|
|
302
|
+
title: session.title || null,
|
|
303
|
+
name: session.title || (dir ? path.basename(dir) : '') || 'OpenCode',
|
|
304
|
+
cwd: dir,
|
|
305
|
+
kind: 'interactive',
|
|
306
|
+
entrypoint: 'cli',
|
|
307
|
+
status: st.status,
|
|
308
|
+
waitingFor: st.waitingFor,
|
|
309
|
+
detail: st.detail || null,
|
|
310
|
+
statusSince: st.since ? seenSince(st.since, now) : st.at || session.time?.updated || null,
|
|
311
|
+
startedAt: session.time?.created || null,
|
|
312
|
+
model: session.model?.id || null,
|
|
313
|
+
modelName: session.model?.id || null,
|
|
314
|
+
outputTokens: session.tokens?.output || 0,
|
|
315
|
+
lastPrompt: turn.lastPrompt || null,
|
|
316
|
+
lastReply: turn.lastReply || null,
|
|
317
|
+
prompts: turn.prompts || 0,
|
|
318
|
+
ticketRefs: turn.ticketRefs || [],
|
|
319
|
+
memBytes: win?.memBytes ?? null,
|
|
320
|
+
terminalTitle: null,
|
|
321
|
+
subagents: NO_SUBAGENTS,
|
|
322
|
+
};
|
|
323
|
+
});
|
|
324
|
+
for (const key of firstSeen.keys()) if (!keys.has(key)) firstSeen.delete(key);
|
|
325
|
+
return agents;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// OpenCode's cards from the last check, which checks again in the
|
|
329
|
+
// background, and the windows whose tab titles should be read.
|
|
330
|
+
function snapshot() {
|
|
331
|
+
refreshWindows();
|
|
332
|
+
poll();
|
|
333
|
+
return { agents: agentsFrom(state), windowPids: windows.map((w) => w.pid) };
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ---- driving sessions ------------------------------------------------------------
|
|
337
|
+
|
|
338
|
+
// Stops the turn a session is running.
|
|
339
|
+
async function interrupt(id) {
|
|
340
|
+
const service = readService();
|
|
341
|
+
if (!service) return { ok: false, error: "OpenCode's background service isn't running." };
|
|
342
|
+
try {
|
|
343
|
+
await request(service, `/api/session/${encodeURIComponent(id)}/interrupt`, { method: 'POST', body: {} });
|
|
344
|
+
refreshedAt = 0;
|
|
345
|
+
return { ok: true };
|
|
346
|
+
} catch (err) {
|
|
347
|
+
return { ok: false, error: `Couldn't stop OpenCode's turn: ${err.message}` };
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// Sends a prompt, which waits for the turn running, if any, to end.
|
|
352
|
+
async function queuePrompt(id, text) {
|
|
353
|
+
const service = readService();
|
|
354
|
+
if (!service) return { ok: false, error: "OpenCode's background service isn't running." };
|
|
355
|
+
try {
|
|
356
|
+
await request(service, `/api/session/${encodeURIComponent(id)}/prompt`, { method: 'POST', body: { text, delivery: 'queue' } });
|
|
357
|
+
refreshedAt = 0;
|
|
358
|
+
return { ok: true };
|
|
359
|
+
} catch (err) {
|
|
360
|
+
return { ok: false, error: `Couldn't send OpenCode the prompt: ${err.message}` };
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// The command a new tab runs: OpenCode, approving what isn't denied if
|
|
365
|
+
// Settings says to skip permission prompts, on a session if given one.
|
|
366
|
+
function command({ skipPermissions = false, resume = null } = {}) {
|
|
367
|
+
const auto = skipPermissions ? ' --auto' : '';
|
|
368
|
+
return resume && SESSION_ID.test(resume) ? `opencode${auto} --session ${resume}` : `opencode${auto}`;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
module.exports = { snapshot, interrupt, queuePrompt, command, agentsFrom, statusOf, lastTurn, matchWindows, isSessionWindow, sessionArg, titleIn, SESSION_ID };
|
package/lib/repos.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const settings = require('./settings');
|
|
7
|
+
|
|
8
|
+
const SOURCE_DIR = process.env.REPOS_DIR || path.join(os.homedir(), 'source');
|
|
9
|
+
const MAX_DEPTH = 6;
|
|
10
|
+
const CACHE_MS = 60000;
|
|
11
|
+
const SKIP = new Set(['node_modules', 'vendor', 'dist', 'build', 'bin', 'obj', 'target', 'venv', '__pycache__']);
|
|
12
|
+
|
|
13
|
+
let scan = null;
|
|
14
|
+
let scannedAt = 0;
|
|
15
|
+
let cache = null;
|
|
16
|
+
|
|
17
|
+
const byName = (a, b) => a.name.localeCompare(b.name, 'en', { sensitivity: 'base' });
|
|
18
|
+
|
|
19
|
+
// A folder with a .git entry (a directory, or a file for worktrees) is a repo.
|
|
20
|
+
// Repos are leaves: nothing inside one is searched.
|
|
21
|
+
function walk(dir, rel, depth) {
|
|
22
|
+
let entries;
|
|
23
|
+
try {
|
|
24
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
if (rel && entries.some((e) => e.name === '.git')) return { name: path.basename(dir), path: rel, repo: true };
|
|
29
|
+
if (depth >= MAX_DEPTH) return null;
|
|
30
|
+
const folders = [];
|
|
31
|
+
const repos = [];
|
|
32
|
+
for (const e of entries) {
|
|
33
|
+
if (!e.isDirectory() || e.name.startsWith('.') || SKIP.has(e.name)) continue;
|
|
34
|
+
const child = walk(path.join(dir, e.name), rel ? `${rel}/${e.name}` : e.name, depth + 1);
|
|
35
|
+
if (child) (child.repo ? repos : folders).push(child);
|
|
36
|
+
}
|
|
37
|
+
if (!folders.length && !repos.length) return null;
|
|
38
|
+
return { name: path.basename(dir), path: rel, children: [...folders.sort(byName), ...repos.sort(byName)] };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// The menu's tree: the scan without the excluded folders and repos, or the
|
|
42
|
+
// folders that have nothing left in them.
|
|
43
|
+
function prune(nodes, excluded, paths) {
|
|
44
|
+
const out = [];
|
|
45
|
+
for (const n of nodes) {
|
|
46
|
+
if (excluded.has(n.path.toLowerCase())) continue;
|
|
47
|
+
if (n.repo) {
|
|
48
|
+
paths.add(n.path);
|
|
49
|
+
out.push(n);
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
const children = prune(n.children, excluded, paths);
|
|
53
|
+
if (children.length) out.push({ ...n, children });
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// `tree` is what the menu shows and `all` is everything found, for Settings.
|
|
59
|
+
// Changing the excluded folders doesn't need a rescan, only a new prune.
|
|
60
|
+
function scanRepos(force) {
|
|
61
|
+
if (force || !scan || Date.now() - scannedAt > CACHE_MS) {
|
|
62
|
+
scan = walk(SOURCE_DIR, '', 0)?.children || [];
|
|
63
|
+
scannedAt = Date.now();
|
|
64
|
+
cache = null;
|
|
65
|
+
}
|
|
66
|
+
const { excludedFolders } = settings.get();
|
|
67
|
+
if (!cache || cache.excludedFolders !== excludedFolders) {
|
|
68
|
+
const paths = new Set();
|
|
69
|
+
const tree = prune(scan, new Set(excludedFolders.map((p) => p.toLowerCase())), paths);
|
|
70
|
+
cache = { root: SOURCE_DIR, tree, all: scan, count: paths.size, paths, excludedFolders };
|
|
71
|
+
}
|
|
72
|
+
return cache;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Only folders the scan found can be opened, never an arbitrary path.
|
|
76
|
+
function resolveRepo(rel) {
|
|
77
|
+
const { paths } = scanRepos(false);
|
|
78
|
+
return typeof rel === 'string' && paths.has(rel) ? path.join(SOURCE_DIR, ...rel.split('/')) : null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
module.exports = { scanRepos, resolveRepo, SOURCE_DIR };
|
package/lib/saved.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const store = require('./store');
|
|
4
|
+
const { isSessionId } = require('./session-id');
|
|
5
|
+
|
|
6
|
+
// The set of sessions Save and close saved last, for Resume last session to
|
|
7
|
+
// open again. Saved as saved-sessions.json. Each is what's needed to resume
|
|
8
|
+
// it: its app, ID and folder, and a name to show.
|
|
9
|
+
|
|
10
|
+
function clean(s) {
|
|
11
|
+
if (!s || !isSessionId(s.id) || typeof s.cwd !== 'string' || !['claude', 'codex', 'copilot', 'opencode', 'cursor'].includes(s.app)) return null;
|
|
12
|
+
return { app: s.app, id: s.id, cwd: s.cwd, name: typeof s.name === 'string' ? s.name.slice(0, 300) : null };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function load() {
|
|
16
|
+
const saved = store.read('saved-sessions', null);
|
|
17
|
+
if (!saved || !Number.isFinite(saved.savedAt) || !Array.isArray(saved.sessions)) return null;
|
|
18
|
+
return { savedAt: saved.savedAt, sessions: saved.sessions.map(clean).filter(Boolean) };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let saved = load();
|
|
22
|
+
|
|
23
|
+
// Replaces the saved set with these sessions.
|
|
24
|
+
function save(sessions, now = Date.now()) {
|
|
25
|
+
const next = { savedAt: now, sessions: sessions.map(clean).filter(Boolean) };
|
|
26
|
+
store.write('saved-sessions', next);
|
|
27
|
+
saved = next;
|
|
28
|
+
return saved;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const get = () => saved;
|
|
32
|
+
|
|
33
|
+
module.exports = { save, get };
|
package/lib/secrets.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { execFileSync } = require('child_process');
|
|
7
|
+
const store = require('./store');
|
|
8
|
+
|
|
9
|
+
// Secrets in Tabherd's JSON files are encrypted with AES-256-GCM, as
|
|
10
|
+
// "enc:v1:" and the base64 of the IV, tag and ciphertext. The key is 32
|
|
11
|
+
// random bytes that the operating system keeps for the signed-in user, made
|
|
12
|
+
// the first time a secret is saved:
|
|
13
|
+
// - Windows: protected with DPAPI for the current user, in secret.key.
|
|
14
|
+
// - macOS: an item in the login Keychain.
|
|
15
|
+
// - Linux: the Secret Service (GNOME Keyring, KWallet), through secret-tool;
|
|
16
|
+
// without one, secret.key, readable only by its owner.
|
|
17
|
+
// A file copied to another computer or user can't be read there, and what
|
|
18
|
+
// can't be read counts as unset.
|
|
19
|
+
|
|
20
|
+
const PREFIX = 'enc:v1:';
|
|
21
|
+
const KEY_FILE = path.join(store.DATA_DIR, 'secret.key');
|
|
22
|
+
const LABEL = 'Tabherd settings key';
|
|
23
|
+
// Each data folder has a key of its own, so a test's, or a second copy's,
|
|
24
|
+
// can't touch yours.
|
|
25
|
+
const ACCOUNT = store.DATA_DIR;
|
|
26
|
+
|
|
27
|
+
// A key that's there but can't be unlocked by this user on this computer,
|
|
28
|
+
// as against a key store that didn't answer.
|
|
29
|
+
class Elsewhere extends Error {}
|
|
30
|
+
|
|
31
|
+
const run = (cmd, args, input) =>
|
|
32
|
+
execFileSync(cmd, args, { input, encoding: 'utf8', windowsHide: true, timeout: 20000, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
33
|
+
|
|
34
|
+
// DPAPI through Windows PowerShell, which every Windows has. The key goes in
|
|
35
|
+
// and out on standard input and output, never on a command line.
|
|
36
|
+
function dpapi(op, base64) {
|
|
37
|
+
const script = `$ErrorActionPreference = 'Stop'
|
|
38
|
+
$ProgressPreference = 'SilentlyContinue'
|
|
39
|
+
Add-Type -AssemblyName System.Security
|
|
40
|
+
$in = [Convert]::FromBase64String([Console]::In.ReadToEnd().Trim())
|
|
41
|
+
$entropy = [Text.Encoding]::UTF8.GetBytes('${LABEL}')
|
|
42
|
+
$out = [Security.Cryptography.ProtectedData]::${op}($in, $entropy, [Security.Cryptography.DataProtectionScope]::CurrentUser)
|
|
43
|
+
[Console]::Out.Write([Convert]::ToBase64String($out))`;
|
|
44
|
+
try {
|
|
45
|
+
return run('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], base64).trim();
|
|
46
|
+
} catch (err) {
|
|
47
|
+
if (/CryptographicException/.test(String(err.stderr))) throw new Elsewhere('The saved secrets were encrypted by another Windows user or computer.');
|
|
48
|
+
throw new Error("Windows' data protection didn't answer.");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const fromHex = (text) => {
|
|
53
|
+
const key = Buffer.from(String(text).trim(), 'hex');
|
|
54
|
+
if (key.length !== 32) throw new Elsewhere('The saved key is damaged.');
|
|
55
|
+
return key;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
function readKeyFile() {
|
|
59
|
+
return fs.existsSync(KEY_FILE) ? fs.readFileSync(KEY_FILE, 'utf8') : null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function writeKeyFile(text) {
|
|
63
|
+
fs.mkdirSync(store.DATA_DIR, { recursive: true });
|
|
64
|
+
const temp = `${KEY_FILE}.${process.pid}.tmp`;
|
|
65
|
+
fs.writeFileSync(temp, text, { mode: 0o600 });
|
|
66
|
+
fs.renameSync(temp, KEY_FILE);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const PROVIDERS = {
|
|
70
|
+
win32: {
|
|
71
|
+
protection: 'dpapi',
|
|
72
|
+
read() {
|
|
73
|
+
const blob = readKeyFile();
|
|
74
|
+
return blob ? Buffer.from(dpapi('Unprotect', blob), 'base64') : null;
|
|
75
|
+
},
|
|
76
|
+
create(key) {
|
|
77
|
+
writeKeyFile(dpapi('Protect', key.toString('base64')));
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
darwin: {
|
|
81
|
+
protection: 'keychain',
|
|
82
|
+
read() {
|
|
83
|
+
try {
|
|
84
|
+
return fromHex(run('security', ['find-generic-password', '-a', ACCOUNT, '-s', LABEL, '-w']));
|
|
85
|
+
} catch (err) {
|
|
86
|
+
// 44: no such item yet.
|
|
87
|
+
if (err.status === 44) return null;
|
|
88
|
+
if (err instanceof Elsewhere) throw err;
|
|
89
|
+
throw new Error("The Keychain didn't give the key.");
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
create(key) {
|
|
93
|
+
if (/["\\\n]/.test(ACCOUNT)) throw new Error("The data folder's path can't be used as a Keychain account.");
|
|
94
|
+
// Interactive mode takes the command on standard input, so the key never
|
|
95
|
+
// shows in a process list.
|
|
96
|
+
run('security', ['-i'], `add-generic-password -U -a "${ACCOUNT}" -s "${LABEL}" -w ${key.toString('hex')}\n`);
|
|
97
|
+
if (!this.read()?.equals(key)) throw new Error("The Keychain didn't keep the key.");
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
linux: {
|
|
101
|
+
protection: 'secret-service',
|
|
102
|
+
read() {
|
|
103
|
+
// A key file means the Secret Service wasn't there when the key was made.
|
|
104
|
+
const file = readKeyFile();
|
|
105
|
+
if (file) {
|
|
106
|
+
this.protection = 'file';
|
|
107
|
+
return fromHex(file);
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
const found = run('secret-tool', ['lookup', 'service', 'tabherd', 'account', ACCOUNT]).trim();
|
|
111
|
+
return found ? fromHex(found) : null;
|
|
112
|
+
} catch (err) {
|
|
113
|
+
if (err instanceof Elsewhere) throw err;
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
create(key) {
|
|
118
|
+
try {
|
|
119
|
+
run('secret-tool', ['store', `--label=${LABEL}`, 'service', 'tabherd', 'account', ACCOUNT], key.toString('hex'));
|
|
120
|
+
if (fromHex(run('secret-tool', ['lookup', 'service', 'tabherd', 'account', ACCOUNT])).equals(key)) return;
|
|
121
|
+
} catch {}
|
|
122
|
+
writeKeyFile(key.toString('hex'));
|
|
123
|
+
this.protection = 'file';
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
let provider = PROVIDERS[process.platform] || PROVIDERS.linux;
|
|
129
|
+
let key = null;
|
|
130
|
+
// null until the key store has been asked; then 'ready', 'none' (no key made
|
|
131
|
+
// yet), 'elsewhere' (one that can't be unlocked here) or 'failed'.
|
|
132
|
+
let state = null;
|
|
133
|
+
let problem = null;
|
|
134
|
+
|
|
135
|
+
function load() {
|
|
136
|
+
if (state) return;
|
|
137
|
+
try {
|
|
138
|
+
key = provider.read();
|
|
139
|
+
state = key ? 'ready' : 'none';
|
|
140
|
+
} catch (err) {
|
|
141
|
+
state = err instanceof Elsewhere ? 'elsewhere' : 'failed';
|
|
142
|
+
problem = err.message;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const isEncrypted = (value) => typeof value === 'string' && value.startsWith(PREFIX);
|
|
147
|
+
|
|
148
|
+
// Any JSON value, encrypted. The first secret saved makes the key; one that
|
|
149
|
+
// can't be unlocked here is replaced, as what it locked is lost anyway. A key
|
|
150
|
+
// store that didn't answer throws, so nothing is saved unencrypted.
|
|
151
|
+
function encrypt(value) {
|
|
152
|
+
load();
|
|
153
|
+
if (state === 'failed') throw new Error(problem);
|
|
154
|
+
if (!key) {
|
|
155
|
+
const next = crypto.randomBytes(32);
|
|
156
|
+
provider.create(next);
|
|
157
|
+
key = next;
|
|
158
|
+
state = 'ready';
|
|
159
|
+
problem = null;
|
|
160
|
+
}
|
|
161
|
+
const iv = crypto.randomBytes(12);
|
|
162
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
|
163
|
+
const data = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()]);
|
|
164
|
+
return PREFIX + Buffer.concat([iv, cipher.getAuthTag(), data]).toString('base64');
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// The value, or undefined if it can't be decrypted here.
|
|
168
|
+
function decrypt(text) {
|
|
169
|
+
if (!isEncrypted(text)) return undefined;
|
|
170
|
+
load();
|
|
171
|
+
if (!key) return undefined;
|
|
172
|
+
try {
|
|
173
|
+
const raw = Buffer.from(text.slice(PREFIX.length), 'base64');
|
|
174
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', key, raw.subarray(0, 12));
|
|
175
|
+
decipher.setAuthTag(raw.subarray(12, 28));
|
|
176
|
+
return JSON.parse(Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString('utf8'));
|
|
177
|
+
} catch {
|
|
178
|
+
return undefined;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// How secrets are kept here, for Settings.
|
|
183
|
+
function status() {
|
|
184
|
+
load();
|
|
185
|
+
return { protection: provider.protection, state, problem };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// For tests: this key, kept in memory only.
|
|
189
|
+
function useKey(k) {
|
|
190
|
+
provider = { protection: 'test', read: () => k, create() {} };
|
|
191
|
+
key = k;
|
|
192
|
+
state = k ? 'ready' : null;
|
|
193
|
+
problem = null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
module.exports = { encrypt, decrypt, isEncrypted, status, useKey };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// A session's ID as the apps make them: a UUID (Claude, Codex, Copilot), or
|
|
4
|
+
// OpenCode's ses_… Either is safe in a command line as it is.
|
|
5
|
+
const SESSION_ID = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|ses_[A-Za-z0-9]{10,60})$/i;
|
|
6
|
+
|
|
7
|
+
const isSessionId = (id) => typeof id === 'string' && SESSION_ID.test(id);
|
|
8
|
+
|
|
9
|
+
module.exports = { isSessionId };
|