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.
Files changed (68) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/LICENSE +674 -0
  3. package/README.md +538 -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 +35 -7
  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
  68. package/placeholder.js +0 -3
@@ -0,0 +1,251 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const { Transcript, clip } = require('./transcript');
5
+
6
+ // A Codex session file ("rollout"): one JSON object per line, each
7
+ // { timestamp, type, payload }. Read the same way as a Claude transcript, a
8
+ // few new bytes at a time, into the same summary, so the card is the same.
9
+ //
10
+ // What's taken from where:
11
+ // session_meta where and how the session began, its git branch
12
+ // turn_context the model and approval policy, for each turn
13
+ // event_msg turns starting and finishing, prompts, replies,
14
+ // token counts (item_completed in current files;
15
+ // user_message and agent_message in older ones)
16
+ // response_item tool calls, paired with their output by call_id
17
+ // compacted a compaction
18
+ //
19
+ // The file never records that a session is waiting for an approval; the
20
+ // Codex service reports that.
21
+
22
+ // Lines that are large and carry nothing shown.
23
+ const SKIP = /^\{"timestamp":"[^"]*","type":"(world_state|token_usage_record|retained_context|dynamic_tools_updated|security_risk_score|realtime_item)"/;
24
+
25
+ class Rollout extends Transcript {
26
+ reset() {
27
+ super.reset();
28
+ Object.assign(this.s, {
29
+ originator: null,
30
+ source: null,
31
+ parentThreadId: null,
32
+ version: null,
33
+ approvalPolicy: null,
34
+ contextLimit: 0,
35
+ // The turn running now, which Stop interrupts.
36
+ turnId: null,
37
+ });
38
+ }
39
+
40
+ line(line) {
41
+ if (!line || SKIP.test(line)) return;
42
+ let e;
43
+ try {
44
+ e = JSON.parse(line);
45
+ } catch {
46
+ return;
47
+ }
48
+ const s = this.s;
49
+ const p = e.payload || {};
50
+ if (e.timestamp) {
51
+ s.lastEventAt = e.timestamp;
52
+ s.startedAt = s.startedAt || e.timestamp;
53
+ }
54
+ switch (e.type) {
55
+ case 'session_meta': {
56
+ s.cwd = s.cwd || p.cwd || null;
57
+ s.originator = p.originator || null;
58
+ s.source = p.source ?? null;
59
+ // A subagent whose parent isn't named is still a subagent.
60
+ const sub = subagentOf(p.source);
61
+ s.parentThreadId = p.parent_thread_id || sub?.parentThreadId || (sub ? 'subagent' : null);
62
+ s.version = p.cli_version || null;
63
+ s.startedAt = p.timestamp || s.startedAt;
64
+ if (p.git?.branch && p.git.branch !== 'HEAD') s.gitBranch = p.git.branch;
65
+ break;
66
+ }
67
+ case 'turn_context':
68
+ s.model = p.model || s.model;
69
+ s.approvalPolicy = p.approval_policy || s.approvalPolicy;
70
+ break;
71
+ case 'compacted':
72
+ s.compactions++;
73
+ break;
74
+ case 'response_item':
75
+ this.responseItem(p, e.timestamp);
76
+ break;
77
+ case 'event_msg':
78
+ this.event(p, e.timestamp);
79
+ break;
80
+ }
81
+ }
82
+
83
+ event(p, at) {
84
+ const s = this.s;
85
+ switch (p.type) {
86
+ case 'task_started':
87
+ s.turnId = p.turn_id || 'unknown';
88
+ s.tools.clear();
89
+ if (p.model_context_window) s.contextLimit = p.model_context_window;
90
+ break;
91
+ case 'task_complete':
92
+ s.turnId = null;
93
+ s.tools.clear();
94
+ s.lastTurnMs = p.duration_ms ?? null;
95
+ if (p.last_agent_message?.trim()) s.lastReply = { text: clip(p.last_agent_message), at };
96
+ break;
97
+ case 'turn_aborted':
98
+ s.turnId = null;
99
+ s.tools.clear();
100
+ break;
101
+ case 'token_count': {
102
+ const info = p.info;
103
+ if (!info) break;
104
+ if (info.last_token_usage?.total_tokens) s.contextTokens = info.last_token_usage.total_tokens;
105
+ if (info.total_token_usage) s.outputTokens = info.total_token_usage.output_tokens || 0;
106
+ if (info.model_context_window) s.contextLimit = info.model_context_window;
107
+ break;
108
+ }
109
+ case 'item_completed':
110
+ if (p.item?.type === 'UserMessage') this.prompt(texts(p.item.content), at);
111
+ else if (p.item?.type === 'AgentMessage') this.reply(texts(p.item.content), at);
112
+ break;
113
+ case 'user_message':
114
+ this.prompt(p.message, at);
115
+ break;
116
+ case 'agent_message':
117
+ this.reply(p.message, at);
118
+ break;
119
+ }
120
+ }
121
+
122
+ responseItem(p, at) {
123
+ const s = this.s;
124
+ switch (p.type) {
125
+ case 'custom_tool_call':
126
+ case 'function_call':
127
+ case 'local_shell_call':
128
+ if (p.call_id) s.tools.set(p.call_id, { ...describeCall(p), at });
129
+ break;
130
+ case 'custom_tool_call_output':
131
+ case 'function_call_output':
132
+ case 'local_shell_call_output':
133
+ s.tools.delete(p.call_id);
134
+ break;
135
+ }
136
+ }
137
+
138
+ prompt(text, at) {
139
+ const t = typeof text === 'string' ? text.trim() : '';
140
+ if (!t) return;
141
+ const s = this.s;
142
+ this.noteTickets(t, 'prompt');
143
+ s.tools.clear();
144
+ s.lastPrompt = { text: clip(t), at };
145
+ s.firstPrompt = s.firstPrompt || s.lastPrompt;
146
+ s.prompts++;
147
+ }
148
+
149
+ reply(text, at) {
150
+ if (typeof text !== 'string' || !text.trim()) return;
151
+ this.s.lastReply = { text: clip(text), at };
152
+ this.noteTickets(text, 'reply');
153
+ }
154
+
155
+ origin() {
156
+ const { cwd, originator, source, parentThreadId, startedAt } = this.s;
157
+ return { cwd, entrypoint: originator, originator, source, parentThreadId, startedAt };
158
+ }
159
+
160
+ summary() {
161
+ const s = this.s;
162
+ return {
163
+ title: null,
164
+ model: s.model,
165
+ modelName: null,
166
+ permissionMode: s.approvalPolicy === 'never' ? 'never-ask' : null,
167
+ gitBranch: s.gitBranch,
168
+ firstPrompt: s.firstPrompt,
169
+ lastPrompt: s.lastPrompt,
170
+ lastReply: s.lastReply,
171
+ recap: null,
172
+ tools: [...s.tools.values()],
173
+ lastEventAt: s.lastEventAt,
174
+ lastTurnMs: s.lastTurnMs,
175
+ contextTokens: s.contextTokens,
176
+ contextLimit: s.contextLimit || 0,
177
+ outputTokens: s.outputTokens,
178
+ prompts: s.prompts,
179
+ compactions: s.compactions,
180
+ prs: [],
181
+ ticketRefs: s.ticketRefs,
182
+ turnOpen: Boolean(s.turnId),
183
+ version: s.version,
184
+ };
185
+ }
186
+ }
187
+
188
+ // A subagent's session says so in its source, in a shape that has changed
189
+ // between Codex versions: { subagent: { thread_spawn: { parent_thread_id,
190
+ // agent_nickname, agent_role } } }, in either case style. Null if it isn't one.
191
+ function subagentOf(source) {
192
+ if (!source || typeof source !== 'object') return null;
193
+ const found = {};
194
+ const walk = (o, depth) => {
195
+ if (!o || typeof o !== 'object' || depth > 4) return;
196
+ for (const [k, v] of Object.entries(o)) {
197
+ const key = k.replace(/_/g, '').toLowerCase();
198
+ if (typeof v === 'string' && key === 'parentthreadid') found.parentThreadId = v;
199
+ else if (typeof v === 'string' && key === 'agentnickname') found.nickname = v;
200
+ else if (typeof v === 'string' && key === 'agentrole') found.role = v;
201
+ else walk(v, depth + 1);
202
+ }
203
+ };
204
+ walk(source, 0);
205
+ const isSub = Object.keys(source).some((k) => k.replace(/_/g, '').toLowerCase() === 'subagent');
206
+ return isSub || found.parentThreadId ? { parentThreadId: found.parentThreadId || null, nickname: found.nickname || null, role: found.role || null } : null;
207
+ }
208
+
209
+ const texts = (content) =>
210
+ Array.isArray(content)
211
+ ? content
212
+ .map((c) => (typeof c?.text === 'string' ? c.text : ''))
213
+ .filter(Boolean)
214
+ .join('\n')
215
+ : typeof content === 'string'
216
+ ? content
217
+ : '';
218
+
219
+ // What a tool call is doing, for the card's "now" rows. Codex runs most
220
+ // commands through a script tool whose input calls tools.exec_command, and
221
+ // edits files with apply_patch.
222
+ function describeCall(p) {
223
+ const input = typeof p.input === 'string' ? p.input : typeof p.arguments === 'string' ? p.arguments : '';
224
+ const cmd = input.match(/exec_command\(\s*\{\s*cmd\s*:\s*"((?:[^"\\]|\\.)*)"/);
225
+ if (cmd) return { name: 'Shell', detail: short(unescape(cmd[1])) };
226
+ const files = [...input.matchAll(/\*\*\* (?:Add|Update|Delete) File: (.+)/g)].map((m) => path.basename(m[1].trim()));
227
+ if (files.length) return { name: 'Edit', detail: short(files.join(', ')) };
228
+ if (p.type === 'local_shell_call') return { name: 'Shell', detail: short([].concat(p.action?.command || []).join(' ')) };
229
+ let args = null;
230
+ try {
231
+ args = JSON.parse(input);
232
+ } catch {}
233
+ if (p.name === 'wait') return { name: 'Waiting on a command', detail: '' };
234
+ const detail = args && typeof args === 'object' ? Object.values(args).find((v) => typeof v === 'string' && v.length < 200) : input.split('\n')[0];
235
+ return { name: p.name || 'Tool', detail: short(detail || '') };
236
+ }
237
+
238
+ function unescape(s) {
239
+ try {
240
+ return JSON.parse(`"${s}"`);
241
+ } catch {
242
+ return s;
243
+ }
244
+ }
245
+
246
+ function short(text) {
247
+ const t = String(text).replace(/\s+/g, ' ').trim();
248
+ return t.length > 160 ? `${t.slice(0, 159)}…` : t;
249
+ }
250
+
251
+ module.exports = { Rollout, describeCall, subagentOf };
package/lib/codex.js ADDED
@@ -0,0 +1,424 @@
1
+ 'use strict';
2
+
3
+ // Codex sessions, as cards like Claude's. Which sessions are open, and
4
+ // whether each is working, idle or waiting for you, come from Codex's
5
+ // background service (codex-client.js); what they last did comes from their
6
+ // session files (codex-rollout.js). Codex records no process for a session,
7
+ // so its terminal window is found by its tab's title, which Codex sets to the
8
+ // session's name.
9
+
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const { execFile } = require('child_process');
13
+ const { CodexClient, mapStatus, serviceRunning, codexCommand, CODEX_HOME } = require('./codex-client');
14
+ const { Rollout, subagentOf } = require('./codex-rollout');
15
+ const terminals = require('./terminals');
16
+
17
+ const SESSIONS_DIR = path.join(CODEX_HOME, 'sessions');
18
+ const NAMES_FILE = path.join(CODEX_HOME, 'session_index.jsonl');
19
+ const IS_WIN = process.platform === 'win32';
20
+ const WINDOWS_REFRESH_MS = 10000;
21
+ const START_WAIT_MS = 60 * 1000;
22
+ const FINISHED_SUBAGENTS = 5;
23
+ const ROLLOUT_FILE = /^rollout-.+-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i;
24
+ // `codex <command>`s that aren't a session in a terminal.
25
+ const NOT_A_SESSION = new Set(
26
+ 'exec e login logout mcp mcp-server app-server completion sandbox debug apply a cloud features queue archive unarchive delete help update agents doctor migrate-rollouts exec-server responses-api-proxy stdio-to-uds generate-ts'.split(' '),
27
+ );
28
+
29
+ const client = new CodexClient();
30
+ const rollouts = new Map();
31
+ const rolloutPaths = new Map();
32
+ let windows = [];
33
+ let windowsAt = 0;
34
+ let windowsPending = null;
35
+
36
+ function run(cmd, args) {
37
+ return new Promise((resolve) => {
38
+ execFile(cmd, args, { windowsHide: true, timeout: 15000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) =>
39
+ resolve(err && !stdout ? null : String(stdout)),
40
+ );
41
+ });
42
+ }
43
+
44
+ // Whether a process is Codex in a terminal: the `codex` program (named for
45
+ // its platform when installed by winget), running no other command.
46
+ function isSessionWindow(name, args) {
47
+ if (!/^codex(-(x86_64|aarch64|arm64)[\w.-]*)?(\.exe)?$/i.test(name)) return false;
48
+ const first = args.find((a) => !a.startsWith('-'));
49
+ return !first || !NOT_A_SESSION.has(first);
50
+ }
51
+
52
+ // The `codex` processes running in terminals: [{ pid, memBytes }].
53
+ async function findWindows() {
54
+ const found = [];
55
+ if (IS_WIN) {
56
+ const script =
57
+ `Get-CimInstance Win32_Process -Filter "Name like 'codex%'" | ForEach-Object { ` +
58
+ `'{0}|{1}|{2}|{3}' -f $_.ProcessId, $_.Name, $_.WorkingSetSize, $_.CommandLine }`;
59
+ const out = await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script]);
60
+ if (out === null) return null;
61
+ for (const line of out.split(/\r?\n/)) {
62
+ const [pid, name, ws, ...cmd] = line.trim().split('|');
63
+ if (!pid) continue;
64
+ const args = cmd.join('|').replace(/^\s*("[^"]*"|\S+)\s*/, '').split(/\s+/).filter(Boolean);
65
+ if (isSessionWindow(name, args)) found.push({ pid: Number(pid), memBytes: Number(ws) || null });
66
+ }
67
+ } else {
68
+ const out = await run('ps', ['-A', '-o', 'pid=,rss=,args=']);
69
+ if (out === null) return null;
70
+ for (const line of out.split('\n')) {
71
+ const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)\s*(.*)$/);
72
+ if (m && isSessionWindow(path.basename(m[3]), m[4].split(/\s+/).filter(Boolean))) {
73
+ found.push({ pid: Number(m[1]), memBytes: Number(m[2]) * 1024 });
74
+ }
75
+ }
76
+ }
77
+ return found;
78
+ }
79
+
80
+ function refreshWindows() {
81
+ if (windowsPending || Date.now() - windowsAt < WINDOWS_REFRESH_MS) return;
82
+ windowsPending = findWindows().then((found) => {
83
+ if (found) {
84
+ windows = found;
85
+ windowsAt = Date.now();
86
+ }
87
+ windowsPending = null;
88
+ });
89
+ }
90
+
91
+ // The parts of a Codex tab's title: its session's name and project, after
92
+ // a spinner or "Action Required" while it works or waits.
93
+ const titleParts = (title) =>
94
+ String(title || '')
95
+ .split(' | ')
96
+ .map((p) => p.replace(/^[⠀-⣿]\s*/, '').trim())
97
+ .filter(Boolean);
98
+
99
+ // Each session's window, by its name in a tab's title. A session that isn't
100
+ // named yet goes with the only window left, if there's one.
101
+ function matchWindows(threads, wins, titleFor = terminals.titleFor) {
102
+ const byThread = new Map();
103
+ const free = new Map(wins.map((w) => [w.pid, w]));
104
+ for (const t of threads) {
105
+ if (!t.name) continue;
106
+ const matches = [...free.values()].filter((w) => titleParts(titleFor(w.pid)).includes(t.name));
107
+ if (matches.length !== 1) continue;
108
+ byThread.set(t.id, matches[0]);
109
+ free.delete(matches[0].pid);
110
+ }
111
+ const left = threads.filter((t) => !byThread.has(t.id));
112
+ if (left.length === 1 && free.size === 1) byThread.set(left[0].id, [...free.values()][0]);
113
+ return byThread;
114
+ }
115
+
116
+ // A session's file, from the service or else its folder for the day it began.
117
+ // Codex creates it at the first prompt, so a new session has none yet.
118
+ function findRollout(t) {
119
+ if (t.path && fs.existsSync(t.path)) return t.path;
120
+ const cached = rolloutPaths.get(t.id);
121
+ if (cached && fs.existsSync(cached)) return cached;
122
+ const began = t.createdAt ? new Date(t.createdAt * 1000) : new Date();
123
+ for (const offset of [0, 1, -1]) {
124
+ const d = new Date(began.getTime() + offset * 86400000);
125
+ const dir = path.join(SESSIONS_DIR, String(d.getFullYear()), String(d.getMonth() + 1).padStart(2, '0'), String(d.getDate()).padStart(2, '0'));
126
+ let names;
127
+ try {
128
+ names = fs.readdirSync(dir);
129
+ } catch {
130
+ continue;
131
+ }
132
+ const name = names.find((n) => n.endsWith(`-${t.id}.jsonl`));
133
+ if (name) {
134
+ rolloutPaths.set(t.id, path.join(dir, name));
135
+ return path.join(dir, name);
136
+ }
137
+ }
138
+ return null;
139
+ }
140
+
141
+ function readRollout(file, used) {
142
+ let r = rollouts.get(file);
143
+ if (!r) {
144
+ r = new Rollout(file);
145
+ rollouts.set(file, r);
146
+ }
147
+ used.add(file);
148
+ return r.update() ? r : null;
149
+ }
150
+
151
+ // The session a subagent belongs to, if it is one.
152
+ const parentOf = (t) => t.parentThreadId || subagentOf(t.source)?.parentThreadId || null;
153
+
154
+ // A session in a terminal, not a subagent's or one run by `codex exec`.
155
+ function isInteractive(t) {
156
+ if (t.ephemeral || parentOf(t) || subagentOf(t.source)) return false;
157
+ return !['exec', 'mcp'].includes(typeof t.source === 'string' ? t.source : null);
158
+ }
159
+
160
+ function isRunning(pid) {
161
+ try {
162
+ process.kill(pid, 0);
163
+ return true;
164
+ } catch (err) {
165
+ return err.code === 'EPERM';
166
+ }
167
+ }
168
+
169
+ const CASELESS = IS_WIN || process.platform === 'darwin';
170
+ const sameDir = (a, b) => {
171
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
172
+ const [x, y] = [path.resolve(a), path.resolve(b)];
173
+ return CASELESS ? x.toLowerCase() === y.toLowerCase() : x === y;
174
+ };
175
+
176
+ // Tabherd opened a tab running Codex in `cwd`: the first session to start
177
+ // there within a minute is that one, and `found` is called with its ID.
178
+ // Codex can't be given a session ID to use, as Claude can.
179
+ let expected = [];
180
+ const claimed = new Set();
181
+
182
+ function expect(cwd, found) {
183
+ expected.push({ cwd, at: Date.now(), found });
184
+ }
185
+
186
+ function matchExpected(threads) {
187
+ const now = Date.now();
188
+ expected = expected.filter((e) => now - e.at < START_WAIT_MS);
189
+ for (const e of [...expected]) {
190
+ // Codex gives a session's start in whole seconds.
191
+ const t = threads
192
+ .filter((x) => !claimed.has(x.id) && (x.createdAt || 0) * 1000 >= e.at - 2000 && sameDir(x.cwd, e.cwd))
193
+ .sort((a, b) => a.createdAt - b.createdAt)[0];
194
+ if (!t) continue;
195
+ claimed.add(t.id);
196
+ expected = expected.filter((x) => x !== e);
197
+ e.found(t.id);
198
+ }
199
+ }
200
+
201
+ // Each session's window when last seen. Once that window has closed, the
202
+ // card goes, rather than staying the minute Codex keeps the session loaded.
203
+ const lastWindow = new Map();
204
+
205
+ // Subagents seen this run, by their parent session's ID, so finished ones
206
+ // stay listed after Codex unloads them.
207
+ const subagentsSeen = new Map();
208
+
209
+ // A session's subagents, as on a Claude card: running ones with what they're
210
+ // doing, then the latest finished.
211
+ function subagentsFor(parentId, threads, used = new Set()) {
212
+ const seen = subagentsSeen.get(parentId) || new Map();
213
+ const running = [];
214
+ for (const t of threads) {
215
+ if (parentOf(t) !== parentId) continue;
216
+ const sub = subagentOf(t.source) || {};
217
+ const entry = {
218
+ id: t.id,
219
+ type: sub.role || 'agent',
220
+ description: sub.nickname || t.name || t.preview || '',
221
+ background: false,
222
+ updatedAt: (t.updatedAt || t.createdAt || 0) * 1000,
223
+ };
224
+ seen.set(t.id, entry);
225
+ if (!['busy', 'waiting'].includes(mapStatus(t.status)?.status)) continue;
226
+ const file = findRollout(t);
227
+ const s = file ? readRollout(file, used)?.summary() : null;
228
+ running.push({ ...entry, status: 'running', startedAt: (t.createdAt || 0) * 1000, tools: s?.tools || [], lastReply: s?.lastReply || null, outputTokens: s?.outputTokens || 0 });
229
+ }
230
+ if (seen.size) subagentsSeen.set(parentId, seen);
231
+ const runningIds = new Set(running.map((r) => r.id));
232
+ const finished = [...seen.values()].filter((e) => !runningIds.has(e.id)).sort((a, b) => b.updatedAt - a.updatedAt);
233
+ return {
234
+ running,
235
+ finished: finished.slice(0, FINISHED_SUBAGENTS).map((e) => ({ ...e, status: 'done' })),
236
+ finishedTotal: finished.length,
237
+ };
238
+ }
239
+
240
+ // Codex sessions as dashboard agents, and the PIDs of their windows, whose
241
+ // tab titles the next snapshot needs.
242
+ function snapshot() {
243
+ const all = client.poll();
244
+ const threads = all.filter(isInteractive);
245
+ matchExpected(threads);
246
+ refreshWindows();
247
+ const byThread = matchWindows(threads, windows);
248
+ const used = new Set();
249
+ const agents = [];
250
+ for (const t of threads) {
251
+ const state = mapStatus(t.status);
252
+ if (!state) continue;
253
+ let win = byThread.get(t.id);
254
+ if (win && !isRunning(win.pid)) win = null;
255
+ const last = lastWindow.get(t.id);
256
+ if (win) lastWindow.set(t.id, win.pid);
257
+ else if (last && !isRunning(last)) continue;
258
+ const file = findRollout(t);
259
+ const r = file ? readRollout(file, used) : null;
260
+ agents.push({
261
+ ...(r ? r.summary() : {}),
262
+ app: 'codex',
263
+ id: t.id,
264
+ pid: win?.pid ?? null,
265
+ // Codex names a session from its first prompt, or as renamed.
266
+ title: t.name || null,
267
+ name: t.name || path.basename(t.cwd || '') || 'Codex',
268
+ cwd: t.cwd,
269
+ kind: 'interactive',
270
+ entrypoint: 'cli',
271
+ version: r?.s.version || null,
272
+ status: state.status,
273
+ waitingFor: state.waitingFor,
274
+ detail: state.detail || null,
275
+ statusSince: t.statusSince,
276
+ startedAt: t.createdAt ? t.createdAt * 1000 : null,
277
+ memBytes: win?.memBytes ?? null,
278
+ terminalTitle: null,
279
+ subagents: subagentsFor(t.id, all, used),
280
+ });
281
+ }
282
+ const open = new Set(all.map((t) => t.id));
283
+ for (const id of lastWindow.keys()) if (!open.has(id)) lastWindow.delete(id);
284
+ for (const id of subagentsSeen.keys()) if (!open.has(id)) subagentsSeen.delete(id);
285
+ for (const file of rollouts.keys()) if (!used.has(file)) rollouts.delete(file);
286
+ return { agents, windowPids: windows.map((w) => w.pid) };
287
+ }
288
+
289
+ // ---- driving sessions ------------------------------------------------------------
290
+
291
+ // The command a new tab runs: Codex, without its approvals and sandbox if
292
+ // Settings says to skip permission prompts, resuming a session if given one.
293
+ function command({ skipPermissions = false, resume = null } = {}) {
294
+ const bypass = skipPermissions ? ' --dangerously-bypass-approvals-and-sandbox' : '';
295
+ return resume ? `codex resume${bypass} ${resume}` : `codex${bypass}`;
296
+ }
297
+
298
+ // Names a session, as /rename does. Its tab's title follows.
299
+ async function rename(id, name) {
300
+ try {
301
+ await client.request('thread/name/set', { threadId: id, name });
302
+ return { ok: true };
303
+ } catch (err) {
304
+ return { ok: false, error: err.message };
305
+ }
306
+ }
307
+
308
+ // Sends a prompt to a session through Codex's service, with `codex queue`:
309
+ // an idle session starts on it at once, a busy one after its current turn.
310
+ // Nothing is typed into its window, so nothing there can be answered by it.
311
+ function queuePrompt(id, prompt) {
312
+ return new Promise((resolve) => {
313
+ execFile(codexCommand(), ['queue', '--thread', id, '--message', prompt], { windowsHide: true, timeout: 30000 }, (err, stdout, stderr) => {
314
+ const why = String(stderr || '').trim().split(/\r?\n/).pop();
315
+ resolve(err ? { ok: false, error: `Codex couldn't take the prompt: ${why || err.message}` } : { ok: true });
316
+ });
317
+ });
318
+ }
319
+
320
+ // Stops the turn a session is running, if it's running one. The turn comes
321
+ // from its session file, which records each turn's start.
322
+ async function interrupt(id) {
323
+ const t = client.threads.get(id);
324
+ const file = t ? findRollout(t) : null;
325
+ const turnId = file ? readRollout(file, new Set())?.s.turnId : null;
326
+ if (!turnId || turnId === 'unknown') return { ok: true, interrupted: false };
327
+ try {
328
+ await client.request('turn/interrupt', { threadId: id, turnId });
329
+ return { ok: true, interrupted: true };
330
+ } catch (err) {
331
+ return { ok: false, error: `Couldn't interrupt it: ${err.message}` };
332
+ }
333
+ }
334
+
335
+ // Whether Codex is on this computer: its folder, or `codex` on the PATH.
336
+ // Checked at most every half a minute.
337
+ let installedAt = 0;
338
+ let installedNow = false;
339
+ function installed() {
340
+ if (Date.now() - installedAt < 30000) return installedNow;
341
+ const names = IS_WIN ? ['codex.exe', 'codex.cmd'] : ['codex'];
342
+ installedNow =
343
+ fs.existsSync(CODEX_HOME) ||
344
+ (process.env.PATH || '').split(path.delimiter).some((dir) => dir && names.some((n) => fs.existsSync(path.join(dir, n))));
345
+ installedAt = Date.now();
346
+ return installedNow;
347
+ }
348
+
349
+ // ---- history -----------------------------------------------------------------
350
+
351
+ // Whether the open sessions are known: the service has answered, or isn't running.
352
+ const settled = () => client.ready || !serviceRunning();
353
+
354
+ // Session names, from the file Codex appends one to whenever a session is
355
+ // named or renamed. The last one for each session wins.
356
+ function sessionNames() {
357
+ const names = new Map();
358
+ let text;
359
+ try {
360
+ text = fs.readFileSync(NAMES_FILE, 'utf8');
361
+ } catch {
362
+ return names;
363
+ }
364
+ for (const line of text.split('\n')) {
365
+ try {
366
+ const e = JSON.parse(line);
367
+ if (e.id) names.set(e.id, e.thread_name || null);
368
+ } catch {}
369
+ }
370
+ return names;
371
+ }
372
+
373
+ // Session files changed since `floor` (ms): [{ id, file, mtime }], newest day
374
+ // first. Ones Codex has compressed (.jsonl.zst, after a week) are left out.
375
+ async function sessionFiles(floor) {
376
+ const files = [];
377
+ const list = async (dir) => {
378
+ try {
379
+ return (await fs.promises.readdir(dir)).sort().reverse();
380
+ } catch {
381
+ return [];
382
+ }
383
+ };
384
+ const floorDay = new Date(floor);
385
+ floorDay.setHours(0, 0, 0, 0);
386
+ for (const y of await list(SESSIONS_DIR)) {
387
+ if (Number(y) < floorDay.getFullYear()) continue;
388
+ for (const m of await list(path.join(SESSIONS_DIR, y))) {
389
+ for (const d of await list(path.join(SESSIONS_DIR, y, m))) {
390
+ if (new Date(Number(y), Number(m) - 1, Number(d)) < floorDay) continue;
391
+ const dir = path.join(SESSIONS_DIR, y, m, d);
392
+ for (const name of await list(dir)) {
393
+ const id = name.match(ROLLOUT_FILE)?.[1];
394
+ if (!id) continue;
395
+ const file = path.join(dir, name);
396
+ try {
397
+ const mtime = (await fs.promises.stat(file)).mtimeMs;
398
+ if (mtime >= floor) files.push({ id, file, mtime });
399
+ } catch {}
400
+ }
401
+ }
402
+ }
403
+ }
404
+ return files;
405
+ }
406
+
407
+ module.exports = {
408
+ snapshot,
409
+ settled,
410
+ sessionNames,
411
+ sessionFiles,
412
+ isSessionWindow,
413
+ matchWindows,
414
+ titleParts,
415
+ subagentsFor,
416
+ expect,
417
+ command,
418
+ rename,
419
+ queuePrompt,
420
+ interrupt,
421
+ installed,
422
+ client,
423
+ SESSIONS_DIR,
424
+ };